commit
stringlengths 40
40
| old_file
stringlengths 2
205
| new_file
stringlengths 2
205
| old_contents
stringlengths 0
32.9k
| new_contents
stringlengths 1
38.9k
| subject
stringlengths 3
9.4k
| message
stringlengths 6
9.84k
| lang
stringlengths 3
13
| license
stringclasses 13
values | repos
stringlengths 6
115k
|
---|---|---|---|---|---|---|---|---|---|
a727681c02dbac90022c0da8d1d1e9b241303d62
|
lotuswordpro/qa/cppunit/test_lotuswordpro.cxx
|
lotuswordpro/qa/cppunit/test_lotuswordpro.cxx
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Version: MPL 1.1 / GPLv3+ / LGPLv3+
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Initial Developer of the Original Code is
* Caolán McNamara <[email protected]> (Red Hat, Inc.)
* Portions created by the Initial Developer are Copyright (C) 2011 the
* Initial Developer. All Rights Reserved.
*
* Contributor(s): Caolán McNamara <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 3 or later (the "GPLv3+"), or
* the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
* in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
* instead of those above.
*/
#include <sal/cppunit.h>
#include <cppuhelper/bootstrap.hxx>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/document/XFilter.hpp>
#include <osl/file.hxx>
#include <osl/process.h>
#include <vcl/svapp.hxx>
using namespace ::com::sun::star;
namespace
{
class LotusWordProTest : public ::CppUnit::TestFixture
{
public:
LotusWordProTest();
~LotusWordProTest();
virtual void setUp();
virtual void tearDown();
void recursiveScan(const rtl::OUString &rURL, bool bExpected);
bool load(const rtl::OUString &rURL);
void test();
CPPUNIT_TEST_SUITE(LotusWordProTest);
CPPUNIT_TEST(test);
CPPUNIT_TEST_SUITE_END();
private:
uno::Reference<uno::XComponentContext> m_xContext;
uno::Reference<lang::XMultiComponentFactory> m_xFactory;
uno::Reference<lang::XMultiServiceFactory> m_xMSF;
uno::Reference<document::XFilter> m_xFilter;
::rtl::OUString m_aSrcRoot;
int m_nLoadedDocs;
};
LotusWordProTest::LotusWordProTest() : m_aSrcRoot( RTL_CONSTASCII_USTRINGPARAM( "file://" ) ), m_nLoadedDocs(0)
{
m_xContext = cppu::defaultBootstrap_InitialComponentContext();
m_xFactory = m_xContext->getServiceManager();
m_xMSF = uno::Reference<lang::XMultiServiceFactory>(m_xFactory, uno::UNO_QUERY_THROW);
m_xFilter = uno::Reference< document::XFilter >(m_xMSF->createInstance(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.Writer.LotusWordProImportFilter"))),
uno::UNO_QUERY_THROW);
const char* pSrcRoot = getenv( "SRC_ROOT" );
CPPUNIT_ASSERT_MESSAGE("SRC_ROOT env variable not set", pSrcRoot != NULL && pSrcRoot[0] != 0);
m_aSrcRoot += rtl::OUString::createFromAscii( pSrcRoot );
//Without this we're crashing because callees are using
//getProcessServiceFactory. In general those should be removed in favour
//of retaining references to the root ServiceFactory as its passed around
comphelper::setProcessServiceFactory(m_xMSF);
//Lotus Import filter pokes at printers :-(
InitVCL(m_xMSF);
}
LotusWordProTest::~LotusWordProTest()
{
DeInitVCL();
}
void LotusWordProTest::setUp()
{
}
void LotusWordProTest::tearDown()
{
}
bool LotusWordProTest::load(const rtl::OUString &rURL)
{
uno::Sequence< beans::PropertyValue > aDescriptor(1);
aDescriptor[0].Name = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("URL"));
aDescriptor[0].Value <<= rURL;
sal_Bool bRet = m_xFilter->filter(aDescriptor);
++m_nLoadedDocs;
return bRet;
}
void LotusWordProTest::recursiveScan(const rtl::OUString &rURL, bool bExpected)
{
osl::Directory aDir(rURL);
CPPUNIT_ASSERT(osl::FileBase::E_None == aDir.open());
osl::DirectoryItem aItem;
osl::FileStatus aFileStatus(osl_FileStatus_Mask_FileURL|osl_FileStatus_Mask_Type);
while (aDir.getNextItem(aItem) == osl::FileBase::E_None)
{
aItem.getFileStatus(aFileStatus);
rtl::OUString sURL = aFileStatus.getFileURL();
if (aFileStatus.getFileType() == osl::FileStatus::Directory)
recursiveScan(sURL, bExpected);
else
{
bool bRes = load(sURL);
rtl::OString aRes(rtl::OUStringToOString(sURL, osl_getThreadTextEncoding()));
CPPUNIT_ASSERT_MESSAGE(aRes.getStr(), bRes == bExpected);
}
}
CPPUNIT_ASSERT(osl::FileBase::E_None == aDir.close());
}
void LotusWordProTest::test()
{
recursiveScan(m_aSrcRoot + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/lotuswordpro/qa/cppunit/data/pass")), true);
recursiveScan(m_aSrcRoot + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/lotuswordpro/qa/cppunit/data/fail/")), false);
printf("LotusWordPro: tested %d files\n", m_nLoadedDocs);
}
CPPUNIT_TEST_SUITE_REGISTRATION(LotusWordProTest);
}
CPPUNIT_PLUGIN_IMPLEMENT();
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Version: MPL 1.1 / GPLv3+ / LGPLv3+
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Initial Developer of the Original Code is
* Caolán McNamara <[email protected]> (Red Hat, Inc.)
* Portions created by the Initial Developer are Copyright (C) 2011 the
* Initial Developer. All Rights Reserved.
*
* Contributor(s): Caolán McNamara <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 3 or later (the "GPLv3+"), or
* the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
* in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
* instead of those above.
*/
#include <sal/cppunit.h>
#include <cppuhelper/bootstrap.hxx>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/document/XFilter.hpp>
#include <osl/file.hxx>
#include <osl/process.h>
#include <vcl/svapp.hxx>
using namespace ::com::sun::star;
namespace
{
class LotusWordProTest : public ::CppUnit::TestFixture
{
public:
LotusWordProTest();
~LotusWordProTest();
virtual void setUp();
virtual void tearDown();
void recursiveScan(const rtl::OUString &rURL, bool bExpected);
bool load(const rtl::OUString &rURL);
void test();
CPPUNIT_TEST_SUITE(LotusWordProTest);
CPPUNIT_TEST(test);
CPPUNIT_TEST_SUITE_END();
private:
uno::Reference<uno::XComponentContext> m_xContext;
uno::Reference<lang::XMultiComponentFactory> m_xFactory;
uno::Reference<lang::XMultiServiceFactory> m_xMSF;
uno::Reference<document::XFilter> m_xFilter;
::rtl::OUString m_aSrcRoot;
int m_nLoadedDocs;
};
LotusWordProTest::LotusWordProTest() : m_aSrcRoot( RTL_CONSTASCII_USTRINGPARAM( "file://" ) ), m_nLoadedDocs(0)
{
m_xContext = cppu::defaultBootstrap_InitialComponentContext();
m_xFactory = m_xContext->getServiceManager();
m_xMSF = uno::Reference<lang::XMultiServiceFactory>(m_xFactory, uno::UNO_QUERY_THROW);
m_xFilter = uno::Reference< document::XFilter >(m_xMSF->createInstance(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.Writer.LotusWordProImportFilter"))),
uno::UNO_QUERY_THROW);
const char* pSrcRoot = getenv( "SRC_ROOT" );
CPPUNIT_ASSERT_MESSAGE("SRC_ROOT env variable not set", pSrcRoot != NULL && pSrcRoot[0] != 0);
#ifdef WNT
if (pSrcRoot[1] == ':')
m_aSrcRoot += rtl::OUString::createFromAscii( "/" );
#endif
m_aSrcRoot += rtl::OUString::createFromAscii( pSrcRoot );
//Without this we're crashing because callees are using
//getProcessServiceFactory. In general those should be removed in favour
//of retaining references to the root ServiceFactory as its passed around
comphelper::setProcessServiceFactory(m_xMSF);
//Lotus Import filter pokes at printers :-(
InitVCL(m_xMSF);
}
LotusWordProTest::~LotusWordProTest()
{
DeInitVCL();
}
void LotusWordProTest::setUp()
{
}
void LotusWordProTest::tearDown()
{
}
bool LotusWordProTest::load(const rtl::OUString &rURL)
{
uno::Sequence< beans::PropertyValue > aDescriptor(1);
aDescriptor[0].Name = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("URL"));
aDescriptor[0].Value <<= rURL;
sal_Bool bRet = m_xFilter->filter(aDescriptor);
++m_nLoadedDocs;
return bRet;
}
void LotusWordProTest::recursiveScan(const rtl::OUString &rURL, bool bExpected)
{
osl::Directory aDir(rURL);
CPPUNIT_ASSERT(osl::FileBase::E_None == aDir.open());
osl::DirectoryItem aItem;
osl::FileStatus aFileStatus(osl_FileStatus_Mask_FileURL|osl_FileStatus_Mask_Type);
while (aDir.getNextItem(aItem) == osl::FileBase::E_None)
{
aItem.getFileStatus(aFileStatus);
rtl::OUString sURL = aFileStatus.getFileURL();
if (aFileStatus.getFileType() == osl::FileStatus::Directory)
recursiveScan(sURL, bExpected);
else
{
bool bRes = load(sURL);
rtl::OString aRes(rtl::OUStringToOString(sURL, osl_getThreadTextEncoding()));
CPPUNIT_ASSERT_MESSAGE(aRes.getStr(), bRes == bExpected);
}
}
CPPUNIT_ASSERT(osl::FileBase::E_None == aDir.close());
}
void LotusWordProTest::test()
{
recursiveScan(m_aSrcRoot + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/clone/filters/lotuswordpro/qa/cppunit/data/pass")), true);
recursiveScan(m_aSrcRoot + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/clone/filters/lotuswordpro/qa/cppunit/data/fail/")), false);
printf("LotusWordPro: tested %d files\n", m_nLoadedDocs);
}
CPPUNIT_TEST_SUITE_REGISTRATION(LotusWordProTest);
}
CPPUNIT_PLUGIN_IMPLEMENT();
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
Fix lotuswordpro unit test on Windows
|
Fix lotuswordpro unit test on Windows
file: URLs on Windows are of the form file:///c:/path/to/file , and
the SRC_ROOT environment variable is of the form C:/lo/git/master, so
we can't just concatenate "file://" and SRC_ROOT, but have to insert a
"/".
Windows programs don't understand Cygwin symlinks, so we have to
specify the path from SRC_ROOT to lotuswordpro through an explicit
clone/filters path.
|
C++
|
mpl-2.0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
54f5bec2e7b12acb28cb1070fa2ffb2d3fa6867c
|
rtree/wrapper.cc
|
rtree/wrapper.cc
|
/*
# =============================================================================
# Rtree spatial index. Copyright (C) 2007 Sean C. Gillies
#
# 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
#
# Contact email: [email protected]
# =============================================================================
*/
#include "gispyspatialindex.h"
#include "Python.h"
#ifdef _MSC_VER
#include "SpatialIndex.h"
#else
#include <spatialindex/SpatialIndex.h>
#endif
using namespace SpatialIndex;
class PyListVisitor : public IVisitor
{
public:
PyListVisitor(PyObject *o)
{
ids = o;
Py_INCREF(ids);
}
~PyListVisitor()
{
Py_DECREF(ids);
}
void visitNode(const INode & n) {}
void visitData(const IData & d)
{
PyList_Append(ids, PyLong_FromLongLong(d.getIdentifier()));
}
void visitData(std::vector<const IData*>& v) {}
private:
PyObject *ids;
};
extern "C"
GISPySpatialIndex *
RtreeIndex_new(char* filename, unsigned long nPageLength, int load)
{
if (!filename)
return new GISPySpatialIndex;
else
{
if (load == 1)
{
return new GISPySpatialIndex(filename);
}
else
{
if (!nPageLength) nPageLength=4096;
return new GISPySpatialIndex(filename, nPageLength);
}
}
}
extern "C"
void
RtreeIndex_del(GISPySpatialIndex *index)
{
delete index;
}
extern "C"
int
RtreeIndex_insertData(GISPySpatialIndex *index, uint64_t id,
double *min, double *max)
{
try {
index->index().insertData(0, 0, SpatialIndex::Region(min, max, 2), id);
return 1;
}
catch (Tools::Exception& e) {
PyErr_SetString(PyExc_TypeError, e.what().c_str());
return 0;
}
}
extern "C"
int
RtreeIndex_deleteData(GISPySpatialIndex *index, uint64_t id,
double *min, double *max)
{
try {
index->index().deleteData(SpatialIndex::Region(min, max, 2), id);
return 1;
}
catch (Tools::Exception& e) {
PyErr_SetString(PyExc_TypeError, e.what().c_str());
return NULL;
}
}
extern "C"
PyObject *
RtreeIndex_intersects(GISPySpatialIndex *index, double *min, double *max)
{
/* get intersecting data */
int count=0;
PyObject *ids;
ids = PyList_New((size_t)count);
PyListVisitor *visitor = new PyListVisitor(ids);
try {
const SpatialIndex::Region *region = new SpatialIndex::Region(min, max, 2);
index->index().intersectsWithQuery((*region), (*visitor));
delete region;
delete visitor;
return ids;
}
catch (Tools::Exception& e) {
PyErr_SetString(PyExc_TypeError, e.what().c_str());
delete visitor;
return NULL;
}
}
extern "C"
int
RtreeIndex_isValid(GISPySpatialIndex *index)
{
try {
return (int) index->index().isIndexValid();
}
catch (...) {
// isIndexValid throws an exception for empty indexes which we'll assume is valid
return 1;
}
}
extern "C"
PyObject *
RtreeIndex_nearestNeighbors(GISPySpatialIndex *index, uint32_t num_results, double *min, double *max)
{
/* get intersecting data */
int count=0;
PyObject *ids;
ids = PyList_New((size_t)count);
PyListVisitor *visitor = new PyListVisitor(ids);
try {
const SpatialIndex::Region *region = new SpatialIndex::Region(min, max, 2);
index->index().nearestNeighborQuery(num_results, (*region), (*visitor));
delete region;
delete visitor;
return ids;
}
catch (Tools::Exception& e) {
PyErr_SetString(PyExc_TypeError, e.what().c_str());
delete visitor;
return NULL;
}
}
|
/*
# =============================================================================
# Rtree spatial index. Copyright (C) 2007 Sean C. Gillies
#
# 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
#
# Contact email: [email protected]
# =============================================================================
*/
#include "gispyspatialindex.h"
#include "Python.h"
#ifdef _MSC_VER
#include "SpatialIndex.h"
#else
#include <spatialindex/SpatialIndex.h>
#endif
using namespace SpatialIndex;
class PyListVisitor : public IVisitor
{
public:
PyListVisitor(PyObject *o)
{
ids = o;
Py_INCREF(ids);
}
~PyListVisitor()
{
Py_DECREF(ids);
}
void visitNode(const INode & n) {}
void visitData(const IData & d)
{
PyObject* ob = PyLong_FromLongLong(d.getIdentifier());
PyList_Append(ids, ob);
Py_DECREF(ob);
}
void visitData(std::vector<const IData*>& v) {}
private:
PyObject *ids;
};
extern "C"
GISPySpatialIndex *
RtreeIndex_new(char* filename, unsigned long nPageLength, int load)
{
if (!filename)
return new GISPySpatialIndex;
else
{
if (load == 1)
{
return new GISPySpatialIndex(filename);
}
else
{
if (!nPageLength) nPageLength=4096;
return new GISPySpatialIndex(filename, nPageLength);
}
}
}
extern "C"
void
RtreeIndex_del(GISPySpatialIndex *index)
{
delete index;
}
extern "C"
int
RtreeIndex_insertData(GISPySpatialIndex *index, uint64_t id,
double *min, double *max)
{
try {
index->index().insertData(0, 0, SpatialIndex::Region(min, max, 2), id);
return 1;
}
catch (Tools::Exception& e) {
PyErr_SetString(PyExc_TypeError, e.what().c_str());
return 0;
}
}
extern "C"
int
RtreeIndex_deleteData(GISPySpatialIndex *index, uint64_t id,
double *min, double *max)
{
try {
index->index().deleteData(SpatialIndex::Region(min, max, 2), id);
return 1;
}
catch (Tools::Exception& e) {
PyErr_SetString(PyExc_TypeError, e.what().c_str());
return NULL;
}
}
extern "C"
PyObject *
RtreeIndex_intersects(GISPySpatialIndex *index, double *min, double *max)
{
/* get intersecting data */
int count=0;
PyObject *ids;
ids = PyList_New((size_t)count);
PyListVisitor *visitor = new PyListVisitor(ids);
try {
const SpatialIndex::Region *region = new SpatialIndex::Region(min, max, 2);
index->index().intersectsWithQuery((*region), (*visitor));
delete region;
delete visitor;
return ids;
}
catch (Tools::Exception& e) {
PyErr_SetString(PyExc_TypeError, e.what().c_str());
delete visitor;
return NULL;
}
}
extern "C"
int
RtreeIndex_isValid(GISPySpatialIndex *index)
{
try {
return (int) index->index().isIndexValid();
}
catch (...) {
// isIndexValid throws an exception for empty indexes which we'll assume is valid
return 1;
}
}
extern "C"
PyObject *
RtreeIndex_nearestNeighbors(GISPySpatialIndex *index, uint32_t num_results, double *min, double *max)
{
/* get intersecting data */
int count=0;
PyObject *ids;
ids = PyList_New((size_t)count);
PyListVisitor *visitor = new PyListVisitor(ids);
try {
const SpatialIndex::Region *region = new SpatialIndex::Region(min, max, 2);
index->index().nearestNeighborQuery(num_results, (*region), (*visitor));
delete region;
delete visitor;
return ids;
}
catch (Tools::Exception& e) {
PyErr_SetString(PyExc_TypeError, e.what().c_str());
delete visitor;
return NULL;
}
}
|
fix #181, incorrect reference counting in VisitData
|
fix #181, incorrect reference counting in VisitData
|
C++
|
mit
|
mwtoews/rtree,Toblerity/rtree,parasmehta/tprtree,mwtoews/rtree,Toblerity/rtree
|
523f587726e2f9a62db03caf750420b9df246f74
|
cgogn/rendering/drawer.cpp
|
cgogn/rendering/drawer.cpp
|
/*******************************************************************************
* CGoGN: Combinatorial and Geometric modeling with Generic N-dimensional Maps *
* Copyright (C) 2015, IGG Group, ICube, University of Strasbourg, France *
* *
* 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. *
* *
* Web site: http://cgogn.unistra.fr/ *
* Contact information: [email protected] *
* *
*******************************************************************************/
#define CGOGN_RENDERING_DLL_EXPORT
#include <cgogn/rendering/drawer.h>
#include <QOpenGLFunctions>
#include <iostream>
#include<QColor>
namespace cgogn
{
namespace rendering
{
// static members init
ShaderColorPerVertex* Drawer::shader_cpv_ = nullptr;
ShaderBoldLine* Drawer::shader_bl_ = nullptr;
ShaderRoundPoint* Drawer::shader_rp_ = nullptr;
ShaderPointSprite* Drawer::shader_ps_ = nullptr;
int32 Drawer::nb_instances_ = 0;
Drawer::Drawer():
current_size_(1.0f),
current_aa_(true),
current_ball_(true)
{
nb_instances_++;
vbo_pos_ = new VBO(3);
vbo_col_ = new VBO(3);
if (!shader_cpv_)
shader_cpv_ = new ShaderColorPerVertex();
if (!shader_bl_)
shader_bl_ = new ShaderBoldLine(true);
if (!shader_rp_)
shader_rp_ = new ShaderRoundPoint(true);
if (!shader_ps_)
shader_ps_ = new ShaderPointSprite(true);
param_cpv_ = shader_cpv_->generate_param();
param_bl_ = shader_bl_->generate_param();
param_rp_ = shader_rp_->generate_param();
param_ps_ = shader_ps_->generate_param();
param_cpv_->set_vbo(vbo_pos_,vbo_col_);
param_bl_->set_vbo(vbo_pos_,vbo_col_);
param_rp_->set_vbo(vbo_pos_,vbo_col_);
param_ps_->set_vbo(vbo_pos_,vbo_col_);
}
void Drawer::reinit_vao()
{
param_cpv_->reinit_vao();
param_bl_->reinit_vao();
param_rp_->reinit_vao();
param_ps_->reinit_vao();
param_cpv_->set_vbo(vbo_pos_,vbo_col_);
param_bl_->set_vbo(vbo_pos_,vbo_col_);
param_rp_->set_vbo(vbo_pos_,vbo_col_);
param_ps_->set_vbo(vbo_pos_,vbo_col_);
}
Drawer::~Drawer()
{
delete vbo_pos_;
delete vbo_col_;
nb_instances_--;
if (nb_instances_ == 0)
{
// delete shaders when last drawer is deleted
// ensure context still enable when delete shaders
delete shader_ps_;
delete shader_rp_;
delete shader_bl_;
delete shader_cpv_;
}
}
void Drawer::new_list()
{
data_pos_.clear();
data_col_.clear();
begins_point_.clear();
begins_round_point_.clear();
begins_balls_.clear();
begins_line_.clear();
begins_bold_line_.clear();
begins_face_.clear();
}
void Drawer::begin(GLenum mode)
{
switch (mode)
{
case GL_POINTS:
if (current_ball_)
{
begins_balls_.push_back(PrimParam(data_pos_.size(), mode, current_size_,false));
current_begin_ = &begins_balls_;
}
else if (current_size_ > 2.0)
{
begins_round_point_.push_back(PrimParam(data_pos_.size(), mode, current_size_,current_aa_));
current_begin_ = &begins_round_point_;
}
else
{
begins_point_.push_back(PrimParam(data_pos_.size(), mode, current_size_,false));
current_begin_ = &begins_point_;
}
break;
case GL_LINES:
case GL_LINE_STRIP:
case GL_LINE_LOOP:
if (current_size_ > 1.0)
{
begins_bold_line_.push_back(PrimParam(data_pos_.size(), mode, current_size_,current_aa_));
current_begin_ = &begins_bold_line_;
}
else
{
begins_line_.push_back(PrimParam(data_pos_.size(), mode, 1.0,current_aa_));
current_begin_ = &begins_line_;
}
break;
default:
begins_face_.push_back(PrimParam(data_pos_.size(), mode, 1.0f,false));
current_begin_ = &begins_face_;
break;
}
}
void Drawer::end()
{
current_begin_->back().nb = uint32(data_pos_.size() - current_begin_->back().begin);
}
void Drawer::vertex3f(float32 x, float32 y, float32 z)
{
if (data_pos_.size() == data_col_.size())
{
if (data_col_.empty())
data_col_.push_back(Vec3f{1.0f, 1.0f, 1.0f});
else
data_col_.push_back( data_col_.back());
}
data_pos_.push_back(Vec3f{x,y,z});
}
void Drawer::color3f(float32 r, float32 g, float32 b)
{
if (data_pos_.size() == data_col_.size())
data_col_.push_back(Vec3f{r,g,b});
else
data_col_.back() = Vec3f{r,g,b};
}
void Drawer::end_list()
{
uint32 nb_elts = uint32(data_pos_.size());
if (nb_elts == 0)
return;
vbo_pos_->allocate(nb_elts,3);
float32* ptr = vbo_pos_->lock_pointer();
std::memcpy(ptr,data_pos_[0].data(),nb_elts*12);
vbo_pos_->release_pointer();
vbo_col_->allocate(nb_elts,3);
ptr = vbo_col_->lock_pointer();
std::memcpy(ptr,data_col_[0].data(),nb_elts*12);
vbo_col_->release_pointer();
// free memory
data_pos_.clear();
data_pos_.shrink_to_fit();
data_col_.clear();
data_col_.shrink_to_fit();
}
void Drawer::call_list(const QMatrix4x4& projection, const QMatrix4x4& modelview, QOpenGLFunctions_3_3_Core* ogl33)
{
//classic rendering
if (!begins_point_.empty() && !begins_line_.empty() && !begins_face_.empty())
{
param_cpv_->bind(projection,modelview);
for (auto& pp : begins_point_)
{
ogl33->glPointSize(pp.width);
ogl33->glDrawArrays(pp.mode, pp.begin, pp.nb);
}
for (auto& pp : begins_line_)
{
ogl33->glDrawArrays(pp.mode, pp.begin, pp.nb);
}
for (auto& pp : begins_face_)
{
ogl33->glDrawArrays(pp.mode, pp.begin, pp.nb);
}
param_cpv_->release();
}
// balls
if (!begins_balls_.empty())
{
param_ps_->bind(projection,modelview);
for (auto& pp : begins_balls_)
{
shader_ps_->set_size(pp.width);
ogl33->glDrawArrays(pp.mode, pp.begin, pp.nb);
}
param_ps_->release();
}
// round points
if (!begins_round_point_.empty())
{
param_rp_->bind(projection,modelview);
for (auto& pp : begins_round_point_)
{
if (pp.aa)
{
ogl33->glEnable(GL_BLEND);
ogl33->glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
shader_rp_->set_size(pp.width);
ogl33->glDrawArrays(pp.mode, pp.begin, pp.nb);
if (pp.aa)
ogl33->glDisable(GL_BLEND);
}
param_rp_->release();
}
// bold lines
if (!begins_bold_line_.empty())
{
param_bl_->bind(projection,modelview);
for (auto& pp : begins_bold_line_)
{
shader_bl_->set_width(pp.width);
shader_bl_->set_color(QColor(255,255,0));
if (pp.aa)
{
ogl33->glEnable(GL_BLEND);
ogl33->glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
ogl33->glDrawArrays(pp.mode, pp.begin, pp.nb);
if (pp.aa)
ogl33->glDisable(GL_BLEND);
}
param_bl_->release();
}
}
} // namespace rendering
} // namespace cgogn
|
/*******************************************************************************
* CGoGN: Combinatorial and Geometric modeling with Generic N-dimensional Maps *
* Copyright (C) 2015, IGG Group, ICube, University of Strasbourg, France *
* *
* 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. *
* *
* Web site: http://cgogn.unistra.fr/ *
* Contact information: [email protected] *
* *
*******************************************************************************/
#define CGOGN_RENDERING_DLL_EXPORT
#include <cgogn/rendering/drawer.h>
#include <QOpenGLFunctions>
#include <iostream>
#include<QColor>
namespace cgogn
{
namespace rendering
{
// static members init
ShaderColorPerVertex* Drawer::shader_cpv_ = nullptr;
ShaderBoldLine* Drawer::shader_bl_ = nullptr;
ShaderRoundPoint* Drawer::shader_rp_ = nullptr;
ShaderPointSprite* Drawer::shader_ps_ = nullptr;
int32 Drawer::nb_instances_ = 0;
Drawer::Drawer():
current_size_(1.0f),
current_aa_(true),
current_ball_(true)
{
nb_instances_++;
vbo_pos_ = new VBO(3);
vbo_col_ = new VBO(3);
if (!shader_cpv_)
shader_cpv_ = new ShaderColorPerVertex();
if (!shader_bl_)
shader_bl_ = new ShaderBoldLine(true);
if (!shader_rp_)
shader_rp_ = new ShaderRoundPoint(true);
if (!shader_ps_)
shader_ps_ = new ShaderPointSprite(true);
param_cpv_ = shader_cpv_->generate_param();
param_bl_ = shader_bl_->generate_param();
param_rp_ = shader_rp_->generate_param();
param_ps_ = shader_ps_->generate_param();
param_cpv_->set_vbo(vbo_pos_,vbo_col_);
param_bl_->set_vbo(vbo_pos_,vbo_col_);
param_rp_->set_vbo(vbo_pos_,vbo_col_);
param_ps_->set_vbo(vbo_pos_,vbo_col_);
}
void Drawer::reinit_vao()
{
param_cpv_->reinit_vao();
param_bl_->reinit_vao();
param_rp_->reinit_vao();
param_ps_->reinit_vao();
param_cpv_->set_vbo(vbo_pos_,vbo_col_);
param_bl_->set_vbo(vbo_pos_,vbo_col_);
param_rp_->set_vbo(vbo_pos_,vbo_col_);
param_ps_->set_vbo(vbo_pos_,vbo_col_);
}
Drawer::~Drawer()
{
delete vbo_pos_;
delete vbo_col_;
nb_instances_--;
if (nb_instances_ == 0)
{
// delete shaders when last drawer is deleted
// ensure context still enable when delete shaders
delete shader_ps_;
delete shader_rp_;
delete shader_bl_;
delete shader_cpv_;
}
}
void Drawer::new_list()
{
data_pos_.clear();
data_col_.clear();
begins_point_.clear();
begins_round_point_.clear();
begins_balls_.clear();
begins_line_.clear();
begins_bold_line_.clear();
begins_face_.clear();
}
void Drawer::begin(GLenum mode)
{
switch (mode)
{
case GL_POINTS:
if (current_ball_)
{
begins_balls_.push_back(PrimParam(data_pos_.size(), mode, current_size_,false));
current_begin_ = &begins_balls_;
}
else if (current_size_ > 2.0)
{
begins_round_point_.push_back(PrimParam(data_pos_.size(), mode, current_size_,current_aa_));
current_begin_ = &begins_round_point_;
}
else
{
begins_point_.push_back(PrimParam(data_pos_.size(), mode, current_size_,false));
current_begin_ = &begins_point_;
}
break;
case GL_LINES:
case GL_LINE_STRIP:
case GL_LINE_LOOP:
if (current_size_ > 1.0)
{
begins_bold_line_.push_back(PrimParam(data_pos_.size(), mode, current_size_,current_aa_));
current_begin_ = &begins_bold_line_;
}
else
{
begins_line_.push_back(PrimParam(data_pos_.size(), mode, 1.0,current_aa_));
current_begin_ = &begins_line_;
}
break;
default:
begins_face_.push_back(PrimParam(data_pos_.size(), mode, 1.0f,false));
current_begin_ = &begins_face_;
break;
}
}
void Drawer::end()
{
current_begin_->back().nb = uint32(data_pos_.size() - current_begin_->back().begin);
}
void Drawer::vertex3f(float32 x, float32 y, float32 z)
{
if (data_pos_.size() == data_col_.size())
{
if (data_col_.empty())
data_col_.push_back(Vec3f{1.0f, 1.0f, 1.0f});
else
data_col_.push_back( data_col_.back());
}
data_pos_.push_back(Vec3f{x,y,z});
}
void Drawer::color3f(float32 r, float32 g, float32 b)
{
if (data_pos_.size() == data_col_.size())
data_col_.push_back(Vec3f{r,g,b});
else
data_col_.back() = Vec3f{r,g,b};
}
void Drawer::end_list()
{
uint32 nb_elts = uint32(data_pos_.size());
if (nb_elts == 0)
return;
vbo_pos_->allocate(nb_elts,3);
float32* ptr = vbo_pos_->lock_pointer();
std::memcpy(ptr,data_pos_[0].data(),nb_elts*12);
vbo_pos_->release_pointer();
vbo_col_->allocate(nb_elts,3);
ptr = vbo_col_->lock_pointer();
std::memcpy(ptr,data_col_[0].data(),nb_elts*12);
vbo_col_->release_pointer();
// free memory
data_pos_.clear();
data_pos_.shrink_to_fit();
data_col_.clear();
data_col_.shrink_to_fit();
}
void Drawer::call_list(const QMatrix4x4& projection, const QMatrix4x4& modelview, QOpenGLFunctions_3_3_Core* ogl33)
{
//classic rendering
if (!begins_point_.empty() || !begins_line_.empty() || !begins_face_.empty())
{
param_cpv_->bind(projection,modelview);
for (auto& pp : begins_point_)
{
ogl33->glPointSize(pp.width);
ogl33->glDrawArrays(pp.mode, pp.begin, pp.nb);
}
for (auto& pp : begins_line_)
{
ogl33->glDrawArrays(pp.mode, pp.begin, pp.nb);
}
for (auto& pp : begins_face_)
{
ogl33->glDrawArrays(pp.mode, pp.begin, pp.nb);
}
param_cpv_->release();
}
// balls
if (!begins_balls_.empty())
{
param_ps_->bind(projection,modelview);
for (auto& pp : begins_balls_)
{
shader_ps_->set_size(pp.width);
ogl33->glDrawArrays(pp.mode, pp.begin, pp.nb);
}
param_ps_->release();
}
// round points
if (!begins_round_point_.empty())
{
param_rp_->bind(projection,modelview);
for (auto& pp : begins_round_point_)
{
if (pp.aa)
{
ogl33->glEnable(GL_BLEND);
ogl33->glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
shader_rp_->set_size(pp.width);
ogl33->glDrawArrays(pp.mode, pp.begin, pp.nb);
if (pp.aa)
ogl33->glDisable(GL_BLEND);
}
param_rp_->release();
}
// bold lines
if (!begins_bold_line_.empty())
{
param_bl_->bind(projection,modelview);
for (auto& pp : begins_bold_line_)
{
shader_bl_->set_width(pp.width);
shader_bl_->set_color(QColor(255,255,0));
if (pp.aa)
{
ogl33->glEnable(GL_BLEND);
ogl33->glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
ogl33->glDrawArrays(pp.mode, pp.begin, pp.nb);
if (pp.aa)
ogl33->glDisable(GL_BLEND);
}
param_bl_->release();
}
}
} // namespace rendering
} // namespace cgogn
|
fix bug of phantom triangles
|
fix bug of phantom triangles
|
C++
|
lgpl-2.1
|
etienneschmitt/CGoGN_2,cgogn/CGoGN_2,cgogn/CGoGN_2,untereiner/CGoGN_2,untereiner/CGoGN_2,david-cazier/CGoGN_2,david-cazier/CGoGN_2
|
a4d7f4fea574cfa53678c2722638aff140b830b6
|
Source/platform/network/SocketStreamHandle.cpp
|
Source/platform/network/SocketStreamHandle.cpp
|
/*
* Copyright (C) 2009, 2011, 2012 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "platform/network/SocketStreamHandle.h"
#include "platform/Logging.h"
#include "platform/network/SocketStreamError.h"
#include "platform/network/SocketStreamHandleClient.h"
#include "platform/network/SocketStreamHandleInternal.h"
#include "public/platform/Platform.h"
#include "public/platform/WebData.h"
#include "public/platform/WebSocketStreamError.h"
#include "public/platform/WebSocketStreamHandle.h"
#include "wtf/PassOwnPtr.h"
namespace WebCore {
static const unsigned bufferSize = 100 * 1024 * 1024;
SocketStreamHandleInternal::SocketStreamHandleInternal(SocketStreamHandle* handle)
: m_handle(handle)
, m_maxPendingSendAllowed(0)
, m_pendingAmountSent(0)
{
}
SocketStreamHandleInternal::~SocketStreamHandleInternal()
{
m_handle = 0;
}
void SocketStreamHandleInternal::connect(const KURL& url)
{
m_socket = adoptPtr(blink::Platform::current()->createSocketStreamHandle());
WTF_LOG(Network, "SocketStreamHandleInternal %p connect()", this);
ASSERT(m_socket);
ASSERT(m_handle);
if (m_handle->m_client)
m_handle->m_client->willOpenSocketStream(m_handle);
m_socket->connect(url, this);
}
int SocketStreamHandleInternal::send(const char* data, int len)
{
WTF_LOG(Network, "SocketStreamHandleInternal %p send() len=%d", this, len);
// FIXME: |m_socket| should not be null here, but it seems that there is the
// case. We should figure out such a path and fix it rather than checking
// null here.
if (!m_socket) {
WTF_LOG(Network, "SocketStreamHandleInternal %p send() m_socket is NULL", this);
return 0;
}
if (m_pendingAmountSent + len > m_maxPendingSendAllowed)
len = m_maxPendingSendAllowed - m_pendingAmountSent;
if (len <= 0)
return len;
blink::WebData webdata(data, len);
if (m_socket->send(webdata)) {
m_pendingAmountSent += len;
WTF_LOG(Network, "SocketStreamHandleInternal %p send() Sent %d bytes", this, len);
return len;
}
WTF_LOG(Network, "SocketStreamHandleInternal %p send() m_socket->send() failed", this);
return 0;
}
void SocketStreamHandleInternal::close()
{
WTF_LOG(Network, "SocketStreamHandleInternal %p close()", this);
if (m_socket)
m_socket->close();
}
void SocketStreamHandleInternal::didOpenStream(blink::WebSocketStreamHandle* socketHandle, int maxPendingSendAllowed)
{
WTF_LOG(Network, "SocketStreamHandleInternal %p didOpenStream() maxPendingSendAllowed=%d", this, maxPendingSendAllowed);
ASSERT(maxPendingSendAllowed > 0);
if (m_handle && m_socket) {
ASSERT(socketHandle == m_socket.get());
m_maxPendingSendAllowed = maxPendingSendAllowed;
m_handle->m_state = SocketStreamHandle::Open;
if (m_handle->m_client) {
m_handle->m_client->didOpenSocketStream(m_handle);
return;
}
}
WTF_LOG(Network, "SocketStreamHandleInternal %p didOpenStream() m_handle or m_socket is NULL", this);
}
void SocketStreamHandleInternal::didSendData(blink::WebSocketStreamHandle* socketHandle, int amountSent)
{
WTF_LOG(Network, "SocketStreamHandleInternal %p didSendData() amountSent=%d", this, amountSent);
ASSERT(amountSent > 0);
if (m_handle && m_socket) {
ASSERT(socketHandle == m_socket.get());
m_pendingAmountSent -= amountSent;
ASSERT(m_pendingAmountSent >= 0);
m_handle->sendPendingData();
}
}
void SocketStreamHandleInternal::didReceiveData(blink::WebSocketStreamHandle* socketHandle, const blink::WebData& data)
{
WTF_LOG(Network, "SocketStreamHandleInternal %p didReceiveData() Received %lu bytes", this, static_cast<unsigned long>(data.size()));
if (m_handle && m_socket) {
ASSERT(socketHandle == m_socket.get());
if (m_handle->m_client)
m_handle->m_client->didReceiveSocketStreamData(m_handle, data.data(), data.size());
}
}
void SocketStreamHandleInternal::didClose(blink::WebSocketStreamHandle* socketHandle)
{
WTF_LOG(Network, "SocketStreamHandleInternal %p didClose()", this);
if (m_handle && m_socket) {
ASSERT(socketHandle == m_socket.get());
m_socket.clear();
SocketStreamHandle* h = m_handle;
m_handle = 0;
if (h->m_client)
h->m_client->didCloseSocketStream(h);
}
}
void SocketStreamHandleInternal::didFail(blink::WebSocketStreamHandle* socketHandle, const blink::WebSocketStreamError& err)
{
WTF_LOG(Network, "SocketStreamHandleInternal %p didFail()", this);
if (m_handle && m_socket) {
ASSERT(socketHandle == m_socket.get());
if (m_handle->m_client)
m_handle->m_client->didFailSocketStream(m_handle, *(PassRefPtr<SocketStreamError>(err)));
}
}
// SocketStreamHandle ----------------------------------------------------------
SocketStreamHandle::SocketStreamHandle(const KURL& url, SocketStreamHandleClient* client)
: m_url(url)
, m_client(client)
, m_state(Connecting)
{
m_internal = SocketStreamHandleInternal::create(this);
m_internal->connect(m_url);
}
SocketStreamHandle::~SocketStreamHandle()
{
setClient(0);
m_internal.clear();
}
SocketStreamHandle::SocketStreamState SocketStreamHandle::state() const
{
return m_state;
}
bool SocketStreamHandle::send(const char* data, int length)
{
if (m_state == Connecting || m_state == Closing)
return false;
if (!m_buffer.isEmpty()) {
if (m_buffer.size() + length > bufferSize) {
// FIXME: report error to indicate that buffer has no more space.
return false;
}
m_buffer.append(data, length);
if (m_client)
m_client->didUpdateBufferedAmount(static_cast<SocketStreamHandle*>(this), bufferedAmount());
return true;
}
int bytesWritten = 0;
if (m_state == Open)
bytesWritten = sendInternal(data, length);
if (bytesWritten < 0)
return false;
if (m_buffer.size() + length - bytesWritten > bufferSize) {
// FIXME: report error to indicate that buffer has no more space.
return false;
}
if (bytesWritten < length) {
m_buffer.append(data + bytesWritten, length - bytesWritten);
if (m_client)
m_client->didUpdateBufferedAmount(static_cast<SocketStreamHandle*>(this), bufferedAmount());
}
return true;
}
void SocketStreamHandle::close()
{
if (m_state == Closed)
return;
m_state = Closing;
if (!m_buffer.isEmpty())
return;
disconnect();
}
void SocketStreamHandle::disconnect()
{
RefPtr<SocketStreamHandle> protect(static_cast<SocketStreamHandle*>(this)); // closeInternal calls the client, which may make the handle get deallocated immediately.
closeInternal();
m_state = Closed;
}
void SocketStreamHandle::setClient(SocketStreamHandleClient* client)
{
ASSERT(!client || (!m_client && m_state == Connecting));
m_client = client;
}
bool SocketStreamHandle::sendPendingData()
{
if (m_state != Open && m_state != Closing)
return false;
if (m_buffer.isEmpty()) {
if (m_state == Open)
return false;
if (m_state == Closing) {
disconnect();
return false;
}
}
bool pending;
do {
int bytesWritten = sendInternal(m_buffer.firstBlockData(), m_buffer.firstBlockSize());
pending = bytesWritten != static_cast<int>(m_buffer.firstBlockSize());
if (bytesWritten <= 0)
return false;
ASSERT(m_buffer.size() - bytesWritten <= bufferSize);
m_buffer.consume(bytesWritten);
} while (!pending && !m_buffer.isEmpty());
if (m_client)
m_client->didUpdateBufferedAmount(static_cast<SocketStreamHandle*>(this), bufferedAmount());
return true;
}
int SocketStreamHandle::sendInternal(const char* buf, int len)
{
if (!m_internal)
return 0;
return m_internal->send(buf, len);
}
void SocketStreamHandle::closeInternal()
{
if (m_internal)
m_internal->close();
}
} // namespace WebCore
|
/*
* Copyright (C) 2009, 2011, 2012 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "platform/network/SocketStreamHandle.h"
#include "platform/Logging.h"
#include "platform/network/SocketStreamError.h"
#include "platform/network/SocketStreamHandleClient.h"
#include "platform/network/SocketStreamHandleInternal.h"
#include "public/platform/Platform.h"
#include "public/platform/WebData.h"
#include "public/platform/WebSocketStreamError.h"
#include "public/platform/WebSocketStreamHandle.h"
#include "wtf/PassOwnPtr.h"
namespace WebCore {
static const unsigned bufferSize = 100 * 1024 * 1024;
SocketStreamHandleInternal::SocketStreamHandleInternal(SocketStreamHandle* handle)
: m_handle(handle)
, m_maxPendingSendAllowed(0)
, m_pendingAmountSent(0)
{
}
SocketStreamHandleInternal::~SocketStreamHandleInternal()
{
m_handle = 0;
}
void SocketStreamHandleInternal::connect(const KURL& url)
{
m_socket = adoptPtr(blink::Platform::current()->createSocketStreamHandle());
WTF_LOG(Network, "SocketStreamHandleInternal %p connect()", this);
ASSERT(m_socket);
ASSERT(m_handle);
if (m_handle->m_client)
m_handle->m_client->willOpenSocketStream(m_handle);
m_socket->connect(url, this);
}
int SocketStreamHandleInternal::send(const char* data, int len)
{
WTF_LOG(Network, "SocketStreamHandleInternal %p send() len=%d", this, len);
// FIXME: |m_socket| should not be null here, but it seems that there is the
// case. We should figure out such a path and fix it rather than checking
// null here.
if (!m_socket) {
WTF_LOG(Network, "SocketStreamHandleInternal %p send() m_socket is NULL", this);
return 0;
}
if (m_pendingAmountSent + len > m_maxPendingSendAllowed)
len = m_maxPendingSendAllowed - m_pendingAmountSent;
if (len <= 0)
return len;
blink::WebData webdata(data, len);
if (m_socket->send(webdata)) {
m_pendingAmountSent += len;
WTF_LOG(Network, "SocketStreamHandleInternal %p send() Sent %d bytes", this, len);
return len;
}
WTF_LOG(Network, "SocketStreamHandleInternal %p send() m_socket->send() failed", this);
return 0;
}
void SocketStreamHandleInternal::close()
{
WTF_LOG(Network, "SocketStreamHandleInternal %p close()", this);
if (m_socket)
m_socket->close();
}
void SocketStreamHandleInternal::didOpenStream(blink::WebSocketStreamHandle* socketHandle, int maxPendingSendAllowed)
{
WTF_LOG(Network, "SocketStreamHandleInternal %p didOpenStream() maxPendingSendAllowed=%d", this, maxPendingSendAllowed);
ASSERT(maxPendingSendAllowed > 0);
if (m_handle && m_socket) {
ASSERT(socketHandle == m_socket.get());
m_maxPendingSendAllowed = maxPendingSendAllowed;
m_handle->m_state = SocketStreamHandle::Open;
if (m_handle->m_client) {
m_handle->m_client->didOpenSocketStream(m_handle);
return;
}
}
WTF_LOG(Network, "SocketStreamHandleInternal %p didOpenStream() m_handle or m_socket is NULL", this);
}
void SocketStreamHandleInternal::didSendData(blink::WebSocketStreamHandle* socketHandle, int amountSent)
{
WTF_LOG(Network, "SocketStreamHandleInternal %p didSendData() amountSent=%d", this, amountSent);
ASSERT(amountSent > 0);
if (m_handle && m_socket) {
ASSERT(socketHandle == m_socket.get());
m_pendingAmountSent -= amountSent;
ASSERT(m_pendingAmountSent >= 0);
m_handle->sendPendingData();
}
}
void SocketStreamHandleInternal::didReceiveData(blink::WebSocketStreamHandle* socketHandle, const blink::WebData& data)
{
WTF_LOG(Network, "SocketStreamHandleInternal %p didReceiveData() Received %lu bytes", this, static_cast<unsigned long>(data.size()));
if (m_handle && m_socket) {
ASSERT(socketHandle == m_socket.get());
if (m_handle->m_client)
m_handle->m_client->didReceiveSocketStreamData(m_handle, data.data(), data.size());
}
}
void SocketStreamHandleInternal::didClose(blink::WebSocketStreamHandle* socketHandle)
{
WTF_LOG(Network, "SocketStreamHandleInternal %p didClose()", this);
if (m_handle && m_socket) {
ASSERT(socketHandle == m_socket.get());
m_socket.clear();
SocketStreamHandle* h = m_handle;
m_handle = 0;
if (h->m_client)
h->m_client->didCloseSocketStream(h);
}
}
void SocketStreamHandleInternal::didFail(blink::WebSocketStreamHandle* socketHandle, const blink::WebSocketStreamError& err)
{
WTF_LOG(Network, "SocketStreamHandleInternal %p didFail()", this);
if (m_handle && m_socket) {
ASSERT(socketHandle == m_socket.get());
if (m_handle->m_client)
m_handle->m_client->didFailSocketStream(m_handle, *(PassRefPtr<SocketStreamError>(err)));
}
}
// SocketStreamHandle ----------------------------------------------------------
SocketStreamHandle::SocketStreamHandle(const KURL& url, SocketStreamHandleClient* client)
: m_url(url)
, m_client(client)
, m_state(Connecting)
{
m_internal = SocketStreamHandleInternal::create(this);
m_internal->connect(m_url);
}
SocketStreamHandle::~SocketStreamHandle()
{
setClient(0);
m_internal.clear();
}
SocketStreamHandle::SocketStreamState SocketStreamHandle::state() const
{
return m_state;
}
bool SocketStreamHandle::send(const char* data, int length)
{
if (m_state == Connecting || m_state == Closing)
return false;
if (!m_buffer.isEmpty()) {
if (m_buffer.size() + length > bufferSize) {
// FIXME: report error to indicate that buffer has no more space.
return false;
}
m_buffer.append(data, length);
if (m_client)
m_client->didUpdateBufferedAmount(this, bufferedAmount());
return true;
}
int bytesWritten = 0;
if (m_state == Open)
bytesWritten = sendInternal(data, length);
if (bytesWritten < 0)
return false;
if (m_buffer.size() + length - bytesWritten > bufferSize) {
// FIXME: report error to indicate that buffer has no more space.
return false;
}
if (bytesWritten < length) {
m_buffer.append(data + bytesWritten, length - bytesWritten);
if (m_client)
m_client->didUpdateBufferedAmount(this, bufferedAmount());
}
return true;
}
void SocketStreamHandle::close()
{
if (m_state == Closed)
return;
m_state = Closing;
if (!m_buffer.isEmpty())
return;
disconnect();
}
void SocketStreamHandle::disconnect()
{
RefPtr<SocketStreamHandle> protect(this); // closeInternal calls the client, which may make the handle get deallocated immediately.
closeInternal();
m_state = Closed;
}
void SocketStreamHandle::setClient(SocketStreamHandleClient* client)
{
ASSERT(!client || (!m_client && m_state == Connecting));
m_client = client;
}
bool SocketStreamHandle::sendPendingData()
{
if (m_state != Open && m_state != Closing)
return false;
if (m_buffer.isEmpty()) {
if (m_state == Open)
return false;
if (m_state == Closing) {
disconnect();
return false;
}
}
bool pending;
do {
int bytesWritten = sendInternal(m_buffer.firstBlockData(), m_buffer.firstBlockSize());
pending = bytesWritten != static_cast<int>(m_buffer.firstBlockSize());
if (bytesWritten <= 0)
return false;
ASSERT(m_buffer.size() - bytesWritten <= bufferSize);
m_buffer.consume(bytesWritten);
} while (!pending && !m_buffer.isEmpty());
if (m_client)
m_client->didUpdateBufferedAmount(this, bufferedAmount());
return true;
}
int SocketStreamHandle::sendInternal(const char* buf, int len)
{
if (!m_internal)
return 0;
return m_internal->send(buf, len);
}
void SocketStreamHandle::closeInternal()
{
if (m_internal)
m_internal->close();
}
} // namespace WebCore
|
Remove unnecessary static_cast<SocketStreamHandle*>().
|
Remove unnecessary static_cast<SocketStreamHandle*>().
|this| is SocketStreamHandle*. These static_casts are unnecessary.
BUG=
Review URL: https://codereview.chromium.org/105513004
git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@163501 bbb929c8-8fbe-4397-9dbb-9b2b20218538
|
C++
|
bsd-3-clause
|
smishenk/blink-crosswalk,Pluto-tv/blink-crosswalk,hgl888/blink-crosswalk-efl,kurli/blink-crosswalk,PeterWangIntel/blink-crosswalk,smishenk/blink-crosswalk,ondra-novak/blink,Pluto-tv/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,Bysmyyr/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,XiaosongWei/blink-crosswalk,smishenk/blink-crosswalk,kurli/blink-crosswalk,XiaosongWei/blink-crosswalk,hgl888/blink-crosswalk-efl,nwjs/blink,crosswalk-project/blink-crosswalk-efl,XiaosongWei/blink-crosswalk,smishenk/blink-crosswalk,modulexcite/blink,XiaosongWei/blink-crosswalk,modulexcite/blink,nwjs/blink,smishenk/blink-crosswalk,Bysmyyr/blink-crosswalk,nwjs/blink,Bysmyyr/blink-crosswalk,PeterWangIntel/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,kurli/blink-crosswalk,smishenk/blink-crosswalk,jtg-gg/blink,PeterWangIntel/blink-crosswalk,PeterWangIntel/blink-crosswalk,modulexcite/blink,jtg-gg/blink,Bysmyyr/blink-crosswalk,ondra-novak/blink,smishenk/blink-crosswalk,Pluto-tv/blink-crosswalk,hgl888/blink-crosswalk-efl,XiaosongWei/blink-crosswalk,XiaosongWei/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,jtg-gg/blink,PeterWangIntel/blink-crosswalk,hgl888/blink-crosswalk-efl,hgl888/blink-crosswalk-efl,Pluto-tv/blink-crosswalk,ondra-novak/blink,nwjs/blink,jtg-gg/blink,modulexcite/blink,crosswalk-project/blink-crosswalk-efl,kurli/blink-crosswalk,nwjs/blink,ondra-novak/blink,hgl888/blink-crosswalk-efl,kurli/blink-crosswalk,hgl888/blink-crosswalk-efl,hgl888/blink-crosswalk-efl,ondra-novak/blink,nwjs/blink,PeterWangIntel/blink-crosswalk,XiaosongWei/blink-crosswalk,ondra-novak/blink,kurli/blink-crosswalk,jtg-gg/blink,modulexcite/blink,hgl888/blink-crosswalk-efl,modulexcite/blink,PeterWangIntel/blink-crosswalk,PeterWangIntel/blink-crosswalk,jtg-gg/blink,kurli/blink-crosswalk,XiaosongWei/blink-crosswalk,Bysmyyr/blink-crosswalk,kurli/blink-crosswalk,hgl888/blink-crosswalk-efl,crosswalk-project/blink-crosswalk-efl,Pluto-tv/blink-crosswalk,modulexcite/blink,Pluto-tv/blink-crosswalk,PeterWangIntel/blink-crosswalk,XiaosongWei/blink-crosswalk,ondra-novak/blink,Bysmyyr/blink-crosswalk,Bysmyyr/blink-crosswalk,nwjs/blink,kurli/blink-crosswalk,Pluto-tv/blink-crosswalk,Bysmyyr/blink-crosswalk,ondra-novak/blink,Pluto-tv/blink-crosswalk,Pluto-tv/blink-crosswalk,modulexcite/blink,jtg-gg/blink,nwjs/blink,ondra-novak/blink,jtg-gg/blink,jtg-gg/blink,nwjs/blink,Bysmyyr/blink-crosswalk,PeterWangIntel/blink-crosswalk,modulexcite/blink,nwjs/blink,kurli/blink-crosswalk,smishenk/blink-crosswalk,jtg-gg/blink,modulexcite/blink,smishenk/blink-crosswalk,Bysmyyr/blink-crosswalk,Pluto-tv/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,smishenk/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,XiaosongWei/blink-crosswalk
|
f42665874352b21abec147ef14c94ccfd04bc1ae
|
remoting/host/encoder_verbatim.cc
|
remoting/host/encoder_verbatim.cc
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/host/encoder_verbatim.h"
#include "gfx/rect.h"
#include "media/base/data_buffer.h"
#include "remoting/base/protocol/chromotocol.pb.h"
namespace remoting {
using media::DataBuffer;
void EncoderVerbatim::Encode(const DirtyRects& dirty_rects,
const uint8* const* input_data,
const int* strides,
bool key_frame,
DataAvailableCallback* data_available_callback) {
int num_rects = dirty_rects.size();
for (int i = 0; i < num_rects; i++) {
scoped_refptr<DataBuffer> data;
gfx::Rect dirty_rect = dirty_rects[i];
scoped_ptr<UpdateStreamPacketHeader> header(new UpdateStreamPacketHeader);
if (EncodeRect(dirty_rect,
input_data,
strides,
header.get(),
&data)) {
EncodingState state = EncodingInProgress;
if (i == 0) {
state |= EncodingStarting;
} else if (i == num_rects - 1) {
state |= EncodingEnded;
}
data_available_callback->Run(header.release(),
data,
state);
}
}
delete data_available_callback;
}
void EncoderVerbatim::SetSize(int width, int height) {
width_ = width;
height_ = height;
}
void EncoderVerbatim::SetPixelFormat(PixelFormat pixel_format) {
// These are sorted so that the most common formats are checked first.
// TODO(hclam): Extract this into a util function.
if (pixel_format == PixelFormatRgb24) {
bytes_per_pixel_ = 3;
} else if (pixel_format == PixelFormatRgb565) {
bytes_per_pixel_ = 2;
} else if (pixel_format == PixelFormatRgb32) {
bytes_per_pixel_ = 4;
} else if (pixel_format != PixelFormatAscii) {
bytes_per_pixel_ = 1;
} else {
NOTREACHED() << "Pixel format not supported";
}
pixel_format_ = pixel_format;
}
bool EncoderVerbatim::EncodeRect(const gfx::Rect& dirty,
const uint8* const* input_data,
const int* strides,
UpdateStreamPacketHeader *header,
scoped_refptr<DataBuffer>* output_data) {
const int kPlanes = 3;
// Calculate the size of output.
int output_size = 0;
for (int i = 0; i < kPlanes; ++i) {
// TODO(hclam): Handle YUV since the height would be different.
output_size += strides[i] * height_;
}
header->set_x(dirty.x());
header->set_y(dirty.y());
header->set_width(dirty.width());
header->set_height(dirty.height());
header->set_encoding(EncodingNone);
header->set_pixel_format(pixel_format_);
*output_data = new DataBuffer(new uint8[output_size], output_size);
uint8* out = (*output_data)->GetWritableData();
for (int i = 0; i < kPlanes; ++i) {
const uint8* in = input_data[i];
// Skip over planes that don't have data.
if (!in)
continue;
// TODO(hclam): Handle YUV since the height would be different.
for (int j = 0; j < height_; ++j) {
int row_size = width_ * bytes_per_pixel_;
DCHECK_LE(row_size, strides[i]);
memcpy(out, in, row_size);
in += strides[i];
out += row_size;
}
}
return true;
}
} // namespace remoting
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/host/encoder_verbatim.h"
#include "gfx/rect.h"
#include "media/base/data_buffer.h"
#include "remoting/base/protocol_util.h"
namespace remoting {
using media::DataBuffer;
void EncoderVerbatim::Encode(const DirtyRects& dirty_rects,
const uint8* const* input_data,
const int* strides,
bool key_frame,
DataAvailableCallback* data_available_callback) {
int num_rects = dirty_rects.size();
for (int i = 0; i < num_rects; i++) {
scoped_refptr<DataBuffer> data;
gfx::Rect dirty_rect = dirty_rects[i];
scoped_ptr<UpdateStreamPacketHeader> header(new UpdateStreamPacketHeader);
if (EncodeRect(dirty_rect,
input_data,
strides,
header.get(),
&data)) {
EncodingState state = EncodingInProgress;
if (i == 0) {
state |= EncodingStarting;
} else if (i == num_rects - 1) {
state |= EncodingEnded;
}
data_available_callback->Run(header.release(),
data,
state);
}
}
delete data_available_callback;
}
void EncoderVerbatim::SetSize(int width, int height) {
width_ = width;
height_ = height;
}
void EncoderVerbatim::SetPixelFormat(PixelFormat pixel_format) {
bytes_per_pixel_ = GetBytesPerPixel(pixel_format);
pixel_format_ = pixel_format;
}
bool EncoderVerbatim::EncodeRect(const gfx::Rect& dirty,
const uint8* const* input_data,
const int* strides,
UpdateStreamPacketHeader *header,
scoped_refptr<DataBuffer>* output_data) {
const int kPlanes = 3;
// Calculate the size of output.
int output_size = 0;
for (int i = 0; i < kPlanes; ++i) {
// TODO(hclam): Handle YUV since the height would be different.
output_size += strides[i] * height_;
}
header->set_x(dirty.x());
header->set_y(dirty.y());
header->set_width(dirty.width());
header->set_height(dirty.height());
header->set_encoding(EncodingNone);
header->set_pixel_format(pixel_format_);
*output_data = new DataBuffer(new uint8[output_size], output_size);
uint8* out = (*output_data)->GetWritableData();
for (int i = 0; i < kPlanes; ++i) {
const uint8* in = input_data[i];
// Skip over planes that don't have data.
if (!in)
continue;
// TODO(hclam): Handle YUV since the height would be different.
for (int j = 0; j < height_; ++j) {
int row_size = width_ * bytes_per_pixel_;
DCHECK_LE(row_size, strides[i]);
memcpy(out, in, row_size);
in += strides[i];
out += row_size;
}
}
return true;
}
} // namespace remoting
|
Use GetBytesPerPixel util function in one more place.
|
remoting: Use GetBytesPerPixel util function in one more place.
Note: This fix another TODO for hclam, missed in the other patch.
BUG=None
TEST=trybots
Review URL: http://codereview.chromium.org/2863028
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@51018 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
Just-D/chromium-1,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,ondra-novak/chromium.src,ondra-novak/chromium.src,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,littlstar/chromium.src,mogoweb/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,patrickm/chromium.src,nacl-webkit/chrome_deps,ondra-novak/chromium.src,Jonekee/chromium.src,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,hgl888/chromium-crosswalk-efl,nacl-webkit/chrome_deps,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,robclark/chromium,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,rogerwang/chromium,TheTypoMaster/chromium-crosswalk,rogerwang/chromium,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,patrickm/chromium.src,anirudhSK/chromium,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,junmin-zhu/chromium-rivertrail,keishi/chromium,Just-D/chromium-1,Jonekee/chromium.src,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,rogerwang/chromium,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,Just-D/chromium-1,Jonekee/chromium.src,chuan9/chromium-crosswalk,robclark/chromium,keishi/chromium,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,ltilve/chromium,hgl888/chromium-crosswalk,robclark/chromium,dushu1203/chromium.src,Chilledheart/chromium,timopulkkinen/BubbleFish,ltilve/chromium,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,markYoungH/chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,rogerwang/chromium,jaruba/chromium.src,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,hujiajie/pa-chromium,Chilledheart/chromium,mogoweb/chromium-crosswalk,markYoungH/chromium.src,anirudhSK/chromium,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,zcbenz/cefode-chromium,jaruba/chromium.src,timopulkkinen/BubbleFish,nacl-webkit/chrome_deps,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,M4sse/chromium.src,mogoweb/chromium-crosswalk,ltilve/chromium,chuan9/chromium-crosswalk,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,zcbenz/cefode-chromium,Jonekee/chromium.src,fujunwei/chromium-crosswalk,keishi/chromium,bright-sparks/chromium-spacewalk,dednal/chromium.src,nacl-webkit/chrome_deps,keishi/chromium,Chilledheart/chromium,Just-D/chromium-1,zcbenz/cefode-chromium,ondra-novak/chromium.src,anirudhSK/chromium,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,anirudhSK/chromium,Fireblend/chromium-crosswalk,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,ltilve/chromium,littlstar/chromium.src,patrickm/chromium.src,bright-sparks/chromium-spacewalk,jaruba/chromium.src,patrickm/chromium.src,junmin-zhu/chromium-rivertrail,robclark/chromium,keishi/chromium,M4sse/chromium.src,dednal/chromium.src,Pluto-tv/chromium-crosswalk,timopulkkinen/BubbleFish,Just-D/chromium-1,keishi/chromium,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,zcbenz/cefode-chromium,nacl-webkit/chrome_deps,dednal/chromium.src,littlstar/chromium.src,hujiajie/pa-chromium,timopulkkinen/BubbleFish,Jonekee/chromium.src,Chilledheart/chromium,rogerwang/chromium,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,keishi/chromium,dednal/chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,nacl-webkit/chrome_deps,jaruba/chromium.src,hujiajie/pa-chromium,dednal/chromium.src,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,ltilve/chromium,dednal/chromium.src,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,rogerwang/chromium,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,ltilve/chromium,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,bright-sparks/chromium-spacewalk,M4sse/chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk,rogerwang/chromium,ChromiumWebApps/chromium,keishi/chromium,patrickm/chromium.src,keishi/chromium,mogoweb/chromium-crosswalk,patrickm/chromium.src,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail,ondra-novak/chromium.src,markYoungH/chromium.src,timopulkkinen/BubbleFish,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,hgl888/chromium-crosswalk,dushu1203/chromium.src,zcbenz/cefode-chromium,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,jaruba/chromium.src,timopulkkinen/BubbleFish,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,rogerwang/chromium,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk,markYoungH/chromium.src,zcbenz/cefode-chromium,dednal/chromium.src,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,ltilve/chromium,dushu1203/chromium.src,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,rogerwang/chromium,robclark/chromium,fujunwei/chromium-crosswalk,anirudhSK/chromium,M4sse/chromium.src,robclark/chromium,ChromiumWebApps/chromium,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,M4sse/chromium.src,littlstar/chromium.src,robclark/chromium,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,axinging/chromium-crosswalk,Jonekee/chromium.src,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,dednal/chromium.src,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,mogoweb/chromium-crosswalk,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,hujiajie/pa-chromium,keishi/chromium,nacl-webkit/chrome_deps,mogoweb/chromium-crosswalk,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,chuan9/chromium-crosswalk,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,TheTypoMaster/chromium-crosswalk,ondra-novak/chromium.src,ChromiumWebApps/chromium,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,keishi/chromium,Just-D/chromium-1,robclark/chromium,robclark/chromium,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,junmin-zhu/chromium-rivertrail,krieger-od/nwjs_chromium.src,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,Fireblend/chromium-crosswalk,robclark/chromium,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,anirudhSK/chromium,Jonekee/chromium.src,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,zcbenz/cefode-chromium,littlstar/chromium.src,hujiajie/pa-chromium,Chilledheart/chromium,markYoungH/chromium.src,ChromiumWebApps/chromium,Just-D/chromium-1,patrickm/chromium.src,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,dushu1203/chromium.src,ChromiumWebApps/chromium,dednal/chromium.src,markYoungH/chromium.src,mogoweb/chromium-crosswalk,ondra-novak/chromium.src,M4sse/chromium.src,ChromiumWebApps/chromium,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,junmin-zhu/chromium-rivertrail,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,zcbenz/cefode-chromium,junmin-zhu/chromium-rivertrail,littlstar/chromium.src,axinging/chromium-crosswalk,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,nacl-webkit/chrome_deps,rogerwang/chromium,fujunwei/chromium-crosswalk
|
61adf4acbf3c5d9e0f881715005b065c6e0e667e
|
Tests/Sandbox/Sources/Implementations/main.cpp
|
Tests/Sandbox/Sources/Implementations/main.cpp
|
#include "neural_network_trainer.hpp"
#include "InputData/sentence.hpp"
#include "Learning/learning_method.hpp"
#include "InputData/image.hpp"
#include "Layer/fully_connected_neural_network.hpp"
#include "Layer/filters.hpp"
using namespace Convolutional;
enum class Categories {
Cat,
NotCat,
CategoryCount
};
int main() {
TrainingData<Categories> trainingData;
InputData::Image someCat("../../image.png");
trainingData.AddData(std::move(someCat), Categories::Cat);
Layer::Layers layers {
Layer::Filters{3},
Layer::Pooler::MaxPooler{},
Layer::FullyConnectedNeuralNetwork{static_cast<std::size_t>(Categories::CategoryCount)}
};
NeuralNetworktrainer<Categories> networktrainer {
50,
std::move(trainingData),
std::move(layers)
};
auto trainedNetwork = networktrainer.Train();
//Learning::memes<Categories> m(trainedNetwork, trainingData);
return 0;
}
|
#include "neural_network_trainer.hpp"
#include "InputData/sentence.hpp"
#include "Learning/learning_method.hpp"
#include "InputData/image.hpp"
#include "Layer/fully_connected_neural_network.hpp"
#include "Layer/filters.hpp"
using namespace Convolutional;
enum class Categories {
Cat,
NotCat,
CategoryCount
};
int main(int argc, char* argv[]){
Magick::InitializeMagick(argv[0]);
TrainingData<Categories> trainingData;
InputData::Image someCat("../../image.png");
trainingData.AddData(std::move(someCat), Categories::Cat);
Layer::Layers layers {
Layer::Filters{3},
Layer::Pooler::MaxPooler{},
Layer::FullyConnectedNeuralNetwork{static_cast<std::size_t>(Categories::CategoryCount)}
};
NeuralNetworktrainer<Categories> networktrainer {
50,
std::move(trainingData),
std::move(layers)
};
auto trainedNetwork = networktrainer.Train();
//Learning::memes<Categories> m(trainedNetwork, trainingData);
return 0;
}
|
Add Initialization for Magick
|
Add Initialization for Magick
|
C++
|
agpl-3.0
|
IDPA16/Hippocrates,SirRade/Hippocrates,SirRade/Hippocrates,IDPA16/Hippocrates,SirRade/JNF_NEAT,IDPA16/CNN-Code
|
6b32903b5501afbdbfe5c6c03874fd65a40c1e4d
|
src/itkIterateNeighborhoodOptimizer.cxx
|
src/itkIterateNeighborhoodOptimizer.cxx
|
/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: $RCSfile: itkIterateNeighborhoodOptimizer.cxx,v $
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkIterateNeighborhoodOptimizer.h"
#include "itkCommand.h"
#include "itkEventObject.h"
#include "itkMacro.h"
namespace itk
{
/**
* Constructor
*/
IterateNeighborhoodOptimizer ::IterateNeighborhoodOptimizer()
{
m_Stop = false;
m_Maximize = false;
m_FullyConnected = true;
m_CurrentIteration = 0;
m_CurrentValue = 0.0;
}
/**
* PrintSelf
*/
void
IterateNeighborhoodOptimizer ::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "Maximize: " << m_Maximize << std::endl;
os << indent << "FullyConnected: " << m_FullyConnected << std::endl;
os << indent << "CurrentIteration: " << m_CurrentIteration;
os << indent << "CurrentValue: " << m_CurrentValue;
if (m_CostFunction)
{
os << indent << "CostFunction: " << m_CostFunction;
}
}
/**
* Start the optimization
*/
void
IterateNeighborhoodOptimizer ::StartOptimization()
{
m_CurrentIteration = 0;
this->SetCurrentPosition(this->GetInitialPosition());
this->ResumeOptimization();
}
/**
* Resume the optimization
*/
void
IterateNeighborhoodOptimizer ::ResumeOptimization()
{
m_Stop = false;
InvokeEvent(StartEvent());
while (!m_Stop)
{
try
{
m_CurrentValue = m_CostFunction->GetValue(this->GetCurrentPosition());
}
catch (ExceptionObject & err)
{
// An exception has occurred, terminate immediately.
StopOptimization();
// Pass exception to caller
throw err;
}
if (m_Stop)
{
break;
}
AdvanceOneStep();
m_CurrentIteration++;
}
}
/**
* Stop optimization
*/
void
IterateNeighborhoodOptimizer ::StopOptimization()
{
m_Stop = true;
InvokeEvent(EndEvent());
}
/**
* Advance one Step by searching the neighborhood
*/
void
IterateNeighborhoodOptimizer ::AdvanceOneStep()
{
const unsigned int spaceDimension = m_CostFunction->GetNumberOfParameters();
const ParametersType & currentPosition = this->GetCurrentPosition();
ParametersType newPosition(spaceDimension);
double bestValue = m_CurrentValue;
if (!m_FullyConnected)
{
// Iterate face connected values
for (unsigned int j = 0; j < spaceDimension; j += 1)
{
for (int i = -1; i <= 1; i += 2)
{
// Get the neighborhood position
ParametersType neighborPosition(currentPosition);
neighborPosition[j] += i * m_NeighborhoodSize[j];
// Check if this value is better than current
double neighborValue = m_CostFunction->GetValue(neighborPosition);
if (m_Maximize && neighborValue > bestValue)
{
bestValue = neighborValue;
newPosition = neighborPosition;
}
else if (!m_Maximize && neighborValue < bestValue)
{
bestValue = neighborValue;
newPosition = neighborPosition;
}
}
}
}
else
{
// Iterate face+edge+vertex connected values
for (int i = -1; i <= 1; i += 1)
{
for (int j = -1; j <= 1; j += 1)
{
if (spaceDimension == 2)
{
// Get the neighborhood position
ParametersType neighborPosition(currentPosition);
neighborPosition[0] += i * m_NeighborhoodSize[0];
neighborPosition[1] += j * m_NeighborhoodSize[1];
// Check if this value is better than current
double neighborValue = m_CostFunction->GetValue(neighborPosition);
if (m_Maximize && neighborValue > bestValue)
{
bestValue = neighborValue;
newPosition = neighborPosition;
}
else if (!m_Maximize && neighborValue < bestValue)
{
bestValue = neighborValue;
newPosition = neighborPosition;
}
} // end spaceDimension == 2
else if (spaceDimension == 3)
{
for (int k = -1; k <= 1; k += 1)
{
// Get the neighborhood position
ParametersType neighborPosition(currentPosition);
neighborPosition[0] += i * m_NeighborhoodSize[0];
neighborPosition[1] += j * m_NeighborhoodSize[1];
neighborPosition[2] += k * m_NeighborhoodSize[2];
// Check if this value is better than current
double neighborValue = m_CostFunction->GetValue(neighborPosition);
if (m_Maximize && neighborValue > bestValue)
{
bestValue = neighborValue;
newPosition = neighborPosition;
}
else if (!m_Maximize && neighborValue < bestValue)
{
bestValue = neighborValue;
newPosition = neighborPosition;
}
} // end for k
} // end spaceDimension == 3
} // end for j
} // end for i
} // end m_FullyConnected
if (bestValue == m_CurrentValue)
{
// We have found a local maxima/minima
this->StopOptimization();
}
else
{
m_CurrentValue = bestValue;
this->SetCurrentPosition(newPosition);
this->InvokeEvent(IterationEvent());
}
}
} // end namespace itk
|
/*=========================================================================
*
* Copyright NumFOCUS
*
* 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.txt
*
* 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 "itkIterateNeighborhoodOptimizer.h"
#include "itkCommand.h"
#include "itkEventObject.h"
#include "itkMacro.h"
namespace itk
{
/**
* Constructor
*/
IterateNeighborhoodOptimizer ::IterateNeighborhoodOptimizer()
{
m_Stop = false;
m_Maximize = false;
m_FullyConnected = true;
m_CurrentIteration = 0;
m_CurrentValue = 0.0;
}
/**
* PrintSelf
*/
void
IterateNeighborhoodOptimizer ::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "Maximize: " << m_Maximize << std::endl;
os << indent << "FullyConnected: " << m_FullyConnected << std::endl;
os << indent << "CurrentIteration: " << m_CurrentIteration;
os << indent << "CurrentValue: " << m_CurrentValue;
if (m_CostFunction)
{
os << indent << "CostFunction: " << m_CostFunction;
}
}
/**
* Start the optimization
*/
void
IterateNeighborhoodOptimizer ::StartOptimization()
{
m_CurrentIteration = 0;
this->SetCurrentPosition(this->GetInitialPosition());
this->ResumeOptimization();
}
/**
* Resume the optimization
*/
void
IterateNeighborhoodOptimizer ::ResumeOptimization()
{
m_Stop = false;
InvokeEvent(StartEvent());
while (!m_Stop)
{
try
{
m_CurrentValue = m_CostFunction->GetValue(this->GetCurrentPosition());
}
catch (ExceptionObject & err)
{
// An exception has occurred, terminate immediately.
StopOptimization();
// Pass exception to caller
throw err;
}
if (m_Stop)
{
break;
}
AdvanceOneStep();
m_CurrentIteration++;
}
}
/**
* Stop optimization
*/
void
IterateNeighborhoodOptimizer ::StopOptimization()
{
m_Stop = true;
InvokeEvent(EndEvent());
}
/**
* Advance one Step by searching the neighborhood
*/
void
IterateNeighborhoodOptimizer ::AdvanceOneStep()
{
const unsigned int spaceDimension = m_CostFunction->GetNumberOfParameters();
const ParametersType & currentPosition = this->GetCurrentPosition();
ParametersType newPosition(spaceDimension);
double bestValue = m_CurrentValue;
if (!m_FullyConnected)
{
// Iterate face connected values
for (unsigned int j = 0; j < spaceDimension; j += 1)
{
for (int i = -1; i <= 1; i += 2)
{
// Get the neighborhood position
ParametersType neighborPosition(currentPosition);
neighborPosition[j] += i * m_NeighborhoodSize[j];
// Check if this value is better than current
double neighborValue = m_CostFunction->GetValue(neighborPosition);
if (m_Maximize && neighborValue > bestValue)
{
bestValue = neighborValue;
newPosition = neighborPosition;
}
else if (!m_Maximize && neighborValue < bestValue)
{
bestValue = neighborValue;
newPosition = neighborPosition;
}
}
}
}
else
{
// Iterate face+edge+vertex connected values
for (int i = -1; i <= 1; i += 1)
{
for (int j = -1; j <= 1; j += 1)
{
if (spaceDimension == 2)
{
// Get the neighborhood position
ParametersType neighborPosition(currentPosition);
neighborPosition[0] += i * m_NeighborhoodSize[0];
neighborPosition[1] += j * m_NeighborhoodSize[1];
// Check if this value is better than current
double neighborValue = m_CostFunction->GetValue(neighborPosition);
if (m_Maximize && neighborValue > bestValue)
{
bestValue = neighborValue;
newPosition = neighborPosition;
}
else if (!m_Maximize && neighborValue < bestValue)
{
bestValue = neighborValue;
newPosition = neighborPosition;
}
} // end spaceDimension == 2
else if (spaceDimension == 3)
{
for (int k = -1; k <= 1; k += 1)
{
// Get the neighborhood position
ParametersType neighborPosition(currentPosition);
neighborPosition[0] += i * m_NeighborhoodSize[0];
neighborPosition[1] += j * m_NeighborhoodSize[1];
neighborPosition[2] += k * m_NeighborhoodSize[2];
// Check if this value is better than current
double neighborValue = m_CostFunction->GetValue(neighborPosition);
if (m_Maximize && neighborValue > bestValue)
{
bestValue = neighborValue;
newPosition = neighborPosition;
}
else if (!m_Maximize && neighborValue < bestValue)
{
bestValue = neighborValue;
newPosition = neighborPosition;
}
} // end for k
} // end spaceDimension == 3
} // end for j
} // end for i
} // end m_FullyConnected
if (bestValue == m_CurrentValue)
{
// We have found a local maxima/minima
this->StopOptimization();
}
else
{
m_CurrentValue = bestValue;
this->SetCurrentPosition(newPosition);
this->InvokeEvent(IterationEvent());
}
}
} // end namespace itk
|
Update copyright assignment to NumFOCUS
|
DOC: Update copyright assignment to NumFOCUS
The mission of NumFOCUS is to promote open
practices in research, data, and scientific
computing.
https://numfocus.org
|
C++
|
apache-2.0
|
thewtex/ITKMinimalPathExtraction,InsightSoftwareConsortium/ITKMinimalPathExtraction,thewtex/ITKMinimalPathExtraction,InsightSoftwareConsortium/ITKMinimalPathExtraction,InsightSoftwareConsortium/ITKMinimalPathExtraction,thewtex/ITKMinimalPathExtraction
|
badb11b0953de77f93d6c44bff8e6bbef4f22f67
|
ouzel/core/windows/main.cpp
|
ouzel/core/windows/main.cpp
|
// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.
#include <windows.h>
#include "EngineWin.h"
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
std::unique_ptr<ouzel::EngineWin> engine(new ouzel::EngineWin());
int result = engine->run();
engine.release(); // must release engine instance before exit on Windows
return result;
}
|
// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.
#include <windows.h>
#include "EngineWin.h"
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
std::unique_ptr<ouzel::EngineWin> engine(new ouzel::EngineWin());
int result = engine->run();
engine.reset(); // must release engine instance before exit on Windows
return result;
}
|
Fix engine reset
|
Fix engine reset
|
C++
|
unlicense
|
elnormous/ouzel,elvman/ouzel,elvman/ouzel,elnormous/ouzel,elnormous/ouzel
|
4fbba30f3f95d8a219f8e028b9509a238a839f5f
|
Hello-OpenCV/main.cpp
|
Hello-OpenCV/main.cpp
|
//
// main.cpp
// Hello-OpenCV
//
// Created by nsp on 13/2/17.
// Copyright © 2017 nspool. All rights reserved.
//
// Because the opencv framework headers don't play well with clang
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdocumentation"
#include <iostream>
#include "opencv2/opencv.hpp"
//cv::Vec small, fixed vectors
//cv::Matx small, fixed matrices
//cv::Point (x & y) can be cast to Vec but not derived from it. Dot & cross product.
//cv::Size (width & height), area computation
//cv::Rect (x & y & width & height), area, upper-left and bottom-right, intersections
//cv::RotatedRect
//cv::Scalar a four-dimensional point class, element-wise multiplication, quaternion conjection
void createSparse() {
int size[] = {10,10};
cv::SparseMat sm(2,size, CV_32F);
for(int i=0; i<10; i++) {
int idx[2];
idx[0] = size[0] * rand();
idx[1] = size[1] * rand();
sm.ref<float>(idx) += 1.0f;
}
// cv::SparseMatConstIterator_<float> it = sm.begin<float>();
// cv::SparseMatConstIterator_<float> it_end = sm.end<float>();
auto it = sm.begin<float>();
auto it_end = sm.end();
for(;it != it_end; ++it) {
const cv::SparseMat::Node* node = it.node();
printf("(%3d,%3d) %f\n", node->idx[0],node->idx[1], *it);
}
}
void createMat() {
cv::Mat m;
m.create(3, 10, CV_32FC3); // Create data area for 3 rows and 10 columns of 3-channel 32-bit floats
m.setTo(cv::Scalar(1.0f, 0.0f, 1.0f)); // Set the value of 1st and 3rd channels to 1.0, 2nd channel to 0
// Equivalent to:
cv::Mat m2(3,10,CV_32FC3,cv::Scalar(1.0f, 0.0f, 1.0f));
}
void solve() {
}
int main(int argc, const char * argv[]) {
// createSparse();
// Colours
cv::Mat imgBackground = cv::imread("a.jpg");
cv::Mat imgSprite = cv::imread("b.jpg");
// For borders
auto white = cv::Scalar(255,255,255,0);
auto red = cv::Scalar(0,0,255,0);
if(imgBackground.empty() || imgSprite.empty()){
return -1;
}
cv::Mat imgOutput;
cv::transpose(imgSprite, imgOutput);
cv::Mat roi1(imgBackground, cv::Rect(10,10,259,258));
cv::Mat roi2(imgOutput, cv::Rect(0,0,259,258));
cv::addWeighted(roi1, 0.5, roi2, 0.5, 0.0, roi1);
// Put a border around the transposed sprite
cv::rectangle(imgBackground, cv::Point(10,10), cv::Point(269,268), white);
// Draw the title text and place a red border around it
auto titleText = std::string("Title Appears Here");
cv::Point textPoint = cv::Point(300,30);
cv::putText(imgBackground, titleText, textPoint, 0, 1, 0, 2, 4, false);
int textBaseline = 0;
cv::Size textSize = cv::getTextSize(titleText, 0, 1, 2, &textBaseline);
textPoint.y = textPoint.y + textBaseline;
cv::rectangle(imgBackground, textPoint, cv::Point(textPoint.x + textSize.width, textPoint.y - textBaseline - textSize.height - 2), red);
cv::imshow("Example", imgBackground);
cv::waitKey();
cv::destroyWindow("Example");
return 0;
}
|
//
// main.cpp
// Hello-OpenCV
//
// Created by nsp on 13/2/17.
// Copyright © 2017 nspool. All rights reserved.
//
// Because the opencv framework headers don't play well with clang
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdocumentation"
#include <iostream>
#include "opencv2/opencv.hpp"
//cv::Vec small, fixed vectors
//cv::Matx small, fixed matrices
//cv::Point (x & y) can be cast to Vec but not derived from it. Dot & cross product.
//cv::Size (width & height), area computation
//cv::Rect (x & y & width & height), area, upper-left and bottom-right, intersections
//cv::RotatedRect
//cv::Scalar a four-dimensional point class, element-wise multiplication, quaternion conjection
void createSparse() {
int size[] = {10,10};
cv::SparseMat sm(2,size, CV_32F);
for(int i=0; i<10; i++) {
int idx[2];
idx[0] = size[0] * rand();
idx[1] = size[1] * rand();
sm.ref<float>(idx) += 1.0f;
}
// cv::SparseMatConstIterator_<float> it = sm.begin<float>();
// cv::SparseMatConstIterator_<float> it_end = sm.end<float>();
auto it = sm.begin<float>();
auto it_end = sm.end();
for(;it != it_end; ++it) {
const cv::SparseMat::Node* node = it.node();
printf("(%3d,%3d) %f\n", node->idx[0],node->idx[1], *it);
}
}
void createMat() {
cv::Mat m;
m.create(3, 10, CV_32FC3); // Create data area for 3 rows and 10 columns of 3-channel 32-bit floats
m.setTo(cv::Scalar(1.0f, 0.0f, 1.0f)); // Set the value of 1st and 3rd channels to 1.0, 2nd channel to 0
// Equivalent to:
cv::Mat m2(3,10,CV_32FC3,cv::Scalar(1.0f, 0.0f, 1.0f));
}
void solve() {
}
int main(int argc, const char * argv[]) {
// createSparse();
auto titleText = std::string("Hello, OpenCV");
// Colours
cv::Mat imgBackground = cv::imread("a.jpg");
cv::Mat imgSprite = cv::imread("b.jpg");
if(imgBackground.empty() || imgSprite.empty()){
std::cerr << "Cannot load images. Aborting." << std::endl;
return -1;
}
// For borders
auto white = cv::Scalar(255,255,255,0);
auto red = cv::Scalar(0,0,255,0);
cv::Mat imgOutput;
cv::transpose(imgSprite, imgOutput);
cv::Mat roi1(imgBackground, cv::Rect(10,10,259,258));
cv::Mat roi2(imgOutput, cv::Rect(0,0,259,258));
// Blend the sprite onto the background image
cv::addWeighted(roi1, 0.5, roi2, 0.5, 0.0, roi1);
// Put a border around the transposed sprite
cv::rectangle(imgBackground, cv::Point(10,10), cv::Point(269,268), white);
// Draw the title text and place a red border around it
cv::Point textPoint = cv::Point(300,30);
cv::putText(imgBackground, titleText, textPoint, 0, 1, 0, 2, 4, false);
int textBaseline = 0;
cv::Size textSize = cv::getTextSize(titleText, 0, 1, 2, &textBaseline);
textPoint.y = textPoint.y + textBaseline;
cv::rectangle(imgBackground, textPoint, cv::Point(textPoint.x + textSize.width, textPoint.y - textBaseline - textSize.height - 2), red);
// Display the window and draw the image
if(cv::startWindowThread() != 0) {
std::cerr << "Cannot start window thread. Continuing.." << std::endl;
}
cv::imshow(titleText, imgBackground);
cv::waitKey();
cv::destroyAllWindows();
return 0;
}
|
Fix UI init and add error handling.
|
Fix UI init and add error handling.
|
C++
|
mit
|
nspool/hello-opencv
|
c558002b767c628468394721ee499cc0979e6db9
|
src/leapserial/SchemaWriterProtobuf.cpp
|
src/leapserial/SchemaWriterProtobuf.cpp
|
// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "SchemaWriterProtobuf.h"
#include "Descriptor.h"
#include "ProtobufUtil.hpp"
#include <iomanip>
#include <sstream>
using namespace leap;
SchemaWriterProtobuf::SchemaWriterProtobuf(const descriptor& desc, protobuf::Version version) :
Desc(desc),
Version(version)
{}
struct SchemaWriterProtobuf::indent {
indent(size_t level) : level(level) {}
const size_t level;
friend std::ostream& operator<<(std::ostream& os, const indent& rhs) {
for (size_t i = rhs.level; i--;)
os << " ";
return os;
}
};
struct SchemaWriterProtobuf::name {
name(const descriptor& desc) : desc(desc) {}
const descriptor& desc;
friend std::ostream& operator<<(std::ostream& os, const name& rhs) {
if (rhs.desc.name)
os << rhs.desc.name;
else
// Need to derive a locally valid name
os << "msg_" << std::hex << std::setfill('0') << std::setw(8) << reinterpret_cast<uint32_t>(&rhs.desc);
return os;
}
};
struct SchemaWriterProtobuf::type {
type(SchemaWriterProtobuf& parent, const field_serializer& ser, bool print_req = true) :
parent(parent),
ser(ser),
print_req(print_req)
{}
SchemaWriterProtobuf& parent;
const field_serializer& ser;
bool print_req = true;
const char* signifier(void) const {
return
!print_req ?
"" :
ser.is_optional() ?
"optional " :
"required ";
}
std::ostream& print(std::ostream& os) const {
switch (auto atom = ser.type()) {
case serial_atom::array:
// "repeated" field, entry type knows more
return os << "repeated " << type{ parent, dynamic_cast<const field_serializer_array&>(ser).element(), false };
case serial_atom::map:
{
const auto& ser_map = dynamic_cast<const field_serializer_map&>(ser);
switch(parent.Version) {
case protobuf::Version::Proto1:
{
parent.synthetic.emplace_back(nullptr);
std::unique_ptr<leap::descriptor>& pDesc = parent.synthetic.back();
std::string* pSyntheticName;
{
std::stringstream ss;
ss << "MapEntry_" << std::hex << std::setw(8) << std::setfill('0') << reinterpret_cast<uint32_t>(&pDesc);
parent.syntheticNames.emplace_back(ss.str());
pSyntheticName = &parent.syntheticNames.back();
}
pDesc = std::unique_ptr<leap::descriptor> {
new leap::descriptor{
pSyntheticName->c_str(),
{
leap::field_descriptor { ser_map.key(), "key", 1, ~0UL },
leap::field_descriptor { ser_map.mapped(), "value", 2, ~0UL }
}
}
};
parent.awaiting.push_back(pDesc.get());
os << "repeated " << *pSyntheticName;
}
break;
case protobuf::Version::Proto2:
case protobuf::Version::Proto3:
return os
<< signifier()
<< "map<"
<< type{ parent, ser_map.key() }
<< ','
<< type{ parent, ser_map.mapped() }
<< '>';
}
}
break;
case serial_atom::descriptor:
case serial_atom::finalized_descriptor:
// Need to generate a reference to this type by name:
{
const auto& f_ser_obj = dynamic_cast<const field_serializer_object&>(ser);
const auto& ser_obj = f_ser_obj.object();
parent.awaiting.push_back(&ser_obj);
return os << signifier() << name{ ser_obj };
}
default:
// Type is fundamental
return os
<< signifier()
<< leap::internal::protobuf::ToProtobufField(atom);
}
return os;
}
friend std::ostream& operator<<(std::ostream& os, const type& rhs) { return rhs.print(os); }
};
void SchemaWriterProtobuf::Write(IOutputStream& os) {
std::stringstream ss;
Write(ss);
auto str = ss.str();
os.Write(str.data(), str.size());
}
void SchemaWriterProtobuf::Write(std::ostream& os) {
awaiting.push_back(&Desc);
encountered.clear();
synthetic.clear();
syntheticNames.clear();
while (!awaiting.empty()) {
const descriptor& cur = *awaiting.back();
awaiting.pop_back();
if (encountered.count(&cur))
continue;
encountered.insert(&cur);
os << "message " << name(cur) << " {" << std::endl;
for (auto& e : cur.identified_descriptors) {
os << indent(tabLevel + 1) << type(*this, e.second.serializer);
os << ' ';
if (e.second.name)
os << e.second.name;
else
os << "field_" << std::dec << e.first;
os << " = " << e.first << ";" << std::endl;
}
os << '}' << std::endl << std::endl;
}
}
|
// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "SchemaWriterProtobuf.h"
#include "Descriptor.h"
#include "ProtobufUtil.hpp"
#include <iomanip>
#include <sstream>
using namespace leap;
SchemaWriterProtobuf::SchemaWriterProtobuf(const descriptor& desc, protobuf::Version version) :
Desc(desc),
Version(version)
{}
struct SchemaWriterProtobuf::indent {
indent(size_t level) : level(level) {}
const size_t level;
friend std::ostream& operator<<(std::ostream& os, const indent& rhs) {
for (size_t i = rhs.level; i--;)
os << " ";
return os;
}
};
struct SchemaWriterProtobuf::name {
name(const descriptor& desc) : desc(desc) {}
const descriptor& desc;
friend std::ostream& operator<<(std::ostream& os, const name& rhs) {
if (rhs.desc.name)
os << rhs.desc.name;
else
// Need to derive a locally valid name
os << "msg_" << std::hex << std::setfill('0') << std::setw(8) << static_cast<uint32_t>(reinterpret_cast<size_t>(&rhs.desc));
return os;
}
};
struct SchemaWriterProtobuf::type {
type(SchemaWriterProtobuf& parent, const field_serializer& ser, bool print_req = true) :
parent(parent),
ser(ser),
print_req(print_req)
{}
SchemaWriterProtobuf& parent;
const field_serializer& ser;
bool print_req = true;
const char* signifier(void) const {
return
!print_req ?
"" :
ser.is_optional() ?
"optional " :
"required ";
}
std::ostream& print(std::ostream& os) const {
switch (auto atom = ser.type()) {
case serial_atom::array:
// "repeated" field, entry type knows more
return os << "repeated " << type{ parent, dynamic_cast<const field_serializer_array&>(ser).element(), false };
case serial_atom::map:
{
const auto& ser_map = dynamic_cast<const field_serializer_map&>(ser);
switch(parent.Version) {
case protobuf::Version::Proto1:
{
parent.synthetic.emplace_back(nullptr);
std::unique_ptr<leap::descriptor>& pDesc = parent.synthetic.back();
std::string* pSyntheticName;
{
std::stringstream ss;
ss << "MapEntry_" << std::hex << std::setw(8) << std::setfill('0') << static_cast<uint32_t>(reinterpret_cast<size_t>(&pDesc));
parent.syntheticNames.emplace_back(ss.str());
pSyntheticName = &parent.syntheticNames.back();
}
pDesc = std::unique_ptr<leap::descriptor> {
new leap::descriptor{
pSyntheticName->c_str(),
{
leap::field_descriptor { ser_map.key(), "key", 1, ~0UL },
leap::field_descriptor { ser_map.mapped(), "value", 2, ~0UL }
}
}
};
parent.awaiting.push_back(pDesc.get());
os << "repeated " << *pSyntheticName;
}
break;
case protobuf::Version::Proto2:
case protobuf::Version::Proto3:
return os
<< signifier()
<< "map<"
<< type{ parent, ser_map.key() }
<< ','
<< type{ parent, ser_map.mapped() }
<< '>';
}
}
break;
case serial_atom::descriptor:
case serial_atom::finalized_descriptor:
// Need to generate a reference to this type by name:
{
const auto& f_ser_obj = dynamic_cast<const field_serializer_object&>(ser);
const auto& ser_obj = f_ser_obj.object();
parent.awaiting.push_back(&ser_obj);
return os << signifier() << name{ ser_obj };
}
default:
// Type is fundamental
return os
<< signifier()
<< leap::internal::protobuf::ToProtobufField(atom);
}
return os;
}
friend std::ostream& operator<<(std::ostream& os, const type& rhs) { return rhs.print(os); }
};
void SchemaWriterProtobuf::Write(IOutputStream& os) {
std::stringstream ss;
Write(ss);
auto str = ss.str();
os.Write(str.data(), str.size());
}
void SchemaWriterProtobuf::Write(std::ostream& os) {
awaiting.push_back(&Desc);
encountered.clear();
synthetic.clear();
syntheticNames.clear();
while (!awaiting.empty()) {
const descriptor& cur = *awaiting.back();
awaiting.pop_back();
if (encountered.count(&cur))
continue;
encountered.insert(&cur);
os << "message " << name(cur) << " {" << std::endl;
for (auto& e : cur.identified_descriptors) {
os << indent(tabLevel + 1) << type(*this, e.second.serializer);
os << ' ';
if (e.second.name)
os << e.second.name;
else
os << "field_" << std::dec << e.first;
os << " = " << e.first << ";" << std::endl;
}
os << '}' << std::endl << std::endl;
}
}
|
Fix casting error
|
Fix casting error
|
C++
|
apache-2.0
|
leapmotion/leapserial,leapmotion/leapserial,codemercenary/leapserial,leapmotion/leapserial,codemercenary/leapserial,codemercenary/leapserial
|
d23d69950d9bd7e9b854dc58f354af3dc61b0ded
|
src/cc/b_frontend_action.cc
|
src/cc/b_frontend_action.cc
|
#include <linux/bpf.h>
#include <clang/AST/ASTConsumer.h>
#include <clang/AST/ASTContext.h>
#include <clang/AST/RecordLayout.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Rewrite/Core/Rewriter.h>
#include "b_frontend_action.h"
extern "C"
int bpf_create_map(enum bpf_map_type map_type, int key_size, int value_size,
int max_entries);
namespace ebpf {
using std::map;
using std::string;
using std::to_string;
using std::unique_ptr;
using namespace clang;
BTypeVisitor::BTypeVisitor(ASTContext &C, Rewriter &rewriter, map<string, BPFTable> &tables)
: C(C), rewriter_(rewriter), out_(llvm::errs()), tables_(tables) {
}
bool BTypeVisitor::VisitFunctionDecl(FunctionDecl *D) {
return true;
}
// convert calls of the type:
// table.foo(&key)
// to:
// bpf_table_foo_elem(bpf_pseudo_fd(table), &key [,&leaf])
bool BTypeVisitor::VisitCallExpr(CallExpr *Call) {
// make sure node is a reference to a bpf table, which is assured by the
// presence of the section("maps/<typename>") GNU __attribute__
if (MemberExpr *Memb = dyn_cast<MemberExpr>(Call->getCallee()->IgnoreImplicit())) {
StringRef memb_name = Memb->getMemberDecl()->getName();
if (DeclRefExpr *Ref = dyn_cast<DeclRefExpr>(Memb->getBase())) {
if (SectionAttr *A = Ref->getDecl()->getAttr<SectionAttr>()) {
if (!A->getName().startswith("maps"))
return true;
SourceRange argRange(Call->getArg(0)->getLocStart(),
Call->getArg(Call->getNumArgs()-1)->getLocEnd());
string args = rewriter_.getRewrittenText(argRange);
// find the table fd, which was opened at declaration time
auto table_it = tables_.find(Ref->getDecl()->getName());
if (table_it == tables_.end()) {
C.getDiagnostics().Report(Ref->getLocEnd(), diag::err_expected)
<< "initialized handle for bpf_table";
return false;
}
string fd = to_string(table_it->second.fd);
string prefix, suffix;
string map_update_policy = "BPF_ANY";
string txt;
if (memb_name == "lookup_or_init") {
string map_update_policy = "BPF_NOEXIST";
string name = Ref->getDecl()->getName();
string arg0 = rewriter_.getRewrittenText(SourceRange(Call->getArg(0)->getLocStart(),
Call->getArg(0)->getLocEnd()));
string arg1 = rewriter_.getRewrittenText(SourceRange(Call->getArg(1)->getLocStart(),
Call->getArg(1)->getLocEnd()));
string lookup = "bpf_map_lookup_elem_(bpf_pseudo_fd(1, " + fd + ")";
string update = "bpf_map_update_elem_(bpf_pseudo_fd(1, " + fd + ")";
txt = "({typeof(" + name + ".leaf) *leaf = " + lookup + ", " + arg0 + "); ";
txt += "if (!leaf) {";
txt += " " + update + ", " + arg0 + ", " + arg1 + ", " + map_update_policy + ");";
txt += " leaf = " + lookup + ", " + arg0 + ");";
txt += " if (!leaf) return -1;";
txt += "}";
txt += "leaf;})";
} else {
if (memb_name == "lookup") {
prefix = "bpf_map_lookup_elem";
suffix = ")";
} else if (memb_name == "update") {
prefix = "bpf_map_update_elem";
suffix = ", " + map_update_policy + ")";
} else if (memb_name == "delete") {
prefix = "bpf_map_delete_elem";
suffix = ")";
} else if (memb_name == "call") {
prefix = "bpf_tail_call_";
suffix = ")";
} else {
llvm::errs() << "error: unknown bpf_table operation " << memb_name << "\n";
return false;
}
prefix += "((void *)bpf_pseudo_fd(1, " + fd + "), ";
txt = prefix + args + suffix;
}
rewriter_.ReplaceText(SourceRange(Call->getLocStart(), Call->getLocEnd()), txt);
return true;
}
}
}
return true;
}
// look for table subscript references, and turn them into auto table entries:
// table.data[key]
// becomes:
// struct Key key = {123};
// struct Leaf *leaf = table.get(&key);
// if (!leaf) {
// struct Leaf zleaf = {0};
// table.put(&key, &zleaf, BPF_NOEXIST);
// leaf = table.get(&key);
// if (!leaf) return -1;
// }
bool BTypeVisitor::VisitArraySubscriptExpr(ArraySubscriptExpr *Arr) {
Expr *LHS = Arr->getLHS()->IgnoreImplicit();
Expr *RHS = Arr->getRHS()->IgnoreImplicit();
if (MemberExpr *Memb = dyn_cast<MemberExpr>(LHS)) {
if (DeclRefExpr *Ref = dyn_cast<DeclRefExpr>(Memb->getBase())) {
if (SectionAttr *A = Ref->getDecl()->getAttr<SectionAttr>()) {
if (A->getName().startswith("maps")) {
auto table_it = tables_.find(Ref->getDecl()->getName());
if (table_it == tables_.end()) {
C.getDiagnostics().Report(Ref->getLocEnd(), diag::err_expected)
<< "initialized handle for bpf_table";
return false;
}
string fd = to_string(table_it->second.fd);
string map_update_policy = "BPF_NOEXIST";
string name = Ref->getDecl()->getName();
SourceRange argRange(RHS->getLocStart(), RHS->getLocEnd());
string args = rewriter_.getRewrittenText(argRange);
string lookup = "bpf_map_lookup_elem_(bpf_pseudo_fd(1, " + fd + ")";
string update = "bpf_map_update_elem_(bpf_pseudo_fd(1, " + fd + ")";
string txt = "(*({typeof(" + name + ".leaf) *leaf = " + lookup + ", " + args + "); ";
txt += "if (!leaf) {";
txt += " typeof(" + name + ".leaf) zleaf = {0};";
txt += " " + update + ", " + args + ", &zleaf, " + map_update_policy + ");";
txt += " leaf = " + lookup + ", " + args + ");";
txt += " if (!leaf) return -1;";
txt += "}";
txt += "leaf;}))";
rewriter_.ReplaceText(SourceRange(Arr->getLocStart(), Arr->getLocEnd()), txt);
}
}
}
}
return true;
}
bool BTypeVisitor::VisitMemberExpr(MemberExpr *E) {
Expr *Base = E->getBase()->IgnoreImplicit();
if (DeclRefExpr *Ref = dyn_cast<DeclRefExpr>(Base)) {
if (DeprecatedAttr *A = Ref->getDecl()->getAttr<DeprecatedAttr>()) {
if (A->getMessage() == "packet") {
if (FieldDecl *F = dyn_cast<FieldDecl>(E->getMemberDecl())) {
uint64_t ofs = C.getFieldOffset(F);
uint64_t sz = F->isBitField() ? F->getBitWidthValue(C) : C.getTypeSize(F->getType());
string base = rewriter_.getRewrittenText(SourceRange(Base->getLocStart(), Base->getLocEnd()));
string text = "bpf_dext_pkt(skb, (u64)" + base + "+" + to_string(ofs >> 3)
+ ", " + to_string(ofs & 0x7) + ", " + to_string(sz) + ")";
rewriter_.ReplaceText(SourceRange(E->getLocStart(), E->getLocEnd()), text);
}
}
}
}
return true;
}
// Open table FDs when bpf tables (as denoted by section("maps*") attribute)
// are declared.
bool BTypeVisitor::VisitVarDecl(VarDecl *Decl) {
const RecordType *R = Decl->getType()->getAs<RecordType>();
if (SectionAttr *A = Decl->getAttr<SectionAttr>()) {
if (!A->getName().startswith("maps"))
return true;
if (!R) {
C.getDiagnostics().Report(Decl->getLocEnd(), diag::err_expected)
<< "struct type for bpf_table";
return false;
}
const RecordDecl *RD = R->getDecl()->getDefinition();
BPFTable table;
unsigned i = 0;
for (auto F : RD->fields()) {
size_t sz = C.getTypeSize(F->getType()) >> 3;
if (F->getName() == "key") {
table.key_size = sz;
} else if (F->getName() == "leaf") {
table.leaf_size = sz;
} else if (F->getName() == "data") {
table.max_entries = sz / table.leaf_size;
}
++i;
}
bpf_map_type map_type = BPF_MAP_TYPE_UNSPEC;
if (A->getName() == "maps/hash")
map_type = BPF_MAP_TYPE_HASH;
else if (A->getName() == "maps/array")
map_type = BPF_MAP_TYPE_ARRAY;
else if (A->getName() == "maps/prog")
map_type = BPF_MAP_TYPE_PROG_ARRAY;
table.fd = bpf_create_map(map_type, table.key_size, table.leaf_size, table.max_entries);
if (table.fd < 0) {
llvm::errs() << "error: could not open bpf fd\n";
return false;
}
tables_[Decl->getName()] = table;
}
return true;
}
BTypeConsumer::BTypeConsumer(ASTContext &C, Rewriter &rewriter, map<string, BPFTable> &tables)
: visitor_(C, rewriter, tables) {
}
bool BTypeConsumer::HandleTopLevelDecl(DeclGroupRef D) {
for (auto it : D)
visitor_.TraverseDecl(it);
return true;
}
BFrontendAction::BFrontendAction(llvm::raw_ostream &os)
: rewriter_(new Rewriter), os_(os), tables_(new map<string, BPFTable>) {
}
void BFrontendAction::EndSourceFileAction() {
// uncomment to see rewritten source
//rewriter_->getEditBuffer(rewriter_->getSourceMgr().getMainFileID()).write(llvm::errs());
rewriter_->getEditBuffer(rewriter_->getSourceMgr().getMainFileID()).write(os_);
os_.flush();
}
unique_ptr<ASTConsumer> BFrontendAction::CreateASTConsumer(CompilerInstance &Compiler, llvm::StringRef InFile) {
rewriter_->setSourceMgr(Compiler.getSourceManager(), Compiler.getLangOpts());
return unique_ptr<ASTConsumer>(new BTypeConsumer(Compiler.getASTContext(), *rewriter_, *tables_));
}
}
|
#include <linux/bpf.h>
#include <clang/AST/ASTConsumer.h>
#include <clang/AST/ASTContext.h>
#include <clang/AST/RecordLayout.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Rewrite/Core/Rewriter.h>
#include "b_frontend_action.h"
extern "C"
int bpf_create_map(enum bpf_map_type map_type, int key_size, int value_size,
int max_entries);
namespace ebpf {
using std::map;
using std::string;
using std::to_string;
using std::unique_ptr;
using namespace clang;
BTypeVisitor::BTypeVisitor(ASTContext &C, Rewriter &rewriter, map<string, BPFTable> &tables)
: C(C), rewriter_(rewriter), out_(llvm::errs()), tables_(tables) {
}
bool BTypeVisitor::VisitFunctionDecl(FunctionDecl *D) {
return true;
}
// convert calls of the type:
// table.foo(&key)
// to:
// bpf_table_foo_elem(bpf_pseudo_fd(table), &key [,&leaf])
bool BTypeVisitor::VisitCallExpr(CallExpr *Call) {
// make sure node is a reference to a bpf table, which is assured by the
// presence of the section("maps/<typename>") GNU __attribute__
if (MemberExpr *Memb = dyn_cast<MemberExpr>(Call->getCallee()->IgnoreImplicit())) {
StringRef memb_name = Memb->getMemberDecl()->getName();
if (DeclRefExpr *Ref = dyn_cast<DeclRefExpr>(Memb->getBase())) {
if (SectionAttr *A = Ref->getDecl()->getAttr<SectionAttr>()) {
if (!A->getName().startswith("maps"))
return true;
SourceRange argRange(Call->getArg(0)->getLocStart(),
Call->getArg(Call->getNumArgs()-1)->getLocEnd());
string args = rewriter_.getRewrittenText(argRange);
// find the table fd, which was opened at declaration time
auto table_it = tables_.find(Ref->getDecl()->getName());
if (table_it == tables_.end()) {
C.getDiagnostics().Report(Ref->getLocEnd(), diag::err_expected)
<< "initialized handle for bpf_table";
return false;
}
string fd = to_string(table_it->second.fd);
string prefix, suffix;
string map_update_policy = "BPF_ANY";
string txt;
if (memb_name == "lookup_or_init") {
string map_update_policy = "BPF_NOEXIST";
string name = Ref->getDecl()->getName();
string arg0 = rewriter_.getRewrittenText(SourceRange(Call->getArg(0)->getLocStart(),
Call->getArg(0)->getLocEnd()));
string arg1 = rewriter_.getRewrittenText(SourceRange(Call->getArg(1)->getLocStart(),
Call->getArg(1)->getLocEnd()));
string lookup = "bpf_map_lookup_elem_(bpf_pseudo_fd(1, " + fd + ")";
string update = "bpf_map_update_elem_(bpf_pseudo_fd(1, " + fd + ")";
txt = "({typeof(" + name + ".leaf) *leaf = " + lookup + ", " + arg0 + "); ";
txt += "if (!leaf) {";
txt += " " + update + ", " + arg0 + ", " + arg1 + ", " + map_update_policy + ");";
txt += " leaf = " + lookup + ", " + arg0 + ");";
txt += " if (!leaf) return 0;";
txt += "}";
txt += "leaf;})";
} else {
if (memb_name == "lookup") {
prefix = "bpf_map_lookup_elem";
suffix = ")";
} else if (memb_name == "update") {
prefix = "bpf_map_update_elem";
suffix = ", " + map_update_policy + ")";
} else if (memb_name == "delete") {
prefix = "bpf_map_delete_elem";
suffix = ")";
} else if (memb_name == "call") {
prefix = "bpf_tail_call_";
suffix = ")";
} else {
llvm::errs() << "error: unknown bpf_table operation " << memb_name << "\n";
return false;
}
prefix += "((void *)bpf_pseudo_fd(1, " + fd + "), ";
txt = prefix + args + suffix;
}
rewriter_.ReplaceText(SourceRange(Call->getLocStart(), Call->getLocEnd()), txt);
return true;
}
}
}
return true;
}
// look for table subscript references, and turn them into auto table entries:
// table.data[key]
// becomes:
// struct Key key = {123};
// struct Leaf *leaf = table.get(&key);
// if (!leaf) {
// struct Leaf zleaf = {0};
// table.put(&key, &zleaf, BPF_NOEXIST);
// leaf = table.get(&key);
// if (!leaf) return -1;
// }
bool BTypeVisitor::VisitArraySubscriptExpr(ArraySubscriptExpr *Arr) {
Expr *LHS = Arr->getLHS()->IgnoreImplicit();
Expr *RHS = Arr->getRHS()->IgnoreImplicit();
if (MemberExpr *Memb = dyn_cast<MemberExpr>(LHS)) {
if (DeclRefExpr *Ref = dyn_cast<DeclRefExpr>(Memb->getBase())) {
if (SectionAttr *A = Ref->getDecl()->getAttr<SectionAttr>()) {
if (A->getName().startswith("maps")) {
auto table_it = tables_.find(Ref->getDecl()->getName());
if (table_it == tables_.end()) {
C.getDiagnostics().Report(Ref->getLocEnd(), diag::err_expected)
<< "initialized handle for bpf_table";
return false;
}
string fd = to_string(table_it->second.fd);
string map_update_policy = "BPF_NOEXIST";
string name = Ref->getDecl()->getName();
SourceRange argRange(RHS->getLocStart(), RHS->getLocEnd());
string args = rewriter_.getRewrittenText(argRange);
string lookup = "bpf_map_lookup_elem_(bpf_pseudo_fd(1, " + fd + ")";
string update = "bpf_map_update_elem_(bpf_pseudo_fd(1, " + fd + ")";
string txt = "(*({typeof(" + name + ".leaf) *leaf = " + lookup + ", " + args + "); ";
txt += "if (!leaf) {";
txt += " typeof(" + name + ".leaf) zleaf = {0};";
txt += " " + update + ", " + args + ", &zleaf, " + map_update_policy + ");";
txt += " leaf = " + lookup + ", " + args + ");";
txt += " if (!leaf) return 0;";
txt += "}";
txt += "leaf;}))";
rewriter_.ReplaceText(SourceRange(Arr->getLocStart(), Arr->getLocEnd()), txt);
}
}
}
}
return true;
}
bool BTypeVisitor::VisitMemberExpr(MemberExpr *E) {
Expr *Base = E->getBase()->IgnoreImplicit();
if (DeclRefExpr *Ref = dyn_cast<DeclRefExpr>(Base)) {
if (DeprecatedAttr *A = Ref->getDecl()->getAttr<DeprecatedAttr>()) {
if (A->getMessage() == "packet") {
if (FieldDecl *F = dyn_cast<FieldDecl>(E->getMemberDecl())) {
uint64_t ofs = C.getFieldOffset(F);
uint64_t sz = F->isBitField() ? F->getBitWidthValue(C) : C.getTypeSize(F->getType());
string base = rewriter_.getRewrittenText(SourceRange(Base->getLocStart(), Base->getLocEnd()));
string text = "bpf_dext_pkt(skb, (u64)" + base + "+" + to_string(ofs >> 3)
+ ", " + to_string(ofs & 0x7) + ", " + to_string(sz) + ")";
rewriter_.ReplaceText(SourceRange(E->getLocStart(), E->getLocEnd()), text);
}
}
}
}
return true;
}
// Open table FDs when bpf tables (as denoted by section("maps*") attribute)
// are declared.
bool BTypeVisitor::VisitVarDecl(VarDecl *Decl) {
const RecordType *R = Decl->getType()->getAs<RecordType>();
if (SectionAttr *A = Decl->getAttr<SectionAttr>()) {
if (!A->getName().startswith("maps"))
return true;
if (!R) {
C.getDiagnostics().Report(Decl->getLocEnd(), diag::err_expected)
<< "struct type for bpf_table";
return false;
}
const RecordDecl *RD = R->getDecl()->getDefinition();
BPFTable table;
unsigned i = 0;
for (auto F : RD->fields()) {
size_t sz = C.getTypeSize(F->getType()) >> 3;
if (F->getName() == "key") {
table.key_size = sz;
} else if (F->getName() == "leaf") {
table.leaf_size = sz;
} else if (F->getName() == "data") {
table.max_entries = sz / table.leaf_size;
}
++i;
}
bpf_map_type map_type = BPF_MAP_TYPE_UNSPEC;
if (A->getName() == "maps/hash")
map_type = BPF_MAP_TYPE_HASH;
else if (A->getName() == "maps/array")
map_type = BPF_MAP_TYPE_ARRAY;
else if (A->getName() == "maps/prog")
map_type = BPF_MAP_TYPE_PROG_ARRAY;
table.fd = bpf_create_map(map_type, table.key_size, table.leaf_size, table.max_entries);
if (table.fd < 0) {
llvm::errs() << "error: could not open bpf fd\n";
return false;
}
tables_[Decl->getName()] = table;
}
return true;
}
BTypeConsumer::BTypeConsumer(ASTContext &C, Rewriter &rewriter, map<string, BPFTable> &tables)
: visitor_(C, rewriter, tables) {
}
bool BTypeConsumer::HandleTopLevelDecl(DeclGroupRef D) {
for (auto it : D)
visitor_.TraverseDecl(it);
return true;
}
BFrontendAction::BFrontendAction(llvm::raw_ostream &os)
: rewriter_(new Rewriter), os_(os), tables_(new map<string, BPFTable>) {
}
void BFrontendAction::EndSourceFileAction() {
// uncomment to see rewritten source
//rewriter_->getEditBuffer(rewriter_->getSourceMgr().getMainFileID()).write(llvm::errs());
rewriter_->getEditBuffer(rewriter_->getSourceMgr().getMainFileID()).write(os_);
os_.flush();
}
unique_ptr<ASTConsumer> BFrontendAction::CreateASTConsumer(CompilerInstance &Compiler, llvm::StringRef InFile) {
rewriter_->setSourceMgr(Compiler.getSourceManager(), Compiler.getLangOpts());
return unique_ptr<ASTConsumer>(new BTypeConsumer(Compiler.getASTContext(), *rewriter_, *tables_));
}
}
|
Return 0 in lookup_or_init error path
|
Return 0 in lookup_or_init error path
Signed-off-by: Brenden Blanco <[email protected]>
|
C++
|
apache-2.0
|
mbudiu-bfn/bcc,mkacik/bcc,romain-intel/bcc,mbudiu-bfn/bcc,mshahbaz/bcc-deprecated,shodoco/bcc,mcaleavya/bcc,mshahbaz/bcc-deprecated,mbudiu-bfn/bcc,arslanabbasi/bcc,hgn/bcc,shodoco/bcc,zaafar/bcc,tuxology/bcc,mcaleavya/bcc,romain-intel/bcc,mbudiu-bfn/bcc,zaafar/bcc,mcaleavya/bcc,shodoco/bcc,iovisor/bcc,romain-intel/bcc,brendangregg/bcc,hgn/bcc,mbudiu-bfn/bcc,arslanabbasi/bcc,iovisor/bcc,mkacik/bcc,mshahbaz/bcc-deprecated,mkacik/bcc,tuxology/bcc,hgn/bcc,mcaleavya/bcc,iovisor/bcc,arslanabbasi/bcc,hgn/bcc,bpowers/bcc,arslanabbasi/bcc,bpowers/bcc,hgn/bcc,iovisor/bcc,mshahbaz/bcc-deprecated,mkacik/bcc,tuxology/bcc,mcaleavya/bcc,zaafar/bcc,brendangregg/bcc,romain-intel/bcc,bpowers/bcc,shodoco/bcc,zaafar/bcc,brendangregg/bcc,brendangregg/bcc,bpowers/bcc,zaafar/bcc,shodoco/bcc,iovisor/bcc,tuxology/bcc,brendangregg/bcc,mkacik/bcc,tuxology/bcc,mshahbaz/bcc-deprecated,arslanabbasi/bcc,bpowers/bcc,romain-intel/bcc
|
298c2902003245ce061a6c0f5c94a9d16e638969
|
src/cellitems/pawnpiece.cpp
|
src/cellitems/pawnpiece.cpp
|
#include "pawnpiece.h"
#include "../utils.h"
PawnPiece::PawnPiece(PieceColor color, int cellIndex)
: ChessPiece(ChessPieceType::Pawn, color, cellIndex)
, m_firstStep(true)
{
}
PawnPiece::~PawnPiece()
{
}
QString PawnPiece::imageName() const
{
return QStringLiteral("pawn_") + ChessPiece::colorName(color());
}
bool PawnPiece::isMovePossible(int newCell) const
{
const int newX = ChessPiece::positionX(newCell);
const int newY = ChessPiece::positionY(newCell);
const int allowStep = m_firstStep ? 2 : 1;
if(newX != positionX())
return false;
if(Utils::abs(positionY()- newY) > allowStep)
return false;
return true;
}
bool PawnPiece::isAtackPossible(int newCell) const
{
const int newX = ChessPiece::positionX(newCell);
const int newY = ChessPiece::positionY(newCell);
if(newX == positionX())
return false;
if(Utils::abs(positionY()- newY) > 1 || Utils::abs(positionX()- newX) > 1)
return false;
return true;
}
void PawnPiece::move(int newCellIndex)
{
ChessPiece::move(newCellIndex);
m_firstStep = false;
}
bool PawnPiece::canJumpOver() const
{
return false;
}
|
#include "pawnpiece.h"
#include "../utils.h"
PawnPiece::PawnPiece(PieceColor color, int cellIndex)
: ChessPiece(ChessPieceType::Pawn, color, cellIndex)
, m_firstStep(true)
{
}
PawnPiece::~PawnPiece()
{
}
QString PawnPiece::imageName() const
{
return QStringLiteral("pawn_") + ChessPiece::colorName(color());
}
bool PawnPiece::isMovePossible(int newCell) const
{
const int newX = ChessPiece::positionX(newCell);
const int newY = ChessPiece::positionY(newCell);
const int allowStep = m_firstStep ? 2 : 1;
const int delta = positionY()- newY;
if(newX != positionX())
return false;
if(Utils::abs(delta) > allowStep)
return false;
if(color() == PieceColor::Black && delta > 0)
return false;
if(color() == PieceColor::White && delta < 0)
return false;
return true;
}
bool PawnPiece::isAtackPossible(int newCell) const
{
const int newX = ChessPiece::positionX(newCell);
const int newY = ChessPiece::positionY(newCell);
const int delta = positionY()- newY;
if(newX == positionX())
return false;
if(Utils::abs(delta) > 1 || Utils::abs(positionX()- newX) > 1)
return false;
if(color() == PieceColor::Black && delta > 0)
return false;
if(color() == PieceColor::White && delta < 0)
return false;
return true;
}
void PawnPiece::move(int newCellIndex)
{
ChessPiece::move(newCellIndex);
m_firstStep = false;
}
bool PawnPiece::canJumpOver() const
{
return false;
}
|
fix pawn backward movement
|
fix pawn backward movement
|
C++
|
bsd-2-clause
|
Alexander-Sh/chess-task
|
838307c785ee1c4340b15379cfa9d31321d2df0e
|
src/chartsql/CSTableScan.cc
|
src/chartsql/CSTableScan.cc
|
/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. 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 <chartsql/CSTableScan.h>
#include <chartsql/qtree/ColumnReferenceNode.h>
#include <chartsql/runtime/defaultruntime.h>
#include <chartsql/runtime/compile.h>
#include <fnord/inspect.h>
using namespace fnord;
namespace csql {
CSTableScan::CSTableScan(
RefPtr<SequentialScanNode> stmt,
cstable::CSTableReader&& cstable,
DefaultRuntime* runtime) :
cstable_(std::move(cstable)),
colindex_(0),
aggr_strategy_(stmt->aggregationStrategy()) {
Set<String> column_names;
for (const auto& slnode : stmt->selectList()) {
findColumns(slnode->expression(), &column_names);
}
for (const auto& col : column_names) {
columns_.emplace(col, ColumnRef(cstable_.getColumnReader(col), colindex_++));
}
for (auto& slnode : stmt->selectList()) {
resolveColumns(slnode->expression());
}
for (const auto& slnode : stmt->selectList()) {
select_list_.emplace_back(
findMaxRepetitionLevel(slnode->expression()),
runtime->buildScalarExpression(slnode->expression()),
&scratch_);
}
}
void CSTableScan::execute(
ExecutionContext* context,
Function<bool (int argc, const SValue* argv)> fn) {
uint64_t select_level = 0;
uint64_t fetch_level = 0;
Vector<SValue> in_row(colindex_, SValue{});
Vector<SValue> out_row(select_list_.size(), SValue{});
size_t num_records = 0;
size_t total_records = cstable_.numRecords();
while (num_records < total_records) {
uint64_t next_level = 0;
if (fetch_level == 0) {
++num_records;
}
for (auto& col : columns_) {
auto nextr = col.second.reader->nextRepetitionLevel();
if (nextr >= fetch_level) {
auto& reader = col.second.reader;
uint64_t r;
uint64_t d;
void* data;
size_t size;
reader->next(&r, &d, &data, &size);
switch (col.second.reader->type()) {
case msg::FieldType::STRING:
in_row[col.second.index] =
SValue(SValue::StringType((char*) data, size));
break;
case msg::FieldType::UINT32:
case msg::FieldType::UINT64:
switch (size) {
case sizeof(uint32_t):
in_row[col.second.index] =
SValue(SValue::IntegerType(*((uint32_t*) data)));
break;
case sizeof(uint64_t):
in_row[col.second.index] =
SValue(SValue::IntegerType(*((uint64_t*) data)));
break;
case 0:
in_row[col.second.index] = SValue();
break;
}
break;
case msg::FieldType::BOOLEAN:
switch (size) {
case sizeof(uint32_t):
in_row[col.second.index] =
SValue(SValue::BoolType(*((uint32_t*) data) > 0));
break;
case sizeof(uint64_t):
in_row[col.second.index] =
SValue(SValue::BoolType(*((uint64_t*) data) > 0));
break;
case 0:
in_row[col.second.index] = SValue(SValue::BoolType(false));
break;
}
break;
case msg::FieldType::OBJECT:
RAISE(kIllegalStateError);
}
}
next_level = std::max(
next_level,
col.second.reader->nextRepetitionLevel());
}
fetch_level = next_level;
if (true) { // where clause
for (int i = 0; i < select_list_.size(); ++i) {
if (select_list_[i].rep_level >= select_level) {
select_list_[i].compiled->accumulate(
&select_list_[i].instance,
in_row.size(),
in_row.data());
}
}
switch (aggr_strategy_) {
case AggregationStrategy::AGGREGATE_ALL:
break;
case AggregationStrategy::AGGREGATE_WITHIN_RECORD:
if (next_level != 0) {
break;
}
/* fallthrough */
case AggregationStrategy::NO_AGGREGATION:
for (int i = 0; i < select_list_.size(); ++i) {
select_list_[i].compiled->evaluate(
in_row.size(),
in_row.data(),
&out_row[i]);
}
if (!fn(out_row.size(), out_row.data())) {
return;
}
break;
}
select_level = fetch_level;
} else {
select_level = std::min(select_level, fetch_level);
}
}
switch (aggr_strategy_) {
case AggregationStrategy::AGGREGATE_ALL:
for (int i = 0; i < select_list_.size(); ++i) {
select_list_[i].compiled->result(
&select_list_[i].instance,
&out_row[i]);
select_list_[i].compiled->reset(&select_list_[i].instance);
}
fn(out_row.size(), out_row.data());
break;
default:
break;
}
}
void CSTableScan::findColumns(
RefPtr<ScalarExpressionNode> expr,
Set<String>* column_names) const {
auto fieldref = dynamic_cast<ColumnReferenceNode*>(expr.get());
if (fieldref != nullptr) {
column_names->emplace(fieldref->fieldName());
}
for (const auto& e : expr->arguments()) {
findColumns(e, column_names);
}
}
void CSTableScan::resolveColumns(RefPtr<ScalarExpressionNode> expr) const {
auto fieldref = dynamic_cast<ColumnReferenceNode*>(expr.get());
if (fieldref != nullptr) {
auto col = columns_.find(fieldref->fieldName());
if (col == columns_.end()) {
RAISE(kIllegalStateError);
}
fieldref->setColumnIndex(col->second.index);
}
for (const auto& e : expr->arguments()) {
resolveColumns(e);
}
}
uint64_t CSTableScan::findMaxRepetitionLevel(
RefPtr<ScalarExpressionNode> expr) const {
uint64_t max_level = 0;
auto fieldref = dynamic_cast<ColumnReferenceNode*>(expr.get());
if (fieldref != nullptr) {
auto col = columns_.find(fieldref->fieldName());
if (col == columns_.end()) {
RAISE(kIllegalStateError);
}
auto col_level = col->second.reader->maxRepetitionLevel();
if (col_level > max_level) {
max_level = col_level;
}
}
for (const auto& e : expr->arguments()) {
auto e_level = findMaxRepetitionLevel(e);
if (e_level > max_level) {
max_level = e_level;
}
}
return max_level;
}
CSTableScan::ColumnRef::ColumnRef(
RefPtr<cstable::ColumnReader> r,
size_t i) :
reader(r),
index(i) {}
CSTableScan::ExpressionRef::ExpressionRef(
size_t _rep_level,
ScopedPtr<ScalarExpression> _compiled,
ScratchMemory* smem) :
rep_level(_rep_level),
compiled(std::move(_compiled)),
instance(compiled->allocInstance(smem)) {}
CSTableScan::ExpressionRef::ExpressionRef(
ExpressionRef&& other) :
rep_level(other.rep_level),
compiled(std::move(other.compiled)),
instance(other.instance) {
other.instance.scratch = nullptr;
}
CSTableScan::ExpressionRef::~ExpressionRef() {
if (instance.scratch) {
compiled->freeInstance(&instance);
}
}
} // namespace csql
|
/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. 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 <chartsql/CSTableScan.h>
#include <chartsql/qtree/ColumnReferenceNode.h>
#include <chartsql/runtime/defaultruntime.h>
#include <chartsql/runtime/compile.h>
#include <fnord/inspect.h>
using namespace fnord;
namespace csql {
CSTableScan::CSTableScan(
RefPtr<SequentialScanNode> stmt,
cstable::CSTableReader&& cstable,
DefaultRuntime* runtime) :
cstable_(std::move(cstable)),
colindex_(0),
aggr_strategy_(stmt->aggregationStrategy()) {
Set<String> column_names;
for (const auto& slnode : stmt->selectList()) {
findColumns(slnode->expression(), &column_names);
}
for (const auto& col : column_names) {
columns_.emplace(col, ColumnRef(cstable_.getColumnReader(col), colindex_++));
}
for (auto& slnode : stmt->selectList()) {
resolveColumns(slnode->expression());
}
for (const auto& slnode : stmt->selectList()) {
select_list_.emplace_back(
findMaxRepetitionLevel(slnode->expression()),
runtime->buildScalarExpression(slnode->expression()),
&scratch_);
}
}
void CSTableScan::execute(
ExecutionContext* context,
Function<bool (int argc, const SValue* argv)> fn) {
uint64_t select_level = 0;
uint64_t fetch_level = 0;
Vector<SValue> in_row(colindex_, SValue{});
Vector<SValue> out_row(select_list_.size(), SValue{});
size_t num_records = 0;
size_t total_records = cstable_.numRecords();
while (num_records < total_records) {
uint64_t next_level = 0;
if (fetch_level == 0) {
++num_records;
}
for (auto& col : columns_) {
auto nextr = col.second.reader->nextRepetitionLevel();
if (nextr >= fetch_level) {
auto& reader = col.second.reader;
uint64_t r;
uint64_t d;
void* data;
size_t size;
reader->next(&r, &d, &data, &size);
switch (col.second.reader->type()) {
case msg::FieldType::STRING:
in_row[col.second.index] =
SValue(SValue::StringType((char*) data, size));
break;
case msg::FieldType::UINT32:
case msg::FieldType::UINT64:
switch (size) {
case sizeof(uint32_t):
in_row[col.second.index] =
SValue(SValue::IntegerType(*((uint32_t*) data)));
break;
case sizeof(uint64_t):
in_row[col.second.index] =
SValue(SValue::IntegerType(*((uint64_t*) data)));
break;
case 0:
in_row[col.second.index] = SValue();
break;
}
break;
case msg::FieldType::BOOLEAN:
switch (size) {
case sizeof(uint32_t):
in_row[col.second.index] =
SValue(SValue::BoolType(*((uint32_t*) data) > 0));
break;
case sizeof(uint64_t):
in_row[col.second.index] =
SValue(SValue::BoolType(*((uint64_t*) data) > 0));
break;
case 0:
in_row[col.second.index] = SValue(SValue::BoolType(false));
break;
}
break;
case msg::FieldType::OBJECT:
RAISE(kIllegalStateError);
}
}
next_level = std::max(
next_level,
col.second.reader->nextRepetitionLevel());
}
fetch_level = next_level;
if (true) { // where clause
for (int i = 0; i < select_list_.size(); ++i) {
if (select_list_[i].rep_level >= select_level) {
select_list_[i].compiled->accumulate(
&select_list_[i].instance,
in_row.size(),
in_row.data());
}
}
switch (aggr_strategy_) {
case AggregationStrategy::AGGREGATE_ALL:
break;
case AggregationStrategy::AGGREGATE_WITHIN_RECORD:
if (next_level != 0) {
break;
}
/* fallthrough */
case AggregationStrategy::NO_AGGREGATION:
for (int i = 0; i < select_list_.size(); ++i) {
select_list_[i].compiled->evaluate(
in_row.size(),
in_row.data(),
&out_row[i]);
}
if (!fn(out_row.size(), out_row.data())) {
return;
}
break;
}
select_level = fetch_level;
} else {
select_level = std::min(select_level, fetch_level);
}
for (const auto& col : columns_) {
if (col.second.reader->maxRepetitionLevel() >= select_level) {
in_row[col.second.index] = SValue();
}
}
}
switch (aggr_strategy_) {
case AggregationStrategy::AGGREGATE_ALL:
for (int i = 0; i < select_list_.size(); ++i) {
select_list_[i].compiled->result(
&select_list_[i].instance,
&out_row[i]);
select_list_[i].compiled->reset(&select_list_[i].instance);
}
fn(out_row.size(), out_row.data());
break;
default:
break;
}
}
void CSTableScan::findColumns(
RefPtr<ScalarExpressionNode> expr,
Set<String>* column_names) const {
auto fieldref = dynamic_cast<ColumnReferenceNode*>(expr.get());
if (fieldref != nullptr) {
column_names->emplace(fieldref->fieldName());
}
for (const auto& e : expr->arguments()) {
findColumns(e, column_names);
}
}
void CSTableScan::resolveColumns(RefPtr<ScalarExpressionNode> expr) const {
auto fieldref = dynamic_cast<ColumnReferenceNode*>(expr.get());
if (fieldref != nullptr) {
auto col = columns_.find(fieldref->fieldName());
if (col == columns_.end()) {
RAISE(kIllegalStateError);
}
fieldref->setColumnIndex(col->second.index);
}
for (const auto& e : expr->arguments()) {
resolveColumns(e);
}
}
uint64_t CSTableScan::findMaxRepetitionLevel(
RefPtr<ScalarExpressionNode> expr) const {
uint64_t max_level = 0;
auto fieldref = dynamic_cast<ColumnReferenceNode*>(expr.get());
if (fieldref != nullptr) {
auto col = columns_.find(fieldref->fieldName());
if (col == columns_.end()) {
RAISE(kIllegalStateError);
}
auto col_level = col->second.reader->maxRepetitionLevel();
if (col_level > max_level) {
max_level = col_level;
}
}
for (const auto& e : expr->arguments()) {
auto e_level = findMaxRepetitionLevel(e);
if (e_level > max_level) {
max_level = e_level;
}
}
return max_level;
}
CSTableScan::ColumnRef::ColumnRef(
RefPtr<cstable::ColumnReader> r,
size_t i) :
reader(r),
index(i) {}
CSTableScan::ExpressionRef::ExpressionRef(
size_t _rep_level,
ScopedPtr<ScalarExpression> _compiled,
ScratchMemory* smem) :
rep_level(_rep_level),
compiled(std::move(_compiled)),
instance(compiled->allocInstance(smem)) {}
CSTableScan::ExpressionRef::ExpressionRef(
ExpressionRef&& other) :
rep_level(other.rep_level),
compiled(std::move(other.compiled)),
instance(other.instance) {
other.instance.scratch = nullptr;
}
CSTableScan::ExpressionRef::~ExpressionRef() {
if (instance.scratch) {
compiled->freeInstance(&instance);
}
}
} // namespace csql
|
allow aggregating over multiple leaves
|
allow aggregating over multiple leaves
|
C++
|
agpl-3.0
|
eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql
|
f51a403518c23933947bdd84de941ef19f0f1387
|
src/plugins/clangcodemodel/clangmodelmanagersupport.cpp
|
src/plugins/clangcodemodel/clangmodelmanagersupport.cpp
|
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "clangmodelmanagersupport.h"
#include "constants.h"
#include "clangeditordocumentprocessor.h"
#include "clangutils.h"
#include <coreplugin/editormanager/editormanager.h>
#include <cpptools/baseeditordocumentparser.h>
#include <cpptools/editordocumenthandle.h>
#include <projectexplorer/project.h>
#include <clangbackendipc/cmbregisterprojectsforcodecompletioncommand.h>
#include <clangbackendipc/filecontainer.h>
#include <clangbackendipc/projectpartcontainer.h>
#include <utils/qtcassert.h>
#include <QCoreApplication>
using namespace ClangCodeModel;
using namespace ClangCodeModel::Internal;
static ModelManagerSupportClang *m_instance_forTestsOnly = 0;
static CppTools::CppModelManager *cppModelManager()
{
return CppTools::CppModelManager::instance();
}
ModelManagerSupportClang::ModelManagerSupportClang()
: m_completionAssistProvider(m_ipcCommunicator)
{
QTC_CHECK(!m_instance_forTestsOnly);
m_instance_forTestsOnly = this;
Core::EditorManager *editorManager = Core::EditorManager::instance();
connect(editorManager, &Core::EditorManager::currentEditorChanged,
this, &ModelManagerSupportClang::onCurrentEditorChanged);
connect(editorManager, &Core::EditorManager::editorOpened,
this, &ModelManagerSupportClang::onEditorOpened);
CppTools::CppModelManager *modelManager = cppModelManager();
connect(modelManager, &CppTools::CppModelManager::abstractEditorSupportContentsUpdated,
this, &ModelManagerSupportClang::onAbstractEditorSupportContentsUpdated);
connect(modelManager, &CppTools::CppModelManager::abstractEditorSupportRemoved,
this, &ModelManagerSupportClang::onAbstractEditorSupportRemoved);
connect(modelManager, &CppTools::CppModelManager::projectPartsUpdated,
this, &ModelManagerSupportClang::onProjectPartsUpdated);
connect(modelManager, &CppTools::CppModelManager::projectPartsRemoved,
this, &ModelManagerSupportClang::onProjectPartsRemoved);
}
ModelManagerSupportClang::~ModelManagerSupportClang()
{
m_instance_forTestsOnly = 0;
}
CppTools::CppCompletionAssistProvider *ModelManagerSupportClang::completionAssistProvider()
{
return &m_completionAssistProvider;
}
CppTools::BaseEditorDocumentProcessor *ModelManagerSupportClang::editorDocumentProcessor(
TextEditor::TextDocument *baseTextDocument)
{
return new ClangEditorDocumentProcessor(this, baseTextDocument);
}
void ModelManagerSupportClang::onCurrentEditorChanged(Core::IEditor *newCurrent)
{
// If we switch away from a cpp editor, update the backend about
// the document's unsaved content.
if (m_previousCppEditor && m_previousCppEditor->document()->isModified()) {
m_ipcCommunicator.updateUnsavedFileFromCppEditorDocument(
m_previousCppEditor->document()->filePath().toString());
}
// Remember previous editor
if (newCurrent && cppModelManager()->isCppEditor(newCurrent))
m_previousCppEditor = newCurrent;
else
m_previousCppEditor.clear();
}
void ModelManagerSupportClang::onEditorOpened(Core::IEditor *editor)
{
QTC_ASSERT(editor, return);
Core::IDocument *document = editor->document();
QTC_ASSERT(document, return);
TextEditor::TextDocument *textDocument = qobject_cast<TextEditor::TextDocument *>(document);
if (textDocument && cppModelManager()->isCppEditor(editor)) {
// Handle externally changed documents
connect(textDocument, &Core::IDocument::reloadFinished,
this, &ModelManagerSupportClang::onCppDocumentReloadFinished,
Qt::UniqueConnection);
// Handle changes from e.g. refactoring actions
connect(textDocument, &TextEditor::TextDocument::contentsChanged,
this, &ModelManagerSupportClang::onCppDocumentContentsChanged,
Qt::UniqueConnection);
// TODO: Ensure that not fully loaded documents are updated?
}
}
void ModelManagerSupportClang::onCppDocumentReloadFinished(bool success)
{
if (!success)
return;
Core::IDocument *document = qobject_cast<Core::IDocument *>(sender());
m_ipcCommunicator.updateUnsavedFileIfNotCurrentDocument(document);
}
void ModelManagerSupportClang::onCppDocumentContentsChanged()
{
Core::IDocument *document = qobject_cast<Core::IDocument *>(sender());
m_ipcCommunicator.updateUnsavedFileIfNotCurrentDocument(document);
}
void ModelManagerSupportClang::onAbstractEditorSupportContentsUpdated(const QString &filePath,
const QByteArray &content)
{
QTC_ASSERT(!filePath.isEmpty(), return);
m_ipcCommunicator.updateUnsavedFile(filePath, content);
}
void ModelManagerSupportClang::onAbstractEditorSupportRemoved(const QString &filePath)
{
QTC_ASSERT(!filePath.isEmpty(), return);
if (!cppModelManager()->cppEditorDocument(filePath)) {
const QString projectPartId = Utils::projectPartIdForFile(filePath);
m_ipcCommunicator.unregisterFilesForCodeCompletion(
{ClangBackEnd::FileContainer(filePath, projectPartId)});
}
}
void ModelManagerSupportClang::onProjectPartsUpdated(ProjectExplorer::Project *project)
{
QTC_ASSERT(project, return);
const CppTools::ProjectInfo projectInfo = cppModelManager()->projectInfo(project);
QTC_ASSERT(projectInfo.isValid(), return);
m_ipcCommunicator.registerProjectsParts(projectInfo.projectParts());
}
void ModelManagerSupportClang::onProjectPartsRemoved(const QStringList &projectPartIds)
{
m_ipcCommunicator.unregisterProjectPartsForCodeCompletion(projectPartIds);
}
#ifdef QT_TESTLIB_LIB
ModelManagerSupportClang *ModelManagerSupportClang::instance_forTestsOnly()
{
return m_instance_forTestsOnly;
}
#endif
IpcCommunicator &ModelManagerSupportClang::ipcCommunicator()
{
return m_ipcCommunicator;
}
QString ModelManagerSupportProviderClang::id() const
{
return QLatin1String(Constants::CLANG_MODELMANAGERSUPPORT_ID);
}
QString ModelManagerSupportProviderClang::displayName() const
{
//: Display name
return QCoreApplication::translate("ClangCodeModel::Internal::ModelManagerSupport",
"Clang");
}
CppTools::ModelManagerSupport::Ptr ModelManagerSupportProviderClang::createModelManagerSupport()
{
return CppTools::ModelManagerSupport::Ptr(new ModelManagerSupportClang);
}
|
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "clangmodelmanagersupport.h"
#include "constants.h"
#include "clangeditordocumentprocessor.h"
#include "clangutils.h"
#include <coreplugin/editormanager/editormanager.h>
#include <cpptools/baseeditordocumentparser.h>
#include <cpptools/editordocumenthandle.h>
#include <projectexplorer/project.h>
#include <clangbackendipc/cmbregisterprojectsforcodecompletioncommand.h>
#include <clangbackendipc/filecontainer.h>
#include <clangbackendipc/projectpartcontainer.h>
#include <utils/qtcassert.h>
#include <QCoreApplication>
using namespace ClangCodeModel;
using namespace ClangCodeModel::Internal;
static ModelManagerSupportClang *m_instance_forTestsOnly = 0;
static CppTools::CppModelManager *cppModelManager()
{
return CppTools::CppModelManager::instance();
}
ModelManagerSupportClang::ModelManagerSupportClang()
: m_completionAssistProvider(m_ipcCommunicator)
{
QTC_CHECK(!m_instance_forTestsOnly);
m_instance_forTestsOnly = this;
Core::EditorManager *editorManager = Core::EditorManager::instance();
connect(editorManager, &Core::EditorManager::currentEditorChanged,
this, &ModelManagerSupportClang::onCurrentEditorChanged);
connect(editorManager, &Core::EditorManager::editorOpened,
this, &ModelManagerSupportClang::onEditorOpened);
CppTools::CppModelManager *modelManager = cppModelManager();
connect(modelManager, &CppTools::CppModelManager::abstractEditorSupportContentsUpdated,
this, &ModelManagerSupportClang::onAbstractEditorSupportContentsUpdated);
connect(modelManager, &CppTools::CppModelManager::abstractEditorSupportRemoved,
this, &ModelManagerSupportClang::onAbstractEditorSupportRemoved);
connect(modelManager, &CppTools::CppModelManager::projectPartsUpdated,
this, &ModelManagerSupportClang::onProjectPartsUpdated);
connect(modelManager, &CppTools::CppModelManager::projectPartsRemoved,
this, &ModelManagerSupportClang::onProjectPartsRemoved);
}
ModelManagerSupportClang::~ModelManagerSupportClang()
{
m_instance_forTestsOnly = 0;
}
CppTools::CppCompletionAssistProvider *ModelManagerSupportClang::completionAssistProvider()
{
return &m_completionAssistProvider;
}
CppTools::BaseEditorDocumentProcessor *ModelManagerSupportClang::editorDocumentProcessor(
TextEditor::TextDocument *baseTextDocument)
{
return new ClangEditorDocumentProcessor(this, baseTextDocument);
}
void ModelManagerSupportClang::onCurrentEditorChanged(Core::IEditor *newCurrent)
{
// If we switch away from a cpp editor, update the backend about
// the document's unsaved content.
if (m_previousCppEditor && m_previousCppEditor->document()->isModified()) {
m_ipcCommunicator.updateUnsavedFileFromCppEditorDocument(
m_previousCppEditor->document()->filePath().toString());
}
// Remember previous editor
if (newCurrent && cppModelManager()->isCppEditor(newCurrent))
m_previousCppEditor = newCurrent;
else
m_previousCppEditor.clear();
}
void ModelManagerSupportClang::onEditorOpened(Core::IEditor *editor)
{
QTC_ASSERT(editor, return);
Core::IDocument *document = editor->document();
QTC_ASSERT(document, return);
TextEditor::TextDocument *textDocument = qobject_cast<TextEditor::TextDocument *>(document);
if (textDocument && cppModelManager()->isCppEditor(editor)) {
// Handle externally changed documents
connect(textDocument, &Core::IDocument::reloadFinished,
this, &ModelManagerSupportClang::onCppDocumentReloadFinished,
Qt::UniqueConnection);
// Handle changes from e.g. refactoring actions
connect(textDocument, &TextEditor::TextDocument::contentsChanged,
this, &ModelManagerSupportClang::onCppDocumentContentsChanged,
Qt::UniqueConnection);
// TODO: Ensure that not fully loaded documents are updated?
}
}
void ModelManagerSupportClang::onCppDocumentReloadFinished(bool success)
{
if (!success)
return;
Core::IDocument *document = qobject_cast<Core::IDocument *>(sender());
m_ipcCommunicator.updateUnsavedFileIfNotCurrentDocument(document);
}
void ModelManagerSupportClang::onCppDocumentContentsChanged()
{
Core::IDocument *document = qobject_cast<Core::IDocument *>(sender());
m_ipcCommunicator.updateUnsavedFileIfNotCurrentDocument(document);
}
void ModelManagerSupportClang::onAbstractEditorSupportContentsUpdated(const QString &filePath,
const QByteArray &content)
{
QTC_ASSERT(!filePath.isEmpty(), return);
m_ipcCommunicator.updateUnsavedFile(filePath, content);
}
void ModelManagerSupportClang::onAbstractEditorSupportRemoved(const QString &filePath)
{
QTC_ASSERT(!filePath.isEmpty(), return);
if (!cppModelManager()->cppEditorDocument(filePath)) {
const QString projectPartId = Utils::projectPartIdForFile(filePath);
m_ipcCommunicator.unregisterFilesForCodeCompletion(
{ClangBackEnd::FileContainer(filePath, projectPartId)});
}
}
void ModelManagerSupportClang::onProjectPartsUpdated(ProjectExplorer::Project *project)
{
QTC_ASSERT(project, return);
const CppTools::ProjectInfo projectInfo = cppModelManager()->projectInfo(project);
QTC_ASSERT(projectInfo.isValid(), return);
m_ipcCommunicator.registerProjectsParts(projectInfo.projectParts());
}
void ModelManagerSupportClang::onProjectPartsRemoved(const QStringList &projectPartIds)
{
if (!projectPartIds.isEmpty())
m_ipcCommunicator.unregisterProjectPartsForCodeCompletion(projectPartIds);
}
#ifdef QT_TESTLIB_LIB
ModelManagerSupportClang *ModelManagerSupportClang::instance_forTestsOnly()
{
return m_instance_forTestsOnly;
}
#endif
IpcCommunicator &ModelManagerSupportClang::ipcCommunicator()
{
return m_ipcCommunicator;
}
QString ModelManagerSupportProviderClang::id() const
{
return QLatin1String(Constants::CLANG_MODELMANAGERSUPPORT_ID);
}
QString ModelManagerSupportProviderClang::displayName() const
{
//: Display name
return QCoreApplication::translate("ClangCodeModel::Internal::ModelManagerSupport",
"Clang");
}
CppTools::ModelManagerSupport::Ptr ModelManagerSupportProviderClang::createModelManagerSupport()
{
return CppTools::ModelManagerSupport::Ptr(new ModelManagerSupportClang);
}
|
Send unregisterProjectParts only with non-empty list
|
Clang: Send unregisterProjectParts only with non-empty list
Change-Id: Id11d420c481758ccd58921dddc92c6036c9204e1
Reviewed-by: Marco Bubke <[email protected]>
|
C++
|
lgpl-2.1
|
martyone/sailfish-qtcreator,xianian/qt-creator,xianian/qt-creator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,xianian/qt-creator,martyone/sailfish-qtcreator,xianian/qt-creator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,xianian/qt-creator,martyone/sailfish-qtcreator,xianian/qt-creator,xianian/qt-creator,xianian/qt-creator,xianian/qt-creator,martyone/sailfish-qtcreator
|
d430767fa795672e0f8988d183ba04a05ed3cc3e
|
xs/src/libslic3r/Surface.hpp
|
xs/src/libslic3r/Surface.hpp
|
#ifndef slic3r_Surface_hpp_
#define slic3r_Surface_hpp_
#include "libslic3r.h"
#include "ExPolygon.hpp"
namespace Slic3r {
enum SurfaceType {
// Top horizontal surface, visible from the top.
stTop,
// Bottom horizontal surface, visible from the bottom, printed with a normal extrusion flow.
stBottom,
// Bottom horizontal surface, visible from the bottom, unsupported, printed with a bridging extrusion flow.
stBottomBridge,
// Normal sparse infill.
stInternal,
// Full infill, supporting the top surfaces and/or defining the verticall wall thickness.
stInternalSolid,
// 1st layer of dense infill over sparse infill, printed with a bridging extrusion flow.
stInternalBridge,
// stInternal turns into void surfaces if the sparse infill is used for supports only,
// or if sparse infill layers get combined into a single layer.
stInternalVoid,
// Inner/outer perimeters.
stPerimeter
};
class Surface
{
public:
SurfaceType surface_type;
ExPolygon expolygon;
double thickness; // in mm
unsigned short thickness_layers; // in layers
double bridge_angle; // in radians, ccw, 0 = East, only 0+ (negative means undefined)
unsigned short extra_perimeters;
Surface(SurfaceType _surface_type, const ExPolygon &_expolygon)
: surface_type(_surface_type), expolygon(_expolygon),
thickness(-1), thickness_layers(1), bridge_angle(-1), extra_perimeters(0)
{};
Surface(const Surface &other, const ExPolygon &_expolygon)
: surface_type(other.surface_type), expolygon(_expolygon),
thickness(other.thickness), thickness_layers(other.thickness_layers), bridge_angle(other.bridge_angle), extra_perimeters(other.extra_perimeters)
{};
#if SLIC3R_CPPVER >= 11
Surface(SurfaceType _surface_type, const ExPolygon &&_expolygon)
: surface_type(_surface_type), expolygon(std::move(_expolygon)),
thickness(-1), thickness_layers(1), bridge_angle(-1), extra_perimeters(0)
{};
Surface(const Surface &other, const ExPolygon &&_expolygon)
: surface_type(other.surface_type), expolygon(std::move(_expolygon)),
thickness(other.thickness), thickness_layers(other.thickness_layers), bridge_angle(other.bridge_angle), extra_perimeters(other.extra_perimeters)
{};
#endif
operator Polygons() const;
double area() const;
bool empty() const { return expolygon.empty(); }
void clear() { expolygon.clear(); }
bool is_solid() const;
bool is_external() const;
bool is_internal() const;
bool is_bottom() const;
bool is_bridge() const;
};
typedef std::vector<Surface> Surfaces;
typedef std::vector<Surface*> SurfacesPtr;
inline Polygons to_polygons(const Surfaces &src)
{
size_t num = 0;
for (Surfaces::const_iterator it = src.begin(); it != src.end(); ++it)
num += it->expolygon.holes.size() + 1;
Polygons polygons;
polygons.reserve(num);
for (Surfaces::const_iterator it = src.begin(); it != src.end(); ++it) {
polygons.push_back(it->expolygon.contour);
for (Polygons::const_iterator ith = it->expolygon.holes.begin(); ith != it->expolygon.holes.end(); ++ith)
polygons.push_back(*ith);
}
return polygons;
}
inline Polygons to_polygons(const SurfacesPtr &src)
{
size_t num = 0;
for (SurfacesPtr::const_iterator it = src.begin(); it != src.end(); ++it)
num += (*it)->expolygon.holes.size() + 1;
Polygons polygons;
polygons.reserve(num);
for (SurfacesPtr::const_iterator it = src.begin(); it != src.end(); ++it) {
polygons.push_back((*it)->expolygon.contour);
for (Polygons::const_iterator ith = (*it)->expolygon.holes.begin(); ith != (*it)->expolygon.holes.end(); ++ith)
polygons.push_back(*ith);
}
return polygons;
}
inline ExPolygons to_expolygons(const Surfaces &src)
{
ExPolygons expolygons;
expolygons.reserve(src.size());
for (Surfaces::const_iterator it = src.begin(); it != src.end(); ++it)
expolygons.push_back(it->expolygon);
return expolygons;
}
inline ExPolygons to_expolygons(Surfaces &&src)
{
ExPolygons expolygons;
expolygons.reserve(src.size());
for (Surfaces::const_iterator it = src.begin(); it != src.end(); ++it)
expolygons.emplace_back(ExPolygon(std::move(it->expolygon)));
src.clear();
return expolygons;
}
inline ExPolygons to_expolygons(const SurfacesPtr &src)
{
ExPolygons expolygons;
expolygons.reserve(src.size());
for (SurfacesPtr::const_iterator it = src.begin(); it != src.end(); ++it)
expolygons.push_back((*it)->expolygon);
return expolygons;
}
// Count a nuber of polygons stored inside the vector of expolygons.
// Useful for allocating space for polygons when converting expolygons to polygons.
inline size_t number_polygons(const Surfaces &surfaces)
{
size_t n_polygons = 0;
for (Surfaces::const_iterator it = surfaces.begin(); it != surfaces.end(); ++ it)
n_polygons += it->expolygon.holes.size() + 1;
return n_polygons;
}
inline size_t number_polygons(const SurfacesPtr &surfaces)
{
size_t n_polygons = 0;
for (SurfacesPtr::const_iterator it = surfaces.begin(); it != surfaces.end(); ++ it)
n_polygons += (*it)->expolygon.holes.size() + 1;
return n_polygons;
}
// Append a vector of Surfaces at the end of another vector of polygons.
inline void polygons_append(Polygons &dst, const Surfaces &src)
{
dst.reserve(dst.size() + number_polygons(src));
for (Surfaces::const_iterator it = src.begin(); it != src.end(); ++ it) {
dst.push_back(it->expolygon.contour);
dst.insert(dst.end(), it->expolygon.holes.begin(), it->expolygon.holes.end());
}
}
inline void polygons_append(Polygons &dst, Surfaces &&src)
{
dst.reserve(dst.size() + number_polygons(src));
for (Surfaces::iterator it = src.begin(); it != src.end(); ++ it) {
dst.push_back(std::move(it->expolygon.contour));
std::move(std::begin(it->expolygon.holes), std::end(it->expolygon.holes), std::back_inserter(dst));
it->expolygon.holes.clear();
}
}
// Append a vector of Surfaces at the end of another vector of polygons.
inline void polygons_append(Polygons &dst, const SurfacesPtr &src)
{
dst.reserve(dst.size() + number_polygons(src));
for (SurfacesPtr::const_iterator it = src.begin(); it != src.end(); ++ it) {
dst.push_back((*it)->expolygon.contour);
dst.insert(dst.end(), (*it)->expolygon.holes.begin(), (*it)->expolygon.holes.end());
}
}
inline void polygons_append(Polygons &dst, SurfacesPtr &&src)
{
dst.reserve(dst.size() + number_polygons(src));
for (SurfacesPtr::const_iterator it = src.begin(); it != src.end(); ++ it) {
dst.push_back(std::move((*it)->expolygon.contour));
std::move(std::begin((*it)->expolygon.holes), std::end((*it)->expolygon.holes), std::back_inserter(dst));
(*it)->expolygon.holes.clear();
}
}
// Append a vector of Surfaces at the end of another vector of polygons.
inline void surfaces_append(Surfaces &dst, const ExPolygons &src, SurfaceType surfaceType)
{
dst.reserve(dst.size() + src.size());
for (ExPolygons::const_iterator it = src.begin(); it != src.end(); ++ it)
dst.push_back(Surface(surfaceType, *it));
}
inline void surfaces_append(Surfaces &dst, const ExPolygons &src, const Surface &surfaceTempl)
{
dst.reserve(dst.size() + number_polygons(src));
for (ExPolygons::const_iterator it = src.begin(); it != src.end(); ++ it)
dst.push_back(Surface(surfaceTempl, *it));
}
inline void surfaces_append(Surfaces &dst, const Surfaces &src)
{
dst.insert(dst.end(), src.begin(), src.end());
}
inline void surfaces_append(Surfaces &dst, ExPolygons &&src, SurfaceType surfaceType)
{
dst.reserve(dst.size() + src.size());
for (ExPolygons::const_iterator it = src.begin(); it != src.end(); ++ it)
dst.push_back(Surface(surfaceType, std::move(*it)));
src.clear();
}
inline void surfaces_append(Surfaces &dst, ExPolygons &&src, const Surface &surfaceTempl)
{
dst.reserve(dst.size() + number_polygons(src));
for (ExPolygons::const_iterator it = src.begin(); it != src.end(); ++ it)
dst.push_back(Surface(surfaceTempl, std::move(*it)));
src.clear();
}
inline void surfaces_append(Surfaces &dst, Surfaces &&src)
{
if (dst.empty()) {
dst = std::move(src);
} else {
std::move(std::begin(src), std::end(src), std::back_inserter(dst));
src.clear();
}
}
extern BoundingBox get_extents(const Surface &surface);
extern BoundingBox get_extents(const Surfaces &surfaces);
extern BoundingBox get_extents(const SurfacesPtr &surfaces);
inline bool surfaces_could_merge(const Surface &s1, const Surface &s2)
{
return
s1.surface_type == s2.surface_type &&
s1.thickness == s2.thickness &&
s1.thickness_layers == s2.thickness_layers &&
s1.bridge_angle == s2.bridge_angle;
}
class SVG;
extern const char* surface_type_to_color_name(const SurfaceType surface_type);
extern void export_surface_type_legend_to_svg(SVG &svg, const Point &pos);
extern Point export_surface_type_legend_to_svg_box_size();
extern bool export_to_svg(const char *path, const Surfaces &surfaces, const float transparency = 1.f);
}
#endif
|
#ifndef slic3r_Surface_hpp_
#define slic3r_Surface_hpp_
#include "libslic3r.h"
#include "ExPolygon.hpp"
namespace Slic3r {
enum SurfaceType {
// Top horizontal surface, visible from the top.
stTop,
// Bottom horizontal surface, visible from the bottom, printed with a normal extrusion flow.
stBottom,
// Bottom horizontal surface, visible from the bottom, unsupported, printed with a bridging extrusion flow.
stBottomBridge,
// Normal sparse infill.
stInternal,
// Full infill, supporting the top surfaces and/or defining the verticall wall thickness.
stInternalSolid,
// 1st layer of dense infill over sparse infill, printed with a bridging extrusion flow.
stInternalBridge,
// stInternal turns into void surfaces if the sparse infill is used for supports only,
// or if sparse infill layers get combined into a single layer.
stInternalVoid,
// Inner/outer perimeters.
stPerimeter,
// Last surface type, if the SurfaceType is used as an index into a vector.
stLast,
stCount = stLast + 1
};
class Surface
{
public:
SurfaceType surface_type;
ExPolygon expolygon;
double thickness; // in mm
unsigned short thickness_layers; // in layers
double bridge_angle; // in radians, ccw, 0 = East, only 0+ (negative means undefined)
unsigned short extra_perimeters;
Surface(SurfaceType _surface_type, const ExPolygon &_expolygon)
: surface_type(_surface_type), expolygon(_expolygon),
thickness(-1), thickness_layers(1), bridge_angle(-1), extra_perimeters(0)
{};
Surface(const Surface &other, const ExPolygon &_expolygon)
: surface_type(other.surface_type), expolygon(_expolygon),
thickness(other.thickness), thickness_layers(other.thickness_layers), bridge_angle(other.bridge_angle), extra_perimeters(other.extra_perimeters)
{};
#if SLIC3R_CPPVER >= 11
Surface(SurfaceType _surface_type, const ExPolygon &&_expolygon)
: surface_type(_surface_type), expolygon(std::move(_expolygon)),
thickness(-1), thickness_layers(1), bridge_angle(-1), extra_perimeters(0)
{};
Surface(const Surface &other, const ExPolygon &&_expolygon)
: surface_type(other.surface_type), expolygon(std::move(_expolygon)),
thickness(other.thickness), thickness_layers(other.thickness_layers), bridge_angle(other.bridge_angle), extra_perimeters(other.extra_perimeters)
{};
#endif
operator Polygons() const;
double area() const;
bool empty() const { return expolygon.empty(); }
void clear() { expolygon.clear(); }
bool is_solid() const;
bool is_external() const;
bool is_internal() const;
bool is_bottom() const;
bool is_bridge() const;
};
typedef std::vector<Surface> Surfaces;
typedef std::vector<Surface*> SurfacesPtr;
inline Polygons to_polygons(const Surfaces &src)
{
size_t num = 0;
for (Surfaces::const_iterator it = src.begin(); it != src.end(); ++it)
num += it->expolygon.holes.size() + 1;
Polygons polygons;
polygons.reserve(num);
for (Surfaces::const_iterator it = src.begin(); it != src.end(); ++it) {
polygons.push_back(it->expolygon.contour);
for (Polygons::const_iterator ith = it->expolygon.holes.begin(); ith != it->expolygon.holes.end(); ++ith)
polygons.push_back(*ith);
}
return polygons;
}
inline Polygons to_polygons(const SurfacesPtr &src)
{
size_t num = 0;
for (SurfacesPtr::const_iterator it = src.begin(); it != src.end(); ++it)
num += (*it)->expolygon.holes.size() + 1;
Polygons polygons;
polygons.reserve(num);
for (SurfacesPtr::const_iterator it = src.begin(); it != src.end(); ++it) {
polygons.push_back((*it)->expolygon.contour);
for (Polygons::const_iterator ith = (*it)->expolygon.holes.begin(); ith != (*it)->expolygon.holes.end(); ++ith)
polygons.push_back(*ith);
}
return polygons;
}
inline ExPolygons to_expolygons(const Surfaces &src)
{
ExPolygons expolygons;
expolygons.reserve(src.size());
for (Surfaces::const_iterator it = src.begin(); it != src.end(); ++it)
expolygons.push_back(it->expolygon);
return expolygons;
}
inline ExPolygons to_expolygons(Surfaces &&src)
{
ExPolygons expolygons;
expolygons.reserve(src.size());
for (Surfaces::const_iterator it = src.begin(); it != src.end(); ++it)
expolygons.emplace_back(ExPolygon(std::move(it->expolygon)));
src.clear();
return expolygons;
}
inline ExPolygons to_expolygons(const SurfacesPtr &src)
{
ExPolygons expolygons;
expolygons.reserve(src.size());
for (SurfacesPtr::const_iterator it = src.begin(); it != src.end(); ++it)
expolygons.push_back((*it)->expolygon);
return expolygons;
}
// Count a nuber of polygons stored inside the vector of expolygons.
// Useful for allocating space for polygons when converting expolygons to polygons.
inline size_t number_polygons(const Surfaces &surfaces)
{
size_t n_polygons = 0;
for (Surfaces::const_iterator it = surfaces.begin(); it != surfaces.end(); ++ it)
n_polygons += it->expolygon.holes.size() + 1;
return n_polygons;
}
inline size_t number_polygons(const SurfacesPtr &surfaces)
{
size_t n_polygons = 0;
for (SurfacesPtr::const_iterator it = surfaces.begin(); it != surfaces.end(); ++ it)
n_polygons += (*it)->expolygon.holes.size() + 1;
return n_polygons;
}
// Append a vector of Surfaces at the end of another vector of polygons.
inline void polygons_append(Polygons &dst, const Surfaces &src)
{
dst.reserve(dst.size() + number_polygons(src));
for (Surfaces::const_iterator it = src.begin(); it != src.end(); ++ it) {
dst.push_back(it->expolygon.contour);
dst.insert(dst.end(), it->expolygon.holes.begin(), it->expolygon.holes.end());
}
}
inline void polygons_append(Polygons &dst, Surfaces &&src)
{
dst.reserve(dst.size() + number_polygons(src));
for (Surfaces::iterator it = src.begin(); it != src.end(); ++ it) {
dst.push_back(std::move(it->expolygon.contour));
std::move(std::begin(it->expolygon.holes), std::end(it->expolygon.holes), std::back_inserter(dst));
it->expolygon.holes.clear();
}
}
// Append a vector of Surfaces at the end of another vector of polygons.
inline void polygons_append(Polygons &dst, const SurfacesPtr &src)
{
dst.reserve(dst.size() + number_polygons(src));
for (SurfacesPtr::const_iterator it = src.begin(); it != src.end(); ++ it) {
dst.push_back((*it)->expolygon.contour);
dst.insert(dst.end(), (*it)->expolygon.holes.begin(), (*it)->expolygon.holes.end());
}
}
inline void polygons_append(Polygons &dst, SurfacesPtr &&src)
{
dst.reserve(dst.size() + number_polygons(src));
for (SurfacesPtr::const_iterator it = src.begin(); it != src.end(); ++ it) {
dst.push_back(std::move((*it)->expolygon.contour));
std::move(std::begin((*it)->expolygon.holes), std::end((*it)->expolygon.holes), std::back_inserter(dst));
(*it)->expolygon.holes.clear();
}
}
// Append a vector of Surfaces at the end of another vector of polygons.
inline void surfaces_append(Surfaces &dst, const ExPolygons &src, SurfaceType surfaceType)
{
dst.reserve(dst.size() + src.size());
for (ExPolygons::const_iterator it = src.begin(); it != src.end(); ++ it)
dst.push_back(Surface(surfaceType, *it));
}
inline void surfaces_append(Surfaces &dst, const ExPolygons &src, const Surface &surfaceTempl)
{
dst.reserve(dst.size() + number_polygons(src));
for (ExPolygons::const_iterator it = src.begin(); it != src.end(); ++ it)
dst.push_back(Surface(surfaceTempl, *it));
}
inline void surfaces_append(Surfaces &dst, const Surfaces &src)
{
dst.insert(dst.end(), src.begin(), src.end());
}
inline void surfaces_append(Surfaces &dst, ExPolygons &&src, SurfaceType surfaceType)
{
dst.reserve(dst.size() + src.size());
for (ExPolygons::const_iterator it = src.begin(); it != src.end(); ++ it)
dst.push_back(Surface(surfaceType, std::move(*it)));
src.clear();
}
inline void surfaces_append(Surfaces &dst, ExPolygons &&src, const Surface &surfaceTempl)
{
dst.reserve(dst.size() + number_polygons(src));
for (ExPolygons::const_iterator it = src.begin(); it != src.end(); ++ it)
dst.push_back(Surface(surfaceTempl, std::move(*it)));
src.clear();
}
inline void surfaces_append(Surfaces &dst, Surfaces &&src)
{
if (dst.empty()) {
dst = std::move(src);
} else {
std::move(std::begin(src), std::end(src), std::back_inserter(dst));
src.clear();
}
}
extern BoundingBox get_extents(const Surface &surface);
extern BoundingBox get_extents(const Surfaces &surfaces);
extern BoundingBox get_extents(const SurfacesPtr &surfaces);
inline bool surfaces_could_merge(const Surface &s1, const Surface &s2)
{
return
s1.surface_type == s2.surface_type &&
s1.thickness == s2.thickness &&
s1.thickness_layers == s2.thickness_layers &&
s1.bridge_angle == s2.bridge_angle;
}
class SVG;
extern const char* surface_type_to_color_name(const SurfaceType surface_type);
extern void export_surface_type_legend_to_svg(SVG &svg, const Point &pos);
extern Point export_surface_type_legend_to_svg_box_size();
extern bool export_to_svg(const char *path, const Surfaces &surfaces, const float transparency = 1.f);
}
#endif
|
Define a surface type count constant to be able to address a vector with a surface type.
|
Define a surface type count constant to be able to address a vector
with a surface type.
|
C++
|
agpl-3.0
|
prusa3d/Slic3r,prusa3d/Slic3r,prusa3d/Slic3r,prusa3d/Slic3r,prusa3d/Slic3r,prusa3d/Slic3r,prusa3d/Slic3r
|
37fe8cab2a02dfc7d94968009552d3dbe524211c
|
src/eventql/transport/http/default_servlet.cc
|
src/eventql/transport/http/default_servlet.cc
|
/**
* Copyright (c) 2016 zScale Technology GmbH <[email protected]>
* Authors:
* - Paul Asmuth <[email protected]>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* 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 license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include <eventql/util/http/cookies.h>
#include <eventql/util/assets.h>
#include <eventql/transport/http/default_servlet.h>
#include <eventql/transport/http/http_auth.h>
namespace eventql {
void DefaultServlet::handleHTTPRequest(
http::HTTPRequest* request,
http::HTTPResponse* response) {
URI uri(request->uri());
if (uri.path() == "/" &&
request->hasHeader("X-ZenBase-Production")) {
String auth_cookie;
http::Cookies::getCookie(
request->cookies(),
HTTPAuth::kSessionCookieKey,
&auth_cookie);
if (auth_cookie.empty()) {
response->setStatus(http::kStatusFound);
response->addHeader("Location", "http://app.eventql.io/");
return;
}
}
if (uri.path() == "/") {
response->setStatus(http::kStatusFound);
response->addHeader("Location", "/a/");
return;
}
if (uri.path() == "/ping") {
response->setStatus(http::kStatusOK);
response->addBody("pong");
return;
}
response->setStatus(http::kStatusNotFound);
response->addHeader("Content-Type", "text/html; charset=utf-8");
response->addBody(Assets::getAsset("eventql/webui/404.html"));
}
}
|
/**
* Copyright (c) 2016 zScale Technology GmbH <[email protected]>
* Authors:
* - Paul Asmuth <[email protected]>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* 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 license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include <eventql/util/http/cookies.h>
#include <eventql/util/assets.h>
#include <eventql/transport/http/default_servlet.h>
#include <eventql/transport/http/http_auth.h>
namespace eventql {
void DefaultServlet::handleHTTPRequest(
http::HTTPRequest* request,
http::HTTPResponse* response) {
URI uri(request->uri());
if (uri.path() == "/" &&
request->hasHeader("X-ZenBase-Production")) {
String auth_cookie;
http::Cookies::getCookie(
request->cookies(),
HTTPAuth::kSessionCookieKey,
&auth_cookie);
if (auth_cookie.empty()) {
response->setStatus(http::kStatusFound);
response->addHeader("Location", "http://app.eventql.io/");
return;
}
}
if (uri.path() == "/") {
response->setStatus(http::kStatusFound);
response->addHeader("Location", "/a/");
return;
}
if (uri.path() == "/ping") {
response->setStatus(http::kStatusOK);
response->addBody("pong");
return;
}
response->setStatus(http::kStatusNotFound);
response->addHeader("Content-Type", "text/plain; charset=utf-8");
response->addBody("not found");
}
}
|
return plaintext 404
|
return plaintext 404
|
C++
|
agpl-3.0
|
eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql
|
7f879f849a0ead39cc5a566f48a77be0724b9ed2
|
libcef/browser/url_request_context_getter.cc
|
libcef/browser/url_request_context_getter.cc
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "libcef/browser/url_request_context_getter.h"
#if defined(OS_WIN)
#include <winhttp.h>
#endif
#include <string>
#include <vector>
#include "libcef/browser/content_browser_client.h"
#include "libcef/browser/context.h"
#include "libcef/browser/scheme_handler.h"
#include "libcef/browser/thread_util.h"
#include "libcef/browser/url_network_delegate.h"
#include "libcef/browser/url_request_context_proxy.h"
#include "libcef/browser/url_request_interceptor.h"
#include "libcef/common/cef_switches.h"
#include "libcef/common/content_client.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/worker_pool.h"
#include "chrome/browser/net/proxy_service_factory.h"
#include "content/browser/net/sqlite_persistent_cookie_store.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/cookie_crypto_delegate.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/url_constants.h"
#include "net/cert/cert_verifier.h"
#include "net/cookies/cookie_monster.h"
#include "net/dns/host_resolver.h"
#include "net/ftp/ftp_network_layer.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_cache.h"
#include "net/http/http_server_properties_impl.h"
#include "net/http/http_util.h"
#include "net/http/transport_security_state.h"
#include "net/proxy/proxy_service.h"
#include "net/ssl/channel_id_service.h"
#include "net/ssl/default_channel_id_store.h"
#include "net/ssl/ssl_config_service_defaults.h"
#include "url/url_constants.h"
#include "net/url_request/http_user_agent_settings.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_storage.h"
#include "net/url_request/url_request_intercepting_job_factory.h"
#include "net/url_request/url_request_job_factory_impl.h"
#include "net/url_request/url_request_job_manager.h"
using content::BrowserThread;
#if defined(OS_WIN)
#pragma comment(lib, "winhttp.lib")
#endif
namespace {
// An implementation of |HttpUserAgentSettings| that provides a static
// HTTP Accept-Language header value and uses |content::GetUserAgent|
// to provide the HTTP User-Agent header value.
class CefHttpUserAgentSettings : public net::HttpUserAgentSettings {
public:
explicit CefHttpUserAgentSettings(const std::string& raw_language_list)
: http_accept_language_(net::HttpUtil::GenerateAcceptLanguageHeader(
raw_language_list)) {
CEF_REQUIRE_IOT();
}
// net::HttpUserAgentSettings implementation
std::string GetAcceptLanguage() const override {
CEF_REQUIRE_IOT();
return http_accept_language_;
}
std::string GetUserAgent() const override {
CEF_REQUIRE_IOT();
return CefContentClient::Get()->GetUserAgent();
}
private:
const std::string http_accept_language_;
DISALLOW_COPY_AND_ASSIGN(CefHttpUserAgentSettings);
};
} // namespace
CefURLRequestContextGetter::CefURLRequestContextGetter(
base::MessageLoop* io_loop,
base::MessageLoop* file_loop,
content::ProtocolHandlerMap* protocol_handlers,
content::URLRequestInterceptorScopedVector request_interceptors)
: io_loop_(io_loop),
file_loop_(file_loop),
request_interceptors_(request_interceptors.Pass()) {
// Must first be created on the UI thread.
CEF_REQUIRE_UIT();
std::swap(protocol_handlers_, *protocol_handlers);
}
CefURLRequestContextGetter::~CefURLRequestContextGetter() {
CEF_REQUIRE_IOT();
STLDeleteElements(&url_request_context_proxies_);
// Delete the ProxyService object here so that any pending requests will be
// canceled before the associated URLRequestContext is destroyed in this
// object's destructor.
storage_->set_proxy_service(NULL);
}
net::URLRequestContext* CefURLRequestContextGetter::GetURLRequestContext() {
CEF_REQUIRE_IOT();
if (!url_request_context_.get()) {
const base::FilePath& cache_path = CefContext::Get()->cache_path();
const base::CommandLine* command_line =
base::CommandLine::ForCurrentProcess();
const CefSettings& settings = CefContext::Get()->settings();
url_request_context_.reset(new net::URLRequestContext());
storage_.reset(
new net::URLRequestContextStorage(url_request_context_.get()));
bool persist_session_cookies =
(settings.persist_session_cookies ||
command_line->HasSwitch(switches::kPersistSessionCookies));
SetCookieStoragePath(cache_path, persist_session_cookies);
storage_->set_network_delegate(new CefNetworkDelegate);
storage_->set_channel_id_service(new net::ChannelIDService(
new net::DefaultChannelIDStore(NULL),
base::WorkerPool::GetTaskRunner(true)));
storage_->set_http_user_agent_settings(
new CefHttpUserAgentSettings("en-us,en"));
storage_->set_host_resolver(net::HostResolver::CreateDefaultResolver(NULL));
storage_->set_cert_verifier(net::CertVerifier::CreateDefault());
storage_->set_transport_security_state(new net::TransportSecurityState);
scoped_ptr<net::ProxyService> system_proxy_service;
system_proxy_service.reset(
ProxyServiceFactory::CreateProxyService(
NULL,
url_request_context_.get(),
url_request_context_->network_delegate(),
CefContentBrowserClient::Get()->proxy_config_service().release(),
*command_line,
true));
storage_->set_proxy_service(system_proxy_service.release());
storage_->set_ssl_config_service(new net::SSLConfigServiceDefaults);
// Add support for single sign-on.
url_security_manager_.reset(net::URLSecurityManager::Create(NULL, NULL));
std::vector<std::string> supported_schemes;
supported_schemes.push_back("basic");
supported_schemes.push_back("digest");
supported_schemes.push_back("ntlm");
supported_schemes.push_back("negotiate");
storage_->set_http_auth_handler_factory(
net::HttpAuthHandlerRegistryFactory::Create(
supported_schemes,
url_security_manager_.get(),
url_request_context_->host_resolver(),
std::string(),
false,
false));
storage_->set_http_server_properties(
make_scoped_ptr<net::HttpServerProperties>(
new net::HttpServerPropertiesImpl));
net::HttpCache::DefaultBackend* main_backend =
new net::HttpCache::DefaultBackend(
cache_path.empty() ? net::MEMORY_CACHE : net::DISK_CACHE,
net::CACHE_BACKEND_DEFAULT,
cache_path,
0,
BrowserThread::GetMessageLoopProxyForThread(
BrowserThread::CACHE));
net::HttpNetworkSession::Params network_session_params;
network_session_params.host_resolver =
url_request_context_->host_resolver();
network_session_params.cert_verifier =
url_request_context_->cert_verifier();
network_session_params.transport_security_state =
url_request_context_->transport_security_state();
network_session_params.channel_id_service =
url_request_context_->channel_id_service();
network_session_params.proxy_service =
url_request_context_->proxy_service();
network_session_params.ssl_config_service =
url_request_context_->ssl_config_service();
network_session_params.http_auth_handler_factory =
url_request_context_->http_auth_handler_factory();
network_session_params.network_delegate =
url_request_context_->network_delegate();
network_session_params.http_server_properties =
url_request_context_->http_server_properties();
network_session_params.ignore_certificate_errors =
(settings.ignore_certificate_errors ||
command_line->HasSwitch(switches::kIgnoreCertificateErrors));
net::HttpCache* main_cache = new net::HttpCache(network_session_params,
main_backend);
storage_->set_http_transaction_factory(main_cache);
#if !defined(DISABLE_FTP_SUPPORT)
ftp_transaction_factory_.reset(
new net::FtpNetworkLayer(network_session_params.host_resolver));
#endif
scoped_ptr<net::URLRequestJobFactoryImpl> job_factory(
new net::URLRequestJobFactoryImpl());
job_factory_impl_ = job_factory.get();
scheme::InstallInternalProtectedHandlers(job_factory.get(),
&protocol_handlers_,
ftp_transaction_factory_.get());
protocol_handlers_.clear();
request_interceptors_.push_back(new CefRequestInterceptor());
// Set up interceptors in the reverse order.
scoped_ptr<net::URLRequestJobFactory> top_job_factory =
job_factory.Pass();
for (content::URLRequestInterceptorScopedVector::reverse_iterator i =
request_interceptors_.rbegin();
i != request_interceptors_.rend();
++i) {
top_job_factory.reset(new net::URLRequestInterceptingJobFactory(
top_job_factory.Pass(), make_scoped_ptr(*i)));
}
request_interceptors_.weak_clear();
storage_->set_job_factory(top_job_factory.release());
}
return url_request_context_.get();
}
scoped_refptr<base::SingleThreadTaskRunner>
CefURLRequestContextGetter::GetNetworkTaskRunner() const {
return BrowserThread::GetMessageLoopProxyForThread(CEF_IOT);
}
net::HostResolver* CefURLRequestContextGetter::host_resolver() {
return url_request_context_->host_resolver();
}
void CefURLRequestContextGetter::SetCookieStoragePath(
const base::FilePath& path,
bool persist_session_cookies) {
CEF_REQUIRE_IOT();
if (url_request_context_->cookie_store() &&
((cookie_store_path_.empty() && path.empty()) ||
cookie_store_path_ == path)) {
// The path has not changed so don't do anything.
return;
}
scoped_refptr<content::SQLitePersistentCookieStore> persistent_store;
if (!path.empty()) {
// TODO(cef): Move directory creation to the blocking pool instead of
// allowing file IO on this thread.
base::ThreadRestrictions::ScopedAllowIO allow_io;
if (base::DirectoryExists(path) ||
base::CreateDirectory(path)) {
const base::FilePath& cookie_path = path.AppendASCII("Cookies");
persistent_store =
new content::SQLitePersistentCookieStore(
cookie_path,
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO),
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB),
persist_session_cookies,
NULL,
NULL);
} else {
NOTREACHED() << "The cookie storage directory could not be created";
}
}
// Set the new cookie store that will be used for all new requests. The old
// cookie store, if any, will be automatically flushed and closed when no
// longer referenced.
scoped_refptr<net::CookieMonster> cookie_monster =
new net::CookieMonster(persistent_store.get(), NULL);
storage_->set_cookie_store(cookie_monster.get());
if (persistent_store.get() && persist_session_cookies)
cookie_monster->SetPersistSessionCookies(true);
cookie_store_path_ = path;
// Restore the previously supported schemes.
SetCookieSupportedSchemes(cookie_supported_schemes_);
}
void CefURLRequestContextGetter::SetCookieSupportedSchemes(
const std::vector<std::string>& schemes) {
CEF_REQUIRE_IOT();
cookie_supported_schemes_ = schemes;
if (cookie_supported_schemes_.empty()) {
cookie_supported_schemes_.push_back("http");
cookie_supported_schemes_.push_back("https");
}
std::set<std::string> scheme_set;
std::vector<std::string>::const_iterator it =
cookie_supported_schemes_.begin();
for (; it != cookie_supported_schemes_.end(); ++it)
scheme_set.insert(*it);
const char** arr = new const char*[scheme_set.size()];
std::set<std::string>::const_iterator it2 = scheme_set.begin();
for (int i = 0; it2 != scheme_set.end(); ++it2, ++i)
arr[i] = it2->c_str();
url_request_context_->cookie_store()->GetCookieMonster()->
SetCookieableSchemes(arr, scheme_set.size());
delete [] arr;
}
CefURLRequestContextProxy*
CefURLRequestContextGetter::CreateURLRequestContextProxy() {
CEF_REQUIRE_IOT();
CefURLRequestContextProxy* proxy = new CefURLRequestContextProxy(this);
url_request_context_proxies_.insert(proxy);
return proxy;
}
void CefURLRequestContextGetter::ReleaseURLRequestContextProxy(
CefURLRequestContextProxy* proxy) {
CEF_REQUIRE_IOT();
// Don't do anything if we're currently shutting down. The proxy objects will
// be deleted when this object is destroyed.
if (CefContext::Get()->shutting_down())
return;
if (proxy->url_requests()->size() == 0) {
// Safe to delete the proxy.
RequestContextProxySet::iterator it =
url_request_context_proxies_.find(proxy);
DCHECK(it != url_request_context_proxies_.end());
url_request_context_proxies_.erase(it);
delete proxy;
} else {
proxy->increment_delete_try_count();
if (proxy->delete_try_count() <= 1) {
// Cancel the pending requests. This may result in additional tasks being
// posted on the IO thread.
std::set<const net::URLRequest*>::iterator it =
proxy->url_requests()->begin();
for (; it != proxy->url_requests()->end(); ++it)
const_cast<net::URLRequest*>(*it)->Cancel();
// Try to delete the proxy again later.
CEF_POST_TASK(CEF_IOT,
base::Bind(&CefURLRequestContextGetter::ReleaseURLRequestContextProxy,
this, proxy));
} else {
NOTREACHED() <<
"too many retries to delete URLRequestContext proxy object";
}
}
}
void CefURLRequestContextGetter::CreateProxyConfigService() {
if (proxy_config_service_.get())
return;
proxy_config_service_.reset(
net::ProxyService::CreateSystemProxyConfigService(
io_loop_->message_loop_proxy(), file_loop_->message_loop_proxy()));
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "libcef/browser/url_request_context_getter.h"
#if defined(OS_WIN)
#include <winhttp.h>
#endif
#include <string>
#include <vector>
#include "libcef/browser/content_browser_client.h"
#include "libcef/browser/context.h"
#include "libcef/browser/scheme_handler.h"
#include "libcef/browser/thread_util.h"
#include "libcef/browser/url_network_delegate.h"
#include "libcef/browser/url_request_context_proxy.h"
#include "libcef/browser/url_request_interceptor.h"
#include "libcef/common/cef_switches.h"
#include "libcef/common/content_client.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/worker_pool.h"
#include "chrome/browser/net/proxy_service_factory.h"
#include "content/browser/net/sqlite_persistent_cookie_store.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/cookie_crypto_delegate.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/url_constants.h"
#include "net/cert/cert_verifier.h"
#include "net/cookies/cookie_monster.h"
#include "net/dns/host_resolver.h"
#include "net/ftp/ftp_network_layer.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_cache.h"
#include "net/http/http_server_properties_impl.h"
#include "net/http/http_util.h"
#include "net/http/transport_security_state.h"
#include "net/proxy/proxy_service.h"
#include "net/ssl/channel_id_service.h"
#include "net/ssl/default_channel_id_store.h"
#include "net/ssl/ssl_config_service_defaults.h"
#include "url/url_constants.h"
#include "net/url_request/http_user_agent_settings.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_storage.h"
#include "net/url_request/url_request_intercepting_job_factory.h"
#include "net/url_request/url_request_job_factory_impl.h"
#include "net/url_request/url_request_job_manager.h"
#if defined(USE_NSS)
#include "net/ocsp/nss_ocsp.h"
#endif
using content::BrowserThread;
#if defined(OS_WIN)
#pragma comment(lib, "winhttp.lib")
#endif
namespace {
// An implementation of |HttpUserAgentSettings| that provides a static
// HTTP Accept-Language header value and uses |content::GetUserAgent|
// to provide the HTTP User-Agent header value.
class CefHttpUserAgentSettings : public net::HttpUserAgentSettings {
public:
explicit CefHttpUserAgentSettings(const std::string& raw_language_list)
: http_accept_language_(net::HttpUtil::GenerateAcceptLanguageHeader(
raw_language_list)) {
CEF_REQUIRE_IOT();
}
// net::HttpUserAgentSettings implementation
std::string GetAcceptLanguage() const override {
CEF_REQUIRE_IOT();
return http_accept_language_;
}
std::string GetUserAgent() const override {
CEF_REQUIRE_IOT();
return CefContentClient::Get()->GetUserAgent();
}
private:
const std::string http_accept_language_;
DISALLOW_COPY_AND_ASSIGN(CefHttpUserAgentSettings);
};
} // namespace
CefURLRequestContextGetter::CefURLRequestContextGetter(
base::MessageLoop* io_loop,
base::MessageLoop* file_loop,
content::ProtocolHandlerMap* protocol_handlers,
content::URLRequestInterceptorScopedVector request_interceptors)
: io_loop_(io_loop),
file_loop_(file_loop),
request_interceptors_(request_interceptors.Pass()) {
// Must first be created on the UI thread.
CEF_REQUIRE_UIT();
std::swap(protocol_handlers_, *protocol_handlers);
}
CefURLRequestContextGetter::~CefURLRequestContextGetter() {
CEF_REQUIRE_IOT();
STLDeleteElements(&url_request_context_proxies_);
// Delete the ProxyService object here so that any pending requests will be
// canceled before the associated URLRequestContext is destroyed in this
// object's destructor.
storage_->set_proxy_service(NULL);
}
net::URLRequestContext* CefURLRequestContextGetter::GetURLRequestContext() {
CEF_REQUIRE_IOT();
if (!url_request_context_.get()) {
const base::FilePath& cache_path = CefContext::Get()->cache_path();
const base::CommandLine* command_line =
base::CommandLine::ForCurrentProcess();
const CefSettings& settings = CefContext::Get()->settings();
url_request_context_.reset(new net::URLRequestContext());
storage_.reset(
new net::URLRequestContextStorage(url_request_context_.get()));
bool persist_session_cookies =
(settings.persist_session_cookies ||
command_line->HasSwitch(switches::kPersistSessionCookies));
SetCookieStoragePath(cache_path, persist_session_cookies);
storage_->set_network_delegate(new CefNetworkDelegate);
storage_->set_channel_id_service(new net::ChannelIDService(
new net::DefaultChannelIDStore(NULL),
base::WorkerPool::GetTaskRunner(true)));
storage_->set_http_user_agent_settings(
new CefHttpUserAgentSettings("en-us,en"));
storage_->set_host_resolver(net::HostResolver::CreateDefaultResolver(NULL));
storage_->set_cert_verifier(net::CertVerifier::CreateDefault());
storage_->set_transport_security_state(new net::TransportSecurityState);
scoped_ptr<net::ProxyService> system_proxy_service;
system_proxy_service.reset(
ProxyServiceFactory::CreateProxyService(
NULL,
url_request_context_.get(),
url_request_context_->network_delegate(),
CefContentBrowserClient::Get()->proxy_config_service().release(),
*command_line,
true));
storage_->set_proxy_service(system_proxy_service.release());
storage_->set_ssl_config_service(new net::SSLConfigServiceDefaults);
// Add support for single sign-on.
url_security_manager_.reset(net::URLSecurityManager::Create(NULL, NULL));
std::vector<std::string> supported_schemes;
supported_schemes.push_back("basic");
supported_schemes.push_back("digest");
supported_schemes.push_back("ntlm");
supported_schemes.push_back("negotiate");
storage_->set_http_auth_handler_factory(
net::HttpAuthHandlerRegistryFactory::Create(
supported_schemes,
url_security_manager_.get(),
url_request_context_->host_resolver(),
std::string(),
false,
false));
storage_->set_http_server_properties(
make_scoped_ptr<net::HttpServerProperties>(
new net::HttpServerPropertiesImpl));
net::HttpCache::DefaultBackend* main_backend =
new net::HttpCache::DefaultBackend(
cache_path.empty() ? net::MEMORY_CACHE : net::DISK_CACHE,
net::CACHE_BACKEND_DEFAULT,
cache_path,
0,
BrowserThread::GetMessageLoopProxyForThread(
BrowserThread::CACHE));
net::HttpNetworkSession::Params network_session_params;
network_session_params.host_resolver =
url_request_context_->host_resolver();
network_session_params.cert_verifier =
url_request_context_->cert_verifier();
network_session_params.transport_security_state =
url_request_context_->transport_security_state();
network_session_params.channel_id_service =
url_request_context_->channel_id_service();
network_session_params.proxy_service =
url_request_context_->proxy_service();
network_session_params.ssl_config_service =
url_request_context_->ssl_config_service();
network_session_params.http_auth_handler_factory =
url_request_context_->http_auth_handler_factory();
network_session_params.network_delegate =
url_request_context_->network_delegate();
network_session_params.http_server_properties =
url_request_context_->http_server_properties();
network_session_params.ignore_certificate_errors =
(settings.ignore_certificate_errors ||
command_line->HasSwitch(switches::kIgnoreCertificateErrors));
net::HttpCache* main_cache = new net::HttpCache(network_session_params,
main_backend);
storage_->set_http_transaction_factory(main_cache);
#if !defined(DISABLE_FTP_SUPPORT)
ftp_transaction_factory_.reset(
new net::FtpNetworkLayer(network_session_params.host_resolver));
#endif
scoped_ptr<net::URLRequestJobFactoryImpl> job_factory(
new net::URLRequestJobFactoryImpl());
job_factory_impl_ = job_factory.get();
scheme::InstallInternalProtectedHandlers(job_factory.get(),
&protocol_handlers_,
ftp_transaction_factory_.get());
protocol_handlers_.clear();
request_interceptors_.push_back(new CefRequestInterceptor());
// Set up interceptors in the reverse order.
scoped_ptr<net::URLRequestJobFactory> top_job_factory =
job_factory.Pass();
for (content::URLRequestInterceptorScopedVector::reverse_iterator i =
request_interceptors_.rbegin();
i != request_interceptors_.rend();
++i) {
top_job_factory.reset(new net::URLRequestInterceptingJobFactory(
top_job_factory.Pass(), make_scoped_ptr(*i)));
}
request_interceptors_.weak_clear();
storage_->set_job_factory(top_job_factory.release());
#if defined(USE_NSS)
net::SetURLRequestContextForNSSHttpIO(url_request_context_.get());
#endif
}
return url_request_context_.get();
}
scoped_refptr<base::SingleThreadTaskRunner>
CefURLRequestContextGetter::GetNetworkTaskRunner() const {
return BrowserThread::GetMessageLoopProxyForThread(CEF_IOT);
}
net::HostResolver* CefURLRequestContextGetter::host_resolver() {
return url_request_context_->host_resolver();
}
void CefURLRequestContextGetter::SetCookieStoragePath(
const base::FilePath& path,
bool persist_session_cookies) {
CEF_REQUIRE_IOT();
if (url_request_context_->cookie_store() &&
((cookie_store_path_.empty() && path.empty()) ||
cookie_store_path_ == path)) {
// The path has not changed so don't do anything.
return;
}
scoped_refptr<content::SQLitePersistentCookieStore> persistent_store;
if (!path.empty()) {
// TODO(cef): Move directory creation to the blocking pool instead of
// allowing file IO on this thread.
base::ThreadRestrictions::ScopedAllowIO allow_io;
if (base::DirectoryExists(path) ||
base::CreateDirectory(path)) {
const base::FilePath& cookie_path = path.AppendASCII("Cookies");
persistent_store =
new content::SQLitePersistentCookieStore(
cookie_path,
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO),
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB),
persist_session_cookies,
NULL,
NULL);
} else {
NOTREACHED() << "The cookie storage directory could not be created";
}
}
// Set the new cookie store that will be used for all new requests. The old
// cookie store, if any, will be automatically flushed and closed when no
// longer referenced.
scoped_refptr<net::CookieMonster> cookie_monster =
new net::CookieMonster(persistent_store.get(), NULL);
storage_->set_cookie_store(cookie_monster.get());
if (persistent_store.get() && persist_session_cookies)
cookie_monster->SetPersistSessionCookies(true);
cookie_store_path_ = path;
// Restore the previously supported schemes.
SetCookieSupportedSchemes(cookie_supported_schemes_);
}
void CefURLRequestContextGetter::SetCookieSupportedSchemes(
const std::vector<std::string>& schemes) {
CEF_REQUIRE_IOT();
cookie_supported_schemes_ = schemes;
if (cookie_supported_schemes_.empty()) {
cookie_supported_schemes_.push_back("http");
cookie_supported_schemes_.push_back("https");
}
std::set<std::string> scheme_set;
std::vector<std::string>::const_iterator it =
cookie_supported_schemes_.begin();
for (; it != cookie_supported_schemes_.end(); ++it)
scheme_set.insert(*it);
const char** arr = new const char*[scheme_set.size()];
std::set<std::string>::const_iterator it2 = scheme_set.begin();
for (int i = 0; it2 != scheme_set.end(); ++it2, ++i)
arr[i] = it2->c_str();
url_request_context_->cookie_store()->GetCookieMonster()->
SetCookieableSchemes(arr, scheme_set.size());
delete [] arr;
}
CefURLRequestContextProxy*
CefURLRequestContextGetter::CreateURLRequestContextProxy() {
CEF_REQUIRE_IOT();
CefURLRequestContextProxy* proxy = new CefURLRequestContextProxy(this);
url_request_context_proxies_.insert(proxy);
return proxy;
}
void CefURLRequestContextGetter::ReleaseURLRequestContextProxy(
CefURLRequestContextProxy* proxy) {
CEF_REQUIRE_IOT();
// Don't do anything if we're currently shutting down. The proxy objects will
// be deleted when this object is destroyed.
if (CefContext::Get()->shutting_down())
return;
if (proxy->url_requests()->size() == 0) {
// Safe to delete the proxy.
RequestContextProxySet::iterator it =
url_request_context_proxies_.find(proxy);
DCHECK(it != url_request_context_proxies_.end());
url_request_context_proxies_.erase(it);
delete proxy;
} else {
proxy->increment_delete_try_count();
if (proxy->delete_try_count() <= 1) {
// Cancel the pending requests. This may result in additional tasks being
// posted on the IO thread.
std::set<const net::URLRequest*>::iterator it =
proxy->url_requests()->begin();
for (; it != proxy->url_requests()->end(); ++it)
const_cast<net::URLRequest*>(*it)->Cancel();
// Try to delete the proxy again later.
CEF_POST_TASK(CEF_IOT,
base::Bind(&CefURLRequestContextGetter::ReleaseURLRequestContextProxy,
this, proxy));
} else {
NOTREACHED() <<
"too many retries to delete URLRequestContext proxy object";
}
}
}
void CefURLRequestContextGetter::CreateProxyConfigService() {
if (proxy_config_service_.get())
return;
proxy_config_service_.reset(
net::ProxyService::CreateSystemProxyConfigService(
io_loop_->message_loop_proxy(), file_loop_->message_loop_proxy()));
}
|
Fix "No URLRequestContext for NSS HTTP handler" error (issue #1490).
|
Linux: Fix "No URLRequestContext for NSS HTTP handler" error (issue #1490).
git-svn-id: 4ff65e90c7c89c8f5eba592fcee26b49aecf64bc@1978 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
|
C++
|
bsd-3-clause
|
svn2github/ttserver,svn2github/ttserver,svn2github/midle110,svn2github/cef3,svn2github/midle110,svn2github/ttserver,svn2github/midle110,svn2github/cef3,svn2github/cef3,svn2github/cef3,svn2github/midle110,svn2github/ttserver,svn2github/cef3,svn2github/midle110,svn2github/ttserver
|
0d1160fa6bd2bdda26e9ec9c756ed254ba0ddfd9
|
libvast/test/system/indexer_stage_driver.cpp
|
libvast/test/system/indexer_stage_driver.cpp
|
/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#define SUITE indexer_stage_driver
#include "test.hpp"
#include <random>
#include <vector>
#include "vast/const_table_slice_handle.hpp"
#include "vast/detail/spawn_container_source.hpp"
#include "vast/meta_index.hpp"
#include "vast/system/indexer_stage_driver.hpp"
#include "vast/system/partition.hpp"
#include "vast/table_slice_handle.hpp"
#include "vast/uuid.hpp"
#include "fixtures/actor_system_and_events.hpp"
using namespace caf;
using namespace vast;
using namespace vast::system;
using std::shared_ptr;
using std::make_shared;
namespace {
using event_buffer = std::vector<event>;
using shared_event_buffer = shared_ptr<event_buffer>;
using shared_event_buffer_vector = std::vector<shared_event_buffer>;
behavior dummy_sink(event_based_actor* self, size_t* dummy_sink_count,
shared_event_buffer buf) {
*dummy_sink_count += 1;
return {
[=](stream<const_table_slice_handle> in) {
self->make_sink(
in,
[=](unit_t&) {
// nop
},
[=](unit_t&, const_table_slice_handle slice) {
auto xs = slice->rows_to_events();
for (auto& x : xs)
buf->emplace_back(std::move(x));
}
);
self->unbecome();
}
};
}
auto partition_factory(actor_system& sys, path p, size_t* dummy_count,
shared_ptr<shared_event_buffer_vector> bufs) {
return [=, &sys] {
bufs->emplace_back(std::make_shared<event_buffer>());
auto buf = bufs->back();
auto sink_factory = [=, &sys](path, type) -> actor {
return sys.spawn(dummy_sink, dummy_count, buf);
};
auto id = uuid::random();
return make_partition(p, std::move(id), sink_factory);
};
}
behavior test_stage(event_based_actor* self, meta_index* pi,
indexer_stage_driver::partition_factory f, size_t mps) {
return {[=](stream<const_table_slice_handle> in) {
auto mgr = self->make_continuous_stage<indexer_stage_driver>(*pi, f, mps);
mgr->add_inbound_path(in);
self->unbecome();
}};
}
struct fixture : fixtures::deterministic_actor_system_and_events {
fixture() {
/// Only needed for computing how many layouts are in our data set.
std::set<record_type> layouts;
/// Makes sure no persistet state exists.
rm(state_dir);
// Pick slices from various data sets.
auto pick_from = [&](const auto& slices) {
VAST_ASSERT(slices.size() > 0);
test_slices.emplace_back(slices[0]);
layouts.emplace(slices[0]->layout());
};
pick_from(bro_conn_log_slices);
pick_from(ascending_integers_slices);
/// TODO: uncomment when resolving [ch3215]
/// pick_from(bro_http_log_slices);
/// pick_from(bgpdump_txt_slices);
/// pick_from(random_slices);
num_layouts = layouts.size();
REQUIRE_EQUAL(test_slices.size(), num_layouts);
}
/// Directory where the manager is supposed to persist its state.
path state_dir = directory / "indexer-manager";
meta_index pindex;
std::vector<const_table_slice_handle> test_slices;
size_t num_layouts;
};
} // namespace <anonymous>
FIXTURE_SCOPE(indexer_stage_driver_tests, fixture)
TEST(spawning sinks automatically) {
MESSAGE("spawn the stage");
auto dummies = size_t{0};
auto bufs = make_shared<shared_event_buffer_vector>();
auto stg = sys.spawn(test_stage, &pindex,
partition_factory(sys, state_dir, &dummies, bufs),
std::numeric_limits<size_t>::max());
MESSAGE("spawn the source and run");
auto src = vast::detail::spawn_container_source(self->system(),
test_slices, stg);
run_exhaustively();
CHECK_EQUAL(dummies, num_layouts);
MESSAGE("check content of the shared buffer");
REQUIRE_EQUAL(bufs->size(), 1u);
auto& buf = bufs->back();
CHECK_EQUAL(test_slices.size() * slice_size, buf->size());
std::sort(test_slices.begin(), test_slices.end());
std::sort(buf->begin(), buf->end());
CHECK_EQUAL(test_slices, *buf);
anon_send_exit(stg, exit_reason::user_shutdown);
}
TEST(creating bro conn log partitions automatically) {
MESSAGE("spawn the stage");
auto dummies = size_t{0};
auto bufs = make_shared<shared_event_buffer_vector>();
auto stg = sys.spawn(test_stage, &pindex,
partition_factory(sys, state_dir, &dummies, bufs),
slice_size);
MESSAGE("spawn the source and run");
auto src = vast::detail::spawn_container_source(self->system(),
const_bro_conn_log_slices,
stg);
run_exhaustively();
CHECK_EQUAL(bufs->size(), const_bro_conn_log_slices.size());
MESSAGE("flatten all partitions into one buffer");
event_buffer xs;
for (auto& buf : *bufs)
xs.insert(xs.end(), buf->begin(), buf->end());
CHECK_EQUAL(bro_conn_log.size(), xs.size());
std::sort(xs.begin(), xs.end());
auto ys = bro_conn_log;
std::sort(ys.begin(), ys.end());
REQUIRE_EQUAL(xs.size(), ys.size());
for (size_t i = 0; i < xs.size(); ++i)
CHECK_EQUAL(xs[i], flatten(ys[i]));
anon_send_exit(stg, exit_reason::user_shutdown);
}
FIXTURE_SCOPE_END()
|
/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#define SUITE indexer_stage_driver
#include "test.hpp"
#include <random>
#include <vector>
#include "vast/const_table_slice_handle.hpp"
#include "vast/detail/spawn_container_source.hpp"
#include "vast/meta_index.hpp"
#include "vast/system/indexer_stage_driver.hpp"
#include "vast/system/partition.hpp"
#include "vast/table_slice_handle.hpp"
#include "vast/uuid.hpp"
#include "vast/concept/printable/to_string.hpp"
#include "fixtures/actor_system_and_events.hpp"
using namespace caf;
using namespace vast;
using namespace vast::system;
using std::shared_ptr;
using std::make_shared;
namespace {
using event_buffer = std::vector<event>;
using shared_event_buffer = shared_ptr<event_buffer>;
using shared_event_buffer_vector = std::vector<shared_event_buffer>;
behavior dummy_sink(event_based_actor* self, size_t* dummy_sink_count,
shared_event_buffer buf) {
*dummy_sink_count += 1;
return {
[=](stream<const_table_slice_handle> in) {
self->make_sink(
in,
[=](unit_t&) {
// nop
},
[=](unit_t&, const_table_slice_handle slice) {
auto xs = slice->rows_to_events();
for (auto& x : xs)
buf->emplace_back(std::move(x));
}
);
self->unbecome();
}
};
}
auto partition_factory(actor_system& sys, path p, size_t* dummy_count,
shared_ptr<shared_event_buffer_vector> bufs) {
return [=, &sys] {
bufs->emplace_back(std::make_shared<event_buffer>());
auto buf = bufs->back();
auto sink_factory = [=, &sys](path, type) -> actor {
return sys.spawn(dummy_sink, dummy_count, buf);
};
auto id = uuid::random();
return make_partition(p, std::move(id), sink_factory);
};
}
behavior test_stage(event_based_actor* self, meta_index* pi,
indexer_stage_driver::partition_factory f, size_t mps) {
return {[=](stream<const_table_slice_handle> in) {
auto mgr = self->make_continuous_stage<indexer_stage_driver>(*pi, f, mps);
mgr->add_inbound_path(in);
self->unbecome();
}};
}
struct fixture : fixtures::deterministic_actor_system_and_events {
fixture() {
/// Only needed for computing how many layouts are in our data set.
std::set<record_type> layouts;
/// Makes sure no persistet state exists.
rm(state_dir);
// Pick slices from various data sets.
auto pick_from = [&](const auto& slices) {
VAST_ASSERT(slices.size() > 0);
test_slices.emplace_back(slices[0]);
layouts.emplace(slices[0]->layout());
};
pick_from(bro_conn_log_slices);
pick_from(ascending_integers_slices);
/// TODO: uncomment when resolving [ch3215]
/// pick_from(bro_http_log_slices);
/// pick_from(bgpdump_txt_slices);
/// pick_from(random_slices);
num_layouts = layouts.size();
REQUIRE_EQUAL(test_slices.size(), num_layouts);
}
/// Directory where the manager is supposed to persist its state.
path state_dir = directory / "indexer-manager";
meta_index pindex;
std::vector<const_table_slice_handle> test_slices;
size_t num_layouts;
};
} // namespace <anonymous>
FIXTURE_SCOPE(indexer_stage_driver_tests, fixture)
TEST(spawning sinks automatically) {
MESSAGE("spawn the stage");
auto dummies = size_t{0};
auto bufs = make_shared<shared_event_buffer_vector>();
auto stg = sys.spawn(test_stage, &pindex,
partition_factory(sys, state_dir, &dummies, bufs),
std::numeric_limits<size_t>::max());
MESSAGE("spawn the source and run");
auto src = vast::detail::spawn_container_source(self->system(),
test_slices, stg);
run_exhaustively();
CHECK_EQUAL(dummies, num_layouts);
MESSAGE("check content of the shared buffer");
REQUIRE_EQUAL(bufs->size(), 1u);
auto& buf = bufs->back();
CHECK_EQUAL(test_slices.size() * slice_size, buf->size());
std::sort(test_slices.begin(), test_slices.end());
std::sort(buf->begin(), buf->end());
CHECK_EQUAL(test_slices, *buf);
anon_send_exit(stg, exit_reason::user_shutdown);
}
TEST(creating bro conn log partitions automatically) {
MESSAGE("spawn the stage");
auto dummies = size_t{0};
auto bufs = make_shared<shared_event_buffer_vector>();
auto stg = sys.spawn(test_stage, &pindex,
partition_factory(sys, state_dir, &dummies, bufs),
slice_size);
MESSAGE("spawn the source and run");
auto src = vast::detail::spawn_container_source(self->system(),
const_bro_conn_log_slices,
stg);
run_exhaustively();
CHECK_EQUAL(bufs->size(), const_bro_conn_log_slices.size());
MESSAGE("flatten all partitions into one buffer");
event_buffer xs;
for (auto& buf : *bufs)
xs.insert(xs.end(), buf->begin(), buf->end());
CHECK_EQUAL(bro_conn_log.size(), xs.size());
std::sort(xs.begin(), xs.end());
auto ys = bro_conn_log;
std::sort(ys.begin(), ys.end());
REQUIRE_EQUAL(xs.size(), ys.size());
for (size_t i = 0; i < xs.size(); ++i)
CHECK_EQUAL(xs[i], flatten(ys[i]));
anon_send_exit(stg, exit_reason::user_shutdown);
}
FIXTURE_SCOPE_END()
|
Fix inexplicable to_string unit test anomaly
|
Fix inexplicable to_string unit test anomaly
|
C++
|
bsd-3-clause
|
mavam/vast,vast-io/vast,mavam/vast,vast-io/vast,mavam/vast,vast-io/vast,vast-io/vast,vast-io/vast,mavam/vast
|
c559d9f4ea2ac2aa86e473b80f49d2f88404ee7c
|
include/etl/expr/bias_batch_mean_expr.hpp
|
include/etl/expr/bias_batch_mean_expr.hpp
|
//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include "etl/expr/base_temporary_expr.hpp"
namespace etl {
/*!
* \brief A transposition expression.
* \tparam A The transposed type
*/
template <typename A>
struct bias_batch_mean_expr : base_temporary_expr_un<bias_batch_mean_expr<A>, A> {
using value_type = value_t<A>; ///< The type of value of the expression
using this_type = bias_batch_mean_expr<A>; ///< The type of this expression
using base_type = base_temporary_expr_un<this_type, A>; ///< The base type
using sub_traits = decay_traits<A>; ///< The traits of the sub type
static constexpr auto storage_order = sub_traits::storage_order; ///< The sub storage order
/*!
* \brief Construct a new expression
* \param a The sub expression
*/
explicit bias_batch_mean_expr(A a) : base_type(a) {
//Nothing else to init
}
/*!
* \brief Validate the transposition dimensions
* \param a The input matrix
* \þaram c The output matrix
*/
template <typename C, cpp_enable_if(all_fast<A,C>::value)>
static void check(const A& a, const C& c) {
cpp_unused(a);
cpp_unused(c);
static_assert(etl::dimensions<C>() == 1, "The output of bias_batch_mean is a vector");
static_assert(etl::dimensions<A>() == 4, "The input of bias_batch_mean is a 4D matrix");
static_assert(etl::dim<1, A>() == etl::dim<0, C>(), "Invalid dimensions for bias_batch_mean");
}
/*!
* \brief Validate the transposition dimensions
* \param a The input matrix
* \þaram c The output matrix
*/
template <typename C, cpp_disable_if(all_fast<A,C>::value)>
static void check(const A& a, const C& c) {
static_assert(etl::dimensions<C>() == 1, "The output of bias_batch_mean is a vector");
static_assert(etl::dimensions<A>() == 4, "The input of bias_batch_mean is a 4D matrix");
cpp_assert(etl::dim<1>(a) == etl::dim<0>(c), "Invalid dimensions for bias_batch_mean");
cpp_unused(a);
cpp_unused(c);
}
/*!
* \brief Apply the expression
* \param a The input
* \param c The expression where to store the results
*/
template <typename C>
static void apply(const A& a, C&& c) {
static_assert(all_etl_expr<A, C>::value, "Transpose only supported for ETL expressions");
const auto N = etl::size(a) / etl::size(c);
const auto K = etl::size(c);
using T = value_t<A>;
check(a, c);
auto batch_fun_k = [&](const size_t first, const size_t last) {
if (last - first) {
SERIAL_SECTION {
for (size_t k = first; k < last; ++k) {
T mean(0);
for (size_t b = 0; b < etl::dim<0>(a); ++b) {
mean += sum(a(b)(k));
}
c(k) = mean / N;
}
}
}
};
smart_dispatch_1d_any(batch_fun_k, 0, K, 2);
}
// Assignment functions
/*!
* \brief Assign to a matrix of the same storage order
* \param lhs The expression to which assign
*/
template<typename L>
void assign_to(L&& lhs) const {
standard_evaluator::pre_assign_rhs(this->a());
standard_evaluator::pre_assign_lhs(lhs);
this->apply_base(lhs);
}
/*!
* \brief Add to the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_add_to(L&& lhs) const {
std_add_evaluate(*this, lhs);
}
/*!
* \brief Sub from the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_sub_to(L&& lhs) const {
std_sub_evaluate(*this, lhs);
}
/*!
* \brief Multiply the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_mul_to(L&& lhs) const {
std_mul_evaluate(*this, lhs);
}
/*!
* \brief Divide the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_div_to(L&& lhs) const {
std_div_evaluate(*this, lhs);
}
/*!
* \brief Modulo the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_mod_to(L&& lhs) const {
std_mod_evaluate(*this, lhs);
}
};
/*!
* \brief Traits for a transpose expression
* \tparam A The transposed sub type
*/
template <typename A>
struct etl_traits<etl::bias_batch_mean_expr<A>> {
using expr_t = etl::bias_batch_mean_expr<A>; ///< The expression type
using sub_expr_t = std::decay_t<A>; ///< The sub expression type
using sub_traits = etl_traits<sub_expr_t>; ///< The sub traits
using value_type = value_t<A>; ///< The value type of the expression
static constexpr bool is_etl = true; ///< Indicates if the type is an ETL expression
static constexpr bool is_transformer = false; ///< Indicates if the type is a transformer
static constexpr bool is_view = false; ///< Indicates if the type is a view
static constexpr bool is_magic_view = false; ///< Indicates if the type is a magic view
static constexpr bool is_fast = sub_traits::is_fast; ///< Indicates if the expression is fast
static constexpr bool is_linear = true; ///< Indicates if the expression is linear
static constexpr bool is_thread_safe = true; ///< Indicates if the expression is thread safe
static constexpr bool is_value = false; ///< Indicates if the expression is of value type
static constexpr bool is_direct = true; ///< Indicates if the expression has direct memory access
static constexpr bool is_generator = false; ///< Indicates if the expression is a generator
static constexpr bool is_padded = false; ///< Indicates if the expression is padded
static constexpr bool is_aligned = true; ///< Indicates if the expression is padded
static constexpr bool is_gpu = false; ///< Indicates if the expression can be done on GPU
static constexpr bool needs_evaluator_visitor = true; ///< Indicates if the expression needs a evaluator visitor
static constexpr order storage_order = sub_traits::storage_order; ///< The expression's storage order
/*!
* \brief Indicates if the expression is vectorizable using the
* given vector mode
* \tparam V The vector mode
*/
template <vector_mode_t V>
using vectorizable = std::true_type;
/*!
* \brief Returns the DDth dimension of the expression
* \return the DDth dimension of the expression
*/
template <std::size_t DD>
static constexpr std::size_t dim() {
static_assert(DD == 0, "Invalid dimensions access");
return decay_traits<A>::template dim<1>();
}
/*!
* \brief Returns the dth dimension of the expression
* \param e The sub expression
* \param d The dimension to get
* \return the dth dimension of the expression
*/
static std::size_t dim(const expr_t& e, std::size_t d) {
cpp_assert(d == 0, "Invalid dimensions access");
return etl::dim<1>(e._a);
}
/*!
* \brief Returns the size of the expression
* \param e The sub expression
* \return the size of the expression
*/
static std::size_t size(const expr_t& e) {
return etl::dim<1>(e._a);
}
/*!
* \brief Returns the size of the expression
* \return the size of the expression
*/
static constexpr std::size_t size() {
return decay_traits<A>::template dim<1>();
}
/*!
* \brief Returns the number of dimensions of the expression
* \return the number of dimensions of the expression
*/
static constexpr std::size_t dimensions() {
return 1;
}
};
} //end of namespace etl
|
//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include "etl/expr/base_temporary_expr.hpp"
namespace etl {
/*!
* \brief A transposition expression.
* \tparam A The transposed type
*/
template <typename A>
struct bias_batch_mean_expr : base_temporary_expr_un<bias_batch_mean_expr<A>, A> {
using value_type = value_t<A>; ///< The type of value of the expression
using this_type = bias_batch_mean_expr<A>; ///< The type of this expression
using base_type = base_temporary_expr_un<this_type, A>; ///< The base type
using sub_traits = decay_traits<A>; ///< The traits of the sub type
static constexpr auto storage_order = sub_traits::storage_order; ///< The sub storage order
/*!
* \brief Construct a new expression
* \param a The sub expression
*/
explicit bias_batch_mean_expr(A a) : base_type(a) {
//Nothing else to init
}
/*!
* \brief Validate the transposition dimensions
* \param a The input matrix
* \þaram c The output matrix
*/
template <typename C, cpp_enable_if(all_fast<A,C>::value)>
static void check(const A& a, const C& c) {
cpp_unused(a);
cpp_unused(c);
static_assert(etl::dimensions<C>() == 1, "The output of bias_batch_mean is a vector");
static_assert(etl::dimensions<A>() == 4, "The input of bias_batch_mean is a 4D matrix");
static_assert(etl::dim<1, A>() == etl::dim<0, C>(), "Invalid dimensions for bias_batch_mean");
}
/*!
* \brief Validate the transposition dimensions
* \param a The input matrix
* \þaram c The output matrix
*/
template <typename C, cpp_disable_if(all_fast<A,C>::value)>
static void check(const A& a, const C& c) {
static_assert(etl::dimensions<C>() == 1, "The output of bias_batch_mean is a vector");
static_assert(etl::dimensions<A>() == 4, "The input of bias_batch_mean is a 4D matrix");
cpp_assert(etl::dim<1>(a) == etl::dim<0>(c), "Invalid dimensions for bias_batch_mean");
cpp_unused(a);
cpp_unused(c);
}
/*!
* \brief Apply the expression
* \param a The input
* \param c The expression where to store the results
*/
template <typename C>
static void apply(const A& a, C&& c) {
static_assert(all_etl_expr<A, C>::value, "Transpose only supported for ETL expressions");
const auto N = etl::size(a) / etl::size(c);
const auto K = etl::size(c);
using T = value_t<A>;
check(a, c);
auto batch_fun_k = [&](const size_t first, const size_t last) {
if (last - first) {
SERIAL_SECTION {
for (size_t k = first; k < last; ++k) {
T mean(0);
for (size_t b = 0; b < etl::dim<0>(a); ++b) {
mean += sum(a(b)(k));
}
c(k) = mean / N;
}
}
}
};
engine_dispatch_1d(batch_fun_k, 0, K, 2);
}
// Assignment functions
/*!
* \brief Assign to a matrix of the same storage order
* \param lhs The expression to which assign
*/
template<typename L>
void assign_to(L&& lhs) const {
standard_evaluator::pre_assign_rhs(this->a());
standard_evaluator::pre_assign_lhs(lhs);
this->apply_base(lhs);
}
/*!
* \brief Add to the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_add_to(L&& lhs) const {
std_add_evaluate(*this, lhs);
}
/*!
* \brief Sub from the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_sub_to(L&& lhs) const {
std_sub_evaluate(*this, lhs);
}
/*!
* \brief Multiply the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_mul_to(L&& lhs) const {
std_mul_evaluate(*this, lhs);
}
/*!
* \brief Divide the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_div_to(L&& lhs) const {
std_div_evaluate(*this, lhs);
}
/*!
* \brief Modulo the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_mod_to(L&& lhs) const {
std_mod_evaluate(*this, lhs);
}
};
/*!
* \brief Traits for a transpose expression
* \tparam A The transposed sub type
*/
template <typename A>
struct etl_traits<etl::bias_batch_mean_expr<A>> {
using expr_t = etl::bias_batch_mean_expr<A>; ///< The expression type
using sub_expr_t = std::decay_t<A>; ///< The sub expression type
using sub_traits = etl_traits<sub_expr_t>; ///< The sub traits
using value_type = value_t<A>; ///< The value type of the expression
static constexpr bool is_etl = true; ///< Indicates if the type is an ETL expression
static constexpr bool is_transformer = false; ///< Indicates if the type is a transformer
static constexpr bool is_view = false; ///< Indicates if the type is a view
static constexpr bool is_magic_view = false; ///< Indicates if the type is a magic view
static constexpr bool is_fast = sub_traits::is_fast; ///< Indicates if the expression is fast
static constexpr bool is_linear = true; ///< Indicates if the expression is linear
static constexpr bool is_thread_safe = true; ///< Indicates if the expression is thread safe
static constexpr bool is_value = false; ///< Indicates if the expression is of value type
static constexpr bool is_direct = true; ///< Indicates if the expression has direct memory access
static constexpr bool is_generator = false; ///< Indicates if the expression is a generator
static constexpr bool is_padded = false; ///< Indicates if the expression is padded
static constexpr bool is_aligned = true; ///< Indicates if the expression is padded
static constexpr bool is_gpu = false; ///< Indicates if the expression can be done on GPU
static constexpr bool needs_evaluator_visitor = true; ///< Indicates if the expression needs a evaluator visitor
static constexpr order storage_order = sub_traits::storage_order; ///< The expression's storage order
/*!
* \brief Indicates if the expression is vectorizable using the
* given vector mode
* \tparam V The vector mode
*/
template <vector_mode_t V>
using vectorizable = std::true_type;
/*!
* \brief Returns the DDth dimension of the expression
* \return the DDth dimension of the expression
*/
template <std::size_t DD>
static constexpr std::size_t dim() {
static_assert(DD == 0, "Invalid dimensions access");
return decay_traits<A>::template dim<1>();
}
/*!
* \brief Returns the dth dimension of the expression
* \param e The sub expression
* \param d The dimension to get
* \return the dth dimension of the expression
*/
static std::size_t dim(const expr_t& e, std::size_t d) {
cpp_assert(d == 0, "Invalid dimensions access");
return etl::dim<1>(e._a);
}
/*!
* \brief Returns the size of the expression
* \param e The sub expression
* \return the size of the expression
*/
static std::size_t size(const expr_t& e) {
return etl::dim<1>(e._a);
}
/*!
* \brief Returns the size of the expression
* \return the size of the expression
*/
static constexpr std::size_t size() {
return decay_traits<A>::template dim<1>();
}
/*!
* \brief Returns the number of dimensions of the expression
* \return the number of dimensions of the expression
*/
static constexpr std::size_t dimensions() {
return 1;
}
};
} //end of namespace etl
|
Use the new engine
|
Use the new engine
|
C++
|
mit
|
wichtounet/etl,wichtounet/etl
|
3a62df38ebc33f737332b7674a5c5bfb689a5188
|
libvast/vast/concept/printable/vast/data.hpp
|
libvast/vast/concept/printable/vast/data.hpp
|
/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#pragma once
#include "vast/data.hpp"
#include "vast/detail/string.hpp"
#include "vast/concept/printable/numeric.hpp"
#include "vast/concept/printable/print.hpp"
#include "vast/concept/printable/string.hpp"
#include "vast/concept/printable/core/printer.hpp"
#include "vast/concept/printable/std/chrono.hpp"
#include "vast/concept/printable/vast/address.hpp"
#include "vast/concept/printable/vast/subnet.hpp"
#include "vast/concept/printable/vast/pattern.hpp"
#include "vast/concept/printable/vast/port.hpp"
#include "vast/concept/printable/vast/none.hpp"
#include "vast/concept/printable/vast/type.hpp"
namespace vast {
struct data_printer : printer<data_printer> {
using attribute = data;
template <class Iterator>
struct visitor {
visitor(Iterator& out) : out_{out} {
}
template <class T>
bool operator()(const T& x) const {
return make_printer<T>{}(out_, x);
}
bool operator()(integer x) const {
return printers::integral<integer, policy::force_sign>(out_, x);
}
bool operator()(const std::string& str) const {
// TODO: create a printer that escapes the output on the fly, as opposed
// to going through an extra copy.
auto escaped = printers::str ->* [](const std::string& x) {
return detail::byte_escape(x, "\"");
};
auto p = '"' << escaped << '"';
return p(out_, str);
}
Iterator& out_;
};
template <class Iterator>
bool print(Iterator& out, const data& d) const {
return visit(visitor<Iterator>{out}, d);
}
};
template <>
struct printer_registry<data> {
using type = data_printer;
};
namespace printers {
auto const data = data_printer{};
} // namespace printers
struct vector_printer : printer<vector_printer> {
using attribute = vector;
template <class Iterator>
bool print(Iterator& out, const vector& v) const {
auto p = '[' << ~(data_printer{} % ", ") << ']';
return p.print(out, v);
}
};
template <>
struct printer_registry<vector> {
using type = vector_printer;
};
struct set_printer : printer<set_printer> {
using attribute = set;
template <class Iterator>
bool print(Iterator& out, const set& s) const {
auto p = '{' << ~(data_printer{} % ", ") << '}';
return p.print(out, s);
}
};
template <>
struct printer_registry<set> {
using type = set_printer;
};
struct table_printer : printer<table_printer> {
using attribute = map;
template <class Iterator>
bool print(Iterator& out, const map& t) const {
auto pair = (data_printer{} << " -> " << data_printer{});
auto p = '{' << ~(pair % ", ") << '}';
return p.print(out, t);
}
};
template <>
struct printer_registry<map> {
using type = table_printer;
};
} // namespace vast
|
/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#pragma once
#include "vast/data.hpp"
#include "vast/detail/string.hpp"
#include "vast/concept/printable/numeric.hpp"
#include "vast/concept/printable/print.hpp"
#include "vast/concept/printable/string.hpp"
#include "vast/concept/printable/core/printer.hpp"
#include "vast/concept/printable/std/chrono.hpp"
#include "vast/concept/printable/vast/address.hpp"
#include "vast/concept/printable/vast/subnet.hpp"
#include "vast/concept/printable/vast/pattern.hpp"
#include "vast/concept/printable/vast/port.hpp"
#include "vast/concept/printable/vast/none.hpp"
#include "vast/concept/printable/vast/type.hpp"
namespace vast {
struct data_printer : printer<data_printer> {
using attribute = data;
template <class Iterator>
struct visitor {
visitor(Iterator& out) : out_{out} {
}
template <class T>
bool operator()(const T& x) const {
return make_printer<T>{}(out_, x);
}
bool operator()(integer x) const {
return printers::integral<integer, policy::force_sign>(out_, x);
}
bool operator()(const std::string& str) const {
// TODO: create a printer that escapes the output on the fly, as opposed
// to going through an extra copy.
auto escaped = printers::str ->* [](const std::string& x) {
return detail::byte_escape(x, "\"");
};
auto p = '"' << escaped << '"';
return p(out_, str);
}
Iterator& out_;
};
template <class Iterator>
bool print(Iterator& out, const data& d) const {
return visit(visitor<Iterator>{out}, d);
}
};
template <>
struct printer_registry<data> {
using type = data_printer;
};
namespace printers {
auto const data = data_printer{};
} // namespace printers
struct vector_printer : printer<vector_printer> {
using attribute = vector;
template <class Iterator>
bool print(Iterator& out, const vector& v) const {
auto p = '[' << ~(data_printer{} % ", ") << ']';
return p.print(out, v);
}
};
template <>
struct printer_registry<vector> {
using type = vector_printer;
};
struct set_printer : printer<set_printer> {
using attribute = set;
template <class Iterator>
bool print(Iterator& out, const set& s) const {
auto p = '{' << ~(data_printer{} % ", ") << '}';
return p.print(out, s);
}
};
template <>
struct printer_registry<set> {
using type = set_printer;
};
struct map_printer : printer<map_printer> {
using attribute = map;
template <class Iterator>
bool print(Iterator& out, const map& t) const {
auto pair = (data_printer{} << " -> " << data_printer{});
auto p = '{' << ~(pair % ", ") << '}';
return p.print(out, t);
}
};
template <>
struct printer_registry<map> {
using type = map_printer;
};
} // namespace vast
|
Rename table_printer to map_printer
|
Rename table_printer to map_printer
|
C++
|
bsd-3-clause
|
mavam/vast,mavam/vast,vast-io/vast,vast-io/vast,mavam/vast,mavam/vast,vast-io/vast,vast-io/vast,vast-io/vast
|
ebd11104b62e3118a08115bf23a093f992e1171e
|
engine/tests/test_rule_inject.cpp
|
engine/tests/test_rule_inject.cpp
|
// Licensed to Qualys, Inc. (QUALYS) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// QUALYS 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.
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
/// @file
/// @brief IronBee --- Rule inject tests
///
/// @author Nick LeRoy <[email protected]>
//////////////////////////////////////////////////////////////////////////////
#include "gtest/gtest.h"
#include "base_fixture.h"
#include "ibtest_util.hpp"
#include "engine_private.h"
#include <ironbee/hash.h>
#include <ironbee/mm.h>
#include <ironbee/field.h>
#include <ironbee/rule_defs.h>
#include <ironbee/rule_engine.h>
#include <string>
#include <list>
/**
* The config creates 4 rules with id "inject-{1,2,3,4}", in that order.
*
* The operator for all is identical, and should always return 1, so the
* actions will execute. "inject-{3,4}" use the inject action, defined below,
* which has not execute function.
*
* All rules use the store action, which adds the rule to the m_actions list.
* The ownership function ownership_fn checks each rule to see if the "inject"
* action is registered for it.
*
* If yes, the ownership function adds the rule to the m_injection list, and
* returns IB_OK. This should be the case for rules "inject-{3,4}".
*
* If no, the ownership function returns IB_DECLINED. This should be the
* case for rules "inject-{1,2}".
*
* The injection function injection_fn injects the rules in m_injection list
* by adding them to the rule list. This should inject rules "inject-{3,4}".
*
* Because rules "inject-{3,4}" were injected, they will run at the start of
* the phase, before rules "inject-{1,2}".
*
* The store action adds the list to the m_action list, thus recording the
* order of rule execution.
*
* The test then verifies that the rules executed in the proper order, namely
* (inject-{3,4,1,2).
*/
/**
* Test rules.
*/
class RuleInjectTest : public BaseTransactionFixture
{
public:
ib_list_t *m_injections;
ib_list_t *m_actions;
public:
RuleInjectTest() : BaseTransactionFixture()
{
}
virtual void SetUp()
{
BaseTransactionFixture::SetUp();
ASSERT_IB_OK(ib_list_create(&m_injections, ib_engine_mm_main_get(ib_engine)));
ASSERT_IB_OK(ib_list_create(&m_actions, ib_engine_mm_main_get(ib_engine)));
}
};
static const char *name = "inject";
/* "inject" action creation function */
static ib_status_t create_fn(
ib_mm_t mm,
ib_context_t *ctx,
const char *parameters,
void *instance_data,
void *cbdata
)
{
*(void **)instance_data = cbdata;
return IB_OK;
}
/* "store" action execute function, adds rule to m_actions list */
static
ib_status_t store_fn(
const ib_rule_exec_t *rule_exec,
void *data,
void *cbdata
)
{
RuleInjectTest *p = static_cast<RuleInjectTest *>(cbdata);
ib_status_t rc;
rc = ib_list_push(p->m_actions, rule_exec->rule);
return rc;
}
/* Ownership function, adds inject rules to the m_injections list */
static ib_status_t ownership_fn(
const ib_engine_t *ib,
const ib_rule_t *rule,
const ib_context_t *ctx,
void *cbdata)
{
ib_status_t rc;
size_t count = 0;
RuleInjectTest *p = static_cast<RuleInjectTest *>(cbdata);
rc = ib_rule_search_action(ib, rule, IB_RULE_ACTION_TRUE,
name, NULL, &count);
if (rc != IB_OK) {
return rc;
}
if (count == 0) {
return IB_DECLINED;
}
rc = ib_list_push(p->m_injections, (ib_rule_t *)rule);
return rc;
}
/* Injection function, injects rules rules from the m_injections list */
static ib_status_t injection_fn(
const ib_engine_t *ib,
const ib_rule_exec_t *rule_exec,
ib_list_t *rule_list,
void *cbdata)
{
const ib_list_node_t *node;
RuleInjectTest *p = static_cast<RuleInjectTest *>(cbdata);
IB_LIST_LOOP_CONST(p->m_injections, node) {
const ib_rule_t *rule = (const ib_rule_t *)node->data;
if (rule->meta.phase == rule_exec->phase) {
ib_status_t rc = ib_list_push(rule_list, (ib_rule_t *)rule);
if (rc != IB_OK) {
return rc;
}
}
}
return IB_OK;
}
TEST_F(RuleInjectTest, test_inject)
{
ib_status_t rc;
const ib_list_node_t *node;
const ib_rule_t *rule;
// Register the inject action and related rule engine callbacks
rc = ib_action_create_and_register(
NULL,
ib_engine, name,
create_fn, this,
NULL, NULL,
NULL, NULL
);
ASSERT_EQ(IB_OK, rc);
rc = ib_action_create_and_register(
NULL, ib_engine, "store",
NULL, NULL,
NULL, NULL,
store_fn, this
);
ASSERT_EQ(IB_OK, rc);
// Register the ownership function
rc = ib_rule_register_ownership_fn(ib_engine, name, ownership_fn, this);
ASSERT_EQ(IB_OK, rc);
// Register the injection function
rc = ib_rule_register_injection_fn(ib_engine, name, IB_PHASE_REQUEST_HEADER,
injection_fn, this);
ASSERT_EQ(IB_OK, rc);
// Setup IronBee after the ownership function is registered
configureIronBee();
// Verify that the correct rules were added to the injection list
ASSERT_EQ(2U, ib_list_elements(m_injections));
node = ib_list_first_const(m_injections);
ASSERT_TRUE(node);
ASSERT_TRUE(node->data);
rule = (const ib_rule_t *)node->data;
ASSERT_TRUE(strstr(ib_rule_id(rule), "inject-3"));
node = ib_list_node_next_const(node);
ASSERT_TRUE(node);
ASSERT_TRUE(node->data);
rule = (const ib_rule_t *)node->data;
ASSERT_TRUE(strstr(ib_rule_id(rule), "inject-4"));
// Now, run the transaction
performTx();
// Verify that the correct number of rules were executed
ASSERT_EQ(4U, ib_list_elements(m_actions));
// Verify that the rules were executed in the expected order
node = ib_list_first_const(m_actions);
ASSERT_TRUE(node);
ASSERT_TRUE(node->data);
rule = (const ib_rule_t *)node->data;
ASSERT_TRUE(strstr(ib_rule_id(rule), "inject-3"));
node = ib_list_node_next_const(node);
ASSERT_TRUE(node);
ASSERT_TRUE(node->data);
rule = (const ib_rule_t *)node->data;
ASSERT_TRUE(strstr(ib_rule_id(rule), "inject-4"));
node = ib_list_node_next_const(node);
ASSERT_TRUE(node);
ASSERT_TRUE(node->data);
rule = (const ib_rule_t *)node->data;
ASSERT_TRUE(strstr(ib_rule_id(rule), "inject-1"));
node = ib_list_node_next_const(node);
ASSERT_TRUE(node);
ASSERT_TRUE(node->data);
rule = (const ib_rule_t *)node->data;
ASSERT_TRUE(strstr(ib_rule_id(rule), "inject-2"));
}
|
// Licensed to Qualys, Inc. (QUALYS) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// QUALYS 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.
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
/// @file
/// @brief IronBee --- Rule inject tests
///
/// @author Nick LeRoy <[email protected]>
//////////////////////////////////////////////////////////////////////////////
#include "gtest/gtest.h"
#include "base_fixture.h"
#include "ibtest_util.hpp"
#include "engine_private.h"
#include <ironbee/hash.h>
#include <ironbee/mm.h>
#include <ironbee/field.h>
#include <ironbee/rule_defs.h>
#include <ironbee/rule_engine.h>
#include <string>
#include <list>
/**
* The config creates 4 rules with id "inject-{1,2,3,4}", in that order.
*
* The operator for all is identical, and should always return 1, so the
* actions will execute. "inject-{3,4}" use the inject action, defined below,
* which has not execute function.
*
* All rules use the store action, which adds the rule to the m_actions list.
* The ownership function ownership_fn checks each rule to see if the "inject"
* action is registered for it.
*
* If yes, the ownership function adds the rule to the m_injection list, and
* returns IB_OK. This should be the case for rules "inject-{3,4}".
*
* If no, the ownership function returns IB_DECLINED. This should be the
* case for rules "inject-{1,2}".
*
* The injection function injection_fn injects the rules in m_injection list
* by adding them to the rule list. This should inject rules "inject-{3,4}".
*
* Because rules "inject-{3,4}" were injected, they will run at the start of
* the phase, before rules "inject-{1,2}".
*
* The store action adds the list to the m_action list, thus recording the
* order of rule execution.
*
* The test then verifies that the rules executed in the proper order, namely
* (inject-{3,4,1,2).
*/
/**
* Test rules.
*/
class RuleInjectTest : public BaseTransactionFixture
{
public:
ib_list_t *m_injections;
ib_list_t *m_actions;
public:
RuleInjectTest() :
BaseTransactionFixture(),
m_injections(NULL),
m_actions(NULL)
{
}
virtual void SetUp()
{
BaseTransactionFixture::SetUp();
ASSERT_IB_OK(ib_list_create(&m_injections, ib_engine_mm_main_get(ib_engine)));
ASSERT_IB_OK(ib_list_create(&m_actions, ib_engine_mm_main_get(ib_engine)));
}
};
static const char *name = "inject";
/* "inject" action creation function */
static ib_status_t create_fn(
ib_mm_t mm,
ib_context_t *ctx,
const char *parameters,
void *instance_data,
void *cbdata
)
{
*(void **)instance_data = cbdata;
return IB_OK;
}
/* "store" action execute function, adds rule to m_actions list */
static
ib_status_t store_fn(
const ib_rule_exec_t *rule_exec,
void *data,
void *cbdata
)
{
RuleInjectTest *p = static_cast<RuleInjectTest *>(cbdata);
ib_status_t rc;
rc = ib_list_push(p->m_actions, rule_exec->rule);
return rc;
}
/* Ownership function, adds inject rules to the m_injections list */
static ib_status_t ownership_fn(
const ib_engine_t *ib,
const ib_rule_t *rule,
const ib_context_t *ctx,
void *cbdata)
{
ib_status_t rc;
size_t count = 0;
RuleInjectTest *p = static_cast<RuleInjectTest *>(cbdata);
rc = ib_rule_search_action(ib, rule, IB_RULE_ACTION_TRUE,
name, NULL, &count);
if (rc != IB_OK) {
return rc;
}
if (count == 0) {
return IB_DECLINED;
}
rc = ib_list_push(p->m_injections, (ib_rule_t *)rule);
return rc;
}
/* Injection function, injects rules rules from the m_injections list */
static ib_status_t injection_fn(
const ib_engine_t *ib,
const ib_rule_exec_t *rule_exec,
ib_list_t *rule_list,
void *cbdata)
{
const ib_list_node_t *node;
RuleInjectTest *p = static_cast<RuleInjectTest *>(cbdata);
IB_LIST_LOOP_CONST(p->m_injections, node) {
const ib_rule_t *rule = (const ib_rule_t *)node->data;
if (rule->meta.phase == rule_exec->phase) {
ib_status_t rc = ib_list_push(rule_list, (ib_rule_t *)rule);
if (rc != IB_OK) {
return rc;
}
}
}
return IB_OK;
}
TEST_F(RuleInjectTest, test_inject)
{
ib_status_t rc;
const ib_list_node_t *node;
const ib_rule_t *rule;
// Register the inject action and related rule engine callbacks
rc = ib_action_create_and_register(
NULL,
ib_engine, name,
create_fn, this,
NULL, NULL,
NULL, NULL
);
ASSERT_EQ(IB_OK, rc);
rc = ib_action_create_and_register(
NULL, ib_engine, "store",
NULL, NULL,
NULL, NULL,
store_fn, this
);
ASSERT_EQ(IB_OK, rc);
// Register the ownership function
rc = ib_rule_register_ownership_fn(ib_engine, name, ownership_fn, this);
ASSERT_EQ(IB_OK, rc);
// Register the injection function
rc = ib_rule_register_injection_fn(ib_engine, name, IB_PHASE_REQUEST_HEADER,
injection_fn, this);
ASSERT_EQ(IB_OK, rc);
// Setup IronBee after the ownership function is registered
configureIronBee();
// Verify that the correct rules were added to the injection list
ASSERT_EQ(2U, ib_list_elements(m_injections));
node = ib_list_first_const(m_injections);
ASSERT_TRUE(node);
ASSERT_TRUE(node->data);
rule = (const ib_rule_t *)node->data;
ASSERT_TRUE(strstr(ib_rule_id(rule), "inject-3"));
node = ib_list_node_next_const(node);
ASSERT_TRUE(node);
ASSERT_TRUE(node->data);
rule = (const ib_rule_t *)node->data;
ASSERT_TRUE(strstr(ib_rule_id(rule), "inject-4"));
// Now, run the transaction
performTx();
// Verify that the correct number of rules were executed
ASSERT_EQ(4U, ib_list_elements(m_actions));
// Verify that the rules were executed in the expected order
node = ib_list_first_const(m_actions);
ASSERT_TRUE(node);
ASSERT_TRUE(node->data);
rule = (const ib_rule_t *)node->data;
ASSERT_TRUE(strstr(ib_rule_id(rule), "inject-3"));
node = ib_list_node_next_const(node);
ASSERT_TRUE(node);
ASSERT_TRUE(node->data);
rule = (const ib_rule_t *)node->data;
ASSERT_TRUE(strstr(ib_rule_id(rule), "inject-4"));
node = ib_list_node_next_const(node);
ASSERT_TRUE(node);
ASSERT_TRUE(node->data);
rule = (const ib_rule_t *)node->data;
ASSERT_TRUE(strstr(ib_rule_id(rule), "inject-1"));
node = ib_list_node_next_const(node);
ASSERT_TRUE(node);
ASSERT_TRUE(node->data);
rule = (const ib_rule_t *)node->data;
ASSERT_TRUE(strstr(ib_rule_id(rule), "inject-2"));
}
|
Initialize every class memeber. CID 11014.
|
test_rule_inject.cpp: Initialize every class memeber. CID 11014.
|
C++
|
apache-2.0
|
ironbee/ironbee,ironbee/ironbee,ironbee/ironbee,ironbee/ironbee,b1v1r/ironbee,b1v1r/ironbee,b1v1r/ironbee,ironbee/ironbee,ironbee/ironbee,ironbee/ironbee,ironbee/ironbee,b1v1r/ironbee,ironbee/ironbee,b1v1r/ironbee,b1v1r/ironbee,ironbee/ironbee,b1v1r/ironbee,b1v1r/ironbee,ironbee/ironbee,b1v1r/ironbee,b1v1r/ironbee,b1v1r/ironbee,ironbee/ironbee,b1v1r/ironbee
|
6320ddeacb416c6914c023e6c17492c9dd6aafc9
|
Player/DecoderStateData.cpp
|
Player/DecoderStateData.cpp
|
/*
* Copyright (C) 2009 Stephen F. Booth <[email protected]>
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of Stephen F. Booth nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "DecoderStateData.h"
#include "AudioDecoder.h"
#include "AudioEngineDefines.h"
DecoderStateData::DecoderStateData()
: mDecoder(NULL), mTimeStamp(0), mTotalFrames(0), mFramesRendered(0), mFrameToSeek(-1), mDecodingThread(static_cast<pthread_t>(0)), mNext(NULL)
{}
DecoderStateData::DecoderStateData(AudioDecoder *decoder)
: mDecoder(decoder), mTimeStamp(0), mFramesRendered(0), mFrameToSeek(-1), mDecodingThread(static_cast<pthread_t>(0)), mNext(NULL)
{
assert(NULL != decoder);
mTotalFrames = mDecoder->GetTotalFrames();
}
DecoderStateData::~DecoderStateData()
{
if(static_cast<pthread_t>(0) != mDecodingThread) {
int killResult = pthread_kill(mDecodingThread, SIGKILL);
if(0 != killResult)
ERR("pthread_kill failed: %i", killResult);
}
if(mDecoder)
delete mDecoder, mDecoder = NULL;
}
|
/*
* Copyright (C) 2009 Stephen F. Booth <[email protected]>
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of Stephen F. Booth nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "DecoderStateData.h"
#include "AudioDecoder.h"
#include "AudioEngineDefines.h"
DecoderStateData::DecoderStateData()
: mDecoder(NULL), mTimeStamp(0), mTotalFrames(0), mFramesRendered(0), mFrameToSeek(-1), mDecodingThread(static_cast<pthread_t>(0)), mNext(NULL)
{}
DecoderStateData::DecoderStateData(AudioDecoder *decoder)
: mDecoder(decoder), mTimeStamp(0), mFramesRendered(0), mFrameToSeek(-1), mDecodingThread(static_cast<pthread_t>(0)), mNext(NULL)
{
assert(NULL != decoder);
mTotalFrames = mDecoder->GetTotalFrames();
}
DecoderStateData::~DecoderStateData()
{
if(static_cast<pthread_t>(0) != mDecodingThread) {
int killResult = pthread_kill(mDecodingThread, SIGKILL);
if(0 != killResult)
ERR("pthread_kill failed: %i", killResult);
mDecodingThread = static_cast<pthread_t>(0);
}
if(mDecoder)
delete mDecoder, mDecoder = NULL;
}
|
Set thread id to 0 after kill
|
Set thread id to 0 after kill
|
C++
|
mit
|
sbooth/SFBAudioEngine,eriser/SFBAudioEngine,sbooth/SFBAudioEngine,sonoramac/SFBAudioEngine,sonoramac/SFBAudioEngine,sbooth/SFBAudioEngine
|
b849992f70b5f3a0d6a31284716dc52c5b45c149
|
fshell2/fql/parser/query_parser.cpp
|
fshell2/fql/parser/query_parser.cpp
|
/* -*- Mode: C++; tab-width: 4 -*- */
/* vi: set ts=4 sw=4 noexpandtab: */
/*******************************************************************************
* FShell 2
* Copyright 2009 Michael Tautschnig, [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/*! \file fshell2/fql/parser/query_parser.cpp
* \brief TODO
*
* $Id$
* \author Michael Tautschnig <[email protected]>
* \date Thu Apr 2 17:29:47 CEST 2009
*/
#include <fshell2/fql/parser/query_parser.hpp>
#include <fshell2/config/annotations.hpp>
#include <fshell2/exception/query_processing_error.hpp>
#if FSHELL2_DEBUG__LEVEL__ > -1
# include <diagnostics/basic_exceptions/violated_invariance.hpp>
#endif
#include <sstream>
#include <cerrno>
/* parser */
#define yyFlexLexer FQLFlexLexer
#include <FlexLexer.h>
extern int FQLparse(FQLFlexLexer *, ::std::ostream *, ::fshell2::fql::Query **);
// extern int yydebug;
/* end parser */
#include <fshell2/fql/parser/grammar.hpp>
FSHELL2_NAMESPACE_BEGIN;
FSHELL2_FQL_NAMESPACE_BEGIN;
Query_Parser::Query_Parser() {
}
::std::ostream & Query_Parser::help(::std::ostream & os) {
os << "FQL:" << ::std::endl << FQL_HELP << ::std::endl;
return os;
}
void Query_Parser::parse(::std::ostream & os, char const * query, Query ** query_ast) {
// new lexer
FQLFlexLexer lexer;
// put the input into a stream
::std::istringstream is(query);
// set the stream as the input to the parser
lexer.switch_streams(&is, &os);
// reset errno, readline for some reason sets this to EINVAL
errno = 0;
// try to parse
try {
int parse(0);
parse = FQLparse(&lexer, &os, query_ast);
FSHELL2_AUDIT_ASSERT(::diagnostics::Violated_Invariance, 0 == parse);
} catch (::fshell2::Query_Processing_Error & e) {
FSHELL2_PROD_CHECK1(Query_Processing_Error, false,
::std::string("Query parsing failed: ") + e.what());
}
}
FSHELL2_FQL_NAMESPACE_END;
FSHELL2_NAMESPACE_END;
|
/* -*- Mode: C++; tab-width: 4 -*- */
/* vi: set ts=4 sw=4 noexpandtab: */
/*******************************************************************************
* FShell 2
* Copyright 2009 Michael Tautschnig, [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/*! \file fshell2/fql/parser/query_parser.cpp
* \brief TODO
*
* $Id$
* \author Michael Tautschnig <[email protected]>
* \date Thu Apr 2 17:29:47 CEST 2009
*/
#include <fshell2/fql/parser/query_parser.hpp>
#include <fshell2/config/annotations.hpp>
#include <fshell2/exception/query_processing_error.hpp>
#if FSHELL2_DEBUG__LEVEL__ > -1
# include <diagnostics/basic_exceptions/violated_invariance.hpp>
#endif
#include <sstream>
#include <cerrno>
/* parser */
#define yyFlexLexer FQLFlexLexer
#include <FlexLexer.h>
extern int FQLparse(FQLFlexLexer *, ::std::ostream *, ::fshell2::fql::Query **);
// extern int yydebug;
/* end parser */
#include <fshell2/fql/parser/grammar.hpp>
FSHELL2_NAMESPACE_BEGIN;
FSHELL2_FQL_NAMESPACE_BEGIN;
Query_Parser::Query_Parser() {
}
::std::ostream & Query_Parser::help(::std::ostream & os) {
os << "FQL:" << ::std::endl << FQL_HELP << ::std::endl;
return os;
}
void Query_Parser::parse(::std::ostream & os, char const * query, Query ** query_ast) {
// new lexer
FQLFlexLexer lexer;
// put the input into a stream
::std::istringstream is(query);
// set the stream as the input to the parser
lexer.switch_streams(&is, &os);
// reset errno, readline for some reason sets this to EINVAL
errno = 0;
// try to parse
try {
int parse(0);
parse = FQLparse(&lexer, &os, query_ast);
if(0 != parse)
FSHELL2_AUDIT_ASSERT(::diagnostics::Violated_Invariance, false);
} catch (::fshell2::Query_Processing_Error & e) {
FSHELL2_PROD_CHECK1(Query_Processing_Error, false,
::std::string("Query parsing failed: ") + e.what());
}
}
FSHELL2_FQL_NAMESPACE_END;
FSHELL2_NAMESPACE_END;
|
Fix set-but-not-used variable
|
Fix set-but-not-used variable
git-svn-id: 5facb983d7372ae426b1e6603b58ad22977bf690@465 740c81f5-4728-4b1f-bc77-cf82a461b733
|
C++
|
apache-2.0
|
tautschnig/fshell,tautschnig/fshell,tautschnig/fshell,tautschnig/fshell
|
f8ca3929a5ecbbd4f0e0270ad2186e95ed180bd3
|
game/shared/sdk/ios_fileupdater.cpp
|
game/shared/sdk/ios_fileupdater.cpp
|
#include "cbase.h"
#include "ios_fileupdater.h"
#include "curl/curl.h"
#include "Filesystem.h"
#include "utlbuffer.h"
#include "checksum_md5.h"
#include "threadtools.h"
#include "ios_teamkit_parse.h"
ConVar cl_clientfiles_download_url("cl_clientfiles_download_url", "http://simrai.iosoccer.com/downloads/clientfiles/iosoccer");
ConVar sv_serverfiles_download_url("sv_serverfiles_download_url", "http://simrai.iosoccer.com/downloads/serverfiles/iosoccer");
struct FileInfo
{
char path[256];
char md5[33];
int bytes;
};
struct FileData
{
FileHandle_t fh;
MD5Context_t md5Ctx;
IOSUpdateInfo *pUpdateInfo;
};
static size_t rcvFileListData(void *ptr, size_t size, size_t nmemb, CUtlBuffer &buffer)
{
buffer.Put(ptr, nmemb);
return nmemb;
}
static size_t rcvFile(void *ptr, size_t size, size_t nmemb, FileData *vars)
{
filesystem->Write(ptr, nmemb, vars->fh);
MD5Update(&vars->md5Ctx, (unsigned char *)ptr, nmemb);
vars->pUpdateInfo->receivedBytes += nmemb;
return nmemb;
}
void GetLocalFileList(char *fileListString, CUtlVector<FileInfo> &fileList)
{
char *line = strtok(fileListString, "\n");
while (line != NULL)
{
char *md5 = strstr(line, ":");
if (md5 && md5 + 1)
{
md5 += 1;
if (strlen(md5) == 32)
{
FileInfo fileInfo;
Q_strncpy(fileInfo.path, line, min(md5 - line, sizeof(fileInfo.path)));
Q_strncpy(fileInfo.md5, md5, sizeof(fileInfo.md5));
fileInfo.bytes = 0;
fileList.AddToTail(fileInfo);
}
}
line = strtok(NULL, "\n");
}
}
long GetServerFileList(char *fileListString, CUtlVector<FileInfo> &fileList)
{
long totalBytes = 0;
char *line = strtok(fileListString, "\n");
while (line != NULL)
{
char *md5 = strstr(line, ":");
if (md5 && md5 + 1)
{
md5 += 1;
char *bytes = strstr(md5, ":");
if (bytes && bytes + 1)
{
if (bytes - md5 == 32)
{
bytes += 1;
FileInfo fileInfo;
Q_strncpy(fileInfo.path, line, min(md5 - line, sizeof(fileInfo.path)));
Q_strncpy(fileInfo.md5, md5, sizeof(fileInfo.md5));
fileInfo.bytes = atoi(bytes);
totalBytes += fileInfo.bytes;
fileList.AddToTail(fileInfo);
}
}
}
line = strtok(NULL, "\n");
}
return totalBytes;
}
unsigned PerformUpdate(void *params)
{
const char *downloadUrl;
#ifdef CLIENT_DLL
downloadUrl = cl_clientfiles_download_url.GetString();
#else
downloadUrl = sv_serverfiles_download_url.GetString();
#endif
IOSUpdateInfo *pUpdateInfo = (IOSUpdateInfo *)params;
const char *fileListPath = "filelist.txt";
CUtlVector<FileInfo> localFileList;
if (filesystem->FileExists(fileListPath, "MOD"))
{
FileHandle_t fh = filesystem->Open(fileListPath, "rb", "MOD");
int fileSize = filesystem->Size(fh);
char *localFileListString = new char[fileSize + 1];
filesystem->Read((void *)localFileListString, fileSize, fh);
localFileListString[fileSize] = 0; // null terminator
filesystem->Close(fh);
GetLocalFileList(localFileListString, localFileList);
delete[] localFileListString;
}
CUtlBuffer buffer;
CURL *curl;
curl = curl_easy_init();
char url[512];
Q_snprintf(url, sizeof(url), "%s/filelist_v2.txt.gz", downloadUrl);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, "gzip");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, rcvFileListData);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
CURLcode result = curl_easy_perform(curl);
long code;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
curl_easy_cleanup(curl);
if (result != CURLE_OK || code != 200)
{
pUpdateInfo->connectionError = true;
return CFileUpdater::UpdateFinished(pUpdateInfo);
}
char *serverFileListString = new char[buffer.Size() + 1];
buffer.GetString(serverFileListString);
serverFileListString[buffer.Size()] = 0;
CUtlVector<FileInfo> serverFileList;
long totalServerBytes = GetServerFileList(serverFileListString, serverFileList);
delete[] serverFileListString;
for (int i = 0; i < localFileList.Count(); i++)
{
for (int j = 0; j < serverFileList.Count(); j++)
{
if (!Q_strcmp(serverFileList[j].path, localFileList[i].path))
{
if (!Q_strcmp(serverFileList[j].md5, localFileList[i].md5))
{
totalServerBytes -= serverFileList[j].bytes;
serverFileList.Remove(j);
}
else
{
localFileList.Remove(i);
i -= 1;
}
break;
}
}
}
pUpdateInfo->filesToUpdateCount = serverFileList.Count();
pUpdateInfo->totalBytes = totalServerBytes;
if (pUpdateInfo->checkOnly || pUpdateInfo->filesToUpdateCount == 0)
{
if (pUpdateInfo->checkOnly)
{
CUtlBuffer changelogBuffer;
curl = curl_easy_init();
Q_snprintf(url, sizeof(url), "%s/changelog.txt.gz", downloadUrl);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, "gzip");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, rcvFileListData);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &changelogBuffer);
result = curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
curl_easy_cleanup(curl);
char *changelogString = new char[changelogBuffer.Size() + 1];
changelogBuffer.GetString(changelogString);
changelogString[changelogBuffer.Size()] = 0;
Q_strncpy(pUpdateInfo->changelogText, changelogString, sizeof(pUpdateInfo->changelogText));
delete[] changelogString;
pUpdateInfo->changelogDownloaded = true;
}
return CFileUpdater::UpdateFinished(pUpdateInfo);
}
FileHandle_t fh = filesystem->Open(fileListPath, "wb", "MOD");
for (int i = 0; i < localFileList.Count(); i++)
{
char str[256];
Q_snprintf(str, sizeof(str), "%s%s:%s", i == 0 ? "" : "\n", localFileList[i].path, localFileList[i].md5);
filesystem->Write(str, strlen(str), fh);
}
for (int i = 0; i < serverFileList.Count(); i++)
{
char filePath[256];
Q_snprintf(filePath, sizeof(filePath), "%s", serverFileList[i].path);
char folderPath[256];
Q_strncpy(folderPath, filePath, sizeof(folderPath));
char *pos = strrchr(folderPath, '/');
if (pos)
{
*pos = '\0';
if (!filesystem->FileExists(folderPath, "MOD"))
filesystem->CreateDirHierarchy(folderPath, "MOD");
}
if (!Q_strcmp(&filePath[strlen(filePath) - 4], ".dll") && filesystem->FileExists(filePath, "MOD"))
{
char newFilePath[256];
Q_snprintf(newFilePath, sizeof(newFilePath), "%s_old", filePath);
if (filesystem->FileExists(newFilePath, "MOD"))
filesystem->RemoveFile(newFilePath, "MOD");
filesystem->RenameFile(filePath, newFilePath, "MOD");
pUpdateInfo->restartRequired = true;
}
Q_strncpy(pUpdateInfo->filePath, serverFileList[i].path, sizeof(pUpdateInfo->filePath));
FileData curlData;
curlData.fh = filesystem->Open(filePath, "wb", "MOD");
memset(&curlData.md5Ctx, 0, sizeof(MD5Context_t));
MD5Init(&curlData.md5Ctx);
curlData.pUpdateInfo = pUpdateInfo;
curl = curl_easy_init();
Q_snprintf(url, sizeof(url), "%s/%s.gz", downloadUrl, serverFileList[i].path);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, "gzip");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, rcvFile);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &curlData);
CURLcode result = curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
curl_easy_cleanup(curl);
filesystem->Close(curlData.fh);
unsigned char digest[MD5_DIGEST_LENGTH];
MD5Final(digest, &curlData.md5Ctx);
char hexDigest[MD5_DIGEST_LENGTH * 2 + 1];
for (int j = 0; j < MD5_DIGEST_LENGTH; j++)
Q_snprintf(&hexDigest[j * 2], sizeof(hexDigest) - (j * 2), "%02x", digest[j]);
char str[256];
Q_snprintf(str, sizeof(str), "%s%s:%s", localFileList.Count() == 0 && i == 0 ? "" : "\n", serverFileList[i].path, hexDigest);
filesystem->Write(str, strlen(str), fh);
pUpdateInfo->filesUpdatedCount = i + 1;
if (pUpdateInfo->cancelled)
break;
}
filesystem->Close(fh);
return CFileUpdater::UpdateFinished(pUpdateInfo);
}
void CFileUpdater::UpdateFiles(IOSUpdateInfo *pUpdateInfo)
{
if (pUpdateInfo->async)
CreateSimpleThread(PerformUpdate, pUpdateInfo);
else
PerformUpdate(pUpdateInfo);
}
int CFileUpdater::UpdateFinished(IOSUpdateInfo *pUpdateInfo)
{
pUpdateInfo->finished = true;
#ifdef CLIENT_DLL
return 0;
#else
const char *msg;
if (pUpdateInfo->connectionError)
msg = "Server Updater: Couldn't connect to the update server.";
else if (pUpdateInfo->checkOnly)
msg = "Server Updater: Check for changes successful.";
else
{
if (pUpdateInfo->filesToUpdateCount == 0)
msg = "Server Updater: All server files are up to date.";
else
{
CTeamInfo::ParseTeamKits();
CBallInfo::ParseBallSkins();
CPitchInfo::ParsePitchTextures();
if (pUpdateInfo->restartRequired)
msg = "Server Updater: Server files successfully updated. A server restart is required to use the new binaries.";
else
msg = "Server Updater: Server files successfully updated. A server restart might be required to use the new files.";
}
}
char consoleMsg[256];
Q_snprintf(consoleMsg, sizeof(consoleMsg), "%s\n", msg);
Msg(consoleMsg);
UTIL_ClientPrintAll(HUD_PRINTCONSOLE, msg);
if (pUpdateInfo->async)
delete pUpdateInfo;
return 0;
#endif
}
|
#include "cbase.h"
#include "ios_fileupdater.h"
#include "curl/curl.h"
#include "Filesystem.h"
#include "utlbuffer.h"
#include "checksum_md5.h"
#include "threadtools.h"
#include "ios_teamkit_parse.h"
ConVar cl_clientfiles_download_url("cl_clientfiles_download_url", "http://simrai.iosoccer.com/downloads/clientfiles/iosoccer");
ConVar sv_serverfiles_download_url("sv_serverfiles_download_url", "http://simrai.iosoccer.com/downloads/serverfiles/iosoccer");
struct FileInfo
{
char path[256];
char md5[33];
int bytes;
};
struct FileData
{
FileHandle_t fh;
MD5Context_t md5Ctx;
IOSUpdateInfo *pUpdateInfo;
long prevReceivedBytes;
CURL *curl;
};
static size_t rcvFileListData(void *ptr, size_t size, size_t nmemb, CUtlBuffer &buffer)
{
buffer.Put(ptr, nmemb);
return nmemb;
}
static size_t rcvFile(void *ptr, size_t size, size_t nmemb, FileData *vars)
{
filesystem->Write(ptr, nmemb, vars->fh);
MD5Update(&vars->md5Ctx, (unsigned char *)ptr, nmemb);
double receivedBytes;
curl_easy_getinfo(vars->curl, CURLINFO_SIZE_DOWNLOAD, &receivedBytes);
vars->pUpdateInfo->receivedBytes = vars->prevReceivedBytes + (long)receivedBytes;
return nmemb;
}
void GetLocalFileList(char *fileListString, CUtlVector<FileInfo> &fileList)
{
char *line = strtok(fileListString, "\n");
while (line != NULL)
{
char *md5 = strstr(line, ":");
if (md5 && md5 + 1)
{
md5 += 1;
if (strlen(md5) == 32)
{
FileInfo fileInfo;
Q_strncpy(fileInfo.path, line, min(md5 - line, sizeof(fileInfo.path)));
Q_strncpy(fileInfo.md5, md5, sizeof(fileInfo.md5));
fileInfo.bytes = 0;
fileList.AddToTail(fileInfo);
}
}
line = strtok(NULL, "\n");
}
}
long GetServerFileList(char *fileListString, CUtlVector<FileInfo> &fileList)
{
long totalBytes = 0;
char *line = strtok(fileListString, "\n");
while (line != NULL)
{
char *md5 = strstr(line, ":");
if (md5 && md5 + 1)
{
md5 += 1;
char *bytes = strstr(md5, ":");
if (bytes && bytes + 1)
{
if (bytes - md5 == 32)
{
bytes += 1;
FileInfo fileInfo;
Q_strncpy(fileInfo.path, line, min(md5 - line, sizeof(fileInfo.path)));
Q_strncpy(fileInfo.md5, md5, sizeof(fileInfo.md5));
fileInfo.bytes = atoi(bytes);
totalBytes += fileInfo.bytes;
fileList.AddToTail(fileInfo);
}
}
}
line = strtok(NULL, "\n");
}
return totalBytes;
}
unsigned PerformUpdate(void *params)
{
const char *downloadUrl;
#ifdef CLIENT_DLL
downloadUrl = cl_clientfiles_download_url.GetString();
#else
downloadUrl = sv_serverfiles_download_url.GetString();
#endif
IOSUpdateInfo *pUpdateInfo = (IOSUpdateInfo *)params;
const char *fileListPath = "filelist.txt";
CUtlVector<FileInfo> localFileList;
if (filesystem->FileExists(fileListPath, "MOD"))
{
FileHandle_t fh = filesystem->Open(fileListPath, "rb", "MOD");
int fileSize = filesystem->Size(fh);
char *localFileListString = new char[fileSize + 1];
filesystem->Read((void *)localFileListString, fileSize, fh);
localFileListString[fileSize] = 0; // null terminator
filesystem->Close(fh);
GetLocalFileList(localFileListString, localFileList);
delete[] localFileListString;
}
CUtlBuffer buffer;
CURL *curl;
curl = curl_easy_init();
char url[512];
Q_snprintf(url, sizeof(url), "%s/filelist_v2.txt.gz", downloadUrl);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, "gzip");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, rcvFileListData);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
CURLcode result = curl_easy_perform(curl);
long code;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
curl_easy_cleanup(curl);
if (result != CURLE_OK || code != 200)
{
pUpdateInfo->connectionError = true;
return CFileUpdater::UpdateFinished(pUpdateInfo);
}
char *serverFileListString = new char[buffer.Size() + 1];
buffer.GetString(serverFileListString);
serverFileListString[buffer.Size()] = 0;
CUtlVector<FileInfo> serverFileList;
long totalServerBytes = GetServerFileList(serverFileListString, serverFileList);
delete[] serverFileListString;
for (int i = 0; i < localFileList.Count(); i++)
{
for (int j = 0; j < serverFileList.Count(); j++)
{
if (!Q_strcmp(serverFileList[j].path, localFileList[i].path))
{
if (!Q_strcmp(serverFileList[j].md5, localFileList[i].md5))
{
totalServerBytes -= serverFileList[j].bytes;
serverFileList.Remove(j);
}
else
{
localFileList.Remove(i);
i -= 1;
}
break;
}
}
}
pUpdateInfo->filesToUpdateCount = serverFileList.Count();
pUpdateInfo->totalBytes = totalServerBytes;
if (pUpdateInfo->checkOnly || pUpdateInfo->filesToUpdateCount == 0)
{
if (pUpdateInfo->checkOnly)
{
CUtlBuffer changelogBuffer;
curl = curl_easy_init();
Q_snprintf(url, sizeof(url), "%s/changelog.txt.gz", downloadUrl);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, "gzip");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, rcvFileListData);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &changelogBuffer);
result = curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
curl_easy_cleanup(curl);
char *changelogString = new char[changelogBuffer.Size() + 1];
changelogBuffer.GetString(changelogString);
changelogString[changelogBuffer.Size()] = 0;
Q_strncpy(pUpdateInfo->changelogText, changelogString, sizeof(pUpdateInfo->changelogText));
delete[] changelogString;
pUpdateInfo->changelogDownloaded = true;
}
return CFileUpdater::UpdateFinished(pUpdateInfo);
}
FileHandle_t fh = filesystem->Open(fileListPath, "wb", "MOD");
for (int i = 0; i < localFileList.Count(); i++)
{
char str[256];
Q_snprintf(str, sizeof(str), "%s%s:%s", i == 0 ? "" : "\n", localFileList[i].path, localFileList[i].md5);
filesystem->Write(str, strlen(str), fh);
}
for (int i = 0; i < serverFileList.Count(); i++)
{
char filePath[256];
Q_snprintf(filePath, sizeof(filePath), "%s", serverFileList[i].path);
char folderPath[256];
Q_strncpy(folderPath, filePath, sizeof(folderPath));
char *pos = strrchr(folderPath, '/');
if (pos)
{
*pos = '\0';
if (!filesystem->FileExists(folderPath, "MOD"))
filesystem->CreateDirHierarchy(folderPath, "MOD");
}
if (!Q_strcmp(&filePath[strlen(filePath) - 4], ".dll") && filesystem->FileExists(filePath, "MOD"))
{
char newFilePath[256];
Q_snprintf(newFilePath, sizeof(newFilePath), "%s_old", filePath);
if (filesystem->FileExists(newFilePath, "MOD"))
filesystem->RemoveFile(newFilePath, "MOD");
filesystem->RenameFile(filePath, newFilePath, "MOD");
pUpdateInfo->restartRequired = true;
}
Q_strncpy(pUpdateInfo->filePath, serverFileList[i].path, sizeof(pUpdateInfo->filePath));
FileData curlData;
curlData.fh = filesystem->Open(filePath, "wb", "MOD");
memset(&curlData.md5Ctx, 0, sizeof(MD5Context_t));
MD5Init(&curlData.md5Ctx);
curlData.pUpdateInfo = pUpdateInfo;
curlData.prevReceivedBytes = pUpdateInfo->receivedBytes;
curl = curl_easy_init();
curlData.curl = curl;
Q_snprintf(url, sizeof(url), "%s/%s.gz", downloadUrl, serverFileList[i].path);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, "gzip");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, rcvFile);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &curlData);
CURLcode result = curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
curl_easy_cleanup(curl);
filesystem->Close(curlData.fh);
unsigned char digest[MD5_DIGEST_LENGTH];
MD5Final(digest, &curlData.md5Ctx);
char hexDigest[MD5_DIGEST_LENGTH * 2 + 1];
for (int j = 0; j < MD5_DIGEST_LENGTH; j++)
Q_snprintf(&hexDigest[j * 2], sizeof(hexDigest) - (j * 2), "%02x", digest[j]);
char str[256];
Q_snprintf(str, sizeof(str), "%s%s:%s", localFileList.Count() == 0 && i == 0 ? "" : "\n", serverFileList[i].path, hexDigest);
filesystem->Write(str, strlen(str), fh);
pUpdateInfo->filesUpdatedCount = i + 1;
if (pUpdateInfo->cancelled)
break;
}
filesystem->Close(fh);
return CFileUpdater::UpdateFinished(pUpdateInfo);
}
void CFileUpdater::UpdateFiles(IOSUpdateInfo *pUpdateInfo)
{
if (pUpdateInfo->async)
CreateSimpleThread(PerformUpdate, pUpdateInfo);
else
PerformUpdate(pUpdateInfo);
}
int CFileUpdater::UpdateFinished(IOSUpdateInfo *pUpdateInfo)
{
pUpdateInfo->finished = true;
#ifdef CLIENT_DLL
return 0;
#else
const char *msg;
if (pUpdateInfo->connectionError)
msg = "Server Updater: Couldn't connect to the update server.";
else if (pUpdateInfo->checkOnly)
msg = "Server Updater: Check for changes successful.";
else
{
if (pUpdateInfo->filesToUpdateCount == 0)
msg = "Server Updater: All server files are up to date.";
else
{
CTeamInfo::ParseTeamKits();
CBallInfo::ParseBallSkins();
CPitchInfo::ParsePitchTextures();
if (pUpdateInfo->restartRequired)
msg = "Server Updater: Server files successfully updated. A server restart is required to use the new binaries.";
else
msg = "Server Updater: Server files successfully updated. A server restart might be required to use the new files.";
}
}
char consoleMsg[256];
Q_snprintf(consoleMsg, sizeof(consoleMsg), "%s\n", msg);
Msg(consoleMsg);
UTIL_ClientPrintAll(HUD_PRINTCONSOLE, msg);
if (pUpdateInfo->async)
delete pUpdateInfo;
return 0;
#endif
}
|
Fix #370
|
Fix #370
|
C++
|
mit
|
ziming/IOS,ziming/IOS,iosoccer/iosoccer-game,romdi/IOS,romdi/IOS,romdi/IOS,romdi/IOS,ziming/IOS,iosoccer/iosoccer-game,iosoccer/iosoccer-game,ziming/IOS,iosoccer/iosoccer-game
|
01078815d7abb5a10078b1d7ac9138b1327ecb84
|
Geometry/Grassmann-body.hpp
|
Geometry/Grassmann-body.hpp
|
#pragma once
namespace Principia {
namespace Geometry {
template<typename T, typename Frame, unsigned int Rank>
inline Multivector<T, Frame,
Rank> operator+ (Multivector<T, Frame, Rank> const& right) {
return Multivector<T, Frame, Rank>(+right.coordinates);
}
template<typename T, typename Frame, unsigned int Rank>
inline Multivector<T, Frame,
Rank> operator- (Multivector<T, Frame, Rank> const& right) {
return Multivector<T, Frame, Rank>(-right.coordinates);
}
template<typename T, typename Frame, unsigned int Rank>
inline Multivector<T, Frame,
Rank> operator+ (Multivector<T, Frame, Rank> const& left,
Multivector<T, Frame, Rank> const& right) {
return Multivector<T, Frame, Rank>(left.coordinates + right.coordinates);
}
template<typename T, typename Frame, unsigned int Rank>
inline Multivector<T, Frame,
Rank> operator- (Multivector<T, Frame, Rank> const& left,
Multivector<T, Frame, Rank> const& right) {
return Multivector<T, Frame, Rank>(left.coordinates + left.coordinates);
}
}
}
|
#pragma once
namespace Principia {
namespace Geometry {
template<typename T, typename Frame, unsigned int Rank>
inline Multivector<T, Frame,
Rank> operator+ (Multivector<T, Frame, Rank> const& right) {
return Multivector<T, Frame, Rank>(+right.coordinates);
}
template<typename T, typename Frame, unsigned int Rank>
inline Multivector<T, Frame,
Rank> operator- (Multivector<T, Frame, Rank> const& right) {
return Multivector<T, Frame, Rank>(-right.coordinates);
}
template<typename T, typename Frame, unsigned int Rank>
inline Multivector<T, Frame,
Rank> operator+ (Multivector<T, Frame, Rank> const& left,
Multivector<T, Frame, Rank> const& right) {
return Multivector<T, Frame, Rank>(left.coordinates + right.coordinates);
}
template<typename T, typename Frame, unsigned int Rank>
inline Multivector<T, Frame,
Rank> operator- (Multivector<T, Frame, Rank> const& left,
Multivector<T, Frame, Rank> const& right) {
return Multivector<T, Frame, Rank>(left.coordinates + left.coordinates);
}
template<typename T, typename Frame, unsigned int Rank>
inline Multivector<T, Frame,
Rank> operator* (Quantities::Dimensionless const& left,
Multivector<T, Frame, Rank> const& right) {
return Multivector<T, Frame, Rank>(left * right.coordinates);
}
template<typename T, typename Frame, unsigned int Rank>
inline Multivector<T, Frame,
Rank> operator* (Multivector<T, Frame, Rank> const& left,
Quantities::Dimensionless const& right) {
return Multivector<T, Frame, Rank>(left.coordinates * right);
}
template<typename T, typename Frame, unsigned int Rank>
inline Multivector<T, Frame,
Rank> operator/ (Multivector<T, Frame, Rank> const& left,
Quantities::Dimensionless const& right) {
return Multivector<T, Frame, Rank>(left.coordinates / right);
}
template<typename T, typename U, typename Frame, unsigned int Rank>
inline Multivector<Quantities::Product<U, T> , Frame,
Rank> operator* (U const& left,
Multivector<T, Frame, Rank> const& right) {
return Multivector<T, Frame, Rank>(left * right.coordinates);
}
template<typename T, typename U, typename Frame, unsigned int Rank>
inline Multivector<Quantities::Product<T, U>, Frame,
Rank> operator* (Multivector<T, Frame, Rank> const& left,
Quantities::Dimensionless const& right) {
return Multivector<T, Frame, Rank>(left.coordinates * right);
}
template<typename T, typename U, typename Frame, unsigned int Rank>
inline Multivector<Quantities::Quotient<T, U>, Frame,
Rank> operator/ (Multivector<T, Frame, Rank> const& left,
Quantities::Dimensionless const& right) {
return Multivector<T, Frame, Rank>(left.coordinates / right);
}
}
}
|
Implement * and /, both dimensionful and dimensionless.
|
Implement * and /, both dimensionful and dimensionless.
|
C++
|
mit
|
mockingbirdnest/Principia,Norgg/Principia,Norgg/Principia,pleroy/Principia,Norgg/Principia,pleroy/Principia,mockingbirdnest/Principia,pleroy/Principia,mockingbirdnest/Principia,Norgg/Principia,mockingbirdnest/Principia,eggrobin/Principia,eggrobin/Principia,eggrobin/Principia,pleroy/Principia
|
d1b3a4fe8b3aa45c1cbd771cbb9e18ba35fc099d
|
eventrpc/eventrpc/net_utility.cpp
|
eventrpc/eventrpc/net_utility.cpp
|
/*
* Copyright (C) Lichuang
*
*/
#include <sys/select.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <strings.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include "net_utility.h"
#include "log.h"
namespace {
static const uint32 kConnectTimeoutSecond = 5;
static const uint32 kMaxTryConnecTime = 3;
static const uint32 kConnectFailSleepTime = 1;
};
namespace eventrpc {
static bool is_connected(int fd,
const fd_set *read_events,
const fd_set *write_events,
const fd_set *exception_events) {
int error_save = 0;
socklen_t length = sizeof(error_save);
// assume no error
errno = 0;
if (!FD_ISSET(fd, read_events) &&
!FD_ISSET(fd, write_events)) {
return false;
}
if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &error_save, &length)< 0) {
return false;
}
errno = error_save;
return (error_save == 0);
}
int NetUtility::Connect(const NetAddress &address) {
int fd = ::socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) {
VLOG_ERROR() << "create socket error: " << strerror(errno);
return -1;
}
if (!NetUtility::SetNonBlocking(fd)) {
VLOG_ERROR() << "SetNonBlocking fail";
::close(fd);
return -1;
}
const struct sockaddr_in *addr = address.address();
int ret = ::connect(fd, (struct sockaddr *)(addr), sizeof(*addr));
if (ret == 0) {
// connected?
return fd;
}
// time-out connect
fd_set read_events, write_events, exception_events;
struct timeval tv;
FD_ZERO(&read_events);
FD_SET(fd, &read_events);
write_events = read_events;
exception_events = read_events;
tv.tv_sec = kConnectTimeoutSecond;
tv.tv_usec = 0;
int result = ::select(fd + 1, &read_events,
&write_events, &exception_events,
&tv);
if (result < 0) {
VLOG_ERROR() << "select fail: " << strerror(errno);
::close(fd);
return -1;
}
if (result == 0) {
VLOG_ERROR() << "connect time out";
::close(fd);
return -1;
}
if (is_connected(fd, &read_events, &write_events, &exception_events)) {
VLOG_INFO() << "connect to " << address.DebugString()
<< " success";
return fd;
}
VLOG_ERROR() << "connect time out";
::close(fd);
return -1;
}
int NetUtility::Listen(const NetAddress &address) {
int fd = ::socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) {
VLOG_ERROR() << "create socket error: " << strerror(errno);
return -1;
}
int one = 1;
if (::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
&one, sizeof(one)) < 0) {
return -1;
}
if (!NetUtility::SetNonBlocking(fd)) {
return -1;
}
const struct sockaddr_in *addr = address.address();
if (::bind(fd, (struct sockaddr *)(addr), sizeof(*addr)) < 0) {
VLOG_ERROR() << "bind socket to " << address.DebugString()
<< " error: " << strerror(errno);
return -1;
}
if (::listen(fd, 10000) < 0) {
VLOG_ERROR() << "listen socket to " << address.DebugString()
<< " error: " << strerror(errno);
return -1;
}
return fd;
}
bool NetUtility::Accept(int listen_fd,
struct sockaddr_in *addr,
int *fd) {
int accept_fd = 0, errno_copy = 0;
socklen_t length = sizeof(*addr);
do {
accept_fd = ::accept(listen_fd,
(struct sockaddr *)(addr),
&length);
if (accept_fd > 0) {
break;
}
errno_copy = errno;
if (accept_fd < 0) {
if (errno_copy == EINTR) {
continue;
} else if (errno_copy == EAGAIN) {
*fd = 0;
return true;
} else {
VLOG_ERROR() << "Fail to accept, "
<< " error: "
<< strerror(errno_copy);
return false;
}
}
} while (true);
if (!NetUtility::SetNonBlocking(accept_fd)) {
close(accept_fd);
return false;
}
*fd = accept_fd;
return true;
}
bool NetUtility::Send(int fd, const void *buf, size_t count,
int *length) {
int ret = 0, errno_copy = 0;
*length = 0;
do {
ret = ::send(fd, ((char*)buf + (*length)),
count, MSG_NOSIGNAL | MSG_DONTWAIT);
errno_copy = errno;
if (ret > 0) {
count -= ret;
*length += ret;
continue;
}
if (ret == 0) {
return true;
}
if (errno_copy == EINTR) {
continue;
}
if (errno_copy == EAGAIN || errno_copy == EWOULDBLOCK) {
return true;
}
VLOG_ERROR() << "send error: " << strerror(errno_copy);
return false;
} while (ret > 0 && count > 0);
return true;
}
bool NetUtility::Recv(int fd, void *buf, size_t count, int *length) {
int ret = 0, errno_copy = 0;
*length = 0;
do {
ret = ::recv(fd, (char*)buf + (*length), count, MSG_DONTWAIT);
errno_copy = errno;
if (ret == 0) {
// socket has been closed
VLOG_ERROR() << "recv error: " << strerror(errno_copy);
return true;
}
if (ret > 0) {
count -= ret;
*length += ret;
if (count == 0) {
return true;
}
continue;
}
// if or not try again depends on the error code
if (errno_copy == EINTR) {
continue;
}
if (errno_copy == EAGAIN || errno_copy == EWOULDBLOCK) {
return true;
}
VLOG_ERROR() << "recv error: " << strerror(errno_copy);
return false;
} while (ret > 0 && count > 0);
return true;
}
bool NetUtility::SetNonBlocking(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1) {
return false;
}
if (-1 == fcntl(fd, F_SETFL, flags | O_NONBLOCK)) {
return false;
}
return true;
}
};
|
/*
* Copyright (C) Lichuang
*
*/
#include <sys/select.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <strings.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include "net_utility.h"
#include "log.h"
namespace {
static const uint32 kConnectTimeoutSecond = 5;
static const uint32 kMaxTryConnecTime = 3;
static const uint32 kConnectFailSleepTime = 1;
};
namespace eventrpc {
static bool is_connected(int fd,
const fd_set *read_events,
const fd_set *write_events) {
int error_save = 0;
socklen_t length = sizeof(error_save);
// assume no error
errno = 0;
if (!FD_ISSET(fd, read_events) &&
!FD_ISSET(fd, write_events)) {
return false;
}
if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &error_save, &length)< 0) {
return false;
}
errno = error_save;
return (error_save == 0);
}
int NetUtility::Connect(const NetAddress &address) {
int fd = ::socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) {
VLOG_ERROR() << "create socket error: " << strerror(errno);
return -1;
}
if (!NetUtility::SetNonBlocking(fd)) {
VLOG_ERROR() << "SetNonBlocking fail";
::close(fd);
return -1;
}
const struct sockaddr_in *addr = address.address();
int ret = ::connect(fd, (struct sockaddr *)(addr), sizeof(*addr));
if (ret == 0) {
// connected?
return fd;
}
// time-out connect
fd_set read_events, write_events, exception_events;
struct timeval tv;
FD_ZERO(&read_events);
FD_SET(fd, &read_events);
write_events = read_events;
exception_events = read_events;
tv.tv_sec = kConnectTimeoutSecond;
tv.tv_usec = 0;
int result = ::select(fd + 1, &read_events,
&write_events, &exception_events,
&tv);
if (result < 0) {
VLOG_ERROR() << "select fail: " << strerror(errno);
::close(fd);
return -1;
}
if (result == 0) {
VLOG_ERROR() << "connect time out";
::close(fd);
return -1;
}
if (is_connected(fd, &read_events, &write_events)) {
VLOG_INFO() << "connect to " << address.DebugString()
<< " success";
return fd;
}
VLOG_ERROR() << "connect time out";
::close(fd);
return -1;
}
int NetUtility::Listen(const NetAddress &address) {
int fd = ::socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) {
VLOG_ERROR() << "create socket error: " << strerror(errno);
return -1;
}
int one = 1;
if (::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
&one, sizeof(one)) < 0) {
return -1;
}
if (!NetUtility::SetNonBlocking(fd)) {
return -1;
}
const struct sockaddr_in *addr = address.address();
if (::bind(fd, (struct sockaddr *)(addr), sizeof(*addr)) < 0) {
VLOG_ERROR() << "bind socket to " << address.DebugString()
<< " error: " << strerror(errno);
return -1;
}
if (::listen(fd, 10000) < 0) {
VLOG_ERROR() << "listen socket to " << address.DebugString()
<< " error: " << strerror(errno);
return -1;
}
return fd;
}
bool NetUtility::Accept(int listen_fd,
struct sockaddr_in *addr,
int *fd) {
int accept_fd = 0, errno_copy = 0;
socklen_t length = sizeof(*addr);
do {
accept_fd = ::accept(listen_fd,
(struct sockaddr *)(addr),
&length);
if (accept_fd > 0) {
break;
}
errno_copy = errno;
if (accept_fd < 0) {
if (errno_copy == EINTR) {
continue;
} else if (errno_copy == EAGAIN) {
*fd = 0;
return true;
} else {
VLOG_ERROR() << "Fail to accept, "
<< " error: "
<< strerror(errno_copy);
return false;
}
}
} while (true);
if (!NetUtility::SetNonBlocking(accept_fd)) {
close(accept_fd);
return false;
}
*fd = accept_fd;
return true;
}
bool NetUtility::Send(int fd, const void *buf, size_t count,
int *length) {
int ret = 0, errno_copy = 0;
*length = 0;
do {
ret = ::send(fd, ((char*)buf + (*length)),
count, MSG_NOSIGNAL | MSG_DONTWAIT);
errno_copy = errno;
if (ret > 0) {
count -= ret;
*length += ret;
continue;
}
if (ret == 0) {
return true;
}
if (errno_copy == EINTR) {
continue;
}
if (errno_copy == EAGAIN || errno_copy == EWOULDBLOCK) {
return true;
}
VLOG_ERROR() << "send error: " << strerror(errno_copy);
return false;
} while (ret > 0 && count > 0);
return true;
}
bool NetUtility::Recv(int fd, void *buf, size_t count, int *length) {
int ret = 0, errno_copy = 0;
*length = 0;
do {
ret = ::recv(fd, (char*)buf + (*length), count, MSG_DONTWAIT);
errno_copy = errno;
if (ret == 0) {
// socket has been closed
VLOG_ERROR() << "recv error: " << strerror(errno_copy);
return true;
}
if (ret > 0) {
count -= ret;
*length += ret;
if (count == 0) {
return true;
}
continue;
}
// if or not try again depends on the error code
if (errno_copy == EINTR) {
continue;
}
if (errno_copy == EAGAIN || errno_copy == EWOULDBLOCK) {
return true;
}
VLOG_ERROR() << "recv error: " << strerror(errno_copy);
return false;
} while (ret > 0 && count > 0);
return true;
}
bool NetUtility::SetNonBlocking(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1) {
return false;
}
if (-1 == fcntl(fd, F_SETFL, flags | O_NONBLOCK)) {
return false;
}
return true;
}
};
|
add time-out connect
|
add time-out connect
|
C++
|
bsd-3-clause
|
zackxue/avidya,wenyongking/avidya,baiduGo/avidya,TheFool0415/avidya,yangaofeng/avidya,CoderJie/avidya,sandynie/avidya,CuriousBoy0822/avidya,wanyisunflower/avidya,CuriousBoy0822/avidya,zackxue/avidya,weimaolong/avidya,hnzhangshilong/avidya,xmandy/avidya,sandynie/avidya,crisish/avidya,wanggchongg/avidya,iCoolcoder/avidya,yangaofeng/avidya,baiduGo/avidya,hnzhangshilong/avidya,fujianbo/avidya,crisish/avidya,JackSon3756/avidya,wenyongking/avidya,CoderJie/avidya,weimaolong/avidya,fujianbo/avidya,wanyisunflower/avidya,songyundi2014/avidya,songyundi2014/avidya,iCoolcoder/avidya,TheFool0415/avidya,wanggchongg/avidya,JackSon3756/avidya,xmandy/avidya
|
6e8b0dd038f2c552979c323ae801de75bd22182c
|
examples/mic.cxx
|
examples/mic.cxx
|
/*
* Author: Yevgeniy Kiveisha <[email protected]>
* Copyright (c) 2014 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice 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 <unistd.h>
#include <iostream>
#include "mic.h"
#include <signal.h>
#include <stdlib.h>
#include <sys/time.h>
int is_running = 0;
uint16_t buffer [128];
upm::Microphone *sensor = NULL;
void
sig_handler(int signo)
{
printf("got signal\n");
if (signo == SIGINT) {
is_running = 1;
}
}
//! [Interesting]
int
main(int argc, char **argv)
{
sensor = new upm::Microphone(0);
signal(SIGINT, sig_handler);
thresholdContext ctx;
ctx.averageReading = 0;
ctx.runningAverage = 0;
ctx.averagedOver = 2;
while (!is_running) {
int len = sensor->getSampledWindow (2, 128, buffer);
if (len) {
int thresh = sensor->findThreshold (&ctx, 30, buffer, len);
sensor->printGraph(&ctx);
if (thresh) {
// do something ....
}
}
}
std::cout << "exiting application" << std::endl;
delete sensor;
return 0;
}
//! [Interesting]
|
/*
* Author: Yevgeniy Kiveisha <[email protected]>
* Copyright (c) 2014 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice 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 <unistd.h>
#include <iostream>
#include "mic.h"
#include <signal.h>
#include <stdlib.h>
#include <sys/time.h>
int is_running = 0;
uint16_t buffer [128];
upm::Microphone *sensor = NULL;
void
sig_handler(int signo)
{
printf("got signal\n");
if (signo == SIGINT) {
is_running = 1;
}
}
//! [Interesting]
int
main(int argc, char **argv)
{
// Attach microphone to analog port A0
sensor = new upm::Microphone(0);
signal(SIGINT, sig_handler);
thresholdContext ctx;
ctx.averageReading = 0;
ctx.runningAverage = 0;
ctx.averagedOver = 2;
// Infinite loop, ends when script is cancelled
// Repeatedly, take a sample every 2 microseconds;
// find the average of 128 samples; and
// print a running graph of the averages
while (!is_running) {
int len = sensor->getSampledWindow (2, 128, buffer);
if (len) {
int thresh = sensor->findThreshold (&ctx, 30, buffer, len);
sensor->printGraph(&ctx);
if (thresh) {
// do something ....
}
}
}
std::cout << "exiting application" << std::endl;
delete sensor;
return 0;
}
//! [Interesting]
|
Add comments to C++ example for Grove microphone/sound sensor
|
mic: Add comments to C++ example for Grove microphone/sound sensor
Signed-off-by: Sarah Knepper <[email protected]>
|
C++
|
mit
|
pylbert/upm,stefan-andritoiu/upm,whbruce/upm,GSmurf/upm,ShawnHymel/upm,g-vidal/upm,malikabhi05/upm,MakerCollider/upm,rafaneri/upm,intel-iot-devkit/upm,tylergibson/upm,Vaghesh/upm,jontrulson/upm,0xD34D/upm,MakerCollider/upm,spitfire88/upm,whbruce/upm,andreivasiliu2211/upm,skiselev/upm,GSmurf/upm,izard/upm,noahchense/upm,Propanu/upm,sasmita/upm,tylergibson/upm,sasmita/upm,GSmurf/upm,g-vidal/upm,jontrulson/upm,afmckinney/upm,jontrulson/upm,whbruce/upm,rafaneri/upm,arfoll/upm,intel-iot-devkit/upm,noahchense/upm,yoyojacky/upm,tylergibson/upm,Jon-ICS/upm,srware/upm,Jon-ICS/upm,srware/upm,stefan-andritoiu/upm,whbruce/upm,intel-iot-devkit/upm,malikabhi05/upm,srware/upm,stefan-andritoiu/upm,arfoll/upm,fieldhawker/upm,mircea/upm,GSmurf/upm,jontrulson/upm,pylbert/upm,sasmita/upm,skiselev/upm,spitfire88/upm,rafaneri/upm,rafaneri/upm,andreivasiliu2211/upm,noahchense/upm,tripzero/upm,skiselev/upm,fieldhawker/upm,0xD34D/upm,stefan-andritoiu/upm,nitirohilla/upm,pylbert/upm,malikabhi05/upm,spitfire88/upm,yoyojacky/upm,skiselev/upm,andreivasiliu2211/upm,g-vidal/upm,afmckinney/upm,malikabhi05/upm,Jon-ICS/upm,yoyojacky/upm,afmckinney/upm,whbruce/upm,yoyojacky/upm,Jon-ICS/upm,ShawnHymel/upm,ShawnHymel/upm,stefan-andritoiu/upm,arfoll/upm,intel-iot-devkit/upm,fieldhawker/upm,mircea/upm,Propanu/upm,mircea/upm,intel-iot-devkit/upm,tripzero/upm,skiselev/upm,tripzero/upm,Jon-ICS/upm,stefan-andritoiu/upm,tripzero/upm,nitirohilla/upm,pylbert/upm,afmckinney/upm,kissbac/upm,intel-iot-devkit/upm,izard/upm,rafaneri/upm,sasmita/upm,MakerCollider/upm,Vaghesh/upm,g-vidal/upm,pylbert/upm,MakerCollider/upm,andreivasiliu2211/upm,srware/upm,kissbac/upm,skiselev/upm,spitfire88/upm,0xD34D/upm,Vaghesh/upm,g-vidal/upm,ShawnHymel/upm,srware/upm,tylergibson/upm,tripzero/upm,mircea/upm,arfoll/upm,kissbac/upm,nitirohilla/upm,Vaghesh/upm,nitirohilla/upm,noahchense/upm,kissbac/upm,afmckinney/upm,mircea/upm,MakerCollider/upm,arfoll/upm,malikabhi05/upm,Propanu/upm,sasmita/upm,Propanu/upm,nitirohilla/upm,kissbac/upm,izard/upm,spitfire88/upm,g-vidal/upm,Propanu/upm,yoyojacky/upm,tylergibson/upm,fieldhawker/upm,Propanu/upm,ShawnHymel/upm,jontrulson/upm,pylbert/upm,malikabhi05/upm,0xD34D/upm,andreivasiliu2211/upm
|
c9fb2cfaaf83ac223005990e7ee00f5162e1695e
|
tests/discovery_test.cpp
|
tests/discovery_test.cpp
|
/* discovery_test.cpp -*- C++ -*-
Rémi Attab ([email protected]), 04 Jan 2014
FreeBSD-style copyright and disclaimer apply
Tests for the discovery mechanism.
*/
#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#include "discovery.h"
#include "lockless/tm.h"
#include "lockless/format.h"
#include <boost/test/unit_test.hpp>
using namespace std;
using namespace slick;
using namespace lockless;
template<typename T>
double waitFor(T& value)
{
double start = lockless::wall();
while (!value);
return lockless::wall() - start;
}
const char* fmt(const std::vector<Address>& node)
{
stringstream ss; ss << "[ ";
for (const auto& addr : node) ss << addr.toString() << " ";
ss << "]";
return ss.str().c_str();
}
const char* fmt(const UUID& uuid)
{
return uuid.toString().c_str();
}
BOOST_AUTO_TEST_CASE(basics)
{
cerr << fmtTitle("basics", '=') << endl;
enum {
Period = 1,
WaitPeriod = Period * 2000 + 100,
};
// Need some random on the ports otherwise you get periodic weird failures
// when the test crash and isn't able to properly close the connection. I
// believe the kernel lags the ipv4 closing while immediately cleaning up
// the ipv6. This means that we're able to bind to the ipv6 but we only ever
// try to connect to the ipv4 (luck of the interface sorting).
const Port Port0 = 1888 + (lockless::rdtsc() % 100);
const Port Port1 = Port0 + 1;
PollThread poller;
DistributedDiscovery node0({}, Port0);
node0.setPeriod(Period);
poller.add(node0);
printf("node0: %s -> %s\n", fmt(node0.id()), fmt(node0.node()));
DistributedDiscovery node1({ Address("localhost", Port0) }, Port1);
node1.setPeriod(Period);
poller.add(node1);
printf("node1: %s -> %s\n", fmt(node1.id()), fmt(node1.node()));
poller.run();
// Wait for both nodes to notice each other.
lockless::sleep(WaitPeriod);
{
cerr << fmtTitle("discover-publish", '-') << endl;
std::atomic<size_t> discovered(0);
node0.discover("key0", [&] (Discovery::WatchHandle handle, const Payload& data) {
discovered = unpack<size_t>(data);
printf("%s: disc=%s -> %lu\n", fmt(node0.id()), "key0", discovered.load());
node0.forget("key0", handle);
});
lockless::sleep(WaitPeriod);
node1.publish("key0", pack(size_t(1)));
double elapsed = waitFor(discovered);
printf("Discoverd in %s\n", fmtElapsed(elapsed).c_str());
BOOST_CHECK_EQUAL(discovered.load(), 1);
}
{
cerr << fmtTitle("publish-discover", '-') << endl;
std::atomic<size_t> discovered(0);
node0.publish("key1", pack(size_t(2)));
lockless::sleep(WaitPeriod);
node1.discover("key1", [&] (Discovery::WatchHandle handle, const Payload& data) {
discovered = unpack<size_t>(data);
node0.forget("key1", handle);
});
double elapsed = waitFor(discovered);
printf("Discoverd in %s\n", fmtElapsed(elapsed).c_str());
BOOST_CHECK_EQUAL(discovered.load(), 2);
}
poller.join();
}
|
/* discovery_test.cpp -*- C++ -*-
Rémi Attab ([email protected]), 04 Jan 2014
FreeBSD-style copyright and disclaimer apply
Tests for the discovery mechanism.
*/
#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#include "discovery.h"
#include "lockless/tm.h"
#include "lockless/format.h"
#include <boost/test/unit_test.hpp>
using namespace std;
using namespace slick;
using namespace lockless;
template<typename T>
double waitFor(T& value)
{
double start = lockless::wall();
while (!value);
return lockless::wall() - start;
}
const char* fmt(const std::vector<Address>& node)
{
stringstream ss; ss << "[ ";
for (const auto& addr : node) ss << addr.toString() << " ";
ss << "]";
return ss.str().c_str();
}
const char* fmt(const UUID& uuid)
{
return uuid.toString().c_str();
}
BOOST_AUTO_TEST_CASE(basics)
{
cerr << fmtTitle("basics", '=') << endl;
enum {
Period = 1,
WaitPeriod = Period * 2000 + 100,
};
// Need some random on the ports otherwise you get periodic weird failures
// when the test crash and isn't able to properly close the connection. I
// believe the kernel lags the ipv4 closing while immediately cleaning up
// the ipv6. This means that we're able to bind to the ipv6 but we only ever
// try to connect to the ipv4 (luck of the interface sorting).
const Port Port0 = 1888 + (lockless::rdtsc() % 100);
const Port Port1 = Port0 + 1;
DistributedDiscovery node0({}, Port0);
node0.setPeriod(Period);
printf("node0: %s -> %s\n", fmt(node0.id()), fmt(node0.node()));
PollThread poller0;
poller0.add(node0);
poller0.run();
DistributedDiscovery node1({ Address("localhost", Port0) }, Port1);
node1.setPeriod(Period);
printf("node1: %s -> %s\n", fmt(node1.id()), fmt(node1.node()));
PollThread poller1;
poller1.add(node1);
poller1.run();
// Wait for both nodes to notice each other.
lockless::sleep(WaitPeriod);
{
cerr << fmtTitle("discover-publish", '-') << endl;
std::atomic<size_t> discovered(0);
node0.discover("key0", [&] (Discovery::WatchHandle handle, const Payload& data) {
discovered = unpack<size_t>(data);
printf("%s: disc=%s -> %lu\n", fmt(node0.id()), "key0", discovered.load());
node0.forget("key0", handle);
});
lockless::sleep(WaitPeriod);
node1.publish("key0", pack(size_t(1)));
double elapsed = waitFor(discovered);
printf("Discoverd in %s\n", fmtElapsed(elapsed).c_str());
BOOST_CHECK_EQUAL(discovered.load(), 1);
}
{
cerr << fmtTitle("publish-discover", '-') << endl;
std::atomic<size_t> discovered(0);
node0.publish("key1", pack(size_t(2)));
lockless::sleep(WaitPeriod);
node1.discover("key1", [&] (Discovery::WatchHandle handle, const Payload& data) {
discovered = unpack<size_t>(data);
node0.forget("key1", handle);
});
double elapsed = waitFor(discovered);
printf("Discoverd in %s\n", fmtElapsed(elapsed).c_str());
BOOST_CHECK_EQUAL(discovered.load(), 2);
}
poller0.join();
poller1.join();
}
|
Split off the nodes into threads for the test.
|
Split off the nodes into threads for the test.
|
C++
|
bsd-2-clause
|
RAttab/slick,RAttab/slick,RAttab/slick
|
0494e3eccc14c88f65f03583f4cec558e44ac1f0
|
simulator/modules/fetch/bpu/t/unit_test.cpp
|
simulator/modules/fetch/bpu/t/unit_test.cpp
|
// generic C
#include <cassert>
#include <cstdlib>
// Catch2
#include <catch.hpp>
// MIPT-MIPS modules
#include "../bpu.h"
TEST_CASE( "Initialization: WrongParameters")
{
// Check failing with wrong input values
CHECK_THROWS_AS( BaseBP::create_bp( "saturating_three_bits", 128, 16), BPInvalidMode);
CHECK_THROWS_AS( BaseBP::create_bp( "saturating_two_bits", 100, 20), BPInvalidMode);
}
TEST_CASE( "Static, all branches not taken")
{
auto bp = BaseBP::create_bp( "always_not_taken", 128, 16);
Addr PC = 28;
Addr target = 12;
bp->update( BPInterface( PC, false, target));
bp->update( BPInterface( PC, true, target));
bp->update( BPInterface( PC, true, target));
CHECK_FALSE( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == PC + 4);
}
TEST_CASE( "Static, all branches taken")
{
auto bp = BaseBP::create_bp( "always_taken", 128, 16);
Addr PC = 28;
Addr target = 12;
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
}
TEST_CASE( "Backward only branches taken")
{
auto bp = BaseBP::create_bp( "backward_jumps", 128, 16);
Addr PC = 28;
Addr target = 12;
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
}
TEST_CASE( "Backward only branches taken in case of forward jump")
{
auto bp = BaseBP::create_bp( "backward_jumps", 128, 16);
Addr PC = 28;
Addr target = 36;
bp->update( BPInterface( PC, true, target));
CHECK_FALSE( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == PC + 4);
}
TEST_CASE( "One bit predictor")
{
auto bp = BaseBP::create_bp( "saturating_one_bit", 128, 16);
Addr PC = 28;
Addr target = 12;
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
}
TEST_CASE( "One bit predictor in case of changed target")
{
auto bp = BaseBP::create_bp( "saturating_one_bit", 128, 16);
Addr PC = 28;
Addr target = 12;
//learn
bp->update( BPInterface( PC, true, target));
//change the target
target = 16;
bp->update( BPInterface( PC, true, target));
CHECK( bp->get_target(PC) == target);
}
TEST_CASE( "Two bit predictor, basic")
{
auto bp = BaseBP::create_bp( "saturating_two_bits", 128, 16);
Addr PC = 28;
Addr target = 12;
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
}
TEST_CASE( "Two bit predictor, advanced")
{
auto bp = BaseBP::create_bp( "saturating_two_bits", 128, 16);
Addr PC = 12;
Addr target = 28;
// Learn
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
// "Over" - learning
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
// Moderate "Un" - learning
bp->update( BPInterface( PC, false, NO_VAL32));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
// Strong "un" - learning
bp->update( BPInterface( PC, false, NO_VAL32));
bp->update( BPInterface( PC, false, NO_VAL32));
bp->update( BPInterface( PC, false, NO_VAL32));
CHECK_FALSE(bp->is_taken(PC));
bp->update( BPInterface( PC, false, NO_VAL32));
CHECK_FALSE(bp->is_taken(PC));
bp->update( BPInterface( PC, false, NO_VAL32));
CHECK_FALSE(bp->is_taken(PC));
bp->update( BPInterface( PC, false, NO_VAL32));
CHECK_FALSE(bp->is_taken(PC));
// Learn again
bp->update( BPInterface( PC, true, target));
CHECK_FALSE(bp->is_taken(PC));
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
}
TEST_CASE( "Adaptive two bit prediction")
{
auto bp = BaseBP::create_bp( "adaptive_two_levels", 128, 16);
Addr PC = 12;
Addr target = 28;
// Learn in sequence 001001001
bp->update( BPInterface( PC, false, target));
bp->update( BPInterface( PC, false, target));
bp->update( BPInterface( PC, true, target));
bp->update( BPInterface( PC, false, target));
bp->update( BPInterface( PC, false, target));
bp->update( BPInterface( PC, true, target));
bp->update( BPInterface( PC, false, target));
bp->update( BPInterface( PC, false, target));
bp->update( BPInterface( PC, true, target));
//check prediction on 00 sequence
bp->update( BPInterface( PC, false, target));
bp->update( BPInterface( PC, false, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
//check prediction on 01 sequence
bp->update( BPInterface( PC, false, target));
bp->update( BPInterface( PC, true, target));
CHECK_FALSE( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == PC + 4);
//check prediction on 10 sequence
bp->update( BPInterface( PC, true, target));
bp->update( BPInterface( PC, false, target));
CHECK_FALSE( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == PC + 4);
}
TEST_CASE( "Adaptive two bit prediction in case of changed target")
{
auto bp = BaseBP::create_bp( "adaptive_two_levels", 128, 16);
Addr PC = 12;
Addr target = 28;
// Learn in sequence 001001001
bp->update( BPInterface( PC, false, target));
bp->update( BPInterface( PC, false, target));
bp->update( BPInterface( PC, true, target));
bp->update( BPInterface( PC, false, target));
bp->update( BPInterface( PC, false, target));
bp->update( BPInterface( PC, true, target));
bp->update( BPInterface( PC, false, target));
bp->update( BPInterface( PC, false, target));
bp->update( BPInterface( PC, true, target));
//change the target
target = 24;
//update the target
bp->update( BPInterface( PC, true, target));
//check if the target was updated
bp->update( BPInterface( PC, false, target));
bp->update( BPInterface( PC, false, target));
CHECK( bp->get_target(PC) == target);
}
TEST_CASE( "Cache Miss")
{
auto bp = BaseBP::create_bp( "saturating_two_bits", 128, 16);
// Check default cache miss behaviour
Addr PC = 12;
CHECK_FALSE(bp->is_taken(PC));
PC = 16;
CHECK_FALSE(bp->is_taken(PC));
PC = 20;
CHECK_FALSE(bp->is_taken(PC));
PC = 12;
CHECK_FALSE(bp->is_taken(PC));
}
TEST_CASE( "Overload: LRU")
{
auto bp = BaseBP::create_bp( "saturating_two_bits", 128, 16);
const Addr PCconst = 16;
Addr target = 48;
// Trying to make it forget the PCconst
for ( int i = 0; i < 1000; i++)
{
bp->update( BPInterface( i, false, NO_VAL32));
if ( i % 50 == 0)
bp->update( BPInterface( PCconst, true, target));
}
// Checking some random PC and PCConst
Addr PC = 4;
CHECK_FALSE( bp->is_taken(PC) );
CHECK( bp->is_taken(PCconst) );
CHECK( bp->get_target(PCconst) == target);
}
|
// generic C
#include <cassert>
#include <cstdlib>
// Catch2
#include <catch.hpp>
// MIPT-MIPS modules
#include "../bpu.h"
TEST_CASE( "Initialization: WrongParameters")
{
// Check failing with wrong input values
CHECK_THROWS_AS( BaseBP::create_bp( "saturating_three_bits", 128, 16), BPInvalidMode);
CHECK_THROWS_AS( BaseBP::create_bp( "saturating_two_bits", 100, 20), BPInvalidMode);
}
TEST_CASE( "Static, all branches not taken")
{
auto bp = BaseBP::create_bp( "always_not_taken", 128, 16);
Addr PC = 28;
Addr target = 12;
bp->update( BPInterface( PC, false, target));
bp->update( BPInterface( PC, true, target));
bp->update( BPInterface( PC, true, target));
CHECK_FALSE( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == PC + 4);
}
TEST_CASE( "Static, all branches taken")
{
auto bp = BaseBP::create_bp( "always_taken", 128, 16);
Addr PC = 28;
Addr target = 12;
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
}
TEST_CASE( "Backward only branches taken")
{
auto bp = BaseBP::create_bp( "backward_jumps", 128, 16);
Addr PC = 28;
Addr target = 12;
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
}
TEST_CASE( "Backward only branches taken in case of forward jump")
{
auto bp = BaseBP::create_bp( "backward_jumps", 128, 16);
Addr PC = 28;
Addr target = 36;
bp->update( BPInterface( PC, true, target));
CHECK_FALSE( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == PC + 4);
}
TEST_CASE( "One bit predictor")
{
auto bp = BaseBP::create_bp( "saturating_one_bit", 128, 16);
Addr PC = 28;
Addr target = 12;
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
}
TEST_CASE( "One bit predictor in case of changed target")
{
auto bp = BaseBP::create_bp( "saturating_one_bit", 128, 16);
Addr PC = 28;
Addr target = 12;
//learn
bp->update( BPInterface( PC, true, target));
//change the target
target = 16;
bp->update( BPInterface( PC, true, target));
CHECK( bp->get_target(PC) == target);
}
TEST_CASE( "Two bit predictor, basic")
{
auto bp = BaseBP::create_bp( "saturating_two_bits", 128, 16);
Addr PC = 28;
Addr target = 12;
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
}
TEST_CASE( "Two bit predictor, advanced")
{
auto bp = BaseBP::create_bp( "saturating_two_bits", 128, 16);
Addr PC = 12;
Addr target = 28;
// Learn
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
// "Over" - learning
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
// Moderate "Un" - learning
bp->update( BPInterface( PC, false, NO_VAL32));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
// Strong "un" - learning
bp->update( BPInterface( PC, false, NO_VAL32));
bp->update( BPInterface( PC, false, NO_VAL32));
bp->update( BPInterface( PC, false, NO_VAL32));
CHECK_FALSE(bp->is_taken(PC));
bp->update( BPInterface( PC, false, NO_VAL32));
CHECK_FALSE(bp->is_taken(PC));
bp->update( BPInterface( PC, false, NO_VAL32));
CHECK_FALSE(bp->is_taken(PC));
bp->update( BPInterface( PC, false, NO_VAL32));
CHECK_FALSE(bp->is_taken(PC));
// Learn again
bp->update( BPInterface( PC, true, target));
CHECK_FALSE(bp->is_taken(PC));
bp->update( BPInterface( PC, true, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
}
static auto get_trained_adaptive_two_level_predictor( Addr PC, Addr target)
{
auto bp = BaseBP::create_bp( "adaptive_two_levels", 128, 16);
// Learn in sequence 001001001
bp->update( BPInterface( PC, false, target));
bp->update( BPInterface( PC, false, target));
bp->update( BPInterface( PC, true, target));
bp->update( BPInterface( PC, false, target));
bp->update( BPInterface( PC, false, target));
bp->update( BPInterface( PC, true, target));
bp->update( BPInterface( PC, false, target));
bp->update( BPInterface( PC, false, target));
bp->update( BPInterface( PC, true, target));
return bp;
}
TEST_CASE( "Adaptive two bit prediction")
{
Addr PC = 12;
Addr target = 28;
auto bp = get_trained_adaptive_two_level_predictor( PC, target);
//check prediction on 00 sequence
bp->update( BPInterface( PC, false, target));
bp->update( BPInterface( PC, false, target));
CHECK( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == target);
//check prediction on 01 sequence
bp->update( BPInterface( PC, false, target));
bp->update( BPInterface( PC, true, target));
CHECK_FALSE( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == PC + 4);
//check prediction on 10 sequence
bp->update( BPInterface( PC, true, target));
bp->update( BPInterface( PC, false, target));
CHECK_FALSE( bp->is_taken(PC) );
CHECK( bp->get_target(PC) == PC + 4);
}
TEST_CASE( "Adaptive two bit prediction in case of changed target")
{
Addr PC = 12;
Addr target = 28;
auto bp = get_trained_adaptive_two_level_predictor( PC, target);
// use different target
target = 24;
bp->update( BPInterface( PC, true, target));
//check if the target was updated
bp->update( BPInterface( PC, false, target));
bp->update( BPInterface( PC, false, target));
CHECK( bp->get_target(PC) == target);
}
TEST_CASE( "Cache Miss")
{
auto bp = BaseBP::create_bp( "saturating_two_bits", 128, 16);
// Check default cache miss behaviour
Addr PC = 12;
CHECK_FALSE(bp->is_taken(PC));
PC = 16;
CHECK_FALSE(bp->is_taken(PC));
PC = 20;
CHECK_FALSE(bp->is_taken(PC));
PC = 12;
CHECK_FALSE(bp->is_taken(PC));
}
TEST_CASE( "Overload: LRU")
{
auto bp = BaseBP::create_bp( "saturating_two_bits", 128, 16);
const Addr PCconst = 16;
Addr target = 48;
// Trying to make it forget the PCconst
for ( int i = 0; i < 1000; i++)
{
bp->update( BPInterface( i, false, NO_VAL32));
if ( i % 50 == 0)
bp->update( BPInterface( PCconst, true, target));
}
// Checking some random PC and PCConst
Addr PC = 4;
CHECK_FALSE( bp->is_taken(PC) );
CHECK( bp->is_taken(PCconst) );
CHECK( bp->get_target(PCconst) == target);
}
|
Clean up duplicated code in BP tests (#645)
|
Clean up duplicated code in BP tests (#645)
|
C++
|
mit
|
MIPT-ILab/mipt-mips-2015,MIPT-ILab/mipt-mips,MIPT-ILab/mipt-mips-2015,MIPT-ILab/mipt-mips,MIPT-ILab/mipt-mips-2015,MIPT-ILab/mipt-mips-2015
|
a58e8ce119dc4dd13b6371511fb26647680dce52
|
runtime/src/main/jni/JsV8InspectorClient.cpp
|
runtime/src/main/jni/JsV8InspectorClient.cpp
|
#include "JsV8InspectorClient.h"
//#include "V8GlobalHelpers.h"
//#include "ArgConverter.h"
//#include "JniLocalRef.h"
//#include "NativeScriptException.h"
//#include "NativeScriptAssert.h"
#include <sstream>
#include <assert.h>
#include <include/libplatform/libplatform.h>
#include "Runtime.h"
#include "NativeScriptException.h"
#include "ArgConverter.h"
using namespace std;
using namespace tns;
using namespace v8;
using namespace v8_inspector;
JsV8InspectorClient::JsV8InspectorClient(v8::Isolate* isolate)
: isolate_(isolate),
inspector_(nullptr),
session_(nullptr),
connection(nullptr),
context_(),
running_nested_loop_(false) {
JEnv env;
inspectorClass = env.FindClass("com/tns/AndroidJsV8Inspector");
assert(inspectorClass != nullptr);
sendMethod = env.GetStaticMethodID(inspectorClass, "send", "(Ljava/lang/Object;Ljava/lang/String;)V");
assert(sendMethod != nullptr);
sendToDevToolsConsoleMethod = env.GetStaticMethodID(inspectorClass, "sendToDevToolsConsole", "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;)V");
assert(sendToDevToolsConsoleMethod != nullptr);
getInspectorMessageMethod = env.GetStaticMethodID(inspectorClass, "getInspectorMessage", "(Ljava/lang/Object;)Ljava/lang/String;");
assert(getInspectorMessageMethod != nullptr);
}
void JsV8InspectorClient::connect(jobject connection) {
JEnv env;
this->connection = env.NewGlobalRef(connection);
}
void JsV8InspectorClient::createInspectorSession(v8::Isolate* isolate, const v8::Local<v8::Context>& context) {
session_ = inspector_->connect(0, this, v8_inspector::StringView());
}
void JsV8InspectorClient::disconnect() {
if (this->connection == nullptr) {
return;
}
Isolate::Scope isolate_scope(isolate_);
v8::HandleScope handleScope(isolate_);
session_->resume();
session_.reset();
JEnv env;
env.DeleteGlobalRef(this->connection);
this->connection = nullptr;
this->createInspectorSession(isolate_, JsV8InspectorClient::PersistentToLocal(isolate_, context_));
}
void JsV8InspectorClient::dispatchMessage(const std::string& message) {
Isolate::Scope isolate_scope(isolate_);
v8::HandleScope handleScope(isolate_);
Context::Scope context_scope(isolate_->GetCurrentContext());
this->doDispatchMessage(isolate_, message);
}
void JsV8InspectorClient::runMessageLoopOnPause(int context_group_id) {
if (running_nested_loop_) {
return;
}
JEnv env;
terminated_ = false;
running_nested_loop_ = true;
while (!terminated_) {
JniLocalRef msg(env.CallStaticObjectMethod(inspectorClass, getInspectorMessageMethod, this->connection));
if (!msg.IsNull()) {
auto inspectorMessage = ArgConverter::jstringToString(msg);
this->doDispatchMessage(this->isolate_, inspectorMessage);
}
while (v8::platform::PumpMessageLoop(Runtime::platform, isolate_)) {
}
}
terminated_ = false;
running_nested_loop_ = false;
}
void JsV8InspectorClient::quitMessageLoopOnPause() {
terminated_ = true;
}
v8::Local<v8::Context> JsV8InspectorClient::ensureDefaultContextInGroup(int contextGroupId) {
v8::Local<v8::Context> context = PersistentToLocal(isolate_, context_);
return context;
}
void JsV8InspectorClient::doDispatchMessage(v8::Isolate* isolate, const std::string& message) {
if (session_ == nullptr) {
return;
}
const String16 msg(message.c_str());
v8_inspector::StringView message_view(reinterpret_cast<const uint16_t*>(msg.characters16()), msg.length());
session_->dispatchProtocolMessage(message_view);
}
void JsV8InspectorClient::sendProtocolResponse(int callId, const v8_inspector::StringView& message) {
sendProtocolNotification(message);
}
static v8_inspector::String16 ToString16(const v8_inspector::StringView& string) {
if (string.is8Bit()) {
return v8_inspector::String16(reinterpret_cast<const char*>(string.characters8()), string.length());
}
return v8_inspector::String16(reinterpret_cast<const uint16_t*>(string.characters16()), string.length());
}
void JsV8InspectorClient::sendProtocolNotification(const v8_inspector::StringView& message) {
if (inspectorClass == nullptr || this->connection == nullptr) {
return;
}
v8_inspector::String16 msg = ToString16(message);
JEnv env;
const char* msss = msg.utf8().c_str();
JniLocalRef str(env.NewStringUTF(msg.utf8().c_str()));
env.CallStaticVoidMethod(inspectorClass, sendMethod, this->connection, (jstring) str);
}
void JsV8InspectorClient::flushProtocolNotifications() {
}
template<class TypeName>
inline v8::Local<TypeName> StrongPersistentToLocal(const v8::Persistent<TypeName>& persistent) {
return *reinterpret_cast<v8::Local<TypeName> *>(const_cast<v8::Persistent<TypeName> *>(&persistent));
}
template<class TypeName>
inline v8::Local<TypeName> WeakPersistentToLocal(v8::Isolate* isolate, const v8::Persistent<TypeName>& persistent) {
return v8::Local<TypeName>::New(isolate, persistent);
}
template<class TypeName>
inline v8::Local<TypeName> JsV8InspectorClient::PersistentToLocal(v8::Isolate* isolate, const v8::Persistent<TypeName>& persistent) {
if (persistent.IsWeak()) {
return WeakPersistentToLocal(isolate, persistent);
} else {
return StrongPersistentToLocal(persistent);
}
}
void JsV8InspectorClient::init() {
if (inspector_ != nullptr) {
return;
}
v8::HandleScope handle_scope(isolate_);
v8::Local<Context> context = isolate_->GetCurrentContext();
v8::Context::Scope context_scope(context);
inspector_ = V8Inspector::create(isolate_, this);
inspector_->contextCreated(v8_inspector::V8ContextInfo(context, 0, v8_inspector::StringView()));
v8::Persistent<v8::Context> persistentContext(context->GetIsolate(), context);
context_.Reset(isolate_, persistentContext);
this->createInspectorSession(isolate_, context);
}
JsV8InspectorClient* JsV8InspectorClient::GetInstance() {
if (instance == nullptr) {
instance = new JsV8InspectorClient(Runtime::GetRuntime(0)->GetIsolate());
}
return instance;
}
void JsV8InspectorClient::sendToFrontEndCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
if ((instance == nullptr) || (instance->connection == nullptr)) {
return;
}
try {
if ((args.Length() > 0) && args[0]->IsString()) {
std::string message = ArgConverter::ConvertToString(args[0]->ToString());
std:
string level = "log";
if (args.Length() > 1 && args[1]->IsString()) {
level = ArgConverter::ConvertToString(args[1]->ToString());
}
JEnv env;
JniLocalRef str(env.NewStringUTF(message.c_str()));
JniLocalRef lev(env.NewStringUTF(level.c_str()));
env.CallStaticVoidMethod(inspectorClass, sendToDevToolsConsoleMethod, instance->connection, (jstring) str, (jstring)lev);
}
} catch (NativeScriptException& e) {
e.ReThrowToV8();
} catch (std::exception e) {
stringstream ss;
ss << "Error: c++ exception: " << e.what() << endl;
NativeScriptException nsEx(ss.str());
nsEx.ReThrowToV8();
} catch (...) {
NativeScriptException nsEx(std::string("Error: c++ exception!"));
nsEx.ReThrowToV8();
}
}
void MessageHandler(v8::Local<v8::Message> message, v8::Local<v8::Value> exception) {
// v8::Isolate *isolate = v8::Isolate::GetCurrent();
// v8::Local<v8::Context> context = isolate->GetEnteredContext();
// if (context.IsEmpty()) return;
// v8_inspector::V8Inspector *inspector = InspectorClientImpl::InspectorFromContext(context);
//
// v8::Local<v8::StackTrace> stack = message->GetStackTrace();
// int script_id = message->GetScriptOrigin().ScriptID()->Value();
// if (!stack.IsEmpty() && stack->GetFrameCount() > 0)
// {
// int top_script_id = stack->GetFrame(0)->GetScriptId();
// if (top_script_id == script_id) script_id = 0;
// }
// int line_number = message->GetLineNumber(context).FromMaybe(0);
// int column_number = 0;
// if (message->GetStartColumn(context).IsJust())
// column_number = message->GetStartColumn(context).FromJust() + 1;
//
// v8_inspector::StringView detailed_message;
// v8_inspector::String16 message_text_string = ToString16(message->Get());
// v8_inspector::StringView message_text(message_text_string.characters16(),
// message_text_string.length());
// v8_inspector::String16 url_string;
// if (message->GetScriptOrigin().ResourceName()->IsString())
// {
// url_string =
// ToString16(message->GetScriptOrigin().ResourceName().As<v8::String>());
// }
// v8_inspector::StringView url(url_string.characters16(), url_string.length());
//
// inspector->exceptionThrown(context, message_text, exception, detailed_message,
// url, line_number, column_number,
// inspector->createStackTrace(stack), script_id);
}
JsV8InspectorClient* JsV8InspectorClient::instance = nullptr;
jclass JsV8InspectorClient::inspectorClass = nullptr;
jmethodID JsV8InspectorClient::sendMethod = nullptr;
jmethodID JsV8InspectorClient::sendToDevToolsConsoleMethod = nullptr;
jmethodID JsV8InspectorClient::getInspectorMessageMethod = nullptr;
|
#include "JsV8InspectorClient.h"
#include <sstream>
#include <assert.h>
#include <include/libplatform/libplatform.h>
#include "Runtime.h"
#include "NativeScriptException.h"
#include "ArgConverter.h"
using namespace std;
using namespace tns;
using namespace v8;
using namespace v8_inspector;
JsV8InspectorClient::JsV8InspectorClient(v8::Isolate* isolate)
: isolate_(isolate),
inspector_(nullptr),
session_(nullptr),
connection(nullptr),
context_(),
running_nested_loop_(false) {
JEnv env;
inspectorClass = env.FindClass("com/tns/AndroidJsV8Inspector");
assert(inspectorClass != nullptr);
sendMethod = env.GetStaticMethodID(inspectorClass, "send", "(Ljava/lang/Object;Ljava/lang/String;)V");
assert(sendMethod != nullptr);
sendToDevToolsConsoleMethod = env.GetStaticMethodID(inspectorClass, "sendToDevToolsConsole", "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;)V");
assert(sendToDevToolsConsoleMethod != nullptr);
getInspectorMessageMethod = env.GetStaticMethodID(inspectorClass, "getInspectorMessage", "(Ljava/lang/Object;)Ljava/lang/String;");
assert(getInspectorMessageMethod != nullptr);
}
void JsV8InspectorClient::connect(jobject connection) {
JEnv env;
this->connection = env.NewGlobalRef(connection);
}
void JsV8InspectorClient::createInspectorSession(v8::Isolate* isolate, const v8::Local<v8::Context>& context) {
session_ = inspector_->connect(0, this, v8_inspector::StringView());
}
void JsV8InspectorClient::disconnect() {
if (this->connection == nullptr) {
return;
}
Isolate::Scope isolate_scope(isolate_);
v8::HandleScope handleScope(isolate_);
session_->resume();
session_.reset();
JEnv env;
env.DeleteGlobalRef(this->connection);
this->connection = nullptr;
this->createInspectorSession(isolate_, JsV8InspectorClient::PersistentToLocal(isolate_, context_));
}
void JsV8InspectorClient::dispatchMessage(const std::string& message) {
Isolate::Scope isolate_scope(isolate_);
v8::HandleScope handleScope(isolate_);
Context::Scope context_scope(isolate_->GetCurrentContext());
this->doDispatchMessage(isolate_, message);
}
void JsV8InspectorClient::runMessageLoopOnPause(int context_group_id) {
if (running_nested_loop_) {
return;
}
JEnv env;
terminated_ = false;
running_nested_loop_ = true;
while (!terminated_) {
JniLocalRef msg(env.CallStaticObjectMethod(inspectorClass, getInspectorMessageMethod, this->connection));
if (!msg.IsNull()) {
auto inspectorMessage = ArgConverter::jstringToString(msg);
this->doDispatchMessage(this->isolate_, inspectorMessage);
}
while (v8::platform::PumpMessageLoop(Runtime::platform, isolate_)) {
}
}
terminated_ = false;
running_nested_loop_ = false;
}
void JsV8InspectorClient::quitMessageLoopOnPause() {
terminated_ = true;
}
v8::Local<v8::Context> JsV8InspectorClient::ensureDefaultContextInGroup(int contextGroupId) {
v8::Local<v8::Context> context = PersistentToLocal(isolate_, context_);
return context;
}
void JsV8InspectorClient::doDispatchMessage(v8::Isolate* isolate, const std::string& message) {
if (session_ == nullptr) {
return;
}
const String16 msg(message.c_str());
v8_inspector::StringView message_view(reinterpret_cast<const uint16_t*>(msg.characters16()), msg.length());
session_->dispatchProtocolMessage(message_view);
}
void JsV8InspectorClient::sendProtocolResponse(int callId, const v8_inspector::StringView& message) {
sendProtocolNotification(message);
}
static v8_inspector::String16 ToString16(const v8_inspector::StringView& string) {
if (string.is8Bit()) {
return v8_inspector::String16(reinterpret_cast<const char*>(string.characters8()), string.length());
}
return v8_inspector::String16(reinterpret_cast<const uint16_t*>(string.characters16()), string.length());
}
void JsV8InspectorClient::sendProtocolNotification(const v8_inspector::StringView& message) {
if (inspectorClass == nullptr || this->connection == nullptr) {
return;
}
v8_inspector::String16 msg = ToString16(message);
JEnv env;
const char* msss = msg.utf8().c_str();
JniLocalRef str(env.NewStringUTF(msg.utf8().c_str()));
env.CallStaticVoidMethod(inspectorClass, sendMethod, this->connection, (jstring) str);
}
void JsV8InspectorClient::flushProtocolNotifications() {
}
template<class TypeName>
inline v8::Local<TypeName> StrongPersistentToLocal(const v8::Persistent<TypeName>& persistent) {
return *reinterpret_cast<v8::Local<TypeName> *>(const_cast<v8::Persistent<TypeName> *>(&persistent));
}
template<class TypeName>
inline v8::Local<TypeName> WeakPersistentToLocal(v8::Isolate* isolate, const v8::Persistent<TypeName>& persistent) {
return v8::Local<TypeName>::New(isolate, persistent);
}
template<class TypeName>
inline v8::Local<TypeName> JsV8InspectorClient::PersistentToLocal(v8::Isolate* isolate, const v8::Persistent<TypeName>& persistent) {
if (persistent.IsWeak()) {
return WeakPersistentToLocal(isolate, persistent);
} else {
return StrongPersistentToLocal(persistent);
}
}
void JsV8InspectorClient::init() {
if (inspector_ != nullptr) {
return;
}
v8::HandleScope handle_scope(isolate_);
v8::Local<Context> context = isolate_->GetCurrentContext();
inspector_ = V8Inspector::create(isolate_, this);
inspector_->contextCreated(v8_inspector::V8ContextInfo(context, 0, v8_inspector::StringView()));
v8::Persistent<v8::Context> persistentContext(context->GetIsolate(), JsV8InspectorClient::PersistentToLocal(isolate_, context_));
context_.Reset(isolate_, persistentContext);
this->createInspectorSession(isolate_, context);
}
JsV8InspectorClient* JsV8InspectorClient::GetInstance() {
if (instance == nullptr) {
instance = new JsV8InspectorClient(Runtime::GetRuntime(0)->GetIsolate());
}
return instance;
}
void JsV8InspectorClient::sendToFrontEndCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
if ((instance == nullptr) || (instance->connection == nullptr)) {
return;
}
try {
if ((args.Length() > 0) && args[0]->IsString()) {
std::string message = ArgConverter::ConvertToString(args[0]->ToString());
std:
string level = "log";
if (args.Length() > 1 && args[1]->IsString()) {
level = ArgConverter::ConvertToString(args[1]->ToString());
}
JEnv env;
JniLocalRef str(env.NewStringUTF(message.c_str()));
JniLocalRef lev(env.NewStringUTF(level.c_str()));
env.CallStaticVoidMethod(inspectorClass, sendToDevToolsConsoleMethod, instance->connection, (jstring) str, (jstring)lev);
}
} catch (NativeScriptException& e) {
e.ReThrowToV8();
} catch (std::exception e) {
stringstream ss;
ss << "Error: c++ exception: " << e.what() << endl;
NativeScriptException nsEx(ss.str());
nsEx.ReThrowToV8();
} catch (...) {
NativeScriptException nsEx(std::string("Error: c++ exception!"));
nsEx.ReThrowToV8();
}
}
void MessageHandler(v8::Local<v8::Message> message, v8::Local<v8::Value> exception) {
// v8::Isolate *isolate = v8::Isolate::GetCurrent();
// v8::Local<v8::Context> context = isolate->GetEnteredContext();
// if (context.IsEmpty()) return;
// v8_inspector::V8Inspector *inspector = InspectorClientImpl::InspectorFromContext(context);
//
// v8::Local<v8::StackTrace> stack = message->GetStackTrace();
// int script_id = message->GetScriptOrigin().ScriptID()->Value();
// if (!stack.IsEmpty() && stack->GetFrameCount() > 0)
// {
// int top_script_id = stack->GetFrame(0)->GetScriptId();
// if (top_script_id == script_id) script_id = 0;
// }
// int line_number = message->GetLineNumber(context).FromMaybe(0);
// int column_number = 0;
// if (message->GetStartColumn(context).IsJust())
// column_number = message->GetStartColumn(context).FromJust() + 1;
//
// v8_inspector::StringView detailed_message;
// v8_inspector::String16 message_text_string = ToString16(message->Get());
// v8_inspector::StringView message_text(message_text_string.characters16(),
// message_text_string.length());
// v8_inspector::String16 url_string;
// if (message->GetScriptOrigin().ResourceName()->IsString())
// {
// url_string =
// ToString16(message->GetScriptOrigin().ResourceName().As<v8::String>());
// }
// v8_inspector::StringView url(url_string.characters16(), url_string.length());
//
// inspector->exceptionThrown(context, message_text, exception, detailed_message,
// url, line_number, column_number,
// inspector->createStackTrace(stack), script_id);
}
JsV8InspectorClient* JsV8InspectorClient::instance = nullptr;
jclass JsV8InspectorClient::inspectorClass = nullptr;
jmethodID JsV8InspectorClient::sendMethod = nullptr;
jmethodID JsV8InspectorClient::sendToDevToolsConsoleMethod = nullptr;
jmethodID JsV8InspectorClient::getInspectorMessageMethod = nullptr;
|
fix console messages not displaying when app is built in debug
|
fix console messages not displaying when app is built in debug
|
C++
|
apache-2.0
|
NativeScript/android-runtime,NativeScript/android-runtime,NativeScript/android-runtime,NativeScript/android-runtime,NativeScript/android-runtime,NativeScript/android-runtime,NativeScript/android-runtime
|
4a8384bcc3f397c03110d92c6f35d4d667e748c4
|
JEB/Test/MacroUtilities.cpp
|
JEB/Test/MacroUtilities.cpp
|
/* JEBTest: A C++ unit testing framework
* Copyright 2013 Jan Erik Breimo
* All rights reserved.
*
* This file is distributed under the BSD License.
* License text is included with the source distribution.
*/
#include "MacroUtilities.hpp"
#include "JEB/Sys/Path.hpp"
#include "JEB/String/String.hpp"
#undef JEB
using namespace JEBTestLib::String;
using namespace JEBTestLib::Sys;
namespace JEB { namespace Test {
// std::string extractTestName(const std::string& name)
// {
// if (startsWith(name, "test_", FindFlags::CaseInsensitive))
// return name.substr(5);
// return name;
// }
std::vector<std::string> extractTestNames(const std::string& names)
{
return split(names, ",");
}
std::string extractSuiteName(const std::string& path)
{
return Path::baseName(Path::removeExtension(path));
}
}}
|
/* JEBTest: A C++ unit testing framework
* Copyright 2013 Jan Erik Breimo
* All rights reserved.
*
* This file is distributed under the BSD License.
* License text is included with the source distribution.
*/
#include "MacroUtilities.hpp"
#include <algorithm>
#include "JEB/Sys/Path.hpp"
#include "JEB/String/String.hpp"
#undef JEB
using namespace JEBTestLib::String;
using namespace JEBTestLib::Sys;
namespace JEB { namespace Test {
// std::string extractTestName(const std::string& name)
// {
// if (startsWith(name, "test_", FindFlags::CaseInsensitive))
// return name.substr(5);
// return name;
// }
std::vector<std::string> extractTestNames(const std::string& names)
{
std::vector<std::string> result = split(names, ",", 0, SplitFlags::IgnoreEmpty);
for (auto it = result.begin(); it != result.end(); ++it)
*it = trim(*it);
return result;
}
std::string extractSuiteName(const std::string& path)
{
return Path::baseName(Path::removeExtension(path));
}
}}
|
Remove white space characters from test names
|
Remove white space characters from test names
|
C++
|
bsd-3-clause
|
jebreimo/JEBTest
|
46101378c3f6b887513a357eb1e130c41be74ab9
|
samples/StarClusters/src/RenderFunctions.cpp
|
samples/StarClusters/src/RenderFunctions.cpp
|
//
// RenderFunctions.cpp
//
// Created by Soso Limited on 7/13/15.
//
//
#include "RenderFunctions.h"
#include "Transform.h"
#include "Circle.h"
#include "RenderLayer.h"
#include "entityx/Entity.h"
#include "cinder/gl/gl.h"
using namespace soso;
using namespace cinder;
void soso::renderAllEntitiesAsCircles(entityx::EntityManager &entities)
{
gl::ScopedDepth depth(true, true);
entityx::ComponentHandle<Transform> transform;
for (auto __unused e : entities.entities_with_components(transform)) {
gl::ScopedModelMatrix mat;
gl::multModelMatrix(transform->worldTransform());
gl::drawSolidCircle(vec2(0), 12.0f);
}
}
void soso::renderCircles(entityx::EntityManager &entities)
{
gl::ScopedDepth depth(true, true);
entityx::ComponentHandle<Transform> transform;
entityx::ComponentHandle<Circle> circle;
auto billboard_xf = [] (Transform::Handle transform) {
auto q = inverse(normalize(quat_cast(transform->worldTransform())));
return transform->worldTransform() * glm::mat4_cast(q);
};
gl::ScopedColor color(Color(1.0f, 1.0f, 1.0f));
for (auto __unused e : entities.entities_with_components(transform, circle)) {
gl::ScopedModelMatrix mat;
gl::multModelMatrix(billboard_xf(transform));
gl::color(circle->color);
gl::drawSolidCircle(vec2(0), circle->radius);
}
}
void soso::renderCirclesDepthSorted(entityx::EntityManager &entities)
{
struct RenderInfo {
ci::vec3 position;
float radius = 1.0f;
ci::Color color;
};
std::vector<RenderInfo> circles;
auto insertion_point = [&circles] (float depth) {
auto iter = circles.begin();
while (iter != circles.end() && depth < iter->position.z) {
++iter;
}
return iter;
};
entityx::ComponentHandle<Transform> transform;
entityx::ComponentHandle<Circle> circle;
for (auto __unused e : entities.entities_with_components(transform, circle)) {
auto pos = vec3(transform->worldTransform() * vec4(0, 0, 0, 1));
circles.insert(insertion_point(pos.z), RenderInfo{pos, circle->radius, circle->color});
}
gl::ScopedColor color(Color(1.0f, 1.0f, 1.0f));
for (auto &c : circles) {
gl::ScopedModelMatrix mat;
gl::translate(c.position);
gl::color(c.color);
gl::drawSolidCircle(vec2(0), c.radius);
}
}
void soso::renderCirclesHierarchically(entityx::EntityManager &entities)
{
entityx::ComponentHandle<Transform> transform;
entityx::ComponentHandle<Circle> circle;
auto xf = mat4(1);
const auto billboard_xf = [] (const Transform &transform) {
auto q = inverse(normalize(quat_cast(transform.localTransform())));
return transform.localTransform() * glm::mat4_cast(q);
};
using function = std::function<void (Transform::Handle)>;
function draw_recursively = [&billboard_xf, &draw_recursively] (Transform::Handle transform) {
gl::ScopedModelMatrix mat;
gl::multModelMatrix(transform->localTransform());
auto circle = transform->entity().component<Circle>();
if (circle)
{
// billboard the circles (mostly works)
gl::ScopedModelMatrix mat;
gl::multModelMatrix(glm::mat4_cast(inverse(normalize(quat_cast(transform->worldTransform())))));
gl::color(circle->color);
gl::drawSolidCircle(vec2(0), circle->radius);
}
for (auto &child: transform->children())
{
draw_recursively(child);
}
};
gl::ScopedColor color(Color::white());
gl::ScopedDepth depth(false);
for (auto __unused e : entities.entities_with_components(transform, circle)) {
if (transform->isRoot())
{
draw_recursively(transform);
}
}
}
void soso::renderCirclesByLayer(entityx::EntityManager &entities)
{
// Data types for collecting render information into layers.
struct DataPoint
{
mat4 transform;
Color color;
float radius;
};
using RenderData = std::vector<DataPoint>;
using RenderDataRef = std::unique_ptr<RenderData>;
struct RenderDataLayer {
RenderDataLayer(int layer)
: layer(layer)
{}
int layer = 0;
RenderDataRef render_data = std::make_unique<RenderData>();
};
// Our layers for rendering
std::vector<RenderDataLayer> layers;
// Returns the requested render layer, creating it if necessary.
auto get_layer = [&layers] (int layer) -> RenderData& {
for (auto &l : layers) {
if (l.layer == layer) {
return *l.render_data;
}
}
layers.emplace_back(RenderDataLayer(layer));
return *layers.back().render_data;
};
// Billboards a transform matrix.
auto billboard_xf = [] (Transform::Handle transform) {
auto q = inverse(normalize(quat_cast(transform->worldTransform())));
return transform->worldTransform() * glm::mat4_cast(q);
};
// Recursive function to properly capture render layer changes.
using function = std::function<void (Transform::Handle, int)>;
function gather_recursively = [&gather_recursively, &get_layer, &billboard_xf] (Transform::Handle transform, int layer) {
auto rlc = entityx::ComponentHandle<soso::RenderLayer>();
auto circle = entityx::ComponentHandle<Circle>();
auto e = transform->entity();
e.unpack(rlc, circle);
if (rlc)
{
if (rlc->relative())
{
layer += rlc->layer();
}
else
{
layer = rlc->layer();
}
}
if (circle)
{
get_layer(layer).push_back({ billboard_xf(transform), circle->color, circle->radius });
}
for (auto &c : transform->children())
{
gather_recursively(c, layer);
}
};
entityx::ComponentHandle<Transform> transform;
for (auto __unused e : entities.entities_with_components(transform))
{
// gather trees for rendering
if (transform->isRoot())
{
gather_recursively(transform, 0);
}
}
// In case we encountered layers out of order, put them into order.
std::sort(layers.begin(), layers.end(), [] (const RenderDataLayer &lhs, const RenderDataLayer &rhs) {
return lhs.layer < rhs.layer;
});
// Draw everything we gathered, by layer.
gl::ScopedModelMatrix mat;
gl::ScopedColor color(Color::white());
for (auto &layer : layers)
{
for (auto &data : *layer.render_data)
{
gl::setModelMatrix(data.transform);
gl::color(data.color);
gl::drawSolidCircle(vec2(0), data.radius);
}
}
}
|
//
// RenderFunctions.cpp
//
// Created by Soso Limited on 7/13/15.
//
//
#include "RenderFunctions.h"
#include "Transform.h"
#include "Circle.h"
#include "RenderLayer.h"
#include "entityx/Entity.h"
#include "cinder/gl/gl.h"
using namespace soso;
using namespace cinder;
void soso::renderAllEntitiesAsCircles(entityx::EntityManager &entities)
{
gl::ScopedDepth depth(true, true);
entityx::ComponentHandle<Transform> transform;
for (auto __unused e : entities.entities_with_components(transform)) {
gl::ScopedModelMatrix mat;
gl::multModelMatrix(transform->worldTransform());
gl::drawSolidCircle(vec2(0), 12.0f);
}
}
void soso::renderCircles(entityx::EntityManager &entities)
{
gl::ScopedDepth depth(true, true);
entityx::ComponentHandle<Transform> transform;
entityx::ComponentHandle<Circle> circle;
auto billboard_xf = [] (Transform::Handle transform) {
auto q = inverse(normalize(quat_cast(transform->worldTransform())));
return transform->worldTransform() * glm::mat4_cast(q);
};
gl::ScopedColor color(Color(1.0f, 1.0f, 1.0f));
for (auto __unused e : entities.entities_with_components(transform, circle)) {
gl::ScopedModelMatrix mat;
gl::multModelMatrix(billboard_xf(transform));
gl::color(circle->color);
gl::drawSolidCircle(vec2(0), circle->radius);
}
}
void soso::renderCirclesDepthSorted(entityx::EntityManager &entities)
{
struct RenderInfo {
ci::vec3 position;
float scale;
float radius = 1.0f;
ci::Color color;
};
std::vector<RenderInfo> circles;
auto insertion_point = [&circles] (float depth) {
auto iter = circles.begin();
while (iter != circles.end() && depth < iter->position.z) {
++iter;
}
return iter;
};
entityx::ComponentHandle<Transform> transform;
entityx::ComponentHandle<Circle> circle;
for (auto __unused e : entities.entities_with_components(transform, circle)) {
auto pos = vec3(transform->worldTransform() * vec4(0, 0, 0, 1));
auto scale = length(vec3(transform->worldTransform() * vec4(1, 0, 0, 0)));
circles.insert(insertion_point(pos.z), RenderInfo{pos, scale, circle->radius, circle->color});
}
gl::ScopedColor color(Color(1.0f, 1.0f, 1.0f));
for (auto &c : circles) {
gl::ScopedModelMatrix mat;
gl::translate(c.position);
gl::scale(vec3(c.scale));
gl::color(c.color);
gl::drawSolidCircle(vec2(0), c.radius);
}
}
void soso::renderCirclesHierarchically(entityx::EntityManager &entities)
{
entityx::ComponentHandle<Transform> transform;
entityx::ComponentHandle<Circle> circle;
auto xf = mat4(1);
const auto billboard_xf = [] (const Transform &transform) {
auto q = inverse(normalize(quat_cast(transform.localTransform())));
return transform.localTransform() * glm::mat4_cast(q);
};
using function = std::function<void (Transform::Handle)>;
function draw_recursively = [&billboard_xf, &draw_recursively] (Transform::Handle transform) {
gl::ScopedModelMatrix mat;
gl::multModelMatrix(transform->localTransform());
auto circle = transform->entity().component<Circle>();
if (circle)
{
// billboard the circles (mostly works)
gl::ScopedModelMatrix mat;
gl::multModelMatrix(glm::mat4_cast(inverse(normalize(quat_cast(transform->worldTransform())))));
gl::color(circle->color);
gl::drawSolidCircle(vec2(0), circle->radius);
}
for (auto &child: transform->children())
{
draw_recursively(child);
}
};
gl::ScopedColor color(Color::white());
gl::ScopedDepth depth(false);
for (auto __unused e : entities.entities_with_components(transform, circle)) {
if (transform->isRoot())
{
draw_recursively(transform);
}
}
}
void soso::renderCirclesByLayer(entityx::EntityManager &entities)
{
// Data types for collecting render information into layers.
struct DataPoint
{
mat4 transform;
Color color;
float radius;
};
using RenderData = std::vector<DataPoint>;
using RenderDataRef = std::unique_ptr<RenderData>;
struct RenderDataLayer {
RenderDataLayer(int layer)
: layer(layer)
{}
int layer = 0;
RenderDataRef render_data = std::make_unique<RenderData>();
};
// Our layers for rendering
std::vector<RenderDataLayer> layers;
// Returns the requested render layer, creating it if necessary.
auto get_layer = [&layers] (int layer) -> RenderData& {
for (auto &l : layers) {
if (l.layer == layer) {
return *l.render_data;
}
}
layers.emplace_back(RenderDataLayer(layer));
return *layers.back().render_data;
};
// Billboards a transform matrix.
auto billboard_xf = [] (Transform::Handle transform) {
auto q = inverse(normalize(quat_cast(transform->worldTransform())));
return transform->worldTransform() * glm::mat4_cast(q);
};
// Recursive function to properly capture render layer changes.
using function = std::function<void (Transform::Handle, int)>;
function gather_recursively = [&gather_recursively, &get_layer, &billboard_xf] (Transform::Handle transform, int layer) {
auto rlc = entityx::ComponentHandle<soso::RenderLayer>();
auto circle = entityx::ComponentHandle<Circle>();
auto e = transform->entity();
e.unpack(rlc, circle);
if (rlc)
{
if (rlc->relative())
{
layer += rlc->layer();
}
else
{
layer = rlc->layer();
}
}
if (circle)
{
get_layer(layer).push_back({ billboard_xf(transform), circle->color, circle->radius });
}
for (auto &c : transform->children())
{
gather_recursively(c, layer);
}
};
entityx::ComponentHandle<Transform> transform;
for (auto __unused e : entities.entities_with_components(transform))
{
// gather trees for rendering
if (transform->isRoot())
{
gather_recursively(transform, 0);
}
}
// In case we encountered layers out of order, put them into order.
std::sort(layers.begin(), layers.end(), [] (const RenderDataLayer &lhs, const RenderDataLayer &rhs) {
return lhs.layer < rhs.layer;
});
// Draw everything we gathered, by layer.
gl::ScopedModelMatrix mat;
gl::ScopedColor color(Color::white());
for (auto &layer : layers)
{
for (auto &data : *layer.render_data)
{
gl::setModelMatrix(data.transform);
gl::color(data.color);
gl::drawSolidCircle(vec2(0), data.radius);
}
}
}
|
Enable uniform scaling in depth sorted circles.
|
Enable uniform scaling in depth sorted circles.
|
C++
|
mit
|
sosolimited/Entity-Component-Samples
|
09a49c77ca30004fd6e49cf3dabcd55f3e929bbd
|
cpp/205.cpp
|
cpp/205.cpp
|
/*
* Hash Table
*/
class Solution {
public:
bool isIsomorphic(string s, string t) {
char map_s[128] = { 0 };
char map_t[128] = { 0 };
int len = s.size();
for (int i = 0; i < len; ++i)
{
if (map_s[s[i]]!=map_t[t[i]]) return false;
map_s[s[i]] = i+1;
map_t[t[i]] = i+1;
}
return true;
}
};
|
/*
* Hash Table
*/
// version 1:
class Solution {
public:
bool isIsomorphic(string s, string t) {
if(s.length() != t.length()) return false;
int len = s.length();
unordered_map<char, int> codedS, codedT; // char --> last appeared index
if(len == 0) return true;
for(int i = 0; i < len; i++) {
char sc = s[i], tc = t[i];
if(codedS[sc] != codedT[tc]) return false;
codedS[sc] = i+1;
codedT[tc] = i+1;
}
return true;
}
};
// version 2:
class Solution {
public:
bool isIsomorphic(string s, string t) {
char map_s[128] = {0};
char map_t[128] = {0};
int len = s.size();
for (int i = 0; i < len; ++i) {
if (map_s[s[i]]!=map_t[t[i]]) return false;
map_s[s[i]] = i+1;
map_t[t[i]] = i+1;
}
return true;
}
};
// Conclusion:
//
// Reference:
//
|
Update 205.cpp
|
Update 205.cpp
|
C++
|
mit
|
xpharry/Leetcode
|
52b4fe63c17dd00554b4f15cd313fd7a6cdf6422
|
samples/gpu/cascadeclassifier_nvidia_api.cpp
|
samples/gpu/cascadeclassifier_nvidia_api.cpp
|
#if defined _MSC_VER && _MSC_VER >= 1400
#pragma warning( disable : 4201 4408 4127 4100)
#endif
#include "cvconfig.h"
#include <iostream>
#include <iomanip>
#include <cstdio>
#include "opencv2/core/cuda.hpp"
#include "opencv2/cudalegacy.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/objdetect.hpp"
#include "opencv2/objdetect/objdetect_c.h"
using namespace std;
using namespace cv;
#if !defined(HAVE_CUDA) || defined(__arm__)
int main( int, const char** )
{
#if !defined(HAVE_CUDA)
std::cout << "CUDA support is required (CMake key 'WITH_CUDA' must be true)." << std::endl;
#endif
#if defined(__arm__)
std::cout << "Unsupported for ARM CUDA library." << std::endl;
#endif
return 0;
}
#else
const Size2i preferredVideoFrameSize(640, 480);
const cv::String wndTitle = "NVIDIA Computer Vision :: Haar Classifiers Cascade";
static void matPrint(Mat &img, int lineOffsY, Scalar fontColor, const string &ss)
{
int fontFace = FONT_HERSHEY_DUPLEX;
double fontScale = 0.8;
int fontThickness = 2;
Size fontSize = cv::getTextSize("T[]", fontFace, fontScale, fontThickness, 0);
Point org;
org.x = 1;
org.y = 3 * fontSize.height * (lineOffsY + 1) / 2;
putText(img, ss, org, fontFace, fontScale, Scalar(0,0,0), 5*fontThickness/2, 16);
putText(img, ss, org, fontFace, fontScale, fontColor, fontThickness, 16);
}
static void displayState(Mat &canvas, bool bHelp, bool bGpu, bool bLargestFace, bool bFilter, double fps)
{
Scalar fontColorRed(0,0,255);
Scalar fontColorNV(0,185,118);
ostringstream ss;
ss << "FPS = " << setprecision(1) << fixed << fps;
matPrint(canvas, 0, fontColorRed, ss.str());
ss.str("");
ss << "[" << canvas.cols << "x" << canvas.rows << "], " <<
(bGpu ? "GPU, " : "CPU, ") <<
(bLargestFace ? "OneFace, " : "MultiFace, ") <<
(bFilter ? "Filter:ON" : "Filter:OFF");
matPrint(canvas, 1, fontColorRed, ss.str());
if (bHelp)
{
matPrint(canvas, 2, fontColorNV, "Space - switch GPU / CPU");
matPrint(canvas, 3, fontColorNV, "M - switch OneFace / MultiFace");
matPrint(canvas, 4, fontColorNV, "F - toggle rectangles Filter");
matPrint(canvas, 5, fontColorNV, "H - toggle hotkeys help");
}
else
{
matPrint(canvas, 2, fontColorNV, "H - toggle hotkeys help");
}
}
static NCVStatus process(Mat *srcdst,
Ncv32u width, Ncv32u height,
NcvBool bFilterRects, NcvBool bLargestFace,
HaarClassifierCascadeDescriptor &haar,
NCVVector<HaarStage64> &d_haarStages, NCVVector<HaarClassifierNode128> &d_haarNodes,
NCVVector<HaarFeature64> &d_haarFeatures, NCVVector<HaarStage64> &h_haarStages,
INCVMemAllocator &gpuAllocator,
INCVMemAllocator &cpuAllocator,
cudaDeviceProp &devProp)
{
ncvAssertReturn(!((srcdst == NULL) ^ gpuAllocator.isCounting()), NCV_NULL_PTR);
NCVStatus ncvStat;
NCV_SET_SKIP_COND(gpuAllocator.isCounting());
NCVMatrixAlloc<Ncv8u> d_src(gpuAllocator, width, height);
ncvAssertReturn(d_src.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC);
NCVMatrixAlloc<Ncv8u> h_src(cpuAllocator, width, height);
ncvAssertReturn(h_src.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC);
NCVVectorAlloc<NcvRect32u> d_rects(gpuAllocator, 100);
ncvAssertReturn(d_rects.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC);
NCV_SKIP_COND_BEGIN
for (Ncv32u i=0; i<(Ncv32u)srcdst->rows; i++)
{
memcpy(h_src.ptr() + i * h_src.stride(), srcdst->ptr(i), srcdst->cols);
}
ncvStat = h_src.copySolid(d_src, 0);
ncvAssertReturnNcvStat(ncvStat);
ncvAssertCUDAReturn(cudaStreamSynchronize(0), NCV_CUDA_ERROR);
NCV_SKIP_COND_END
NcvSize32u roi;
roi.width = d_src.width();
roi.height = d_src.height();
Ncv32u numDetections;
ncvStat = ncvDetectObjectsMultiScale_device(
d_src, roi, d_rects, numDetections, haar, h_haarStages,
d_haarStages, d_haarNodes, d_haarFeatures,
haar.ClassifierSize,
(bFilterRects || bLargestFace) ? 4 : 0,
1.2f, 1,
(bLargestFace ? NCVPipeObjDet_FindLargestObject : 0)
| NCVPipeObjDet_VisualizeInPlace,
gpuAllocator, cpuAllocator, devProp, 0);
ncvAssertReturnNcvStat(ncvStat);
ncvAssertCUDAReturn(cudaStreamSynchronize(0), NCV_CUDA_ERROR);
NCV_SKIP_COND_BEGIN
ncvStat = d_src.copySolid(h_src, 0);
ncvAssertReturnNcvStat(ncvStat);
ncvAssertCUDAReturn(cudaStreamSynchronize(0), NCV_CUDA_ERROR);
for (Ncv32u i=0; i<(Ncv32u)srcdst->rows; i++)
{
memcpy(srcdst->ptr(i), h_src.ptr() + i * h_src.stride(), srcdst->cols);
}
NCV_SKIP_COND_END
return NCV_SUCCESS;
}
int main(int argc, const char** argv)
{
cout << "OpenCV / NVIDIA Computer Vision" << endl;
cout << "Face Detection in video and live feed" << endl;
cout << "Syntax: exename <cascade_file> <image_or_video_or_cameraid>" << endl;
cout << "=========================================" << endl;
ncvAssertPrintReturn(cv::cuda::getCudaEnabledDeviceCount() != 0, "No GPU found or the library is compiled without CUDA support", -1);
ncvAssertPrintReturn(argc == 3, "Invalid number of arguments", -1);
cv::cuda::printShortCudaDeviceInfo(cv::cuda::getDevice());
string cascadeName = argv[1];
string inputName = argv[2];
NCVStatus ncvStat;
NcvBool bQuit = false;
VideoCapture capture;
Size2i frameSize;
//open content source
Mat image = imread(inputName);
Mat frame;
if (!image.empty())
{
frameSize.width = image.cols;
frameSize.height = image.rows;
}
else
{
if (!capture.open(inputName))
{
int camid = -1;
istringstream ss(inputName);
int x = 0;
ss >> x;
ncvAssertPrintReturn(capture.open(camid) != 0, "Can't open source", -1);
}
capture >> frame;
ncvAssertPrintReturn(!frame.empty(), "Empty video source", -1);
frameSize.width = frame.cols;
frameSize.height = frame.rows;
}
NcvBool bUseGPU = true;
NcvBool bLargestObject = false;
NcvBool bFilterRects = true;
NcvBool bHelpScreen = false;
CascadeClassifier classifierOpenCV;
ncvAssertPrintReturn(classifierOpenCV.load(cascadeName) != 0, "Error (in OpenCV) opening classifier", -1);
int devId;
ncvAssertCUDAReturn(cudaGetDevice(&devId), -1);
cudaDeviceProp devProp;
ncvAssertCUDAReturn(cudaGetDeviceProperties(&devProp, devId), -1);
cout << "Using GPU: " << devId << "(" << devProp.name <<
"), arch=" << devProp.major << "." << devProp.minor << endl;
//==============================================================================
//
// Load the classifier from file (assuming its size is about 1 mb)
// using a simple allocator
//
//==============================================================================
NCVMemNativeAllocator gpuCascadeAllocator(NCVMemoryTypeDevice, static_cast<Ncv32u>(devProp.textureAlignment));
ncvAssertPrintReturn(gpuCascadeAllocator.isInitialized(), "Error creating cascade GPU allocator", -1);
NCVMemNativeAllocator cpuCascadeAllocator(NCVMemoryTypeHostPinned, static_cast<Ncv32u>(devProp.textureAlignment));
ncvAssertPrintReturn(cpuCascadeAllocator.isInitialized(), "Error creating cascade CPU allocator", -1);
Ncv32u haarNumStages, haarNumNodes, haarNumFeatures;
ncvStat = ncvHaarGetClassifierSize(cascadeName, haarNumStages, haarNumNodes, haarNumFeatures);
ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error reading classifier size (check the file)", -1);
NCVVectorAlloc<HaarStage64> h_haarStages(cpuCascadeAllocator, haarNumStages);
ncvAssertPrintReturn(h_haarStages.isMemAllocated(), "Error in cascade CPU allocator", -1);
NCVVectorAlloc<HaarClassifierNode128> h_haarNodes(cpuCascadeAllocator, haarNumNodes);
ncvAssertPrintReturn(h_haarNodes.isMemAllocated(), "Error in cascade CPU allocator", -1);
NCVVectorAlloc<HaarFeature64> h_haarFeatures(cpuCascadeAllocator, haarNumFeatures);
ncvAssertPrintReturn(h_haarFeatures.isMemAllocated(), "Error in cascade CPU allocator", -1);
HaarClassifierCascadeDescriptor haar;
ncvStat = ncvHaarLoadFromFile_host(cascadeName, haar, h_haarStages, h_haarNodes, h_haarFeatures);
ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error loading classifier", -1);
NCVVectorAlloc<HaarStage64> d_haarStages(gpuCascadeAllocator, haarNumStages);
ncvAssertPrintReturn(d_haarStages.isMemAllocated(), "Error in cascade GPU allocator", -1);
NCVVectorAlloc<HaarClassifierNode128> d_haarNodes(gpuCascadeAllocator, haarNumNodes);
ncvAssertPrintReturn(d_haarNodes.isMemAllocated(), "Error in cascade GPU allocator", -1);
NCVVectorAlloc<HaarFeature64> d_haarFeatures(gpuCascadeAllocator, haarNumFeatures);
ncvAssertPrintReturn(d_haarFeatures.isMemAllocated(), "Error in cascade GPU allocator", -1);
ncvStat = h_haarStages.copySolid(d_haarStages, 0);
ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error copying cascade to GPU", -1);
ncvStat = h_haarNodes.copySolid(d_haarNodes, 0);
ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error copying cascade to GPU", -1);
ncvStat = h_haarFeatures.copySolid(d_haarFeatures, 0);
ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error copying cascade to GPU", -1);
//==============================================================================
//
// Calculate memory requirements and create real allocators
//
//==============================================================================
NCVMemStackAllocator gpuCounter(static_cast<Ncv32u>(devProp.textureAlignment));
ncvAssertPrintReturn(gpuCounter.isInitialized(), "Error creating GPU memory counter", -1);
NCVMemStackAllocator cpuCounter(static_cast<Ncv32u>(devProp.textureAlignment));
ncvAssertPrintReturn(cpuCounter.isInitialized(), "Error creating CPU memory counter", -1);
ncvStat = process(NULL, frameSize.width, frameSize.height,
false, false, haar,
d_haarStages, d_haarNodes,
d_haarFeatures, h_haarStages,
gpuCounter, cpuCounter, devProp);
ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error in memory counting pass", -1);
NCVMemStackAllocator gpuAllocator(NCVMemoryTypeDevice, gpuCounter.maxSize(), static_cast<Ncv32u>(devProp.textureAlignment));
ncvAssertPrintReturn(gpuAllocator.isInitialized(), "Error creating GPU memory allocator", -1);
NCVMemStackAllocator cpuAllocator(NCVMemoryTypeHostPinned, cpuCounter.maxSize(), static_cast<Ncv32u>(devProp.textureAlignment));
ncvAssertPrintReturn(cpuAllocator.isInitialized(), "Error creating CPU memory allocator", -1);
printf("Initialized for frame size [%dx%d]\n", frameSize.width, frameSize.height);
//==============================================================================
//
// Main processing loop
//
//==============================================================================
namedWindow(wndTitle, 1);
Mat frameDisp;
do
{
Mat gray;
cvtColor((image.empty() ? frame : image), gray, cv::COLOR_BGR2GRAY);
//
// process
//
NcvSize32u minSize = haar.ClassifierSize;
if (bLargestObject)
{
Ncv32u ratioX = preferredVideoFrameSize.width / minSize.width;
Ncv32u ratioY = preferredVideoFrameSize.height / minSize.height;
Ncv32u ratioSmallest = min(ratioX, ratioY);
ratioSmallest = max((Ncv32u)(ratioSmallest / 2.5f), (Ncv32u)1);
minSize.width *= ratioSmallest;
minSize.height *= ratioSmallest;
}
Ncv32f avgTime;
NcvTimer timer = ncvStartTimer();
if (bUseGPU)
{
ncvStat = process(&gray, frameSize.width, frameSize.height,
bFilterRects, bLargestObject, haar,
d_haarStages, d_haarNodes,
d_haarFeatures, h_haarStages,
gpuAllocator, cpuAllocator, devProp);
ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error in memory counting pass", -1);
}
else
{
vector<Rect> rectsOpenCV;
classifierOpenCV.detectMultiScale(
gray,
rectsOpenCV,
1.2f,
bFilterRects ? 4 : 0,
(bLargestObject ? CV_HAAR_FIND_BIGGEST_OBJECT : 0)
| CV_HAAR_SCALE_IMAGE,
Size(minSize.width, minSize.height));
for (size_t rt = 0; rt < rectsOpenCV.size(); ++rt)
rectangle(gray, rectsOpenCV[rt], Scalar(255));
}
avgTime = (Ncv32f)ncvEndQueryTimerMs(timer);
cvtColor(gray, frameDisp, cv::COLOR_GRAY2BGR);
displayState(frameDisp, bHelpScreen, bUseGPU, bLargestObject, bFilterRects, 1000.0f / avgTime);
imshow(wndTitle, frameDisp);
//handle input
switch (cv::waitKey(3))
{
case ' ':
bUseGPU = !bUseGPU;
break;
case 'm':
case 'M':
bLargestObject = !bLargestObject;
break;
case 'f':
case 'F':
bFilterRects = !bFilterRects;
break;
case 'h':
case 'H':
bHelpScreen = !bHelpScreen;
break;
case 27:
bQuit = true;
break;
}
// For camera and video file, capture the next image
if (capture.isOpened())
{
capture >> frame;
if (frame.empty())
{
break;
}
}
} while (!bQuit);
cv::destroyWindow(wndTitle);
return 0;
}
#endif //!defined(HAVE_CUDA)
|
#if defined _MSC_VER && _MSC_VER >= 1400
#pragma warning( disable : 4201 4408 4127 4100)
#endif
#include "opencv2/cvconfig.h"
#include <iostream>
#include <iomanip>
#include <cstdio>
#include "opencv2/core/cuda.hpp"
#include "opencv2/cudalegacy.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/objdetect.hpp"
#include "opencv2/objdetect/objdetect_c.h"
using namespace std;
using namespace cv;
#if !defined(HAVE_CUDA) || defined(__arm__)
int main( int, const char** )
{
#if !defined(HAVE_CUDA)
std::cout << "CUDA support is required (CMake key 'WITH_CUDA' must be true)." << std::endl;
#endif
#if defined(__arm__)
std::cout << "Unsupported for ARM CUDA library." << std::endl;
#endif
return 0;
}
#else
const Size2i preferredVideoFrameSize(640, 480);
const cv::String wndTitle = "NVIDIA Computer Vision :: Haar Classifiers Cascade";
static void matPrint(Mat &img, int lineOffsY, Scalar fontColor, const string &ss)
{
int fontFace = FONT_HERSHEY_DUPLEX;
double fontScale = 0.8;
int fontThickness = 2;
Size fontSize = cv::getTextSize("T[]", fontFace, fontScale, fontThickness, 0);
Point org;
org.x = 1;
org.y = 3 * fontSize.height * (lineOffsY + 1) / 2;
putText(img, ss, org, fontFace, fontScale, Scalar(0,0,0), 5*fontThickness/2, 16);
putText(img, ss, org, fontFace, fontScale, fontColor, fontThickness, 16);
}
static void displayState(Mat &canvas, bool bHelp, bool bGpu, bool bLargestFace, bool bFilter, double fps)
{
Scalar fontColorRed(0,0,255);
Scalar fontColorNV(0,185,118);
ostringstream ss;
ss << "FPS = " << setprecision(1) << fixed << fps;
matPrint(canvas, 0, fontColorRed, ss.str());
ss.str("");
ss << "[" << canvas.cols << "x" << canvas.rows << "], " <<
(bGpu ? "GPU, " : "CPU, ") <<
(bLargestFace ? "OneFace, " : "MultiFace, ") <<
(bFilter ? "Filter:ON" : "Filter:OFF");
matPrint(canvas, 1, fontColorRed, ss.str());
if (bHelp)
{
matPrint(canvas, 2, fontColorNV, "Space - switch GPU / CPU");
matPrint(canvas, 3, fontColorNV, "M - switch OneFace / MultiFace");
matPrint(canvas, 4, fontColorNV, "F - toggle rectangles Filter");
matPrint(canvas, 5, fontColorNV, "H - toggle hotkeys help");
}
else
{
matPrint(canvas, 2, fontColorNV, "H - toggle hotkeys help");
}
}
static NCVStatus process(Mat *srcdst,
Ncv32u width, Ncv32u height,
NcvBool bFilterRects, NcvBool bLargestFace,
HaarClassifierCascadeDescriptor &haar,
NCVVector<HaarStage64> &d_haarStages, NCVVector<HaarClassifierNode128> &d_haarNodes,
NCVVector<HaarFeature64> &d_haarFeatures, NCVVector<HaarStage64> &h_haarStages,
INCVMemAllocator &gpuAllocator,
INCVMemAllocator &cpuAllocator,
cudaDeviceProp &devProp)
{
ncvAssertReturn(!((srcdst == NULL) ^ gpuAllocator.isCounting()), NCV_NULL_PTR);
NCVStatus ncvStat;
NCV_SET_SKIP_COND(gpuAllocator.isCounting());
NCVMatrixAlloc<Ncv8u> d_src(gpuAllocator, width, height);
ncvAssertReturn(d_src.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC);
NCVMatrixAlloc<Ncv8u> h_src(cpuAllocator, width, height);
ncvAssertReturn(h_src.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC);
NCVVectorAlloc<NcvRect32u> d_rects(gpuAllocator, 100);
ncvAssertReturn(d_rects.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC);
NCV_SKIP_COND_BEGIN
for (Ncv32u i=0; i<(Ncv32u)srcdst->rows; i++)
{
memcpy(h_src.ptr() + i * h_src.stride(), srcdst->ptr(i), srcdst->cols);
}
ncvStat = h_src.copySolid(d_src, 0);
ncvAssertReturnNcvStat(ncvStat);
ncvAssertCUDAReturn(cudaStreamSynchronize(0), NCV_CUDA_ERROR);
NCV_SKIP_COND_END
NcvSize32u roi;
roi.width = d_src.width();
roi.height = d_src.height();
Ncv32u numDetections;
ncvStat = ncvDetectObjectsMultiScale_device(
d_src, roi, d_rects, numDetections, haar, h_haarStages,
d_haarStages, d_haarNodes, d_haarFeatures,
haar.ClassifierSize,
(bFilterRects || bLargestFace) ? 4 : 0,
1.2f, 1,
(bLargestFace ? NCVPipeObjDet_FindLargestObject : 0)
| NCVPipeObjDet_VisualizeInPlace,
gpuAllocator, cpuAllocator, devProp, 0);
ncvAssertReturnNcvStat(ncvStat);
ncvAssertCUDAReturn(cudaStreamSynchronize(0), NCV_CUDA_ERROR);
NCV_SKIP_COND_BEGIN
ncvStat = d_src.copySolid(h_src, 0);
ncvAssertReturnNcvStat(ncvStat);
ncvAssertCUDAReturn(cudaStreamSynchronize(0), NCV_CUDA_ERROR);
for (Ncv32u i=0; i<(Ncv32u)srcdst->rows; i++)
{
memcpy(srcdst->ptr(i), h_src.ptr() + i * h_src.stride(), srcdst->cols);
}
NCV_SKIP_COND_END
return NCV_SUCCESS;
}
int main(int argc, const char** argv)
{
cout << "OpenCV / NVIDIA Computer Vision" << endl;
cout << "Face Detection in video and live feed" << endl;
cout << "Syntax: exename <cascade_file> <image_or_video_or_cameraid>" << endl;
cout << "=========================================" << endl;
ncvAssertPrintReturn(cv::cuda::getCudaEnabledDeviceCount() != 0, "No GPU found or the library is compiled without CUDA support", -1);
ncvAssertPrintReturn(argc == 3, "Invalid number of arguments", -1);
cv::cuda::printShortCudaDeviceInfo(cv::cuda::getDevice());
string cascadeName = argv[1];
string inputName = argv[2];
NCVStatus ncvStat;
NcvBool bQuit = false;
VideoCapture capture;
Size2i frameSize;
//open content source
Mat image = imread(inputName);
Mat frame;
if (!image.empty())
{
frameSize.width = image.cols;
frameSize.height = image.rows;
}
else
{
if (!capture.open(inputName))
{
int camid = -1;
istringstream ss(inputName);
int x = 0;
ss >> x;
ncvAssertPrintReturn(capture.open(camid) != 0, "Can't open source", -1);
}
capture >> frame;
ncvAssertPrintReturn(!frame.empty(), "Empty video source", -1);
frameSize.width = frame.cols;
frameSize.height = frame.rows;
}
NcvBool bUseGPU = true;
NcvBool bLargestObject = false;
NcvBool bFilterRects = true;
NcvBool bHelpScreen = false;
CascadeClassifier classifierOpenCV;
ncvAssertPrintReturn(classifierOpenCV.load(cascadeName) != 0, "Error (in OpenCV) opening classifier", -1);
int devId;
ncvAssertCUDAReturn(cudaGetDevice(&devId), -1);
cudaDeviceProp devProp;
ncvAssertCUDAReturn(cudaGetDeviceProperties(&devProp, devId), -1);
cout << "Using GPU: " << devId << "(" << devProp.name <<
"), arch=" << devProp.major << "." << devProp.minor << endl;
//==============================================================================
//
// Load the classifier from file (assuming its size is about 1 mb)
// using a simple allocator
//
//==============================================================================
NCVMemNativeAllocator gpuCascadeAllocator(NCVMemoryTypeDevice, static_cast<Ncv32u>(devProp.textureAlignment));
ncvAssertPrintReturn(gpuCascadeAllocator.isInitialized(), "Error creating cascade GPU allocator", -1);
NCVMemNativeAllocator cpuCascadeAllocator(NCVMemoryTypeHostPinned, static_cast<Ncv32u>(devProp.textureAlignment));
ncvAssertPrintReturn(cpuCascadeAllocator.isInitialized(), "Error creating cascade CPU allocator", -1);
Ncv32u haarNumStages, haarNumNodes, haarNumFeatures;
ncvStat = ncvHaarGetClassifierSize(cascadeName, haarNumStages, haarNumNodes, haarNumFeatures);
ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error reading classifier size (check the file)", -1);
NCVVectorAlloc<HaarStage64> h_haarStages(cpuCascadeAllocator, haarNumStages);
ncvAssertPrintReturn(h_haarStages.isMemAllocated(), "Error in cascade CPU allocator", -1);
NCVVectorAlloc<HaarClassifierNode128> h_haarNodes(cpuCascadeAllocator, haarNumNodes);
ncvAssertPrintReturn(h_haarNodes.isMemAllocated(), "Error in cascade CPU allocator", -1);
NCVVectorAlloc<HaarFeature64> h_haarFeatures(cpuCascadeAllocator, haarNumFeatures);
ncvAssertPrintReturn(h_haarFeatures.isMemAllocated(), "Error in cascade CPU allocator", -1);
HaarClassifierCascadeDescriptor haar;
ncvStat = ncvHaarLoadFromFile_host(cascadeName, haar, h_haarStages, h_haarNodes, h_haarFeatures);
ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error loading classifier", -1);
NCVVectorAlloc<HaarStage64> d_haarStages(gpuCascadeAllocator, haarNumStages);
ncvAssertPrintReturn(d_haarStages.isMemAllocated(), "Error in cascade GPU allocator", -1);
NCVVectorAlloc<HaarClassifierNode128> d_haarNodes(gpuCascadeAllocator, haarNumNodes);
ncvAssertPrintReturn(d_haarNodes.isMemAllocated(), "Error in cascade GPU allocator", -1);
NCVVectorAlloc<HaarFeature64> d_haarFeatures(gpuCascadeAllocator, haarNumFeatures);
ncvAssertPrintReturn(d_haarFeatures.isMemAllocated(), "Error in cascade GPU allocator", -1);
ncvStat = h_haarStages.copySolid(d_haarStages, 0);
ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error copying cascade to GPU", -1);
ncvStat = h_haarNodes.copySolid(d_haarNodes, 0);
ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error copying cascade to GPU", -1);
ncvStat = h_haarFeatures.copySolid(d_haarFeatures, 0);
ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error copying cascade to GPU", -1);
//==============================================================================
//
// Calculate memory requirements and create real allocators
//
//==============================================================================
NCVMemStackAllocator gpuCounter(static_cast<Ncv32u>(devProp.textureAlignment));
ncvAssertPrintReturn(gpuCounter.isInitialized(), "Error creating GPU memory counter", -1);
NCVMemStackAllocator cpuCounter(static_cast<Ncv32u>(devProp.textureAlignment));
ncvAssertPrintReturn(cpuCounter.isInitialized(), "Error creating CPU memory counter", -1);
ncvStat = process(NULL, frameSize.width, frameSize.height,
false, false, haar,
d_haarStages, d_haarNodes,
d_haarFeatures, h_haarStages,
gpuCounter, cpuCounter, devProp);
ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error in memory counting pass", -1);
NCVMemStackAllocator gpuAllocator(NCVMemoryTypeDevice, gpuCounter.maxSize(), static_cast<Ncv32u>(devProp.textureAlignment));
ncvAssertPrintReturn(gpuAllocator.isInitialized(), "Error creating GPU memory allocator", -1);
NCVMemStackAllocator cpuAllocator(NCVMemoryTypeHostPinned, cpuCounter.maxSize(), static_cast<Ncv32u>(devProp.textureAlignment));
ncvAssertPrintReturn(cpuAllocator.isInitialized(), "Error creating CPU memory allocator", -1);
printf("Initialized for frame size [%dx%d]\n", frameSize.width, frameSize.height);
//==============================================================================
//
// Main processing loop
//
//==============================================================================
namedWindow(wndTitle, 1);
Mat frameDisp;
do
{
Mat gray;
cvtColor((image.empty() ? frame : image), gray, cv::COLOR_BGR2GRAY);
//
// process
//
NcvSize32u minSize = haar.ClassifierSize;
if (bLargestObject)
{
Ncv32u ratioX = preferredVideoFrameSize.width / minSize.width;
Ncv32u ratioY = preferredVideoFrameSize.height / minSize.height;
Ncv32u ratioSmallest = min(ratioX, ratioY);
ratioSmallest = max((Ncv32u)(ratioSmallest / 2.5f), (Ncv32u)1);
minSize.width *= ratioSmallest;
minSize.height *= ratioSmallest;
}
Ncv32f avgTime;
NcvTimer timer = ncvStartTimer();
if (bUseGPU)
{
ncvStat = process(&gray, frameSize.width, frameSize.height,
bFilterRects, bLargestObject, haar,
d_haarStages, d_haarNodes,
d_haarFeatures, h_haarStages,
gpuAllocator, cpuAllocator, devProp);
ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error in memory counting pass", -1);
}
else
{
vector<Rect> rectsOpenCV;
classifierOpenCV.detectMultiScale(
gray,
rectsOpenCV,
1.2f,
bFilterRects ? 4 : 0,
(bLargestObject ? CV_HAAR_FIND_BIGGEST_OBJECT : 0)
| CV_HAAR_SCALE_IMAGE,
Size(minSize.width, minSize.height));
for (size_t rt = 0; rt < rectsOpenCV.size(); ++rt)
rectangle(gray, rectsOpenCV[rt], Scalar(255));
}
avgTime = (Ncv32f)ncvEndQueryTimerMs(timer);
cvtColor(gray, frameDisp, cv::COLOR_GRAY2BGR);
displayState(frameDisp, bHelpScreen, bUseGPU, bLargestObject, bFilterRects, 1000.0f / avgTime);
imshow(wndTitle, frameDisp);
//handle input
switch (cv::waitKey(3))
{
case ' ':
bUseGPU = !bUseGPU;
break;
case 'm':
case 'M':
bLargestObject = !bLargestObject;
break;
case 'f':
case 'F':
bFilterRects = !bFilterRects;
break;
case 'h':
case 'H':
bHelpScreen = !bHelpScreen;
break;
case 27:
bQuit = true;
break;
}
// For camera and video file, capture the next image
if (capture.isOpened())
{
capture >> frame;
if (frame.empty())
{
break;
}
}
} while (!bQuit);
cv::destroyWindow(wndTitle);
return 0;
}
#endif //!defined(HAVE_CUDA)
|
Update cascadeclassifier_nvidia_api.cpp
|
Update cascadeclassifier_nvidia_api.cpp
|
C++
|
apache-2.0
|
opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv
|
25abb3ba55253394c1f80872f7f113930861b8a2
|
cpp/683.cpp
|
cpp/683.cpp
|
/*
* BST
*
*/
class Solution {
public:
int kEmptySlots(vector<int>& flowers, int k) {
set<int> s;
for (int i = 0; i < flowers.size(); ++i) {
int cur = flowers[i];
auto it = s.upper_bound(cur);
if (it != s.end() && *it - cur == k + 1) {
return i + 1;
}
it = s.lower_bound(cur);
if (it != s.begin() && cur - *(--it) == k + 1) {
return i + 1;
}
s.insert(cur);
}
return -1;
}
};
// Reference:
// http://www.cnblogs.com/grandyang/p/8415880.html
// https://leetcode.com/problems/k-empty-slots/discuss/107948/Iterate-over-time-vs.-iterate-over-position
|
/*
* BST
*
*/
// version 1:
class Solution {
public:
int kEmptySlots(vector<int>& flowers, int k) {
set<int> s;
for (int i = 0; i < flowers.size(); ++i) {
int cur = flowers[i];
auto it = s.upper_bound(cur);
if (it != s.end() && *it - cur == k + 1) {
return i + 1;
}
it = s.lower_bound(cur);
if (it != s.begin() && cur - *(--it) == k + 1) {
return i + 1;
}
s.insert(cur);
}
return -1;
}
};
// version 2:
class Solution {
public:
int kEmptySlots(vector<int>& flowers, int k) {
int n = flowers.size();
if (n == 0 || k >= n) return -1;
set<int> xs;
for (int i = 0; i < n; ++i) {
int x = flowers[i];
auto r = xs.insert(x).first;
auto l = r;
if (++r != xs.end() && *r == x + k + 1) return i + 1;
if (l != xs.begin() && *(--l) == x - k - 1) return i + 1;
}
return -1;
}
};
// Conclusion:
// Observe from the time view, we tranverse the array "flowers" and by time we store each flower position in order.
// So we can refer to set container in cpp which is implemented as a Balanced Binary Tree. By set, we can easily
// visit the prior and following value by lower_bound and upper_bound.
//
// Set in cpp:
// Sets are containers that store unique elements following a specific order.
// Sets are typically implemented as binary search trees.
// std::set::upper_bound (>) & std::set::lower_bound (>=)
// - Returns an iterator pointing to the first element in the container which is considered to go after val.
// - lower_bound, has the same behavior as upper_bound, except in the case that the set contains an element
// equivalent to val: In this case lower_bound returns an iterator pointing to that element, whereas upper_bound
// returns an iterator pointing to the next element.
//
// Reference:
// http://www.cnblogs.com/grandyang/p/8415880.html
// https://leetcode.com/problems/k-empty-slots/discuss/107948/Iterate-over-time-vs.-iterate-over-position
|
Update 683.cpp
|
Update 683.cpp
|
C++
|
mit
|
xpharry/Leetcode
|
8a96469ed0ac0a35f988202adc70c9a03c4feb5b
|
modules/control/controller/lon_controller.cc
|
modules/control/controller/lon_controller.cc
|
/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/control/controller/lon_controller.h"
#include <cstdio>
#include <utility>
#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/common/log.h"
#include "modules/common/math/math_utils.h"
#include "modules/common/time/time.h"
#include "modules/common/util/string_util.h"
#include "modules/control/common/control_gflags.h"
#include "modules/localization/common/localization_gflags.h"
namespace apollo {
namespace control {
using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::TrajectoryPoint;
using apollo::common::VehicleStateProvider;
using apollo::common::time::Clock;
constexpr double GRA_ACC = 9.8;
LonController::LonController()
: name_(ControlConf_ControllerType_Name(ControlConf::LON_CONTROLLER)) {
if (FLAGS_enable_csv_debug) {
time_t rawtime;
char name_buffer[80];
std::time(&rawtime);
strftime(name_buffer, 80, "/tmp/speed_log__%F_%H%M%S.csv",
localtime(&rawtime));
speed_log_file_ = fopen(name_buffer, "w");
if (speed_log_file_ == nullptr) {
AERROR << "Fail to open file:" << name_buffer;
FLAGS_enable_csv_debug = false;
}
if (speed_log_file_ != nullptr) {
fprintf(speed_log_file_,
"station_reference,"
"station_error,"
"station_error_limited,"
"preview_station_error,"
"speed_reference,"
"speed_error,"
"speed_error_limited,"
"preview_speed_reference,"
"preview_speed_error,"
"preview_acceleration_reference,"
"acceleration_cmd_closeloop,"
"acceleration_cmd,"
"acceleration_lookup,"
"speed_lookup,"
"calibration_value,"
"throttle_cmd,"
"brake_cmd,"
"is_full_stop,"
"\r\n");
fflush(speed_log_file_);
}
AINFO << name_ << " used.";
}
}
void LonController::CloseLogFile() {
if (FLAGS_enable_csv_debug) {
if (speed_log_file_ != nullptr) {
fclose(speed_log_file_);
speed_log_file_ = nullptr;
}
}
}
void LonController::Stop() { CloseLogFile(); }
LonController::~LonController() { CloseLogFile(); }
Status LonController::Init(const ControlConf *control_conf) {
control_conf_ = control_conf;
if (control_conf_ == nullptr) {
controller_initialized_ = false;
AERROR << "get_longitudinal_param() nullptr";
return Status(ErrorCode::CONTROL_INIT_ERROR,
"Failed to load LonController conf");
}
const LonControllerConf &lon_controller_conf =
control_conf_->lon_controller_conf();
station_pid_controller_.Init(lon_controller_conf.station_pid_conf());
speed_pid_controller_.Init(lon_controller_conf.low_speed_pid_conf());
vehicle_param_.CopyFrom(
common::VehicleConfigHelper::instance()->GetConfig().vehicle_param());
SetDigitalFilterPitchAngle(lon_controller_conf);
LoadControlCalibrationTable(lon_controller_conf);
controller_initialized_ = true;
return Status::OK();
}
void LonController::SetDigitalFilterPitchAngle(
const LonControllerConf &lon_controller_conf) {
double cutoff_freq =
lon_controller_conf.pitch_angle_filter_conf().cutoff_freq();
double ts = lon_controller_conf.ts();
SetDigitalFilter(ts, cutoff_freq, &digital_filter_pitch_angle_);
}
void LonController::LoadControlCalibrationTable(
const LonControllerConf &lon_controller_conf) {
const auto &control_table = lon_controller_conf.calibration_table();
AINFO << "Control calibration table loaded";
AINFO << "Control calibration table size is "
<< control_table.calibration_size();
Interpolation2D::DataType xyz;
for (const auto &calibration : control_table.calibration()) {
xyz.push_back(std::make_tuple(calibration.speed(),
calibration.acceleration(),
calibration.command()));
}
control_interpolation_.reset(new Interpolation2D);
CHECK(control_interpolation_->Init(xyz))
<< "Fail to load control calibration table";
}
Status LonController::ComputeControlCommand(
const localization::LocalizationEstimate *localization,
const canbus::Chassis *chassis,
const planning::ADCTrajectory *planning_published_trajectory,
control::ControlCommand *cmd) {
localization_ = localization;
chassis_ = chassis;
trajectory_message_ = planning_published_trajectory;
if (!control_interpolation_) {
AERROR << "Fail to initialize calibration table.";
return Status(ErrorCode::CONTROL_COMPUTE_ERROR,
"Fail to initialize calibration table.");
}
if (trajectory_analyzer_ == nullptr ||
trajectory_analyzer_->seq_num() !=
trajectory_message_->header().sequence_num()) {
trajectory_analyzer_.reset(new TrajectoryAnalyzer(trajectory_message_));
}
const LonControllerConf &lon_controller_conf =
control_conf_->lon_controller_conf();
auto debug = cmd->mutable_debug()->mutable_simple_lon_debug();
debug->Clear();
double brake_cmd = 0.0;
double throttle_cmd = 0.0;
double ts = lon_controller_conf.ts();
double preview_time = lon_controller_conf.preview_window() * ts;
if (preview_time < 0.0) {
const auto error_msg = common::util::StrCat(
"Preview time set as: ", preview_time, " less than 0");
AERROR << error_msg;
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, error_msg);
}
ComputeLongitudinalErrors(trajectory_analyzer_.get(), preview_time, debug);
double station_error_limit = lon_controller_conf.station_error_limit();
double station_error_limited = 0.0;
if (FLAGS_enable_speed_station_preview) {
station_error_limited =
common::math::Clamp(debug->preview_station_error(),
-station_error_limit, station_error_limit);
} else {
station_error_limited = common::math::Clamp(
debug->station_error(), -station_error_limit, station_error_limit);
}
double speed_offset =
station_pid_controller_.Control(station_error_limited, ts);
double speed_controller_input = 0.0;
double speed_controller_input_limit =
lon_controller_conf.speed_controller_input_limit();
double speed_controller_input_limited = 0.0;
if (FLAGS_enable_speed_station_preview) {
speed_controller_input = speed_offset + debug->preview_speed_error();
} else {
speed_controller_input = speed_offset + debug->speed_error();
}
speed_controller_input_limited =
common::math::Clamp(speed_controller_input, -speed_controller_input_limit,
speed_controller_input_limit);
double acceleration_cmd_closeloop = 0.0;
if (VehicleStateProvider::instance()->linear_velocity() <=
lon_controller_conf.switch_speed()) {
speed_pid_controller_.SetPID(lon_controller_conf.low_speed_pid_conf());
acceleration_cmd_closeloop =
speed_pid_controller_.Control(speed_controller_input_limited, ts);
} else {
speed_pid_controller_.SetPID(lon_controller_conf.high_speed_pid_conf());
acceleration_cmd_closeloop =
speed_pid_controller_.Control(speed_controller_input_limited, ts);
}
double slope_offset_compenstaion = digital_filter_pitch_angle_.Filter(
GRA_ACC * std::sin(VehicleStateProvider::instance()->pitch()));
debug->set_slope_offset_compensation(slope_offset_compenstaion);
double acceleration_cmd =
acceleration_cmd_closeloop + debug->preview_acceleration_reference() +
FLAGS_enable_slope_offset * debug->slope_offset_compensation();
debug->set_is_full_stop(false);
GetPathRemain(debug);
if ((std::fabs(debug->preview_acceleration_reference()) <=
FLAGS_max_acceleration_when_stopped &&
std::fabs(debug->preview_speed_reference()) <=
vehicle_param_.max_abs_speed_when_stopped()) ||
(debug->path_remain() < 0.3)) {
acceleration_cmd = lon_controller_conf.standstill_acceleration();
AINFO << "Stop location reached";
debug->set_is_full_stop(true);
}
double throttle_deadzone = lon_controller_conf.throttle_deadzone();
double brake_deadzone = lon_controller_conf.brake_deadzone();
double calibration_value = 0.0;
if (FLAGS_use_preview_speed_for_table) {
calibration_value = control_interpolation_->Interpolate(
std::make_pair(debug->preview_speed_reference(), acceleration_cmd));
} else {
calibration_value = control_interpolation_->Interpolate(
std::make_pair(chassis_->speed_mps(), acceleration_cmd));
}
if (calibration_value >= 0) {
throttle_cmd = calibration_value > throttle_deadzone ? calibration_value
: throttle_deadzone;
brake_cmd = 0.0;
} else {
throttle_cmd = 0.0;
brake_cmd = -calibration_value > brake_deadzone ? -calibration_value
: brake_deadzone;
}
debug->set_station_error_limited(station_error_limited);
debug->set_speed_controller_input_limited(speed_controller_input_limited);
debug->set_acceleration_cmd(acceleration_cmd);
debug->set_throttle_cmd(throttle_cmd);
debug->set_brake_cmd(brake_cmd);
debug->set_acceleration_lookup(acceleration_cmd);
debug->set_speed_lookup(chassis_->speed_mps());
debug->set_calibration_value(calibration_value);
debug->set_acceleration_cmd_closeloop(acceleration_cmd_closeloop);
if (FLAGS_enable_csv_debug && speed_log_file_ != nullptr) {
fprintf(speed_log_file_,
"%.6f, %.6f, %.6f, %.6f, %.6f, %.6f, %.6f, %.6f, %.6f, %.6f,"
"%.6f, %.6f, %.6f, %.6f, %.6f, %.6f, %.6f, %d,\r\n",
debug->station_reference(), debug->station_error(),
station_error_limited, debug->preview_station_error(),
debug->speed_reference(), debug->speed_error(),
speed_controller_input_limited, debug->preview_speed_reference(),
debug->preview_speed_error(),
debug->preview_acceleration_reference(), acceleration_cmd_closeloop,
acceleration_cmd, debug->acceleration_lookup(),
debug->speed_lookup(), calibration_value, throttle_cmd, brake_cmd,
debug->is_full_stop());
}
cmd->set_throttle(throttle_cmd);
cmd->set_brake(brake_cmd);
if (std::fabs(VehicleStateProvider::instance()->linear_velocity()) <=
vehicle_param_.max_abs_speed_when_stopped() ||
chassis->gear_location() == trajectory_message_->gear() ||
chassis->gear_location() == canbus::Chassis::GEAR_NEUTRAL) {
cmd->set_gear_location(trajectory_message_->gear());
} else {
cmd->set_gear_location(chassis->gear_location());
}
return Status::OK();
}
Status LonController::Reset() {
speed_pid_controller_.Reset();
station_pid_controller_.Reset();
return Status::OK();
}
std::string LonController::Name() const { return name_; }
void LonController::ComputeLongitudinalErrors(
const TrajectoryAnalyzer *trajectory_analyzer, const double preview_time,
SimpleLongitudinalDebug *debug) {
// the decomposed vehicle motion onto Frenet frame
// s: longitudinal accumulated distance along reference trajectory
// s_dot: longitudinal velocity along reference trajectory
// d: lateral distance w.r.t. reference trajectory
// d_dot: lateral distance change rate, i.e. dd/dt
double s_matched = 0.0;
double s_dot_matched = 0.0;
double d_matched = 0.0;
double d_dot_matched = 0.0;
auto matched_point = trajectory_analyzer->QueryMatchedPathPoint(
VehicleStateProvider::instance()->x(),
VehicleStateProvider::instance()->y());
trajectory_analyzer->ToTrajectoryFrame(
VehicleStateProvider::instance()->x(),
VehicleStateProvider::instance()->y(),
VehicleStateProvider::instance()->heading(),
VehicleStateProvider::instance()->linear_velocity(), matched_point,
&s_matched, &s_dot_matched, &d_matched, &d_dot_matched);
double current_control_time = Clock::NowInSeconds();
double preview_control_time = current_control_time + preview_time;
TrajectoryPoint reference_point =
trajectory_analyzer->QueryNearestPointByAbsoluteTime(
current_control_time);
TrajectoryPoint preview_point =
trajectory_analyzer->QueryNearestPointByAbsoluteTime(
preview_control_time);
ADEBUG << "matched point:" << matched_point.DebugString();
ADEBUG << "reference point:" << reference_point.DebugString();
ADEBUG << "preview point:" << preview_point.DebugString();
debug->set_station_error(reference_point.path_point().s() - s_matched);
debug->set_speed_error(reference_point.v() - s_dot_matched);
debug->set_station_reference(reference_point.path_point().s());
debug->set_speed_reference(reference_point.v());
debug->set_preview_station_error(preview_point.path_point().s() - s_matched);
debug->set_preview_speed_error(preview_point.v() - s_dot_matched);
debug->set_preview_speed_reference(preview_point.v());
debug->set_preview_acceleration_reference(preview_point.a());
debug->set_current_station(s_matched);
}
void LonController::SetDigitalFilter(double ts, double cutoff_freq,
common::DigitalFilter *digital_filter) {
std::vector<double> denominators;
std::vector<double> numerators;
common::LpfCoefficients(ts, cutoff_freq, &denominators, &numerators);
digital_filter->set_coefficients(denominators, numerators);
}
void LonController::GetPathRemain(SimpleLongitudinalDebug *debug) {
int stop_index = 0;
while (stop_index < trajectory_message_->trajectory_point_size()) {
if (fabs(trajectory_message_->trajectory_point(stop_index).v()) < 1e-3 &&
trajectory_message_->trajectory_point(stop_index).a() > -0.01 &&
trajectory_message_->trajectory_point(stop_index).a() < 0.0) {
break;
} else {
++stop_index;
}
}
if (stop_index == trajectory_message_->trajectory_point_size()) {
--stop_index;
if (fabs(trajectory_message_->trajectory_point(stop_index).v()) < 0.1) {
AINFO << "the last point is selected as parking point";
} else {
AINFO << "the last point found in path and speed > speed_deadzone";
debug->set_path_remain(10000);
}
}
debug->set_path_remain(
trajectory_message_->trajectory_point(stop_index).path_point().s() -
debug->current_station());
}
} // namespace control
} // namespace apollo
|
/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/control/controller/lon_controller.h"
#include <cstdio>
#include <utility>
#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/common/log.h"
#include "modules/common/math/math_utils.h"
#include "modules/common/time/time.h"
#include "modules/common/util/string_util.h"
#include "modules/control/common/control_gflags.h"
#include "modules/localization/common/localization_gflags.h"
namespace apollo {
namespace control {
using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::TrajectoryPoint;
using apollo::common::VehicleStateProvider;
using apollo::common::time::Clock;
constexpr double GRA_ACC = 9.8;
LonController::LonController()
: name_(ControlConf_ControllerType_Name(ControlConf::LON_CONTROLLER)) {
if (FLAGS_enable_csv_debug) {
time_t rawtime;
char name_buffer[80];
std::time(&rawtime);
strftime(name_buffer, 80, "/tmp/speed_log__%F_%H%M%S.csv",
localtime(&rawtime));
speed_log_file_ = fopen(name_buffer, "w");
if (speed_log_file_ == nullptr) {
AERROR << "Fail to open file:" << name_buffer;
FLAGS_enable_csv_debug = false;
}
if (speed_log_file_ != nullptr) {
fprintf(speed_log_file_,
"station_reference,"
"station_error,"
"station_error_limited,"
"preview_station_error,"
"speed_reference,"
"speed_error,"
"speed_error_limited,"
"preview_speed_reference,"
"preview_speed_error,"
"preview_acceleration_reference,"
"acceleration_cmd_closeloop,"
"acceleration_cmd,"
"acceleration_lookup,"
"speed_lookup,"
"calibration_value,"
"throttle_cmd,"
"brake_cmd,"
"is_full_stop,"
"\r\n");
fflush(speed_log_file_);
}
AINFO << name_ << " used.";
}
}
void LonController::CloseLogFile() {
if (FLAGS_enable_csv_debug) {
if (speed_log_file_ != nullptr) {
fclose(speed_log_file_);
speed_log_file_ = nullptr;
}
}
}
void LonController::Stop() { CloseLogFile(); }
LonController::~LonController() { CloseLogFile(); }
Status LonController::Init(const ControlConf *control_conf) {
control_conf_ = control_conf;
if (control_conf_ == nullptr) {
controller_initialized_ = false;
AERROR << "get_longitudinal_param() nullptr";
return Status(ErrorCode::CONTROL_INIT_ERROR,
"Failed to load LonController conf");
}
const LonControllerConf &lon_controller_conf =
control_conf_->lon_controller_conf();
station_pid_controller_.Init(lon_controller_conf.station_pid_conf());
speed_pid_controller_.Init(lon_controller_conf.low_speed_pid_conf());
vehicle_param_.CopyFrom(
common::VehicleConfigHelper::instance()->GetConfig().vehicle_param());
SetDigitalFilterPitchAngle(lon_controller_conf);
LoadControlCalibrationTable(lon_controller_conf);
controller_initialized_ = true;
return Status::OK();
}
void LonController::SetDigitalFilterPitchAngle(
const LonControllerConf &lon_controller_conf) {
double cutoff_freq =
lon_controller_conf.pitch_angle_filter_conf().cutoff_freq();
double ts = lon_controller_conf.ts();
SetDigitalFilter(ts, cutoff_freq, &digital_filter_pitch_angle_);
}
void LonController::LoadControlCalibrationTable(
const LonControllerConf &lon_controller_conf) {
const auto &control_table = lon_controller_conf.calibration_table();
AINFO << "Control calibration table loaded";
AINFO << "Control calibration table size is "
<< control_table.calibration_size();
Interpolation2D::DataType xyz;
for (const auto &calibration : control_table.calibration()) {
xyz.push_back(std::make_tuple(calibration.speed(),
calibration.acceleration(),
calibration.command()));
}
control_interpolation_.reset(new Interpolation2D);
CHECK(control_interpolation_->Init(xyz))
<< "Fail to load control calibration table";
}
Status LonController::ComputeControlCommand(
const localization::LocalizationEstimate *localization,
const canbus::Chassis *chassis,
const planning::ADCTrajectory *planning_published_trajectory,
control::ControlCommand *cmd) {
localization_ = localization;
chassis_ = chassis;
trajectory_message_ = planning_published_trajectory;
if (!control_interpolation_) {
AERROR << "Fail to initialize calibration table.";
return Status(ErrorCode::CONTROL_COMPUTE_ERROR,
"Fail to initialize calibration table.");
}
if (trajectory_analyzer_ == nullptr ||
trajectory_analyzer_->seq_num() !=
trajectory_message_->header().sequence_num()) {
trajectory_analyzer_.reset(new TrajectoryAnalyzer(trajectory_message_));
}
const LonControllerConf &lon_controller_conf =
control_conf_->lon_controller_conf();
auto debug = cmd->mutable_debug()->mutable_simple_lon_debug();
debug->Clear();
double brake_cmd = 0.0;
double throttle_cmd = 0.0;
double ts = lon_controller_conf.ts();
double preview_time = lon_controller_conf.preview_window() * ts;
if (preview_time < 0.0) {
const auto error_msg = common::util::StrCat(
"Preview time set as: ", preview_time, " less than 0");
AERROR << error_msg;
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, error_msg);
}
ComputeLongitudinalErrors(trajectory_analyzer_.get(), preview_time, debug);
double station_error_limit = lon_controller_conf.station_error_limit();
double station_error_limited = 0.0;
if (FLAGS_enable_speed_station_preview) {
station_error_limited =
common::math::Clamp(debug->preview_station_error(),
-station_error_limit, station_error_limit);
} else {
station_error_limited = common::math::Clamp(
debug->station_error(), -station_error_limit, station_error_limit);
}
double speed_offset =
station_pid_controller_.Control(station_error_limited, ts);
double speed_controller_input = 0.0;
double speed_controller_input_limit =
lon_controller_conf.speed_controller_input_limit();
double speed_controller_input_limited = 0.0;
if (FLAGS_enable_speed_station_preview) {
speed_controller_input = speed_offset + debug->preview_speed_error();
} else {
speed_controller_input = speed_offset + debug->speed_error();
}
speed_controller_input_limited =
common::math::Clamp(speed_controller_input, -speed_controller_input_limit,
speed_controller_input_limit);
double acceleration_cmd_closeloop = 0.0;
if (VehicleStateProvider::instance()->linear_velocity() <=
lon_controller_conf.switch_speed()) {
speed_pid_controller_.SetPID(lon_controller_conf.low_speed_pid_conf());
acceleration_cmd_closeloop =
speed_pid_controller_.Control(speed_controller_input_limited, ts);
} else {
speed_pid_controller_.SetPID(lon_controller_conf.high_speed_pid_conf());
acceleration_cmd_closeloop =
speed_pid_controller_.Control(speed_controller_input_limited, ts);
}
double slope_offset_compenstaion = digital_filter_pitch_angle_.Filter(
GRA_ACC * std::sin(VehicleStateProvider::instance()->pitch()));
if (isnan(slope_offset_compenstaion)) {
slope_offset_compenstaion = 0;
}
debug->set_slope_offset_compensation(slope_offset_compenstaion);
double acceleration_cmd =
acceleration_cmd_closeloop + debug->preview_acceleration_reference() +
FLAGS_enable_slope_offset * debug->slope_offset_compensation();
debug->set_is_full_stop(false);
GetPathRemain(debug);
if ((std::fabs(debug->preview_acceleration_reference()) <=
FLAGS_max_acceleration_when_stopped &&
std::fabs(debug->preview_speed_reference()) <=
vehicle_param_.max_abs_speed_when_stopped()) ||
(debug->path_remain() < 0.3)) {
acceleration_cmd = lon_controller_conf.standstill_acceleration();
AINFO << "Stop location reached";
debug->set_is_full_stop(true);
}
double throttle_deadzone = lon_controller_conf.throttle_deadzone();
double brake_deadzone = lon_controller_conf.brake_deadzone();
double calibration_value = 0.0;
if (FLAGS_use_preview_speed_for_table) {
calibration_value = control_interpolation_->Interpolate(
std::make_pair(debug->preview_speed_reference(), acceleration_cmd));
} else {
calibration_value = control_interpolation_->Interpolate(
std::make_pair(chassis_->speed_mps(), acceleration_cmd));
}
if (calibration_value >= 0) {
throttle_cmd = calibration_value > throttle_deadzone ? calibration_value
: throttle_deadzone;
brake_cmd = 0.0;
} else {
throttle_cmd = 0.0;
brake_cmd = -calibration_value > brake_deadzone ? -calibration_value
: brake_deadzone;
}
debug->set_station_error_limited(station_error_limited);
debug->set_speed_controller_input_limited(speed_controller_input_limited);
debug->set_acceleration_cmd(acceleration_cmd);
debug->set_throttle_cmd(throttle_cmd);
debug->set_brake_cmd(brake_cmd);
debug->set_acceleration_lookup(acceleration_cmd);
debug->set_speed_lookup(chassis_->speed_mps());
debug->set_calibration_value(calibration_value);
debug->set_acceleration_cmd_closeloop(acceleration_cmd_closeloop);
if (FLAGS_enable_csv_debug && speed_log_file_ != nullptr) {
fprintf(speed_log_file_,
"%.6f, %.6f, %.6f, %.6f, %.6f, %.6f, %.6f, %.6f, %.6f, %.6f,"
"%.6f, %.6f, %.6f, %.6f, %.6f, %.6f, %.6f, %d,\r\n",
debug->station_reference(), debug->station_error(),
station_error_limited, debug->preview_station_error(),
debug->speed_reference(), debug->speed_error(),
speed_controller_input_limited, debug->preview_speed_reference(),
debug->preview_speed_error(),
debug->preview_acceleration_reference(), acceleration_cmd_closeloop,
acceleration_cmd, debug->acceleration_lookup(),
debug->speed_lookup(), calibration_value, throttle_cmd, brake_cmd,
debug->is_full_stop());
}
cmd->set_throttle(throttle_cmd);
cmd->set_brake(brake_cmd);
if (std::fabs(VehicleStateProvider::instance()->linear_velocity()) <=
vehicle_param_.max_abs_speed_when_stopped() ||
chassis->gear_location() == trajectory_message_->gear() ||
chassis->gear_location() == canbus::Chassis::GEAR_NEUTRAL) {
cmd->set_gear_location(trajectory_message_->gear());
} else {
cmd->set_gear_location(chassis->gear_location());
}
return Status::OK();
}
Status LonController::Reset() {
speed_pid_controller_.Reset();
station_pid_controller_.Reset();
return Status::OK();
}
std::string LonController::Name() const { return name_; }
void LonController::ComputeLongitudinalErrors(
const TrajectoryAnalyzer *trajectory_analyzer, const double preview_time,
SimpleLongitudinalDebug *debug) {
// the decomposed vehicle motion onto Frenet frame
// s: longitudinal accumulated distance along reference trajectory
// s_dot: longitudinal velocity along reference trajectory
// d: lateral distance w.r.t. reference trajectory
// d_dot: lateral distance change rate, i.e. dd/dt
double s_matched = 0.0;
double s_dot_matched = 0.0;
double d_matched = 0.0;
double d_dot_matched = 0.0;
auto matched_point = trajectory_analyzer->QueryMatchedPathPoint(
VehicleStateProvider::instance()->x(),
VehicleStateProvider::instance()->y());
trajectory_analyzer->ToTrajectoryFrame(
VehicleStateProvider::instance()->x(),
VehicleStateProvider::instance()->y(),
VehicleStateProvider::instance()->heading(),
VehicleStateProvider::instance()->linear_velocity(), matched_point,
&s_matched, &s_dot_matched, &d_matched, &d_dot_matched);
double current_control_time = Clock::NowInSeconds();
double preview_control_time = current_control_time + preview_time;
TrajectoryPoint reference_point =
trajectory_analyzer->QueryNearestPointByAbsoluteTime(
current_control_time);
TrajectoryPoint preview_point =
trajectory_analyzer->QueryNearestPointByAbsoluteTime(
preview_control_time);
ADEBUG << "matched point:" << matched_point.DebugString();
ADEBUG << "reference point:" << reference_point.DebugString();
ADEBUG << "preview point:" << preview_point.DebugString();
debug->set_station_error(reference_point.path_point().s() - s_matched);
debug->set_speed_error(reference_point.v() - s_dot_matched);
debug->set_station_reference(reference_point.path_point().s());
debug->set_speed_reference(reference_point.v());
debug->set_preview_station_error(preview_point.path_point().s() - s_matched);
debug->set_preview_speed_error(preview_point.v() - s_dot_matched);
debug->set_preview_speed_reference(preview_point.v());
debug->set_preview_acceleration_reference(preview_point.a());
debug->set_current_station(s_matched);
}
void LonController::SetDigitalFilter(double ts, double cutoff_freq,
common::DigitalFilter *digital_filter) {
std::vector<double> denominators;
std::vector<double> numerators;
common::LpfCoefficients(ts, cutoff_freq, &denominators, &numerators);
digital_filter->set_coefficients(denominators, numerators);
}
void LonController::GetPathRemain(SimpleLongitudinalDebug *debug) {
int stop_index = 0;
while (stop_index < trajectory_message_->trajectory_point_size()) {
if (fabs(trajectory_message_->trajectory_point(stop_index).v()) < 1e-3 &&
trajectory_message_->trajectory_point(stop_index).a() > -0.01 &&
trajectory_message_->trajectory_point(stop_index).a() < 0.0) {
break;
} else {
++stop_index;
}
}
if (stop_index == trajectory_message_->trajectory_point_size()) {
--stop_index;
if (fabs(trajectory_message_->trajectory_point(stop_index).v()) < 0.1) {
AINFO << "the last point is selected as parking point";
} else {
AINFO << "the last point found in path and speed > speed_deadzone";
debug->set_path_remain(10000);
}
}
debug->set_path_remain(
trajectory_message_->trajectory_point(stop_index).path_point().s() -
debug->current_station());
}
} // namespace control
} // namespace apollo
|
Update lon_controller.cc (#4782)
|
Update lon_controller.cc (#4782)
* Update lon_controller.cc
fix issue #4738
* Update lon_controller.cc
|
C++
|
apache-2.0
|
msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo
|
ef3d3c24eb54fd7954efff821562c99a92f7926b
|
physics/transforms_body.hpp
|
physics/transforms_body.hpp
|
#pragma once
#include "physics/transforms.hpp"
#include "geometry/affine_map.hpp"
#include "geometry/grassmann.hpp"
#include "geometry/identity.hpp"
#include "geometry/named_quantities.hpp"
#include "geometry/permutation.hpp"
#include "glog/logging.h"
#include "physics/massive_body.hpp"
#include "quantities/named_quantities.hpp"
#include "quantities/si.hpp"
using principia::geometry::AffineMap;
using principia::geometry::Bivector;
using principia::geometry::Displacement;
using principia::geometry::Identity;
using principia::geometry::Permutation;
using principia::geometry::Position;
using principia::geometry::Wedge;
using principia::quantities::AngularFrequency;
using principia::si::Radian;
namespace principia {
namespace physics {
namespace {
// TODO(egg): Move this somewhere more appropriate, wrap it, etc.
struct Matrix {
geometry::R3Element<double> row_x;
geometry::R3Element<double> row_y;
geometry::R3Element<double> row_z;
template <typename Scalar>
geometry::R3Element<Scalar> operator()(
geometry::R3Element<Scalar> const& right) const {
return {geometry::Dot(row_x, right),
geometry::Dot(row_y, right),
geometry::Dot(row_z, right)};
}
};
Matrix FromColumns(geometry::R3Element<double> const& column_x,
geometry::R3Element<double> const& column_y,
geometry::R3Element<double> const& column_z) {
return {{column_x.x, column_y.x, column_z.x},
{column_x.y, column_y.y, column_z.y},
{column_x.z, column_y.z, column_z.z}};
}
Matrix Transpose(Matrix const& m) {
return FromColumns(m.row_x, m.row_y, m.row_z);
}
// Fills the rotation |*matrix| that maps the standard basis to the basis of the
// barycentric frame. Fills |*angular_frequency| with the corresponding angular
// velocity. These pointers must be nonnul, and there is no transfer of
// ownership. |barycentre_degrees_of_freedom| must be a convex combination of
// the two other degrees of freedom.
// TODO(phl): All of this should be strongly typed. It's awfully confusing as
// it stands. In particular, the sign of the bivector may or may not be
// correct.
template<typename Frame>
void FromStandardBasisToBasisOfBarycentricFrame(
DegreesOfFreedom<Frame> const& barycentre_degrees_of_freedom,
DegreesOfFreedom<Frame> const& primary_degrees_of_freedom,
DegreesOfFreedom<Frame> const& secondary_degrees_of_freedom,
Matrix* matrix,
Bivector<AngularFrequency, Frame>* angular_frequency) {
CHECK_NOTNULL(matrix);
CHECK_NOTNULL(angular_frequency);
Displacement<Frame> const reference_direction =
primary_degrees_of_freedom.position -
barycentre_degrees_of_freedom.position;
Vector<double, Frame> const normalized_reference_direction =
Normalize(reference_direction);
Velocity<Frame> const reference_coplanar =
primary_degrees_of_freedom.velocity -
barycentre_degrees_of_freedom.velocity;
// Modified Gram-Schmidt.
Velocity<Frame> const reference_normal =
reference_coplanar -
InnerProduct(reference_coplanar, normalized_reference_direction) *
normalized_reference_direction;
Vector<double, Frame> const normalized_reference_normal =
Normalize(reference_normal);
// TODO(egg): should we normalize this?
Bivector<double, Frame> const normalized_reference_binormal =
Wedge(normalized_reference_direction, normalized_reference_normal);
*matrix = FromColumns(normalized_reference_direction.coordinates(),
normalized_reference_normal.coordinates(),
normalized_reference_binormal.coordinates());
*angular_frequency =
(1 * Radian * reference_normal.Norm() / reference_direction.Norm()) *
normalized_reference_binormal;
}
} // namespace
template<typename FromFrame, typename ThroughFrame, typename ToFrame>
std::unique_ptr<Transforms<FromFrame, ThroughFrame, ToFrame>>
Transforms<FromFrame, ThroughFrame, ToFrame>::BodyCentredNonRotating(
Trajectory<FromFrame> const& from_centre_trajectory,
Trajectory<ToFrame> const& to_centre_trajectory) {
std::unique_ptr<Transforms> transforms(new Transforms);
// From the perspective of the lambda the following variable is really |this|,
// hence the name.
Transforms* that = transforms.get();
transforms->first_ =
[&from_centre_trajectory, that](
Instant const& t,
DegreesOfFreedom<FromFrame> const& from_degrees_of_freedom,
Trajectory<FromFrame> const* trajectory) ->
DegreesOfFreedom<ThroughFrame> {
// First check if the result is cached.
auto cache_it = that->first_cache_.find(std::make_pair(trajectory, t));
if (cache_it != that->first_cache_.end()) {
return cache_it->second;
}
// on_or_after() is Ln(N), but it doesn't matter unless the map gets very
// big, in which case we'll have cache misses anyway.
Trajectory<FromFrame>::NativeIterator const centre_it =
from_centre_trajectory.on_or_after(t);
CHECK_EQ(centre_it.time(), t)
<< "Time " << t << " not in centre trajectory";
DegreesOfFreedom<FromFrame> const& centre_degrees_of_freedom =
centre_it.degrees_of_freedom();
AffineMap<FromFrame, ThroughFrame, Length, Identity> position_map(
centre_degrees_of_freedom.position,
ThroughFrame::origin,
Identity<FromFrame, ThroughFrame>());
Identity<FromFrame, ThroughFrame> velocity_map;
DegreesOfFreedom<ThroughFrame> through_degrees_of_freedom =
{position_map(from_degrees_of_freedom.position),
velocity_map(from_degrees_of_freedom.velocity -
centre_degrees_of_freedom.velocity)};
// Cache the result before returning it.
that->first_cache_.emplace(std::make_pair(trajectory, t),
through_degrees_of_freedom);
return std::move(through_degrees_of_freedom);
};
transforms->second_ =
[&to_centre_trajectory](
Instant const& t,
DegreesOfFreedom<ThroughFrame> const& through_degrees_of_freedom,
Trajectory<ThroughFrame> const* trajectory) ->
DegreesOfFreedom<ToFrame> {
DegreesOfFreedom<ToFrame> const& last_centre_degrees_of_freedom =
to_centre_trajectory.last().degrees_of_freedom();
AffineMap<ThroughFrame, ToFrame, Length, Identity> position_map(
ThroughFrame::origin,
last_centre_degrees_of_freedom.position,
Identity<ThroughFrame, ToFrame>());
Identity<ThroughFrame, ToFrame> velocity_map;
return {position_map(through_degrees_of_freedom.position),
velocity_map(through_degrees_of_freedom.velocity)};
};
return transforms;
}
template<typename FromFrame, typename ThroughFrame, typename ToFrame>
std::unique_ptr<Transforms<FromFrame, ThroughFrame, ToFrame>>
Transforms<FromFrame, ThroughFrame, ToFrame>::BarycentricRotating(
Trajectory<FromFrame> const& from_primary_trajectory,
Trajectory<ToFrame> const& to_primary_trajectory,
Trajectory<FromFrame> const& from_secondary_trajectory,
Trajectory<ToFrame> const& to_secondary_trajectory) {
std::unique_ptr<Transforms> transforms(new Transforms);
// From the perspective of the lambda the following variable is really |this|,
// hence the name.
Transforms* that = transforms.get();
transforms->first_ =
[&from_primary_trajectory, &from_secondary_trajectory, that](
Instant const& t,
DegreesOfFreedom<FromFrame> const& from_degrees_of_freedom,
Trajectory<FromFrame> const* trajectory) ->
DegreesOfFreedom<ThroughFrame> {
// First check if the result is cached.
auto cache_it = that->first_cache_.find(std::make_pair(trajectory, t));
if (cache_it != that->first_cache_.end()) {
return cache_it->second;
}
// on_or_after() is Ln(N).
Trajectory<FromFrame>::NativeIterator const primary_it =
from_primary_trajectory.on_or_after(t);
CHECK_EQ(primary_it.time(), t)
<< "Time " << t << " not in primary trajectory";
Trajectory<FromFrame>::NativeIterator secondary_it =
from_secondary_trajectory.on_or_after(t);
CHECK_EQ(secondary_it.time(), t)
<< "Time " << t << " not in secondary trajectory";
DegreesOfFreedom<FromFrame> const& primary_degrees_of_freedom =
primary_it.degrees_of_freedom();
DegreesOfFreedom<FromFrame> const& secondary_degrees_of_freedom =
secondary_it.degrees_of_freedom();
DegreesOfFreedom<FromFrame> const barycentre_degrees_of_freedom =
Barycentre<FromFrame, GravitationalParameter>(
{primary_degrees_of_freedom,
secondary_degrees_of_freedom},
{from_primary_trajectory.body<MassiveBody>().
gravitational_parameter(),
from_secondary_trajectory.body<MassiveBody>().
gravitational_parameter()});
Matrix from_basis_of_barycentric_frame_to_standard_basis;
Bivector<AngularFrequency, FromFrame> angular_frequency;
FromStandardBasisToBasisOfBarycentricFrame(
barycentre_degrees_of_freedom,
primary_degrees_of_freedom,
secondary_degrees_of_freedom,
&from_basis_of_barycentric_frame_to_standard_basis,
&angular_frequency);
from_basis_of_barycentric_frame_to_standard_basis =
Transpose(from_basis_of_barycentric_frame_to_standard_basis);
// TODO(phl): There should be an affine map here too, once we have properly
// 'framed' the matrix.
DegreesOfFreedom<ThroughFrame> through_degrees_of_freedom =
{Displacement<ThroughFrame>(
from_basis_of_barycentric_frame_to_standard_basis(
(from_degrees_of_freedom.position -
barycentre_degrees_of_freedom.position).
coordinates())) + ThroughFrame::origin,
Velocity<ThroughFrame>(
from_basis_of_barycentric_frame_to_standard_basis(
(from_degrees_of_freedom.velocity -
barycentre_degrees_of_freedom.velocity -
angular_frequency *
(from_degrees_of_freedom.position -
barycentre_degrees_of_freedom.position) /
(1 * Radian)).
coordinates()))};
// Cache the result before returning it.
that->first_cache_.emplace(std::make_pair(trajectory, t),
through_degrees_of_freedom);
return std::move(through_degrees_of_freedom);
};
transforms->second_ =
[&to_primary_trajectory, &to_secondary_trajectory](
Instant const& t,
DegreesOfFreedom<ThroughFrame> const& through_degrees_of_freedom,
Trajectory<ThroughFrame> const* trajectory) ->
DegreesOfFreedom<ToFrame> {
DegreesOfFreedom<ToFrame> const& last_primary_degrees_of_freedom =
to_primary_trajectory.last().degrees_of_freedom();
DegreesOfFreedom<ToFrame> const& last_secondary_degrees_of_freedom =
to_secondary_trajectory.last().degrees_of_freedom();
DegreesOfFreedom<ToFrame> const last_barycentre_degrees_of_freedom =
Barycentre<ToFrame, GravitationalParameter>(
{last_primary_degrees_of_freedom,
last_secondary_degrees_of_freedom},
{to_primary_trajectory.body<MassiveBody>().
gravitational_parameter(),
to_secondary_trajectory.body<MassiveBody>().
gravitational_parameter()});
Matrix from_standard_basis_to_basis_of_last_barycentric_frame;
Bivector<AngularFrequency, ToFrame> angular_frequency;
FromStandardBasisToBasisOfBarycentricFrame(
last_barycentre_degrees_of_freedom,
last_primary_degrees_of_freedom,
last_secondary_degrees_of_freedom,
&from_standard_basis_to_basis_of_last_barycentric_frame,
&angular_frequency);
// TODO(phl): There should be an affine map here too, once we have properly
// 'framed' the matrix.
return {Displacement<ToFrame>(
from_standard_basis_to_basis_of_last_barycentric_frame(
(through_degrees_of_freedom.position -
ThroughFrame::origin).coordinates())) +
last_barycentre_degrees_of_freedom.position,
Velocity<ToFrame>(
from_standard_basis_to_basis_of_last_barycentric_frame(
through_degrees_of_freedom.velocity.coordinates()))};
};
return transforms;
}
template<typename FromFrame, typename ThroughFrame, typename ToFrame>
typename Trajectory<FromFrame>::template TransformingIterator<ThroughFrame>
Transforms<FromFrame, ThroughFrame, ToFrame>::first(
Trajectory<FromFrame> const* from_trajectory) {
return CHECK_NOTNULL(from_trajectory)->first_with_transform(first_);
}
template<typename FromFrame, typename ThroughFrame, typename ToFrame>
typename Trajectory<ThroughFrame>::template TransformingIterator<ToFrame>
Transforms<FromFrame, ThroughFrame, ToFrame>::second(
Trajectory<ThroughFrame> const* through_trajectory) {
return CHECK_NOTNULL(through_trajectory)->
first_with_transform(second_);
}
} // namespace physics
} // namespace principia
|
#pragma once
#include "physics/transforms.hpp"
#include "geometry/affine_map.hpp"
#include "geometry/grassmann.hpp"
#include "geometry/identity.hpp"
#include "geometry/named_quantities.hpp"
#include "geometry/permutation.hpp"
#include "glog/logging.h"
#include "physics/massive_body.hpp"
#include "quantities/named_quantities.hpp"
#include "quantities/si.hpp"
using principia::geometry::AffineMap;
using principia::geometry::Bivector;
using principia::geometry::Displacement;
using principia::geometry::Identity;
using principia::geometry::Permutation;
using principia::geometry::Position;
using principia::geometry::Wedge;
using principia::quantities::AngularFrequency;
using principia::si::Radian;
namespace principia {
namespace physics {
namespace {
// TODO(egg): Move this somewhere more appropriate, wrap it, etc.
struct Matrix {
geometry::R3Element<double> row_x;
geometry::R3Element<double> row_y;
geometry::R3Element<double> row_z;
template <typename Scalar>
geometry::R3Element<Scalar> operator()(
geometry::R3Element<Scalar> const& right) const {
return {geometry::Dot(row_x, right),
geometry::Dot(row_y, right),
geometry::Dot(row_z, right)};
}
};
Matrix FromColumns(geometry::R3Element<double> const& column_x,
geometry::R3Element<double> const& column_y,
geometry::R3Element<double> const& column_z) {
return {{column_x.x, column_y.x, column_z.x},
{column_x.y, column_y.y, column_z.y},
{column_x.z, column_y.z, column_z.z}};
}
Matrix Transpose(Matrix const& m) {
return FromColumns(m.row_x, m.row_y, m.row_z);
}
// Fills |*matrix| with the rotation matrix that maps the standard basis to the
// basis of the barycentric frame. Fills |*angular_frequency| with the
// corresponding angular velocity. These pointers must be nonnul, and there is
// no transfer of ownership. |barycentre_degrees_of_freedom| must be a convex
// combination of the two other degrees of freedom.
// TODO(phl): All of this should be strongly typed. It's awfully confusing as
// it stands. In particular, the sign of the bivector may or may not be
// correct.
template<typename Frame>
void FromStandardBasisToBasisOfBarycentricFrame(
DegreesOfFreedom<Frame> const& barycentre_degrees_of_freedom,
DegreesOfFreedom<Frame> const& primary_degrees_of_freedom,
DegreesOfFreedom<Frame> const& secondary_degrees_of_freedom,
Matrix* matrix,
Bivector<AngularFrequency, Frame>* angular_frequency) {
CHECK_NOTNULL(matrix);
CHECK_NOTNULL(angular_frequency);
Displacement<Frame> const reference_direction =
primary_degrees_of_freedom.position -
barycentre_degrees_of_freedom.position;
Vector<double, Frame> const normalized_reference_direction =
Normalize(reference_direction);
Velocity<Frame> const reference_coplanar =
primary_degrees_of_freedom.velocity -
barycentre_degrees_of_freedom.velocity;
// Modified Gram-Schmidt.
Velocity<Frame> const reference_normal =
reference_coplanar -
InnerProduct(reference_coplanar, normalized_reference_direction) *
normalized_reference_direction;
Vector<double, Frame> const normalized_reference_normal =
Normalize(reference_normal);
// TODO(egg): should we normalize this?
Bivector<double, Frame> const normalized_reference_binormal =
Wedge(normalized_reference_direction, normalized_reference_normal);
*matrix = FromColumns(normalized_reference_direction.coordinates(),
normalized_reference_normal.coordinates(),
normalized_reference_binormal.coordinates());
*angular_frequency =
(1 * Radian * reference_normal.Norm() / reference_direction.Norm()) *
normalized_reference_binormal;
}
} // namespace
template<typename FromFrame, typename ThroughFrame, typename ToFrame>
std::unique_ptr<Transforms<FromFrame, ThroughFrame, ToFrame>>
Transforms<FromFrame, ThroughFrame, ToFrame>::BodyCentredNonRotating(
Trajectory<FromFrame> const& from_centre_trajectory,
Trajectory<ToFrame> const& to_centre_trajectory) {
std::unique_ptr<Transforms> transforms(new Transforms);
// From the perspective of the lambda the following variable is really |this|,
// hence the name.
Transforms* that = transforms.get();
transforms->first_ =
[&from_centre_trajectory, that](
Instant const& t,
DegreesOfFreedom<FromFrame> const& from_degrees_of_freedom,
Trajectory<FromFrame> const* trajectory) ->
DegreesOfFreedom<ThroughFrame> {
// First check if the result is cached.
auto cache_it = that->first_cache_.find(std::make_pair(trajectory, t));
if (cache_it != that->first_cache_.end()) {
return cache_it->second;
}
// on_or_after() is Ln(N), but it doesn't matter unless the map gets very
// big, in which case we'll have cache misses anyway.
Trajectory<FromFrame>::NativeIterator const centre_it =
from_centre_trajectory.on_or_after(t);
CHECK_EQ(centre_it.time(), t)
<< "Time " << t << " not in centre trajectory";
DegreesOfFreedom<FromFrame> const& centre_degrees_of_freedom =
centre_it.degrees_of_freedom();
AffineMap<FromFrame, ThroughFrame, Length, Identity> position_map(
centre_degrees_of_freedom.position,
ThroughFrame::origin,
Identity<FromFrame, ThroughFrame>());
Identity<FromFrame, ThroughFrame> velocity_map;
DegreesOfFreedom<ThroughFrame> through_degrees_of_freedom =
{position_map(from_degrees_of_freedom.position),
velocity_map(from_degrees_of_freedom.velocity -
centre_degrees_of_freedom.velocity)};
// Cache the result before returning it.
that->first_cache_.emplace(std::make_pair(trajectory, t),
through_degrees_of_freedom);
return std::move(through_degrees_of_freedom);
};
transforms->second_ =
[&to_centre_trajectory](
Instant const& t,
DegreesOfFreedom<ThroughFrame> const& through_degrees_of_freedom,
Trajectory<ThroughFrame> const* trajectory) ->
DegreesOfFreedom<ToFrame> {
DegreesOfFreedom<ToFrame> const& last_centre_degrees_of_freedom =
to_centre_trajectory.last().degrees_of_freedom();
AffineMap<ThroughFrame, ToFrame, Length, Identity> position_map(
ThroughFrame::origin,
last_centre_degrees_of_freedom.position,
Identity<ThroughFrame, ToFrame>());
Identity<ThroughFrame, ToFrame> velocity_map;
return {position_map(through_degrees_of_freedom.position),
velocity_map(through_degrees_of_freedom.velocity)};
};
return transforms;
}
template<typename FromFrame, typename ThroughFrame, typename ToFrame>
std::unique_ptr<Transforms<FromFrame, ThroughFrame, ToFrame>>
Transforms<FromFrame, ThroughFrame, ToFrame>::BarycentricRotating(
Trajectory<FromFrame> const& from_primary_trajectory,
Trajectory<ToFrame> const& to_primary_trajectory,
Trajectory<FromFrame> const& from_secondary_trajectory,
Trajectory<ToFrame> const& to_secondary_trajectory) {
std::unique_ptr<Transforms> transforms(new Transforms);
// From the perspective of the lambda the following variable is really |this|,
// hence the name.
Transforms* that = transforms.get();
transforms->first_ =
[&from_primary_trajectory, &from_secondary_trajectory, that](
Instant const& t,
DegreesOfFreedom<FromFrame> const& from_degrees_of_freedom,
Trajectory<FromFrame> const* trajectory) ->
DegreesOfFreedom<ThroughFrame> {
// First check if the result is cached.
auto cache_it = that->first_cache_.find(std::make_pair(trajectory, t));
if (cache_it != that->first_cache_.end()) {
return cache_it->second;
}
// on_or_after() is Ln(N).
Trajectory<FromFrame>::NativeIterator const primary_it =
from_primary_trajectory.on_or_after(t);
CHECK_EQ(primary_it.time(), t)
<< "Time " << t << " not in primary trajectory";
Trajectory<FromFrame>::NativeIterator secondary_it =
from_secondary_trajectory.on_or_after(t);
CHECK_EQ(secondary_it.time(), t)
<< "Time " << t << " not in secondary trajectory";
DegreesOfFreedom<FromFrame> const& primary_degrees_of_freedom =
primary_it.degrees_of_freedom();
DegreesOfFreedom<FromFrame> const& secondary_degrees_of_freedom =
secondary_it.degrees_of_freedom();
DegreesOfFreedom<FromFrame> const barycentre_degrees_of_freedom =
Barycentre<FromFrame, GravitationalParameter>(
{primary_degrees_of_freedom,
secondary_degrees_of_freedom},
{from_primary_trajectory.body<MassiveBody>().
gravitational_parameter(),
from_secondary_trajectory.body<MassiveBody>().
gravitational_parameter()});
Matrix from_basis_of_barycentric_frame_to_standard_basis;
Bivector<AngularFrequency, FromFrame> angular_frequency;
FromStandardBasisToBasisOfBarycentricFrame(
barycentre_degrees_of_freedom,
primary_degrees_of_freedom,
secondary_degrees_of_freedom,
&from_basis_of_barycentric_frame_to_standard_basis,
&angular_frequency);
from_basis_of_barycentric_frame_to_standard_basis =
Transpose(from_basis_of_barycentric_frame_to_standard_basis);
// TODO(phl): There should be an affine map here too, once we have properly
// 'framed' the matrix.
DegreesOfFreedom<ThroughFrame> through_degrees_of_freedom =
{Displacement<ThroughFrame>(
from_basis_of_barycentric_frame_to_standard_basis(
(from_degrees_of_freedom.position -
barycentre_degrees_of_freedom.position).
coordinates())) + ThroughFrame::origin,
Velocity<ThroughFrame>(
from_basis_of_barycentric_frame_to_standard_basis(
(from_degrees_of_freedom.velocity -
barycentre_degrees_of_freedom.velocity -
angular_frequency *
(from_degrees_of_freedom.position -
barycentre_degrees_of_freedom.position) /
(1 * Radian)).
coordinates()))};
// Cache the result before returning it.
that->first_cache_.emplace(std::make_pair(trajectory, t),
through_degrees_of_freedom);
return std::move(through_degrees_of_freedom);
};
transforms->second_ =
[&to_primary_trajectory, &to_secondary_trajectory](
Instant const& t,
DegreesOfFreedom<ThroughFrame> const& through_degrees_of_freedom,
Trajectory<ThroughFrame> const* trajectory) ->
DegreesOfFreedom<ToFrame> {
DegreesOfFreedom<ToFrame> const& last_primary_degrees_of_freedom =
to_primary_trajectory.last().degrees_of_freedom();
DegreesOfFreedom<ToFrame> const& last_secondary_degrees_of_freedom =
to_secondary_trajectory.last().degrees_of_freedom();
DegreesOfFreedom<ToFrame> const last_barycentre_degrees_of_freedom =
Barycentre<ToFrame, GravitationalParameter>(
{last_primary_degrees_of_freedom,
last_secondary_degrees_of_freedom},
{to_primary_trajectory.body<MassiveBody>().
gravitational_parameter(),
to_secondary_trajectory.body<MassiveBody>().
gravitational_parameter()});
Matrix from_standard_basis_to_basis_of_last_barycentric_frame;
Bivector<AngularFrequency, ToFrame> angular_frequency;
FromStandardBasisToBasisOfBarycentricFrame(
last_barycentre_degrees_of_freedom,
last_primary_degrees_of_freedom,
last_secondary_degrees_of_freedom,
&from_standard_basis_to_basis_of_last_barycentric_frame,
&angular_frequency);
// TODO(phl): There should be an affine map here too, once we have properly
// 'framed' the matrix.
return {Displacement<ToFrame>(
from_standard_basis_to_basis_of_last_barycentric_frame(
(through_degrees_of_freedom.position -
ThroughFrame::origin).coordinates())) +
last_barycentre_degrees_of_freedom.position,
Velocity<ToFrame>(
from_standard_basis_to_basis_of_last_barycentric_frame(
through_degrees_of_freedom.velocity.coordinates()))};
};
return transforms;
}
template<typename FromFrame, typename ThroughFrame, typename ToFrame>
typename Trajectory<FromFrame>::template TransformingIterator<ThroughFrame>
Transforms<FromFrame, ThroughFrame, ToFrame>::first(
Trajectory<FromFrame> const* from_trajectory) {
return CHECK_NOTNULL(from_trajectory)->first_with_transform(first_);
}
template<typename FromFrame, typename ThroughFrame, typename ToFrame>
typename Trajectory<ThroughFrame>::template TransformingIterator<ToFrame>
Transforms<FromFrame, ThroughFrame, ToFrame>::second(
Trajectory<ThroughFrame> const* through_trajectory) {
return CHECK_NOTNULL(through_trajectory)->
first_with_transform(second_);
}
} // namespace physics
} // namespace principia
|
Fix grammar.
|
Fix grammar.
|
C++
|
mit
|
eggrobin/Principia,pleroy/Principia,pleroy/Principia,Norgg/Principia,eggrobin/Principia,Norgg/Principia,mockingbirdnest/Principia,mockingbirdnest/Principia,pleroy/Principia,Norgg/Principia,Norgg/Principia,mockingbirdnest/Principia,eggrobin/Principia,pleroy/Principia,mockingbirdnest/Principia
|
bfbf646e24390648f362002fb4f6e18e090be571
|
PjsuaCommunicator.cpp
|
PjsuaCommunicator.cpp
|
#include "PjsuaCommunicator.hpp"
#include <pjlib.h>
#include <pjsua-lib/pjsua.h>
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
using namespace std;
namespace sip {
using namespace log4cpp;
class _LogWriter : public pj::LogWriter {
public:
_LogWriter(Category &logger)
: logger(logger) { }
virtual void write(const pj::LogEntry &entry) {
auto message = entry.msg.substr(0, entry.msg.size() - 1); // remove newline
logger << prioritiesMap.at(entry.level) << message;
}
private:
log4cpp::Category &logger;
std::map<int, Priority::Value> prioritiesMap = {
{1, Priority::ERROR},
{2, Priority::WARN},
{3, Priority::NOTICE},
{4, Priority::INFO},
{5, Priority::DEBUG},
{6, Priority::DEBUG}
};
};
class _MumlibAudioMedia : public pj::AudioMedia {
public:
_MumlibAudioMedia(sip::PjsuaCommunicator &comm)
: communicator(comm) {
createMediaPort();
registerMediaPort(&mediaPort);
}
~_MumlibAudioMedia() {
unregisterMediaPort();
}
private:
pjmedia_port mediaPort;
sip::PjsuaCommunicator &communicator;
static pj_status_t callback_getFrame(pjmedia_port *port, pjmedia_frame *frame) {
auto *communicator = static_cast<sip::PjsuaCommunicator *>(port->port_data.pdata);
return communicator->mediaPortGetFrame(port, frame);
}
static pj_status_t callback_putFrame(pjmedia_port *port, pjmedia_frame *frame) {
auto *communicator = static_cast<sip::PjsuaCommunicator *>(port->port_data.pdata);
return communicator->mediaPortPutFrame(port, frame);
}
void createMediaPort() {
auto name = pj_str((char *) "MumsiMediaPort");
pj_status_t status = pjmedia_port_info_init(&(mediaPort.info),
&name,
PJMEDIA_SIG_CLASS_PORT_AUD('s', 'i'),
SAMPLING_RATE,
1,
16,
SAMPLING_RATE * 20 /
1000); // todo recalculate to match mumble specs
if (status != PJ_SUCCESS) {
throw sip::Exception("error while calling pjmedia_port_info_init()", status);
}
mediaPort.port_data.pdata = &communicator;
mediaPort.get_frame = &callback_getFrame;
mediaPort.put_frame = &callback_putFrame;
}
};
class _Call : public pj::Call {
public:
_Call(sip::PjsuaCommunicator &comm, pj::Account &acc, int call_id = PJSUA_INVALID_ID)
: pj::Call(acc, call_id),
communicator(comm),
account(acc) { }
virtual void onCallState(pj::OnCallStateParam &prm);
virtual void onCallMediaState(pj::OnCallMediaStateParam &prm);
virtual void onDtmfDigit(pj::OnDtmfDigitParam &prm);
private:
sip::PjsuaCommunicator &communicator;
pj::Account &account;
};
class _Account : public pj::Account {
public:
_Account(sip::PjsuaCommunicator &comm)
: communicator(comm) { }
virtual void onRegState(pj::OnRegStateParam &prm);
virtual void onIncomingCall(pj::OnIncomingCallParam &iprm);
private:
sip::PjsuaCommunicator &communicator;
bool available = true;
friend class _Call;
};
void _Call::onCallState(pj::OnCallStateParam &prm) {
auto ci = getInfo();
communicator.logger.info("Call %d state=%s.", ci.id, ci.stateText.c_str());
string address = ci.remoteUri;
boost::replace_all(address, "<", "");
boost::replace_all(address, ">", "");
if (ci.state == PJSIP_INV_STATE_CONFIRMED) {
auto msgText = "Incoming call from " + address + ".";
communicator.logger.notice(msgText);
communicator.onStateChange(msgText);
} else if (ci.state == PJSIP_INV_STATE_DISCONNECTED) {
auto &acc = dynamic_cast<_Account &>(account);
if (not acc.available) {
auto msgText = "Call from " + address + " finished.";
communicator.logger.notice(msgText);
communicator.onStateChange(msgText);
acc.available = true;
}
delete this;
}
}
void _Call::onCallMediaState(pj::OnCallMediaStateParam &prm) {
auto ci = getInfo();
if (ci.media.size() != 1) {
throw sip::Exception("ci.media.size is not 1");
}
if (ci.media[0].status == PJSUA_CALL_MEDIA_ACTIVE) {
auto *aud_med = static_cast<pj::AudioMedia *>(getMedia(0));
communicator.media->startTransmit(*aud_med);
aud_med->startTransmit(*communicator.media);
} else if (ci.media[0].status == PJSUA_CALL_MEDIA_NONE) {
dynamic_cast<_Account &>(account).available = true;
}
}
void _Call::onDtmfDigit(pj::OnDtmfDigitParam &prm) {
communicator.logger.notice("DTMF digit '%s' (call %d).", prm.digit.c_str(), getId());
}
void _Account::onRegState(pj::OnRegStateParam &prm) {
pj::AccountInfo ai = getInfo();
communicator.logger << log4cpp::Priority::INFO
<< (ai.regIsActive ? "Register:" : "Unregister:") << " code=" << prm.code;
}
void _Account::onIncomingCall(pj::OnIncomingCallParam &iprm) {
auto *call = new _Call(communicator, *this, iprm.callId);
string uri = call->getInfo().remoteUri;
communicator.logger.info("Incoming call from %s.", uri.c_str());
pj::CallOpParam param;
if (communicator.uriValidator.validateUri(uri)) {
if (available) {
param.statusCode = PJSIP_SC_OK;
available = false;
} else {
param.statusCode = PJSIP_SC_BUSY_EVERYWHERE;
}
call->answer(param);
} else {
communicator.logger.warn("Refusing call from %s.", uri.c_str());
param.statusCode = PJSIP_SC_DECLINE;
call->hangup(param);
}
}
}
sip::PjsuaCommunicator::PjsuaCommunicator(IncomingConnectionValidator &validator)
: logger(log4cpp::Category::getInstance("SipCommunicator")),
pjsuaLogger(log4cpp::Category::getInstance("Pjsua")),
uriValidator(validator) {
logWriter.reset(new sip::_LogWriter(pjsuaLogger));
endpoint.libCreate();
pj::EpConfig endpointConfig;
endpointConfig.uaConfig.userAgent = "Mumsi Mumble-SIP gateway";
endpointConfig.uaConfig.maxCalls = 1;
endpointConfig.logConfig.writer = logWriter.get();
endpointConfig.logConfig.level = 5;
endpointConfig.medConfig.noVad = true;
endpoint.libInit(endpointConfig);
pj_status_t status;
pj_caching_pool cachingPool;
pj_caching_pool_init(&cachingPool, &pj_pool_factory_default_policy, 0);
pool = pj_pool_create(&cachingPool.factory, "media", 32768, 8192, nullptr);
if (!pool) {
throw sip::Exception("error when creating memory pool", status);
}
// todo calculate sizes
status = pjmedia_circ_buf_create(pool, 960 * 10, &inputBuff);
if (status != PJ_SUCCESS) {
throw sip::Exception("error when creating circular buffer", status);
}
media.reset(new _MumlibAudioMedia(*this));
}
void sip::PjsuaCommunicator::connect(
std::string host,
std::string user,
std::string password,
unsigned int port) {
pj::TransportConfig transportConfig;
transportConfig.port = port;
endpoint.transportCreate(PJSIP_TRANSPORT_UDP, transportConfig); // todo try catch
endpoint.libStart();
pj_status_t status = pjsua_set_null_snd_dev();
if (status != PJ_SUCCESS) {
throw sip::Exception("error in pjsua_set_null_std_dev()", status);
}
registerAccount(host, user, password);
}
sip::PjsuaCommunicator::~PjsuaCommunicator() {
endpoint.libDestroy();
}
pj_status_t sip::PjsuaCommunicator::mediaPortGetFrame(pjmedia_port *port, pjmedia_frame *frame) {
std::unique_lock<std::mutex> lock(inBuffAccessMutex);
frame->type = PJMEDIA_FRAME_TYPE_AUDIO;
pj_int16_t *samples = static_cast<pj_int16_t *>(frame->buf);
pj_size_t count = frame->size / 2 / PJMEDIA_PIA_CCNT(&(port->info));
pj_size_t availableSamples = pjmedia_circ_buf_get_len(inputBuff);
const int samplesToRead = std::min(count, availableSamples);
pjsuaLogger.debug("Pulling %d samples from in-buff.", samplesToRead);
pjmedia_circ_buf_read(inputBuff, samples, samplesToRead);
if (availableSamples < count) {
pjsuaLogger.debug("Requested %d samples, available %d, filling remaining with zeros.", count,
availableSamples);
for (int i = samplesToRead; i < count; ++i) {
samples[i] = 0;
}
}
return PJ_SUCCESS;
}
pj_status_t sip::PjsuaCommunicator::mediaPortPutFrame(pjmedia_port *port, pjmedia_frame *frame) {
pj_int16_t *samples = static_cast<pj_int16_t *>(frame->buf);
pj_size_t count = frame->size / 2 / PJMEDIA_PIA_CCNT(&port->info);
frame->type = PJMEDIA_FRAME_TYPE_AUDIO;
if (count > 0) {
pjsuaLogger.debug("Calling onIncomingPcmSamples with %d samples.", count);
onIncomingPcmSamples(samples, count);
}
return PJ_SUCCESS;
}
void sip::PjsuaCommunicator::registerAccount(string host, string user, string password) {
string uri = "sip:" + user + "@" + host;
pj::AccountConfig accountConfig;
accountConfig.idUri = uri;
accountConfig.regConfig.registrarUri = "sip:" + host;
pj::AuthCredInfo cred("digest", "*", user, 0, password);
accountConfig.sipConfig.authCreds.push_back(cred);
logger.info("Registering account for URI: %s.", uri.c_str());
account.reset(new _Account(*this));
account->create(accountConfig);
}
void sip::PjsuaCommunicator::sendPcmSamples(int16_t *samples, unsigned int length) {
std::unique_lock<std::mutex> lock(inBuffAccessMutex);
pjsuaLogger.debug("Pushing %d samples to in-buff.", length);
pjmedia_circ_buf_write(inputBuff, samples, length);
}
|
#include "PjsuaCommunicator.hpp"
#include <pjlib.h>
#include <pjsua-lib/pjsua.h>
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
using namespace std;
namespace sip {
using namespace log4cpp;
class _LogWriter : public pj::LogWriter {
public:
_LogWriter(Category &logger)
: logger(logger) { }
virtual void write(const pj::LogEntry &entry) {
auto message = entry.msg.substr(0, entry.msg.size() - 1); // remove newline
logger << prioritiesMap.at(entry.level) << message;
}
private:
log4cpp::Category &logger;
std::map<int, Priority::Value> prioritiesMap = {
{1, Priority::ERROR},
{2, Priority::WARN},
{3, Priority::NOTICE},
{4, Priority::INFO},
{5, Priority::DEBUG},
{6, Priority::DEBUG}
};
};
class _MumlibAudioMedia : public pj::AudioMedia {
public:
_MumlibAudioMedia(sip::PjsuaCommunicator &comm)
: communicator(comm) {
createMediaPort();
registerMediaPort(&mediaPort);
}
~_MumlibAudioMedia() {
unregisterMediaPort();
}
private:
pjmedia_port mediaPort;
sip::PjsuaCommunicator &communicator;
static pj_status_t callback_getFrame(pjmedia_port *port, pjmedia_frame *frame) {
auto *communicator = static_cast<sip::PjsuaCommunicator *>(port->port_data.pdata);
return communicator->mediaPortGetFrame(port, frame);
}
static pj_status_t callback_putFrame(pjmedia_port *port, pjmedia_frame *frame) {
auto *communicator = static_cast<sip::PjsuaCommunicator *>(port->port_data.pdata);
return communicator->mediaPortPutFrame(port, frame);
}
void createMediaPort() {
auto name = pj_str((char *) "MumsiMediaPort");
pj_status_t status = pjmedia_port_info_init(&(mediaPort.info),
&name,
PJMEDIA_SIG_CLASS_PORT_AUD('s', 'i'),
SAMPLING_RATE,
1,
16,
SAMPLING_RATE * 20 /
1000); // todo recalculate to match mumble specs
if (status != PJ_SUCCESS) {
throw sip::Exception("error while calling pjmedia_port_info_init()", status);
}
mediaPort.port_data.pdata = &communicator;
mediaPort.get_frame = &callback_getFrame;
mediaPort.put_frame = &callback_putFrame;
}
};
class _Call : public pj::Call {
public:
_Call(sip::PjsuaCommunicator &comm, pj::Account &acc, int call_id = PJSUA_INVALID_ID)
: pj::Call(acc, call_id),
communicator(comm),
account(acc) { }
virtual void onCallState(pj::OnCallStateParam &prm);
virtual void onCallMediaState(pj::OnCallMediaStateParam &prm);
virtual void onDtmfDigit(pj::OnDtmfDigitParam &prm);
private:
sip::PjsuaCommunicator &communicator;
pj::Account &account;
};
class _Account : public pj::Account {
public:
_Account(sip::PjsuaCommunicator &comm)
: communicator(comm) { }
virtual void onRegState(pj::OnRegStateParam &prm);
virtual void onIncomingCall(pj::OnIncomingCallParam &iprm);
private:
sip::PjsuaCommunicator &communicator;
bool available = true;
friend class _Call;
};
void _Call::onCallState(pj::OnCallStateParam &prm) {
auto ci = getInfo();
communicator.logger.info("Call %d state=%s.", ci.id, ci.stateText.c_str());
string address = ci.remoteUri;
boost::replace_all(address, "<", "");
boost::replace_all(address, ">", "");
if (ci.state == PJSIP_INV_STATE_CONFIRMED) {
auto msgText = "Incoming call from " + address + ".";
communicator.logger.notice(msgText);
communicator.onStateChange(msgText);
} else if (ci.state == PJSIP_INV_STATE_DISCONNECTED) {
auto &acc = dynamic_cast<_Account &>(account);
if (not acc.available) {
auto msgText = "Call from " + address + " finished.";
communicator.logger.notice(msgText);
communicator.onStateChange(msgText);
acc.available = true;
}
delete this;
}
}
void _Call::onCallMediaState(pj::OnCallMediaStateParam &prm) {
auto ci = getInfo();
if (ci.media.size() != 1) {
throw sip::Exception("ci.media.size is not 1");
}
if (ci.media[0].status == PJSUA_CALL_MEDIA_ACTIVE) {
auto *aud_med = static_cast<pj::AudioMedia *>(getMedia(0));
communicator.media->startTransmit(*aud_med);
aud_med->startTransmit(*communicator.media);
} else if (ci.media[0].status == PJSUA_CALL_MEDIA_NONE) {
dynamic_cast<_Account &>(account).available = true;
}
}
void _Call::onDtmfDigit(pj::OnDtmfDigitParam &prm) {
communicator.logger.notice("DTMF digit '%s' (call %d).", prm.digit.c_str(), getId());
}
void _Account::onRegState(pj::OnRegStateParam &prm) {
pj::AccountInfo ai = getInfo();
communicator.logger << log4cpp::Priority::INFO
<< (ai.regIsActive ? "Register:" : "Unregister:") << " code=" << prm.code;
}
void _Account::onIncomingCall(pj::OnIncomingCallParam &iprm) {
auto *call = new _Call(communicator, *this, iprm.callId);
string uri = call->getInfo().remoteUri;
communicator.logger.info("Incoming call from %s.", uri.c_str());
pj::CallOpParam param;
if (communicator.uriValidator.validateUri(uri)) {
if (available) {
param.statusCode = PJSIP_SC_OK;
available = false;
} else {
param.statusCode = PJSIP_SC_BUSY_EVERYWHERE;
}
call->answer(param);
} else {
communicator.logger.warn("Refusing call from %s.", uri.c_str());
param.statusCode = PJSIP_SC_SERVICE_UNAVAILABLE;
call->hangup(param);
}
}
}
sip::PjsuaCommunicator::PjsuaCommunicator(IncomingConnectionValidator &validator)
: logger(log4cpp::Category::getInstance("SipCommunicator")),
pjsuaLogger(log4cpp::Category::getInstance("Pjsua")),
uriValidator(validator) {
logWriter.reset(new sip::_LogWriter(pjsuaLogger));
endpoint.libCreate();
pj::EpConfig endpointConfig;
endpointConfig.uaConfig.userAgent = "Mumsi Mumble-SIP gateway";
endpointConfig.uaConfig.maxCalls = 1;
endpointConfig.logConfig.writer = logWriter.get();
endpointConfig.logConfig.level = 5;
endpointConfig.medConfig.noVad = true;
endpoint.libInit(endpointConfig);
pj_status_t status;
pj_caching_pool cachingPool;
pj_caching_pool_init(&cachingPool, &pj_pool_factory_default_policy, 0);
pool = pj_pool_create(&cachingPool.factory, "media", 32768, 8192, nullptr);
if (!pool) {
throw sip::Exception("error when creating memory pool", status);
}
// todo calculate sizes
status = pjmedia_circ_buf_create(pool, 960 * 10, &inputBuff);
if (status != PJ_SUCCESS) {
throw sip::Exception("error when creating circular buffer", status);
}
media.reset(new _MumlibAudioMedia(*this));
}
void sip::PjsuaCommunicator::connect(
std::string host,
std::string user,
std::string password,
unsigned int port) {
pj::TransportConfig transportConfig;
transportConfig.port = port;
endpoint.transportCreate(PJSIP_TRANSPORT_UDP, transportConfig); // todo try catch
endpoint.libStart();
pj_status_t status = pjsua_set_null_snd_dev();
if (status != PJ_SUCCESS) {
throw sip::Exception("error in pjsua_set_null_std_dev()", status);
}
registerAccount(host, user, password);
}
sip::PjsuaCommunicator::~PjsuaCommunicator() {
endpoint.libDestroy();
}
pj_status_t sip::PjsuaCommunicator::mediaPortGetFrame(pjmedia_port *port, pjmedia_frame *frame) {
std::unique_lock<std::mutex> lock(inBuffAccessMutex);
frame->type = PJMEDIA_FRAME_TYPE_AUDIO;
pj_int16_t *samples = static_cast<pj_int16_t *>(frame->buf);
pj_size_t count = frame->size / 2 / PJMEDIA_PIA_CCNT(&(port->info));
pj_size_t availableSamples = pjmedia_circ_buf_get_len(inputBuff);
const int samplesToRead = std::min(count, availableSamples);
pjsuaLogger.debug("Pulling %d samples from in-buff.", samplesToRead);
pjmedia_circ_buf_read(inputBuff, samples, samplesToRead);
if (availableSamples < count) {
pjsuaLogger.debug("Requested %d samples, available %d, filling remaining with zeros.", count,
availableSamples);
for (int i = samplesToRead; i < count; ++i) {
samples[i] = 0;
}
}
return PJ_SUCCESS;
}
pj_status_t sip::PjsuaCommunicator::mediaPortPutFrame(pjmedia_port *port, pjmedia_frame *frame) {
pj_int16_t *samples = static_cast<pj_int16_t *>(frame->buf);
pj_size_t count = frame->size / 2 / PJMEDIA_PIA_CCNT(&port->info);
frame->type = PJMEDIA_FRAME_TYPE_AUDIO;
if (count > 0) {
pjsuaLogger.debug("Calling onIncomingPcmSamples with %d samples.", count);
onIncomingPcmSamples(samples, count);
}
return PJ_SUCCESS;
}
void sip::PjsuaCommunicator::registerAccount(string host, string user, string password) {
string uri = "sip:" + user + "@" + host;
pj::AccountConfig accountConfig;
accountConfig.idUri = uri;
accountConfig.regConfig.registrarUri = "sip:" + host;
pj::AuthCredInfo cred("digest", "*", user, 0, password);
accountConfig.sipConfig.authCreds.push_back(cred);
logger.info("Registering account for URI: %s.", uri.c_str());
account.reset(new _Account(*this));
account->create(accountConfig);
}
void sip::PjsuaCommunicator::sendPcmSamples(int16_t *samples, unsigned int length) {
std::unique_lock<std::mutex> lock(inBuffAccessMutex);
pjsuaLogger.debug("Pushing %d samples to in-buff.", length);
pjmedia_circ_buf_write(inputBuff, samples, length);
}
|
Change to answer SERVICE_UNAVAILABLE for invalid URIs.
|
Change to answer SERVICE_UNAVAILABLE for invalid URIs.
|
C++
|
apache-2.0
|
slomkowski/mumsi
|
765560781fe5a5d2ac46ef72149426a853c8e026
|
OgreMain/src/OgreWorkQueue.cpp
|
OgreMain/src/OgreWorkQueue.cpp
|
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreWorkQueue.h"
#include "OgreLogManager.h"
#include "OgreRoot.h"
#include "OgreRenderSystem.h"
namespace Ogre {
//---------------------------------------------------------------------
WorkQueue::Request::Request(uint16 channel, uint16 rtype, const Any& rData, uint8 retry, RequestID rid)
: mChannel(channel), mType(rtype), mData(rData), mRetryCount(retry), mID(rid)
{
}
//---------------------------------------------------------------------
WorkQueue::Request::~Request()
{
}
//---------------------------------------------------------------------
//---------------------------------------------------------------------
WorkQueue::Response::Response(const Request* rq, bool success, const Any& data, const String& msg)
: mRequest(rq), mSuccess(success), mMessages(msg), mData(data)
{
}
//---------------------------------------------------------------------
WorkQueue::Response::~Response()
{
OGRE_DELETE mRequest;
}
//---------------------------------------------------------------------
//---------------------------------------------------------------------
DefaultWorkQueueBase::DefaultWorkQueueBase(const String& name)
: mName(name)
, mWorkerThreadCount(1)
, mWorkerRenderSystemAccess(false)
, mIsRunning(false)
, mResposeTimeLimitMS(0)
, mWorkerFunc(this)
, mRequestCount(0)
, mPaused(false)
, mAcceptRequests(true)
{
}
//---------------------------------------------------------------------
const String& DefaultWorkQueueBase::getName() const
{
return mName;
}
//---------------------------------------------------------------------
size_t DefaultWorkQueueBase::getWorkerThreadCount() const
{
return mWorkerThreadCount;
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::setWorkerThreadCount(size_t c)
{
mWorkerThreadCount = c;
}
//---------------------------------------------------------------------
bool DefaultWorkQueueBase::getWorkersCanAccessRenderSystem() const
{
return mWorkerRenderSystemAccess;
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::setWorkersCanAccessRenderSystem(bool access)
{
mWorkerRenderSystemAccess = access;
}
//---------------------------------------------------------------------
DefaultWorkQueueBase::~DefaultWorkQueueBase()
{
//shutdown(); // can't call here; abstract function
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::addRequestHandler(uint16 channel, RequestHandler* rh)
{
OGRE_LOCK_RW_MUTEX_WRITE(mRequestHandlerMutex);
RequestHandlerListByChannel::iterator i = mRequestHandlers.find(channel);
if (i == mRequestHandlers.end())
i = mRequestHandlers.insert(RequestHandlerListByChannel::value_type(channel, RequestHandlerList())).first;
RequestHandlerList& handlers = i->second;
if (std::find(handlers.begin(), handlers.end(), rh) == handlers.end())
handlers.push_back(rh);
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::removeRequestHandler(uint16 channel, RequestHandler* rh)
{
OGRE_LOCK_RW_MUTEX_WRITE(mRequestHandlerMutex);
RequestHandlerListByChannel::iterator i = mRequestHandlers.find(channel);
if (i != mRequestHandlers.end())
{
RequestHandlerList& handlers = i->second;
RequestHandlerList::iterator j = std::find(
handlers.begin(), handlers.end(), rh);
if (j != handlers.end())
handlers.erase(j);
}
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::addResponseHandler(uint16 channel, ResponseHandler* rh)
{
ResponseHandlerListByChannel::iterator i = mResponseHandlers.find(channel);
if (i == mResponseHandlers.end())
i = mResponseHandlers.insert(ResponseHandlerListByChannel::value_type(channel, ResponseHandlerList())).first;
ResponseHandlerList& handlers = i->second;
if (std::find(handlers.begin(), handlers.end(), rh) == handlers.end())
handlers.push_back(rh);
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::removeResponseHandler(uint16 channel, ResponseHandler* rh)
{
ResponseHandlerListByChannel::iterator i = mResponseHandlers.find(channel);
if (i != mResponseHandlers.end())
{
ResponseHandlerList& handlers = i->second;
ResponseHandlerList::iterator j = std::find(
handlers.begin(), handlers.end(), rh);
if (j != handlers.end())
handlers.erase(j);
}
}
//---------------------------------------------------------------------
WorkQueue::RequestID DefaultWorkQueueBase::addRequest(uint16 channel, uint16 requestType,
const Any& rData, uint8 retryCount, bool forceSynchronous)
{
Request* req = 0;
RequestID rid = 0;
{
// lock to acquire rid and push request to the queue
OGRE_LOCK_MUTEX(mRequestMutex)
if (!mAcceptRequests || mShuttingDown)
return 0;
rid = ++mRequestCount;
req = OGRE_NEW Request(channel, requestType, rData, retryCount, rid);
LogManager::getSingleton().stream(LML_TRIVIAL) <<
"DefaultWorkQueueBase('" << mName << "') - QUEUED(thread:" <<
#if OGRE_THREAD_SUPPORT
OGRE_THREAD_CURRENT_ID
#else
"main"
#endif
<< "): ID=" << rid
<< " channel=" << channel << " requestType=" << requestType;
#if OGRE_THREAD_SUPPORT
if (!forceSynchronous)
{
mRequestQueue.push_back(req);
notifyWorkers();
return rid;
}
#endif
}
processRequestResponse(req, true);
return rid;
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::addRequestWithRID(WorkQueue::RequestID rid, uint16 channel,
uint16 requestType, const Any& rData, uint8 retryCount)
{
// lock to push request to the queue
OGRE_LOCK_MUTEX(mRequestMutex)
if (mShuttingDown)
return;
Request* req = OGRE_NEW Request(channel, requestType, rData, retryCount, rid);
LogManager::getSingleton().stream(LML_TRIVIAL) <<
"DefaultWorkQueueBase('" << mName << "') - REQUEUED(thread:" <<
#if OGRE_THREAD_SUPPORT
OGRE_THREAD_CURRENT_ID
#else
"main"
#endif
<< "): ID=" << rid
<< " channel=" << channel << " requestType=" << requestType;
#if OGRE_THREAD_SUPPORT
mRequestQueue.push_back(req);
notifyWorkers();
#else
processRequestResponse(req, true);
#endif
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::abortRequest(RequestID id)
{
OGRE_LOCK_MUTEX(mRequestMutex)
for (RequestQueue::iterator i = mRequestQueue.begin(); i != mRequestQueue.end(); ++i)
{
if ((*i)->getID() == id)
{
OGRE_DELETE *i;
mRequestQueue.erase(i);
break;
}
}
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::abortRequestsByChannel(uint16 channel)
{
OGRE_LOCK_MUTEX(mRequestMutex)
for (RequestQueue::iterator i = mRequestQueue.begin(); i != mRequestQueue.end();)
{
if ((*i)->getChannel() == channel)
{
OGRE_DELETE *i;
i = mRequestQueue.erase(i);
}
else
++i;
}
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::abortAllRequests()
{
OGRE_LOCK_MUTEX(mRequestMutex)
for (RequestQueue::iterator i = mRequestQueue.begin(); i != mRequestQueue.end();)
{
OGRE_DELETE *i;
}
mRequestQueue.clear();
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::setPaused(bool pause)
{
OGRE_LOCK_MUTEX(mRequestMutex)
mPaused = pause;
}
//---------------------------------------------------------------------
bool DefaultWorkQueueBase::isPaused() const
{
return mPaused;
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::setRequestsAccepted(bool accept)
{
OGRE_LOCK_MUTEX(mRequestMutex)
mAcceptRequests = accept;
}
//---------------------------------------------------------------------
bool DefaultWorkQueueBase::getRequestsAccepted() const
{
return mAcceptRequests;
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::_processNextRequest()
{
Request* request = 0;
{
// scoped to only lock while retrieving the next request
OGRE_LOCK_MUTEX(mRequestMutex)
if (!mRequestQueue.empty())
{
request = mRequestQueue.front();
mRequestQueue.pop_front();
}
}
if (request)
{
processRequestResponse(request, false);
}
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::processRequestResponse(Request* r, bool synchronous)
{
Response* response = processRequest(r);
if (response)
{
if (!response->succeeded())
{
// Failed, should we retry?
const Request* req = response->getRequest();
if (req->getRetryCount())
{
addRequestWithRID(req->getID(), req->getChannel(), req->getType(), req->getData(),
req->getRetryCount() - 1);
// discard response (this also deletes request)
OGRE_DELETE response;
return;
}
}
if (synchronous)
{
processResponse(response);
}
else
{
// Queue response
OGRE_LOCK_MUTEX(mResponseMutex)
mResponseQueue.push_back(response);
// no need to wake thread, this is processed by the main thread
}
}
else
{
// no response, delete request
LogManager::getSingleton().stream() <<
"DefaultWorkQueueBase('" << mName << "') warning: no handler processed request "
<< r->getID() << ", channel " << r->getChannel()
<< ", type " << r->getType();
OGRE_DELETE r;
}
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::processResponses()
{
unsigned long msStart = Root::getSingleton().getTimer()->getMilliseconds();
unsigned long msCurrent = msStart;
// keep going until we run out of responses or out of time
while(true)
{
Response* response = 0;
{
OGRE_LOCK_MUTEX(mResponseMutex)
if (mResponseQueue.empty())
break; // exit loop
else
{
response = mResponseQueue.front();
mResponseQueue.pop_front();
}
}
if (response)
{
processResponse(response);
OGRE_DELETE response;
}
// time limit
if (mResposeTimeLimitMS)
{
msCurrent = Root::getSingleton().getTimer()->getMilliseconds();
if (msCurrent - msStart > mResposeTimeLimitMS)
break;
}
}
}
//---------------------------------------------------------------------
WorkQueue::Response* DefaultWorkQueueBase::processRequest(Request* r)
{
OGRE_LOCK_RW_MUTEX_READ(mRequestHandlerMutex);
Response* response = 0;
StringUtil::StrStreamType dbgMsg;
dbgMsg <<
#if OGRE_THREAD_SUPPORT
OGRE_THREAD_CURRENT_ID
#else
"main"
#endif
<< "): ID=" << r->getID() << " channel=" << r->getChannel()
<< " requestType=" << r->getType();
LogManager::getSingleton().stream(LML_TRIVIAL) <<
"DefaultWorkQueueBase('" << mName << "') - PROCESS_REQUEST_START(" << dbgMsg.str();
RequestHandlerListByChannel::iterator i = mRequestHandlers.find(r->getChannel());
if (i != mRequestHandlers.end())
{
RequestHandlerList& handlers = i->second;
for (RequestHandlerList::reverse_iterator j = handlers.rbegin(); j != handlers.rend(); ++j)
{
if ((*j)->canHandleRequest(r, this))
{
response = (*j)->handleRequest(r, this);
}
}
}
LogManager::getSingleton().stream(LML_TRIVIAL) <<
"DefaultWorkQueueBase('" << mName << "') - PROCESS_REQUEST_END(" << dbgMsg.str()
<< " processed=" << (response!=0);
return response;
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::processResponse(Response* r)
{
StringUtil::StrStreamType dbgMsg;
dbgMsg << "thread:" <<
#if OGRE_THREAD_SUPPORT
OGRE_THREAD_CURRENT_ID
#else
"main"
#endif
<< "): ID=" << r->getRequest()->getID()
<< " success=" << r->succeeded() << " messages=[" << r->getMessages() << "] channel="
<< r->getRequest()->getChannel() << " requestType=" << r->getRequest()->getType();
LogManager::getSingleton().stream(LML_TRIVIAL) <<
"DefaultWorkQueueBase('" << mName << "') - PROCESS_RESPONSE_START(" << dbgMsg.str();
ResponseHandlerListByChannel::iterator i = mResponseHandlers.find(r->getRequest()->getChannel());
if (i != mResponseHandlers.end())
{
ResponseHandlerList& handlers = i->second;
for (ResponseHandlerList::reverse_iterator j = handlers.rbegin(); j != handlers.rend(); ++j)
{
if ((*j)->canHandleResponse(r, this))
{
(*j)->handleResponse(r, this);
}
}
}
LogManager::getSingleton().stream(LML_TRIVIAL) <<
"DefaultWorkQueueBase('" << mName << "') - PROCESS_RESPONSE_END(" << dbgMsg.str();
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::WorkerFunc::operator()()
{
mQueue->_threadMain();
}
void DefaultWorkQueueBase::WorkerFunc::run()
{
mQueue->_threadMain();
}
}
|
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreWorkQueue.h"
#include "OgreLogManager.h"
#include "OgreRoot.h"
#include "OgreRenderSystem.h"
namespace Ogre {
//---------------------------------------------------------------------
WorkQueue::Request::Request(uint16 channel, uint16 rtype, const Any& rData, uint8 retry, RequestID rid)
: mChannel(channel), mType(rtype), mData(rData), mRetryCount(retry), mID(rid)
{
}
//---------------------------------------------------------------------
WorkQueue::Request::~Request()
{
}
//---------------------------------------------------------------------
//---------------------------------------------------------------------
WorkQueue::Response::Response(const Request* rq, bool success, const Any& data, const String& msg)
: mRequest(rq), mSuccess(success), mMessages(msg), mData(data)
{
}
//---------------------------------------------------------------------
WorkQueue::Response::~Response()
{
OGRE_DELETE mRequest;
}
//---------------------------------------------------------------------
//---------------------------------------------------------------------
DefaultWorkQueueBase::DefaultWorkQueueBase(const String& name)
: mName(name)
, mWorkerThreadCount(1)
, mWorkerRenderSystemAccess(false)
, mIsRunning(false)
, mResposeTimeLimitMS(0)
, mWorkerFunc(this)
, mRequestCount(0)
, mPaused(false)
, mAcceptRequests(true)
{
}
//---------------------------------------------------------------------
const String& DefaultWorkQueueBase::getName() const
{
return mName;
}
//---------------------------------------------------------------------
size_t DefaultWorkQueueBase::getWorkerThreadCount() const
{
return mWorkerThreadCount;
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::setWorkerThreadCount(size_t c)
{
mWorkerThreadCount = c;
}
//---------------------------------------------------------------------
bool DefaultWorkQueueBase::getWorkersCanAccessRenderSystem() const
{
return mWorkerRenderSystemAccess;
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::setWorkersCanAccessRenderSystem(bool access)
{
mWorkerRenderSystemAccess = access;
}
//---------------------------------------------------------------------
DefaultWorkQueueBase::~DefaultWorkQueueBase()
{
//shutdown(); // can't call here; abstract function
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::addRequestHandler(uint16 channel, RequestHandler* rh)
{
OGRE_LOCK_RW_MUTEX_WRITE(mRequestHandlerMutex);
RequestHandlerListByChannel::iterator i = mRequestHandlers.find(channel);
if (i == mRequestHandlers.end())
i = mRequestHandlers.insert(RequestHandlerListByChannel::value_type(channel, RequestHandlerList())).first;
RequestHandlerList& handlers = i->second;
if (std::find(handlers.begin(), handlers.end(), rh) == handlers.end())
handlers.push_back(rh);
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::removeRequestHandler(uint16 channel, RequestHandler* rh)
{
OGRE_LOCK_RW_MUTEX_WRITE(mRequestHandlerMutex);
RequestHandlerListByChannel::iterator i = mRequestHandlers.find(channel);
if (i != mRequestHandlers.end())
{
RequestHandlerList& handlers = i->second;
RequestHandlerList::iterator j = std::find(
handlers.begin(), handlers.end(), rh);
if (j != handlers.end())
handlers.erase(j);
}
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::addResponseHandler(uint16 channel, ResponseHandler* rh)
{
ResponseHandlerListByChannel::iterator i = mResponseHandlers.find(channel);
if (i == mResponseHandlers.end())
i = mResponseHandlers.insert(ResponseHandlerListByChannel::value_type(channel, ResponseHandlerList())).first;
ResponseHandlerList& handlers = i->second;
if (std::find(handlers.begin(), handlers.end(), rh) == handlers.end())
handlers.push_back(rh);
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::removeResponseHandler(uint16 channel, ResponseHandler* rh)
{
ResponseHandlerListByChannel::iterator i = mResponseHandlers.find(channel);
if (i != mResponseHandlers.end())
{
ResponseHandlerList& handlers = i->second;
ResponseHandlerList::iterator j = std::find(
handlers.begin(), handlers.end(), rh);
if (j != handlers.end())
handlers.erase(j);
}
}
//---------------------------------------------------------------------
WorkQueue::RequestID DefaultWorkQueueBase::addRequest(uint16 channel, uint16 requestType,
const Any& rData, uint8 retryCount, bool forceSynchronous)
{
Request* req = 0;
RequestID rid = 0;
{
// lock to acquire rid and push request to the queue
OGRE_LOCK_MUTEX(mRequestMutex)
if (!mAcceptRequests || mShuttingDown)
return 0;
rid = ++mRequestCount;
req = OGRE_NEW Request(channel, requestType, rData, retryCount, rid);
LogManager::getSingleton().stream(LML_TRIVIAL) <<
"DefaultWorkQueueBase('" << mName << "') - QUEUED(thread:" <<
#if OGRE_THREAD_SUPPORT
OGRE_THREAD_CURRENT_ID
#else
"main"
#endif
<< "): ID=" << rid
<< " channel=" << channel << " requestType=" << requestType;
#if OGRE_THREAD_SUPPORT
if (!forceSynchronous)
{
mRequestQueue.push_back(req);
notifyWorkers();
return rid;
}
#endif
}
processRequestResponse(req, true);
return rid;
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::addRequestWithRID(WorkQueue::RequestID rid, uint16 channel,
uint16 requestType, const Any& rData, uint8 retryCount)
{
// lock to push request to the queue
OGRE_LOCK_MUTEX(mRequestMutex)
if (mShuttingDown)
return;
Request* req = OGRE_NEW Request(channel, requestType, rData, retryCount, rid);
LogManager::getSingleton().stream(LML_TRIVIAL) <<
"DefaultWorkQueueBase('" << mName << "') - REQUEUED(thread:" <<
#if OGRE_THREAD_SUPPORT
OGRE_THREAD_CURRENT_ID
#else
"main"
#endif
<< "): ID=" << rid
<< " channel=" << channel << " requestType=" << requestType;
#if OGRE_THREAD_SUPPORT
mRequestQueue.push_back(req);
notifyWorkers();
#else
processRequestResponse(req, true);
#endif
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::abortRequest(RequestID id)
{
OGRE_LOCK_MUTEX(mRequestMutex)
for (RequestQueue::iterator i = mRequestQueue.begin(); i != mRequestQueue.end(); ++i)
{
if ((*i)->getID() == id)
{
OGRE_DELETE *i;
mRequestQueue.erase(i);
break;
}
}
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::abortRequestsByChannel(uint16 channel)
{
OGRE_LOCK_MUTEX(mRequestMutex)
for (RequestQueue::iterator i = mRequestQueue.begin(); i != mRequestQueue.end();)
{
if ((*i)->getChannel() == channel)
{
OGRE_DELETE *i;
i = mRequestQueue.erase(i);
}
else
++i;
}
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::abortAllRequests()
{
OGRE_LOCK_MUTEX(mRequestMutex)
for (RequestQueue::iterator i = mRequestQueue.begin(); i != mRequestQueue.end();)
{
OGRE_DELETE *i;
}
mRequestQueue.clear();
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::setPaused(bool pause)
{
OGRE_LOCK_MUTEX(mRequestMutex)
mPaused = pause;
}
//---------------------------------------------------------------------
bool DefaultWorkQueueBase::isPaused() const
{
return mPaused;
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::setRequestsAccepted(bool accept)
{
OGRE_LOCK_MUTEX(mRequestMutex)
mAcceptRequests = accept;
}
//---------------------------------------------------------------------
bool DefaultWorkQueueBase::getRequestsAccepted() const
{
return mAcceptRequests;
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::_processNextRequest()
{
Request* request = 0;
{
// scoped to only lock while retrieving the next request
OGRE_LOCK_MUTEX(mRequestMutex)
if (!mRequestQueue.empty())
{
request = mRequestQueue.front();
mRequestQueue.pop_front();
}
}
if (request)
{
processRequestResponse(request, false);
}
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::processRequestResponse(Request* r, bool synchronous)
{
Response* response = processRequest(r);
if (response)
{
if (!response->succeeded())
{
// Failed, should we retry?
const Request* req = response->getRequest();
if (req->getRetryCount())
{
addRequestWithRID(req->getID(), req->getChannel(), req->getType(), req->getData(),
req->getRetryCount() - 1);
// discard response (this also deletes request)
OGRE_DELETE response;
return;
}
}
if (synchronous)
{
processResponse(response);
OGRE_DELETE response;
}
else
{
// Queue response
OGRE_LOCK_MUTEX(mResponseMutex)
mResponseQueue.push_back(response);
// no need to wake thread, this is processed by the main thread
}
}
else
{
// no response, delete request
LogManager::getSingleton().stream() <<
"DefaultWorkQueueBase('" << mName << "') warning: no handler processed request "
<< r->getID() << ", channel " << r->getChannel()
<< ", type " << r->getType();
OGRE_DELETE r;
}
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::processResponses()
{
unsigned long msStart = Root::getSingleton().getTimer()->getMilliseconds();
unsigned long msCurrent = msStart;
// keep going until we run out of responses or out of time
while(true)
{
Response* response = 0;
{
OGRE_LOCK_MUTEX(mResponseMutex)
if (mResponseQueue.empty())
break; // exit loop
else
{
response = mResponseQueue.front();
mResponseQueue.pop_front();
}
}
if (response)
{
processResponse(response);
OGRE_DELETE response;
}
// time limit
if (mResposeTimeLimitMS)
{
msCurrent = Root::getSingleton().getTimer()->getMilliseconds();
if (msCurrent - msStart > mResposeTimeLimitMS)
break;
}
}
}
//---------------------------------------------------------------------
WorkQueue::Response* DefaultWorkQueueBase::processRequest(Request* r)
{
OGRE_LOCK_RW_MUTEX_READ(mRequestHandlerMutex);
Response* response = 0;
StringUtil::StrStreamType dbgMsg;
dbgMsg <<
#if OGRE_THREAD_SUPPORT
OGRE_THREAD_CURRENT_ID
#else
"main"
#endif
<< "): ID=" << r->getID() << " channel=" << r->getChannel()
<< " requestType=" << r->getType();
LogManager::getSingleton().stream(LML_TRIVIAL) <<
"DefaultWorkQueueBase('" << mName << "') - PROCESS_REQUEST_START(" << dbgMsg.str();
RequestHandlerListByChannel::iterator i = mRequestHandlers.find(r->getChannel());
if (i != mRequestHandlers.end())
{
RequestHandlerList& handlers = i->second;
for (RequestHandlerList::reverse_iterator j = handlers.rbegin(); j != handlers.rend(); ++j)
{
if ((*j)->canHandleRequest(r, this))
{
response = (*j)->handleRequest(r, this);
}
}
}
LogManager::getSingleton().stream(LML_TRIVIAL) <<
"DefaultWorkQueueBase('" << mName << "') - PROCESS_REQUEST_END(" << dbgMsg.str()
<< " processed=" << (response!=0);
return response;
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::processResponse(Response* r)
{
StringUtil::StrStreamType dbgMsg;
dbgMsg << "thread:" <<
#if OGRE_THREAD_SUPPORT
OGRE_THREAD_CURRENT_ID
#else
"main"
#endif
<< "): ID=" << r->getRequest()->getID()
<< " success=" << r->succeeded() << " messages=[" << r->getMessages() << "] channel="
<< r->getRequest()->getChannel() << " requestType=" << r->getRequest()->getType();
LogManager::getSingleton().stream(LML_TRIVIAL) <<
"DefaultWorkQueueBase('" << mName << "') - PROCESS_RESPONSE_START(" << dbgMsg.str();
ResponseHandlerListByChannel::iterator i = mResponseHandlers.find(r->getRequest()->getChannel());
if (i != mResponseHandlers.end())
{
ResponseHandlerList& handlers = i->second;
for (ResponseHandlerList::reverse_iterator j = handlers.rbegin(); j != handlers.rend(); ++j)
{
if ((*j)->canHandleResponse(r, this))
{
(*j)->handleResponse(r, this);
}
}
}
LogManager::getSingleton().stream(LML_TRIVIAL) <<
"DefaultWorkQueueBase('" << mName << "') - PROCESS_RESPONSE_END(" << dbgMsg.str();
}
//---------------------------------------------------------------------
void DefaultWorkQueueBase::WorkerFunc::operator()()
{
mQueue->_threadMain();
}
void DefaultWorkQueueBase::WorkerFunc::run()
{
mQueue->_threadMain();
}
}
|
Patch 2857373: make sure to delete response in synchronous mode
|
Patch 2857373: make sure to delete response in synchronous mode
--HG--
extra : convert_revision : svn%3A8631bf8a-c64b-0410-883c-f3eb003322f7/trunk%401147
|
C++
|
mit
|
ruleless/ogre,bhlzlx/ogre,largerussiangames/ogre,vancepym/ogre,jhu-lcsr-forks/ogre,vancepym/ogre,jhu-lcsr-forks/ogre,bhlzlx/ogre,bhlzlx/ogre,jhu-lcsr-forks/ogre,ruleless/ogre,jhu-lcsr-forks/ogre,ruleless/ogre,ehsan/ogre,ehsan/ogre,nezticle/ogre,bhlzlx/ogre,ehsan/ogre,ruleless/ogre,jhu-lcsr-forks/ogre,nezticle/ogre,bhlzlx/ogre,ehsan/ogre,largerussiangames/ogre,vancepym/ogre,nezticle/ogre,ehsan/ogre,nezticle/ogre,bhlzlx/ogre,largerussiangames/ogre,vancepym/ogre,ruleless/ogre,vancepym/ogre,ruleless/ogre,largerussiangames/ogre
|
44c71f58e9dee99dc6c204f0797c3e12fa55a80f
|
LineCounter/LineCounter.cpp
|
LineCounter/LineCounter.cpp
|
// LineCounter.cpp : Defines the entry point for the console application.
#include "stdafx.h"
using namespace std;
#pragma comment(lib, "User32.lib")
int linesInFile(WIN32_FIND_DATA); // Returns the number of lines in the file to which the argument is a handle
int linesInDirectory(string); // Returns if an error occurred, exactly like main
int linesInDirectoryRecursive(const string&); // Returns the number of lines in the directory tree with root directory given, or -1 if an error occurred
void help(const char*); // Prints the help message to cout
bool isHelpFlag(const char*); // Returns whether the passed string is a recognized help flag
int main(int argc, char* argv[])
{
string dir;
bool recursive(false); // Whether to use a recursive count
if (argc == 1) // No arguments: Print warning and help message, then flat-count files in current working directory.
{
dir = _getcwd(nullptr, 0);
fprintf(stderr, "Warning: No directory given, assuming %s\n", dir.c_str());
help(argv[0]);
cout << endl;
}
else if (argc == 2) // Only one argument given
{
if (isHelpFlag(argv[1])) // If its a help flag, print the help message and return
{
help(argv[0]);
return 0;
}
else if (!strcmp(argv[1], "/r")) // If its the recursive flag, print warning and help message, then recursive-count files in current working directory.
{
dir = _getcwd(nullptr, 0);
recursive = true;
fprintf(stderr, "Warning: No directory given, assuming %s\n", dir.c_str());
help(argv[0]);
cout << endl;
}
dir = argv[1]; // Else, assume that the argument is the directory to count
}
else if (argc==3) // Two arguments given
{
size_t dirpos(1);
recursive = true; // If the program proceeds, it will be in recursive mode
if (!strcmp(argv[dirpos], "/r")) // If the first argument is the recursive flag
dirpos = 2; // The path will be in the second argument
else if (strcmp(argv[2], "/r")) // If the second argument isn't the recursive flag...
{
fprintf(stderr, "Invalid arguments \"%s\", \"%s\"\n", argv[1], argv[2]); // Generate an error,
help(argv[0]); // Print the help message,
return 127; // And exit with an error.
}
dir = argv[dirpos]; // If we haven't exited, this will set dir to contain the path
}
else // If there are more than two arguments, print an error message with all arguments, print the help message, and exit with an error
{
cerr << "Invalid arguments \"" << argv[1] << "\"";
for (int i = 2; i < argc; ++i)
cerr << ", \"" << argv[i] << "\"";
help(argv[0]);
return 127;
}
if (recursive)
return linesInDirectoryRecursive(dir) == -1;
else
return linesInDirectory(dir);
}
int linesInDirectory(string dir)
{
WIN32_FIND_DATA ffd;
cout << "Target directory is " << dir << endl;
_chdir(dir.c_str());
dir += "\\*";
HANDLE find = INVALID_HANDLE_VALUE;
find = FindFirstFile(dir.c_str(), &ffd);
if (find == INVALID_HANDLE_VALUE)
{
cerr << "No files found!\n";
return 1;
}
uintmax_t sum(0);
size_t len(0);
do
{
len = linesInFile(ffd);
sum += len;
cout << "\tFile " << ffd.cFileName << ": " << len << " lines.\n";
cout << "\t\tRunning total: " << sum << endl << endl;
} while (FindNextFile(find, &ffd));
char msg[9001];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | 80, NULL, GetLastError(), 0, msg, 9001, NULL);
cout << "\n\n" << msg;
cout << "\n\nTotal number of lines in files in the directory " << _getcwd(NULL, NULL) << ": " << sum << ".\n";
return 0;
}
int linesInDirectoryRecursive(const string& path)
{
WIN32_FIND_DATA ffd;
cout << "Target directory is " << path << endl;
_chdir(path.c_str());
string dir = path+"\\*";
HANDLE find = INVALID_HANDLE_VALUE;
find = FindFirstFile(dir.c_str(), &ffd);
if (find == INVALID_HANDLE_VALUE)
{
cerr << "No files found!\n";
return -1;
}
uintmax_t sum(0);
size_t len(0);
do
{
if (ffd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)
{
if (!strcmp(ffd.cFileName, ".") || !strcmp(ffd.cFileName, ".."))
continue;
cout << "\n\nFound directory " << ffd.cFileName << ".\n";
cout << "Counting lines in directory...\n\n";
len = linesInDirectoryRecursive(path+ffd.cFileName+"\\");
if (len != -1)
sum += len;
cout << "Done with subdirectory " << ffd.cFileName << "\\.\n";
cout << "\tRunning total of lines in " << path << ": " << sum << ".\n\n";
}
else
{
len = linesInFile(ffd);
sum += len;
cout << "\tFile " << ffd.cFileName << ": " << len << " lines.\n";
cout << "\t\tRunning total: " << sum << endl << endl;
}
} while (FindNextFile(find, &ffd));
char msg[9001];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | 80, NULL, GetLastError(), 0, msg, 9001, NULL);
cout << "\n\n" << msg;
cout << "\n\nTotal number of lines in files in the directory " << path << ": " << sum << ".\n";
return sum;
}
int linesInFile(WIN32_FIND_DATA ffd)
{
ifstream in;
if (ffd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)
return 0;
in.open(ffd.cFileName, ios::in);
size_t len(0);
string line;
while (in.good())
{
getline(in, line);
++len;
}
in.clear();
in.close();
return len;
}
void help(const char* prog)
{
cout << "LineCounter: Counts the number of lines in all files of the chosen directory.\n";
cout << "Usage: " << prog << " [directory_path] [/r]\n";
cout << " directory_path: The path to the directory in which to count lines\n";
cout << " If omitted, will print a warning message and count files in the current\n";
cout << " working directory.\n";
cout << " /r: Recursive mode\n";
cout << " By default, LineCounter will only count files directly in the directory\n";
cout << " given: That is, it will produce a flat count.\n";
cout << " Passing this flag will instruct it to count files in all subdirectories\n";
cout << " as well: A recursive count.\n";
}
bool isHelpFlag(const char* arg)
{
return !strcmp(arg, "/h") || !strcmp(arg, "/help") || !strcmp(arg, "/?") || !strcmp(arg, "-h") || !strcmp(arg, "--help");
}
|
// LineCounter.cpp : Defines the entry point for the console application.
#include "stdafx.h"
using namespace std;
#pragma comment(lib, "User32.lib")
int linesInFile(WIN32_FIND_DATA); // Returns the number of lines in the file to which the argument is a handle
int linesInDirectory(string); // Returns if an error occurred, exactly like main
int linesInDirectoryRecursive(const string&); // Returns the number of lines in the directory tree with root directory given, or -1 if an error occurred
void help(const char*); // Prints the help message to cout
bool isHelpFlag(const char*); // Returns whether the passed string is a recognized help flag
int main(int argc, char* argv[])
{
string dir;
bool recursive(false); // Whether to use a recursive count
if (argc == 1) // No arguments: Print warning and help message, then flat-count files in current working directory.
{
dir = _getcwd(nullptr, 0);
fprintf(stderr, "Warning: No directory given, assuming %s\n", dir.c_str());
help(argv[0]);
cout << endl;
}
else if (argc == 2) // Only one argument given
{
if (isHelpFlag(argv[1])) // If its a help flag, print the help message and return
{
help(argv[0]);
return 0;
}
else if (!strcmp(argv[1], "/r")) // If its the recursive flag, print warning and help message, then recursive-count files in current working directory.
{
dir = _getcwd(nullptr, 0);
recursive = true;
fprintf(stderr, "Warning: No directory given, assuming %s\n", dir.c_str());
help(argv[0]);
cout << endl;
}
dir = argv[1]; // Else, assume that the argument is the directory to count
}
else if (argc==3) // Two arguments given
{
size_t dirpos(1);
recursive = true; // If the program proceeds, it will be in recursive mode
if (!strcmp(argv[dirpos], "/r")) // If the first argument is the recursive flag
dirpos = 2; // The path will be in the second argument
else if (strcmp(argv[2], "/r")) // If the second argument isn't the recursive flag...
{
fprintf(stderr, "Invalid arguments \"%s\", \"%s\"\n", argv[1], argv[2]); // Generate an error,
help(argv[0]); // Print the help message,
return 127; // And exit with an error.
}
dir = argv[dirpos]; // If we haven't exited, this will set dir to contain the path
}
else // If there are more than two arguments, print an error message with all arguments, print the help message, and exit with an error
{
cerr << "Invalid arguments \"" << argv[1] << "\"";
for (int i = 2; i < argc; ++i)
cerr << ", \"" << argv[i] << "\"";
help(argv[0]);
return 127;
}
if (recursive)
return linesInDirectoryRecursive(dir) == -1;
else
return linesInDirectory(dir);
}
int linesInDirectory(string dir)
{
WIN32_FIND_DATA ffd;
cout << "Target directory is " << dir << endl;
_chdir(dir.c_str());
dir += "\\*";
HANDLE find = INVALID_HANDLE_VALUE;
find = FindFirstFile(dir.c_str(), &ffd);
if (find == INVALID_HANDLE_VALUE)
{
cerr << "No files found!\n";
return 1;
}
uintmax_t sum(0);
size_t len(0);
do
{
len = linesInFile(ffd);
sum += len;
cout << "\tFile " << ffd.cFileName << ": " << len << " lines.\n";
cout << "\t\tRunning total: " << sum << endl << endl;
} while (FindNextFile(find, &ffd));
char msg[9001];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | 80, NULL, GetLastError(), 0, msg, 9001, NULL);
cout << "\n\n" << msg;
cout << "\n\nTotal number of lines in files in the directory " << _getcwd(NULL, NULL) << ": " << sum << ".\n";
return 0;
}
int linesInDirectoryRecursive(const string& path)
{
WIN32_FIND_DATA ffd;
cout << "Target directory is " << path << endl;
_chdir(path.c_str());
string dir = path+"\\*";
HANDLE find = INVALID_HANDLE_VALUE;
find = FindFirstFile(dir.c_str(), &ffd);
if (find == INVALID_HANDLE_VALUE)
{
cerr << "No files found!\n";
return -1;
}
uintmax_t sum(0);
size_t len(0);
do
{
if (ffd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)
{
if (!strcmp(ffd.cFileName, ".") || !strcmp(ffd.cFileName, ".."))
continue;
cout << "\n\nFound directory " << ffd.cFileName << ".\n";
cout << "Counting lines in directory...\n\n";
len = linesInDirectoryRecursive(path+ffd.cFileName+"\\");
if (len != -1)
sum += len;
cout << "Done with subdirectory " << ffd.cFileName << ".\n";
cout << "\tRunning total of lines in " << path << ": " << sum << ".\n\n";
}
else
{
len = linesInFile(ffd);
sum += len;
cout << "\tFile " << ffd.cFileName << ": " << len << " lines.\n";
cout << "\t\tRunning total: " << sum << endl << endl;
}
} while (FindNextFile(find, &ffd));
char msg[9001];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | 80, NULL, GetLastError(), 0, msg, 9001, NULL);
cout << "\n\n" << msg;
cout << "\n\nTotal number of lines in files in the directory " << path << ": " << sum << ".\n";
return sum;
}
int linesInFile(WIN32_FIND_DATA ffd)
{
ifstream in;
if (ffd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)
return 0;
in.open(ffd.cFileName, ios::in);
size_t len(0);
string line;
while (in.good())
{
getline(in, line);
++len;
}
in.clear();
in.close();
return len;
}
void help(const char* prog)
{
cout << "LineCounter: Counts the number of lines in all files of the chosen directory.\n";
cout << "Usage: " << prog << " [directory_path] [/r]\n";
cout << " directory_path: The path to the directory in which to count lines\n";
cout << " If omitted, will print a warning message and count files in the current\n";
cout << " working directory.\n";
cout << " /r: Recursive mode\n";
cout << " By default, LineCounter will only count files directly in the directory\n";
cout << " given: That is, it will produce a flat count.\n";
cout << " Passing this flag will instruct it to count files in all subdirectories\n";
cout << " as well: A recursive count.\n";
}
bool isHelpFlag(const char* arg)
{
return !strcmp(arg, "/h") || !strcmp(arg, "/help") || !strcmp(arg, "/?") || !strcmp(arg, "-h") || !strcmp(arg, "--help");
}
|
Revert one display alteration
|
Revert one display alteration
|
C++
|
apache-2.0
|
za419/LineCounter,za419/LineCounter
|
1eedd6abbafa93377971393c957953ceff1fc758
|
ibv_message_passing_c_project/source/compare_ada_files/compare_ada_files.cpp
|
ibv_message_passing_c_project/source/compare_ada_files/compare_ada_files.cpp
|
/*
* @file compare_ada_files.cpp
* @date 21 May 2022
* @author Chester Gillon
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <set>
#include <string>
#include <ftw.h>
/* Used to contain the relative paths of all source files from one directory root to be compared */
typedef std::set<std::string> source_file_list_t;
/* Maximum number of open file descriptors used by ntfw().
* Conservative value recommended by https://stackoverflow.com/questions/8436841/how-to-recursively-list-directories-in-c-on-linux
*
* sysconf() isn't implemented in mingw, so haven't used the other suggestion of basing upon sysconf(_SC_OPEN_MAX)
*/
#define MAX_NFTW_OPEN_DESCRIPTORS 15
/* The list of source files in two directories trees to be compared */
static source_file_list_t left_source_list;
static source_file_list_t right_source_list;
/* The source list currently being populated by nftw() */
static source_file_list_t *current_source_list = NULL;
/* The length of the source tree root currently being populated by nftw().
* Used so that current_source_list is only populated with the pathname components under the root,
* so will be the same for both trees being compared. */
static size_t current_source_tree_root_prefix_len;
/* This list of extensions considered as Ada source files */
static const char *const ada_source_file_extensions[] =
{
".ada",
".adb",
".ads"
};
static const int num_ada_source_file_extensions = sizeof (ada_source_file_extensions) / sizeof (ada_source_file_extensions[0]);
/* The possible comparison results between two directory trees */
typedef enum
{
/* The file only appears in the left source tree */
FILE_COMPARISON_LEFT_ONLY,
/* The file only appears in the right source tree */
FILE_COMPARISON_RIGHT_ONLY,
/* The file is binary equal between the left and right source tree */
FILE_COMPARISON_BINARY_EQUAL,
/* The file is lexically different between the left and right source tree, meaning some functional difference in the
* Ada statements */
FILE_COMPARISON_DIFFERENT,
/* The file is lexically equal between the left and right source tree, meaning differences in either:
* a. Comments
* b. Whitespace
* c. Casing
* d. Wrapping of statements across source lines
*/
FILE_COMPARISON_LEXICAL_EQUAL,
FILE_COMPARISON_ARRAY_SIZE
} file_comparison_t;
static const char *const file_comparison_names[FILE_COMPARISON_ARRAY_SIZE] =
{
[FILE_COMPARISON_LEFT_ONLY ] = "Left only",
[FILE_COMPARISON_RIGHT_ONLY ] = "Right only",
[FILE_COMPARISON_BINARY_EQUAL ] = "Binary equal",
[FILE_COMPARISON_DIFFERENT ] = "Different",
[FILE_COMPARISON_LEXICAL_EQUAL] = "Lexical equal"
};
/**
* @brief Callback function for nftw()
* @details When passes an Ada source file inserts into current_source_list
* @param[in] fpath The pathname in the directory tree
* @oaram[in] sb Not used
* @param[in] flagtype The type of path:
* a. Files are processed to check if an Ada source file
* b. Directories are ignored
* c. Errors accessing files cause the program to be aborted, to avoid reporting partial trees
*/
static int tree_walk_callback (const char *fpath, const struct stat *sb, int flagtype, struct FTW *ftwbuf)
{
const char *const filename = &fpath[ftwbuf->base];
/* On the first call at directory level zero work out how many characters to ignore from the start of fpath
* so that only store the pathname components of each source file relative to the root. */
if ((current_source_tree_root_prefix_len == 0) && (ftwbuf->level == 0))
{
current_source_tree_root_prefix_len = strlen (fpath);
if (current_source_tree_root_prefix_len > 0)
{
const char last_char = fpath[current_source_tree_root_prefix_len - 1];
if ((last_char != '/') && (last_char != '\\'))
{
/* Skip the assumed directory separator which will be present in subsequent calls */
current_source_tree_root_prefix_len++;
}
}
}
switch (flagtype)
{
case FTW_F:
case FTW_SL:
/* If the file extension is that of an Ada source file, then store the filename in the source file list */
{
const char *const extension = strrchr (filename, '.');
if (extension != NULL)
{
for (int extension_index = 0; extension_index < num_ada_source_file_extensions; extension_index++)
{
if (strcasecmp (extension, ada_source_file_extensions[extension_index]) == 0)
{
current_source_list->insert (&fpath[current_source_tree_root_prefix_len]);
break;
}
}
}
}
break;
case FTW_D:
case FTW_DP:
/* Nothing to do for a directory */
break;
case FTW_DNR:
printf ("Error: %s is a directory which can't be read\n", fpath);
exit (EXIT_FAILURE);
break;
case FTW_NS:
printf ("Error: stat() call failed on %s\n", fpath);
exit (EXIT_FAILURE);
break;
case FTW_SLN:
printf ("Error: %s is a symbolic link pointing to a nonexistent file\n", fpath);
exit (EXIT_FAILURE);
break;
}
/* Continue the tree walk */
return 0;
}
int main (int argc, char *argv[])
{
if (argc != 4)
{
printf ("Usage: %s <left_source_tree_root> <right_source_tree_root> <result_dir>\n", argv[0]);
exit (EXIT_FAILURE);
}
const char *const left_source_tree_root = argv[1];
const char *const right_source_tree_root = argv[2];
const char *const result_dir = argv[3];
/* Get the list of Ada source files in the left and right source trees */
current_source_list = &left_source_list;
current_source_tree_root_prefix_len = 0;
(void) nftw (left_source_tree_root, tree_walk_callback, MAX_NFTW_OPEN_DESCRIPTORS, FTW_PHYS);
current_source_list = &right_source_list;
current_source_tree_root_prefix_len = 0;
(void) nftw (right_source_tree_root, tree_walk_callback, MAX_NFTW_OPEN_DESCRIPTORS, FTW_PHYS);
/* Iterate through the left and right source trees:
* a. For source files in both source trees perform a comparison of the file contents.
* b. For source files in only one source tree report that only present in one tree.
*
* The order in which iterates over the source trees is determined by the std::string compare() order
* for the pathnames. The use of the source_file_list_t map to store the paths in the source trees means they
* are in both in string order, rather than the order nftw() walked the trees.
*/
source_file_list_t::const_iterator left_it = left_source_list.begin();
source_file_list_t::const_iterator right_it = right_source_list.begin();
const std::string *reported_source_name = NULL;
file_comparison_t file_comparison;
while ((left_it != left_source_list.end()) || (right_it != right_source_list.end()))
{
if (left_it == left_source_list.end())
{
/* Right only since reached the end of the left source list */
file_comparison = FILE_COMPARISON_RIGHT_ONLY;
reported_source_name = &(*right_it);
++right_it;
}
else if (right_it == right_source_list.end())
{
/* Left only since reached the end of the right source list */
file_comparison = FILE_COMPARISON_LEFT_ONLY;
reported_source_name = &(*left_it);
++left_it;
}
else
{
const int compare_rc = left_it->compare (*right_it);
if (compare_rc == 0)
{
/* Same source file in the left and right source list, so compare the file contents */
file_comparison = FILE_COMPARISON_DIFFERENT; /* @todo add compare function */
reported_source_name = &(*left_it);
++left_it;
++right_it;
}
else if (compare_rc < 0)
{
/* Left only as the left source path is ordered before the right source path */
file_comparison = FILE_COMPARISON_LEFT_ONLY;
reported_source_name = &(*left_it);
++left_it;
}
else
{
/* Right only as the left source path is order after the right source path */
file_comparison = FILE_COMPARISON_RIGHT_ONLY;
reported_source_name = &(*right_it);
++right_it;
}
}
/* @todo initial test of walking the source trees */
printf ("%s,%s\n", file_comparison_names[file_comparison], reported_source_name->c_str());
}
return EXIT_SUCCESS;
}
|
/*
* @file compare_ada_files.cpp
* @date 21 May 2022
* @author Chester Gillon
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <set>
#include <string>
#include <limits.h>
#include <ftw.h>
/* Used to contain the relative paths of all source files from one directory root to be compared */
typedef std::set<std::string> source_file_list_t;
/* Maximum number of open file descriptors used by ntfw().
* Conservative value recommended by https://stackoverflow.com/questions/8436841/how-to-recursively-list-directories-in-c-on-linux
*
* sysconf() isn't implemented in mingw, so haven't used the other suggestion of basing upon sysconf(_SC_OPEN_MAX)
*/
#define MAX_NFTW_OPEN_DESCRIPTORS 15
/* Contains one source tree */
typedef struct
{
/* The root directory for the source tree, which ends with a directory separator */
char root_directory[PATH_MAX];
/* The paths to the Ada source file in the tree, relative to the root directory */
source_file_list_t source_list;
} source_tree_t;
/* The two directories trees to be compared */
static source_tree_t left_tree;
static source_tree_t right_tree;
/* The source tree currently being populated by nftw() */
static source_tree_t *current_tree = NULL;
/* The length of the source tree root currently being populated by nftw().
* Used so that current_source_list is only populated with the pathname components under the root,
* so will be the same for both trees being compared. */
static size_t current_source_tree_root_prefix_len;
/* This list of extensions considered as Ada source files */
static const char *const ada_source_file_extensions[] =
{
".ada",
".adb",
".ads"
};
static const int num_ada_source_file_extensions = sizeof (ada_source_file_extensions) / sizeof (ada_source_file_extensions[0]);
/* The possible comparison results between two directory trees */
typedef enum
{
/* The file only appears in the left source tree */
FILE_COMPARISON_LEFT_ONLY,
/* The file only appears in the right source tree */
FILE_COMPARISON_RIGHT_ONLY,
/* The file is binary equal between the left and right source tree */
FILE_COMPARISON_BINARY_EQUAL,
/* The file is lexically different between the left and right source tree, meaning some functional difference in the
* Ada statements */
FILE_COMPARISON_DIFFERENT,
/* The file is lexically equal between the left and right source tree, meaning differences in either:
* a. Comments
* b. Whitespace
* c. Casing
* d. Wrapping of statements across source lines
*/
FILE_COMPARISON_LEXICAL_EQUAL,
FILE_COMPARISON_ARRAY_SIZE
} file_comparison_t;
static const char *const file_comparison_names[FILE_COMPARISON_ARRAY_SIZE] =
{
[FILE_COMPARISON_LEFT_ONLY ] = "Left only",
[FILE_COMPARISON_RIGHT_ONLY ] = "Right only",
[FILE_COMPARISON_BINARY_EQUAL ] = "Binary equal",
[FILE_COMPARISON_DIFFERENT ] = "Different",
[FILE_COMPARISON_LEXICAL_EQUAL] = "Lexical equal"
};
/* Used to hold the contents of an Ada source file to be compared */
typedef struct
{
/* The size of the file in bytes */
size_t file_length;
/* The raw byte contents of the file. */
char *file_contents;
/* The lexical length of the file, after removing comments and whitespace */
size_t lexical_length;
/* The lexical contents of the file. Characters outside of string or character literals are converted to lower case
* to allow for Ada being case-insensitive for identifiers. */
char *lexical_contents;
} compared_file_contents_t;
/**
* @brief Callback function for nftw()
* @details When passes an Ada source file inserts into current_source_list
* @param[in] fpath The pathname in the directory tree
* @oaram[in] sb Not used
* @param[in] flagtype The type of path:
* a. Files are processed to check if an Ada source file
* b. Directories are ignored
* c. Errors accessing files cause the program to be aborted, to avoid reporting partial trees
*/
static int tree_walk_callback (const char *fpath, const struct stat *sb, int flagtype, struct FTW *ftwbuf)
{
const char *const filename = &fpath[ftwbuf->base];
/* On the first call at directory level zero work out how many characters to ignore from the start of fpath
* so that only store the pathname components of each source file relative to the root. */
if ((current_source_tree_root_prefix_len == 0) && (ftwbuf->level == 0))
{
current_source_tree_root_prefix_len = strlen (fpath);
if (current_source_tree_root_prefix_len > 0)
{
const char last_char = fpath[current_source_tree_root_prefix_len - 1];
if ((last_char != '/') && (last_char != '\\'))
{
/* Skip the assumed directory separator which will be present in subsequent calls */
current_source_tree_root_prefix_len++;
}
}
}
switch (flagtype)
{
case FTW_F:
case FTW_SL:
/* If the file extension is that of an Ada source file, then store the filename in the source file list */
{
const char *const extension = strrchr (filename, '.');
if (extension != NULL)
{
for (int extension_index = 0; extension_index < num_ada_source_file_extensions; extension_index++)
{
if (strcasecmp (extension, ada_source_file_extensions[extension_index]) == 0)
{
if (current_tree->root_directory[0] == '\0')
{
/* Save the canonicalised root directory */
snprintf (current_tree->root_directory, sizeof (current_tree->root_directory), fpath);
current_tree->root_directory[current_source_tree_root_prefix_len] = '\0';
}
current_tree->source_list.insert (&fpath[current_source_tree_root_prefix_len]);
break;
}
}
}
}
break;
case FTW_D:
case FTW_DP:
/* Nothing to do for a directory */
break;
case FTW_DNR:
printf ("Error: %s is a directory which can't be read\n", fpath);
exit (EXIT_FAILURE);
break;
case FTW_NS:
printf ("Error: stat() call failed on %s\n", fpath);
exit (EXIT_FAILURE);
break;
case FTW_SLN:
printf ("Error: %s is a symbolic link pointing to a nonexistent file\n", fpath);
exit (EXIT_FAILURE);
break;
}
/* Continue the tree walk */
return 0;
}
static void parse_lexical_file_contents (compared_file_contents_t *const contents)
{
bool in_comment = false;
bool in_character_literal = false;
bool in_identifier = false;
size_t file_index = 0;
while (file_index < contents->file_length)
{
const char *ch = &contents->file_contents[file_index];
size_t num_chars_consumed = 1;
const size_t num_remaining_chars = contents->file_length - file_index;
if (in_comment)
{
/* Comment finishes at end of line */
if (*ch == '\n')
{
in_comment = false;
}
}
else if (in_character_literal)
{
if ((num_remaining_chars >= 2) && (ch[0] == '\"') && (ch[1] == '\"'))
{
/* Found an embedded quote in the character literal */
contents->lexical_contents[contents->lexical_length++] = *ch++;
contents->lexical_contents[contents->lexical_length++] = *ch++;
num_chars_consumed++;
}
else if (contents->file_contents[file_index] == '\"')
{
/* Found the end of the character literal */
contents->lexical_contents[contents->lexical_length++] = *ch;
in_character_literal = false;
}
else
{
/* One character inside a character literal */
contents->lexical_contents[contents->lexical_length++] = *ch;
}
}
else if (in_identifier)
{
if (isalnum (*ch) || (*ch == '_'))
{
/* One character inside an identifier, store as lower case */
contents->lexical_contents[contents->lexical_length++] = tolower (*ch);
}
else
{
in_identifier = false;
if (isspace (*ch))
{
/* The identifier has been terminated by a whitespace character.
* Add a single space to the lexical contents to break up identifiers */
/* @todo this doesn't produce the same lexical content in the case of spaces between punctuation.
* E.g:
* rx_buffer := ibv_message_bw_interface_h.poll_rx_paths (communication_context);
* v.s:
* rx_buffer:=ibv_message_bw_interface_h.poll_rx_paths(communication_context);
*
* To fix this only need to insert spaces between identifiers
*/
contents->lexical_contents[contents->lexical_length++] = ' ';
}
else
{
/* The identifier was been terminated by something other than whitespace.
* Don't consume the character which is re-evaluated by the next loop iteration. */
num_chars_consumed = 0;
}
}
}
else if ((num_remaining_chars >= 2) && (ch[0] == '-') && (ch[1] == '-'))
{
/* Found start of comment, which isn't part of the lexical contents */
in_comment = true;
num_chars_consumed++;
}
else if (*ch == '\"')
{
/* Found start of character literal, which forms part of the lexical contents */
in_character_literal = true;
contents->lexical_contents[contents->lexical_length++] = *ch;
}
else if ((num_remaining_chars >= 3) && (ch[0] == '\'') && (ch[2] == '\''))
{
/* Store a character literal.
* @todo This simplistic test gets the wrong answer in the case of:
* test : Character := Character'(' ');
*
* Since the character literal is consider as open-bracket rather than space.
* The GNAT Bench syntax high-lighter seems to make the same mistake.
* To properly detect character literals would need to detect when ' is used for attributes.
* */
contents->lexical_contents[contents->lexical_length++] = *ch++;
contents->lexical_contents[contents->lexical_length++] = *ch++;
num_chars_consumed++;
contents->lexical_contents[contents->lexical_length++] = *ch++;
num_chars_consumed++;
}
else if (isalpha (*ch))
{
/* Store as lower case the first letter which starts an identifier */
in_identifier = true;
contents->lexical_contents[contents->lexical_length++] = tolower (*ch);
}
else if (isspace (*ch))
{
/* Whitespace character which isn't part of the lexical contents compared */
}
else
{
/* Assume punctuation character, which is stored as part of the lexical contents compared.
* This doesn't attempt to detect characters which are syntax errors. */
contents->lexical_contents[contents->lexical_length++] = *ch++;
}
file_index += num_chars_consumed;
}
}
static void read_file_for_comparison (compared_file_contents_t *const contents,
const char *const root_directory, const char *const source_name)
{
char pathname[PATH_MAX];
FILE *source_file;
int rc;
/* Open source file and gets it length */
snprintf (pathname, sizeof (pathname), "%s%s", root_directory, source_name);
source_file = fopen (pathname, "rb");
if (source_file == NULL)
{
printf ("Error: Unable to open %s\n", pathname);
exit (EXIT_FAILURE);
}
rc = fseek (source_file, 0, SEEK_END);
if (rc != 0)
{
printf ("Error: Failed to seek to end of %s\n", pathname);
exit (EXIT_FAILURE);
}
long file_size = ftell (source_file);
if (file_size < 0)
{
printf ("Error: Failed to get size of %s\n", pathname);
exit (EXIT_FAILURE);
}
/* Read the entire contents of the file into memory, and allocate the lexical contents array to be the same maximum length */
rc = fseek (source_file, 0, SEEK_SET);
if (rc != 0)
{
printf ("Error: Failed to seek to start of %s\n", pathname);
exit (EXIT_FAILURE);
}
contents->file_length = (size_t) file_size;
contents->file_contents = (char *) malloc (contents->file_length);
contents->lexical_length = 0;
contents->lexical_contents = (char *) malloc (contents->file_length);
if ((contents->file_contents == NULL) || (contents->lexical_contents == NULL))
{
printf ("Error: Failed to allocate memory to read %s\n", pathname);
exit (EXIT_FAILURE);
}
size_t bytes_read = fread (contents->file_contents, 1, contents->file_length, source_file);
if (bytes_read != contents->file_length)
{
printf ("Error: Failed to read contents of %s\n", pathname);
exit (EXIT_FAILURE);
}
parse_lexical_file_contents (contents);
(void) fclose (source_file);
}
static file_comparison_t compare_source_files (const char *const left_tree_root, const char *const right_tree_root,
const char *const source_name)
{
compared_file_contents_t left_contents;
compared_file_contents_t right_contents;
file_comparison_t file_comparison;
read_file_for_comparison (&left_contents, left_tree_root, source_name);
read_file_for_comparison (&right_contents, right_tree_root, source_name);
if ((left_contents.file_length == right_contents.file_length) &&
(memcmp (left_contents.file_contents, right_contents.file_contents, left_contents.file_length) == 0))
{
file_comparison = FILE_COMPARISON_BINARY_EQUAL;
}
else
{
if ((left_contents.lexical_length == right_contents.lexical_length) &&
(memcmp (left_contents.lexical_contents, right_contents.lexical_contents, left_contents.lexical_length) == 0))
{
file_comparison = FILE_COMPARISON_LEXICAL_EQUAL;
}
else
{
file_comparison = FILE_COMPARISON_DIFFERENT;
}
}
free (left_contents.file_contents);
free (right_contents.lexical_contents);
return file_comparison;
}
int main (int argc, char *argv[])
{
if (argc != 4)
{
printf ("Usage: %s <left_source_tree_root> <right_source_tree_root> <result_dir>\n", argv[0]);
exit (EXIT_FAILURE);
}
const char *const left_source_tree_root = argv[1];
const char *const right_source_tree_root = argv[2];
const char *const result_dir = argv[3];
/* Get the list of Ada source files in the left and right source trees */
current_tree = &left_tree;
current_source_tree_root_prefix_len = 0;
(void) nftw (left_source_tree_root, tree_walk_callback, MAX_NFTW_OPEN_DESCRIPTORS, FTW_PHYS);
current_tree = &right_tree;
current_source_tree_root_prefix_len = 0;
(void) nftw (right_source_tree_root, tree_walk_callback, MAX_NFTW_OPEN_DESCRIPTORS, FTW_PHYS);
/* Iterate through the left and right source trees:
* a. For source files in both source trees perform a comparison of the file contents.
* b. For source files in only one source tree report that only present in one tree.
*
* The order in which iterates over the source trees is determined by the std::string compare() order
* for the pathnames. The use of the source_file_list_t map to store the paths in the source trees means they
* are in both in string order, rather than the order nftw() walked the trees.
*/
source_file_list_t::const_iterator left_it = left_tree.source_list.begin();
source_file_list_t::const_iterator right_it = right_tree.source_list.begin();
const std::string *reported_source_name = NULL;
file_comparison_t file_comparison;
while ((left_it != left_tree.source_list.end()) || (right_it != right_tree.source_list.end()))
{
if (left_it == left_tree.source_list.end())
{
/* Right only since reached the end of the left source list */
file_comparison = FILE_COMPARISON_RIGHT_ONLY;
reported_source_name = &(*right_it);
++right_it;
}
else if (right_it == right_tree.source_list.end())
{
/* Left only since reached the end of the right source list */
file_comparison = FILE_COMPARISON_LEFT_ONLY;
reported_source_name = &(*left_it);
++left_it;
}
else
{
const int compare_rc = left_it->compare (*right_it);
if (compare_rc == 0)
{
/* Same source file in the left and right source list, so compare the file contents */
file_comparison = compare_source_files (left_tree.root_directory, right_tree.root_directory, left_it->c_str());
reported_source_name = &(*left_it);
++left_it;
++right_it;
}
else if (compare_rc < 0)
{
/* Left only as the left source path is ordered before the right source path */
file_comparison = FILE_COMPARISON_LEFT_ONLY;
reported_source_name = &(*left_it);
++left_it;
}
else
{
/* Right only as the left source path is order after the right source path */
file_comparison = FILE_COMPARISON_RIGHT_ONLY;
reported_source_name = &(*right_it);
++right_it;
}
}
/* @todo initial test of walking the source trees */
printf ("%s,%s\n", file_comparison_names[file_comparison], reported_source_name->c_str());
}
return EXIT_SUCCESS;
}
|
Add first attempt at comparing the lexical contents
|
Add first attempt at comparing the lexical contents
|
C++
|
mit
|
Chester-Gillon/ibv_message_passing,Chester-Gillon/ibv_message_passing,Chester-Gillon/ibv_message_passing
|
de1004531d7fdc85f662c9ae791e64ebc5537822
|
src/appleseed/foundation/utility/unzipper.cpp
|
src/appleseed/foundation/utility/unzipper.cpp
|
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2017 Gleb Mishchenko, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "unzipper.h"
// appleseed.foundation headers.
#include "foundation/core/exceptions/exception.h"
#include "foundation/utility/minizip/unzip.h"
// Boost headers.
#include "boost/filesystem.hpp"
// Standard headers.
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
namespace bf = boost::filesystem;
namespace foundation
{
const size_t BUFFER_SIZE = 4096;
bool is_zip_entry_directory(const string& dirname)
{
// used own implementation of is_zip_entry_directory instead of boost implementation
// because this directory is not in filesystem, but in zipfile
return dirname[dirname.size() - 1] == '/';
}
void open_current_file(unzFile& zip_file)
{
const int err = unzOpenCurrentFile(zip_file);
if (err != UNZ_OK)
throw UnzipException("Can't open file inside zip: ", err);
}
int read_chunk(unzFile& zip_file, char* buffer, const int chunk_size)
{
const int err = unzReadCurrentFile(zip_file, buffer, chunk_size);
if (err == UNZ_ERRNO)
throw UnzipException("IO error while reading from zip");
if (err < 0)
throw UnzipException("zLib error while decompressing file: ", err);
return err;
}
void close_current_file(unzFile& zip_file)
{
const int err = unzCloseCurrentFile(zip_file);
if (err == UNZ_CRCERROR)
throw UnzipException("CRC32 is not good");
}
string read_filename(unzFile& zip_file)
{
unz_file_info zip_file_info;
unzGetCurrentFileInfo(zip_file, &zip_file_info, NULL, 0, NULL, 0, NULL, 0);
vector<char> filename(zip_file_info.size_filename + 1);
unzGetCurrentFileInfo(zip_file, &zip_file_info, &filename[0], filename.size(), NULL, 0, NULL, 0);
filename[filename.size() - 1] = '\0';
const string inzip_filename(&filename[0]);
return inzip_filename;
}
string get_filepath(unzFile& zip_file, const string& unzipped_dir)
{
string filename = read_filename(zip_file);
return (bf::path(unzipped_dir) / bf::path(filename)).string();
}
void extract_current_file(unzFile& zip_file, const string& unzipped_dir)
{
const string filepath = get_filepath(zip_file, unzipped_dir);
if (is_zip_entry_directory(filepath))
{
bf::create_directories(bf::path(filepath));
return;
}
else open_current_file(zip_file);
fstream out(filepath.c_str(), ios_base::out | ios_base::binary);
char buffer[BUFFER_SIZE];
int read;
do
{
read = read_chunk(zip_file, (char*) &buffer, BUFFER_SIZE);
out.write((char*) &buffer, read);
}
while (!unzeof(zip_file));
out.close();
close_current_file(zip_file);
}
void unzip(const string& zip_filename, const string& unzipped_dir)
{
try
{
if (bf::exists(bf::path(unzipped_dir)))
bf::remove_all(bf::path(unzipped_dir));
bf::create_directories(bf::path(unzipped_dir));
unzFile zip_file = unzOpen(zip_filename.c_str());
if (zip_file == NULL)
throw UnzipException(("Can't open file " + zip_filename).c_str());
unzGoToFirstFile(zip_file);
int has_next = UNZ_OK;
while (has_next == UNZ_OK)
{
extract_current_file(zip_file, unzipped_dir);
has_next = unzGoToNextFile(zip_file);
}
unzClose(zip_file);
}
catch (exception e)
{
bf::remove_all(bf::path(unzipped_dir));
throw e;
}
}
bool has_extension(const string& filename, const string& extension)
{
return filename.rfind(extension) == filename.size() - extension.size();
}
vector<string> get_filenames_with_extension_from_zip(const string& zip_filename, const string& extension)
{
vector<string> filenames;
unzFile zip_file = unzOpen(zip_filename.c_str());
if (zip_file == NULL)
throw UnzipException(("Can't open file " + zip_filename).c_str());
unzGoToFirstFile(zip_file);
int has_next = UNZ_OK;
while (has_next == UNZ_OK)
{
string filename = read_filename(zip_file);
if (has_extension(filename, extension))
filenames.push_back(filename);
has_next = unzGoToNextFile(zip_file);
}
unzClose(zip_file);
return filenames;
}
} // namespace foundation
|
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2017 Gleb Mishchenko, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "unzipper.h"
// appleseed.foundation headers.
#include "foundation/core/exceptions/exception.h"
#include "foundation/utility/string.h"
#include "foundation/utility/minizip/unzip.h"
// Boost headers.
#include "boost/filesystem.hpp"
// Standard headers.
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
namespace bf = boost::filesystem;
namespace foundation
{
const size_t BUFFER_SIZE = 4096;
bool is_zip_entry_directory(const string& dirname)
{
// used own implementation of is_zip_entry_directory instead of boost implementation
// because this directory is not in filesystem, but in zipfile
return dirname[dirname.size() - 1] == '/';
}
void open_current_file(unzFile& zip_file)
{
const int err = unzOpenCurrentFile(zip_file);
if (err != UNZ_OK)
throw UnzipException("Can't open file inside zip: ", err);
}
int read_chunk(unzFile& zip_file, char* buffer, const int chunk_size)
{
const int err = unzReadCurrentFile(zip_file, buffer, chunk_size);
if (err == UNZ_ERRNO)
throw UnzipException("IO error while reading from zip");
if (err < 0)
throw UnzipException("zLib error while decompressing file: ", err);
return err;
}
void close_current_file(unzFile& zip_file)
{
const int err = unzCloseCurrentFile(zip_file);
if (err == UNZ_CRCERROR)
throw UnzipException("CRC32 is not good");
}
string read_filename(unzFile& zip_file)
{
unz_file_info zip_file_info;
unzGetCurrentFileInfo(zip_file, &zip_file_info, NULL, 0, NULL, 0, NULL, 0);
vector<char> filename(zip_file_info.size_filename + 1);
unzGetCurrentFileInfo(zip_file, &zip_file_info, &filename[0], filename.size(), NULL, 0, NULL, 0);
filename[filename.size() - 1] = '\0';
const string inzip_filename(&filename[0]);
return inzip_filename;
}
string get_filepath(unzFile& zip_file, const string& unzipped_dir)
{
string filename = read_filename(zip_file);
return (bf::path(unzipped_dir) / bf::path(filename)).string();
}
void extract_current_file(unzFile& zip_file, const string& unzipped_dir)
{
const string filepath = get_filepath(zip_file, unzipped_dir);
if (is_zip_entry_directory(filepath))
{
bf::create_directories(bf::path(filepath));
return;
}
else open_current_file(zip_file);
fstream out(filepath.c_str(), ios_base::out | ios_base::binary);
char buffer[BUFFER_SIZE];
int read;
do
{
read = read_chunk(zip_file, (char*) &buffer, BUFFER_SIZE);
out.write((char*) &buffer, read);
}
while (!unzeof(zip_file));
out.close();
close_current_file(zip_file);
}
void unzip(const string& zip_filename, const string& unzipped_dir)
{
try
{
if (bf::exists(bf::path(unzipped_dir)))
bf::remove_all(bf::path(unzipped_dir));
bf::create_directories(bf::path(unzipped_dir));
unzFile zip_file = unzOpen(zip_filename.c_str());
if (zip_file == NULL)
throw UnzipException(("Can't open file " + zip_filename).c_str());
unzGoToFirstFile(zip_file);
int has_next = UNZ_OK;
while (has_next == UNZ_OK)
{
extract_current_file(zip_file, unzipped_dir);
has_next = unzGoToNextFile(zip_file);
}
unzClose(zip_file);
}
catch (exception e)
{
bf::remove_all(bf::path(unzipped_dir));
throw e;
}
}
vector<string> get_filenames_with_extension_from_zip(const string& zip_filename, const string& extension)
{
vector<string> filenames;
unzFile zip_file = unzOpen(zip_filename.c_str());
if (zip_file == NULL)
throw UnzipException(("Can't open file " + zip_filename).c_str());
unzGoToFirstFile(zip_file);
int has_next = UNZ_OK;
while (has_next == UNZ_OK)
{
string filename = read_filename(zip_file);
if (ends_with(filename, extension))
filenames.push_back(filename);
has_next = unzGoToNextFile(zip_file);
}
unzClose(zip_file);
return filenames;
}
} // namespace foundation
|
Fix bug where valid packed project doesn't open (#1306)
|
Fix bug where valid packed project doesn't open (#1306)
|
C++
|
mit
|
Aakash1312/appleseed,est77/appleseed,Vertexwahn/appleseed,dictoon/appleseed,aytekaman/appleseed,aytekaman/appleseed,dictoon/appleseed,Vertexwahn/appleseed,Biart95/appleseed,aiivashchenko/appleseed,glebmish/appleseed,luisbarrancos/appleseed,gospodnetic/appleseed,glebmish/appleseed,glebmish/appleseed,pjessesco/appleseed,aytekaman/appleseed,pjessesco/appleseed,pjessesco/appleseed,aiivashchenko/appleseed,luisbarrancos/appleseed,est77/appleseed,aytekaman/appleseed,Biart95/appleseed,pjessesco/appleseed,aiivashchenko/appleseed,appleseedhq/appleseed,gospodnetic/appleseed,dictoon/appleseed,Biart95/appleseed,Vertexwahn/appleseed,dictoon/appleseed,luisbarrancos/appleseed,est77/appleseed,aiivashchenko/appleseed,gospodnetic/appleseed,gospodnetic/appleseed,glebmish/appleseed,Aakash1312/appleseed,Aakash1312/appleseed,pjessesco/appleseed,appleseedhq/appleseed,glebmish/appleseed,aytekaman/appleseed,aiivashchenko/appleseed,est77/appleseed,luisbarrancos/appleseed,Biart95/appleseed,appleseedhq/appleseed,gospodnetic/appleseed,appleseedhq/appleseed,Aakash1312/appleseed,Biart95/appleseed,est77/appleseed,luisbarrancos/appleseed,Vertexwahn/appleseed,Vertexwahn/appleseed,Aakash1312/appleseed,appleseedhq/appleseed,dictoon/appleseed
|
9e8242b3eb827eca2f0d6ffb2258f0c5bddb4426
|
SDLVersion/CSDLRenderer.cpp
|
SDLVersion/CSDLRenderer.cpp
|
#include <functional>
#include "Common.h"
#include "CGame.h"
#include "CRenderer.h"
#include <SDL/SDL.h>
#include <SDL/SDL_mixer.h>
#include <iostream>
namespace odb {
SDL_Surface *video;
CRenderer::CRenderer(CControlCallback keyPressedCallback, CControlCallback keyReleasedCallback) :
mOnKeyPressedCallback(keyPressedCallback), mOnKeyReleasedCallback(keyReleasedCallback) {
SDL_Init(SDL_INIT_EVERYTHING);
video = SDL_SetVideoMode(640, 480, 0, 0);
}
void CRenderer::sleep(long ms) {
SDL_Delay(33);
}
void CRenderer::handleSystemEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
#ifndef __EMSCRIPTEN__
exit(0);
#endif
}
if (event.type == SDL_KEYUP) {
switch (event.key.keysym.sym) {
case SDLK_q:
#ifndef __EMSCRIPTEN__
exit(0);
#endif
case SDLK_LEFT:
mOnKeyReleasedCallback(ECommand::kLeft);
break;
case SDLK_RIGHT:
mOnKeyReleasedCallback(ECommand::kRight);
break;
case SDLK_UP:
mOnKeyReleasedCallback(ECommand::kUp);
break;
case SDLK_DOWN:
mOnKeyReleasedCallback(ECommand::kDown);
break;
case SDLK_SPACE:
mOnKeyReleasedCallback(ECommand::kFire1);
break;
default:
break;
}
}
if (event.type == SDL_KEYDOWN) {
switch (event.key.keysym.sym) {
case SDLK_LEFT:
mOnKeyPressedCallback(ECommand::kLeft);
break;
case SDLK_RIGHT:
mOnKeyPressedCallback(ECommand::kRight);
break;
case SDLK_UP:
mOnKeyPressedCallback(ECommand::kUp);
break;
case SDLK_DOWN:
mOnKeyPressedCallback(ECommand::kDown);
break;
case SDLK_SPACE:
mOnKeyPressedCallback(ECommand::kFire1);
break;
default:
break;
}
}
}
}
struct vec3 {
vec3(float aX, float aY, float aZ) : x(aX), y(aY), z(aZ) {
}
float x = 0;
float y = 0;
float z = 0;
};
struct vec2 {
vec2(float aX, float aY) : x(aX), y(aY) {
}
float x = 0;
float y = 0;
};
vec2 project(vec3 v) {
float xz = v.x / (1.0f - v.z);
float yz = v.y / (1.0f - v.z);
vec2 v2(320 + (xz * 640), 240 - (yz * 480));
return v2;
}
void CRenderer::render(const CGame &game, long ms) {
SDL_Rect rect;
switch (game.gameState) {
case CGame::EGameState::kTitleScreen:
case CGame::EGameState::kVictory:
case CGame::EGameState::kGameOver:
case CGame::EGameState::kGame:
rect = {0, 0, 640, 241};
SDL_FillRect(video, &rect, SDL_MapRGB(video->format, 0, 0, 255));
int delta = 0;
char shape = game.track[game.elementIndex];
if (shape == ')') {
delta = -1;
}
if (shape == '(') {
delta = 1;
}
int distance = 0;
if (game.distanceToNextElement > 50) {
distance = (100 - game.distanceToNextElement);
} else {
distance = (game.distanceToNextElement);
}
int perspectiveFactor = 0;
int height = 240;
for (int y = height; y > 0; y--) {
perspectiveFactor = y;
int curveFactor = ((height * distance * delta) / y);
int cameraFactor = -((y * game.x) / height);
int roadX = curveFactor + 320 - (perspectiveFactor);
int roadDeltaX = (perspectiveFactor * 2);
int shade = (y / 4);
rect = {0, y, 640, 1};
SDL_FillRect(video, &rect, SDL_MapRGB(video->format, 0, 0, 128 + shade / 2));
rect = {0, height + y, 640, 1};
SDL_FillRect(video, &rect, SDL_MapRGB(video->format, 0, 128 + shade / 2, 0));
rect = {roadX, height + y, roadDeltaX, 1};
SDL_FillRect(video, &rect, SDL_MapRGB(video->format, 64 + shade, 64 + shade, 64 + shade));
float curve = (distance / 20.0f) * delta * y * y / 50.0f;
auto v0 = project(vec3(-0.4 + curve, 0.5f, -y));
rect = {(int) v0.x, (int) v0.y, 3, 3};
SDL_FillRect(video, &rect, SDL_MapRGB(video->format, 255, 255, 255));
auto v1 = project(vec3(0.4 + curve, 0.5f, -y));
rect = {(int) v1.x, (int) v1.y, 5, 5};
SDL_FillRect(video, &rect, SDL_MapRGB(video->format, 255, 255, 0));
auto v2 = project(vec3(curve, -0.5f, -y));
rect = {(int) v2.x, (int) v2.y, 5, 5};
SDL_FillRect(video, &rect, SDL_MapRGB(video->format, 255, 0, 0));
}
rect = SDL_Rect{0, 0, 80, 40};
rect.x = 320 + (game.x);
rect.y = 440;
SDL_FillRect(video, &rect, SDL_MapRGB(video->format, 255, 0, 0));
SDL_Flip(video);
}
}
}
|
#include <functional>
#include "Common.h"
#include "CGame.h"
#include "CRenderer.h"
#include <SDL/SDL.h>
#include <SDL/SDL_mixer.h>
#include <iostream>
namespace odb {
SDL_Surface *video;
CRenderer::CRenderer(CControlCallback keyPressedCallback, CControlCallback keyReleasedCallback) :
mOnKeyPressedCallback(keyPressedCallback), mOnKeyReleasedCallback(keyReleasedCallback) {
SDL_Init(SDL_INIT_EVERYTHING);
video = SDL_SetVideoMode(640, 480, 0, 0);
}
void CRenderer::sleep(long ms) {
SDL_Delay(33);
}
void CRenderer::handleSystemEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
#ifndef __EMSCRIPTEN__
exit(0);
#endif
}
if (event.type == SDL_KEYUP) {
switch (event.key.keysym.sym) {
case SDLK_q:
#ifndef __EMSCRIPTEN__
exit(0);
#endif
case SDLK_LEFT:
mOnKeyReleasedCallback(ECommand::kLeft);
break;
case SDLK_RIGHT:
mOnKeyReleasedCallback(ECommand::kRight);
break;
case SDLK_UP:
mOnKeyReleasedCallback(ECommand::kUp);
break;
case SDLK_DOWN:
mOnKeyReleasedCallback(ECommand::kDown);
break;
case SDLK_SPACE:
mOnKeyReleasedCallback(ECommand::kFire1);
break;
default:
break;
}
}
if (event.type == SDL_KEYDOWN) {
switch (event.key.keysym.sym) {
case SDLK_LEFT:
mOnKeyPressedCallback(ECommand::kLeft);
break;
case SDLK_RIGHT:
mOnKeyPressedCallback(ECommand::kRight);
break;
case SDLK_UP:
mOnKeyPressedCallback(ECommand::kUp);
break;
case SDLK_DOWN:
mOnKeyPressedCallback(ECommand::kDown);
break;
case SDLK_SPACE:
mOnKeyPressedCallback(ECommand::kFire1);
break;
default:
break;
}
}
}
}
struct vec3 {
vec3(float aX, float aY, float aZ) : x(aX), y(aY), z(aZ) {
}
float x = 0;
float y = 0;
float z = 0;
};
struct vec2 {
vec2(float aX, float aY) : x(aX), y(aY) {
}
float x = 0;
float y = 0;
};
vec2 project(vec3 v) {
float xz = v.x / (1.0f - v.z);
float yz = v.y / (1.0f - v.z);
vec2 v2(320 + (xz * 640), 240 - (yz * 480));
return v2;
}
void CRenderer::render(const CGame &game, long ms) {
SDL_Rect rect;
switch (game.gameState) {
case CGame::EGameState::kTitleScreen:
case CGame::EGameState::kVictory:
case CGame::EGameState::kGameOver:
case CGame::EGameState::kGame:
rect = {0, 0, 640, 241};
SDL_FillRect(video, &rect, SDL_MapRGB(video->format, 0, 0, 255));
int delta = 0;
char shape = game.track[game.elementIndex];
if (shape == ')') {
delta = -1;
}
if (shape == '(') {
delta = 1;
}
int distance = 0;
if (game.distanceToNextElement > 50) {
distance = (100 - game.distanceToNextElement);
} else {
distance = (game.distanceToNextElement);
}
int perspectiveFactor = 0;
int height = 240;
for (int y = height; y > 0; y--) {
perspectiveFactor = y;
int curveFactor = ((height * distance * delta) / y);
int cameraFactor = -((y * game.x) / height);
int roadX = curveFactor + 320 - (perspectiveFactor);
int roadDeltaX = (perspectiveFactor * 2);
int shade = (y / 4);
rect = {0, y, 640, 1};
SDL_FillRect(video, &rect, SDL_MapRGB(video->format, 0, 0, 128 + shade / 2));
rect = {0, height + y, 640, 1};
SDL_FillRect(video, &rect, SDL_MapRGB(video->format, 0, 128 + shade / 2, 0));
rect = {roadX, height + y, roadDeltaX, 1};
SDL_FillRect(video, &rect, SDL_MapRGB(video->format, 64 + shade, 64 + shade, 64 + shade));
float curve = (distance / 20.0f) * delta * y * y / 50.0f;
auto v0 = project(vec3(-0.4 + curve, 0.5f, -y));
rect = {(int) v0.x, (int) v0.y, 3, 3};
SDL_FillRect(video, &rect, SDL_MapRGB(video->format, 255, 255, 255));
auto v1 = project(vec3(0.4 + curve, 0.5f, -y));
rect = {(int) v1.x, (int) v1.y, 5, 5};
SDL_FillRect(video, &rect, SDL_MapRGB(video->format, 255, 255, 0));
auto v2 = project(vec3(curve, -0.5f, -y));
rect = {(int) v2.x, (int) v2.y, 5, 5};
SDL_FillRect(video, &rect, SDL_MapRGB(video->format, 255, 0, 0));
}
rect = SDL_Rect{0, 0, 80, 40};
rect.x = 320 + (game.x);
rect.y = 440;
SDL_FillRect(video, &rect, SDL_MapRGB(video->format, 255, 0, 0));
SDL_Flip(video);
}
}
void CRenderer::fill(float x0, float x1, float y0, float x2, float x3, float y1, int count) {
float fromY = std::min( y0, y1 );
float toY = std::max( y0, y1 );
SDL_Rect rect;
float deltaY = toY - fromY;
float ratiox0x2 = 1.0f;
float ratiox1x3 = 1.0f;
if ( toY - fromY > 0.0f ) {
ratiox0x2 = ( x0 - x2 ) / deltaY;
ratiox1x3 = ( x1 - x3 ) / deltaY;
}
float x = x0;
float fx = x1;
for ( int line = toY; line >= fromY; line--) {
rect = { x, line, ( fx - x), 1};
x -= ratiox0x2;
fx -= ratiox1x3;
int shade = 255 * ( count + 10 ) / 20.0f;
SDL_FillRect(video, &rect, SDL_MapRGB(video->format, shade, shade, shade ));
}
}
}
|
Add polygon filling code
|
Add polygon filling code
|
C++
|
bsd-2-clause
|
TheFakeMontyOnTheRun/run-the-world-LD38,TheFakeMontyOnTheRun/run-the-world-LD38,TheFakeMontyOnTheRun/run-the-world-LD38
|
b13eacf6e6814b87edde2f16bf77f94025f6de30
|
src/ngraph/op/quantized_convolution.hpp
|
src/ngraph/op/quantized_convolution.hpp
|
//*****************************************************************************
// Copyright 2018-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#pragma once
#include "ngraph/coordinate_diff.hpp"
#include "ngraph/op/op.hpp"
namespace ngraph
{
namespace op
{
class QuantizedConvolution : public Op
{
public:
/// \brief Constructs a quantized convolution operation.
///
/// \param data_batch The node producing the input data batch tensor.
/// \param filters The node producing the filters tensor.
/// \param window_movement_strides The window movement strides.
/// \param window_dilation_strides The window dilation strides.
/// \param padding_below The padding-below sizes.
/// \param padding_above The padding-above sizes.
/// \param data_dilation_strides The data dilation strides.
/// \param input_scale Scale to transform the input
/// \param input_zero_point Zero point used for mapping
/// \param filter_scale Scale to transform the filters
/// \param filter_zero_point Zero point used for mapping
/// \param output_scale Scale to transform the output
/// \param output_zero_point Zero point used for mapping
/// \param output_type Output element type
/// \param input_axes Input axes set for channel wise quantization
/// \param filter_axes Filter axes set for channel wise quantization
/// \param output_axes Output axes set for channel wise quantization
QuantizedConvolution(const std::shared_ptr<Node>& input,
const std::shared_ptr<Node>& filters,
const Strides& window_movement_strides,
const Strides& window_dilation_strides,
const CoordinateDiff& padding_below,
const CoordinateDiff& padding_above,
const Strides& data_dilation_strides,
const std::shared_ptr<Node>& input_scale,
const std::shared_ptr<Node>& input_zero_point,
const std::shared_ptr<Node>& filter_scale,
const std::shared_ptr<Node>& filter_zero_point,
const std::shared_ptr<Node>& output_scale,
const std::shared_ptr<Node>& output_zero_point,
const ngraph::element::Type& output_type,
const ngraph::AxisSet& input_axes,
const ngraph::AxisSet& filter_axes,
const ngraph::AxisSet& output_axes);
const Strides& get_window_movement_strides() const { return m_window_movement_strides; }
const Strides& get_window_dilation_strides() const { return m_window_dilation_strides; }
const CoordinateDiff& get_padding_below() const { return m_padding_below; }
const CoordinateDiff& get_padding_above() const { return m_padding_above; }
const Strides& get_data_dilation_strides() const { return m_data_dilation_strides; }
std::shared_ptr<Node> get_filters() { return get_argument(1); }
std::shared_ptr<Node> get_data_batch() { return get_argument(0); }
const ngraph::element::Type& get_output_type() const { return m_output_type; }
const ngraph::AxisSet& get_input_axes() const { return m_input_axes; }
const ngraph::AxisSet& get_filter_axes() const { return m_filter_axes; }
const ngraph::AxisSet& get_output_axes() const { return m_output_axes; }
void validate_and_infer_types() override;
virtual std::shared_ptr<Node>
copy_with_new_args(const NodeVector& new_args) const override;
virtual void generate_adjoints(autodiff::Adjoints& adjoints,
const NodeVector& deltas) override;
protected:
Strides m_window_movement_strides;
Strides m_window_dilation_strides;
CoordinateDiff m_padding_below;
CoordinateDiff m_padding_above;
Strides m_data_dilation_strides;
ngraph::element::Type m_output_type;
ngraph::AxisSet m_input_axes;
ngraph::AxisSet m_filter_axes;
ngraph::AxisSet m_output_axes;
};
}
}
|
//*****************************************************************************
// Copyright 2018-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#pragma once
#include "ngraph/coordinate_diff.hpp"
#include "ngraph/op/op.hpp"
namespace ngraph
{
namespace op
{
class QuantizedConvolution : public Op
{
public:
/// \brief Constructs a quantized convolution operation.
///
/// \param input The node producing the input data batch tensor.
/// \param filters The node producing the filters tensor.
/// \param window_movement_strides The window movement strides.
/// \param window_dilation_strides The window dilation strides.
/// \param padding_below The padding-below sizes.
/// \param padding_above The padding-above sizes.
/// \param data_dilation_strides The data dilation strides.
/// \param input_scale Scale to transform the input
/// \param input_zero_point Zero point used for mapping
/// \param filter_scale Scale to transform the filters
/// \param filter_zero_point Zero point used for mapping
/// \param output_scale Scale to transform the output
/// \param output_zero_point Zero point used for mapping
/// \param output_type Output element type
/// \param input_axes Input axes set for channel wise quantization
/// \param filter_axes Filter axes set for channel wise quantization
/// \param output_axes Output axes set for channel wise quantization
QuantizedConvolution(const std::shared_ptr<Node>& input,
const std::shared_ptr<Node>& filters,
const Strides& window_movement_strides,
const Strides& window_dilation_strides,
const CoordinateDiff& padding_below,
const CoordinateDiff& padding_above,
const Strides& data_dilation_strides,
const std::shared_ptr<Node>& input_scale,
const std::shared_ptr<Node>& input_zero_point,
const std::shared_ptr<Node>& filter_scale,
const std::shared_ptr<Node>& filter_zero_point,
const std::shared_ptr<Node>& output_scale,
const std::shared_ptr<Node>& output_zero_point,
const ngraph::element::Type& output_type,
const ngraph::AxisSet& input_axes,
const ngraph::AxisSet& filter_axes,
const ngraph::AxisSet& output_axes);
const Strides& get_window_movement_strides() const { return m_window_movement_strides; }
const Strides& get_window_dilation_strides() const { return m_window_dilation_strides; }
const CoordinateDiff& get_padding_below() const { return m_padding_below; }
const CoordinateDiff& get_padding_above() const { return m_padding_above; }
const Strides& get_data_dilation_strides() const { return m_data_dilation_strides; }
std::shared_ptr<Node> get_filters() { return get_argument(1); }
std::shared_ptr<Node> get_data_batch() { return get_argument(0); }
const ngraph::element::Type& get_output_type() const { return m_output_type; }
const ngraph::AxisSet& get_input_axes() const { return m_input_axes; }
const ngraph::AxisSet& get_filter_axes() const { return m_filter_axes; }
const ngraph::AxisSet& get_output_axes() const { return m_output_axes; }
void validate_and_infer_types() override;
virtual std::shared_ptr<Node>
copy_with_new_args(const NodeVector& new_args) const override;
virtual void generate_adjoints(autodiff::Adjoints& adjoints,
const NodeVector& deltas) override;
protected:
Strides m_window_movement_strides;
Strides m_window_dilation_strides;
CoordinateDiff m_padding_below;
CoordinateDiff m_padding_above;
Strides m_data_dilation_strides;
ngraph::element::Type m_output_type;
ngraph::AxisSet m_input_axes;
ngraph::AxisSet m_filter_axes;
ngraph::AxisSet m_output_axes;
};
}
}
|
Fix comment
|
Fix comment
|
C++
|
apache-2.0
|
NervanaSystems/ngraph,NervanaSystems/ngraph,NervanaSystems/ngraph,NervanaSystems/ngraph
|
c0dccd6f57da1f9a832aea1402c24c3c33c0da98
|
modules/gui/qt4/components/epg/EPGWidget.cpp
|
modules/gui/qt4/components/epg/EPGWidget.cpp
|
/*****************************************************************************
* EPGWidget.h : EPGWidget
****************************************************************************
* Copyright © 2009-2010 VideoLAN
* $Id$
*
* Authors: Ludovic Fauvet <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include "EPGWidget.hpp"
#include <QVBoxLayout>
#include <QScrollBar>
#include <QDebug>
#include <QLabel>
#include "qt4.hpp"
EPGWidget::EPGWidget( QWidget *parent ) : QWidget( parent )
{
m_rulerWidget = new EPGRuler( this );
m_epgView = new EPGView( this );
m_channelsWidget = new EPGChannels( this, m_epgView );
m_channelsWidget->setMinimumWidth( 100 );
m_epgView->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding );
setZoom( 1 );
QGridLayout* layout = new QGridLayout( this );
layout->addWidget( m_rulerWidget, 0, 1 );
layout->addWidget( m_channelsWidget, 1, 0 );
layout->addWidget( m_epgView, 1, 1 );
layout->setSpacing( 0 );
setLayout( layout );
connect( m_epgView, SIGNAL( startTimeChanged(QDateTime) ),
m_rulerWidget, SLOT( setStartTime(QDateTime) ) );
connect( m_epgView, SIGNAL( durationChanged(int) ),
m_rulerWidget, SLOT( setDuration(int) ) );
connect( m_epgView->horizontalScrollBar(), SIGNAL( valueChanged(int) ),
m_rulerWidget, SLOT( setOffset(int) ) );
connect( m_epgView->verticalScrollBar(), SIGNAL( valueChanged(int) ),
m_channelsWidget, SLOT( setOffset(int) ) );
connect( m_epgView, SIGNAL( eventFocusedChanged(EPGEvent*)),
this, SIGNAL(itemSelectionChanged(EPGEvent*)) );
}
void EPGWidget::setZoom( int level )
{
double scale = (double)level / 20;
m_epgView->setScale( scale );
m_rulerWidget->setScale( scale );
}
void EPGWidget::updateEPG( vlc_epg_t **pp_epg, int i_epg )
{
for ( int i = 0; i < i_epg; ++i )
{
vlc_epg_t *p_epg = pp_epg[i];
QString channelName = qfu( p_epg->psz_name );
for ( int j = 0; j < p_epg->i_event; ++j )
{
vlc_epg_event_t *p_event = p_epg->pp_event[j];
QString eventName = qfu( p_event->psz_name );
QDateTime eventStart = QDateTime::fromTime_t( p_event->i_start );
QList<EPGEvent*> events = m_events.values( channelName );
EPGEvent *item = new EPGEvent( eventName );
item->description = qfu( p_event->psz_description );
item->shortDescription = qfu( p_event->psz_short_description );
item->start = eventStart;
item->duration = p_event->i_duration;
item->channelName = channelName;
item->current = ( p_epg->p_current == p_event ) ? true : false;
bool alreadyIn = false;
for ( int k = 0; k < events.count(); ++k )
{
if ( *events.at( k ) == *item )
{
alreadyIn = true;
events.at( k )->updated = true;
break;
}
}
if ( !alreadyIn )
{
m_events.insert( channelName, item );
m_epgView->addEvent( item );
}
else
delete item;
}
}
// Remove old items
QMap<QString, EPGEvent*>::iterator i = m_events.begin();
while ( i != m_events.end() )
{
EPGEvent* item = i.value();
if ( !item->updated )
{
m_epgView->delEvent( item );
delete item;
i = m_events.erase( i );
}
else
item->updated = false;
++i;
}
// Update the global duration and start time.
m_epgView->updateDuration();
m_epgView->updateStartTime();
}
|
/*****************************************************************************
* EPGWidget.h : EPGWidget
****************************************************************************
* Copyright © 2009-2010 VideoLAN
* $Id$
*
* Authors: Ludovic Fauvet <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include "EPGWidget.hpp"
#include <QVBoxLayout>
#include <QScrollBar>
#include <QDebug>
#include <QLabel>
#include "qt4.hpp"
EPGWidget::EPGWidget( QWidget *parent ) : QWidget( parent )
{
m_rulerWidget = new EPGRuler( this );
m_epgView = new EPGView( this );
m_channelsWidget = new EPGChannels( this, m_epgView );
m_channelsWidget->setMinimumWidth( 100 );
m_epgView->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding );
setZoom( 1 );
QGridLayout* layout = new QGridLayout( this );
layout->addWidget( m_rulerWidget, 0, 1 );
layout->addWidget( m_channelsWidget, 1, 0 );
layout->addWidget( m_epgView, 1, 1 );
layout->setSpacing( 0 );
setLayout( layout );
connect( m_epgView, SIGNAL( startTimeChanged(QDateTime) ),
m_rulerWidget, SLOT( setStartTime(QDateTime) ) );
connect( m_epgView, SIGNAL( durationChanged(int) ),
m_rulerWidget, SLOT( setDuration(int) ) );
connect( m_epgView->horizontalScrollBar(), SIGNAL( valueChanged(int) ),
m_rulerWidget, SLOT( setOffset(int) ) );
connect( m_epgView->verticalScrollBar(), SIGNAL( valueChanged(int) ),
m_channelsWidget, SLOT( setOffset(int) ) );
connect( m_epgView, SIGNAL( eventFocusedChanged(EPGEvent*)),
this, SIGNAL(itemSelectionChanged(EPGEvent*)) );
}
void EPGWidget::setZoom( int level )
{
double scale = (double)level / 20;
m_epgView->setScale( scale );
m_rulerWidget->setScale( scale );
}
void EPGWidget::updateEPG( vlc_epg_t **pp_epg, int i_epg )
{
for ( int i = 0; i < i_epg; ++i )
{
vlc_epg_t *p_epg = pp_epg[i];
QString channelName = qfu( p_epg->psz_name );
for ( int j = 0; j < p_epg->i_event; ++j )
{
vlc_epg_event_t *p_event = p_epg->pp_event[j];
QString eventName = qfu( p_event->psz_name );
QDateTime eventStart = QDateTime::fromTime_t( p_event->i_start );
QList<EPGEvent*> events = m_events.values( channelName );
EPGEvent *item = new EPGEvent( eventName );
item->description = qfu( p_event->psz_description );
item->shortDescription = qfu( p_event->psz_short_description );
item->start = eventStart;
item->duration = p_event->i_duration;
item->channelName = channelName;
item->current = ( p_epg->p_current == p_event ) ? true : false;
bool alreadyIn = false;
for ( int k = 0; k < events.count(); ++k )
{
if ( *events.at( k ) == *item )
{
alreadyIn = true;
events.at( k )->updated = true;
break;
}
}
if ( !alreadyIn )
{
m_events.insert( channelName, item );
m_epgView->addEvent( item );
}
else
delete item;
}
}
// Remove old items
QMultiMap<QString, EPGEvent*>::iterator i = m_events.begin();
while ( i != m_events.end() )
{
EPGEvent* item = i.value();
if ( !item->updated )
{
m_epgView->delEvent( item );
delete item;
i--;
m_events.erase( i + 1 );
}
else
item->updated = false;
++i;
}
// Update the global duration and start time.
m_epgView->updateDuration();
m_epgView->updateStartTime();
// Udate the channel list.
m_channelsWidget->update();
}
|
Fix event deletion.
|
Qt/EPG: Fix event deletion.
|
C++
|
lgpl-2.1
|
shyamalschandra/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,xkfz007/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,xkfz007/vlc,vlc-mirror/vlc,krichter722/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,vlc-mirror/vlc,vlc-mirror/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,xkfz007/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,xkfz007/vlc,jomanmuk/vlc-2.1,krichter722/vlc,xkfz007/vlc,krichter722/vlc,vlc-mirror/vlc,krichter722/vlc,vlc-mirror/vlc,krichter722/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,shyamalschandra/vlc,krichter722/vlc,vlc-mirror/vlc,xkfz007/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,krichter722/vlc,xkfz007/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,shyamalschandra/vlc
|
29b544d83cc1df53b666bfddfa2a44d3bdf05c72
|
modules/androidcamera/src/camera_activity.cpp
|
modules/androidcamera/src/camera_activity.cpp
|
#include <dlfcn.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <android/log.h>
#include <cctype>
#include <string>
#include <vector>
#include <algorithm>
#include <opencv2/core/version.hpp>
#include "camera_activity.hpp"
#include "camera_wrapper.h"
#include "EngineCommon.h"
#undef LOG_TAG
#undef LOGE
#undef LOGD
#undef LOGI
#define LOG_TAG "OpenCV::camera"
#define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__))
#define LOGD(...) ((void)__android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__))
#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__))
///////
// Debug
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
class CameraWrapperConnector
{
public:
static CameraActivity::ErrorCode connect(int cameraId, CameraActivity* pCameraActivity, void** camera);
static CameraActivity::ErrorCode disconnect(void** camera);
static CameraActivity::ErrorCode setProperty(void* camera, int propIdx, double value);
static CameraActivity::ErrorCode getProperty(void* camera, int propIdx, double* value);
static CameraActivity::ErrorCode applyProperties(void** ppcamera);
static void setPathLibFolder(const std::string& path);
private:
static std::string pathLibFolder;
static bool isConnectedToLib;
static std::string getPathLibFolder();
static std::string getDefaultPathLibFolder();
static CameraActivity::ErrorCode connectToLib();
static CameraActivity::ErrorCode getSymbolFromLib(void * libHandle, const char* symbolName, void** ppSymbol);
static void fillListWrapperLibs(const std::string& folderPath, std::vector<std::string>& listLibs);
static InitCameraConnectC pInitCameraC;
static CloseCameraConnectC pCloseCameraC;
static GetCameraPropertyC pGetPropertyC;
static SetCameraPropertyC pSetPropertyC;
static ApplyCameraPropertiesC pApplyPropertiesC;
friend bool nextFrame(void* buffer, size_t bufferSize, void* userData);
};
std::string CameraWrapperConnector::pathLibFolder;
bool CameraWrapperConnector::isConnectedToLib = false;
InitCameraConnectC CameraWrapperConnector::pInitCameraC = 0;
CloseCameraConnectC CameraWrapperConnector::pCloseCameraC = 0;
GetCameraPropertyC CameraWrapperConnector::pGetPropertyC = 0;
SetCameraPropertyC CameraWrapperConnector::pSetPropertyC = 0;
ApplyCameraPropertiesC CameraWrapperConnector::pApplyPropertiesC = 0;
#define INIT_CAMERA_SYMBOL_NAME "initCameraConnectC"
#define CLOSE_CAMERA_SYMBOL_NAME "closeCameraConnectC"
#define SET_CAMERA_PROPERTY_SYMBOL_NAME "setCameraPropertyC"
#define GET_CAMERA_PROPERTY_SYMBOL_NAME "getCameraPropertyC"
#define APPLY_CAMERA_PROPERTIES_SYMBOL_NAME "applyCameraPropertiesC"
#define PREFIX_CAMERA_WRAPPER_LIB "libnative_camera"
bool nextFrame(void* buffer, size_t bufferSize, void* userData)
{
if (userData == NULL)
return true;
return ((CameraActivity*)userData)->onFrameBuffer(buffer, bufferSize);
}
CameraActivity::ErrorCode CameraWrapperConnector::connect(int cameraId, CameraActivity* pCameraActivity, void** camera)
{
if (pCameraActivity == NULL)
{
LOGE("CameraWrapperConnector::connect error: wrong pointer to CameraActivity object");
return CameraActivity::ERROR_WRONG_POINTER_CAMERA_WRAPPER;
}
CameraActivity::ErrorCode errcode=connectToLib();
if (errcode) return errcode;
void* cmr = (*pInitCameraC)((void*)nextFrame, cameraId, (void*)pCameraActivity);
if (!cmr)
{
LOGE("CameraWrapperConnector::connectWrapper ERROR: the initializing function returned false");
return CameraActivity::ERROR_CANNOT_INITIALIZE_CONNECTION;
}
*camera = cmr;
return CameraActivity::NO_ERROR;
}
CameraActivity::ErrorCode CameraWrapperConnector::disconnect(void** camera)
{
if (camera == NULL || *camera == NULL)
{
LOGE("CameraWrapperConnector::disconnect error: wrong pointer to camera object");
return CameraActivity::ERROR_WRONG_POINTER_CAMERA_WRAPPER;
}
CameraActivity::ErrorCode errcode=connectToLib();
if (errcode) return errcode;
(*pCloseCameraC)(camera);
return CameraActivity::NO_ERROR;
}
CameraActivity::ErrorCode CameraWrapperConnector::setProperty(void* camera, int propIdx, double value)
{
if (camera == NULL)
{
LOGE("CameraWrapperConnector::setProperty error: wrong pointer to camera object");
return CameraActivity::ERROR_WRONG_POINTER_CAMERA_WRAPPER;
}
(*pSetPropertyC)(camera, propIdx, value);
return CameraActivity::NO_ERROR;
}
CameraActivity::ErrorCode CameraWrapperConnector::getProperty(void* camera, int propIdx, double* value)
{
if (camera == NULL)
{
LOGE("CameraWrapperConnector::getProperty error: wrong pointer to camera object");
return CameraActivity::ERROR_WRONG_POINTER_CAMERA_WRAPPER;
}
LOGE("calling (*pGetPropertyC)(%p, %d)", camera, propIdx);
*value = (*pGetPropertyC)(camera, propIdx);
return CameraActivity::NO_ERROR;
}
CameraActivity::ErrorCode CameraWrapperConnector::applyProperties(void** ppcamera)
{
if ((ppcamera == NULL) || (*ppcamera == NULL))
{
LOGE("CameraWrapperConnector::applyProperties error: wrong pointer to camera object");
return CameraActivity::ERROR_WRONG_POINTER_CAMERA_WRAPPER;
}
(*pApplyPropertiesC)(ppcamera);
return CameraActivity::NO_ERROR;
}
CameraActivity::ErrorCode CameraWrapperConnector::connectToLib()
{
if (isConnectedToLib) {
return CameraActivity::NO_ERROR;
}
dlerror();
std::string folderPath = getPathLibFolder();
if (folderPath.empty())
{
LOGD("Trying to find native camera in default OpenCV packages");
folderPath = getDefaultPathLibFolder();
}
LOGD("CameraWrapperConnector::connectToLib: folderPath=%s", folderPath.c_str());
std::vector<std::string> listLibs;
fillListWrapperLibs(folderPath, listLibs);
std::sort(listLibs.begin(), listLibs.end(), std::greater<std::string>());
void * libHandle=0;
std::string cur_path;
for(size_t i = 0; i < listLibs.size(); i++) {
cur_path=folderPath + listLibs[i];
LOGD("try to load library '%s'", listLibs[i].c_str());
libHandle=dlopen(cur_path.c_str(), RTLD_LAZY);
if (libHandle) {
LOGD("Loaded library '%s'", cur_path.c_str());
break;
} else {
LOGD("CameraWrapperConnector::connectToLib ERROR: cannot dlopen camera wrapper library %s, dlerror=\"%s\"",
cur_path.c_str(), dlerror());
}
}
if (!libHandle) {
LOGE("CameraWrapperConnector::connectToLib ERROR: cannot dlopen camera wrapper library");
return CameraActivity::ERROR_CANNOT_OPEN_CAMERA_WRAPPER_LIB;
}
InitCameraConnectC pInit_C;
CloseCameraConnectC pClose_C;
GetCameraPropertyC pGetProp_C;
SetCameraPropertyC pSetProp_C;
ApplyCameraPropertiesC pApplyProp_C;
CameraActivity::ErrorCode res;
res = getSymbolFromLib(libHandle, (const char*)INIT_CAMERA_SYMBOL_NAME, (void**)(&pInit_C));
if (res) return res;
res = getSymbolFromLib(libHandle, CLOSE_CAMERA_SYMBOL_NAME, (void**)(&pClose_C));
if (res) return res;
res = getSymbolFromLib(libHandle, GET_CAMERA_PROPERTY_SYMBOL_NAME, (void**)(&pGetProp_C));
if (res) return res;
res = getSymbolFromLib(libHandle, SET_CAMERA_PROPERTY_SYMBOL_NAME, (void**)(&pSetProp_C));
if (res) return res;
res = getSymbolFromLib(libHandle, APPLY_CAMERA_PROPERTIES_SYMBOL_NAME, (void**)(&pApplyProp_C));
if (res) return res;
pInitCameraC = pInit_C;
pCloseCameraC = pClose_C;
pGetPropertyC = pGetProp_C;
pSetPropertyC = pSetProp_C;
pApplyPropertiesC = pApplyProp_C;
isConnectedToLib=true;
return CameraActivity::NO_ERROR;
}
CameraActivity::ErrorCode CameraWrapperConnector::getSymbolFromLib(void* libHandle, const char* symbolName, void** ppSymbol)
{
dlerror();
*(void **) (ppSymbol)=dlsym(libHandle, symbolName);
const char* error_dlsym_init=dlerror();
if (error_dlsym_init) {
LOGE("CameraWrapperConnector::getSymbolFromLib ERROR: cannot get symbol of the function '%s' from the camera wrapper library, dlerror=\"%s\"",
symbolName, error_dlsym_init);
return CameraActivity::ERROR_CANNOT_GET_FUNCTION_FROM_CAMERA_WRAPPER_LIB;
}
return CameraActivity::NO_ERROR;
}
void CameraWrapperConnector::fillListWrapperLibs(const std::string& folderPath, std::vector<std::string>& listLibs)
{
DIR *dp;
struct dirent *ep;
dp = opendir (folderPath.c_str());
if (dp != NULL)
{
while ((ep = readdir (dp))) {
const char* cur_name=ep->d_name;
if (strstr(cur_name, PREFIX_CAMERA_WRAPPER_LIB)) {
listLibs.push_back(cur_name);
LOGE("||%s", cur_name);
}
}
(void) closedir (dp);
}
}
std::string CameraWrapperConnector::getDefaultPathLibFolder()
{
#define BIN_PACKAGE_NAME(x) "org.opencv.lib_v" CVAUX_STR(CV_VERSION_EPOCH) CVAUX_STR(CV_VERSION_MAJOR) "_" x
const char* const packageList[] = {BIN_PACKAGE_NAME("armv7a"), OPENCV_ENGINE_PACKAGE};
for (size_t i = 0; i < sizeof(packageList)/sizeof(packageList[0]); i++)
{
char path[128];
sprintf(path, "/data/data/%s/lib/", packageList[i]);
LOGD("Trying package \"%s\" (\"%s\")", packageList[i], path);
DIR* dir = opendir(path);
if (!dir)
{
LOGD("Package not found");
continue;
}
else
{
closedir(dir);
return path;
}
}
return std::string();
}
std::string CameraWrapperConnector::getPathLibFolder()
{
if (!pathLibFolder.empty())
return pathLibFolder;
Dl_info dl_info;
if(0 != dladdr((void *)nextFrame, &dl_info))
{
LOGD("Library name: %s", dl_info.dli_fname);
LOGD("Library base address: %p", dl_info.dli_fbase);
const char* libName=dl_info.dli_fname;
while( ((*libName)=='/') || ((*libName)=='.') )
libName++;
char lineBuf[2048];
FILE* file = fopen("/proc/self/smaps", "rt");
if(file)
{
while (fgets(lineBuf, sizeof lineBuf, file) != NULL)
{
//verify that line ends with library name
int lineLength = strlen(lineBuf);
int libNameLength = strlen(libName);
//trim end
for(int i = lineLength - 1; i >= 0 && isspace(lineBuf[i]); --i)
{
lineBuf[i] = 0;
--lineLength;
}
if (0 != strncmp(lineBuf + lineLength - libNameLength, libName, libNameLength))
{
//the line does not contain the library name
continue;
}
//extract path from smaps line
char* pathBegin = strchr(lineBuf, '/');
if (0 == pathBegin)
{
LOGE("Strange error: could not find path beginning in lin \"%s\"", lineBuf);
continue;
}
char* pathEnd = strrchr(pathBegin, '/');
pathEnd[1] = 0;
LOGD("Libraries folder found: %s", pathBegin);
fclose(file);
return pathBegin;
}
fclose(file);
LOGE("Could not find library path");
}
else
{
LOGE("Could not read /proc/self/smaps");
}
}
else
{
LOGE("Could not get library name and base address");
}
return std::string();
}
void CameraWrapperConnector::setPathLibFolder(const std::string& path)
{
pathLibFolder=path;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
CameraActivity::CameraActivity() : camera(0), frameWidth(-1), frameHeight(-1)
{
}
CameraActivity::~CameraActivity()
{
if (camera != 0)
disconnect();
}
bool CameraActivity::onFrameBuffer(void* /*buffer*/, int /*bufferSize*/)
{
LOGD("CameraActivity::onFrameBuffer - empty callback");
return true;
}
void CameraActivity::disconnect()
{
CameraWrapperConnector::disconnect(&camera);
}
bool CameraActivity::isConnected() const
{
return camera != 0;
}
CameraActivity::ErrorCode CameraActivity::connect(int cameraId)
{
ErrorCode rescode = CameraWrapperConnector::connect(cameraId, this, &camera);
if (rescode) return rescode;
return NO_ERROR;
}
double CameraActivity::getProperty(int propIdx)
{
double propVal;
ErrorCode rescode = CameraWrapperConnector::getProperty(camera, propIdx, &propVal);
if (rescode) return -1;
return propVal;
}
void CameraActivity::setProperty(int propIdx, double value)
{
CameraWrapperConnector::setProperty(camera, propIdx, value);
}
void CameraActivity::applyProperties()
{
frameWidth = -1;
frameHeight = -1;
CameraWrapperConnector::applyProperties(&camera);
frameWidth = getProperty(ANDROID_CAMERA_PROPERTY_FRAMEWIDTH);
frameHeight = getProperty(ANDROID_CAMERA_PROPERTY_FRAMEHEIGHT);
}
int CameraActivity::getFrameWidth()
{
if (frameWidth <= 0)
frameWidth = getProperty(ANDROID_CAMERA_PROPERTY_FRAMEWIDTH);
return frameWidth;
}
int CameraActivity::getFrameHeight()
{
if (frameHeight <= 0)
frameHeight = getProperty(ANDROID_CAMERA_PROPERTY_FRAMEHEIGHT);
return frameHeight;
}
void CameraActivity::setPathLibFolder(const char* path)
{
CameraWrapperConnector::setPathLibFolder(path);
}
|
#include <dlfcn.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <android/log.h>
#include <cctype>
#include <string>
#include <vector>
#include <algorithm>
#include <opencv2/core/version.hpp>
#include "camera_activity.hpp"
#include "camera_wrapper.h"
#include "EngineCommon.h"
#include "opencv2/core.hpp"
#undef LOG_TAG
#undef LOGE
#undef LOGD
#undef LOGI
#define LOG_TAG "OpenCV::camera"
#define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__))
#define LOGD(...) ((void)__android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__))
#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__))
///////
// Debug
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
class CameraWrapperConnector
{
public:
static CameraActivity::ErrorCode connect(int cameraId, CameraActivity* pCameraActivity, void** camera);
static CameraActivity::ErrorCode disconnect(void** camera);
static CameraActivity::ErrorCode setProperty(void* camera, int propIdx, double value);
static CameraActivity::ErrorCode getProperty(void* camera, int propIdx, double* value);
static CameraActivity::ErrorCode applyProperties(void** ppcamera);
static void setPathLibFolder(const cv::String& path);
private:
static cv::String pathLibFolder;
static bool isConnectedToLib;
static cv::String getPathLibFolder();
static cv::String getDefaultPathLibFolder();
static CameraActivity::ErrorCode connectToLib();
static CameraActivity::ErrorCode getSymbolFromLib(void * libHandle, const char* symbolName, void** ppSymbol);
static void fillListWrapperLibs(const cv::String& folderPath, std::vector<cv::String>& listLibs);
static InitCameraConnectC pInitCameraC;
static CloseCameraConnectC pCloseCameraC;
static GetCameraPropertyC pGetPropertyC;
static SetCameraPropertyC pSetPropertyC;
static ApplyCameraPropertiesC pApplyPropertiesC;
friend bool nextFrame(void* buffer, size_t bufferSize, void* userData);
};
cv::String CameraWrapperConnector::pathLibFolder;
bool CameraWrapperConnector::isConnectedToLib = false;
InitCameraConnectC CameraWrapperConnector::pInitCameraC = 0;
CloseCameraConnectC CameraWrapperConnector::pCloseCameraC = 0;
GetCameraPropertyC CameraWrapperConnector::pGetPropertyC = 0;
SetCameraPropertyC CameraWrapperConnector::pSetPropertyC = 0;
ApplyCameraPropertiesC CameraWrapperConnector::pApplyPropertiesC = 0;
#define INIT_CAMERA_SYMBOL_NAME "initCameraConnectC"
#define CLOSE_CAMERA_SYMBOL_NAME "closeCameraConnectC"
#define SET_CAMERA_PROPERTY_SYMBOL_NAME "setCameraPropertyC"
#define GET_CAMERA_PROPERTY_SYMBOL_NAME "getCameraPropertyC"
#define APPLY_CAMERA_PROPERTIES_SYMBOL_NAME "applyCameraPropertiesC"
#define PREFIX_CAMERA_WRAPPER_LIB "libnative_camera"
bool nextFrame(void* buffer, size_t bufferSize, void* userData)
{
if (userData == NULL)
return true;
return ((CameraActivity*)userData)->onFrameBuffer(buffer, bufferSize);
}
CameraActivity::ErrorCode CameraWrapperConnector::connect(int cameraId, CameraActivity* pCameraActivity, void** camera)
{
if (pCameraActivity == NULL)
{
LOGE("CameraWrapperConnector::connect error: wrong pointer to CameraActivity object");
return CameraActivity::ERROR_WRONG_POINTER_CAMERA_WRAPPER;
}
CameraActivity::ErrorCode errcode=connectToLib();
if (errcode) return errcode;
void* cmr = (*pInitCameraC)((void*)nextFrame, cameraId, (void*)pCameraActivity);
if (!cmr)
{
LOGE("CameraWrapperConnector::connectWrapper ERROR: the initializing function returned false");
return CameraActivity::ERROR_CANNOT_INITIALIZE_CONNECTION;
}
*camera = cmr;
return CameraActivity::NO_ERROR;
}
CameraActivity::ErrorCode CameraWrapperConnector::disconnect(void** camera)
{
if (camera == NULL || *camera == NULL)
{
LOGE("CameraWrapperConnector::disconnect error: wrong pointer to camera object");
return CameraActivity::ERROR_WRONG_POINTER_CAMERA_WRAPPER;
}
CameraActivity::ErrorCode errcode=connectToLib();
if (errcode) return errcode;
(*pCloseCameraC)(camera);
return CameraActivity::NO_ERROR;
}
CameraActivity::ErrorCode CameraWrapperConnector::setProperty(void* camera, int propIdx, double value)
{
if (camera == NULL)
{
LOGE("CameraWrapperConnector::setProperty error: wrong pointer to camera object");
return CameraActivity::ERROR_WRONG_POINTER_CAMERA_WRAPPER;
}
(*pSetPropertyC)(camera, propIdx, value);
return CameraActivity::NO_ERROR;
}
CameraActivity::ErrorCode CameraWrapperConnector::getProperty(void* camera, int propIdx, double* value)
{
if (camera == NULL)
{
LOGE("CameraWrapperConnector::getProperty error: wrong pointer to camera object");
return CameraActivity::ERROR_WRONG_POINTER_CAMERA_WRAPPER;
}
LOGE("calling (*pGetPropertyC)(%p, %d)", camera, propIdx);
*value = (*pGetPropertyC)(camera, propIdx);
return CameraActivity::NO_ERROR;
}
CameraActivity::ErrorCode CameraWrapperConnector::applyProperties(void** ppcamera)
{
if ((ppcamera == NULL) || (*ppcamera == NULL))
{
LOGE("CameraWrapperConnector::applyProperties error: wrong pointer to camera object");
return CameraActivity::ERROR_WRONG_POINTER_CAMERA_WRAPPER;
}
(*pApplyPropertiesC)(ppcamera);
return CameraActivity::NO_ERROR;
}
CameraActivity::ErrorCode CameraWrapperConnector::connectToLib()
{
if (isConnectedToLib) {
return CameraActivity::NO_ERROR;
}
dlerror();
cv::String folderPath = getPathLibFolder();
if (folderPath.empty())
{
LOGD("Trying to find native camera in default OpenCV packages");
folderPath = getDefaultPathLibFolder();
}
LOGD("CameraWrapperConnector::connectToLib: folderPath=%s", folderPath.c_str());
std::vector<cv::String> listLibs;
fillListWrapperLibs(folderPath, listLibs);
std::sort(listLibs.begin(), listLibs.end(), std::greater<cv::String>());
void * libHandle=0;
cv::String cur_path;
for(size_t i = 0; i < listLibs.size(); i++) {
cur_path=folderPath + listLibs[i];
LOGD("try to load library '%s'", listLibs[i].c_str());
libHandle=dlopen(cur_path.c_str(), RTLD_LAZY);
if (libHandle) {
LOGD("Loaded library '%s'", cur_path.c_str());
break;
} else {
LOGD("CameraWrapperConnector::connectToLib ERROR: cannot dlopen camera wrapper library %s, dlerror=\"%s\"",
cur_path.c_str(), dlerror());
}
}
if (!libHandle) {
LOGE("CameraWrapperConnector::connectToLib ERROR: cannot dlopen camera wrapper library");
return CameraActivity::ERROR_CANNOT_OPEN_CAMERA_WRAPPER_LIB;
}
InitCameraConnectC pInit_C;
CloseCameraConnectC pClose_C;
GetCameraPropertyC pGetProp_C;
SetCameraPropertyC pSetProp_C;
ApplyCameraPropertiesC pApplyProp_C;
CameraActivity::ErrorCode res;
res = getSymbolFromLib(libHandle, (const char*)INIT_CAMERA_SYMBOL_NAME, (void**)(&pInit_C));
if (res) return res;
res = getSymbolFromLib(libHandle, CLOSE_CAMERA_SYMBOL_NAME, (void**)(&pClose_C));
if (res) return res;
res = getSymbolFromLib(libHandle, GET_CAMERA_PROPERTY_SYMBOL_NAME, (void**)(&pGetProp_C));
if (res) return res;
res = getSymbolFromLib(libHandle, SET_CAMERA_PROPERTY_SYMBOL_NAME, (void**)(&pSetProp_C));
if (res) return res;
res = getSymbolFromLib(libHandle, APPLY_CAMERA_PROPERTIES_SYMBOL_NAME, (void**)(&pApplyProp_C));
if (res) return res;
pInitCameraC = pInit_C;
pCloseCameraC = pClose_C;
pGetPropertyC = pGetProp_C;
pSetPropertyC = pSetProp_C;
pApplyPropertiesC = pApplyProp_C;
isConnectedToLib=true;
return CameraActivity::NO_ERROR;
}
CameraActivity::ErrorCode CameraWrapperConnector::getSymbolFromLib(void* libHandle, const char* symbolName, void** ppSymbol)
{
dlerror();
*(void **) (ppSymbol)=dlsym(libHandle, symbolName);
const char* error_dlsym_init=dlerror();
if (error_dlsym_init) {
LOGE("CameraWrapperConnector::getSymbolFromLib ERROR: cannot get symbol of the function '%s' from the camera wrapper library, dlerror=\"%s\"",
symbolName, error_dlsym_init);
return CameraActivity::ERROR_CANNOT_GET_FUNCTION_FROM_CAMERA_WRAPPER_LIB;
}
return CameraActivity::NO_ERROR;
}
void CameraWrapperConnector::fillListWrapperLibs(const cv::String& folderPath, std::vector<cv::String>& listLibs)
{
DIR *dp;
struct dirent *ep;
dp = opendir (folderPath.c_str());
if (dp != NULL)
{
while ((ep = readdir (dp))) {
const char* cur_name=ep->d_name;
if (strstr(cur_name, PREFIX_CAMERA_WRAPPER_LIB)) {
listLibs.push_back(cur_name);
LOGE("||%s", cur_name);
}
}
(void) closedir (dp);
}
}
cv::String CameraWrapperConnector::getDefaultPathLibFolder()
{
#define BIN_PACKAGE_NAME(x) "org.opencv.lib_v" CVAUX_STR(CV_VERSION_EPOCH) CVAUX_STR(CV_VERSION_MAJOR) "_" x
const char* const packageList[] = {BIN_PACKAGE_NAME("armv7a"), OPENCV_ENGINE_PACKAGE};
for (size_t i = 0; i < sizeof(packageList)/sizeof(packageList[0]); i++)
{
char path[128];
sprintf(path, "/data/data/%s/lib/", packageList[i]);
LOGD("Trying package \"%s\" (\"%s\")", packageList[i], path);
DIR* dir = opendir(path);
if (!dir)
{
LOGD("Package not found");
continue;
}
else
{
closedir(dir);
return path;
}
}
return cv::String();
}
cv::String CameraWrapperConnector::getPathLibFolder()
{
if (!pathLibFolder.empty())
return pathLibFolder;
Dl_info dl_info;
if(0 != dladdr((void *)nextFrame, &dl_info))
{
LOGD("Library name: %s", dl_info.dli_fname);
LOGD("Library base address: %p", dl_info.dli_fbase);
const char* libName=dl_info.dli_fname;
while( ((*libName)=='/') || ((*libName)=='.') )
libName++;
char lineBuf[2048];
FILE* file = fopen("/proc/self/smaps", "rt");
if(file)
{
while (fgets(lineBuf, sizeof lineBuf, file) != NULL)
{
//verify that line ends with library name
int lineLength = strlen(lineBuf);
int libNameLength = strlen(libName);
//trim end
for(int i = lineLength - 1; i >= 0 && isspace(lineBuf[i]); --i)
{
lineBuf[i] = 0;
--lineLength;
}
if (0 != strncmp(lineBuf + lineLength - libNameLength, libName, libNameLength))
{
//the line does not contain the library name
continue;
}
//extract path from smaps line
char* pathBegin = strchr(lineBuf, '/');
if (0 == pathBegin)
{
LOGE("Strange error: could not find path beginning in lin \"%s\"", lineBuf);
continue;
}
char* pathEnd = strrchr(pathBegin, '/');
pathEnd[1] = 0;
LOGD("Libraries folder found: %s", pathBegin);
fclose(file);
return pathBegin;
}
fclose(file);
LOGE("Could not find library path");
}
else
{
LOGE("Could not read /proc/self/smaps");
}
}
else
{
LOGE("Could not get library name and base address");
}
return cv::String();
}
void CameraWrapperConnector::setPathLibFolder(const cv::String& path)
{
pathLibFolder=path;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
CameraActivity::CameraActivity() : camera(0), frameWidth(-1), frameHeight(-1)
{
}
CameraActivity::~CameraActivity()
{
if (camera != 0)
disconnect();
}
bool CameraActivity::onFrameBuffer(void* /*buffer*/, int /*bufferSize*/)
{
LOGD("CameraActivity::onFrameBuffer - empty callback");
return true;
}
void CameraActivity::disconnect()
{
CameraWrapperConnector::disconnect(&camera);
}
bool CameraActivity::isConnected() const
{
return camera != 0;
}
CameraActivity::ErrorCode CameraActivity::connect(int cameraId)
{
ErrorCode rescode = CameraWrapperConnector::connect(cameraId, this, &camera);
if (rescode) return rescode;
return NO_ERROR;
}
double CameraActivity::getProperty(int propIdx)
{
double propVal;
ErrorCode rescode = CameraWrapperConnector::getProperty(camera, propIdx, &propVal);
if (rescode) return -1;
return propVal;
}
void CameraActivity::setProperty(int propIdx, double value)
{
CameraWrapperConnector::setProperty(camera, propIdx, value);
}
void CameraActivity::applyProperties()
{
frameWidth = -1;
frameHeight = -1;
CameraWrapperConnector::applyProperties(&camera);
frameWidth = getProperty(ANDROID_CAMERA_PROPERTY_FRAMEWIDTH);
frameHeight = getProperty(ANDROID_CAMERA_PROPERTY_FRAMEHEIGHT);
}
int CameraActivity::getFrameWidth()
{
if (frameWidth <= 0)
frameWidth = getProperty(ANDROID_CAMERA_PROPERTY_FRAMEWIDTH);
return frameWidth;
}
int CameraActivity::getFrameHeight()
{
if (frameHeight <= 0)
frameHeight = getProperty(ANDROID_CAMERA_PROPERTY_FRAMEHEIGHT);
return frameHeight;
}
void CameraActivity::setPathLibFolder(const char* path)
{
CameraWrapperConnector::setPathLibFolder(path);
}
|
Use cv::String in Android camera wrapper
|
Use cv::String in Android camera wrapper
|
C++
|
bsd-3-clause
|
apavlenko/opencv,apavlenko/opencv,apavlenko/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,apavlenko/opencv,apavlenko/opencv,opencv/opencv,opencv/opencv,apavlenko/opencv
|
18a350b98f53048c95e49576c1fda015ffad6918
|
include/tudocomp/compressors/LZ78UCompressor.hpp
|
include/tudocomp/compressors/LZ78UCompressor.hpp
|
#pragma once
#include <tudocomp/Compressor.hpp>
#include <sdsl/cst_fully.hpp>
#include <sdsl/cst_sada.hpp>
#include <tudocomp/Range.hpp>
#include <tudocomp/ds/TextDS.hpp>
#include <tudocomp/ds/st.hpp>
#include <tudocomp/ds/st_util.hpp>
namespace tdc {
class LZ78UCompressor: public Compressor {
private:
using cst_t = STLz78u;
using node_type = cst_t::node_type;
static inline lz78::factorid_t select_size(Env& env, string_ref name) {
auto& o = env.option(name);
if (o.as_string() == "inf") {
return 0;
} else {
return o.as_integer();
}
}
/// Max dictionary size before reset
const lz78::factorid_t m_dict_max_size {0};
public:
inline LZ78UCompressor(Env&& env):
Compressor(std::move(env)),
m_dict_max_size(env.option("dict_size").as_integer())
{}
inline static Meta meta() {
Meta m("compressor", "lz78u", "Lempel-Ziv 78 U\n\n" LZ78_DICT_SIZE_DESC);
m.option("dict_size").dynamic("inf");
m.needs_sentinel_terminator();
return m;
}
virtual void compress(Input& input, Output& out) override {
env().begin_stat_phase("lz78u");
auto T = input.as_view();
TextDS<> ds { T, env(), TextDS<>::ISA};
auto isa_p = ds.release_isa();
auto& ISA = *isa_p;
cst_t::cst_t backing_cst;
{
env().begin_stat_phase("construct suffix tree");
// TODO: Specialize sdsl template for less alloc here
std::string bad_copy_1 = T.substr(0, T.size() - 1);
std::cout << vec_to_debug_string(bad_copy_1) << "\n";
construct_im(backing_cst, bad_copy_1, 1);
env().end_stat_phase();
}
cst_t ST = cst_t(backing_cst);
std::vector<size_t> R;
R.reserve(backing_cst.nodes());
R.resize(backing_cst.nodes());
size_t pos = 1;
size_t z = 0;
// tx: a a a b a b a a a b a a b a b a $
// sn: 5 10 15 16
auto label = [&](const node_type& v) -> size_t {
return ST.cst.sn(v);
};
auto lambda = [&ST, &pos, &T, &label](const node_type& l1, const node_type& l2) -> View {
auto offset_node = ST.cst.leftmost_leaf(l2);
size_t offset = label(offset_node);
size_t depth1 = ST.str_depth(l1);
size_t depth2 = ST.str_depth(l2);
size_t start = offset + depth1;
size_t end = offset + depth2;
auto v = T.substr(start, end);
std::cout << "pos: " << pos << " lambda(" << start << ", " << end << "): " << v << "\n";
return v;
};
auto parent = [&ST](const node_type& n) {
return ST.parent(n);
};
auto leaf_select = [&ST](const size_t& pos) {
return ST.cst.select_leaf(pos);
};
auto level_anc = [&ST](const node_type& n, size_t d) {
return ST.level_anc(n, d);
};
while (pos <= T.size()) {
auto l = leaf_select(ISA[pos]);
if (R[parent(l)] != 0) {
std::cout << "out l c: " << int(lambda(parent(l), l)[0]) << "\n";
std::cout << "out l r: " << int(0) << "\n";
pos++;
} else {
size_t d = 1;
while (level_anc(l, d) != 0) {
d++;
pos += lambda(level_anc(l, d - 1), level_anc(l, d)).size();
}
auto node = level_anc(l, d);
z++;
R[node] = z;
std::cout << "out m s: " << vec_to_debug_string(lambda(parent(node), node)) << "\n";
std::cout << "out m r: " << int(R[parent(node)]) << "\n";
pos += lambda(parent(node), node).size();
}
}
env().end_stat_phase();
}
virtual void decompress(Input& input, Output& output) override final {
}
};
}//ns
|
#pragma once
#include <tudocomp/Compressor.hpp>
#include <sdsl/cst_fully.hpp>
#include <sdsl/cst_sada.hpp>
#include <tudocomp/Range.hpp>
#include <tudocomp/ds/TextDS.hpp>
#include <tudocomp/ds/st.hpp>
#include <tudocomp/ds/st_util.hpp>
namespace tdc {
class LZ78UCompressor: public Compressor {
private:
using cst_t = STLz78u;
using node_type = cst_t::node_type;
static inline lz78::factorid_t select_size(Env& env, string_ref name) {
auto& o = env.option(name);
if (o.as_string() == "inf") {
return 0;
} else {
return o.as_integer();
}
}
/// Max dictionary size before reset
const lz78::factorid_t m_dict_max_size {0};
public:
inline LZ78UCompressor(Env&& env):
Compressor(std::move(env)),
m_dict_max_size(env.option("dict_size").as_integer())
{}
inline static Meta meta() {
Meta m("compressor", "lz78u", "Lempel-Ziv 78 U\n\n" LZ78_DICT_SIZE_DESC);
m.option("dict_size").dynamic("inf");
m.needs_sentinel_terminator();
return m;
}
virtual void compress(Input& input, Output& out) override {
env().begin_stat_phase("lz78u");
auto iview = input.as_view();
View T = iview;
TextDS<> ds { T, env(), TextDS<>::ISA};
auto isa_p = ds.release_isa();
auto& ISA = *isa_p;
cst_t::cst_t backing_cst;
{
env().begin_stat_phase("construct suffix tree");
// TODO: Specialize sdsl template for less alloc here
std::string bad_copy_1 = T.substr(0, T.size() - 1);
std::cout << vec_to_debug_string(bad_copy_1) << "\n";
construct_im(backing_cst, bad_copy_1, 1);
env().end_stat_phase();
}
cst_t ST = cst_t(backing_cst);
std::vector<size_t> R;
R.reserve(backing_cst.nodes());
R.resize(backing_cst.nodes());
size_t pos = 1;
size_t z = 0;
// tx: a a a b a b a a a b a a b a b a $
// sn: 5 10 15 16
auto label = [&](const node_type& v) -> size_t {
return ST.cst.sn(v);
};
auto lambda = [&ST, &pos, &T, &label](const node_type& l1, const node_type& l2) -> View {
auto offset_node = ST.cst.leftmost_leaf(l2);
size_t offset = label(offset_node);
size_t depth1 = ST.str_depth(l1);
size_t depth2 = ST.str_depth(l2);
size_t start = offset + depth1;
size_t end = offset + depth2;
auto v = T.substr(start, end);
std::cout << "pos: " << pos << " lambda(" << start << ", " << end << "): " << v << "\n";
return v;
};
auto parent = [&ST](const node_type& n) {
return ST.parent(n);
};
auto leaf_select = [&ST](const size_t& pos) {
return ST.cst.select_leaf(pos);
};
auto level_anc = [&ST](const node_type& n, size_t d) {
return ST.level_anc(n, d);
};
while (pos <= T.size()) {
auto l = leaf_select(ISA[pos]);
if (R[parent(l)] != 0) {
std::cout << "out l c: " << int(lambda(parent(l), l)[0]) << "\n";
std::cout << "out l r: " << int(0) << "\n";
pos++;
} else {
size_t d = 1;
while (R[level_anc(l, d)] != 0) {
d++;
pos += lambda(level_anc(l, d - 1), level_anc(l, d)).size();
}
auto node = level_anc(l, d);
z++;
R[node] = z;
std::cout << "out m s: " << vec_to_debug_string(lambda(parent(node), node)) << "\n";
std::cout << "out m r: " << int(R[parent(node)]) << "\n";
pos += lambda(parent(node), node).size();
}
}
env().end_stat_phase();
}
virtual void decompress(Input& input, Output& output) override final {
}
};
}//ns
|
fix bug
|
fix bug
|
C++
|
apache-2.0
|
tudocomp/tudocomp,tudocomp/tudocomp,tudocomp/tudocomp,tudocomp/tudocomp,tudocomp/tudocomp
|
bc960cddc702323d6261dcb067210989ded616d6
|
fbench/src/fbench/client.cpp
|
fbench/src/fbench/client.cpp
|
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <util/timer.h>
#include <httpclient/httpclient.h>
#include <util/filereader.h>
#include "client.h"
Client::Client(ClientArguments *args)
: _args(args),
_status(new ClientStatus()),
_reqTimer(new Timer()),
_cycleTimer(new Timer()),
_masterTimer(new Timer()),
_http(new HTTPClient(_args->_hostname, _args->_port,
_args->_keepAlive, _args->_headerBenchmarkdataCoverage,
_args->_extraHeaders, _args->_authority)),
_reader(new FileReader()),
_output(),
_linebufsize(args->_maxLineSize),
_linebuf(new char[_linebufsize]),
_stop(false),
_done(false),
_thread()
{
assert(args != NULL);
_cycleTimer->SetMax(_args->_cycle);
}
Client::~Client()
{
delete [] _linebuf;
}
void Client::runMe(Client * me) {
me->run();
}
class UrlReader {
FileReader &_reader;
const ClientArguments &_args;
int _restarts;
int _contentbufsize;
int _leftOversLen;
char *_contentbuf;
const char *_leftOvers;
public:
UrlReader(FileReader& reader, const ClientArguments &args)
: _reader(reader), _args(args), _restarts(0),
_contentbufsize(0), _leftOversLen(0),
_contentbuf(0), _leftOvers(0)
{
if (_args._usePostMode) {
_contentbufsize = 16 * _args._maxLineSize;
_contentbuf = new char[_contentbufsize];
}
}
bool reset();
int findUrl(char *buf, int buflen);
int nextUrl(char *buf, int buflen);
int nextContent();
const char *content() const { return _contentbuf; }
~UrlReader() { delete [] _contentbuf; }
};
bool UrlReader::reset()
{
if (_restarts == _args._restartLimit) {
return false;
} else if (_args._restartLimit > 0) {
_restarts++;
}
_reader.Reset();
// Start reading from offset
if (_args._singleQueryFile) {
_reader.SetFilePos(_args._queryfileOffset);
}
return true;
}
int UrlReader::findUrl(char *buf, int buflen)
{
while (true) {
if ( _args._singleQueryFile && _reader.GetFilePos() >= _args._queryfileEndOffset ) {
// reached logical EOF
return -1;
}
int ll = _reader.ReadLine(buf, buflen);
if (ll < 0) {
// reached physical EOF
return ll;
}
if (ll > 0) {
if (buf[0] == '/' || !_args._usePostMode) {
// found URL
return ll;
}
}
}
}
int UrlReader::nextUrl(char *buf, int buflen)
{
if (_leftOvers) {
int sz = std::min(_leftOversLen, buflen-1);
strncpy(buf, _leftOvers, sz);
buf[sz] = '\0';
_leftOvers = NULL;
return _leftOversLen;
}
int ll = findUrl(buf, buflen);
if (ll > 0) {
return ll;
}
if (reset()) {
// try again
ll = findUrl(buf, buflen);
}
return ll;
}
int UrlReader::nextContent()
{
char *buf = _contentbuf;
int totLen = 0;
int nl = 0;
while (totLen + 1 < _contentbufsize) {
int left = _contentbufsize - totLen;
// allow space for newline:
int len = _reader.ReadLine(buf, left - 1);
if (len < 0) {
// reached EOF
return totLen;
}
if (len > 0 && buf[0] == '/') {
// reached next URL
_leftOvers = buf;
_leftOversLen = len;
return totLen;
}
buf += len;
*buf++ = '\n';
totLen += nl + len;
nl = 1;
}
return totLen;
}
void
Client::run()
{
char inputFilename[1024];
char outputFilename[1024];
char timestr[64];
int linelen;
/// int reslen;
std::this_thread::sleep_for(std::chrono::milliseconds(_args->_delay));
// open query file
snprintf(inputFilename, 1024, _args->_filenamePattern, _args->_myNum);
if (!_reader->Open(inputFilename)) {
printf("Client %d: ERROR: could not open file '%s' [read mode]\n",
_args->_myNum, inputFilename);
_status->SetError("Could not open query file.");
return;
}
if (_args->_outputPattern != NULL) {
snprintf(outputFilename, 1024, _args->_outputPattern, _args->_myNum);
_output = std::make_unique<std::ofstream>(outputFilename, std::ofstream::out | std::ofstream::binary);
if (_output->fail()) {
printf("Client %d: ERROR: could not open file '%s' [write mode]\n",
_args->_myNum, outputFilename);
_status->SetError("Could not open output file.");
return;
}
}
if (_output)
_output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1);
if (_args->_ignoreCount == 0)
_masterTimer->Start();
// Start reading from offset
if ( _args->_singleQueryFile )
_reader->SetFilePos(_args->_queryfileOffset);
UrlReader urlSource(*_reader, *_args);
size_t urlNumber = 0;
// run queries
while (!_stop) {
_cycleTimer->Start();
linelen = urlSource.nextUrl(_linebuf, _linebufsize);
if (linelen > 0) {
++urlNumber;
} else {
if (urlNumber == 0) {
fprintf(stderr, "Client %d: ERROR: could not read any lines from '%s'\n",
_args->_myNum, inputFilename);
_status->SetError("Could not read any lines from query file.");
}
break;
}
if (linelen < _linebufsize) {
if (_output) {
_output->write("URL: ", strlen("URL: "));
_output->write(_linebuf, linelen);
_output->write("\n\n", 2);
}
if (linelen + (int)_args->_queryStringToAppend.length() < _linebufsize) {
strcat(_linebuf, _args->_queryStringToAppend.c_str());
}
int cLen = _args->_usePostMode ? urlSource.nextContent() : 0;
_reqTimer->Start();
auto fetch_status = _http->Fetch(_linebuf, _output.get(), _args->_usePostMode, urlSource.content(), cLen);
_reqTimer->Stop();
_status->AddRequestStatus(fetch_status.RequestStatus());
if (fetch_status.Ok() && fetch_status.TotalHitCount() == 0)
++_status->_zeroHitQueries;
if (_output) {
if (!fetch_status.Ok()) {
_output->write("\nFBENCH: URL FETCH FAILED!\n",
strlen("\nFBENCH: URL FETCH FAILED!\n"));
_output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1);
} else {
sprintf(timestr, "\nTIME USED: %0.4f s\n",
_reqTimer->GetTimespan() / 1000.0);
_output->write(timestr, strlen(timestr));
_output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1);
}
}
if (fetch_status.ResultSize() >= _args->_byteLimit) {
if (_args->_ignoreCount == 0)
_status->ResponseTime(_reqTimer->GetTimespan());
} else {
if (_args->_ignoreCount == 0)
_status->RequestFailed();
}
} else {
if (_args->_ignoreCount == 0)
_status->SkippedRequest();
}
_cycleTimer->Stop();
if (_args->_cycle < 0) {
std::this_thread::sleep_for(std::chrono::milliseconds(int(_reqTimer->GetTimespan())));
} else {
if (_cycleTimer->GetRemaining() > 0) {
std::this_thread::sleep_for(std::chrono::milliseconds(int(_cycleTimer->GetRemaining())));
} else {
if (_args->_ignoreCount == 0)
_status->OverTime();
}
}
if (_args->_ignoreCount > 0) {
_args->_ignoreCount--;
if (_args->_ignoreCount == 0)
_masterTimer->Start();
}
// Update current time span to calculate Q/s
_status->SetRealTime(_masterTimer->GetCurrent());
}
_masterTimer->Stop();
_status->SetRealTime(_masterTimer->GetTimespan());
_status->SetReuseCount(_http->GetReuseCount());
printf(".");
fflush(stdout);
_done = true;
}
void Client::stop() {
_stop = true;
}
bool Client::done() {
return _done;
}
void Client::start() {
_thread = std::thread(Client::runMe, this);
}
void Client::join() {
_thread.join();
}
|
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <util/timer.h>
#include <httpclient/httpclient.h>
#include <util/filereader.h>
#include "client.h"
Client::Client(ClientArguments *args)
: _args(args),
_status(new ClientStatus()),
_reqTimer(new Timer()),
_cycleTimer(new Timer()),
_masterTimer(new Timer()),
_http(new HTTPClient(_args->_hostname, _args->_port,
_args->_keepAlive, _args->_headerBenchmarkdataCoverage,
_args->_extraHeaders, _args->_authority)),
_reader(new FileReader()),
_output(),
_linebufsize(args->_maxLineSize),
_linebuf(new char[_linebufsize]),
_stop(false),
_done(false),
_thread()
{
assert(args != NULL);
_cycleTimer->SetMax(_args->_cycle);
}
Client::~Client()
{
delete [] _linebuf;
}
void Client::runMe(Client * me) {
me->run();
}
class UrlReader {
FileReader &_reader;
const ClientArguments &_args;
int _restarts;
int _contentbufsize;
int _leftOversLen;
char *_contentbuf;
const char *_leftOvers;
public:
UrlReader(FileReader& reader, const ClientArguments &args)
: _reader(reader), _args(args), _restarts(0),
_contentbufsize(0), _leftOversLen(0),
_contentbuf(0), _leftOvers(0)
{
if (_args._usePostMode) {
_contentbufsize = 16 * _args._maxLineSize;
_contentbuf = new char[_contentbufsize];
}
}
bool reset();
int findUrl(char *buf, int buflen);
int nextUrl(char *buf, int buflen);
int nextContent();
const char *content() const { return _contentbuf; }
~UrlReader() { delete [] _contentbuf; }
};
bool UrlReader::reset()
{
if (_restarts == _args._restartLimit) {
return false;
} else if (_args._restartLimit > 0) {
_restarts++;
}
_reader.Reset();
// Start reading from offset
if (_args._singleQueryFile) {
_reader.SetFilePos(_args._queryfileOffset);
}
return true;
}
int UrlReader::findUrl(char *buf, int buflen)
{
while (true) {
if ( _args._singleQueryFile && _reader.GetFilePos() >= _args._queryfileEndOffset ) {
// reached logical EOF
return -1;
}
int ll = _reader.ReadLine(buf, buflen);
if (ll < 0) {
// reached physical EOF
return ll;
}
if (ll > 0) {
if (buf[0] == '/' || !_args._usePostMode) {
// found URL
return ll;
}
}
}
}
int UrlReader::nextUrl(char *buf, int buflen)
{
if (_leftOvers) {
int sz = std::min(_leftOversLen, buflen-1);
strncpy(buf, _leftOvers, sz);
buf[sz] = '\0';
_leftOvers = NULL;
return _leftOversLen;
}
int ll = findUrl(buf, buflen);
if (ll > 0) {
return ll;
}
if (reset()) {
// try again
ll = findUrl(buf, buflen);
}
return ll;
}
int UrlReader::nextContent()
{
char *buf = _contentbuf;
int totLen = 0;
// make sure we don't chop leftover URL
while (totLen + _args._maxLineSize < _contentbufsize) {
// allow space for newline:
int room = _contentbufsize - totLen - 1;
int len = _reader.ReadLine(buf, room);
if (len < 0) {
// reached EOF
break;
}
len = std::min(len, room);
if (len > 0 && buf[0] == '/') {
// reached next URL
_leftOvers = buf;
_leftOversLen = len;
break;
}
buf += len;
totLen += len;
*buf++ = '\n';
totLen++;
}
// ignore last newline
return (totLen > 0) ? totLen-1 : 0;
}
void
Client::run()
{
char inputFilename[1024];
char outputFilename[1024];
char timestr[64];
int linelen;
/// int reslen;
std::this_thread::sleep_for(std::chrono::milliseconds(_args->_delay));
// open query file
snprintf(inputFilename, 1024, _args->_filenamePattern, _args->_myNum);
if (!_reader->Open(inputFilename)) {
printf("Client %d: ERROR: could not open file '%s' [read mode]\n",
_args->_myNum, inputFilename);
_status->SetError("Could not open query file.");
return;
}
if (_args->_outputPattern != NULL) {
snprintf(outputFilename, 1024, _args->_outputPattern, _args->_myNum);
_output = std::make_unique<std::ofstream>(outputFilename, std::ofstream::out | std::ofstream::binary);
if (_output->fail()) {
printf("Client %d: ERROR: could not open file '%s' [write mode]\n",
_args->_myNum, outputFilename);
_status->SetError("Could not open output file.");
return;
}
}
if (_output)
_output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1);
if (_args->_ignoreCount == 0)
_masterTimer->Start();
// Start reading from offset
if ( _args->_singleQueryFile )
_reader->SetFilePos(_args->_queryfileOffset);
UrlReader urlSource(*_reader, *_args);
size_t urlNumber = 0;
// run queries
while (!_stop) {
_cycleTimer->Start();
linelen = urlSource.nextUrl(_linebuf, _linebufsize);
if (linelen > 0) {
++urlNumber;
} else {
if (urlNumber == 0) {
fprintf(stderr, "Client %d: ERROR: could not read any lines from '%s'\n",
_args->_myNum, inputFilename);
_status->SetError("Could not read any lines from query file.");
}
break;
}
if (linelen < _linebufsize) {
if (_output) {
_output->write("URL: ", strlen("URL: "));
_output->write(_linebuf, linelen);
_output->write("\n\n", 2);
}
if (linelen + (int)_args->_queryStringToAppend.length() < _linebufsize) {
strcat(_linebuf, _args->_queryStringToAppend.c_str());
}
int cLen = _args->_usePostMode ? urlSource.nextContent() : 0;
_reqTimer->Start();
auto fetch_status = _http->Fetch(_linebuf, _output.get(), _args->_usePostMode, urlSource.content(), cLen);
_reqTimer->Stop();
_status->AddRequestStatus(fetch_status.RequestStatus());
if (fetch_status.Ok() && fetch_status.TotalHitCount() == 0)
++_status->_zeroHitQueries;
if (_output) {
if (!fetch_status.Ok()) {
_output->write("\nFBENCH: URL FETCH FAILED!\n",
strlen("\nFBENCH: URL FETCH FAILED!\n"));
_output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1);
} else {
sprintf(timestr, "\nTIME USED: %0.4f s\n",
_reqTimer->GetTimespan() / 1000.0);
_output->write(timestr, strlen(timestr));
_output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1);
}
}
if (fetch_status.ResultSize() >= _args->_byteLimit) {
if (_args->_ignoreCount == 0)
_status->ResponseTime(_reqTimer->GetTimespan());
} else {
if (_args->_ignoreCount == 0)
_status->RequestFailed();
}
} else {
if (_args->_ignoreCount == 0)
_status->SkippedRequest();
}
_cycleTimer->Stop();
if (_args->_cycle < 0) {
std::this_thread::sleep_for(std::chrono::milliseconds(int(_reqTimer->GetTimespan())));
} else {
if (_cycleTimer->GetRemaining() > 0) {
std::this_thread::sleep_for(std::chrono::milliseconds(int(_cycleTimer->GetRemaining())));
} else {
if (_args->_ignoreCount == 0)
_status->OverTime();
}
}
if (_args->_ignoreCount > 0) {
_args->_ignoreCount--;
if (_args->_ignoreCount == 0)
_masterTimer->Start();
}
// Update current time span to calculate Q/s
_status->SetRealTime(_masterTimer->GetCurrent());
}
_masterTimer->Stop();
_status->SetRealTime(_masterTimer->GetTimespan());
_status->SetReuseCount(_http->GetReuseCount());
printf(".");
fflush(stdout);
_done = true;
}
void Client::stop() {
_stop = true;
}
bool Client::done() {
return _done;
}
void Client::start() {
_thread = std::thread(Client::runMe, this);
}
void Client::join() {
_thread.join();
}
|
simplify newline adding
|
simplify newline adding
also, account for space for full URL to follow
|
C++
|
apache-2.0
|
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
|
d40083a9269bab4634a23222e9d93fdbdec608cf
|
modules/calib3d/test/test_solvepnp_ransac.cpp
|
modules/calib3d/test/test_solvepnp_ransac.cpp
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "test_precomp.hpp"
using namespace cv;
using namespace std;
class CV_solvePnPRansac_Test : public cvtest::BaseTest
{
public:
CV_solvePnPRansac_Test()
{
eps[CV_ITERATIVE] = 1.0e-2;
eps[CV_EPNP] = 1.0e-2;
eps[CV_P3P] = 1.0e-2;
totalTestsCount = 10;
}
~CV_solvePnPRansac_Test() {}
protected:
void generate3DPointCloud(vector<Point3f>& points, Point3f pmin = Point3f(-1,
-1, 5), Point3f pmax = Point3f(1, 1, 10))
{
const Point3f delta = pmax - pmin;
for (size_t i = 0; i < points.size(); i++)
{
Point3f p(float(rand()) / RAND_MAX, float(rand()) / RAND_MAX,
float(rand()) / RAND_MAX);
p.x *= delta.x;
p.y *= delta.y;
p.z *= delta.z;
p = p + pmin;
points[i] = p;
}
}
void generateCameraMatrix(Mat& cameraMatrix, RNG& rng)
{
const double fcMinVal = 1e-3;
const double fcMaxVal = 100;
cameraMatrix.create(3, 3, CV_64FC1);
cameraMatrix.setTo(Scalar(0));
cameraMatrix.at<double>(0,0) = rng.uniform(fcMinVal, fcMaxVal);
cameraMatrix.at<double>(1,1) = rng.uniform(fcMinVal, fcMaxVal);
cameraMatrix.at<double>(0,2) = rng.uniform(fcMinVal, fcMaxVal);
cameraMatrix.at<double>(1,2) = rng.uniform(fcMinVal, fcMaxVal);
cameraMatrix.at<double>(2,2) = 1;
}
void generateDistCoeffs(Mat& distCoeffs, RNG& rng)
{
distCoeffs = Mat::zeros(4, 1, CV_64FC1);
for (int i = 0; i < 3; i++)
distCoeffs.at<double>(i,0) = rng.uniform(0.0, 1.0e-6);
}
void generatePose(Mat& rvec, Mat& tvec, RNG& rng)
{
const double minVal = 1.0e-3;
const double maxVal = 1.0;
rvec.create(3, 1, CV_64FC1);
tvec.create(3, 1, CV_64FC1);
for (int i = 0; i < 3; i++)
{
rvec.at<double>(i,0) = rng.uniform(minVal, maxVal);
tvec.at<double>(i,0) = rng.uniform(minVal, maxVal/10);
}
}
virtual bool runTest(RNG& rng, int mode, int method, const vector<Point3f>& points, const double* epsilon, double& maxError)
{
Mat rvec, tvec;
vector<int> inliers;
Mat trueRvec, trueTvec;
Mat intrinsics, distCoeffs;
generateCameraMatrix(intrinsics, rng);
if (mode == 0)
distCoeffs = Mat::zeros(4, 1, CV_64FC1);
else
generateDistCoeffs(distCoeffs, rng);
generatePose(trueRvec, trueTvec, rng);
vector<Point2f> projectedPoints;
projectedPoints.resize(points.size());
projectPoints(Mat(points), trueRvec, trueTvec, intrinsics, distCoeffs, projectedPoints);
for (size_t i = 0; i < projectedPoints.size(); i++)
{
if (i % 20 == 0)
{
projectedPoints[i] = projectedPoints[rng.uniform(0,(int)points.size()-1)];
}
}
solvePnPRansac(points, projectedPoints, intrinsics, distCoeffs, rvec, tvec,
false, 500, 0.5, -1, inliers, method);
bool isTestSuccess = inliers.size() >= points.size()*0.95;
double rvecDiff = norm(rvec-trueRvec), tvecDiff = norm(tvec-trueTvec);
isTestSuccess = isTestSuccess && rvecDiff < epsilon[method] && tvecDiff < epsilon[method];
double error = rvecDiff > tvecDiff ? rvecDiff : tvecDiff;
//cout << error << " " << inliers.size() << " " << eps[method] << endl;
if (error > maxError)
maxError = error;
return isTestSuccess;
}
void run(int)
{
ts->set_failed_test_info(cvtest::TS::OK);
vector<Point3f> points;
const int pointsCount = 500;
points.resize(pointsCount);
generate3DPointCloud(points);
const int methodsCount = 3;
RNG rng = ts->get_rng();
for (int mode = 0; mode < 2; mode++)
{
for (int method = 0; method < methodsCount; method++)
{
double maxError = 0;
int successfulTestsCount = 0;
for (int testIndex = 0; testIndex < totalTestsCount; testIndex++)
{
if (runTest(rng, mode, method, points, eps, maxError))
successfulTestsCount++;
}
//cout << maxError << " " << successfulTestsCount << endl;
if (successfulTestsCount < 0.7*totalTestsCount)
{
ts->printf( cvtest::TS::LOG, "Invalid accuracy for method %d, failed %d tests from %d, maximum error equals %f, distortion mode equals %d\n",
method, totalTestsCount - successfulTestsCount, totalTestsCount, maxError, mode);
ts->set_failed_test_info(cvtest::TS::FAIL_BAD_ACCURACY);
}
}
}
}
double eps[3];
int totalTestsCount;
};
class CV_solvePnP_Test : public CV_solvePnPRansac_Test
{
public:
CV_solvePnP_Test()
{
eps[CV_ITERATIVE] = 1.0e-6;
eps[CV_EPNP] = 1.0e-6;
eps[CV_P3P] = 1.0e-4;
totalTestsCount = 1000;
}
~CV_solvePnP_Test() {}
protected:
virtual bool runTest(RNG& rng, int mode, int method, const vector<Point3f>& points, const double* epsilon, double& maxError)
{
Mat rvec, tvec;
Mat trueRvec, trueTvec;
Mat intrinsics, distCoeffs;
generateCameraMatrix(intrinsics, rng);
if (mode == 0)
distCoeffs = Mat::zeros(4, 1, CV_64FC1);
else
generateDistCoeffs(distCoeffs, rng);
generatePose(trueRvec, trueTvec, rng);
std::vector<Point3f> opoints;
if (method == 2)
{
opoints = std::vector<Point3f>(points.begin(), points.begin()+4);
}
else
opoints = points;
vector<Point2f> projectedPoints;
projectedPoints.resize(opoints.size());
projectPoints(Mat(opoints), trueRvec, trueTvec, intrinsics, distCoeffs, projectedPoints);
solvePnP(opoints, projectedPoints, intrinsics, distCoeffs, rvec, tvec,
false, method);
double rvecDiff = norm(rvec-trueRvec), tvecDiff = norm(tvec-trueTvec);
bool isTestSuccess = rvecDiff < epsilon[method] && tvecDiff < epsilon[method];
double error = rvecDiff > tvecDiff ? rvecDiff : tvecDiff;
if (error > maxError)
maxError = error;
return isTestSuccess;
}
};
TEST(Calib3d_SolvePnPRansac, accuracy) { CV_solvePnPRansac_Test test; test.safe_run(); }
TEST(Calib3d_SolvePnP, accuracy) { CV_solvePnP_Test test; test.safe_run(); }
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "test_precomp.hpp"
#include "opencv2/core/internal.hpp"
using namespace cv;
using namespace std;
class CV_solvePnPRansac_Test : public cvtest::BaseTest
{
public:
CV_solvePnPRansac_Test()
{
eps[CV_ITERATIVE] = 1.0e-2;
eps[CV_EPNP] = 1.0e-2;
eps[CV_P3P] = 1.0e-2;
totalTestsCount = 10;
}
~CV_solvePnPRansac_Test() {}
protected:
void generate3DPointCloud(vector<Point3f>& points, Point3f pmin = Point3f(-1,
-1, 5), Point3f pmax = Point3f(1, 1, 10))
{
const Point3f delta = pmax - pmin;
for (size_t i = 0; i < points.size(); i++)
{
Point3f p(float(rand()) / RAND_MAX, float(rand()) / RAND_MAX,
float(rand()) / RAND_MAX);
p.x *= delta.x;
p.y *= delta.y;
p.z *= delta.z;
p = p + pmin;
points[i] = p;
}
}
void generateCameraMatrix(Mat& cameraMatrix, RNG& rng)
{
const double fcMinVal = 1e-3;
const double fcMaxVal = 100;
cameraMatrix.create(3, 3, CV_64FC1);
cameraMatrix.setTo(Scalar(0));
cameraMatrix.at<double>(0,0) = rng.uniform(fcMinVal, fcMaxVal);
cameraMatrix.at<double>(1,1) = rng.uniform(fcMinVal, fcMaxVal);
cameraMatrix.at<double>(0,2) = rng.uniform(fcMinVal, fcMaxVal);
cameraMatrix.at<double>(1,2) = rng.uniform(fcMinVal, fcMaxVal);
cameraMatrix.at<double>(2,2) = 1;
}
void generateDistCoeffs(Mat& distCoeffs, RNG& rng)
{
distCoeffs = Mat::zeros(4, 1, CV_64FC1);
for (int i = 0; i < 3; i++)
distCoeffs.at<double>(i,0) = rng.uniform(0.0, 1.0e-6);
}
void generatePose(Mat& rvec, Mat& tvec, RNG& rng)
{
const double minVal = 1.0e-3;
const double maxVal = 1.0;
rvec.create(3, 1, CV_64FC1);
tvec.create(3, 1, CV_64FC1);
for (int i = 0; i < 3; i++)
{
rvec.at<double>(i,0) = rng.uniform(minVal, maxVal);
tvec.at<double>(i,0) = rng.uniform(minVal, maxVal/10);
}
}
virtual bool runTest(RNG& rng, int mode, int method, const vector<Point3f>& points, const double* epsilon, double& maxError)
{
Mat rvec, tvec;
vector<int> inliers;
Mat trueRvec, trueTvec;
Mat intrinsics, distCoeffs;
generateCameraMatrix(intrinsics, rng);
if (mode == 0)
distCoeffs = Mat::zeros(4, 1, CV_64FC1);
else
generateDistCoeffs(distCoeffs, rng);
generatePose(trueRvec, trueTvec, rng);
vector<Point2f> projectedPoints;
projectedPoints.resize(points.size());
projectPoints(Mat(points), trueRvec, trueTvec, intrinsics, distCoeffs, projectedPoints);
for (size_t i = 0; i < projectedPoints.size(); i++)
{
if (i % 20 == 0)
{
projectedPoints[i] = projectedPoints[rng.uniform(0,(int)points.size()-1)];
}
}
solvePnPRansac(points, projectedPoints, intrinsics, distCoeffs, rvec, tvec,
false, 500, 0.5, -1, inliers, method);
bool isTestSuccess = inliers.size() >= points.size()*0.95;
double rvecDiff = norm(rvec-trueRvec), tvecDiff = norm(tvec-trueTvec);
isTestSuccess = isTestSuccess && rvecDiff < epsilon[method] && tvecDiff < epsilon[method];
double error = rvecDiff > tvecDiff ? rvecDiff : tvecDiff;
//cout << error << " " << inliers.size() << " " << eps[method] << endl;
if (error > maxError)
maxError = error;
return isTestSuccess;
}
void run(int)
{
ts->set_failed_test_info(cvtest::TS::OK);
vector<Point3f> points;
const int pointsCount = 500;
points.resize(pointsCount);
generate3DPointCloud(points);
const int methodsCount = 3;
RNG rng = ts->get_rng();
for (int mode = 0; mode < 2; mode++)
{
for (int method = 0; method < methodsCount; method++)
{
double maxError = 0;
int successfulTestsCount = 0;
for (int testIndex = 0; testIndex < totalTestsCount; testIndex++)
{
if (runTest(rng, mode, method, points, eps, maxError))
successfulTestsCount++;
}
//cout << maxError << " " << successfulTestsCount << endl;
if (successfulTestsCount < 0.7*totalTestsCount)
{
ts->printf( cvtest::TS::LOG, "Invalid accuracy for method %d, failed %d tests from %d, maximum error equals %f, distortion mode equals %d\n",
method, totalTestsCount - successfulTestsCount, totalTestsCount, maxError, mode);
ts->set_failed_test_info(cvtest::TS::FAIL_BAD_ACCURACY);
}
}
}
}
double eps[3];
int totalTestsCount;
};
class CV_solvePnP_Test : public CV_solvePnPRansac_Test
{
public:
CV_solvePnP_Test()
{
eps[CV_ITERATIVE] = 1.0e-6;
eps[CV_EPNP] = 1.0e-6;
eps[CV_P3P] = 1.0e-4;
totalTestsCount = 1000;
}
~CV_solvePnP_Test() {}
protected:
virtual bool runTest(RNG& rng, int mode, int method, const vector<Point3f>& points, const double* epsilon, double& maxError)
{
Mat rvec, tvec;
Mat trueRvec, trueTvec;
Mat intrinsics, distCoeffs;
generateCameraMatrix(intrinsics, rng);
if (mode == 0)
distCoeffs = Mat::zeros(4, 1, CV_64FC1);
else
generateDistCoeffs(distCoeffs, rng);
generatePose(trueRvec, trueTvec, rng);
std::vector<Point3f> opoints;
if (method == 2)
{
opoints = std::vector<Point3f>(points.begin(), points.begin()+4);
}
else
opoints = points;
vector<Point2f> projectedPoints;
projectedPoints.resize(opoints.size());
projectPoints(Mat(opoints), trueRvec, trueTvec, intrinsics, distCoeffs, projectedPoints);
solvePnP(opoints, projectedPoints, intrinsics, distCoeffs, rvec, tvec,
false, method);
double rvecDiff = norm(rvec-trueRvec), tvecDiff = norm(tvec-trueTvec);
bool isTestSuccess = rvecDiff < epsilon[method] && tvecDiff < epsilon[method];
double error = rvecDiff > tvecDiff ? rvecDiff : tvecDiff;
if (error > maxError)
maxError = error;
return isTestSuccess;
}
};
TEST(Calib3d_SolvePnPRansac, accuracy) { CV_solvePnPRansac_Test test; test.safe_run(); }
TEST(Calib3d_SolvePnP, accuracy) { CV_solvePnP_Test test; test.safe_run(); }
#ifdef HAVE_TBB
TEST(DISABLED_Calib3d_SolvePnPRansac, concurrency)
{
int count = 7*13;
Mat object(1, count, CV_32FC3);
randu(object, -100, 100);
Mat camera_mat(3, 3, CV_32FC1);
randu(camera_mat, 0.5, 1);
camera_mat.at<float>(0, 1) = 0.f;
camera_mat.at<float>(1, 0) = 0.f;
camera_mat.at<float>(2, 0) = 0.f;
camera_mat.at<float>(2, 1) = 0.f;
Mat dist_coef(1, 8, CV_32F, cv::Scalar::all(0));
vector<cv::Point2f> image_vec;
Mat rvec_gold(1, 3, CV_32FC1);
randu(rvec_gold, 0, 1);
Mat tvec_gold(1, 3, CV_32FC1);
randu(tvec_gold, 0, 1);
projectPoints(object, rvec_gold, tvec_gold, camera_mat, dist_coef, image_vec);
Mat image(1, count, CV_32FC2, &image_vec[0]);
Mat rvec1, rvec2;
Mat tvec1, tvec2;
{
// limit concurrency to get determenistic result
cv::theRNG().state = 20121010;
cv::Ptr<tbb::task_scheduler_init> one_thread = new tbb::task_scheduler_init(1);
solvePnPRansac(object, image, camera_mat, dist_coef, rvec1, tvec1);
}
if(1)
{
Mat rvec;
Mat tvec;
// parallel executions
for(int i = 0; i < 10; ++i)
{
cv::theRNG().state = 20121010;
solvePnPRansac(object, image, camera_mat, dist_coef, rvec, tvec);
}
}
{
// single thread again
cv::theRNG().state = 20121010;
cv::Ptr<tbb::task_scheduler_init> one_thread = new tbb::task_scheduler_init(1);
solvePnPRansac(object, image, camera_mat, dist_coef, rvec2, tvec2);
}
double rnorm = cv::norm(rvec1, rvec2, NORM_INF);
double tnorm = cv::norm(tvec1, tvec2, NORM_INF);
EXPECT_LT(rnorm, 1e-6);
EXPECT_LT(tnorm, 1e-6);
}
#endif
|
Add concurrency test for solvePnPRansac
|
Add concurrency test for solvePnPRansac
|
C++
|
apache-2.0
|
opencv/opencv,opencv/opencv,apavlenko/opencv,opencv/opencv,apavlenko/opencv,apavlenko/opencv,opencv/opencv,apavlenko/opencv,apavlenko/opencv,opencv/opencv,opencv/opencv,apavlenko/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv
|
9a39fe9f3c66223ddac82caaa2e72171c21b963b
|
uwsgiEngine/engineuwsgi.cpp
|
uwsgiEngine/engineuwsgi.cpp
|
/*
* Copyright (C) 2013-2015 Daniel Nicoletti <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "engineuwsgi.h"
#include "bodyuwsgi.h"
#include "bodybuffereduwsgi.h"
#include <QtCore/QSocketNotifier>
#include <QtCore/QCoreApplication>
#include <Cutelyst/common.h>
#include <Cutelyst/application.h>
#include <Cutelyst/context.h>
#include <Cutelyst/response.h>
#include <Cutelyst/request_p.h>
Q_LOGGING_CATEGORY(CUTELYST_UWSGI, "cutelyst.uwsgi")
using namespace Cutelyst;
typedef struct {
QFile *bodyFile;
BodyUWSGI *bodyUWSGI;
BodyBufferedUWSGI *bodyBufferedUWSGI;
RequestPrivate *priv;
Request *request;
} CachedRequest;
uWSGI::uWSGI(const QVariantHash &opts, Application *app, QObject *parent) : Engine(opts, parent)
, m_app(app)
{
connect(this, &uWSGI::postFork,
this, &uWSGI::forked);
}
uWSGI::~uWSGI()
{
}
void uWSGI::setThread(QThread *thread)
{
moveToThread(thread);
connect(thread, &QThread::started,
this, &uWSGI::forked, Qt::DirectConnection);
}
qint64 uWSGI::doWrite(Context *c, const char *data, qint64 len, void *engineData)
{
if (uwsgi_response_write_body_do(static_cast<wsgi_request*>(engineData),
const_cast<char *>(data),
len) != UWSGI_OK) {
qCWarning(CUTELYST_UWSGI) << "Failed to write body";
return -1;
}
return len;
}
void uWSGI::readRequestUWSGI(wsgi_request *wsgi_req)
{
for(;;) {
int ret = uwsgi_wait_read_req(wsgi_req);
if (ret <= 0) {
uwsgi_log("Failed wait read\n");
goto end;
}
int status = wsgi_req->socket->proto(wsgi_req);
if (status < 0) {
uwsgi_log("Failed broken socket\n");
goto end;
} else if (status == 0) {
break;
}
}
// empty request ?
if (!wsgi_req->uh->pktsize) {
qCDebug(CUTELYST_UWSGI) << "Empty request. skip.";
uwsgi_log("Failed empty request\n");
goto end;
}
// get uwsgi variables
if (uwsgi_parse_vars(wsgi_req)) {
uwsgi_log("Invalid request. skip.\n");
qCDebug(CUTELYST_UWSGI) << "Invalid request. skip.";
goto end;
}
processRequest(wsgi_req);
end:
uwsgi_close_request(wsgi_req);
}
void uWSGI::processRequest(wsgi_request *req)
{
CachedRequest *cache = static_cast<CachedRequest *>(req->async_environ);
RequestPrivate *priv = cache->priv;
priv->reset();
priv->startOfRequest = req->start_of_request;
priv->https = req->https_len;
// wsgi_req->uri containg the whole URI it /foo/bar?query=null
// so we use path_info, maybe it would be better to just build our
// Request->uri() from it, but we need to run a performance test
if (req->path_info_len) {
priv->path = QString::fromLatin1(req->path_info + 1, req->path_info_len - 1);
} else {
priv->path = QString();
}
priv->serverAddress = QString::fromLatin1(req->host, req->host_len);
priv->query = QByteArray::fromRawData(req->query_string, req->query_string_len);
priv->method = QString::fromLatin1(req->method, req->method_len);
priv->protocol = QString::fromLatin1(req->protocol, req->protocol_len);
priv->remoteAddress = QHostAddress(QString::fromLatin1(req->remote_addr, req->remote_addr_len));
priv->remoteUser = QString::fromLatin1(req->remote_user, req->remote_user_len);
uint16_t remote_port_len;
char *remote_port = uwsgi_get_var(req, (char *) "REMOTE_PORT", 11, &remote_port_len);
priv->remotePort = QByteArray::fromRawData(remote_port, remote_port_len).toUInt();
Headers headers;
for (int i = 0; i < req->var_cnt; i += 2) {
if (req->hvec[i].iov_len < 6) {
continue;
}
if (!uwsgi_startswith((char *) req->hvec[i].iov_base,
const_cast<char *>("HTTP_"), 5)) {
headers.setHeader(QString::fromLatin1((char *) req->hvec[i].iov_base+5, req->hvec[i].iov_len-5),
QString::fromLatin1((char *) req->hvec[i + 1].iov_base, req->hvec[i + 1].iov_len));
}
}
if (req->content_type_len > 0) {
headers.setContentType(QString::fromLatin1(req->content_type, req->content_type_len));
}
if (req->encoding_len > 0) {
headers.setContentEncoding(QString::fromLatin1(req->encoding, req->encoding_len));
}
priv->headers = headers;
QIODevice *body;
if (req->post_file) {
// qCDebug(CUTELYST_UWSGI) << "Post file available:" << req->post_file;
QFile *upload = cache->bodyFile;
if (upload->open(req->post_file, QIODevice::ReadOnly)) {
body = upload;
} else {
// qCDebug(CUTELYST_UWSGI) << "Could not open post file:" << upload->errorString();
body = cache->bodyBufferedUWSGI;
}
} else if (uwsgi.post_buffering) {
// qCDebug(CUTELYST_UWSGI) << "Post buffering size:" << uwsgi.post_buffering;
body = cache->bodyUWSGI;
} else {
// BodyBufferedUWSGI is an IO device which will
// only consume the body when some of it's functions
// is called, this is because here we can't seek
// the body.
body = cache->bodyBufferedUWSGI;
}
priv->body = body;
handleRequest(cache->request, false);
body->close();
}
void uWSGI::reload()
{
qCDebug(CUTELYST_UWSGI) << "Reloading application due application request";
uwsgi_reload(uwsgi.argv);
}
void uWSGI::addUnusedRequest(wsgi_request *wsgi_req)
{
CachedRequest *cache = static_cast<CachedRequest *>(wsgi_req->async_environ);
if (cache) {
// TODO move to a class
delete cache;
}
cache = new CachedRequest;
cache->bodyFile = new QFile(this);
cache->bodyUWSGI = new BodyUWSGI(wsgi_req, this);
cache->bodyBufferedUWSGI = new BodyBufferedUWSGI(wsgi_req, this);
cache->priv = new RequestPrivate;
cache->priv->engine = this;
cache->priv->requestPtr = wsgi_req;
cache->request = new Request(cache->priv);
wsgi_req->async_environ = cache;
m_unusedReq.append(wsgi_req);
}
void uWSGI::watchSocket(struct uwsgi_socket *uwsgi_sock)
{
QSocketNotifier *socketNotifier = new QSocketNotifier(uwsgi_sock->fd, QSocketNotifier::Read, this);
connect(this, &uWSGI::enableSockets,
socketNotifier, &QSocketNotifier::setEnabled);
connect(socketNotifier, &QSocketNotifier::activated,
[=](int fd) {
struct wsgi_request *wsgi_req = m_unusedReq.takeFirst();
if (wsgi_req == NULL) {
uwsgi_async_queue_is_full(uwsgi_now());
return;
}
// fill wsgi_request structure
wsgi_req_setup(wsgi_req, wsgi_req->async_id, uwsgi_sock);
// mark core as used
uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].in_request = 1;
// accept the connection
if (wsgi_req_simple_accept(wsgi_req, fd) != 0) {
uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].in_request = 0;
m_unusedReq.append(wsgi_req);
return;
}
wsgi_req->start_of_request = uwsgi_micros();
wsgi_req->start_of_request_in_sec = wsgi_req->start_of_request/1000000;
#ifdef UWSGI_GO_CHEAP_CODE
// enter harakiri mode
if (uwsgi.harakiri_options.workers > 0) {
set_harakiri(uwsgi.harakiri_options.workers);
}
#endif // UWSGI_GO_CHEAP_CODE
CachedRequest *cache = static_cast<CachedRequest *>(wsgi_req->async_environ);
readRequestUWSGI(wsgi_req);
wsgi_req->async_environ = cache;
m_unusedReq.append(wsgi_req);
});
}
void uWSGI::reuseEngineRequests(uWSGI *engine)
{
Q_FOREACH (struct wsgi_request *req, engine->unusedRequestQueue()) {
addUnusedRequest(req);
}
}
void uWSGI::stop()
{
Q_EMIT enableSockets(false);
if (thread() != qApp->thread()) {
thread()->quit();
}
}
QList<wsgi_request *> uWSGI::unusedRequestQueue() const
{
return m_unusedReq;
}
quint64 uWSGI::time()
{
return uwsgi_micros();
}
bool uWSGI::finalizeHeaders(Context *ctx)
{
struct wsgi_request *wsgi_req = static_cast<wsgi_request*>(ctx->request()->engineData());
Response *res = ctx->res();
QByteArray status = statusCode(res->status());
if (uwsgi_response_prepare_headers(wsgi_req,
status.data(),
status.size())) {
return false;
}
if (!Engine::finalizeHeaders(ctx)) {
return false;
}
const Headers &headers = res->headers();
QHash<QString, QString>::ConstIterator it = headers.constBegin();
QHash<QString, QString>::ConstIterator end = headers.constEnd();
while (it != end) {
QByteArray key = camelCaseHeader(it.key()).toLatin1();
QByteArray value = it.value().toLatin1();
if (uwsgi_response_add_header(wsgi_req,
key.data(),
key.size(),
value.data(),
value.size())) {
return false;
}
++it;
}
return true;
}
bool uWSGI::init()
{
return true;
}
void uWSGI::forked()
{
if (QThread::currentThread() != qApp->thread()) {
m_app = qobject_cast<Application *>(m_app->metaObject()->newInstance());
if (!m_app) {
uwsgi_log("*** FATAL *** Could not create a NEW instance of your Cutelyst::Application, "
"make sure your constructor has Q_INVOKABLE macro.\n");
Q_EMIT engineDisabled(this);
return;
}
// Move the application and it's children to this thread
m_app->moveToThread(thread());
// We can now set a parent
m_app->setParent(this);
// init and postfork
if (!initApplication(m_app, true)) {
uwsgi_log("Failed to init application on a different thread than main.\n");
Q_EMIT engineDisabled(this);
return;
}
} else if (!postForkApplication()) {
#ifdef UWSGI_GO_CHEAP_CODE
// We need to tell the master process that the
// application failed to setup and that it shouldn't
// try to respawn the worker
exit(UWSGI_GO_CHEAP_CODE);
#endif // UWSGI_GO_CHEAP_CODE
}
if (!m_unusedReq.isEmpty()) {
// Start Monitoring Sockets
struct uwsgi_socket *uwsgi_sock = uwsgi.sockets;
while(uwsgi_sock) {
watchSocket(uwsgi_sock);
uwsgi_sock = uwsgi_sock->next;
}
}
}
|
/*
* Copyright (C) 2013-2015 Daniel Nicoletti <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "engineuwsgi.h"
#include "bodyuwsgi.h"
#include "bodybuffereduwsgi.h"
#include <QtCore/QSocketNotifier>
#include <QtCore/QCoreApplication>
#include <Cutelyst/common.h>
#include <Cutelyst/application.h>
#include <Cutelyst/context.h>
#include <Cutelyst/response.h>
#include <Cutelyst/request_p.h>
Q_LOGGING_CATEGORY(CUTELYST_UWSGI, "cutelyst.uwsgi")
using namespace Cutelyst;
typedef struct {
QFile *bodyFile;
BodyUWSGI *bodyUWSGI;
BodyBufferedUWSGI *bodyBufferedUWSGI;
RequestPrivate *priv;
Request *request;
} CachedRequest;
uWSGI::uWSGI(const QVariantHash &opts, Application *app, QObject *parent) : Engine(opts, parent)
, m_app(app)
{
connect(this, &uWSGI::postFork,
this, &uWSGI::forked);
}
uWSGI::~uWSGI()
{
}
void uWSGI::setThread(QThread *thread)
{
moveToThread(thread);
connect(thread, &QThread::started,
this, &uWSGI::forked, Qt::DirectConnection);
}
qint64 uWSGI::doWrite(Context *c, const char *data, qint64 len, void *engineData)
{
if (uwsgi_response_write_body_do(static_cast<wsgi_request*>(engineData),
const_cast<char *>(data),
len) != UWSGI_OK) {
qCWarning(CUTELYST_UWSGI) << "Failed to write body";
return -1;
}
return len;
}
void uWSGI::readRequestUWSGI(wsgi_request *wsgi_req)
{
for(;;) {
int ret = uwsgi_wait_read_req(wsgi_req);
if (ret <= 0) {
qCDebug(CUTELYST_UWSGI) << "Failed wait read.";
goto end;
}
int status = wsgi_req->socket->proto(wsgi_req);
if (status < 0) {
qCDebug(CUTELYST_UWSGI) << "Failed broken socket.";
goto end;
} else if (status == 0) {
break;
}
}
// empty request ?
if (!wsgi_req->uh->pktsize) {
qCDebug(CUTELYST_UWSGI) << "Empty request. skip.";
goto end;
}
// get uwsgi variables
if (uwsgi_parse_vars(wsgi_req)) {
// If static maps are set or there is some error
// this returns -1 so we just close the request
goto end;
}
processRequest(wsgi_req);
end:
uwsgi_close_request(wsgi_req);
}
void uWSGI::processRequest(wsgi_request *req)
{
CachedRequest *cache = static_cast<CachedRequest *>(req->async_environ);
RequestPrivate *priv = cache->priv;
priv->reset();
priv->startOfRequest = req->start_of_request;
priv->https = req->https_len;
// wsgi_req->uri containg the whole URI it /foo/bar?query=null
// so we use path_info, maybe it would be better to just build our
// Request->uri() from it, but we need to run a performance test
if (req->path_info_len) {
priv->path = QString::fromLatin1(req->path_info + 1, req->path_info_len - 1);
} else {
priv->path = QString();
}
priv->serverAddress = QString::fromLatin1(req->host, req->host_len);
priv->query = QByteArray::fromRawData(req->query_string, req->query_string_len);
priv->method = QString::fromLatin1(req->method, req->method_len);
priv->protocol = QString::fromLatin1(req->protocol, req->protocol_len);
priv->remoteAddress = QHostAddress(QString::fromLatin1(req->remote_addr, req->remote_addr_len));
priv->remoteUser = QString::fromLatin1(req->remote_user, req->remote_user_len);
uint16_t remote_port_len;
char *remote_port = uwsgi_get_var(req, (char *) "REMOTE_PORT", 11, &remote_port_len);
priv->remotePort = QByteArray::fromRawData(remote_port, remote_port_len).toUInt();
Headers headers;
for (int i = 0; i < req->var_cnt; i += 2) {
if (req->hvec[i].iov_len < 6) {
continue;
}
if (!uwsgi_startswith((char *) req->hvec[i].iov_base,
const_cast<char *>("HTTP_"), 5)) {
headers.setHeader(QString::fromLatin1((char *) req->hvec[i].iov_base+5, req->hvec[i].iov_len-5),
QString::fromLatin1((char *) req->hvec[i + 1].iov_base, req->hvec[i + 1].iov_len));
}
}
if (req->content_type_len > 0) {
headers.setContentType(QString::fromLatin1(req->content_type, req->content_type_len));
}
if (req->encoding_len > 0) {
headers.setContentEncoding(QString::fromLatin1(req->encoding, req->encoding_len));
}
priv->headers = headers;
QIODevice *body;
if (req->post_file) {
// qCDebug(CUTELYST_UWSGI) << "Post file available:" << req->post_file;
QFile *upload = cache->bodyFile;
if (upload->open(req->post_file, QIODevice::ReadOnly)) {
body = upload;
} else {
// qCDebug(CUTELYST_UWSGI) << "Could not open post file:" << upload->errorString();
body = cache->bodyBufferedUWSGI;
}
} else if (uwsgi.post_buffering) {
// qCDebug(CUTELYST_UWSGI) << "Post buffering size:" << uwsgi.post_buffering;
body = cache->bodyUWSGI;
} else {
// BodyBufferedUWSGI is an IO device which will
// only consume the body when some of it's functions
// is called, this is because here we can't seek
// the body.
body = cache->bodyBufferedUWSGI;
}
priv->body = body;
handleRequest(cache->request, false);
body->close();
}
void uWSGI::reload()
{
qCDebug(CUTELYST_UWSGI) << "Reloading application due application request";
uwsgi_reload(uwsgi.argv);
}
void uWSGI::addUnusedRequest(wsgi_request *wsgi_req)
{
CachedRequest *cache = static_cast<CachedRequest *>(wsgi_req->async_environ);
if (cache) {
// TODO move to a class
delete cache;
}
cache = new CachedRequest;
cache->bodyFile = new QFile(this);
cache->bodyUWSGI = new BodyUWSGI(wsgi_req, this);
cache->bodyBufferedUWSGI = new BodyBufferedUWSGI(wsgi_req, this);
cache->priv = new RequestPrivate;
cache->priv->engine = this;
cache->priv->requestPtr = wsgi_req;
cache->request = new Request(cache->priv);
wsgi_req->async_environ = cache;
m_unusedReq.append(wsgi_req);
}
void uWSGI::watchSocket(struct uwsgi_socket *uwsgi_sock)
{
QSocketNotifier *socketNotifier = new QSocketNotifier(uwsgi_sock->fd, QSocketNotifier::Read, this);
connect(this, &uWSGI::enableSockets,
socketNotifier, &QSocketNotifier::setEnabled);
connect(socketNotifier, &QSocketNotifier::activated,
[=](int fd) {
struct wsgi_request *wsgi_req = m_unusedReq.takeFirst();
if (wsgi_req == NULL) {
uwsgi_async_queue_is_full(uwsgi_now());
return;
}
// fill wsgi_request structure
wsgi_req_setup(wsgi_req, wsgi_req->async_id, uwsgi_sock);
// mark core as used
uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].in_request = 1;
// accept the connection
if (wsgi_req_simple_accept(wsgi_req, fd) != 0) {
uwsgi.workers[uwsgi.mywid].cores[wsgi_req->async_id].in_request = 0;
m_unusedReq.append(wsgi_req);
return;
}
wsgi_req->start_of_request = uwsgi_micros();
wsgi_req->start_of_request_in_sec = wsgi_req->start_of_request/1000000;
#ifdef UWSGI_GO_CHEAP_CODE
// enter harakiri mode
if (uwsgi.harakiri_options.workers > 0) {
set_harakiri(uwsgi.harakiri_options.workers);
}
#endif // UWSGI_GO_CHEAP_CODE
CachedRequest *cache = static_cast<CachedRequest *>(wsgi_req->async_environ);
readRequestUWSGI(wsgi_req);
wsgi_req->async_environ = cache;
m_unusedReq.append(wsgi_req);
});
}
void uWSGI::reuseEngineRequests(uWSGI *engine)
{
Q_FOREACH (struct wsgi_request *req, engine->unusedRequestQueue()) {
addUnusedRequest(req);
}
}
void uWSGI::stop()
{
Q_EMIT enableSockets(false);
if (thread() != qApp->thread()) {
thread()->quit();
}
}
QList<wsgi_request *> uWSGI::unusedRequestQueue() const
{
return m_unusedReq;
}
quint64 uWSGI::time()
{
return uwsgi_micros();
}
bool uWSGI::finalizeHeaders(Context *ctx)
{
struct wsgi_request *wsgi_req = static_cast<wsgi_request*>(ctx->request()->engineData());
Response *res = ctx->res();
QByteArray status = statusCode(res->status());
if (uwsgi_response_prepare_headers(wsgi_req,
status.data(),
status.size())) {
return false;
}
if (!Engine::finalizeHeaders(ctx)) {
return false;
}
const Headers &headers = res->headers();
QHash<QString, QString>::ConstIterator it = headers.constBegin();
QHash<QString, QString>::ConstIterator end = headers.constEnd();
while (it != end) {
QByteArray key = camelCaseHeader(it.key()).toLatin1();
QByteArray value = it.value().toLatin1();
if (uwsgi_response_add_header(wsgi_req,
key.data(),
key.size(),
value.data(),
value.size())) {
return false;
}
++it;
}
return true;
}
bool uWSGI::init()
{
return true;
}
void uWSGI::forked()
{
if (QThread::currentThread() != qApp->thread()) {
m_app = qobject_cast<Application *>(m_app->metaObject()->newInstance());
if (!m_app) {
uwsgi_log("*** FATAL *** Could not create a NEW instance of your Cutelyst::Application, "
"make sure your constructor has Q_INVOKABLE macro.\n");
Q_EMIT engineDisabled(this);
return;
}
// Move the application and it's children to this thread
m_app->moveToThread(thread());
// We can now set a parent
m_app->setParent(this);
// init and postfork
if (!initApplication(m_app, true)) {
uwsgi_log("Failed to init application on a different thread than main.\n");
Q_EMIT engineDisabled(this);
return;
}
} else if (!postForkApplication()) {
#ifdef UWSGI_GO_CHEAP_CODE
// We need to tell the master process that the
// application failed to setup and that it shouldn't
// try to respawn the worker
exit(UWSGI_GO_CHEAP_CODE);
#endif // UWSGI_GO_CHEAP_CODE
}
if (!m_unusedReq.isEmpty()) {
// Start Monitoring Sockets
struct uwsgi_socket *uwsgi_sock = uwsgi.sockets;
while(uwsgi_sock) {
watchSocket(uwsgi_sock);
uwsgi_sock = uwsgi_sock->next;
}
}
}
|
Change debug info to now show on uWSGI static maps
|
Change debug info to now show on uWSGI static maps
|
C++
|
bsd-3-clause
|
buschmann23/cutelyst,buschmann23/cutelyst,cutelyst/cutelyst,buschmann23/cutelyst,cutelyst/cutelyst,simonaw/cutelyst,cutelyst/cutelyst,simonaw/cutelyst
|
69c6dca19fe843c2509ea5c9f1634401aecbf12d
|
dune/stuff/common/vector.hh
|
dune/stuff/common/vector.hh
|
// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_STUFF_TOOLS_COMMON_VECTOR_HH
#define DUNE_STUFF_TOOLS_COMMON_VECTOR_HH
#include <vector>
#include <ostream>
#include <dune/common/dynvector.hh>
#include <dune/common/fvector.hh>
#include <dune/common/ftraits.hh>
#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/fvector.hh>
#include <dune/stuff/common/type_utils.hh>
namespace Dune {
namespace Stuff {
namespace Common {
template< class VecType >
struct VectorAbstraction;
//! logically and structurally this belongs in type_utils.hh, but the dependent implementation prohibits that
template< class VectorType >
struct is_vector
{
static const bool value = VectorAbstraction< VectorType >::is_vector;
};
/**
* \brief Traits to statically extract information of a (mathematical) vector.
*
* If you want your vector class to benefit from the operators defined in this header you have to manually
* specify a specialization of this class in your code with is_vector defined to true and an appropriate
* static methods and members (see the specializations below).
*/
template< class VecType >
struct VectorAbstraction
{
typedef VecType VectorType;
typedef VecType ScalarType;
typedef VecType RealType;
typedef typename Dune::FieldTraits< VecType >::field_type S;
typedef typename Dune::FieldTraits< VecType >::real_type R;
static const bool is_vector = false;
static const bool has_static_size = false;
static const size_t static_size = std::numeric_limits< size_t >::max();
static inline /*VectorType*/void create(const size_t /*sz*/)
{
static_assert(AlwaysFalse< VecType >::value, "Do not call me if is_vector is false!");
}
static inline /*VectorType*/void create(const size_t /*sz*/, const ScalarType& /*val*/)
{
static_assert(AlwaysFalse< VecType >::value, "Do not call me if is_vector is false!");
}
};
template< class T >
struct VectorAbstraction< std::vector< T > >
{
typedef std::vector< T > VectorType;
typedef typename Dune::FieldTraits< T >::field_type ScalarType;
typedef typename Dune::FieldTraits< T >::real_type RealType;
typedef ScalarType S;
typedef RealType R;
static const bool is_vector = true;
static const bool has_static_size = false;
static const size_t static_size = std::numeric_limits< size_t >::max();
static inline VectorType create(const size_t sz)
{
return VectorType(sz);
}
static inline VectorType create(const size_t sz, const ScalarType& val)
{
return VectorType(sz, val);
}
};
template< class K >
struct VectorAbstraction< Dune::DynamicVector< K > >
{
typedef Dune::DynamicVector< K > VectorType;
typedef typename Dune::FieldTraits< K >::field_type ScalarType;
typedef typename Dune::FieldTraits< K >::real_type RealType;
typedef ScalarType S;
typedef RealType R;
static const bool is_vector = true;
static const bool has_static_size = false;
static const size_t static_size = std::numeric_limits< size_t >::max();
static inline VectorType create(const size_t sz)
{
return VectorType(sz);
}
static inline VectorType create(const size_t sz, const ScalarType& val)
{
return VectorType(sz, val);
}
};
template< class K, int SIZE >
struct VectorAbstraction< Dune::FieldVector< K, SIZE > >
{
typedef Dune::FieldVector< K, SIZE > VectorType;
typedef typename Dune::FieldTraits< K >::field_type ScalarType;
typedef typename Dune::FieldTraits< K >::real_type RealType;
typedef ScalarType S;
typedef RealType R;
static const bool is_vector = true;
static const bool has_static_size = true;
static const size_t static_size = SIZE;
static inline VectorType create(const size_t sz)
{
if (sz != SIZE)
DUNE_THROW(Dune::Stuff::Exceptions::shapes_do_not_match,
"sz = " << sz << "\nSIZE = " << int(SIZE));
return VectorType();
}
static inline VectorType create(const size_t sz, const ScalarType& val)
{
if (sz != SIZE)
DUNE_THROW(Dune::Stuff::Exceptions::shapes_do_not_match,
"sz = " << sz << "\nSIZE = " << int(SIZE));
return VectorType(val);
}
};
template< class K, int SIZE >
struct VectorAbstraction< Dune::Stuff::Common::FieldVector< K, SIZE > >
{
typedef Dune::Stuff::Common::FieldVector< K, SIZE > VectorType;
typedef typename Dune::FieldTraits< K >::field_type ScalarType;
typedef typename Dune::FieldTraits< K >::real_type RealType;
typedef ScalarType S;
typedef RealType R;
static const bool is_vector = true;
static const bool has_static_size = true;
static const size_t static_size = SIZE;
static inline VectorType create(const size_t sz)
{
return VectorType(sz);
}
static inline VectorType create(const size_t sz, const ScalarType& val)
{
return VectorType(sz, val);
}
};
template< class VectorType >
typename std::enable_if< is_vector< VectorType >::value, VectorType >::type
create(const size_t sz,
const typename VectorAbstraction< VectorType >::S& val = typename VectorAbstraction< VectorType >::S(0))
{
return VectorAbstraction< VectorType >::create(sz, val);
}
} // namespace Common
} // namespace Stuff
} // namespace Dune
template< class L, class R >
inline
typename std::enable_if< Dune::Stuff::Common::is_vector< L >::value
&& Dune::Stuff::Common::is_vector< R >::value
, bool >::value
DUNE_DEPRECATED_MSG("vector operator overloads to be removed. If you want FloatCmp bevahior cal the appropiate DSC::FloatCmp::XX function instead")
operator<(const L& lhs, const R& rhs)
{
return Dune::Stuff::Common::FloatCmp::lt(lhs, rhs);
}
template< class L, class R >
inline
typename std::enable_if< Dune::Stuff::Common::is_vector< L >::value
&& Dune::Stuff::Common::is_vector< R >::value
, bool >::value
DUNE_DEPRECATED_MSG("vector operator overloads to be removed. If you want FloatCmp bevahior cal the appropiate DSC::FloatCmp::XX function instead")
operator>(const L& lhs, const R& rhs)
{
return Dune::Stuff::Common::FloatCmp::gt(lhs, rhs);
}
template< class L, class R >
inline
typename std::enable_if< Dune::Stuff::Common::is_vector< L >::value
&& Dune::Stuff::Common::is_vector< R >::value
, bool >::value
DUNE_DEPRECATED_MSG("vector operator overloads to be removed. If you want FloatCmp bevahior cal the appropiate DSC::FloatCmp::XX function instead")
operator<=(const L& lhs, const R& rhs)
{
return Dune::Stuff::Common::FloatCmp::le(lhs, rhs);
}
template< class L, class R >
inline
typename std::enable_if< Dune::Stuff::Common::is_vector< L >::value
&& Dune::Stuff::Common::is_vector< R >::value
, bool >::value
DUNE_DEPRECATED_MSG("vector operator overloads to be removed. If you want FloatCmp bevahior cal the appropiate DSC::FloatCmp::XX function instead")
operator>=(const L& lhs, const R& rhs)
{
return Dune::Stuff::Common::FloatCmp::ge(lhs, rhs);
}
template< class L, class R >
inline
typename std::enable_if< Dune::Stuff::Common::is_vector< L >::value
&& Dune::Stuff::Common::is_vector< R >::value
, bool >::value
DUNE_DEPRECATED_MSG("vector operator overloads to be removed. If you want FloatCmp bevahior cal the appropiate DSC::FloatCmp::XX function instead")
operator==(const L& lhs, const R& rhs)
{
return Dune::Stuff::Common::FloatCmp::eq(lhs, rhs);
}
template< class L, class R >
inline
typename std::enable_if< Dune::Stuff::Common::is_vector< L >::value
&& Dune::Stuff::Common::is_vector< R >::value
, bool >::value
DUNE_DEPRECATED_MSG("vector operator overloads to be removed. If you want FloatCmp bevahior cal the appropiate DSC::FloatCmp::XX function instead")
operator!=(const L& lhs, const R& rhs)
{
return Dune::Stuff::Common::FloatCmp::ne(lhs, rhs);
}
template< class S, class V >
typename std::enable_if< std::is_arithmetic< S >::value && Dune::Stuff::Common::is_vector< V >::value , V >::type
operator*(const S& scalar, const V& vec)
{
V result(vec);
for (size_t ii = 0; ii < vec.size(); ++ii)
result[ii] *= scalar;
return result;
} // ... operator*(...)
template< class L, class R >
typename std::enable_if< Dune::Stuff::Common::is_vector< L >::value
&& Dune::Stuff::Common::is_vector< R >::value
&& std::is_same< typename Dune::Stuff::Common::VectorAbstraction< L >::S
, typename Dune::Stuff::Common::VectorAbstraction< R >::S >::value
, L >::type
operator+(const L& left, const R& right)
{
const auto sz = left.size();
if (right.size() != sz)
DUNE_THROW(Dune::Stuff::Exceptions::shapes_do_not_match,
"left.size() = " << sz << "\nright.size() = " << right.size());
L result(left);
for (size_t ii = 0; ii < sz; ++ii)
result[ii] += right[ii];
return result;
} // ... operator+(...)
template< class V >
typename std::enable_if< Dune::Stuff::Common::is_vector< V >::value, std::ostream& >::type
operator<<(std::ostream& out, const V& vec)
{
if (vec.size() == 0)
out << "[]";
else if (vec.size() == 1)
out << vec[0];
else {
out << "[" << vec[0];
for (decltype(vec.size()) ii = 1; ii < vec.size(); ++ii)
out << " " << vec[ii];
out << "]";
}
return out;
} // ... operator<<(...)
#endif // DUNE_STUFF_TOOLS_COMMON_VECTOR_HH
|
// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_STUFF_TOOLS_COMMON_VECTOR_HH
#define DUNE_STUFF_TOOLS_COMMON_VECTOR_HH
#include <vector>
#include <ostream>
#include <dune/common/dynvector.hh>
#include <dune/common/fvector.hh>
#include <dune/common/ftraits.hh>
#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/fvector.hh>
#include <dune/stuff/common/type_utils.hh>
#include <dune/stuff/common/float_cmp.hh>
namespace Dune {
namespace Stuff {
namespace Common {
template< class VecType >
struct VectorAbstraction;
//! logically and structurally this belongs in type_utils.hh, but the dependent implementation prohibits that
template< class VectorType >
struct is_vector
{
static const bool value = VectorAbstraction< VectorType >::is_vector;
};
/**
* \brief Traits to statically extract information of a (mathematical) vector.
*
* If you want your vector class to benefit from the operators defined in this header you have to manually
* specify a specialization of this class in your code with is_vector defined to true and an appropriate
* static methods and members (see the specializations below).
*/
template< class VecType >
struct VectorAbstraction
{
typedef VecType VectorType;
typedef VecType ScalarType;
typedef VecType RealType;
typedef typename Dune::FieldTraits< VecType >::field_type S;
typedef typename Dune::FieldTraits< VecType >::real_type R;
static const bool is_vector = false;
static const bool has_static_size = false;
static const size_t static_size = std::numeric_limits< size_t >::max();
static inline /*VectorType*/void create(const size_t /*sz*/)
{
static_assert(AlwaysFalse< VecType >::value, "Do not call me if is_vector is false!");
}
static inline /*VectorType*/void create(const size_t /*sz*/, const ScalarType& /*val*/)
{
static_assert(AlwaysFalse< VecType >::value, "Do not call me if is_vector is false!");
}
};
template< class T >
struct VectorAbstraction< std::vector< T > >
{
typedef std::vector< T > VectorType;
typedef typename Dune::FieldTraits< T >::field_type ScalarType;
typedef typename Dune::FieldTraits< T >::real_type RealType;
typedef ScalarType S;
typedef RealType R;
static const bool is_vector = true;
static const bool has_static_size = false;
static const size_t static_size = std::numeric_limits< size_t >::max();
static inline VectorType create(const size_t sz)
{
return VectorType(sz);
}
static inline VectorType create(const size_t sz, const ScalarType& val)
{
return VectorType(sz, val);
}
};
template< class K >
struct VectorAbstraction< Dune::DynamicVector< K > >
{
typedef Dune::DynamicVector< K > VectorType;
typedef typename Dune::FieldTraits< K >::field_type ScalarType;
typedef typename Dune::FieldTraits< K >::real_type RealType;
typedef ScalarType S;
typedef RealType R;
static const bool is_vector = true;
static const bool has_static_size = false;
static const size_t static_size = std::numeric_limits< size_t >::max();
static inline VectorType create(const size_t sz)
{
return VectorType(sz);
}
static inline VectorType create(const size_t sz, const ScalarType& val)
{
return VectorType(sz, val);
}
};
template< class K, int SIZE >
struct VectorAbstraction< Dune::FieldVector< K, SIZE > >
{
typedef Dune::FieldVector< K, SIZE > VectorType;
typedef typename Dune::FieldTraits< K >::field_type ScalarType;
typedef typename Dune::FieldTraits< K >::real_type RealType;
typedef ScalarType S;
typedef RealType R;
static const bool is_vector = true;
static const bool has_static_size = true;
static const size_t static_size = SIZE;
static inline VectorType create(const size_t sz)
{
if (sz != SIZE)
DUNE_THROW(Dune::Stuff::Exceptions::shapes_do_not_match,
"sz = " << sz << "\nSIZE = " << int(SIZE));
return VectorType();
}
static inline VectorType create(const size_t sz, const ScalarType& val)
{
if (sz != SIZE)
DUNE_THROW(Dune::Stuff::Exceptions::shapes_do_not_match,
"sz = " << sz << "\nSIZE = " << int(SIZE));
return VectorType(val);
}
};
template< class K, int SIZE >
struct VectorAbstraction< Dune::Stuff::Common::FieldVector< K, SIZE > >
{
typedef Dune::Stuff::Common::FieldVector< K, SIZE > VectorType;
typedef typename Dune::FieldTraits< K >::field_type ScalarType;
typedef typename Dune::FieldTraits< K >::real_type RealType;
typedef ScalarType S;
typedef RealType R;
static const bool is_vector = true;
static const bool has_static_size = true;
static const size_t static_size = SIZE;
static inline VectorType create(const size_t sz)
{
return VectorType(sz);
}
static inline VectorType create(const size_t sz, const ScalarType& val)
{
return VectorType(sz, val);
}
};
template< class VectorType >
typename std::enable_if< is_vector< VectorType >::value, VectorType >::type
create(const size_t sz,
const typename VectorAbstraction< VectorType >::S& val = typename VectorAbstraction< VectorType >::S(0))
{
return VectorAbstraction< VectorType >::create(sz, val);
}
} // namespace Common
} // namespace Stuff
} // namespace Dune
template< class L, class R >
inline
typename std::enable_if< Dune::Stuff::Common::is_vector< L >::value
&& Dune::Stuff::Common::is_vector< R >::value
, bool >::value
DUNE_DEPRECATED_MSG("vector operator overloads to be removed. If you want FloatCmp bevahior cal the appropiate DSC::FloatCmp::XX function instead")
operator<(const L& lhs, const R& rhs)
{
return Dune::Stuff::Common::FloatCmp::lt(lhs, rhs);
}
template< class L, class R >
inline
typename std::enable_if< Dune::Stuff::Common::is_vector< L >::value
&& Dune::Stuff::Common::is_vector< R >::value
, bool >::value
DUNE_DEPRECATED_MSG("vector operator overloads to be removed. If you want FloatCmp bevahior cal the appropiate DSC::FloatCmp::XX function instead")
operator>(const L& lhs, const R& rhs)
{
return Dune::Stuff::Common::FloatCmp::gt(lhs, rhs);
}
template< class L, class R >
inline
typename std::enable_if< Dune::Stuff::Common::is_vector< L >::value
&& Dune::Stuff::Common::is_vector< R >::value
, bool >::value
DUNE_DEPRECATED_MSG("vector operator overloads to be removed. If you want FloatCmp bevahior cal the appropiate DSC::FloatCmp::XX function instead")
operator<=(const L& lhs, const R& rhs)
{
return Dune::Stuff::Common::FloatCmp::le(lhs, rhs);
}
template< class L, class R >
inline
typename std::enable_if< Dune::Stuff::Common::is_vector< L >::value
&& Dune::Stuff::Common::is_vector< R >::value
, bool >::value
DUNE_DEPRECATED_MSG("vector operator overloads to be removed. If you want FloatCmp bevahior cal the appropiate DSC::FloatCmp::XX function instead")
operator>=(const L& lhs, const R& rhs)
{
return Dune::Stuff::Common::FloatCmp::ge(lhs, rhs);
}
template< class L, class R >
inline
typename std::enable_if< Dune::Stuff::Common::is_vector< L >::value
&& Dune::Stuff::Common::is_vector< R >::value
, bool >::value
DUNE_DEPRECATED_MSG("vector operator overloads to be removed. If you want FloatCmp bevahior cal the appropiate DSC::FloatCmp::XX function instead")
operator==(const L& lhs, const R& rhs)
{
return Dune::Stuff::Common::FloatCmp::eq(lhs, rhs);
}
template< class L, class R >
inline
typename std::enable_if< Dune::Stuff::Common::is_vector< L >::value
&& Dune::Stuff::Common::is_vector< R >::value
, bool >::value
DUNE_DEPRECATED_MSG("vector operator overloads to be removed. If you want FloatCmp bevahior cal the appropiate DSC::FloatCmp::XX function instead")
operator!=(const L& lhs, const R& rhs)
{
return Dune::Stuff::Common::FloatCmp::ne(lhs, rhs);
}
template< class S, class V >
typename std::enable_if< std::is_arithmetic< S >::value && Dune::Stuff::Common::is_vector< V >::value , V >::type
operator*(const S& scalar, const V& vec)
{
V result(vec);
for (size_t ii = 0; ii < vec.size(); ++ii)
result[ii] *= scalar;
return result;
} // ... operator*(...)
template< class L, class R >
typename std::enable_if< Dune::Stuff::Common::is_vector< L >::value
&& Dune::Stuff::Common::is_vector< R >::value
&& std::is_same< typename Dune::Stuff::Common::VectorAbstraction< L >::S
, typename Dune::Stuff::Common::VectorAbstraction< R >::S >::value
, L >::type
operator+(const L& left, const R& right)
{
const auto sz = left.size();
if (right.size() != sz)
DUNE_THROW(Dune::Stuff::Exceptions::shapes_do_not_match,
"left.size() = " << sz << "\nright.size() = " << right.size());
L result(left);
for (size_t ii = 0; ii < sz; ++ii)
result[ii] += right[ii];
return result;
} // ... operator+(...)
template< class V >
typename std::enable_if< Dune::Stuff::Common::is_vector< V >::value, std::ostream& >::type
operator<<(std::ostream& out, const V& vec)
{
if (vec.size() == 0)
out << "[]";
else if (vec.size() == 1)
out << vec[0];
else {
out << "[" << vec[0];
for (decltype(vec.size()) ii = 1; ii < vec.size(); ++ii)
out << " " << vec[ii];
out << "]";
}
return out;
} // ... operator<<(...)
#endif // DUNE_STUFF_TOOLS_COMMON_VECTOR_HH
|
add missing include
|
[common.vector] add missing include
|
C++
|
bsd-2-clause
|
renemilk/DUNE-Stuff,renemilk/DUNE-Stuff,renemilk/DUNE-Stuff
|
32f95ad8e9668da8c65f914c28df4aac441250a6
|
tests/testjsondriver.cpp
|
tests/testjsondriver.cpp
|
/* This file is part of QJson
*
* Copyright (C) 2008 Flavio Castelli <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include <QtTest/QtTest>
#include "json_driver.h"
#include "serializer.h"
#include <QtCore/QVariant>
using namespace QJSon;
class TestJSonDriver: public QObject
{
Q_OBJECT
private slots:
void parseNonAsciiString();
void parseSimpleObject();
void parseEmptyObject();
void parseUrl();
void parseMultipleObject();
void parseSimpleArray();
void parseInvalidObject();
void parseMultipleArray();
void testTrueFalseNullValues();
void testEscapeChars();
void testNumbers();
void testReadWriteEmptyDocument();
void testSerialize();
void testSerialize_data();
void testReadWrite();
void testReadWrite_data();
};
Q_DECLARE_METATYPE(QVariant)
void TestJSonDriver::parseSimpleObject() {
QString json = "{\"foo\":\"bar\"}";
QVariantMap map;
map.insert ("foo", "bar");
QVariant expected(map);
JSonDriver driver;
bool ok;
QVariant result = driver.parse (json, &ok);
QVERIFY (ok);
QCOMPARE(result, expected);
}
void TestJSonDriver::parseEmptyObject() {
QString json = "{}";
QVariantMap map;
QVariant expected (map);
JSonDriver driver;
bool ok;
QVariant result = driver.parse (json, &ok);
QVERIFY (ok);
QCOMPARE(result, expected);
}
void TestJSonDriver::parseInvalidObject() {
QString json = "{\"foo\":\"bar\"";
JSonDriver driver;
bool ok;
QVariant result = driver.parse (json, &ok);
QVERIFY (!ok);
}
void TestJSonDriver::parseNonAsciiString() {
QString json = "{\"artist\":\"Queensr\\u00ffche\"}";
QVariantMap map;
QChar unicode_char (0x00ff);
QString unicode_string;
unicode_string.setUnicode(&unicode_char, 1);
unicode_string = "Queensr" + unicode_string + "che";
map.insert ("artist", unicode_string);
QVariant expected (map);
JSonDriver driver;
bool ok;
QVariant result = driver.parse (json, &ok);
QVERIFY (ok);
QCOMPARE(result, expected);
}
void TestJSonDriver::parseMultipleObject() {
//put also some extra spaces inside the json string
QString json = "{ \"foo\":\"bar\",\n\"number\" : 51.3 , \"array\":[\"item1\", 123]}";
QVariantMap map;
map.insert ("foo", "bar");
map.insert ("number", 51.3);
QVariantList list;
list.append (QString("item1"));
list.append (QString("123"));
map.insert ("array", list);
QVariant expected (map);
JSonDriver driver;
bool ok;
QVariant result = driver.parse (json, &ok);
QVERIFY (ok);
QCOMPARE(result, expected);
QVERIFY (result.toMap()["number"].canConvert<float>());
QVERIFY (result.toMap()["array"].canConvert<QVariantList>());
}
void TestJSonDriver::parseUrl(){
//"http:\/\/www.last.fm\/venue\/8926427"
QString json = "[\"http:\\/\\/www.last.fm\\/venue\\/8926427\"]";
QVariantList list;
list.append (QVariant(QString("http://www.last.fm/venue/8926427")));
QVariant expected (list);
JSonDriver driver;
bool ok;
QVariant result = driver.parse (json, &ok);
QVERIFY (ok);
QCOMPARE(result, expected);
}
void TestJSonDriver::parseSimpleArray() {
QString json = "[\"foo\",\"bar\"]";
QVariantList list;
list.append (QVariant(QString("foo")));
list.append (QVariant(QString("bar")));
QVariant expected (list);
JSonDriver driver;
bool ok;
QVariant result = driver.parse (json, &ok);
QVERIFY (ok);
QCOMPARE(result, expected);
}
void TestJSonDriver::parseMultipleArray() {
//put also some extra spaces inside the json string
QString json = "[ {\"foo\":\"bar\"},\n\"number\",51.3 , [\"item1\", 123]]";
QVariantMap map;
map.insert ("foo", "bar");
QVariantList array;
array.append (QString("item1"));
array.append (123);
QVariantList list;
list.append (map);
list.append (QString("number"));
list.append (QString("51.3"));
list.append ((QVariant) array);
QVariant expected (list);
JSonDriver driver;
bool ok;
QVariant result = driver.parse (json, &ok);
QVERIFY (ok);
QCOMPARE(result, expected);
}
void TestJSonDriver::testTrueFalseNullValues() {
QString json = "[true,false, null, {\"foo\" : true}]";
QVariantList list;
list.append (QVariant(true));
list.append (QVariant(false));
list.append (QVariant());
QVariantMap map;
map.insert ("foo", true);
list.append (map);
QVariant expected (list);
JSonDriver driver;
bool ok;
QVariant result = driver.parse (json, &ok);
QVERIFY (ok);
QCOMPARE(result, expected);
QCOMPARE (result.toList().at(0).toBool(), true);
QCOMPARE (result.toList().at(1).toBool(), false);
QVERIFY (result.toList().at(2).isNull());
}
void TestJSonDriver::testEscapeChars() {
QString json = "[\"\\b \\f \\n \\r \\t \", \" \\\\ \\/ \\\" \", \"http://foo.com\"]";
QVariantList list;
list.append (QVariant("\b \f \n \r \t "));
list.append (QVariant(" \\\\ / \\\" "));
list.append (QVariant("http://foo.com"));
QVariant expected (list);
JSonDriver driver;
bool ok;
QVariant result = driver.parse (json, &ok);
QVERIFY (ok);
QCOMPARE(result, expected);
}
void TestJSonDriver::testNumbers() {
QString json = "[1,2.4, -100, -3.4, -5e+, 2e,3e+,4.3E,5.4E-]";
QVariantList list;
list.append (QVariant(1));
list.append (QVariant(2.4));
list.append (QVariant(-100));
list.append (QVariant(-3.4));
list.append (QVariant("-5e+"));
list.append (QVariant("2e"));
list.append (QVariant("3e+"));
list.append (QVariant("4.3E"));
list.append (QVariant("5.4E-"));
QVariant expected (list);
JSonDriver driver;
bool ok;
QVariant result = driver.parse (json, &ok);
QVERIFY (ok);
QCOMPARE(result, expected);
QVariantList numbers = result.toList();
QCOMPARE( numbers[0].type(),QVariant::Int );
QCOMPARE( numbers[1].type(), QVariant::Double );
QCOMPARE( numbers[2].type(), QVariant::Int );
QCOMPARE( numbers[3].type(), QVariant::Double );
}
void TestJSonDriver::testReadWriteEmptyDocument()
{
QString json = QString("");
JSonDriver driver;
bool ok;
QVariant result = driver.parse( json, &ok );
QVERIFY(ok);
Serializer serializer;
const QString serialized = serializer.serialize( result );
QVERIFY( !serialized.isNull() );
QVERIFY( serialized.isEmpty() );
}
void TestJSonDriver::testSerialize()
{
QFETCH( QVariant, qvariant );
QFETCH( QString, expected );
Serializer serializer;
bool ok;
QString result = serializer.serialize( qvariant);
result = result.replace(" ", "");
expected = expected.replace(" ", "");
QCOMPARE(result, expected);
}
void TestJSonDriver::testSerialize_data()
{
QTest::addColumn<QVariant>( "qvariant" );
QTest::addColumn<QString>( "expected" );
// array tests
QVariantList array;
array.clear();
QTest::newRow( "empty array") << (QVariant) array << "[]";
array << QVariant("foo") << QVariant("bar");
QTest::newRow( "basic array") << (QVariant) array << "[\"foo\",\"bar\"]";
array.clear();
array << QVariant(6);
QTest::newRow( "int array") << (QVariant) array << "[6]";
// document tests
QVariantMap map;
map.clear();
QTest::newRow( "empty object") << (QVariant) map << "{}";
map["foo"] = QVariant("bar");
QTest::newRow( "basic document") << (QVariant) map << "{ \"foo\":\"bar\" }";
map["foo"] = QVariant(6);
QTest::newRow( "object with ints" ) << (QVariant) map << "{ \"foo\":6 }";
}
void TestJSonDriver::testReadWrite()
{
QFETCH( QString, json );
JSonDriver driver;
bool ok;
QVariant result = driver.parse( json, &ok );
QVERIFY(ok);
Serializer serializer;
const QString serialized = serializer.serialize( result );
// qWarning() << serialized;
QVariant writtenThenRead = driver.parse( serialized, &ok );
QCOMPARE( result, writtenThenRead );
}
void TestJSonDriver::testReadWrite_data()
{
QTest::addColumn<QString>( "json" );
// array tests
QTest::newRow( "empty array" ) << "[]";
QTest::newRow( "basic array" ) << "[\"foo\",\"bar\"]";
QTest::newRow( "single int array" ) << "[6]";
QTest::newRow( "int array" ) << "[6,5,6,7]";
const QString json = "[1,2.4, -100, -3.4, -5e+, 2e,3e+,4.3E,5.4E-]";
QTest::newRow( "array of various numbers" ) << json;
// document tests
QTest::newRow( "empty object" ) << "{}";
QTest::newRow( "basic document" ) << "{\"foo\":\"bar\"}";
QTest::newRow( "object with ints" ) << "{\"foo\":6}";
QString json2 = "{ \"foo\":\"bar\",\n\"number\" : 51.3 , \"array\":[\"item1\", 123]}";
QTest::newRow( "complicated document" ) << json2;
// more complex cases
const QString json3 = "[ {\"foo\":\"bar\"},\n\"number\",51.3 , [\"item1\", 123]]";
QTest::newRow( "complicated array" ) << json3;
}
QTEST_MAIN(TestJSonDriver)
#include "moc_testjsondriver.cxx"
|
/* This file is part of QJson
*
* Copyright (C) 2008 Flavio Castelli <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include <QtTest/QtTest>
#include "json_driver.h"
#include "serializer.h"
#include <QtCore/QVariant>
using namespace QJSon;
class TestJSonDriver: public QObject
{
Q_OBJECT
private slots:
void parseNonAsciiString();
void parseSimpleObject();
void parseEmptyObject();
void parseUrl();
void parseMultipleObject();
void parseSimpleArray();
void parseInvalidObject();
void parseMultipleArray();
void testTrueFalseNullValues();
void testEscapeChars();
void testNumbers();
void testReadWriteEmptyDocument();
void testReadWrite();
void testReadWrite_data();
};
Q_DECLARE_METATYPE(QVariant)
void TestJSonDriver::parseSimpleObject() {
QString json = "{\"foo\":\"bar\"}";
QVariantMap map;
map.insert ("foo", "bar");
QVariant expected(map);
JSonDriver driver;
bool ok;
QVariant result = driver.parse (json, &ok);
QVERIFY (ok);
QCOMPARE(result, expected);
}
void TestJSonDriver::parseEmptyObject() {
QString json = "{}";
QVariantMap map;
QVariant expected (map);
JSonDriver driver;
bool ok;
QVariant result = driver.parse (json, &ok);
QVERIFY (ok);
QCOMPARE(result, expected);
}
void TestJSonDriver::parseInvalidObject() {
QString json = "{\"foo\":\"bar\"";
JSonDriver driver;
bool ok;
QVariant result = driver.parse (json, &ok);
QVERIFY (!ok);
}
void TestJSonDriver::parseNonAsciiString() {
QString json = "{\"artist\":\"Queensr\\u00ffche\"}";
QVariantMap map;
QChar unicode_char (0x00ff);
QString unicode_string;
unicode_string.setUnicode(&unicode_char, 1);
unicode_string = "Queensr" + unicode_string + "che";
map.insert ("artist", unicode_string);
QVariant expected (map);
JSonDriver driver;
bool ok;
QVariant result = driver.parse (json, &ok);
QVERIFY (ok);
QCOMPARE(result, expected);
}
void TestJSonDriver::parseMultipleObject() {
//put also some extra spaces inside the json string
QString json = "{ \"foo\":\"bar\",\n\"number\" : 51.3 , \"array\":[\"item1\", 123]}";
QVariantMap map;
map.insert ("foo", "bar");
map.insert ("number", 51.3);
QVariantList list;
list.append (QString("item1"));
list.append (QString("123"));
map.insert ("array", list);
QVariant expected (map);
JSonDriver driver;
bool ok;
QVariant result = driver.parse (json, &ok);
QVERIFY (ok);
QCOMPARE(result, expected);
QVERIFY (result.toMap()["number"].canConvert<float>());
QVERIFY (result.toMap()["array"].canConvert<QVariantList>());
}
void TestJSonDriver::parseUrl(){
//"http:\/\/www.last.fm\/venue\/8926427"
QString json = "[\"http:\\/\\/www.last.fm\\/venue\\/8926427\"]";
QVariantList list;
list.append (QVariant(QString("http://www.last.fm/venue/8926427")));
QVariant expected (list);
JSonDriver driver;
bool ok;
QVariant result = driver.parse (json, &ok);
QVERIFY (ok);
QCOMPARE(result, expected);
}
void TestJSonDriver::parseSimpleArray() {
QString json = "[\"foo\",\"bar\"]";
QVariantList list;
list.append (QVariant(QString("foo")));
list.append (QVariant(QString("bar")));
QVariant expected (list);
JSonDriver driver;
bool ok;
QVariant result = driver.parse (json, &ok);
QVERIFY (ok);
QCOMPARE(result, expected);
}
void TestJSonDriver::parseMultipleArray() {
//put also some extra spaces inside the json string
QString json = "[ {\"foo\":\"bar\"},\n\"number\",51.3 , [\"item1\", 123]]";
QVariantMap map;
map.insert ("foo", "bar");
QVariantList array;
array.append (QString("item1"));
array.append (123);
QVariantList list;
list.append (map);
list.append (QString("number"));
list.append (QString("51.3"));
list.append ((QVariant) array);
QVariant expected (list);
JSonDriver driver;
bool ok;
QVariant result = driver.parse (json, &ok);
QVERIFY (ok);
QCOMPARE(result, expected);
}
void TestJSonDriver::testTrueFalseNullValues() {
QString json = "[true,false, null, {\"foo\" : true}]";
QVariantList list;
list.append (QVariant(true));
list.append (QVariant(false));
list.append (QVariant());
QVariantMap map;
map.insert ("foo", true);
list.append (map);
QVariant expected (list);
JSonDriver driver;
bool ok;
QVariant result = driver.parse (json, &ok);
QVERIFY (ok);
QCOMPARE(result, expected);
QCOMPARE (result.toList().at(0).toBool(), true);
QCOMPARE (result.toList().at(1).toBool(), false);
QVERIFY (result.toList().at(2).isNull());
}
void TestJSonDriver::testEscapeChars() {
QString json = "[\"\\b \\f \\n \\r \\t \", \" \\\\ \\/ \\\" \", \"http://foo.com\"]";
QVariantList list;
list.append (QVariant("\b \f \n \r \t "));
list.append (QVariant(" \\\\ / \\\" "));
list.append (QVariant("http://foo.com"));
QVariant expected (list);
JSonDriver driver;
bool ok;
QVariant result = driver.parse (json, &ok);
QVERIFY (ok);
QCOMPARE(result, expected);
}
void TestJSonDriver::testNumbers() {
QString json = "[1,2.4, -100, -3.4, -5e+, 2e,3e+,4.3E,5.4E-]";
QVariantList list;
list.append (QVariant(1));
list.append (QVariant(2.4));
list.append (QVariant(-100));
list.append (QVariant(-3.4));
list.append (QVariant("-5e+"));
list.append (QVariant("2e"));
list.append (QVariant("3e+"));
list.append (QVariant("4.3E"));
list.append (QVariant("5.4E-"));
QVariant expected (list);
JSonDriver driver;
bool ok;
QVariant result = driver.parse (json, &ok);
QVERIFY (ok);
QCOMPARE(result, expected);
QVariantList numbers = result.toList();
QCOMPARE( numbers[0].type(),QVariant::Int );
QCOMPARE( numbers[1].type(), QVariant::Double );
QCOMPARE( numbers[2].type(), QVariant::Int );
QCOMPARE( numbers[3].type(), QVariant::Double );
}
void TestJSonDriver::testReadWriteEmptyDocument()
{
QString json = QString("");
JSonDriver driver;
bool ok;
QVariant result = driver.parse( json, &ok );
QVERIFY(ok);
Serializer serializer;
const QString serialized = serializer.serialize( result );
QVERIFY( !serialized.isNull() );
QVERIFY( serialized.isEmpty() );
}
void TestJSonDriver::testReadWrite()
{
QFETCH( QString, json );
JSonDriver driver;
bool ok;
QVariant result = driver.parse( json, &ok );
QVERIFY(ok);
Serializer serializer;
const QString serialized = serializer.serialize( result );
// qWarning() << serialized;
QVariant writtenThenRead = driver.parse( serialized, &ok );
QCOMPARE( result, writtenThenRead );
}
void TestJSonDriver::testReadWrite_data()
{
QTest::addColumn<QString>( "json" );
// array tests
QTest::newRow( "empty array" ) << "[]";
QTest::newRow( "basic array" ) << "[\"foo\",\"bar\"]";
QTest::newRow( "single int array" ) << "[6]";
QTest::newRow( "int array" ) << "[6,5,6,7]";
const QString json = "[1,2.4, -100, -3.4, -5e+, 2e,3e+,4.3E,5.4E-]";
QTest::newRow( "array of various numbers" ) << json;
// document tests
QTest::newRow( "empty object" ) << "{}";
QTest::newRow( "basic document" ) << "{\"foo\":\"bar\"}";
QTest::newRow( "object with ints" ) << "{\"foo\":6}";
QString json2 = "{ \"foo\":\"bar\",\n\"number\" : 51.3 , \"array\":[\"item1\", 123]}";
QTest::newRow( "complicated document" ) << json2;
// more complex cases
const QString json3 = "[ {\"foo\":\"bar\"},\n\"number\",51.3 , [\"item1\", 123]]";
QTest::newRow( "complicated array" ) << json3;
}
QTEST_MAIN(TestJSonDriver)
#include "moc_testjsondriver.cxx"
|
remove useless test case
|
remove useless test case
git-svn-id: ec8dad496322030ce832d387f43d3d061c430ff7@993713 283d02a7-25f6-0310-bc7c-ecb5cbfe19da
|
C++
|
lgpl-2.1
|
cbranch/qjson-qmakefriendly,coolshou/qjson,cbranch/qjson-qmakefriendly,seem-sky/qjson,drizt/qjson,seem-sky/qjson,gentlefn/qjson,qlands/qjson,flavio/qjson,qlands/qjson,coolshou/qjson,gentlefn/qjson,drizt/qjson,flavio/qjson
|
d436f8345a648cd4d6dacfa74313a69c3ec830f7
|
iree/compiler/Conversion/LinalgToLLVM/Passes.cpp
|
iree/compiler/Conversion/LinalgToLLVM/Passes.cpp
|
// Copyright 2020 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
//
// https://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 "iree/compiler/Conversion/HLOToLinalg/Passes.h"
#include "iree/compiler/Conversion/Common/Attributes.h"
#include "iree/compiler/Conversion/Common/Passes.h"
#include "iree/compiler/Conversion/HLOToHLO/Passes.h"
#include "iree/compiler/Conversion/LLVMToLLVM/Passes.h"
#include "iree/compiler/Conversion/LinalgToLLVM/Passes.h"
#include "iree/compiler/Dialect/Shape/Transforms/Passes.h"
#include "mlir/Conversion/SCFToStandard/SCFToStandard.h"
#include "mlir/Dialect/Linalg/Passes.h"
#include "mlir/Pass/PassManager.h"
#include "mlir/Transforms/Passes.h"
namespace mlir {
namespace iree_compiler {
static llvm::cl::opt<bool> clEnableLLVMLinalgOnTensors(
"iree-codegen-llvm-experimental-linalg-on-tensors",
llvm::cl::desc("Enable the linalg on tensors experimental LLVM path"),
llvm::cl::init(false));
static llvm::cl::opt<bool> convImg2ColConversion(
"iree-codegen-linalg-to-llvm-conv-img2col-conversion",
llvm::cl::desc("Enable rewriting linalg.conv linalg.generic that does "
"img2col buffer packing + "
"linag.matmul"),
llvm::cl::init(false));
static llvm::cl::opt<bool> fastExpConversion(
"iree-codegen-linalg-to-llvm-fast-exp",
llvm::cl::desc("If true convert llvm.intr.exp into its range reduced "
"polynomial approximation."),
llvm::cl::init(false));
void addLinalgToLLVMPasses(OpPassManager &passManager) {
// Distribute linalg op among a 3d grid of parallel threads. Tile each
// workgroup thread memory then vectorize the linalg op.
passManager.addPass(createLinalgTileAndDistributePass());
OpPassManager &nestedModulePM = passManager.nest<ModuleOp>();
if (!clEnableLLVMLinalgOnTensors) {
nestedModulePM.addPass(createLegalizeNumWorkgroupsFnPass());
}
// Linalg.ConvOp -> (Img2Col packing + matmul).
// After convolution is tiled and distributed among workgroups its converted
// before vectorize workgroup workload.
if (convImg2ColConversion) {
nestedModulePM.addNestedPass<FuncOp>(
createConvImg2ColMatmulConversionPass());
}
nestedModulePM.addNestedPass<FuncOp>(
createLinalgTileAndVectorizeWorkgroupsPass());
nestedModulePM.addNestedPass<FuncOp>(createPlanConvLoopOrderPass());
// Linalg -> SCF
nestedModulePM.addNestedPass<FuncOp>(createConvertLinalgToLoopsPass());
nestedModulePM.addNestedPass<FuncOp>(createCanonicalizerPass());
nestedModulePM.addNestedPass<FuncOp>(createCSEPass());
// SCF -> STD
nestedModulePM.addNestedPass<FuncOp>(createLowerToCFGPass());
nestedModulePM.addNestedPass<FuncOp>(createCanonicalizerPass());
nestedModulePM.addNestedPass<FuncOp>(createCSEPass());
// (HAL, IREE, Linalg, STD) -> LLVM
// OpPassManager& llvmPassManager = nestedModulePM.nest<ModuleOp>();
nestedModulePM.addPass(createConvertToLLVMPass());
nestedModulePM.addPass(createCanonicalizerPass());
nestedModulePM.addPass(createCSEPass());
// Approximate llvm.intr.exp with a 4-th order ploynmial in range[0, ln2].
if (fastExpConversion) {
nestedModulePM.addPass(createFastExpApproximationConversionPass());
}
}
void buildLLVMTransformPassPipeline(OpPassManager &passManager) {
OpPassManager &nestedModulePM = passManager.nest<ModuleOp>();
if (!clEnableLLVMLinalgOnTensors)
nestedModulePM.addPass(createDeclareNumWorkgroupsFnPass());
nestedModulePM.addPass(createInlinerPass());
// HLO -> Linalg on buffers.
if (clEnableLLVMLinalgOnTensors) {
nestedModulePM.addPass(createLinalgVectorizePass());
addLinalgBufferizePasses(nestedModulePM);
nestedModulePM.addPass(createPromoteBuffersToStackPass(1 << 10, 64, 10));
} else {
// Propagates dynamic shapes computation on tensors.
nestedModulePM.addNestedPass<FuncOp>(Shape::createTieDynamicShapesPass());
nestedModulePM.addNestedPass<FuncOp>(
Shape::createMaterializeShapeCalculationsPass());
nestedModulePM.addNestedPass<FuncOp>(
Shape::createHoistShapeCalculationsPass());
nestedModulePM.addNestedPass<FuncOp>(createDecomposeHLOClampPass());
addHLOToLinalgOnBuffersPasses(nestedModulePM);
}
// Linalg -> LLVM passes.
addLinalgToLLVMPasses(passManager);
}
static PassPipelineRegistration<> linalgLLVMVPipeline(
"iree-codegen-linalg-to-llvm-pipeline",
"Runs the progressive lowering pipeline from Linalg to LLVM",
[](OpPassManager &passManager) {
buildLLVMTransformPassPipeline(passManager);
});
static PassPipelineRegistration<> hloToLinalgLLVMVPipeline(
"iree-codegen-hlo-to-llvm-pipeline",
"Runs the progressive lowering pipeline from XLA HLO to Linalg to LLVM",
[](OpPassManager &passManager) {
buildLLVMTransformPassPipeline(passManager);
});
} // namespace iree_compiler
} // namespace mlir
|
// Copyright 2020 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
//
// https://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 "iree/compiler/Conversion/HLOToLinalg/Passes.h"
#include "iree/compiler/Conversion/Common/Attributes.h"
#include "iree/compiler/Conversion/Common/Passes.h"
#include "iree/compiler/Conversion/HLOToHLO/Passes.h"
#include "iree/compiler/Conversion/LLVMToLLVM/Passes.h"
#include "iree/compiler/Conversion/LinalgToLLVM/Passes.h"
#include "iree/compiler/Dialect/Shape/Transforms/Passes.h"
#include "mlir/Conversion/SCFToStandard/SCFToStandard.h"
#include "mlir/Dialect/Linalg/Passes.h"
#include "mlir/Pass/PassManager.h"
#include "mlir/Transforms/Passes.h"
namespace mlir {
namespace iree_compiler {
static llvm::cl::opt<bool> clEnableLLVMLinalgOnTensors(
"iree-codegen-llvm-experimental-linalg-on-tensors",
llvm::cl::desc("Enable the linalg on tensors experimental LLVM path"),
llvm::cl::init(false));
static llvm::cl::opt<bool> convImg2ColConversion(
"iree-codegen-linalg-to-llvm-conv-img2col-conversion",
llvm::cl::desc("Enable rewriting linalg.conv linalg.generic that does "
"img2col buffer packing + "
"linag.matmul"),
llvm::cl::init(false));
static llvm::cl::opt<bool> fastExpConversion(
"iree-codegen-linalg-to-llvm-fast-exp",
llvm::cl::desc("If true convert llvm.intr.exp into its range reduced "
"polynomial approximation."),
llvm::cl::init(false));
void addLinalgToLLVMPasses(OpPassManager &passManager) {
// Distribute linalg op among a 3d grid of parallel threads. Tile each
// workgroup thread memory then vectorize the linalg op.
passManager.addPass(createLinalgTileAndDistributePass());
OpPassManager &nestedModulePM = passManager.nest<ModuleOp>();
if (!clEnableLLVMLinalgOnTensors) {
nestedModulePM.addPass(createLegalizeNumWorkgroupsFnPass());
}
// Linalg.ConvOp -> (Img2Col packing + matmul).
// After convolution is tiled and distributed among workgroups its converted
// before vectorize workgroup workload.
if (convImg2ColConversion) {
nestedModulePM.addNestedPass<FuncOp>(
createConvImg2ColMatmulConversionPass());
}
nestedModulePM.addNestedPass<FuncOp>(
createLinalgTileAndVectorizeWorkgroupsPass());
nestedModulePM.addNestedPass<FuncOp>(createPlanConvLoopOrderPass());
// Linalg -> SCF
nestedModulePM.addNestedPass<FuncOp>(createConvertLinalgToLoopsPass());
nestedModulePM.addNestedPass<FuncOp>(createCanonicalizerPass());
nestedModulePM.addNestedPass<FuncOp>(createCSEPass());
// SCF -> STD
nestedModulePM.addNestedPass<FuncOp>(createLowerToCFGPass());
nestedModulePM.addNestedPass<FuncOp>(createCanonicalizerPass());
nestedModulePM.addNestedPass<FuncOp>(createCSEPass());
// (HAL, IREE, Linalg, STD) -> LLVM
// OpPassManager& llvmPassManager = nestedModulePM.nest<ModuleOp>();
nestedModulePM.addPass(createConvertToLLVMPass());
nestedModulePM.addPass(createCanonicalizerPass());
nestedModulePM.addPass(createCSEPass());
// Approximate llvm.intr.exp with a 4-th order ploynmial in range[0, ln2].
if (fastExpConversion) {
nestedModulePM.addPass(createFastExpApproximationConversionPass());
}
}
void buildLLVMTransformPassPipeline(OpPassManager &passManager) {
OpPassManager &nestedModulePM = passManager.nest<ModuleOp>();
if (!clEnableLLVMLinalgOnTensors)
nestedModulePM.addPass(createDeclareNumWorkgroupsFnPass());
nestedModulePM.addPass(createInlinerPass());
// HLO -> Linalg on buffers.
if (clEnableLLVMLinalgOnTensors) {
nestedModulePM.addPass(createLinalgVectorizePass());
// Use stack allocation on CPU side.
WorkgroupMemoryAllocationFn allocationFn =
[](OpBuilder &builder, Location loc, ArrayRef<Value> dynamicSizes,
MemRefType allocationType) {
MemRefType allocType = MemRefType::get(
allocationType.getShape(), allocationType.getElementType());
return builder.create<AllocaOp>(loc, allocType, dynamicSizes);
};
addLinalgBufferizePasses(nestedModulePM, allocationFn);
nestedModulePM.addPass(createPromoteBuffersToStackPass(1 << 10, 64, 10));
} else {
// Propagates dynamic shapes computation on tensors.
nestedModulePM.addNestedPass<FuncOp>(Shape::createTieDynamicShapesPass());
nestedModulePM.addNestedPass<FuncOp>(
Shape::createMaterializeShapeCalculationsPass());
nestedModulePM.addNestedPass<FuncOp>(
Shape::createHoistShapeCalculationsPass());
nestedModulePM.addNestedPass<FuncOp>(createDecomposeHLOClampPass());
addHLOToLinalgOnBuffersPasses(nestedModulePM);
}
// Linalg -> LLVM passes.
addLinalgToLLVMPasses(passManager);
}
static PassPipelineRegistration<> linalgLLVMVPipeline(
"iree-codegen-linalg-to-llvm-pipeline",
"Runs the progressive lowering pipeline from Linalg to LLVM",
[](OpPassManager &passManager) {
buildLLVMTransformPassPipeline(passManager);
});
static PassPipelineRegistration<> hloToLinalgLLVMVPipeline(
"iree-codegen-hlo-to-llvm-pipeline",
"Runs the progressive lowering pipeline from XLA HLO to Linalg to LLVM",
[](OpPassManager &passManager) {
buildLLVMTransformPassPipeline(passManager);
});
} // namespace iree_compiler
} // namespace mlir
|
Use stack allocation on CPU side for Linalg on tensors path. (#4770)
|
Use stack allocation on CPU side for Linalg on tensors path. (#4770)
Using heap allocations without a free leads to memory leaks. Only
stack allocations are allowed with dispatch regions on CPU side.
|
C++
|
apache-2.0
|
google/iree,iree-org/iree,iree-org/iree,google/iree,iree-org/iree,iree-org/iree,google/iree,iree-org/iree,google/iree,iree-org/iree,iree-org/iree,google/iree,google/iree,google/iree
|
a61004bda5e55d7f6edcaa11b01662713a209c05
|
test/unit/math/prim/mat/err/check_pos_definite_test.cpp
|
test/unit/math/prim/mat/err/check_pos_definite_test.cpp
|
#include <stan/math/prim/mat.hpp>
#include <gtest/gtest.h>
#include <test/unit/util.hpp>
#include <limits>
#include <string>
using stan::math::check_pos_definite;
const char* function = "function";
class ErrorHandlingMatrix : public ::testing::Test {
public:
void SetUp() {}
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> y;
};
TEST_F(ErrorHandlingMatrix, checkPosDefinite) {
y.resize(1, 1);
y << 1;
EXPECT_NO_THROW(check_pos_definite(function, "y", y));
Eigen::LLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > llt_1(y);
EXPECT_NO_THROW(check_pos_definite(function, "y", llt_1));
Eigen::LDLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > ldlt_1
= y.ldlt();
EXPECT_NO_THROW(check_pos_definite(function, "y", ldlt_1));
y.resize(3, 3);
y << 1, 0, 0, 0, 1, 0, 0, 0, 1;
EXPECT_NO_THROW(check_pos_definite(function, "y", y));
Eigen::LLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > llt_2(y);
EXPECT_NO_THROW(check_pos_definite(function, "y", llt_2));
Eigen::LDLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > ldlt_2
= y.ldlt();
EXPECT_NO_THROW(check_pos_definite(function, "y", ldlt_2));
}
TEST_F(ErrorHandlingMatrix, checkPosDefinite_not_square) {
std::stringstream expected_msg;
y.resize(3, 4);
expected_msg << "Expecting a square matrix; rows of y (3) and columns of "
<< "y (4) must match in size";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y), std::invalid_argument,
expected_msg.str());
}
TEST_F(ErrorHandlingMatrix, checkPosDefinite_0_size) {
std::string expected_msg;
expected_msg
= "y must have a positive size, but is 0; "
"dimension size expression = rows";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y), std::invalid_argument,
expected_msg);
Eigen::MatrixXd x;
x.resize(0, 0);
Eigen::LLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > llt(
x.rows());
llt.compute(x);
EXPECT_NO_THROW(check_pos_definite(function, "x", llt));
}
TEST_F(ErrorHandlingMatrix, checkPosDefinite_non_symmetric) {
std::string expected_msg;
y.resize(3, 3);
y << 1, 0, 0, 0, 1, 0.5, 0, 0, 1;
expected_msg = "y is not symmetric. y[2,3] = 0.5, but y[3,2] = 0";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y), std::domain_error,
expected_msg);
Eigen::LLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > llt(y);
EXPECT_NO_THROW(check_pos_definite(function, "y", llt));
Eigen::LDLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > ldlt
= y.ldlt();
EXPECT_NO_THROW(check_pos_definite(function, "y", ldlt));
}
TEST_F(ErrorHandlingMatrix, checkPosDefinite_non_pos_definite) {
std::stringstream expected_msg1_mat;
std::stringstream expected_msg1_llt;
std::stringstream expected_msg1_ldlt;
std::stringstream expected_msg2_mat;
std::stringstream expected_msg3_mat;
std::stringstream expected_msg4;
y.resize(3, 3);
y << -1, 0, 0, 0, -1, 0, 0, 0, -1;
expected_msg1_mat << "function: y is not positive definite.";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y), std::domain_error,
expected_msg1_mat.str());
expected_msg1_llt << "function: Matrix y is not positive definite";
Eigen::LLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > llt_err1(
y);
EXPECT_THROW_MSG(check_pos_definite(function, "y", llt_err1),
std::domain_error, expected_msg1_llt.str());
expected_msg1_ldlt << "function: LDLT decomposition of y failed";
Eigen::LDLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > ldlt_err1
= y.ldlt();
EXPECT_THROW_MSG(check_pos_definite(function, "y", ldlt_err1),
std::domain_error, expected_msg1_ldlt.str());
y.resize(2, 2);
y << 1, 2, 2, 1;
expected_msg2_mat << "function: y is not positive definite.";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y), std::domain_error,
expected_msg2_mat.str());
Eigen::LLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > llt_err2(
y);
EXPECT_THROW_MSG(check_pos_definite(function, "y", llt_err2),
std::domain_error, expected_msg1_llt.str());
Eigen::LDLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > ldlt_err2
= y.ldlt();
EXPECT_THROW_MSG(check_pos_definite(function, "y", ldlt_err2),
std::domain_error, expected_msg1_ldlt.str());
y << 1, 1, 1, 1;
expected_msg3_mat << "function: y is not positive definite.";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y), std::domain_error,
expected_msg3_mat.str());
Eigen::LLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > llt_err3(
y);
EXPECT_THROW_MSG(check_pos_definite(function, "y", llt_err3),
std::domain_error, expected_msg1_llt.str());
Eigen::LDLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > ldlt_err3
= y.ldlt();
EXPECT_THROW_MSG(check_pos_definite(function, "y", ldlt_err3),
std::domain_error, expected_msg1_ldlt.str());
}
TEST_F(ErrorHandlingMatrix, checkPosDefinite_nan) {
double nan = std::numeric_limits<double>::quiet_NaN();
y.resize(1, 1);
y << nan;
std::stringstream expected_msg;
expected_msg << "function: y is not positive definite.";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y), std::domain_error,
expected_msg.str());
Eigen::LLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > llt_err1(
y);
EXPECT_THROW(check_pos_definite(function, "y", llt_err1), std::domain_error);
Eigen::LDLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > ldlt_err1
= y.ldlt();
EXPECT_THROW(check_pos_definite(function, "y", ldlt_err1), std::domain_error);
y.resize(3, 3);
y << 2, -1, 0, -1, 2, -1, 0, -1, 2;
EXPECT_NO_THROW(check_pos_definite(function, "y", y));
for (int i = 0; i < y.rows(); i++)
for (int j = 0; j < y.cols(); j++) {
y << 2, -1, 0, -1, 2, -1, 0, -1, 2;
y(i, j) = nan;
if (i >= j) {
// expected_msg.str("");
// if (i == j)
// expected_msg << "function: y["
// << j*y.cols() + i + 1
// << "] is " << nan
// << ", but must not be nan!";
// else
// expected_msg << "function: y is not symmetric. "
// << "y[" << j+1 << ", " << i+1 << "] = " << y(j, i)
// << ", but y[" << i+1 << ", " << j+1 << "] = "
// << y(i, j);
EXPECT_THROW(check_pos_definite(function, "y", y),
// , expected_msg.str());
std::domain_error);
}
}
y << 2, -1, nan, -1, 2, -1, nan, -1, nan;
Eigen::LLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > llt_err2(
y);
EXPECT_THROW(check_pos_definite(function, "y", llt_err2), std::domain_error);
Eigen::LDLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > ldlt_err2
= y.ldlt();
EXPECT_THROW(check_pos_definite(function, "y", ldlt_err2), std::domain_error);
y << 0, 0, 0, 0, 0, 0, 0, 0, 0;
expected_msg.str("");
expected_msg << "function: y is not positive definite.";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y), std::domain_error,
expected_msg.str());
}
|
#include <stan/math/prim/mat.hpp>
#include <gtest/gtest.h>
#include <test/unit/util.hpp>
#include <limits>
#include <string>
using stan::math::check_pos_definite;
const char* function = "function";
class ErrorHandlingMatrix : public ::testing::Test {
public:
void SetUp() {}
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> y;
};
TEST_F(ErrorHandlingMatrix, checkPosDefinite) {
y.resize(1, 1);
y << 1;
EXPECT_NO_THROW(check_pos_definite(function, "y", y));
Eigen::LLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > llt_1(y);
EXPECT_NO_THROW(check_pos_definite(function, "y", llt_1));
Eigen::LDLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > ldlt_1
= y.ldlt();
EXPECT_NO_THROW(check_pos_definite(function, "y", ldlt_1));
y.resize(3, 3);
y << 1, 0, 0, 0, 1, 0, 0, 0, 1;
EXPECT_NO_THROW(check_pos_definite(function, "y", y));
Eigen::LLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > llt_2(y);
EXPECT_NO_THROW(check_pos_definite(function, "y", llt_2));
Eigen::LDLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > ldlt_2
= y.ldlt();
EXPECT_NO_THROW(check_pos_definite(function, "y", ldlt_2));
}
TEST_F(ErrorHandlingMatrix, checkPosDefinite_not_square) {
std::stringstream expected_msg;
y.resize(3, 4);
expected_msg << "Expecting a square matrix; rows of y (3) and columns of "
<< "y (4) must match in size";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y), std::invalid_argument,
expected_msg.str());
}
TEST_F(ErrorHandlingMatrix, checkPosDefinite_0_size) {
std::string expected_msg;
expected_msg
= "y must have a positive size, but is 0; "
"dimension size expression = rows";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y), std::invalid_argument,
expected_msg);
Eigen::MatrixXd x;
x.resize(0, 0);
Eigen::LLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > llt(
x.rows());
llt.compute(x);
EXPECT_NO_THROW(check_pos_definite(function, "x", llt));
}
TEST_F(ErrorHandlingMatrix, checkPosDefinite_non_symmetric) {
std::string expected_msg;
y.resize(3, 3);
y << 1, 0, 0, 0, 1, 0.5, 0, 0, 1;
expected_msg = "y is not symmetric. y[2,3] = 0.5, but y[3,2] = 0";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y), std::domain_error,
expected_msg);
Eigen::LLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > llt(y);
EXPECT_NO_THROW(check_pos_definite(function, "y", llt));
Eigen::LDLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > ldlt
= y.ldlt();
EXPECT_NO_THROW(check_pos_definite(function, "y", ldlt));
}
TEST_F(ErrorHandlingMatrix, checkPosDefinite_non_pos_definite) {
std::stringstream expected_msg1_mat;
std::stringstream expected_msg1_llt;
std::stringstream expected_msg1_ldlt;
std::stringstream expected_msg2_mat;
std::stringstream expected_msg3_mat;
std::stringstream expected_msg4;
y.resize(3, 3);
y << -1, 0, 0, 0, -1, 0, 0, 0, -1;
expected_msg1_mat << "function: y is not positive definite.";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y), std::domain_error,
expected_msg1_mat.str());
expected_msg1_llt << "function: Matrix y is not positive definite";
Eigen::LLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > llt_err1(
y);
EXPECT_THROW_MSG(check_pos_definite(function, "y", llt_err1),
std::domain_error, expected_msg1_llt.str());
expected_msg1_ldlt << "function: LDLT decomposition of y failed";
Eigen::LDLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > ldlt_err1
= y.ldlt();
EXPECT_THROW_MSG(check_pos_definite(function, "y", ldlt_err1),
std::domain_error, expected_msg1_ldlt.str());
y.resize(2, 2);
y << 1, 2, 2, 1;
expected_msg2_mat << "function: y is not positive definite.";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y), std::domain_error,
expected_msg2_mat.str());
Eigen::LLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > llt_err2(
y);
EXPECT_THROW_MSG(check_pos_definite(function, "y", llt_err2),
std::domain_error, expected_msg1_llt.str());
Eigen::LDLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > ldlt_err2
= y.ldlt();
EXPECT_THROW_MSG(check_pos_definite(function, "y", ldlt_err2),
std::domain_error, expected_msg1_ldlt.str());
y << 1, 1, 1, 1;
expected_msg3_mat << "function: y is not positive definite.";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y), std::domain_error,
expected_msg3_mat.str());
Eigen::LLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > llt_err3(
y);
EXPECT_THROW_MSG(check_pos_definite(function, "y", llt_err3),
std::domain_error, expected_msg1_llt.str());
Eigen::LDLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > ldlt_err3
= y.ldlt();
EXPECT_THROW_MSG(check_pos_definite(function, "y", ldlt_err3),
std::domain_error, expected_msg1_ldlt.str());
}
TEST_F(ErrorHandlingMatrix, checkPosDefinite_nan) {
double nan = std::numeric_limits<double>::quiet_NaN();
y.resize(1, 1);
y << nan;
std::stringstream expected_msg;
expected_msg << "function: y[1] is nan, but must not be nan!";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y), std::domain_error,
expected_msg.str());
Eigen::LLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > llt_err1(
y);
EXPECT_THROW(check_pos_definite(function, "y", llt_err1), std::domain_error);
Eigen::LDLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > ldlt_err1
= y.ldlt();
EXPECT_THROW(check_pos_definite(function, "y", ldlt_err1), std::domain_error);
y.resize(3, 3);
y << 2, -1, 0, -1, 2, -1, 0, -1, 2;
EXPECT_NO_THROW(check_pos_definite(function, "y", y));
for (int i = 0; i < y.rows(); i++)
for (int j = 0; j < y.cols(); j++) {
y << 2, -1, 0, -1, 2, -1, 0, -1, 2;
y(i, j) = nan;
if (i >= j) {
// expected_msg.str("");
// if (i == j)
// expected_msg << "function: y["
// << j*y.cols() + i + 1
// << "] is " << nan
// << ", but must not be nan!";
// else
// expected_msg << "function: y is not symmetric. "
// << "y[" << j+1 << ", " << i+1 << "] = " << y(j, i)
// << ", but y[" << i+1 << ", " << j+1 << "] = "
// << y(i, j);
EXPECT_THROW(check_pos_definite(function, "y", y),
// , expected_msg.str());
std::domain_error);
}
}
y << 2, -1, nan, -1, 2, -1, nan, -1, nan;
Eigen::LLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > llt_err2(
y);
EXPECT_THROW(check_pos_definite(function, "y", llt_err2), std::domain_error);
Eigen::LDLT<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > ldlt_err2
= y.ldlt();
EXPECT_THROW(check_pos_definite(function, "y", ldlt_err2), std::domain_error);
y << 0, 0, 0, 0, 0, 0, 0, 0, 0;
expected_msg.str("");
expected_msg << "function: y is not positive definite.";
EXPECT_THROW_MSG(check_pos_definite(function, "y", y), std::domain_error,
expected_msg.str());
}
|
Fix test
|
Fix test
|
C++
|
bsd-3-clause
|
stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math
|
0a9298b6333f5a373ddd316978f0aa469ef20ce7
|
chrome/browser/chromeos/login/login_browsertest.cc
|
chrome/browser/chromeos/login/login_browsertest.cc
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/time.h"
#include "chrome/browser/chromeos/cros/cros_in_process_browser_test.h"
#include "chrome/browser/chromeos/cros/mock_cryptohome_library.h"
#include "chrome/browser/chromeos/cros/mock_library_loader.h"
#include "chrome/browser/chromeos/cros/mock_network_library.h"
#include "chrome/browser/chromeos/dbus/mock_power_manager_client.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace chromeos {
using ::testing::_;
using ::testing::AtLeast;
using ::testing::Return;
class LoginTestBase : public CrosInProcessBrowserTest {
public:
LoginTestBase() : mock_cryptohome_library_(NULL) {
}
protected:
virtual void SetUpInProcessBrowserTestFixture() {
cros_mock_->InitStatusAreaMocks();
cros_mock_->SetStatusAreaMocksExpectations();
cros_mock_->InitMockCryptohomeLibrary();
mock_cryptohome_library_ = cros_mock_->mock_cryptohome_library();
EXPECT_CALL(*mock_cryptohome_library_, IsMounted())
.WillRepeatedly(Return(true));
}
MockCryptohomeLibrary* mock_cryptohome_library_;
MockPowerManagerClient mock_power_manager_client_;
private:
DISALLOW_COPY_AND_ASSIGN(LoginTestBase);
};
class LoginUserTest : public LoginTestBase {
protected:
virtual void SetUpInProcessBrowserTestFixture() {
LoginTestBase::SetUpInProcessBrowserTestFixture();
EXPECT_CALL(mock_power_manager_client_, AddObserver(_))
.Times(AtLeast(1))
.WillRepeatedly(Return());
EXPECT_CALL(mock_power_manager_client_, RemoveObserver(_))
.Times(AtLeast(1))
.WillRepeatedly(Return());
}
virtual void SetUpCommandLine(CommandLine* command_line) {
command_line->AppendSwitchASCII(switches::kLoginUser, "[email protected]");
command_line->AppendSwitchASCII(switches::kLoginProfile, "user");
command_line->AppendSwitch(switches::kNoFirstRun);
}
};
class LoginProfileTest : public LoginUserTest {
protected:
virtual void SetUpCommandLine(CommandLine* command_line) {
command_line->AppendSwitchASCII(switches::kLoginProfile, "user");
command_line->AppendSwitch(switches::kNoFirstRun);
}
};
// After a chrome crash, the session manager will restart chrome with
// the -login-user flag indicating that the user is already logged in.
// This profile should NOT be an OTR profile.
IN_PROC_BROWSER_TEST_F(LoginUserTest, UserPassed) {
Profile* profile = browser()->profile();
EXPECT_EQ("user", profile->GetPath().BaseName().value());
EXPECT_FALSE(profile->IsOffTheRecord());
}
// On initial launch, we should get the OTR default profile.
IN_PROC_BROWSER_TEST_F(LoginProfileTest, UserNotPassed) {
Profile* profile = browser()->profile();
EXPECT_EQ("Default", profile->GetPath().BaseName().value());
EXPECT_TRUE(profile->IsOffTheRecord());
// Ensure there's extension service for this profile.
EXPECT_TRUE(profile->GetExtensionService());
}
} // namespace chromeos
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/time.h"
#include "chrome/browser/chromeos/cros/cros_in_process_browser_test.h"
#include "chrome/browser/chromeos/cros/mock_cryptohome_library.h"
#include "chrome/browser/chromeos/cros/mock_library_loader.h"
#include "chrome/browser/chromeos/cros/mock_network_library.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace chromeos {
using ::testing::_;
using ::testing::AtLeast;
using ::testing::Return;
class LoginTestBase : public CrosInProcessBrowserTest {
public:
LoginTestBase() : mock_cryptohome_library_(NULL) {
}
protected:
virtual void SetUpInProcessBrowserTestFixture() {
cros_mock_->InitStatusAreaMocks();
cros_mock_->SetStatusAreaMocksExpectations();
cros_mock_->InitMockCryptohomeLibrary();
mock_cryptohome_library_ = cros_mock_->mock_cryptohome_library();
EXPECT_CALL(*mock_cryptohome_library_, IsMounted())
.WillRepeatedly(Return(true));
}
MockCryptohomeLibrary* mock_cryptohome_library_;
private:
DISALLOW_COPY_AND_ASSIGN(LoginTestBase);
};
class LoginUserTest : public LoginTestBase {
protected:
virtual void SetUpInProcessBrowserTestFixture() {
LoginTestBase::SetUpInProcessBrowserTestFixture();
}
virtual void SetUpCommandLine(CommandLine* command_line) {
command_line->AppendSwitchASCII(switches::kLoginUser, "[email protected]");
command_line->AppendSwitchASCII(switches::kLoginProfile, "user");
command_line->AppendSwitch(switches::kNoFirstRun);
}
};
class LoginProfileTest : public LoginUserTest {
protected:
virtual void SetUpCommandLine(CommandLine* command_line) {
command_line->AppendSwitchASCII(switches::kLoginProfile, "user");
command_line->AppendSwitch(switches::kNoFirstRun);
}
};
// After a chrome crash, the session manager will restart chrome with
// the -login-user flag indicating that the user is already logged in.
// This profile should NOT be an OTR profile.
IN_PROC_BROWSER_TEST_F(LoginUserTest, UserPassed) {
Profile* profile = browser()->profile();
EXPECT_EQ("user", profile->GetPath().BaseName().value());
EXPECT_FALSE(profile->IsOffTheRecord());
}
// On initial launch, we should get the OTR default profile.
IN_PROC_BROWSER_TEST_F(LoginProfileTest, UserNotPassed) {
Profile* profile = browser()->profile();
EXPECT_EQ("Default", profile->GetPath().BaseName().value());
EXPECT_TRUE(profile->IsOffTheRecord());
// Ensure there's extension service for this profile.
EXPECT_TRUE(profile->GetExtensionService());
}
} // namespace chromeos
|
remove power manager EXPECTs from login_browsertest
|
chromeos: remove power manager EXPECTs from login_browsertest
BUG=106061
TEST=browser tests should pass
Signed-off-by: Simon Que <[email protected]>
[email protected],[email protected],[email protected]
Review URL: http://codereview.chromium.org/8773016
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@112551 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,Chilledheart/chromium,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,chuan9/chromium-crosswalk,dushu1203/chromium.src,keishi/chromium,keishi/chromium,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk,rogerwang/chromium,zcbenz/cefode-chromium,ChromiumWebApps/chromium,littlstar/chromium.src,jaruba/chromium.src,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,keishi/chromium,rogerwang/chromium,dednal/chromium.src,Chilledheart/chromium,patrickm/chromium.src,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,robclark/chromium,dushu1203/chromium.src,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,Just-D/chromium-1,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,ltilve/chromium,Just-D/chromium-1,nacl-webkit/chrome_deps,junmin-zhu/chromium-rivertrail,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,axinging/chromium-crosswalk,ltilve/chromium,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,ltilve/chromium,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,jaruba/chromium.src,M4sse/chromium.src,Chilledheart/chromium,jaruba/chromium.src,timopulkkinen/BubbleFish,markYoungH/chromium.src,anirudhSK/chromium,dednal/chromium.src,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,littlstar/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,keishi/chromium,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,patrickm/chromium.src,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,Fireblend/chromium-crosswalk,markYoungH/chromium.src,dednal/chromium.src,littlstar/chromium.src,dushu1203/chromium.src,dednal/chromium.src,rogerwang/chromium,Jonekee/chromium.src,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,jaruba/chromium.src,robclark/chromium,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,anirudhSK/chromium,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,robclark/chromium,robclark/chromium,chuan9/chromium-crosswalk,M4sse/chromium.src,hujiajie/pa-chromium,littlstar/chromium.src,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,patrickm/chromium.src,Fireblend/chromium-crosswalk,dednal/chromium.src,littlstar/chromium.src,junmin-zhu/chromium-rivertrail,ondra-novak/chromium.src,dushu1203/chromium.src,M4sse/chromium.src,ltilve/chromium,timopulkkinen/BubbleFish,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk-efl,hujiajie/pa-chromium,ondra-novak/chromium.src,markYoungH/chromium.src,ondra-novak/chromium.src,rogerwang/chromium,littlstar/chromium.src,pozdnyakov/chromium-crosswalk,junmin-zhu/chromium-rivertrail,Just-D/chromium-1,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,ChromiumWebApps/chromium,ltilve/chromium,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,zcbenz/cefode-chromium,Jonekee/chromium.src,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,robclark/chromium,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,Jonekee/chromium.src,anirudhSK/chromium,axinging/chromium-crosswalk,hujiajie/pa-chromium,ltilve/chromium,ondra-novak/chromium.src,hujiajie/pa-chromium,M4sse/chromium.src,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,robclark/chromium,Just-D/chromium-1,Just-D/chromium-1,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,timopulkkinen/BubbleFish,anirudhSK/chromium,zcbenz/cefode-chromium,keishi/chromium,nacl-webkit/chrome_deps,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,rogerwang/chromium,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,mogoweb/chromium-crosswalk,keishi/chromium,rogerwang/chromium,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,jaruba/chromium.src,ondra-novak/chromium.src,keishi/chromium,junmin-zhu/chromium-rivertrail,Just-D/chromium-1,junmin-zhu/chromium-rivertrail,nacl-webkit/chrome_deps,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,Chilledheart/chromium,M4sse/chromium.src,dushu1203/chromium.src,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,hujiajie/pa-chromium,dednal/chromium.src,mogoweb/chromium-crosswalk,dednal/chromium.src,fujunwei/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,keishi/chromium,Chilledheart/chromium,Fireblend/chromium-crosswalk,Just-D/chromium-1,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,markYoungH/chromium.src,ltilve/chromium,rogerwang/chromium,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,axinging/chromium-crosswalk,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,pozdnyakov/chromium-crosswalk,junmin-zhu/chromium-rivertrail,timopulkkinen/BubbleFish,anirudhSK/chromium,patrickm/chromium.src,hgl888/chromium-crosswalk,junmin-zhu/chromium-rivertrail,zcbenz/cefode-chromium,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,rogerwang/chromium,dushu1203/chromium.src,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,hujiajie/pa-chromium,zcbenz/cefode-chromium,patrickm/chromium.src,bright-sparks/chromium-spacewalk,robclark/chromium,TheTypoMaster/chromium-crosswalk,junmin-zhu/chromium-rivertrail,keishi/chromium,markYoungH/chromium.src,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,patrickm/chromium.src,keishi/chromium,Jonekee/chromium.src,nacl-webkit/chrome_deps,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,patrickm/chromium.src,nacl-webkit/chrome_deps,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,ChromiumWebApps/chromium,anirudhSK/chromium,nacl-webkit/chrome_deps,timopulkkinen/BubbleFish,keishi/chromium,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,timopulkkinen/BubbleFish,mogoweb/chromium-crosswalk,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,hgl888/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,M4sse/chromium.src,krieger-od/nwjs_chromium.src,rogerwang/chromium,mogoweb/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,rogerwang/chromium,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,zcbenz/cefode-chromium,junmin-zhu/chromium-rivertrail,zcbenz/cefode-chromium,patrickm/chromium.src,jaruba/chromium.src,nacl-webkit/chrome_deps,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,timopulkkinen/BubbleFish,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,robclark/chromium,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,krieger-od/nwjs_chromium.src,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,timopulkkinen/BubbleFish,robclark/chromium,hgl888/chromium-crosswalk,nacl-webkit/chrome_deps,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,pozdnyakov/chromium-crosswalk,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,Just-D/chromium-1,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,Jonekee/chromium.src,robclark/chromium,bright-sparks/chromium-spacewalk,dednal/chromium.src,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src
|
80e7e9824ff1f4035d712f648df7548961ed0a99
|
Code/BasicFilters/sitkStatisticsImageFilter.cxx
|
Code/BasicFilters/sitkStatisticsImageFilter.cxx
|
#include "sitkStatisticsImageFilter.h"
#include "itkStatisticsImageFilter.h"
namespace itk {
namespace simple {
//----------------------------------------------------------------------------
//
// Default constructor that initializes parameters
//
StatisticsImageFilter::StatisticsImageFilter ()
{
m_Minimum = -1.0;
m_Maximum = -1.0;
m_Mean = -1.0;
m_Variance = -1.0;
this->m_MemberFactory.reset( new detail::MemberFunctionFactory<MemberFunctionType>( this ) );
this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 3 > ();
this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 2 > ();
}
//
// ToString
//
std::string StatisticsImageFilter::ToString() const
{
std::ostringstream out;
out << "itk::simple::StatisticsImageFilter\n";
out << "\tMinimum: " << this->m_Minimum << "\n";
out << "\tMaximum: " << this->m_Maximum << "\n";
out << "\tMean: " << this->m_Mean << "\n";
out << "\tVariance: " << this->m_Variance << "\n";
return out.str();
}
//
// Execute
//
Image StatisticsImageFilter::Execute ( const Image& image1 )
{
PixelIDValueType type = image1.GetPixelIDValue();
unsigned int dimension = image1.GetDimension();
return this->m_MemberFactory->GetMemberFunction( type, dimension )( image1 );
}
//----------------------------------------------------------------------------
//
// ExecuteInternal
//
template <class TImageType>
Image StatisticsImageFilter::ExecuteInternal ( const Image& inImage1 )
{
typedef TImageType InputImageType;
typedef InputImageType OutputImageType;
typename InputImageType::ConstPointer image1 =
dynamic_cast <const InputImageType* > ( inImage1.GetImageBase() );
if ( image1.IsNull() )
{
sitkExceptionMacro( "Unexpected template dispatch error!" );
}
typedef itk::StatisticsImageFilter<InputImageType> FilterType;
typename FilterType::Pointer filter = FilterType::New();
filter->SetInput( image1 );
filter->Update();
return Image( filter->GetOutput() );
}
} // end namespace simple
} // end namespace itk
|
#include "sitkStatisticsImageFilter.h"
#include "itkStatisticsImageFilter.h"
namespace itk {
namespace simple {
//----------------------------------------------------------------------------
//
// Default constructor that initializes parameters
//
StatisticsImageFilter::StatisticsImageFilter ()
{
m_Minimum = -1.0;
m_Maximum = -1.0;
m_Mean = -1.0;
m_Variance = -1.0;
this->m_MemberFactory.reset( new detail::MemberFunctionFactory<MemberFunctionType>( this ) );
this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 3 > ();
this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 2 > ();
}
//
// ToString
//
std::string StatisticsImageFilter::ToString() const
{
std::ostringstream out;
out << "itk::simple::StatisticsImageFilter\n";
out << "\tMinimum: " << this->m_Minimum << "\n";
out << "\tMaximum: " << this->m_Maximum << "\n";
out << "\tMean: " << this->m_Mean << "\n";
out << "\tVariance: " << this->m_Variance << "\n";
return out.str();
}
//
// Execute
//
Image StatisticsImageFilter::Execute ( const Image& image1 )
{
PixelIDValueType type = image1.GetPixelIDValue();
unsigned int dimension = image1.GetDimension();
return this->m_MemberFactory->GetMemberFunction( type, dimension )( image1 );
}
//----------------------------------------------------------------------------
//
// ExecuteInternal
//
template <class TImageType>
Image StatisticsImageFilter::ExecuteInternal ( const Image& inImage1 )
{
typedef TImageType InputImageType;
typedef InputImageType OutputImageType;
typename InputImageType::ConstPointer image1 =
dynamic_cast <const InputImageType* > ( inImage1.GetImageBase() );
if ( image1.IsNull() )
{
sitkExceptionMacro( "Unexpected template dispatch error!" );
}
typedef itk::StatisticsImageFilter<InputImageType> FilterType;
typename FilterType::Pointer filter = FilterType::New();
filter->SetInput( image1 );
filter->Update();
this->m_Minimum = filter->GetMinimum();
this->m_Maximum = filter->GetMaximum();
this->m_Mean = filter->GetMean();
this->m_Variance = filter->GetVariance();
return Image( filter->GetOutput() );
}
} // end namespace simple
} // end namespace itk
|
set the statistics member variables
|
BUG: set the statistics member variables
This filter was designed to run and set the simpleITK member variable
from ITK. These were not set and the filter didn't do anything before.
SIMPLEITK-53
|
C++
|
apache-2.0
|
SimpleITK/Staging,SimpleITK/Staging,SimpleITK/Staging,SimpleITK/Staging,SimpleITK/Staging,SimpleITK/Staging,SimpleITK/Staging
|
2fc6a4f7201d21bd119cba68f47591d4043cf838
|
Source/UI/WhatIsMyIPApp.cpp
|
Source/UI/WhatIsMyIPApp.cpp
|
#include "PrecompiledHeader.h"
#include "Networking\ConnectionProperties.h"
#include "Networking\IPInformationGenerator.h"
#include "Utilities\EventHandler.h"
#include "VisualObjects.h"
#include "WhatIsMyIPApp.h"
using namespace ABI::Windows::ApplicationModel::Activation;
using namespace ABI::Windows::Foundation;
using namespace ABI::Windows::Foundation::Collections;
using namespace ABI::Windows::Networking::Connectivity;
using namespace ABI::Windows::UI;
using namespace ABI::Windows::UI::Core;
using namespace ABI::Windows::UI::ViewManagement;
using namespace ABI::Windows::UI::Xaml;
using namespace ABI::Windows::UI::Xaml::Controls;
using namespace ABI::Windows::UI::Xaml::Media;
using namespace UI;
WhatIsMyIPApp::WhatIsMyIPApp() :
m_ActiveRefreshTaskCount(0)
{
m_OnNetworkStatusChangedToken.value = 0;
}
void WhatIsMyIPApp::Cleanup()
{
if (m_OnNetworkStatusChangedToken.value != 0)
{
auto hr = Networking::IPInformation::UnsubscribeFromOnNetworkStatusChanged(m_OnNetworkStatusChangedToken);
Assert(SUCCEEDED(hr));
}
XamlApplication::Cleanup();
}
HRESULT WhatIsMyIPApp::CreatePage(IUIElement** outPage)
{
WRL::ComPtr<IPage> page;
HRESULT hr = Windows::Foundation::ActivateInstance(WRL::HStringReference(L"Windows.UI.Xaml.Controls.Page").Get(), &page);
ReturnIfFailed(hr);
WRL::ComPtr<IUIElement> grid;
hr = CreateRootGrid(&grid);
ReturnIfFailed(hr);
WRL::ComPtr<IUserControl> pageControl;
hr = page.As(&pageControl);
ReturnIfFailed(hr);
hr = pageControl->put_Content(grid.Get());
ReturnIfFailed(hr);
hr = page.As(&m_RootElement);
ReturnIfFailed(hr);
return page.Get()->QueryInterface(outPage);
}
HRESULT WhatIsMyIPApp::CreateRootGrid(IUIElement** outGrid)
{
WRL::ComPtr<IGrid> grid;
HRESULT hr = Windows::Foundation::ActivateInstance(WRL::HStringReference(L"Windows.UI.Xaml.Controls.Grid").Get(), &grid);
ReturnIfFailed(hr);
WRL::ComPtr<IPanel> gridPanel;
hr = grid.As(&gridPanel);
ReturnIfFailed(hr);
WRL::ComPtr<IBrush> gridBackground;
hr = UI::VisualObjects::GetBrushFromColor(0, 0, 0, 255, &gridBackground);
ReturnIfFailed(hr);
hr = gridPanel->put_Background(gridBackground.Get());
ReturnIfFailed(hr);
WRL::ComPtr<IVector<UIElement*>> gridChildren;
hr = gridPanel->get_Children(&gridChildren);
ReturnIfFailed(hr);
WRL::ComPtr<IUIElement> uiElement;
hr = CreateScrollViewer(&uiElement);
ReturnIfFailed(hr);
hr = gridChildren->Append(uiElement.Get());
ReturnIfFailed(hr);
hr = CreateProgressBar(&uiElement);
ReturnIfFailed(hr);
hr = gridChildren->Append(uiElement.Get());
ReturnIfFailed(hr);
return grid.Get()->QueryInterface(outGrid);
}
HRESULT WhatIsMyIPApp::CreateScrollViewer(IUIElement** outScrollViewer)
{
WRL::ComPtr<IScrollViewer> scrollViewer;
auto hr = Windows::Foundation::ActivateInstance(WRL::HStringReference(L"Windows.UI.Xaml.Controls.ScrollViewer").Get(), &scrollViewer);
ReturnIfFailed(hr);
hr = scrollViewer->put_HorizontalScrollBarVisibility(ScrollBarVisibility_Auto);
ReturnIfFailed(hr);
WRL::ComPtr<IContentControl> scrollViewerContentControl;
hr = scrollViewer.As(&scrollViewerContentControl);
ReturnIfFailed(hr);
WRL::ComPtr<IUIElement> textBlockElement;
hr = CreateIPInformationTextBlock(&textBlockElement);
ReturnIfFailed(hr);
hr = scrollViewerContentControl->put_Content(textBlockElement.Get());
ReturnIfFailed(hr);
WRL::ComPtr<IUIElement> scrollViewerElement;
hr = scrollViewer.As(&scrollViewerElement);
ReturnIfFailed(hr);
return scrollViewer.Get()->QueryInterface(outScrollViewer);
}
HRESULT WhatIsMyIPApp::CreateProgressBar(IUIElement** outProgressBar)
{
WRL::ComPtr<IProgressBar> progressBar;
auto hr = Windows::Foundation::ActivateInstance(WRL::HStringReference(L"Windows.UI.Xaml.Controls.ProgressBar").Get(), &progressBar);
ReturnIfFailed(hr);
hr = progressBar->put_IsIndeterminate(true);
ReturnIfFailed(hr);
WRL::ComPtr<IFrameworkElement> progressBarFrameworkElement;
hr = progressBar.As(&progressBarFrameworkElement);
ReturnIfFailed(hr);
hr = progressBarFrameworkElement->put_VerticalAlignment(VerticalAlignment_Top);
ReturnIfFailed(hr);
hr = progressBarFrameworkElement->put_HorizontalAlignment(HorizontalAlignment_Stretch);
ReturnIfFailed(hr);
progressBar.As(&m_ProgressBar);
ReturnIfFailed(hr);
hr = m_ProgressBar->put_Visibility(Visibility_Collapsed);
ReturnIfFailed(hr);
*outProgressBar = m_ProgressBar.Get();
(*outProgressBar)->AddRef();
return S_OK;
}
HRESULT WhatIsMyIPApp::CreateIPInformationTextBlock(IUIElement** outTextBlock)
{
WRL::ComPtr<ITextBlock> textBlock;
auto hr = Windows::Foundation::ActivateInstance(WRL::HStringReference(L"Windows.UI.Xaml.Controls.TextBlock").Get(), &textBlock);
ReturnIfFailed(hr);
WRL::ComPtr<IBrush> textBrush;
hr = VisualObjects::GetBrushFromColor(255, 255, 255, 255, &textBrush);
ReturnIfFailed(hr);
hr = textBlock->put_Foreground(textBrush.Get());
ReturnIfFailed(hr);
WRL::ComPtr<IFontFamily> font;
hr = VisualObjects::GetMonospaceFont(&font);
ReturnIfFailed(hr);
if (hr != S_FALSE)
{
hr = textBlock->put_FontFamily(font.Get());
ReturnIfFailed(hr);
}
m_TextBlock = textBlock.Detach();
return m_TextBlock.Get()->QueryInterface(outTextBlock);
}
#if !WINDOWS_8_1
static HRESULT SetViewBoundsMode(ApplicationViewBoundsMode boundsMode)
{
WRL::ComPtr<IApplicationViewStatics2> applicationViewStatics;
auto hr = Windows::Foundation::GetActivationFactory(WRL::HStringReference(L"Windows.UI.ViewManagement.ApplicationView").Get(), &applicationViewStatics);
ReturnIfFailed(hr);
WRL::ComPtr<IApplicationView> applicationView;
hr = applicationViewStatics->GetForCurrentView(&applicationView);
ReturnIfFailed(hr);
WRL::ComPtr<IApplicationView2> applicationView2;
hr = applicationView.As(&applicationView2);
ReturnIfFailed(hr);
boolean success;
hr = applicationView2->SetDesiredBoundsMode(boundsMode, &success);
return hr;
}
#endif
HRESULT WhatIsMyIPApp::CreateXamlLayout()
{
HRESULT hr;
#if !WINDOWS_8_1
hr = SetViewBoundsMode(ApplicationViewBoundsMode_UseVisible);
ReturnIfFailed(hr);
#endif
hr = CreatePage(&m_RootElement);
ReturnIfFailed(hr);
return S_OK;
}
HRESULT WhatIsMyIPApp::RefreshIPInformationText()
{
if (m_ActiveRefreshTaskCount == 0)
{
auto hr = m_ProgressBar->put_Visibility(Visibility_Visible);
ReturnIfFailed(hr);
}
m_ActiveRefreshTaskCount++;
WRL::ComPtr<WhatIsMyIPApp> _this = this;
return Networking::GenerateIPInformationAsync([_this](const std::vector<Networking::ConnectionProperties>& connectionProperties)
{
std::wstringstream textStream;
HSTRING text;
for (auto& properties : connectionProperties)
{
textStream << properties.name << std::endl;
for (auto& property : properties.properties)
{
textStream << L" ";
textStream << std::setw(28) << std::left << property.first;
textStream << property.second << std::endl;
}
textStream << std::endl;
}
auto str = textStream.str();
auto hr = WindowsCreateString(str.c_str(), static_cast<uint32_t>(str.length()), &text);
ReturnIfFailed(hr);
hr = _this->ExecuteOnUIThread([_this, text]() -> HRESULT
{
WRL::HString str;
str.Attach(text);
auto hr = _this->m_TextBlock->put_Text(text);
ReturnIfFailed(hr);
_this->m_ActiveRefreshTaskCount--;
if (_this->m_ActiveRefreshTaskCount == 0)
return _this->m_ProgressBar->put_Visibility(Visibility_Collapsed);
return S_OK;
});
if (FAILED(hr))
WindowsDeleteString(text);
return hr;
});
}
HRESULT STDMETHODCALLTYPE WhatIsMyIPApp::OnLaunched(ILaunchActivatedEventArgs* args)
{
auto hr = CreateXamlLayout();
ReturnIfFailed(hr);
hr = GetWindow()->put_Content(m_RootElement.Get());
ReturnIfFailed(hr);
WRL::ComPtr<WhatIsMyIPApp> _this = this;
hr = Networking::IPInformation::SubscribeToOnNetworkStatusChanged(Utilities::EventHandlerFactory<INetworkStatusChangedEventHandler>::Make([_this](IInspectable* sender) -> HRESULT
{
return _this->ExecuteOnUIThread([_this]()
{
return _this->RefreshIPInformationText();
});
}).Get(), &m_OnNetworkStatusChangedToken);
return XamlApplication::OnLaunched(args);
}
HRESULT STDMETHODCALLTYPE WhatIsMyIPApp::OnWindowActivated(IWindowActivatedEventArgs* e)
{
CoreWindowActivationState windowActivationState;
HRESULT hr = e->get_WindowActivationState(&windowActivationState);
ReturnIfFailed(hr);
if (windowActivationState != CoreWindowActivationState_Deactivated)
{
hr = RefreshIPInformationText();
ReturnIfFailed(hr);
}
return S_OK;
}
|
#include "PrecompiledHeader.h"
#include "Networking\ConnectionProperties.h"
#include "Networking\IPInformationGenerator.h"
#include "Utilities\EventHandler.h"
#include "VisualObjects.h"
#include "WhatIsMyIPApp.h"
using namespace ABI::Windows::ApplicationModel::Activation;
using namespace ABI::Windows::Foundation;
using namespace ABI::Windows::Foundation::Collections;
using namespace ABI::Windows::Networking::Connectivity;
using namespace ABI::Windows::UI;
using namespace ABI::Windows::UI::Core;
using namespace ABI::Windows::UI::ViewManagement;
using namespace ABI::Windows::UI::Xaml;
using namespace ABI::Windows::UI::Xaml::Controls;
using namespace ABI::Windows::UI::Xaml::Media;
using namespace UI;
WhatIsMyIPApp::WhatIsMyIPApp() :
m_ActiveRefreshTaskCount(0)
{
m_OnNetworkStatusChangedToken.value = 0;
}
void WhatIsMyIPApp::Cleanup()
{
if (m_OnNetworkStatusChangedToken.value != 0)
{
auto hr = Networking::IPInformation::UnsubscribeFromOnNetworkStatusChanged(m_OnNetworkStatusChangedToken);
Assert(SUCCEEDED(hr));
}
XamlApplication::Cleanup();
}
HRESULT WhatIsMyIPApp::CreatePage(IUIElement** outPage)
{
WRL::ComPtr<IPage> page;
HRESULT hr = Windows::Foundation::ActivateInstance(WRL::HStringReference(L"Windows.UI.Xaml.Controls.Page").Get(), &page);
ReturnIfFailed(hr);
WRL::ComPtr<IUIElement> grid;
hr = CreateRootGrid(&grid);
ReturnIfFailed(hr);
WRL::ComPtr<IUserControl> pageControl;
hr = page.As(&pageControl);
ReturnIfFailed(hr);
hr = pageControl->put_Content(grid.Get());
ReturnIfFailed(hr);
hr = page.As(&m_RootElement);
ReturnIfFailed(hr);
return page.Get()->QueryInterface(outPage);
}
static inline HRESULT AddGridRow(IVector<RowDefinition*>* rows, double height, GridUnitType unitType)
{
WRL::ComPtr<IRowDefinition> row;
auto hr = Windows::Foundation::ActivateInstance(WRL::HStringReference(L"Windows.UI.Xaml.Controls.RowDefinition").Get(), &row);
ReturnIfFailed(hr);
GridLength rowHeight = { height, unitType };
hr = row->put_Height(rowHeight);
ReturnIfFailed(hr);
return rows->Append(row.Get());
}
static inline HRESULT SetGridRow(IGridStatics* gridStatics, IUIElement* child, int row)
{
WRL::ComPtr<IFrameworkElement> frameworkElement;
auto hr = child->QueryInterface(__uuidof(IFrameworkElement), &frameworkElement);
ReturnIfFailed(hr);
return gridStatics->SetRow(frameworkElement.Get(), row);
}
HRESULT WhatIsMyIPApp::CreateRootGrid(IUIElement** outGrid)
{
WRL::ComPtr<IGridStatics> gridStatics;
auto hr = Windows::Foundation::GetActivationFactory(WRL::HStringReference(L"Windows.UI.Xaml.Controls.Grid").Get(), &gridStatics);
ReturnIfFailed(hr);
WRL::ComPtr<IGrid> grid;
hr = Windows::Foundation::ActivateInstance(WRL::HStringReference(L"Windows.UI.Xaml.Controls.Grid").Get(), &grid);
ReturnIfFailed(hr);
WRL::ComPtr<IPanel> gridPanel;
hr = grid.As(&gridPanel);
ReturnIfFailed(hr);
// Row layout
{
WRL::ComPtr<IVector<RowDefinition*>> rowDefinitions;
hr = grid->get_RowDefinitions(&rowDefinitions);
ReturnIfFailed(hr);
hr = AddGridRow(rowDefinitions.Get(), 15.0, GridUnitType_Pixel);
ReturnIfFailed(hr);
hr = AddGridRow(rowDefinitions.Get(), 0.0, GridUnitType_Auto);
ReturnIfFailed(hr);
}
// Background
{
WRL::ComPtr<IBrush> gridBackground;
hr = UI::VisualObjects::GetBrushFromColor(0, 0, 0, 255, &gridBackground);
ReturnIfFailed(hr);
hr = gridPanel->put_Background(gridBackground.Get());
ReturnIfFailed(hr);
}
// Children
{
WRL::ComPtr<IVector<UIElement*>> gridChildren;
hr = gridPanel->get_Children(&gridChildren);
ReturnIfFailed(hr);
WRL::ComPtr<IUIElement> uiElement;
// Progress bar
{
hr = CreateProgressBar(&uiElement);
ReturnIfFailed(hr);
hr = gridChildren->Append(uiElement.Get());
ReturnIfFailed(hr);
hr = SetGridRow(gridStatics.Get(), uiElement.Get(), 0);
ReturnIfFailed(hr);
}
// Scrollviewer
{
hr = CreateScrollViewer(&uiElement);
ReturnIfFailed(hr);
hr = gridChildren->Append(uiElement.Get());
ReturnIfFailed(hr);
hr = SetGridRow(gridStatics.Get(), uiElement.Get(), 1);
ReturnIfFailed(hr);
}
}
return grid.Get()->QueryInterface(outGrid);
}
HRESULT WhatIsMyIPApp::CreateScrollViewer(IUIElement** outScrollViewer)
{
WRL::ComPtr<IScrollViewer> scrollViewer;
auto hr = Windows::Foundation::ActivateInstance(WRL::HStringReference(L"Windows.UI.Xaml.Controls.ScrollViewer").Get(), &scrollViewer);
ReturnIfFailed(hr);
hr = scrollViewer->put_HorizontalScrollBarVisibility(ScrollBarVisibility_Auto);
ReturnIfFailed(hr);
WRL::ComPtr<IContentControl> scrollViewerContentControl;
hr = scrollViewer.As(&scrollViewerContentControl);
ReturnIfFailed(hr);
WRL::ComPtr<IUIElement> textBlockElement;
hr = CreateIPInformationTextBlock(&textBlockElement);
ReturnIfFailed(hr);
hr = scrollViewerContentControl->put_Content(textBlockElement.Get());
ReturnIfFailed(hr);
WRL::ComPtr<IUIElement> scrollViewerElement;
hr = scrollViewer.As(&scrollViewerElement);
ReturnIfFailed(hr);
return scrollViewer.Get()->QueryInterface(outScrollViewer);
}
HRESULT WhatIsMyIPApp::CreateProgressBar(IUIElement** outProgressBar)
{
WRL::ComPtr<IProgressBar> progressBar;
auto hr = Windows::Foundation::ActivateInstance(WRL::HStringReference(L"Windows.UI.Xaml.Controls.ProgressBar").Get(), &progressBar);
ReturnIfFailed(hr);
hr = progressBar->put_IsIndeterminate(true);
ReturnIfFailed(hr);
WRL::ComPtr<IFrameworkElement> progressBarFrameworkElement;
hr = progressBar.As(&progressBarFrameworkElement);
ReturnIfFailed(hr);
hr = progressBarFrameworkElement->put_VerticalAlignment(VerticalAlignment_Top);
ReturnIfFailed(hr);
hr = progressBarFrameworkElement->put_HorizontalAlignment(HorizontalAlignment_Stretch);
ReturnIfFailed(hr);
progressBar.As(&m_ProgressBar);
ReturnIfFailed(hr);
hr = m_ProgressBar->put_Visibility(Visibility_Collapsed);
ReturnIfFailed(hr);
*outProgressBar = m_ProgressBar.Get();
(*outProgressBar)->AddRef();
return S_OK;
}
HRESULT WhatIsMyIPApp::CreateIPInformationTextBlock(IUIElement** outTextBlock)
{
WRL::ComPtr<ITextBlock> textBlock;
auto hr = Windows::Foundation::ActivateInstance(WRL::HStringReference(L"Windows.UI.Xaml.Controls.TextBlock").Get(), &textBlock);
ReturnIfFailed(hr);
WRL::ComPtr<IBrush> textBrush;
hr = VisualObjects::GetBrushFromColor(255, 255, 255, 255, &textBrush);
ReturnIfFailed(hr);
hr = textBlock->put_Foreground(textBrush.Get());
ReturnIfFailed(hr);
WRL::ComPtr<IFontFamily> font;
hr = VisualObjects::GetMonospaceFont(&font);
ReturnIfFailed(hr);
if (hr != S_FALSE)
{
hr = textBlock->put_FontFamily(font.Get());
ReturnIfFailed(hr);
}
m_TextBlock = textBlock.Detach();
return m_TextBlock.Get()->QueryInterface(outTextBlock);
}
#if !WINDOWS_8_1
static HRESULT SetViewBoundsMode(ApplicationViewBoundsMode boundsMode)
{
WRL::ComPtr<IApplicationViewStatics2> applicationViewStatics;
auto hr = Windows::Foundation::GetActivationFactory(WRL::HStringReference(L"Windows.UI.ViewManagement.ApplicationView").Get(), &applicationViewStatics);
ReturnIfFailed(hr);
WRL::ComPtr<IApplicationView> applicationView;
hr = applicationViewStatics->GetForCurrentView(&applicationView);
ReturnIfFailed(hr);
WRL::ComPtr<IApplicationView2> applicationView2;
hr = applicationView.As(&applicationView2);
ReturnIfFailed(hr);
boolean success;
hr = applicationView2->SetDesiredBoundsMode(boundsMode, &success);
return hr;
}
#endif
HRESULT WhatIsMyIPApp::CreateXamlLayout()
{
HRESULT hr;
#if !WINDOWS_8_1
hr = SetViewBoundsMode(ApplicationViewBoundsMode_UseVisible);
ReturnIfFailed(hr);
#endif
hr = CreatePage(&m_RootElement);
ReturnIfFailed(hr);
return S_OK;
}
HRESULT WhatIsMyIPApp::RefreshIPInformationText()
{
if (m_ActiveRefreshTaskCount == 0)
{
auto hr = m_ProgressBar->put_Visibility(Visibility_Visible);
ReturnIfFailed(hr);
}
m_ActiveRefreshTaskCount++;
WRL::ComPtr<WhatIsMyIPApp> _this = this;
return Networking::GenerateIPInformationAsync([_this](const std::vector<Networking::ConnectionProperties>& connectionProperties)
{
std::wstringstream textStream;
HSTRING text;
for (auto& properties : connectionProperties)
{
textStream << properties.name << std::endl;
for (auto& property : properties.properties)
{
textStream << L" ";
textStream << std::setw(28) << std::left << property.first;
textStream << property.second << std::endl;
}
textStream << std::endl;
}
auto str = textStream.str();
auto hr = WindowsCreateString(str.c_str(), static_cast<uint32_t>(str.length()), &text);
ReturnIfFailed(hr);
hr = _this->ExecuteOnUIThread([_this, text]() -> HRESULT
{
WRL::HString str;
str.Attach(text);
auto hr = _this->m_TextBlock->put_Text(text);
ReturnIfFailed(hr);
_this->m_ActiveRefreshTaskCount--;
if (_this->m_ActiveRefreshTaskCount == 0)
return _this->m_ProgressBar->put_Visibility(Visibility_Collapsed);
return S_OK;
});
if (FAILED(hr))
WindowsDeleteString(text);
return hr;
});
}
HRESULT STDMETHODCALLTYPE WhatIsMyIPApp::OnLaunched(ILaunchActivatedEventArgs* args)
{
auto hr = CreateXamlLayout();
ReturnIfFailed(hr);
hr = GetWindow()->put_Content(m_RootElement.Get());
ReturnIfFailed(hr);
WRL::ComPtr<WhatIsMyIPApp> _this = this;
hr = Networking::IPInformation::SubscribeToOnNetworkStatusChanged(Utilities::EventHandlerFactory<INetworkStatusChangedEventHandler>::Make([_this](IInspectable* sender) -> HRESULT
{
return _this->ExecuteOnUIThread([_this]()
{
return _this->RefreshIPInformationText();
});
}).Get(), &m_OnNetworkStatusChangedToken);
return XamlApplication::OnLaunched(args);
}
HRESULT STDMETHODCALLTYPE WhatIsMyIPApp::OnWindowActivated(IWindowActivatedEventArgs* e)
{
CoreWindowActivationState windowActivationState;
HRESULT hr = e->get_WindowActivationState(&windowActivationState);
ReturnIfFailed(hr);
if (windowActivationState != CoreWindowActivationState_Deactivated)
{
hr = RefreshIPInformationText();
ReturnIfFailed(hr);
}
return S_OK;
}
|
Move content down by 15 pixels so it doesn't overlap with progress bar.
|
Move content down by 15 pixels so it doesn't overlap with progress bar.
|
C++
|
mit
|
TautvydasZilys/WhatIsMyIP,TautvydasZilys/WhatIsMyIP
|
04d8ce3ee82ed79793e4441a6bb7b7a756d813c6
|
JPetTaskChainExecutor/JPetTaskChainExecutor.cpp
|
JPetTaskChainExecutor/JPetTaskChainExecutor.cpp
|
/**
* @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may find a copy of the License in the LICENCE file.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @file JPetTaskChainExecutor.cpp
*/
#include "JPetTaskChainExecutor.h"
#include <cassert>
#include <memory>
#include <chrono>
#include "JPetTaskChainExecutorUtils.h"
#include "../JPetLoggerInclude.h"
JPetTaskChainExecutor::JPetTaskChainExecutor(TaskGeneratorChain* taskGeneratorChain, int processedFileId, const OptionsPerFile& opts):
fInputSeqId(processedFileId),
ftaskGeneratorChain(taskGeneratorChain)
{
assert(taskGeneratorChain->size() == opts.size());
/// ParamManager is generated and added to fParams
fParams = JPetTaskChainExecutorUtils::generateParams(opts);
assert(fParams.front().getParamManager());
if (taskGeneratorChain) {
for (auto taskGenerator : *ftaskGeneratorChain) {
auto task = taskGenerator();
fTasks.push_back(task);
}
} else {
ERROR("taskGeneratorChain is null while constructing JPetTaskChainExecutor");
}
}
bool JPetTaskChainExecutor::preprocessing(const std::vector<JPetParams>& params)
{
if (params.empty()) {
ERROR("No parameters provided!");
return false;
} else {
return JPetTaskChainExecutorUtils::process(params.front());
}
}
bool JPetTaskChainExecutor::process()
{
namespace stdc = std::chrono;
std::vector<std::pair<std::string, stdc::seconds>> elapsedTime;
auto startTime = stdc::system_clock::now();
if (!preprocessing(fParams)) {
ERROR("Error in preprocessing phase");
return false;
}
elapsedTime.push_back(std::make_pair("Preprocessing", stdc::duration_cast< stdc::seconds > (stdc::system_clock::now() - startTime)));
JPetDataInterface nullDataObject;
JPetParams outputParams;
assert(fTasks.size() == fParams.size());
auto currParamsIt = fParams.begin();
/// We iterate over both tasks and parameters
for (auto currentTaskIt = fTasks.begin(); currentTaskIt != fTasks.end(); currentTaskIt++) {
auto currentTask = *currentTaskIt;
auto taskName = currentTask->getName();
assert(currParamsIt != fParams.end());
auto currParams = *currParamsIt;
jpet_options_tools::printOptionsToLog(currParams.getOptions(), std::string("Options for ") + taskName);
currParamsIt++;
startTime = stdc::system_clock::now();
INFO(Form("Starting task: %s", taskName.c_str()));
if (!currentTask->init(currParams)) {
ERROR("In task initialization");
return false;
}
if (currentTask->run(nullDataObject)) {
ERROR("In task run()");
return false;
}
if (currentTask->terminate(outputParams)) {
ERROR("In task terminate() ");
return false;
}
elapsedTime.push_back(std::make_pair("task " + taskName, stdc::duration_cast< stdc::seconds > (stdc::system_clock::now() - startTime)));
INFO(Form("Finished task: %s", taskName.c_str()));
}
for (auto& el : elapsedTime) {
INFO("Elapsed time for " + el.first + ":" + el.second.count() + " [s]");
}
auto total = std::accumulate(elapsedTime.begin(),
elapsedTime.end(),
stdc::seconds (0),
[](const stdc::seconds prev, const std::pair <std::string, stdc::seconds>& el) {
return prev + el.second;
}
);
INFO(std::string("Total elapsed time:") + total.count() + " [s]");
return true;
}
void* JPetTaskChainExecutor::processProxy(void* runner)
{
assert(runner);
static_cast<JPetTaskChainExecutor*>(runner)->process();
return 0;
}
TThread* JPetTaskChainExecutor::run()
{
TThread* thread = new TThread(std::to_string(fInputSeqId).c_str(), processProxy, (void*)this);
assert(thread);
thread->Run();
return thread;
}
JPetTaskChainExecutor::~JPetTaskChainExecutor()
{
for (auto& task : fTasks) {
if (task) {
delete task;
task = 0;
}
}
}
|
/**
* @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may find a copy of the License in the LICENCE file.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @file JPetTaskChainExecutor.cpp
*/
#include "JPetTaskChainExecutor.h"
#include <cassert>
#include <memory>
#include <chrono>
#include "JPetTaskChainExecutorUtils.h"
#include "../JPetLoggerInclude.h"
JPetTaskChainExecutor::JPetTaskChainExecutor(TaskGeneratorChain* taskGeneratorChain, int processedFileId, const OptionsPerFile& opts):
fInputSeqId(processedFileId),
ftaskGeneratorChain(taskGeneratorChain)
{
assert(taskGeneratorChain->size() == opts.size());
/// ParamManager is generated and added to fParams
fParams = JPetTaskChainExecutorUtils::generateParams(opts);
assert(fParams.front().getParamManager());
if (taskGeneratorChain) {
for (auto taskGenerator : *ftaskGeneratorChain) {
auto task = taskGenerator();
fTasks.push_back(task);
}
} else {
ERROR("taskGeneratorChain is null while constructing JPetTaskChainExecutor");
}
}
bool JPetTaskChainExecutor::preprocessing(const std::vector<JPetParams>& params)
{
if (params.empty()) {
ERROR("No parameters provided!");
return false;
} else {
return JPetTaskChainExecutorUtils::process(params.front());
}
}
bool JPetTaskChainExecutor::process()
{
namespace stdc = std::chrono;
std::vector<std::pair<std::string, stdc::seconds>> elapsedTime;
auto startTime = stdc::system_clock::now();
if (!preprocessing(fParams)) {
ERROR("Error in preprocessing phase");
return false;
}
elapsedTime.push_back(std::make_pair("Preprocessing", stdc::duration_cast< stdc::seconds > (stdc::system_clock::now() - startTime)));
JPetDataInterface nullDataObject;
JPetParams outputParams;
assert(fTasks.size() == fParams.size());
auto currParamsIt = fParams.begin();
/// We iterate over both tasks and parameters
for (auto currentTaskIt = fTasks.begin(); currentTaskIt != fTasks.end(); currentTaskIt++) {
auto currentTask = *currentTaskIt;
auto taskName = currentTask->getName();
assert(currParamsIt != fParams.end());
auto currParams = *currParamsIt;
jpet_options_tools::printOptionsToLog(currParams.getOptions(), std::string("Options for ") + taskName);
currParamsIt++;
startTime = stdc::system_clock::now();
INFO(Form("Starting task: %s", taskName.c_str()));
if (!currentTask->init(currParams)) {
ERROR("In task initialization");
return false;
}
if (!currentTask->run(nullDataObject)) {
ERROR("In task run()");
return false;
}
if (!currentTask->terminate(outputParams)) {
ERROR("In task terminate() ");
return false;
}
elapsedTime.push_back(std::make_pair("task " + taskName, stdc::duration_cast< stdc::seconds > (stdc::system_clock::now() - startTime)));
INFO(Form("Finished task: %s", taskName.c_str()));
}
for (auto& el : elapsedTime) {
INFO("Elapsed time for " + el.first + ":" + el.second.count() + " [s]");
}
auto total = std::accumulate(elapsedTime.begin(),
elapsedTime.end(),
stdc::seconds (0),
[](const stdc::seconds prev, const std::pair <std::string, stdc::seconds>& el) {
return prev + el.second;
}
);
INFO(std::string("Total elapsed time:") + total.count() + " [s]");
return true;
}
void* JPetTaskChainExecutor::processProxy(void* runner)
{
assert(runner);
static_cast<JPetTaskChainExecutor*>(runner)->process();
return 0;
}
TThread* JPetTaskChainExecutor::run()
{
TThread* thread = new TThread(std::to_string(fInputSeqId).c_str(), processProxy, (void*)this);
assert(thread);
thread->Run();
return thread;
}
JPetTaskChainExecutor::~JPetTaskChainExecutor()
{
for (auto& task : fTasks) {
if (task) {
delete task;
task = 0;
}
}
}
|
Fix error condition in run and terminate
|
Fix error condition in run and terminate
|
C++
|
apache-2.0
|
JPETTomography/j-pet-framework,alexkernphysiker/j-pet-framework,JPETTomography/j-pet-framework,alexkernphysiker/j-pet-framework,alexkernphysiker/j-pet-framework,alexkernphysiker/j-pet-framework,JPETTomography/j-pet-framework,alexkernphysiker/j-pet-framework
|
03f6982c93f7a092b7c36aaefc004d60e491f96e
|
chrome/browser/extensions/extension_ui_unittest.cc
|
chrome/browser/extensions/extension_ui_unittest.cc
|
// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/browser/extensions/extensions_ui.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/json_value_serializer.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
static DictionaryValue* DeserializeJSONTestData(const FilePath& path,
std::string *error) {
Value* value;
JSONFileValueSerializer serializer(path);
value = serializer.Deserialize(error);
return static_cast<DictionaryValue*>(value);
}
static bool CompareExpectedAndActualOutput(
const FilePath& extension_path,
const std::vector<ExtensionPage>& pages,
const FilePath& expected_output_path) {
// TODO(rafaelw): Using the extension_path passed in above, causes this
// unit test to fail on linux. The Values come back valid, but the
// UserScript.path() values return "".
#if defined(OS_WIN)
FilePath path(FILE_PATH_LITERAL("c:\\foo"));
#elif defined(OS_POSIX)
FilePath path(FILE_PATH_LITERAL("/foo"));
#endif
Extension extension(path);
std::string error;
FilePath manifest_path = extension_path.AppendASCII(
Extension::kManifestFilename);
scoped_ptr<DictionaryValue> extension_data(DeserializeJSONTestData(
manifest_path, &error));
EXPECT_EQ("", error);
EXPECT_TRUE(extension.InitFromValue(*extension_data, true, &error));
EXPECT_EQ("", error);
scoped_ptr<DictionaryValue>expected_output_data(DeserializeJSONTestData(
expected_output_path, &error));
EXPECT_EQ("", error);
// Produce test output.
scoped_ptr<DictionaryValue> actual_output_data(
ExtensionsDOMHandler::CreateExtensionDetailValue(&extension, pages));
// Compare the outputs.
return expected_output_data->Equals(actual_output_data.get());
}
} // namespace
class ExtensionUITest : public testing::Test {
};
TEST(ExtensionUITest, GenerateExtensionsJSONData) {
FilePath data_test_dir_path, extension_path, expected_output_path;
EXPECT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &data_test_dir_path));
// Test Extension1
extension_path = data_test_dir_path.AppendASCII("extensions")
.AppendASCII("good")
.AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
.AppendASCII("1.0.0.0");
std::vector<ExtensionPage> pages;
pages.push_back(ExtensionPage(
GURL("chrome-extension://behllobkkfkfnphdnhnkndlbkcpglgmj/bar.html"),
42, 88));
pages.push_back(ExtensionPage(
GURL("chrome-extension://behllobkkfkfnphdnhnkndlbkcpglgmj/dog.html"),
0, 0));
expected_output_path = data_test_dir_path.AppendASCII("extensions")
.AppendASCII("ui")
.AppendASCII("create_extension_detail_value_expected_output")
.AppendASCII("good-extension1.json");
EXPECT_TRUE(CompareExpectedAndActualOutput(extension_path, pages,
expected_output_path)) << extension_path.value();
// Test Extension2
extension_path = data_test_dir_path.AppendASCII("extensions")
.AppendASCII("good")
.AppendASCII("hpiknbiabeeppbpihjehijgoemciehgk")
.AppendASCII("2");
expected_output_path = data_test_dir_path.AppendASCII("extensions")
.AppendASCII("ui")
.AppendASCII("create_extension_detail_value_expected_output")
.AppendASCII("good-extension2.json");
// It's OK to have duplicate URLs, so long as the IDs are different.
pages[1].url = pages[0].url;
EXPECT_TRUE(CompareExpectedAndActualOutput(extension_path, pages,
expected_output_path)) << extension_path.value();
// Test Extension3
extension_path = data_test_dir_path.AppendASCII("extensions")
.AppendASCII("good")
.AppendASCII("bjafgdebaacbbbecmhlhpofkepfkgcpa")
.AppendASCII("1.0");
expected_output_path = data_test_dir_path.AppendASCII("extensions")
.AppendASCII("ui")
.AppendASCII("create_extension_detail_value_expected_output")
.AppendASCII("good-extension3.json");
pages.clear();
EXPECT_TRUE(CompareExpectedAndActualOutput(extension_path, pages,
expected_output_path)) << extension_path.value();
}
|
// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/browser/extensions/extensions_ui.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/json_value_serializer.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
static DictionaryValue* DeserializeJSONTestData(const FilePath& path,
std::string *error) {
Value* value;
JSONFileValueSerializer serializer(path);
value = serializer.Deserialize(error);
return static_cast<DictionaryValue*>(value);
}
static bool CompareExpectedAndActualOutput(
const FilePath& extension_path,
const std::vector<ExtensionPage>& pages,
const FilePath& expected_output_path) {
// TODO(rafaelw): Using the extension_path passed in above, causes this
// unit test to fail on linux. The Values come back valid, but the
// UserScript.path() values return "".
#if defined(OS_WIN)
FilePath path(FILE_PATH_LITERAL("c:\\foo"));
#elif defined(OS_POSIX)
FilePath path(FILE_PATH_LITERAL("/foo"));
#endif
Extension extension(path);
std::string error;
FilePath manifest_path = extension_path.AppendASCII(
Extension::kManifestFilename);
scoped_ptr<DictionaryValue> extension_data(DeserializeJSONTestData(
manifest_path, &error));
EXPECT_EQ("", error);
EXPECT_TRUE(extension.InitFromValue(*extension_data, true, &error));
EXPECT_EQ("", error);
scoped_ptr<DictionaryValue>expected_output_data(DeserializeJSONTestData(
expected_output_path, &error));
EXPECT_EQ("", error);
// Produce test output.
scoped_ptr<DictionaryValue> actual_output_data(
ExtensionsDOMHandler::CreateExtensionDetailValue(&extension, pages));
// Compare the outputs.
return expected_output_data->Equals(actual_output_data.get());
}
} // namespace
class ExtensionUITest : public testing::Test {
};
TEST(ExtensionUITest, GenerateExtensionsJSONData) {
FilePath data_test_dir_path, extension_path, expected_output_path;
EXPECT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &data_test_dir_path));
// Test Extension1
extension_path = data_test_dir_path.AppendASCII("extensions")
.AppendASCII("good")
.AppendASCII("Extensions")
.AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
.AppendASCII("1.0.0.0");
std::vector<ExtensionPage> pages;
pages.push_back(ExtensionPage(
GURL("chrome-extension://behllobkkfkfnphdnhnkndlbkcpglgmj/bar.html"),
42, 88));
pages.push_back(ExtensionPage(
GURL("chrome-extension://behllobkkfkfnphdnhnkndlbkcpglgmj/dog.html"),
0, 0));
expected_output_path = data_test_dir_path.AppendASCII("extensions")
.AppendASCII("ui")
.AppendASCII("create_extension_detail_value_expected_output")
.AppendASCII("good-extension1.json");
EXPECT_TRUE(CompareExpectedAndActualOutput(extension_path, pages,
expected_output_path)) << extension_path.value();
// Test Extension2
extension_path = data_test_dir_path.AppendASCII("extensions")
.AppendASCII("good")
.AppendASCII("Extensions")
.AppendASCII("hpiknbiabeeppbpihjehijgoemciehgk")
.AppendASCII("2");
expected_output_path = data_test_dir_path.AppendASCII("extensions")
.AppendASCII("ui")
.AppendASCII("create_extension_detail_value_expected_output")
.AppendASCII("good-extension2.json");
// It's OK to have duplicate URLs, so long as the IDs are different.
pages[1].url = pages[0].url;
EXPECT_TRUE(CompareExpectedAndActualOutput(extension_path, pages,
expected_output_path)) << extension_path.value();
// Test Extension3
extension_path = data_test_dir_path.AppendASCII("extensions")
.AppendASCII("good")
.AppendASCII("Extensions")
.AppendASCII("bjafgdebaacbbbecmhlhpofkepfkgcpa")
.AppendASCII("1.0");
expected_output_path = data_test_dir_path.AppendASCII("extensions")
.AppendASCII("ui")
.AppendASCII("create_extension_detail_value_expected_output")
.AppendASCII("good-extension3.json");
pages.clear();
EXPECT_TRUE(CompareExpectedAndActualOutput(extension_path, pages,
expected_output_path)) << extension_path.value();
}
|
Fix unit_test breakage from http://codereview.chromium.org/140018
|
Fix unit_test breakage from http://codereview.chromium.org/140018
R=sky
Review URL: http://codereview.chromium.org/147169
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@19288 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
yitian134/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,gavinp/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,ropik/chromium,adobe/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,yitian134/chromium,gavinp/chromium,gavinp/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,adobe/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,ropik/chromium,ropik/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium
|
e5b6f1245709e42b11cbe7a8e3b92bb5f399034a
|
plugins/matcher/matcher.cpp
|
plugins/matcher/matcher.cpp
|
#include "matcher.hpp"
#include "matcher-ast.hpp"
#include <wayfire/debug.hpp>
#include <wayfire/singleton-plugin.hpp>
#include <wayfire/core.hpp>
#include <wayfire/output.hpp>
#include <wayfire/workspace-manager.hpp>
#include <wayfire/util/log.hpp>
extern "C"
{
#define static
#define class class_t
#define namespace namespace_t
#include <wlr/xwayland.h>
#undef static
#undef class
#undef namespace
}
namespace wf
{
namespace matcher
{
std::string get_view_type(wayfire_view view)
{
if (view->role == VIEW_ROLE_TOPLEVEL)
return "toplevel";
if (view->role == VIEW_ROLE_UNMANAGED)
{
auto surf = view->get_wlr_surface();
if (surf && wlr_surface_is_xwayland_surface(surf)) {
return "x-or";
} else {
return "unmanaged";
}
}
if (!view->get_output())
return "unknown";
uint32_t layer = view->get_output()->workspace->get_view_layer(view);
if (layer == LAYER_BACKGROUND || layer == LAYER_BOTTOM)
return "background";
if (layer == LAYER_TOP)
return "panel";
if (layer == LAYER_LOCK)
return "overlay";
return "unknown";
};
class default_view_matcher : public view_matcher
{
std::unique_ptr<expression_t> expr;
wf::option_sptr_t<std::string> match_option;
wf::config::option_base_t::updated_callback_t on_match_string_updated = [=] ()
{
auto result = parse_expression(match_option->get_value_str());
if (!result.first)
{
LOGE("Failed to load match expression %s:\n%s",
match_option->get_value_str().c_str(), result.second.c_str());
}
this->expr = std::move(result.first);
};
public:
default_view_matcher(wf::option_sptr_t<std::string> option)
: match_option(option)
{
on_match_string_updated();
match_option->add_updated_handler(&on_match_string_updated);
}
virtual ~default_view_matcher()
{
match_option->rem_updated_handler(&on_match_string_updated);
}
virtual bool matches(wayfire_view view) const
{
if (!expr || !view->is_mapped())
return false;
view_t data;
data.title = view->get_title();
data.app_id = view->get_app_id();
data.type = get_view_type(view);
data.focuseable = view->is_focuseable() ? "true" : "false";
return expr->evaluate(data);
}
};
class matcher_plugin
{
signal_callback_t on_new_matcher_request = [=] (signal_data_t *data)
{
auto ev = static_cast<match_signal*> (data);
ev->result = std::make_unique<default_view_matcher> (ev->expression);
};
signal_callback_t on_matcher_evaluate = [=] (signal_data_t *data)
{
auto ev = static_cast<match_evaluate_signal*> (data);
auto expr =
dynamic_cast<default_view_matcher*> (ev->matcher.get());
if (expr)
ev->result = expr->matches(ev->view);
};
public:
matcher_plugin()
{
wf::get_core().connect_signal(WF_MATCHER_CREATE_QUERY_SIGNAL,
&on_new_matcher_request);
wf::get_core().connect_signal(WF_MATCHER_EVALUATE_SIGNAL,
&on_matcher_evaluate);
}
};
class matcher_singleton : public wf::singleton_plugin_t<matcher_plugin>
{
bool is_unloadable() override {return false;}
};
}
}
DECLARE_WAYFIRE_PLUGIN(wf::matcher::matcher_singleton);
|
#include "matcher.hpp"
#include "matcher-ast.hpp"
#include <wayfire/debug.hpp>
#include <wayfire/singleton-plugin.hpp>
#include <wayfire/core.hpp>
#include <wayfire/output.hpp>
#include <wayfire/workspace-manager.hpp>
#include <wayfire/util/log.hpp>
#if WLR_HAS_XWAYLAND
extern "C"
{
#define static
#define class class_t
#define namespace namespace_t
#include <wlr/xwayland.h>
#undef static
#undef class
#undef namespace
}
#endif
namespace wf
{
namespace matcher
{
std::string get_view_type(wayfire_view view)
{
if (view->role == VIEW_ROLE_TOPLEVEL)
return "toplevel";
if (view->role == VIEW_ROLE_UNMANAGED)
{
auto surf = view->get_wlr_surface();
#if WLR_HAS_XWAYLAND
if (surf && wlr_surface_is_xwayland_surface(surf))
return "x-or";
#endif
return "unmanaged";
}
if (!view->get_output())
return "unknown";
uint32_t layer = view->get_output()->workspace->get_view_layer(view);
if (layer == LAYER_BACKGROUND || layer == LAYER_BOTTOM)
return "background";
if (layer == LAYER_TOP)
return "panel";
if (layer == LAYER_LOCK)
return "overlay";
return "unknown";
};
class default_view_matcher : public view_matcher
{
std::unique_ptr<expression_t> expr;
wf::option_sptr_t<std::string> match_option;
wf::config::option_base_t::updated_callback_t on_match_string_updated = [=] ()
{
auto result = parse_expression(match_option->get_value_str());
if (!result.first)
{
LOGE("Failed to load match expression %s:\n%s",
match_option->get_value_str().c_str(), result.second.c_str());
}
this->expr = std::move(result.first);
};
public:
default_view_matcher(wf::option_sptr_t<std::string> option)
: match_option(option)
{
on_match_string_updated();
match_option->add_updated_handler(&on_match_string_updated);
}
virtual ~default_view_matcher()
{
match_option->rem_updated_handler(&on_match_string_updated);
}
virtual bool matches(wayfire_view view) const
{
if (!expr || !view->is_mapped())
return false;
view_t data;
data.title = view->get_title();
data.app_id = view->get_app_id();
data.type = get_view_type(view);
data.focuseable = view->is_focuseable() ? "true" : "false";
return expr->evaluate(data);
}
};
class matcher_plugin
{
signal_callback_t on_new_matcher_request = [=] (signal_data_t *data)
{
auto ev = static_cast<match_signal*> (data);
ev->result = std::make_unique<default_view_matcher> (ev->expression);
};
signal_callback_t on_matcher_evaluate = [=] (signal_data_t *data)
{
auto ev = static_cast<match_evaluate_signal*> (data);
auto expr =
dynamic_cast<default_view_matcher*> (ev->matcher.get());
if (expr)
ev->result = expr->matches(ev->view);
};
public:
matcher_plugin()
{
wf::get_core().connect_signal(WF_MATCHER_CREATE_QUERY_SIGNAL,
&on_new_matcher_request);
wf::get_core().connect_signal(WF_MATCHER_EVALUATE_SIGNAL,
&on_matcher_evaluate);
}
};
class matcher_singleton : public wf::singleton_plugin_t<matcher_plugin>
{
bool is_unloadable() override {return false;}
};
}
}
DECLARE_WAYFIRE_PLUGIN(wf::matcher::matcher_singleton);
|
fix build without xwayland
|
matcher: fix build without xwayland
|
C++
|
mit
|
ammen99/wayfire,ammen99/wayfire
|
a14fac4e51e48c6fb9e2e5fc6e33b97eac991193
|
tools/llvm-pdbutil/PrettyClassLayoutGraphicalDumper.cpp
|
tools/llvm-pdbutil/PrettyClassLayoutGraphicalDumper.cpp
|
//===- PrettyClassLayoutGraphicalDumper.h -----------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "PrettyClassLayoutGraphicalDumper.h"
#include "LinePrinter.h"
#include "PrettyClassDefinitionDumper.h"
#include "PrettyEnumDumper.h"
#include "PrettyFunctionDumper.h"
#include "PrettyTypedefDumper.h"
#include "PrettyVariableDumper.h"
#include "PrettyVariableDumper.h"
#include "llvm-pdbutil.h"
#include "llvm/DebugInfo/PDB/PDBSymbolData.h"
#include "llvm/DebugInfo/PDB/PDBSymbolTypeBaseClass.h"
#include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h"
#include "llvm/DebugInfo/PDB/UDTLayout.h"
#include "llvm/Support/Format.h"
using namespace llvm;
using namespace llvm::pdb;
PrettyClassLayoutGraphicalDumper::PrettyClassLayoutGraphicalDumper(
LinePrinter &P, uint32_t RecurseLevel, uint32_t InitialOffset)
: PDBSymDumper(true), Printer(P), RecursionLevel(RecurseLevel),
ClassOffsetZero(InitialOffset), CurrentAbsoluteOffset(InitialOffset) {}
bool PrettyClassLayoutGraphicalDumper::start(const UDTLayoutBase &Layout) {
if (RecursionLevel == 1 &&
opts::pretty::ClassFormat == opts::pretty::ClassDefinitionFormat::All) {
for (auto &Other : Layout.other_items())
Other->dump(*this);
for (auto &Func : Layout.funcs())
Func->dump(*this);
}
const BitVector &UseMap = Layout.usedBytes();
int NextPaddingByte = UseMap.find_first_unset();
for (auto &Item : Layout.layout_items()) {
// Calculate the absolute offset of the first byte of the next field.
uint32_t RelativeOffset = Item->getOffsetInParent();
CurrentAbsoluteOffset = ClassOffsetZero + RelativeOffset;
// Since there is storage there, it should be set! However, this might
// be an empty base, in which case it could extend outside the bounds of
// the parent class.
if (RelativeOffset < UseMap.size() && (Item->getSize() > 0)) {
assert(UseMap.test(RelativeOffset));
// If there is any remaining padding in this class, and the offset of the
// new item is after the padding, then we must have just jumped over some
// padding. Print a padding row and then look for where the next block
// of padding begins.
if ((NextPaddingByte >= 0) &&
(RelativeOffset > uint32_t(NextPaddingByte))) {
printPaddingRow(RelativeOffset - NextPaddingByte);
NextPaddingByte = UseMap.find_next_unset(RelativeOffset);
}
}
CurrentItem = Item;
if (Item->isVBPtr()) {
VTableLayoutItem &Layout = static_cast<VTableLayoutItem &>(*CurrentItem);
VariableDumper VarDumper(Printer);
VarDumper.startVbptr(CurrentAbsoluteOffset, Layout.getSize());
} else {
if (auto Sym = Item->getSymbol())
Sym->dump(*this);
}
if (Item->getLayoutSize() > 0) {
uint32_t Prev = RelativeOffset + Item->getLayoutSize() - 1;
if (Prev < UseMap.size())
NextPaddingByte = UseMap.find_next_unset(Prev);
}
}
auto TailPadding = Layout.tailPadding();
if (TailPadding > 0) {
if (TailPadding != 1 || Layout.getSize() != 1) {
Printer.NewLine();
WithColor(Printer, PDB_ColorItem::Padding).get()
<< "<padding> (" << TailPadding << " bytes)";
DumpedAnything = true;
}
}
return DumpedAnything;
}
void PrettyClassLayoutGraphicalDumper::printPaddingRow(uint32_t Amount) {
if (Amount == 0)
return;
Printer.NewLine();
WithColor(Printer, PDB_ColorItem::Padding).get() << "<padding> (" << Amount
<< " bytes)";
DumpedAnything = true;
}
void PrettyClassLayoutGraphicalDumper::dump(
const PDBSymbolTypeBaseClass &Symbol) {
assert(CurrentItem != nullptr);
Printer.NewLine();
BaseClassLayout &Layout = static_cast<BaseClassLayout &>(*CurrentItem);
std::string Label = "base";
if (Layout.isVirtualBase()) {
Label.insert(Label.begin(), 'v');
if (Layout.getBase().isIndirectVirtualBaseClass())
Label.insert(Label.begin(), 'i');
}
Printer << Label << " ";
uint32_t Size = Layout.isEmptyBase() ? 1 : Layout.getLayoutSize();
WithColor(Printer, PDB_ColorItem::Offset).get()
<< "+" << format_hex(CurrentAbsoluteOffset, 4) << " [sizeof=" << Size
<< "] ";
WithColor(Printer, PDB_ColorItem::Identifier).get() << Layout.getName();
if (shouldRecurse()) {
Printer.Indent();
uint32_t ChildOffsetZero = ClassOffsetZero + Layout.getOffsetInParent();
PrettyClassLayoutGraphicalDumper BaseDumper(Printer, RecursionLevel + 1,
ChildOffsetZero);
DumpedAnything |= BaseDumper.start(Layout);
Printer.Unindent();
}
DumpedAnything = true;
}
bool PrettyClassLayoutGraphicalDumper::shouldRecurse() const {
uint32_t Limit = opts::pretty::ClassRecursionDepth;
if (Limit == 0)
return true;
return RecursionLevel < Limit;
}
void PrettyClassLayoutGraphicalDumper::dump(const PDBSymbolData &Symbol) {
VariableDumper VarDumper(Printer);
VarDumper.start(Symbol, ClassOffsetZero);
if (CurrentItem != nullptr) {
DataMemberLayoutItem &Layout =
static_cast<DataMemberLayoutItem &>(*CurrentItem);
if (Layout.hasUDTLayout() && shouldRecurse()) {
uint32_t ChildOffsetZero = ClassOffsetZero + Layout.getOffsetInParent();
Printer.Indent();
PrettyClassLayoutGraphicalDumper TypeDumper(Printer, RecursionLevel + 1,
ChildOffsetZero);
TypeDumper.start(Layout.getUDTLayout());
Printer.Unindent();
}
}
DumpedAnything = true;
}
void PrettyClassLayoutGraphicalDumper::dump(const PDBSymbolTypeVTable &Symbol) {
assert(CurrentItem != nullptr);
VariableDumper VarDumper(Printer);
VarDumper.start(Symbol, ClassOffsetZero);
DumpedAnything = true;
}
void PrettyClassLayoutGraphicalDumper::dump(const PDBSymbolTypeEnum &Symbol) {
DumpedAnything = true;
Printer.NewLine();
EnumDumper Dumper(Printer);
Dumper.start(Symbol);
}
void PrettyClassLayoutGraphicalDumper::dump(
const PDBSymbolTypeTypedef &Symbol) {
DumpedAnything = true;
Printer.NewLine();
TypedefDumper Dumper(Printer);
Dumper.start(Symbol);
}
void PrettyClassLayoutGraphicalDumper::dump(
const PDBSymbolTypeBuiltin &Symbol) {}
void PrettyClassLayoutGraphicalDumper::dump(const PDBSymbolTypeUDT &Symbol) {}
void PrettyClassLayoutGraphicalDumper::dump(const PDBSymbolFunc &Symbol) {
if (Printer.IsSymbolExcluded(Symbol.getName()))
return;
if (Symbol.isCompilerGenerated() && opts::pretty::ExcludeCompilerGenerated)
return;
if (Symbol.getLength() == 0 && !Symbol.isPureVirtual() &&
!Symbol.isIntroVirtualFunction())
return;
DumpedAnything = true;
Printer.NewLine();
FunctionDumper Dumper(Printer);
Dumper.start(Symbol, FunctionDumper::PointerType::None);
}
|
//===- PrettyClassLayoutGraphicalDumper.h -----------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "PrettyClassLayoutGraphicalDumper.h"
#include "LinePrinter.h"
#include "PrettyClassDefinitionDumper.h"
#include "PrettyEnumDumper.h"
#include "PrettyFunctionDumper.h"
#include "PrettyTypedefDumper.h"
#include "PrettyVariableDumper.h"
#include "PrettyVariableDumper.h"
#include "llvm-pdbutil.h"
#include "llvm/DebugInfo/PDB/PDBSymbolData.h"
#include "llvm/DebugInfo/PDB/PDBSymbolTypeBaseClass.h"
#include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h"
#include "llvm/DebugInfo/PDB/UDTLayout.h"
#include "llvm/Support/Format.h"
using namespace llvm;
using namespace llvm::pdb;
PrettyClassLayoutGraphicalDumper::PrettyClassLayoutGraphicalDumper(
LinePrinter &P, uint32_t RecurseLevel, uint32_t InitialOffset)
: PDBSymDumper(true), Printer(P), RecursionLevel(RecurseLevel),
ClassOffsetZero(InitialOffset), CurrentAbsoluteOffset(InitialOffset) {}
bool PrettyClassLayoutGraphicalDumper::start(const UDTLayoutBase &Layout) {
if (RecursionLevel == 1 &&
opts::pretty::ClassFormat == opts::pretty::ClassDefinitionFormat::All) {
for (auto &Other : Layout.other_items())
Other->dump(*this);
for (auto &Func : Layout.funcs())
Func->dump(*this);
}
const BitVector &UseMap = Layout.usedBytes();
int NextPaddingByte = UseMap.find_first_unset();
for (auto &Item : Layout.layout_items()) {
// Calculate the absolute offset of the first byte of the next field.
uint32_t RelativeOffset = Item->getOffsetInParent();
CurrentAbsoluteOffset = ClassOffsetZero + RelativeOffset;
// This might be an empty base, in which case it could extend outside the
// bounds of the parent class.
if (RelativeOffset < UseMap.size() && (Item->getSize() > 0)) {
// If there is any remaining padding in this class, and the offset of the
// new item is after the padding, then we must have just jumped over some
// padding. Print a padding row and then look for where the next block
// of padding begins.
if ((NextPaddingByte >= 0) &&
(RelativeOffset > uint32_t(NextPaddingByte))) {
printPaddingRow(RelativeOffset - NextPaddingByte);
NextPaddingByte = UseMap.find_next_unset(RelativeOffset);
}
}
CurrentItem = Item;
if (Item->isVBPtr()) {
VTableLayoutItem &Layout = static_cast<VTableLayoutItem &>(*CurrentItem);
VariableDumper VarDumper(Printer);
VarDumper.startVbptr(CurrentAbsoluteOffset, Layout.getSize());
} else {
if (auto Sym = Item->getSymbol())
Sym->dump(*this);
}
if (Item->getLayoutSize() > 0) {
uint32_t Prev = RelativeOffset + Item->getLayoutSize() - 1;
if (Prev < UseMap.size())
NextPaddingByte = UseMap.find_next_unset(Prev);
}
}
auto TailPadding = Layout.tailPadding();
if (TailPadding > 0) {
if (TailPadding != 1 || Layout.getSize() != 1) {
Printer.NewLine();
WithColor(Printer, PDB_ColorItem::Padding).get()
<< "<padding> (" << TailPadding << " bytes)";
DumpedAnything = true;
}
}
return DumpedAnything;
}
void PrettyClassLayoutGraphicalDumper::printPaddingRow(uint32_t Amount) {
if (Amount == 0)
return;
Printer.NewLine();
WithColor(Printer, PDB_ColorItem::Padding).get() << "<padding> (" << Amount
<< " bytes)";
DumpedAnything = true;
}
void PrettyClassLayoutGraphicalDumper::dump(
const PDBSymbolTypeBaseClass &Symbol) {
assert(CurrentItem != nullptr);
Printer.NewLine();
BaseClassLayout &Layout = static_cast<BaseClassLayout &>(*CurrentItem);
std::string Label = "base";
if (Layout.isVirtualBase()) {
Label.insert(Label.begin(), 'v');
if (Layout.getBase().isIndirectVirtualBaseClass())
Label.insert(Label.begin(), 'i');
}
Printer << Label << " ";
uint32_t Size = Layout.isEmptyBase() ? 1 : Layout.getLayoutSize();
WithColor(Printer, PDB_ColorItem::Offset).get()
<< "+" << format_hex(CurrentAbsoluteOffset, 4) << " [sizeof=" << Size
<< "] ";
WithColor(Printer, PDB_ColorItem::Identifier).get() << Layout.getName();
if (shouldRecurse()) {
Printer.Indent();
uint32_t ChildOffsetZero = ClassOffsetZero + Layout.getOffsetInParent();
PrettyClassLayoutGraphicalDumper BaseDumper(Printer, RecursionLevel + 1,
ChildOffsetZero);
DumpedAnything |= BaseDumper.start(Layout);
Printer.Unindent();
}
DumpedAnything = true;
}
bool PrettyClassLayoutGraphicalDumper::shouldRecurse() const {
uint32_t Limit = opts::pretty::ClassRecursionDepth;
if (Limit == 0)
return true;
return RecursionLevel < Limit;
}
void PrettyClassLayoutGraphicalDumper::dump(const PDBSymbolData &Symbol) {
VariableDumper VarDumper(Printer);
VarDumper.start(Symbol, ClassOffsetZero);
if (CurrentItem != nullptr) {
DataMemberLayoutItem &Layout =
static_cast<DataMemberLayoutItem &>(*CurrentItem);
if (Layout.hasUDTLayout() && shouldRecurse()) {
uint32_t ChildOffsetZero = ClassOffsetZero + Layout.getOffsetInParent();
Printer.Indent();
PrettyClassLayoutGraphicalDumper TypeDumper(Printer, RecursionLevel + 1,
ChildOffsetZero);
TypeDumper.start(Layout.getUDTLayout());
Printer.Unindent();
}
}
DumpedAnything = true;
}
void PrettyClassLayoutGraphicalDumper::dump(const PDBSymbolTypeVTable &Symbol) {
assert(CurrentItem != nullptr);
VariableDumper VarDumper(Printer);
VarDumper.start(Symbol, ClassOffsetZero);
DumpedAnything = true;
}
void PrettyClassLayoutGraphicalDumper::dump(const PDBSymbolTypeEnum &Symbol) {
DumpedAnything = true;
Printer.NewLine();
EnumDumper Dumper(Printer);
Dumper.start(Symbol);
}
void PrettyClassLayoutGraphicalDumper::dump(
const PDBSymbolTypeTypedef &Symbol) {
DumpedAnything = true;
Printer.NewLine();
TypedefDumper Dumper(Printer);
Dumper.start(Symbol);
}
void PrettyClassLayoutGraphicalDumper::dump(
const PDBSymbolTypeBuiltin &Symbol) {}
void PrettyClassLayoutGraphicalDumper::dump(const PDBSymbolTypeUDT &Symbol) {}
void PrettyClassLayoutGraphicalDumper::dump(const PDBSymbolFunc &Symbol) {
if (Printer.IsSymbolExcluded(Symbol.getName()))
return;
if (Symbol.isCompilerGenerated() && opts::pretty::ExcludeCompilerGenerated)
return;
if (Symbol.getLength() == 0 && !Symbol.isPureVirtual() &&
!Symbol.isIntroVirtualFunction())
return;
DumpedAnything = true;
Printer.NewLine();
FunctionDumper Dumper(Printer);
Dumper.start(Symbol, FunctionDumper::PointerType::None);
}
|
Remove faulty assertion in llvm-pdbutil
|
Remove faulty assertion in llvm-pdbutil
If a class's first data member is an instance of an empty class, then an
assertion in the PrettyClassLayoutGraphicalDumper would fail. The
storage is reserved, but it's not marked as in use.
As far as I understand, it's the assertion that's faulty, so I removed it
and updated the nearby comment.
Found by running llvm-pdbutil against its own PDB, and this assertion would
fail on HashAdjusters, which is a HashTable whose first data member is a
TraitsT, which is a PdbHashTraits<T>, which is an empty struct. (The struct
has a specialization for uint32_t, but that specialization doesn't apply
here because the T is actually ulittle32_t.)
Differential Revision: https://reviews.llvm.org/D45645
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@330135 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm
|
99b9f822c8c4d526d7ada4cac6ef4e35a9810095
|
src/nacl/libchewing/nacl.cc
|
src/nacl/libchewing/nacl.cc
|
// Copyright 2013 Google Inc. All Rights Reserved.
/**
* @fileoverview NaCl loader for libchewing.
* @author [email protected] (Hung-Te Lin)
*
* Accept messages:
* key:<KEY NAME>
*
* Output messages:
* debug:<DEBUG MESSAGE>
* context:<IM context>
*/
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <pthread.h> // for nacl_io
#include <stdlib.h>
#include <unistd.h>
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/var.h"
#include "nacl_io/nacl_io.h"
#include "json/writer.h"
#include "chewing.h"
#include "chewing-private.h"
using std::string;
#define ARRAYSIZE(x) (sizeof(x)/sizeof(x[0]))
extern "C" size_t getpagesize() {
return sysconf(_SC_PAGESIZE);
}
////////////////////////////////////////////////////////////////////////
// Module Initialization.
////////////////////////////////////////////////////////////////////////
typedef struct {
const char *keyname;
int (*handler)(ChewingContext *ctx);
} ChewingKeyMapping;
ChewingKeyMapping special_key_mappings[] = {
{ "Backspace", chewing_handle_Backspace, },
{ "Tab", chewing_handle_Tab, },
{ "Enter", chewing_handle_Enter, },
{ "Shift", chewing_handle_ShiftLeft, },
{ "CapsLock", chewing_handle_Capslock, },
{ "Esc", chewing_handle_Esc, },
{ " ", chewing_handle_Space, },
{ "PageUp", chewing_handle_PageUp, },
{ "PageDown", chewing_handle_PageDown, },
{ "End", chewing_handle_End, },
{ "Home", chewing_handle_Home, },
{ "Left", chewing_handle_Left, },
{ "Up", chewing_handle_Up, },
{ "Right", chewing_handle_Right, },
{ "Down", chewing_handle_Down, },
{ "Delete", chewing_handle_Del, },
};
void *chewing_init_context(void *arg);
class ChewingInstance: public pp::Instance {
protected:
const string kMsgDebugPrefix;
const string kMsgContextPrefix;
const string kMsgKeyPrefix;
const string kMsgLayoutPrefix;
public:
ChewingContext *ctx;
explicit ChewingInstance(PP_Instance instance): pp::Instance(instance),
kMsgDebugPrefix("debug:"), kMsgContextPrefix("context:"),
kMsgKeyPrefix("key:"), kMsgLayoutPrefix("layout:"), ctx(NULL) {
const char *data_dir = "/data", *user_data_dir = "/user_data";
nacl_io_init_ppapi(instance, pp::Module::Get()->get_browser_interface());
if (mount("libchewing/data", data_dir, "httpfs", 0, "") != 0) {
PostMessage(pp::Var("can't mount data"));
return;
}
// TODO(hungte) change memfs to html5fs.
if (mount("", user_data_dir, "html5fs", 0,
"type=PERSISTENT,expected_size=1048576") != 0) {
PostMessage(pp::Var("can't mount user data"));
return;
}
// Note chewing library does not really take path on its Init...
// So we always need to do putenv.
char chewing_path[] = "CHEWING_PATH=/data";
char chewing_user_path[] = "CHEWING_USER_PATH=/user_data";
putenv(chewing_path);
putenv(chewing_user_path);
chewing_Init(data_dir, ".");
pthread_t main_thread;
pthread_create(&main_thread, NULL, chewing_init_context, (void*)this);
}
virtual ~ChewingInstance() {
if (ctx)
chewing_delete(ctx);
chewing_Terminate();
}
virtual void Debug(const string &message, const string &detail="") {
PostMessage(pp::Var(kMsgDebugPrefix + message + (
detail.empty() ? ", " : "") + detail));
}
virtual void AppendChewingBuffer(Json::Value &array, int from, int to) {
char *text = (char*)calloc(to - from + 1, MAX_UTF8_SIZE);
for (int i = from; i < to; i++) {
strcat(text, (char *)ctx->output->chiSymbolBuf[i].s);
}
array.append(Json::Value(text));
free(text);
}
virtual void ReturnContext() {
char *s;
Json::FastWriter writer;
Json::Value value(Json::objectValue);
// TODO(hungte) Probably just access context internal buffer so we don't
// need to waste time doing calloc/free... reading ChewingOutput directly.
// chewing_cand_CheckDone does not do what we expect...
if (chewing_cand_TotalChoice(ctx) > 0) {
chewing_cand_Enumerate(ctx);
Json::Value cand = Json::Value(Json::arrayValue);
int i, len = chewing_cand_ChoicePerPage(ctx);
for (i = 0; i < len && chewing_cand_hasNext(ctx); i++) {
s = chewing_cand_String(ctx);
cand.append(Json::Value(s));
chewing_free(s);
}
value["cand"] = cand;
value["cand_ChoicePerPage"] = Json::Value(len);
value["cand_TotalPage"] = Json::Value(chewing_cand_TotalPage(ctx));
value["cand_CurrentPage"] = Json::Value(chewing_cand_CurrentPage(ctx));
}
if (chewing_buffer_Check(ctx)) {
s = chewing_buffer_String(ctx);
value["buffer"] = Json::Value(s);
chewing_free(s);
}
{
IntervalType it;
Json::Value intervals = Json::Value(Json::arrayValue);
Json::Value lcch = Json::Value(Json::arrayValue);
chewing_interval_Enumerate(ctx);
int start = 0, end = chewing_buffer_Len(ctx);
// TODO(hungte) It is possible to have groups without buffer.
// i.e., lcch>0, intervals=0
while (chewing_interval_hasNext(ctx)) {
chewing_interval_Get(ctx, &it);
Json::Value itv = Json::Value(Json::objectValue);
itv["from"] = Json::Value(it.from);
itv["to"] = Json::Value(it.to);
intervals.append(itv);
if (start != it.from)
AppendChewingBuffer(lcch, start, it.from);
AppendChewingBuffer(lcch, it.from, it.to);
start = it.to;
}
if (start < end)
AppendChewingBuffer(lcch, start, end);
if (intervals.size() > 0)
value["interval"] = intervals;
if (lcch.size() > 0)
value["lcch"] = lcch;
}
// TODO(hungte) Remove the "#if 0" after v0.3.6 is released.
#if 0
if (chewing_bopomofo_Check(ctx)) {
s = chewing_bopomofo_String(ctx);
value["bopomofo"] = Json::Value(s);
chewing_free(s);
}
#else
if (!chewing_zuin_Check(ctx)) {
s = chewing_zuin_String(ctx, NULL);
value["bopomofo"] = Json::Value(s);
chewing_free(s);
}
#endif
if (chewing_aux_Check(ctx)) {
s = chewing_aux_String(ctx);
value["aux"] = Json::Value(s);
chewing_free(s);
}
if (chewing_commit_Check(ctx)) {
s = chewing_commit_String(ctx);
value["commit"] = Json::Value(s);
chewing_free(s);
}
value["cursor"] = Json::Value(chewing_cursor_Current(ctx));
if (chewing_keystroke_CheckIgnore(ctx))
value["ignore"] = Json::Value(true);
if (chewing_keystroke_CheckAbsorb(ctx))
value["absorb"] = Json::Value(true);
// XCIN compatible fields
value["keystroke"] = value["bopomofo"];
value["mcch"] = value["cand"];
value["cch"] = value["commit"];
value["edit_pos"] = value["cursor"];
// lcch should be already handled when building interval.
PostMessage(pp::Var(kMsgContextPrefix + writer.write(value)));
}
virtual void ReturnLayout(Json::Value value) {
Json::FastWriter writer;
PostMessage(pp::Var(kMsgLayoutPrefix + writer.write(value)));
}
virtual void ProcessKeyMessage(const string &key) {
bool handled = false;
for (int i = 0; i < ARRAYSIZE(special_key_mappings); i++) {
ChewingKeyMapping *map = &special_key_mappings[i];
if (key == map->keyname) {
map->handler(ctx);
handled = true;
break;
}
}
// Some special keys, like Ctrl, should not be mis-handled.
if (!handled && key.size() == 1) {
chewing_handle_Default(ctx, key[0]);
}
ReturnContext();
}
virtual void ProcessLayoutMessage(const string &layout) {
// TODO(hungte) Remove the (char*) when chewing_KBStr2Num has changed to
// const char *.
chewing_set_KBType(ctx, chewing_KBStr2Num((char*)layout.c_str()));
Json::Value v(chewing_get_KBString(ctx));
ReturnLayout(v);
}
virtual void HandleMessage(const pp::Var &var_message) {
// Due to current PPAPI limitation, we need to serialize anything to simple
// string before sending to native client.
if (!ctx || !var_message.is_string())
return;
// Check message type.
string msg(var_message.AsString());
if (msg.find_first_of(kMsgKeyPrefix) == 0) {
msg = msg.substr(kMsgKeyPrefix.size());
ProcessKeyMessage(msg);
return;
}
if (msg.find_first_of(kMsgLayoutPrefix) == 0) {
msg = msg.substr(kMsgLayoutPrefix.size());
ProcessLayoutMessage(msg);
return;
}
Debug("Unknown command", msg);
}
};
void *chewing_init_context(void *arg) {
int selkeys[MAX_SELKEY] = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
ChewingInstance *instance = (ChewingInstance*)arg;
/* chewing_new will do fopen/fread so we must call it inside a dedicated
* thread. */
ChewingContext *ctx = chewing_new();
chewing_set_maxChiSymbolLen(ctx, 16);
chewing_set_addPhraseDirection(ctx, 1);
chewing_set_spaceAsSelection(ctx, 1);
// chewing_set_selKey does not really take the len arg and takes a hard-coded
// value for memcpy size. How amazing!
int nSelKeys = ARRAYSIZE(selkeys);
assert(nSelKeys >= MAX_SELKEY);
chewing_set_selKey(ctx, selkeys, nSelKeys);
chewing_set_candPerPage(ctx, std::min(nSelKeys, MAX_SELKEY));
instance->ctx = ctx;
return NULL;
}
class ChewingModule: public pp::Module {
public:
ChewingModule(): pp::Module() {}
virtual ~ChewingModule() {}
virtual pp::Instance* CreateInstance(PP_Instance instance) {
return new ChewingInstance(instance);
}
};
namespace pp {
Module* CreateModule() {
return new ChewingModule();
}
} // namespace pp
|
// Copyright 2013 Google Inc. All Rights Reserved.
/**
* @fileoverview NaCl loader for libchewing.
* @author [email protected] (Hung-Te Lin)
*
* Accept messages:
* key:<KEY NAME>
*
* Output messages:
* debug:<DEBUG MESSAGE>
* context:<IM context>
*/
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <pthread.h> // for nacl_io
#include <stdlib.h>
#include <unistd.h>
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/var.h"
#include "nacl_io/nacl_io.h"
#include "json/writer.h"
#include "chewing.h"
#include "chewing-private.h"
using std::string;
#define ARRAYSIZE(x) (sizeof(x)/sizeof(x[0]))
extern "C" size_t getpagesize() {
return sysconf(_SC_PAGESIZE);
}
////////////////////////////////////////////////////////////////////////
// Module Initialization.
////////////////////////////////////////////////////////////////////////
typedef struct {
const char *keyname;
int (*handler)(ChewingContext *ctx);
} ChewingKeyMapping;
ChewingKeyMapping special_key_mappings[] = {
{ "Backspace", chewing_handle_Backspace, },
{ "Tab", chewing_handle_Tab, },
{ "Enter", chewing_handle_Enter, },
{ "Shift", chewing_handle_ShiftLeft, },
{ "CapsLock", chewing_handle_Capslock, },
{ "Esc", chewing_handle_Esc, },
{ " ", chewing_handle_Space, },
{ "PageUp", chewing_handle_PageUp, },
{ "PageDown", chewing_handle_PageDown, },
{ "End", chewing_handle_End, },
{ "Home", chewing_handle_Home, },
{ "Left", chewing_handle_Left, },
{ "Up", chewing_handle_Up, },
{ "Right", chewing_handle_Right, },
{ "Down", chewing_handle_Down, },
{ "Delete", chewing_handle_Del, },
};
void *chewing_init_context(void *arg);
class ChewingInstance: public pp::Instance {
protected:
const string kMsgDebugPrefix;
const string kMsgContextPrefix;
const string kMsgKeyPrefix;
const string kMsgLayoutPrefix;
public:
ChewingContext *ctx;
explicit ChewingInstance(PP_Instance instance): pp::Instance(instance),
kMsgDebugPrefix("debug:"), kMsgContextPrefix("context:"),
kMsgKeyPrefix("key:"), kMsgLayoutPrefix("layout:"), ctx(NULL) {
const char *data_dir = "/data", *user_data_dir = "/user_data";
nacl_io_init_ppapi(instance, pp::Module::Get()->get_browser_interface());
if (mount("libchewing/data", data_dir, "httpfs", 0, "") != 0) {
PostMessage(pp::Var("can't mount data"));
return;
}
// TODO(hungte) change memfs to html5fs.
if (mount("", user_data_dir, "html5fs", 0,
"type=PERSISTENT,expected_size=1048576") != 0) {
PostMessage(pp::Var("can't mount user data"));
return;
}
// Note chewing library does not really take path on its Init...
// So we always need to do putenv.
char chewing_path[] = "CHEWING_PATH=/data";
char chewing_user_path[] = "CHEWING_USER_PATH=/user_data";
putenv(chewing_path);
putenv(chewing_user_path);
chewing_Init(data_dir, ".");
pthread_t main_thread;
pthread_create(&main_thread, NULL, chewing_init_context, (void*)this);
}
virtual ~ChewingInstance() {
if (ctx)
chewing_delete(ctx);
chewing_Terminate();
}
virtual void Debug(const string &message, const string &detail="") {
PostMessage(pp::Var(kMsgDebugPrefix + message + (
detail.empty() ? ", " : "") + detail));
}
virtual void AppendChewingBuffer(Json::Value &array, int from, int to) {
char *text = (char*)calloc(to - from + 1, MAX_UTF8_SIZE);
for (int i = from; i < to; i++) {
strcat(text, (char *)ctx->output->chiSymbolBuf[i].s);
}
array.append(Json::Value(text));
free(text);
}
virtual void ReturnContext() {
char *s;
Json::FastWriter writer;
Json::Value value(Json::objectValue);
// TODO(hungte) Probably just access context internal buffer so we don't
// need to waste time doing calloc/free... reading ChewingOutput directly.
// chewing_cand_CheckDone does not do what we expect...
if (chewing_cand_TotalChoice(ctx) > 0) {
chewing_cand_Enumerate(ctx);
Json::Value cand = Json::Value(Json::arrayValue);
int i, len = chewing_cand_ChoicePerPage(ctx);
for (i = 0; i < len && chewing_cand_hasNext(ctx); i++) {
s = chewing_cand_String(ctx);
cand.append(Json::Value(s));
chewing_free(s);
}
value["cand"] = cand;
value["cand_ChoicePerPage"] = Json::Value(len);
value["cand_TotalPage"] = Json::Value(chewing_cand_TotalPage(ctx));
value["cand_CurrentPage"] = Json::Value(chewing_cand_CurrentPage(ctx));
}
if (chewing_buffer_Check(ctx)) {
s = chewing_buffer_String(ctx);
value["buffer"] = Json::Value(s);
chewing_free(s);
}
{
IntervalType it;
Json::Value intervals = Json::Value(Json::arrayValue);
Json::Value lcch = Json::Value(Json::arrayValue);
chewing_interval_Enumerate(ctx);
int start = 0, end = chewing_buffer_Len(ctx);
// TODO(hungte) It is possible to have groups without buffer.
// i.e., lcch>0, intervals=0
while (chewing_interval_hasNext(ctx)) {
chewing_interval_Get(ctx, &it);
Json::Value itv = Json::Value(Json::objectValue);
itv["from"] = Json::Value(it.from);
itv["to"] = Json::Value(it.to);
intervals.append(itv);
if (start != it.from)
AppendChewingBuffer(lcch, start, it.from);
AppendChewingBuffer(lcch, it.from, it.to);
start = it.to;
}
if (start < end)
AppendChewingBuffer(lcch, start, end);
if (intervals.size() > 0)
value["interval"] = intervals;
if (lcch.size() > 0)
value["lcch"] = lcch;
}
// TODO(hungte) Remove the "#if 0" after v0.3.6 is released.
#if 0
if (chewing_bopomofo_Check(ctx)) {
s = chewing_bopomofo_String(ctx);
value["bopomofo"] = Json::Value(s);
chewing_free(s);
}
#else
if (!chewing_zuin_Check(ctx)) {
s = chewing_zuin_String(ctx, NULL);
value["bopomofo"] = Json::Value(s);
chewing_free(s);
}
#endif
if (chewing_aux_Check(ctx)) {
s = chewing_aux_String(ctx);
value["aux"] = Json::Value(s);
chewing_free(s);
}
if (chewing_commit_Check(ctx)) {
s = chewing_commit_String(ctx);
value["commit"] = Json::Value(s);
chewing_free(s);
}
value["cursor"] = Json::Value(chewing_cursor_Current(ctx));
if (chewing_keystroke_CheckIgnore(ctx))
value["ignore"] = Json::Value(true);
if (chewing_keystroke_CheckAbsorb(ctx))
value["absorb"] = Json::Value(true);
// XCIN compatible fields
value["keystroke"] = value["bopomofo"];
value["mcch"] = value["cand"];
value["cch"] = value["commit"];
value["edit_pos"] = value["cursor"];
// lcch should be already handled when building interval.
PostMessage(pp::Var(kMsgContextPrefix + writer.write(value)));
}
virtual void ReturnLayout(Json::Value value) {
Json::FastWriter writer;
PostMessage(pp::Var(kMsgLayoutPrefix + writer.write(value)));
}
virtual void ProcessKeyMessage(const string &key) {
bool handled = false;
for (int i = 0; i < ARRAYSIZE(special_key_mappings); i++) {
ChewingKeyMapping *map = &special_key_mappings[i];
if (key == map->keyname) {
map->handler(ctx);
handled = true;
break;
}
}
// Some special keys, like Ctrl, should not be mis-handled.
if (!handled && key.size() == 1) {
chewing_handle_Default(ctx, key[0]);
}
ReturnContext();
}
virtual void ProcessLayoutMessage(const string &layout) {
// TODO(hungte) Remove the (char*) when chewing_KBStr2Num has changed to
// const char *.
chewing_set_KBType(ctx, chewing_KBStr2Num((char*)layout.c_str()));
/* TODO(hungte) Change this to:
* (1) enumerate and cache chewing_kbtype_string_staci list
* (2) lookup chewing_get_KBType
*/
char *s = chewing_get_KBString(ctx);
Json::Value v(s);
chewing_free(s);
ReturnLayout(v);
}
virtual void HandleMessage(const pp::Var &var_message) {
// Due to current PPAPI limitation, we need to serialize anything to simple
// string before sending to native client.
if (!ctx || !var_message.is_string())
return;
// Check message type.
string msg(var_message.AsString());
if (msg.find_first_of(kMsgKeyPrefix) == 0) {
msg = msg.substr(kMsgKeyPrefix.size());
ProcessKeyMessage(msg);
return;
}
if (msg.find_first_of(kMsgLayoutPrefix) == 0) {
msg = msg.substr(kMsgLayoutPrefix.size());
ProcessLayoutMessage(msg);
return;
}
Debug("Unknown command", msg);
}
};
void *chewing_init_context(void *arg) {
int selkeys[MAX_SELKEY] = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
ChewingInstance *instance = (ChewingInstance*)arg;
/* chewing_new will do fopen/fread so we must call it inside a dedicated
* thread. */
ChewingContext *ctx = chewing_new();
chewing_set_maxChiSymbolLen(ctx, 16);
chewing_set_addPhraseDirection(ctx, 1);
chewing_set_spaceAsSelection(ctx, 1);
// chewing_set_selKey does not really take the len arg and takes a hard-coded
// value for memcpy size. How amazing!
int nSelKeys = ARRAYSIZE(selkeys);
assert(nSelKeys >= MAX_SELKEY);
chewing_set_selKey(ctx, selkeys, nSelKeys);
chewing_set_candPerPage(ctx, std::min(nSelKeys, MAX_SELKEY));
instance->ctx = ctx;
return NULL;
}
class ChewingModule: public pp::Module {
public:
ChewingModule(): pp::Module() {}
virtual ~ChewingModule() {}
virtual pp::Instance* CreateInstance(PP_Instance instance) {
return new ChewingInstance(instance);
}
};
namespace pp {
Module* CreateModule() {
return new ChewingModule();
}
} // namespace pp
|
Fix memory leak by chewing_get_KBString.
|
nacl: Fix memory leak by chewing_get_KBString.
|
C++
|
apache-2.0
|
google/jscin,google/jscin,google/jscin,google/jscin,google/jscin
|
b060f7905bb82ade5c4917d1cbf59751ba9a2c9d
|
chrome/browser/sync/util/user_settings_unittest.cc
|
chrome/browser/sync/util/user_settings_unittest.cc
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <limits>
#include <string>
#include "base/file_util.h"
#include "base/memory/scoped_temp_dir.h"
#include "chrome/browser/password_manager/encryptor.h"
#include "chrome/browser/sync/syncable/directory_manager.h"
#include "chrome/browser/sync/util/user_settings.h"
#include "chrome/common/sqlite_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
using browser_sync::APEncode;
using browser_sync::APDecode;
using browser_sync::ExecOrDie;
using browser_sync::UserSettings;
using std::numeric_limits;
static const FilePath::CharType kV10UserSettingsDB[] =
FILE_PATH_LITERAL("Version10Settings.sqlite3");
static const FilePath::CharType kV11UserSettingsDB[] =
FILE_PATH_LITERAL("Version11Settings.sqlite3");
static const FilePath::CharType kOldStyleSyncDataDB[] =
FILE_PATH_LITERAL("OldStyleSyncData.sqlite3");
class UserSettingsTest : public testing::Test {
public:
UserSettingsTest() : sync_data_("Some sync data") { }
virtual void SetUp() {
#if defined(OS_MACOSX)
// Need to mock the Keychain for unit tests on Mac to avoid possible
// blocking UI. |SetAuthTokenForService| uses Encryptor.
Encryptor::UseMockKeychain(true);
#endif
}
// Creates and populates the V10 database files within
// |destination_directory|.
void SetUpVersion10Databases(const FilePath& destination_directory) {
sqlite3* primer_handle = NULL;
v10_user_setting_db_path_ =
destination_directory.Append(FilePath(kV10UserSettingsDB));
ASSERT_EQ(SQLITE_OK, sqlite_utils::OpenSqliteDb(v10_user_setting_db_path_,
&primer_handle));
sqlite_utils::scoped_sqlite_db_ptr db(primer_handle);
old_style_sync_data_path_ =
destination_directory.Append(FilePath(kOldStyleSyncDataDB));
ASSERT_EQ(sync_data_.length(),
static_cast<size_t>(file_util::WriteFile(
old_style_sync_data_path_, sync_data_.data(),
sync_data_.length())));
// Create settings table.
ExecOrDie(primer_handle, "CREATE TABLE settings"
" (email, key, value, "
" PRIMARY KEY(email, key) ON CONFLICT REPLACE)");
// Add a blank signin table.
ExecOrDie(primer_handle, "CREATE TABLE signin_types"
" (signin, signin_type)");
// Create and populate version table.
ExecOrDie(primer_handle, "CREATE TABLE db_version ( version )");
{
SQLStatement statement;
const char query[] = "INSERT INTO db_version values ( ? )";
statement.prepare(primer_handle, query);
statement.bind_int(0, 10);
if (SQLITE_DONE != statement.step()) {
LOG(FATAL) << query << "\n" << sqlite3_errmsg(primer_handle);
}
}
// Create shares table.
ExecOrDie(primer_handle, "CREATE TABLE shares"
" (email, share_name, file_name,"
" PRIMARY KEY(email, share_name) ON CONFLICT REPLACE)");
// Populate a share.
{
SQLStatement statement;
const char query[] = "INSERT INTO shares values ( ?, ?, ? )";
statement.prepare(primer_handle, query);
statement.bind_string(0, "[email protected]");
statement.bind_string(1, "[email protected]");
#if defined(OS_WIN)
statement.bind_string(2, WideToUTF8(old_style_sync_data_path_.value()));
#elif defined(OS_POSIX)
statement.bind_string(2, old_style_sync_data_path_.value());
#endif
if (SQLITE_DONE != statement.step()) {
LOG(FATAL) << query << "\n" << sqlite3_errmsg(primer_handle);
}
}
}
// Creates and populates the V11 database file within
// |destination_directory|.
void SetUpVersion11Database(const FilePath& destination_directory) {
sqlite3* primer_handle = NULL;
v11_user_setting_db_path_ =
destination_directory.Append(FilePath(kV11UserSettingsDB));
ASSERT_EQ(SQLITE_OK, sqlite_utils::OpenSqliteDb(v11_user_setting_db_path_,
&primer_handle));
sqlite_utils::scoped_sqlite_db_ptr db(primer_handle);
// Create settings table.
ExecOrDie(primer_handle, "CREATE TABLE settings"
" (email, key, value, "
" PRIMARY KEY(email, key) ON CONFLICT REPLACE)");
// Create and populate version table.
ExecOrDie(primer_handle, "CREATE TABLE db_version ( version )");
{
SQLStatement statement;
const char query[] = "INSERT INTO db_version values ( ? )";
statement.prepare(primer_handle, query);
statement.bind_int(0, 11);
if (SQLITE_DONE != statement.step()) {
LOG(FATAL) << query << "\n" << sqlite3_errmsg(primer_handle);
}
}
ExecOrDie(primer_handle, "CREATE TABLE signin_types"
" (signin, signin_type)");
{
SQLStatement statement;
const char query[] = "INSERT INTO signin_types values ( ?, ? )";
statement.prepare(primer_handle, query);
statement.bind_string(0, "test");
statement.bind_string(1, "test");
if (SQLITE_DONE != statement.step()) {
LOG(FATAL) << query << "\n" << sqlite3_errmsg(primer_handle);
}
}
}
const std::string& sync_data() const { return sync_data_; }
const FilePath& v10_user_setting_db_path() const {
return v10_user_setting_db_path_;
}
const FilePath& v11_user_setting_db_path() const {
return v11_user_setting_db_path_;
}
const FilePath& old_style_sync_data_path() const {
return old_style_sync_data_path_;
}
private:
FilePath v10_user_setting_db_path_;
FilePath old_style_sync_data_path_;
FilePath v11_user_setting_db_path_;
std::string sync_data_;
};
TEST_F(UserSettingsTest, MigrateFromV10ToV11) {
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
SetUpVersion10Databases(temp_dir.path());
{
// Create a UserSettings, which should trigger migration code. We do this
// inside a scoped block so it closes itself and we can poke around to see
// what happened later.
UserSettings settings;
settings.Init(v10_user_setting_db_path());
}
// Now poke around using sqlite to see if UserSettings migrated properly.
sqlite3* handle = NULL;
ASSERT_EQ(SQLITE_OK, sqlite_utils::OpenSqliteDb(v10_user_setting_db_path(),
&handle));
sqlite_utils::scoped_sqlite_db_ptr db(handle);
// Note that we don't use ScopedStatement to avoid closing the sqlite handle
// before finalizing the statement.
{
SQLStatement version_query;
version_query.prepare(handle, "SELECT version FROM db_version");
ASSERT_EQ(SQLITE_ROW, version_query.step());
const int version = version_query.column_int(0);
EXPECT_GE(version, 11);
}
EXPECT_FALSE(file_util::PathExists(old_style_sync_data_path()));
FilePath new_style_path = temp_dir.path().Append(
syncable::DirectoryManager::GetSyncDataDatabaseFilename());
std::string contents;
ASSERT_TRUE(file_util::ReadFileToString(new_style_path, &contents));
EXPECT_TRUE(sync_data() == contents);
}
TEST_F(UserSettingsTest, MigrateFromV11ToV12) {
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
SetUpVersion11Database(temp_dir.path());
{
UserSettings settings;
settings.Init(v11_user_setting_db_path());
}
sqlite3* handle = NULL;
ASSERT_EQ(SQLITE_OK, sqlite_utils::OpenSqliteDb(v11_user_setting_db_path(),
&handle));
sqlite_utils::scoped_sqlite_db_ptr db(handle);
{
SQLStatement version_query;
version_query.prepare(handle, "SELECT version FROM db_version");
ASSERT_EQ(SQLITE_ROW, version_query.step());
const int version = version_query.column_int(0);
EXPECT_GE(version, 12);
SQLStatement table_query;
table_query.prepare(handle, "SELECT name FROM sqlite_master "
"WHERE type='table' AND name='signin_types'");
ASSERT_NE(SQLITE_ROW, table_query.step());
}
}
TEST_F(UserSettingsTest, APEncode) {
std::string test;
char i;
for (i = numeric_limits<char>::min(); i < numeric_limits<char>::max(); ++i)
test.push_back(i);
test.push_back(i);
const std::string encoded = APEncode(test);
const std::string decoded = APDecode(encoded);
ASSERT_EQ(test, decoded);
}
TEST_F(UserSettingsTest, PersistEmptyToken) {
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
UserSettings settings;
settings.Init(temp_dir.path().AppendASCII("UserSettings.sqlite3"));
settings.SetAuthTokenForService("username", "service", "");
std::string username;
std::string token;
ASSERT_TRUE(settings.GetLastUserAndServiceToken("service", &username,
&token));
EXPECT_EQ("", token);
EXPECT_EQ("username", username);
}
TEST_F(UserSettingsTest, PersistNonEmptyToken) {
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
UserSettings settings;
settings.Init(temp_dir.path().AppendASCII("UserSettings.sqlite3"));
settings.SetAuthTokenForService("username", "service",
"oonetuhasonteuhasonetuhasonetuhasonetuhasouhasonetuhasonetuhasonetuhah"
"oonetuhasonteuhasonetuhasonetuhasonetuhasouhasonetuhasonetuhasonetuhah"
"oonetuhasonteuhasonetuhasonetuhasonetuhasouhasonetuhasonetuhasonetuhah");
std::string username;
std::string token;
ASSERT_TRUE(settings.GetLastUserAndServiceToken("service", &username,
&token));
EXPECT_EQ(
"oonetuhasonteuhasonetuhasonetuhasonetuhasouhasonetuhasonetuhasonetuhah"
"oonetuhasonteuhasonetuhasonetuhasonetuhasouhasonetuhasonetuhasonetuhah"
"oonetuhasonteuhasonetuhasonetuhasonetuhasouhasonetuhasonetuhasonetuhah",
token);
EXPECT_EQ("username", username);
}
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <limits>
#include <string>
#include "app/sql/statement.h"
#include "base/file_util.h"
#include "base/memory/scoped_temp_dir.h"
#include "base/utf_string_conversions.h"
#include "build/build_config.h"
#include "chrome/browser/password_manager/encryptor.h"
#include "chrome/browser/sync/syncable/directory_manager.h"
#include "chrome/browser/sync/util/user_settings.h"
#include "testing/gtest/include/gtest/gtest.h"
using std::numeric_limits;
namespace {
const FilePath::CharType kV10UserSettingsDB[] =
FILE_PATH_LITERAL("Version10Settings.sqlite3");
const FilePath::CharType kV11UserSettingsDB[] =
FILE_PATH_LITERAL("Version11Settings.sqlite3");
const FilePath::CharType kOldStyleSyncDataDB[] =
FILE_PATH_LITERAL("OldStyleSyncData.sqlite3");
} // namespace
class UserSettingsTest : public testing::Test {
public:
UserSettingsTest() : sync_data_("Some sync data") {}
virtual void SetUp() {
#if defined(OS_MACOSX)
// Need to mock the Keychain for unit tests on Mac to avoid possible
// blocking UI. |SetAuthTokenForService| uses Encryptor.
Encryptor::UseMockKeychain(true);
#endif
}
// Creates and populates the V10 database files within
// |destination_directory|.
void SetUpVersion10Databases(const FilePath& destination_directory) {
v10_user_setting_db_path_ =
destination_directory.Append(FilePath(kV10UserSettingsDB));
sql::Connection db;
ASSERT_TRUE(db.Open(v10_user_setting_db_path_));
old_style_sync_data_path_ =
destination_directory.Append(FilePath(kOldStyleSyncDataDB));
ASSERT_EQ(sync_data_.length(),
static_cast<size_t>(file_util::WriteFile(
old_style_sync_data_path_, sync_data_.data(),
sync_data_.length())));
// Create settings table.
ASSERT_TRUE(db.Execute(
"CREATE TABLE settings (email, key, value, PRIMARY KEY(email, key)"
" ON CONFLICT REPLACE)"));
// Add a blank signin table.
ASSERT_TRUE(db.Execute(
"CREATE TABLE signin_types (signin, signin_type)"));
// Create and populate version table.
ASSERT_TRUE(db.Execute("CREATE TABLE db_version (version)"));
{
const char* query = "INSERT INTO db_version VALUES(?)";
sql::Statement s(db.GetUniqueStatement(query));
if (!s)
LOG(FATAL) << query << "\n" << db.GetErrorMessage();
s.BindInt(0, 10);
if (!s.Run())
LOG(FATAL) << query << "\n" << db.GetErrorMessage();
}
// Create shares table.
ASSERT_TRUE(db.Execute(
"CREATE TABLE shares (email, share_name, file_name,"
" PRIMARY KEY(email, share_name) ON CONFLICT REPLACE)"));
// Populate a share.
{
const char* query = "INSERT INTO shares VALUES(?, ?, ?)";
sql::Statement s(db.GetUniqueStatement(query));
if (!s)
LOG(FATAL) << query << "\n" << db.GetErrorMessage();
s.BindString(0, "[email protected]");
s.BindString(1, "[email protected]");
#if defined(OS_WIN)
s.BindString(2, WideToUTF8(old_style_sync_data_path_.value()));
#elif defined(OS_POSIX)
s.BindString(2, old_style_sync_data_path_.value());
#endif
if (!s.Run())
LOG(FATAL) << query << "\n" << db.GetErrorMessage();
}
}
// Creates and populates the V11 database file within
// |destination_directory|.
void SetUpVersion11Database(const FilePath& destination_directory) {
v11_user_setting_db_path_ =
destination_directory.Append(FilePath(kV11UserSettingsDB));
sql::Connection db;
ASSERT_TRUE(db.Open(v11_user_setting_db_path_));
// Create settings table.
ASSERT_TRUE(db.Execute(
"CREATE TABLE settings (email, key, value, PRIMARY KEY(email, key)"
" ON CONFLICT REPLACE)"));
// Create and populate version table.
ASSERT_TRUE(db.Execute("CREATE TABLE db_version (version)"));
{
const char* query = "INSERT INTO db_version VALUES(?)";
sql::Statement s(db.GetUniqueStatement(query));
if (!s)
LOG(FATAL) << query << "\n" << db.GetErrorMessage();
s.BindInt(0, 11);
if (!s.Run())
LOG(FATAL) << query << "\n" << db.GetErrorMessage();
}
ASSERT_TRUE(db.Execute(
"CREATE TABLE signin_types (signin, signin_type)"));
{
const char* query = "INSERT INTO signin_types VALUES(?, ?)";
sql::Statement s(db.GetUniqueStatement(query));
if (!s)
LOG(FATAL) << query << "\n" << db.GetErrorMessage();
s.BindString(0, "test");
s.BindString(1, "test");
if (!s.Run())
LOG(FATAL) << query << "\n" << db.GetErrorMessage();
}
}
const std::string& sync_data() const { return sync_data_; }
const FilePath& v10_user_setting_db_path() const {
return v10_user_setting_db_path_;
}
const FilePath& v11_user_setting_db_path() const {
return v11_user_setting_db_path_;
}
const FilePath& old_style_sync_data_path() const {
return old_style_sync_data_path_;
}
private:
FilePath v10_user_setting_db_path_;
FilePath old_style_sync_data_path_;
FilePath v11_user_setting_db_path_;
std::string sync_data_;
};
TEST_F(UserSettingsTest, MigrateFromV10ToV11) {
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
SetUpVersion10Databases(temp_dir.path());
{
// Create a UserSettings, which should trigger migration code. We do this
// inside a scoped block so it closes itself and we can poke around to see
// what happened later.
browser_sync::UserSettings settings;
settings.Init(v10_user_setting_db_path());
}
// Now poke around using sqlite to see if UserSettings migrated properly.
sql::Connection db;
ASSERT_TRUE(db.Open(v10_user_setting_db_path()));
// Note that we don't use ScopedStatement to avoid closing the sqlite handle
// before finalizing the statement.
{
const char* query = "SELECT version FROM db_version";
sql::Statement version_query(db.GetUniqueStatement(query));
if (!version_query)
LOG(FATAL) << query << "\n" << db.GetErrorMessage();
ASSERT_TRUE(version_query.Step());
const int version = version_query.ColumnInt(0);
EXPECT_GE(version, 11);
}
EXPECT_FALSE(file_util::PathExists(old_style_sync_data_path()));
FilePath new_style_path = temp_dir.path().Append(
syncable::DirectoryManager::GetSyncDataDatabaseFilename());
std::string contents;
ASSERT_TRUE(file_util::ReadFileToString(new_style_path, &contents));
EXPECT_TRUE(sync_data() == contents);
}
TEST_F(UserSettingsTest, MigrateFromV11ToV12) {
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
SetUpVersion11Database(temp_dir.path());
{
browser_sync::UserSettings settings;
settings.Init(v11_user_setting_db_path());
}
sql::Connection db;
ASSERT_TRUE(db.Open(v11_user_setting_db_path()));
{
const char* query = "SELECT version FROM db_version";
sql::Statement version_query(db.GetUniqueStatement(query));
if (!version_query)
LOG(FATAL) << query << "\n" << db.GetErrorMessage();
ASSERT_TRUE(version_query.Step());
const int version = version_query.ColumnInt(0);
EXPECT_GE(version, 12);
const char* query2 = "SELECT name FROM sqlite_master "
"WHERE type='table' AND name='signin_types'";
sql::Statement table_query(db.GetUniqueStatement(query2));
if (!table_query)
LOG(FATAL) << query2 << "\n" << db.GetErrorMessage();
ASSERT_FALSE(table_query.Step());
}
}
TEST_F(UserSettingsTest, APEncode) {
std::string test;
char i;
for (i = numeric_limits<char>::min(); i < numeric_limits<char>::max(); ++i)
test.push_back(i);
test.push_back(i);
const std::string encoded = browser_sync::APEncode(test);
const std::string decoded = browser_sync::APDecode(encoded);
ASSERT_EQ(test, decoded);
}
TEST_F(UserSettingsTest, PersistEmptyToken) {
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
browser_sync::UserSettings settings;
settings.Init(temp_dir.path().AppendASCII("UserSettings.sqlite3"));
settings.SetAuthTokenForService("username", "service", "");
std::string username;
std::string token;
ASSERT_TRUE(settings.GetLastUserAndServiceToken("service", &username,
&token));
EXPECT_EQ("", token);
EXPECT_EQ("username", username);
}
TEST_F(UserSettingsTest, PersistNonEmptyToken) {
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
browser_sync::UserSettings settings;
settings.Init(temp_dir.path().AppendASCII("UserSettings.sqlite3"));
settings.SetAuthTokenForService("username", "service",
"oonetuhasonteuhasonetuhasonetuhasonetuhasouhasonetuhasonetuhasonetuhah"
"oonetuhasonteuhasonetuhasonetuhasonetuhasouhasonetuhasonetuhasonetuhah"
"oonetuhasonteuhasonetuhasonetuhasonetuhasouhasonetuhasonetuhasonetuhah");
std::string username;
std::string token;
ASSERT_TRUE(settings.GetLastUserAndServiceToken("service", &username,
&token));
EXPECT_EQ(
"oonetuhasonteuhasonetuhasonetuhasonetuhasouhasonetuhasonetuhasonetuhah"
"oonetuhasonteuhasonetuhasonetuhasonetuhasouhasonetuhasonetuhasonetuhah"
"oonetuhasonteuhasonetuhasonetuhasonetuhasouhasonetuhasonetuhasonetuhah",
token);
EXPECT_EQ("username", username);
}
|
Remove sqlite_utils.h from user_settings_unittest.cc
|
Cleanup: Remove sqlite_utils.h from user_settings_unittest.cc
BUG=77634
TEST=sync_unit_tests
[email protected],[email protected]
Review URL: http://codereview.chromium.org/6691022
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@80374 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
anirudhSK/chromium,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,robclark/chromium,keishi/chromium,dushu1203/chromium.src,hgl888/chromium-crosswalk,nacl-webkit/chrome_deps,junmin-zhu/chromium-rivertrail,littlstar/chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,hujiajie/pa-chromium,keishi/chromium,mogoweb/chromium-crosswalk,anirudhSK/chromium,M4sse/chromium.src,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk-efl,robclark/chromium,robclark/chromium,Chilledheart/chromium,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,keishi/chromium,hujiajie/pa-chromium,pozdnyakov/chromium-crosswalk,ltilve/chromium,rogerwang/chromium,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,Jonekee/chromium.src,Just-D/chromium-1,dednal/chromium.src,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,zcbenz/cefode-chromium,jaruba/chromium.src,ltilve/chromium,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,pozdnyakov/chromium-crosswalk,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,timopulkkinen/BubbleFish,junmin-zhu/chromium-rivertrail,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,timopulkkinen/BubbleFish,anirudhSK/chromium,jaruba/chromium.src,rogerwang/chromium,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,dushu1203/chromium.src,mogoweb/chromium-crosswalk,keishi/chromium,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,littlstar/chromium.src,Chilledheart/chromium,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,zcbenz/cefode-chromium,Just-D/chromium-1,zcbenz/cefode-chromium,jaruba/chromium.src,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,ltilve/chromium,Pluto-tv/chromium-crosswalk,junmin-zhu/chromium-rivertrail,Chilledheart/chromium,krieger-od/nwjs_chromium.src,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,robclark/chromium,patrickm/chromium.src,rogerwang/chromium,keishi/chromium,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,mogoweb/chromium-crosswalk,Chilledheart/chromium,ltilve/chromium,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,patrickm/chromium.src,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,ltilve/chromium,ondra-novak/chromium.src,patrickm/chromium.src,anirudhSK/chromium,Jonekee/chromium.src,markYoungH/chromium.src,M4sse/chromium.src,anirudhSK/chromium,nacl-webkit/chrome_deps,mohamed--abdel-maksoud/chromium.src,robclark/chromium,dushu1203/chromium.src,keishi/chromium,bright-sparks/chromium-spacewalk,robclark/chromium,dednal/chromium.src,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,patrickm/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hujiajie/pa-chromium,littlstar/chromium.src,rogerwang/chromium,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,littlstar/chromium.src,Chilledheart/chromium,ondra-novak/chromium.src,chuan9/chromium-crosswalk,rogerwang/chromium,Just-D/chromium-1,junmin-zhu/chromium-rivertrail,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,markYoungH/chromium.src,ltilve/chromium,dednal/chromium.src,junmin-zhu/chromium-rivertrail,TheTypoMaster/chromium-crosswalk,keishi/chromium,ondra-novak/chromium.src,ltilve/chromium,mogoweb/chromium-crosswalk,mogoweb/chromium-crosswalk,dednal/chromium.src,chuan9/chromium-crosswalk,rogerwang/chromium,hgl888/chromium-crosswalk,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,keishi/chromium,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,nacl-webkit/chrome_deps,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,nacl-webkit/chrome_deps,Just-D/chromium-1,Jonekee/chromium.src,Chilledheart/chromium,keishi/chromium,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,markYoungH/chromium.src,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,littlstar/chromium.src,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,junmin-zhu/chromium-rivertrail,axinging/chromium-crosswalk,dednal/chromium.src,ondra-novak/chromium.src,junmin-zhu/chromium-rivertrail,Just-D/chromium-1,jaruba/chromium.src,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,rogerwang/chromium,hujiajie/pa-chromium,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,timopulkkinen/BubbleFish,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,axinging/chromium-crosswalk,robclark/chromium,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,hujiajie/pa-chromium,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,zcbenz/cefode-chromium,dushu1203/chromium.src,dushu1203/chromium.src,mogoweb/chromium-crosswalk,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,Just-D/chromium-1,Fireblend/chromium-crosswalk,jaruba/chromium.src,junmin-zhu/chromium-rivertrail,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,anirudhSK/chromium,nacl-webkit/chrome_deps,junmin-zhu/chromium-rivertrail,patrickm/chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk,nacl-webkit/chrome_deps,timopulkkinen/BubbleFish,hujiajie/pa-chromium,fujunwei/chromium-crosswalk,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,ltilve/chromium,ondra-novak/chromium.src,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,M4sse/chromium.src,patrickm/chromium.src,rogerwang/chromium,rogerwang/chromium,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,timopulkkinen/BubbleFish,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,patrickm/chromium.src,dednal/chromium.src,dednal/chromium.src,Chilledheart/chromium,M4sse/chromium.src,mogoweb/chromium-crosswalk,ondra-novak/chromium.src,nacl-webkit/chrome_deps,M4sse/chromium.src,zcbenz/cefode-chromium,anirudhSK/chromium,ondra-novak/chromium.src,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,robclark/chromium,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,dednal/chromium.src,ltilve/chromium,Fireblend/chromium-crosswalk,dednal/chromium.src,axinging/chromium-crosswalk,axinging/chromium-crosswalk,Jonekee/chromium.src,hujiajie/pa-chromium,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,keishi/chromium,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,robclark/chromium,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,chuan9/chromium-crosswalk,keishi/chromium,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,zcbenz/cefode-chromium,rogerwang/chromium,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,krieger-od/nwjs_chromium.src,anirudhSK/chromium,robclark/chromium,junmin-zhu/chromium-rivertrail,Jonekee/chromium.src,timopulkkinen/BubbleFish,fujunwei/chromium-crosswalk,dednal/chromium.src,bright-sparks/chromium-spacewalk,littlstar/chromium.src,timopulkkinen/BubbleFish,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,anirudhSK/chromium,markYoungH/chromium.src,Jonekee/chromium.src,markYoungH/chromium.src,axinging/chromium-crosswalk,dushu1203/chromium.src,jaruba/chromium.src,M4sse/chromium.src
|
146be3ddbe1e3cf8154bcc59cc5bcbd90e2072cb
|
src/glsl/lower_ubo_reference.cpp
|
src/glsl/lower_ubo_reference.cpp
|
/*
* Copyright © 2012 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
/**
* \file lower_ubo_reference.cpp
*
* IR lower pass to replace dereferences of variables in a uniform
* buffer object with usage of ir_binop_ubo_load expressions, each of
* which can read data up to the size of a vec4.
*
* This relieves drivers of the responsibility to deal with tricky UBO
* layout issues like std140 structures and row_major matrices on
* their own.
*/
#include "ir.h"
#include "ir_builder.h"
#include "ir_rvalue_visitor.h"
#include "main/macros.h"
using namespace ir_builder;
namespace {
class lower_ubo_reference_visitor : public ir_rvalue_enter_visitor {
public:
lower_ubo_reference_visitor(struct gl_shader *shader)
: shader(shader)
{
}
void handle_rvalue(ir_rvalue **rvalue);
void emit_ubo_loads(ir_dereference *deref, ir_variable *base_offset,
unsigned int deref_offset);
ir_expression *ubo_load(const struct glsl_type *type,
ir_rvalue *offset);
void *mem_ctx;
struct gl_shader *shader;
struct gl_uniform_buffer_variable *ubo_var;
ir_rvalue *uniform_block;
bool progress;
};
/**
* Determine the name of the interface block field
*
* This is the name of the specific member as it would appear in the
* \c gl_uniform_buffer_variable::Name field in the shader's
* \c UniformBlocks array.
*/
static const char *
interface_field_name(void *mem_ctx, char *base_name, ir_dereference *d,
ir_rvalue **nonconst_block_index)
{
ir_rvalue *previous_index = NULL;
*nonconst_block_index = NULL;
while (d != NULL) {
switch (d->ir_type) {
case ir_type_dereference_variable: {
ir_dereference_variable *v = (ir_dereference_variable *) d;
if (previous_index
&& v->var->is_interface_instance()
&& v->var->type->is_array()) {
ir_constant *const_index = previous_index->as_constant();
if (!const_index) {
*nonconst_block_index = previous_index;
return ralloc_asprintf(mem_ctx, "%s[0]", base_name);
} else {
return ralloc_asprintf(mem_ctx,
"%s[%d]",
base_name,
const_index->get_uint_component(0));
}
} else {
return base_name;
}
break;
}
case ir_type_dereference_record: {
ir_dereference_record *r = (ir_dereference_record *) d;
d = r->record->as_dereference();
break;
}
case ir_type_dereference_array: {
ir_dereference_array *a = (ir_dereference_array *) d;
d = a->array->as_dereference();
previous_index = a->array_index;
break;
}
default:
assert(!"Should not get here.");
break;
}
}
assert(!"Should not get here.");
return NULL;
}
void
lower_ubo_reference_visitor::handle_rvalue(ir_rvalue **rvalue)
{
if (!*rvalue)
return;
ir_dereference *deref = (*rvalue)->as_dereference();
if (!deref)
return;
ir_variable *var = deref->variable_referenced();
if (!var || !var->is_in_uniform_block())
return;
mem_ctx = ralloc_parent(*rvalue);
ir_rvalue *nonconst_block_index;
const char *const field_name =
interface_field_name(mem_ctx, (char *) var->get_interface_type()->name,
deref, &nonconst_block_index);
this->uniform_block = NULL;
for (unsigned i = 0; i < shader->NumUniformBlocks; i++) {
if (strcmp(field_name, shader->UniformBlocks[i].Name) == 0) {
ir_constant *index = new(mem_ctx) ir_constant(i);
if (nonconst_block_index) {
if (nonconst_block_index->type != glsl_type::uint_type)
nonconst_block_index = i2u(nonconst_block_index);
this->uniform_block = add(nonconst_block_index, index);
} else {
this->uniform_block = index;
}
struct gl_uniform_block *block = &shader->UniformBlocks[i];
this->ubo_var = var->is_interface_instance()
? &block->Uniforms[0] : &block->Uniforms[var->data.location];
break;
}
}
assert(this->uniform_block);
ir_rvalue *offset = new(mem_ctx) ir_constant(0u);
unsigned const_offset = 0;
bool row_major = ubo_var->RowMajor;
/* Calculate the offset to the start of the region of the UBO
* dereferenced by *rvalue. This may be a variable offset if an
* array dereference has a variable index.
*/
while (deref) {
switch (deref->ir_type) {
case ir_type_dereference_variable: {
const_offset += ubo_var->Offset;
deref = NULL;
break;
}
case ir_type_dereference_array: {
ir_dereference_array *deref_array = (ir_dereference_array *)deref;
unsigned array_stride;
if (deref_array->array->type->is_matrix() && row_major) {
/* When loading a vector out of a row major matrix, the
* step between the columns (vectors) is the size of a
* float, while the step between the rows (elements of a
* vector) is handled below in emit_ubo_loads.
*/
array_stride = 4;
} else if (deref_array->type->is_interface()) {
/* We're processing an array dereference of an interface instance
* array. The thing being dereferenced *must* be a variable
* dereference because intefaces cannot be embedded an other
* types. In terms of calculating the offsets for the lowering
* pass, we don't care about the array index. All elements of an
* interface instance array will have the same offsets relative to
* the base of the block that backs them.
*/
assert(deref_array->array->as_dereference_variable());
deref = deref_array->array->as_dereference();
break;
} else {
array_stride = deref_array->type->std140_size(row_major);
array_stride = glsl_align(array_stride, 16);
}
ir_rvalue *array_index = deref_array->array_index;
if (array_index->type->base_type == GLSL_TYPE_INT)
array_index = i2u(array_index);
ir_constant *const_index = array_index->as_constant();
if (const_index) {
const_offset += array_stride * const_index->value.u[0];
} else {
offset = add(offset,
mul(array_index,
new(mem_ctx) ir_constant(array_stride)));
}
deref = deref_array->array->as_dereference();
break;
}
case ir_type_dereference_record: {
ir_dereference_record *deref_record = (ir_dereference_record *)deref;
const glsl_type *struct_type = deref_record->record->type;
unsigned intra_struct_offset = 0;
unsigned max_field_align = 16;
for (unsigned int i = 0; i < struct_type->length; i++) {
const glsl_type *type = struct_type->fields.structure[i].type;
unsigned field_align = type->std140_base_alignment(row_major);
max_field_align = MAX2(field_align, max_field_align);
intra_struct_offset = glsl_align(intra_struct_offset, field_align);
if (strcmp(struct_type->fields.structure[i].name,
deref_record->field) == 0)
break;
intra_struct_offset += type->std140_size(row_major);
}
const_offset = glsl_align(const_offset, max_field_align);
const_offset += intra_struct_offset;
deref = deref_record->record->as_dereference();
break;
}
default:
assert(!"not reached");
deref = NULL;
break;
}
}
/* Now that we've calculated the offset to the start of the
* dereference, walk over the type and emit loads into a temporary.
*/
const glsl_type *type = (*rvalue)->type;
ir_variable *load_var = new(mem_ctx) ir_variable(type,
"ubo_load_temp",
ir_var_temporary);
base_ir->insert_before(load_var);
ir_variable *load_offset = new(mem_ctx) ir_variable(glsl_type::uint_type,
"ubo_load_temp_offset",
ir_var_temporary);
base_ir->insert_before(load_offset);
base_ir->insert_before(assign(load_offset, offset));
deref = new(mem_ctx) ir_dereference_variable(load_var);
emit_ubo_loads(deref, load_offset, const_offset);
*rvalue = deref;
progress = true;
}
ir_expression *
lower_ubo_reference_visitor::ubo_load(const glsl_type *type,
ir_rvalue *offset)
{
ir_rvalue *block_ref = this->uniform_block->clone(mem_ctx, NULL);
return new(mem_ctx)
ir_expression(ir_binop_ubo_load,
type,
block_ref,
offset);
}
/**
* Takes LHS and emits a series of assignments into its components
* from the UBO variable at variable_offset + deref_offset.
*
* Recursively calls itself to break the deref down to the point that
* the ir_binop_ubo_load expressions generated are contiguous scalars
* or vectors.
*/
void
lower_ubo_reference_visitor::emit_ubo_loads(ir_dereference *deref,
ir_variable *base_offset,
unsigned int deref_offset)
{
if (deref->type->is_record()) {
unsigned int field_offset = 0;
for (unsigned i = 0; i < deref->type->length; i++) {
const struct glsl_struct_field *field =
&deref->type->fields.structure[i];
ir_dereference *field_deref =
new(mem_ctx) ir_dereference_record(deref->clone(mem_ctx, NULL),
field->name);
field_offset =
glsl_align(field_offset,
field->type->std140_base_alignment(ubo_var->RowMajor));
emit_ubo_loads(field_deref, base_offset, deref_offset + field_offset);
field_offset += field->type->std140_size(ubo_var->RowMajor);
}
return;
}
if (deref->type->is_array()) {
unsigned array_stride =
glsl_align(deref->type->fields.array->std140_size(ubo_var->RowMajor),
16);
for (unsigned i = 0; i < deref->type->length; i++) {
ir_constant *element = new(mem_ctx) ir_constant(i);
ir_dereference *element_deref =
new(mem_ctx) ir_dereference_array(deref->clone(mem_ctx, NULL),
element);
emit_ubo_loads(element_deref, base_offset,
deref_offset + i * array_stride);
}
return;
}
if (deref->type->is_matrix()) {
for (unsigned i = 0; i < deref->type->matrix_columns; i++) {
ir_constant *col = new(mem_ctx) ir_constant(i);
ir_dereference *col_deref =
new(mem_ctx) ir_dereference_array(deref->clone(mem_ctx, NULL),
col);
/* std140 always rounds the stride of arrays (and matrices)
* to a vec4, so matrices are always 16 between columns/rows.
*/
emit_ubo_loads(col_deref, base_offset, deref_offset + i * 16);
}
return;
}
assert(deref->type->is_scalar() ||
deref->type->is_vector());
if (!ubo_var->RowMajor) {
ir_rvalue *offset = add(base_offset,
new(mem_ctx) ir_constant(deref_offset));
base_ir->insert_before(assign(deref->clone(mem_ctx, NULL),
ubo_load(deref->type, offset)));
} else {
/* We're dereffing a column out of a row-major matrix, so we
* gather the vector from each stored row.
*/
assert(deref->type->base_type == GLSL_TYPE_FLOAT);
/* Matrices, row_major or not, are stored as if they were
* arrays of vectors of the appropriate size in std140.
* Arrays have their strides rounded up to a vec4, so the
* matrix stride is always 16.
*/
unsigned matrix_stride = 16;
for (unsigned i = 0; i < deref->type->vector_elements; i++) {
ir_rvalue *chan_offset =
add(base_offset,
new(mem_ctx) ir_constant(deref_offset + i * matrix_stride));
base_ir->insert_before(assign(deref->clone(mem_ctx, NULL),
ubo_load(glsl_type::float_type,
chan_offset),
(1U << i)));
}
}
}
} /* unnamed namespace */
void
lower_ubo_reference(struct gl_shader *shader, exec_list *instructions)
{
lower_ubo_reference_visitor v(shader);
/* Loop over the instructions lowering references, because we take
* a deref of a UBO array using a UBO dereference as the index will
* produce a collection of instructions all of which have cloned
* UBO dereferences for that array index.
*/
do {
v.progress = false;
visit_list_elements(&v, instructions);
} while (v.progress);
}
|
/*
* Copyright © 2012 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
/**
* \file lower_ubo_reference.cpp
*
* IR lower pass to replace dereferences of variables in a uniform
* buffer object with usage of ir_binop_ubo_load expressions, each of
* which can read data up to the size of a vec4.
*
* This relieves drivers of the responsibility to deal with tricky UBO
* layout issues like std140 structures and row_major matrices on
* their own.
*/
#include "ir.h"
#include "ir_builder.h"
#include "ir_rvalue_visitor.h"
#include "main/macros.h"
using namespace ir_builder;
namespace {
class lower_ubo_reference_visitor : public ir_rvalue_enter_visitor {
public:
lower_ubo_reference_visitor(struct gl_shader *shader)
: shader(shader)
{
}
void handle_rvalue(ir_rvalue **rvalue);
void emit_ubo_loads(ir_dereference *deref, ir_variable *base_offset,
unsigned int deref_offset);
ir_expression *ubo_load(const struct glsl_type *type,
ir_rvalue *offset);
void *mem_ctx;
struct gl_shader *shader;
struct gl_uniform_buffer_variable *ubo_var;
ir_rvalue *uniform_block;
bool progress;
};
/**
* Determine the name of the interface block field
*
* This is the name of the specific member as it would appear in the
* \c gl_uniform_buffer_variable::Name field in the shader's
* \c UniformBlocks array.
*/
static const char *
interface_field_name(void *mem_ctx, char *base_name, ir_dereference *d,
ir_rvalue **nonconst_block_index)
{
ir_rvalue *previous_index = NULL;
*nonconst_block_index = NULL;
while (d != NULL) {
switch (d->ir_type) {
case ir_type_dereference_variable: {
ir_dereference_variable *v = (ir_dereference_variable *) d;
if (previous_index
&& v->var->is_interface_instance()
&& v->var->type->is_array()) {
ir_constant *const_index = previous_index->as_constant();
if (!const_index) {
*nonconst_block_index = previous_index;
return ralloc_asprintf(mem_ctx, "%s[0]", base_name);
} else {
return ralloc_asprintf(mem_ctx,
"%s[%d]",
base_name,
const_index->get_uint_component(0));
}
} else {
return base_name;
}
break;
}
case ir_type_dereference_record: {
ir_dereference_record *r = (ir_dereference_record *) d;
d = r->record->as_dereference();
break;
}
case ir_type_dereference_array: {
ir_dereference_array *a = (ir_dereference_array *) d;
d = a->array->as_dereference();
previous_index = a->array_index;
break;
}
default:
assert(!"Should not get here.");
break;
}
}
assert(!"Should not get here.");
return NULL;
}
void
lower_ubo_reference_visitor::handle_rvalue(ir_rvalue **rvalue)
{
if (!*rvalue)
return;
ir_dereference *deref = (*rvalue)->as_dereference();
if (!deref)
return;
ir_variable *var = deref->variable_referenced();
if (!var || !var->is_in_uniform_block())
return;
mem_ctx = ralloc_parent(*rvalue);
ir_rvalue *nonconst_block_index;
const char *const field_name =
interface_field_name(mem_ctx, (char *) var->get_interface_type()->name,
deref, &nonconst_block_index);
this->uniform_block = NULL;
for (unsigned i = 0; i < shader->NumUniformBlocks; i++) {
if (strcmp(field_name, shader->UniformBlocks[i].Name) == 0) {
ir_constant *index = new(mem_ctx) ir_constant(i);
if (nonconst_block_index) {
if (nonconst_block_index->type != glsl_type::uint_type)
nonconst_block_index = i2u(nonconst_block_index);
this->uniform_block = add(nonconst_block_index, index);
} else {
this->uniform_block = index;
}
struct gl_uniform_block *block = &shader->UniformBlocks[i];
this->ubo_var = var->is_interface_instance()
? &block->Uniforms[0] : &block->Uniforms[var->data.location];
break;
}
}
assert(this->uniform_block);
ir_rvalue *offset = new(mem_ctx) ir_constant(0u);
unsigned const_offset = 0;
bool row_major = ubo_var->RowMajor;
/* Calculate the offset to the start of the region of the UBO
* dereferenced by *rvalue. This may be a variable offset if an
* array dereference has a variable index.
*/
while (deref) {
switch (deref->ir_type) {
case ir_type_dereference_variable: {
const_offset += ubo_var->Offset;
deref = NULL;
break;
}
case ir_type_dereference_array: {
ir_dereference_array *deref_array = (ir_dereference_array *)deref;
unsigned array_stride;
if (deref_array->array->type->is_matrix() && row_major) {
/* When loading a vector out of a row major matrix, the
* step between the columns (vectors) is the size of a
* float, while the step between the rows (elements of a
* vector) is handled below in emit_ubo_loads.
*/
array_stride = 4;
} else if (deref_array->type->is_interface()) {
/* We're processing an array dereference of an interface instance
* array. The thing being dereferenced *must* be a variable
* dereference because intefaces cannot be embedded an other
* types. In terms of calculating the offsets for the lowering
* pass, we don't care about the array index. All elements of an
* interface instance array will have the same offsets relative to
* the base of the block that backs them.
*/
assert(deref_array->array->as_dereference_variable());
deref = deref_array->array->as_dereference();
break;
} else {
array_stride = deref_array->type->std140_size(row_major);
array_stride = glsl_align(array_stride, 16);
}
ir_rvalue *array_index = deref_array->array_index;
if (array_index->type->base_type == GLSL_TYPE_INT)
array_index = i2u(array_index);
ir_constant *const_index =
array_index->constant_expression_value(NULL);
if (const_index) {
const_offset += array_stride * const_index->value.u[0];
} else {
offset = add(offset,
mul(array_index,
new(mem_ctx) ir_constant(array_stride)));
}
deref = deref_array->array->as_dereference();
break;
}
case ir_type_dereference_record: {
ir_dereference_record *deref_record = (ir_dereference_record *)deref;
const glsl_type *struct_type = deref_record->record->type;
unsigned intra_struct_offset = 0;
unsigned max_field_align = 16;
for (unsigned int i = 0; i < struct_type->length; i++) {
const glsl_type *type = struct_type->fields.structure[i].type;
unsigned field_align = type->std140_base_alignment(row_major);
max_field_align = MAX2(field_align, max_field_align);
intra_struct_offset = glsl_align(intra_struct_offset, field_align);
if (strcmp(struct_type->fields.structure[i].name,
deref_record->field) == 0)
break;
intra_struct_offset += type->std140_size(row_major);
}
const_offset = glsl_align(const_offset, max_field_align);
const_offset += intra_struct_offset;
deref = deref_record->record->as_dereference();
break;
}
default:
assert(!"not reached");
deref = NULL;
break;
}
}
/* Now that we've calculated the offset to the start of the
* dereference, walk over the type and emit loads into a temporary.
*/
const glsl_type *type = (*rvalue)->type;
ir_variable *load_var = new(mem_ctx) ir_variable(type,
"ubo_load_temp",
ir_var_temporary);
base_ir->insert_before(load_var);
ir_variable *load_offset = new(mem_ctx) ir_variable(glsl_type::uint_type,
"ubo_load_temp_offset",
ir_var_temporary);
base_ir->insert_before(load_offset);
base_ir->insert_before(assign(load_offset, offset));
deref = new(mem_ctx) ir_dereference_variable(load_var);
emit_ubo_loads(deref, load_offset, const_offset);
*rvalue = deref;
progress = true;
}
ir_expression *
lower_ubo_reference_visitor::ubo_load(const glsl_type *type,
ir_rvalue *offset)
{
ir_rvalue *block_ref = this->uniform_block->clone(mem_ctx, NULL);
return new(mem_ctx)
ir_expression(ir_binop_ubo_load,
type,
block_ref,
offset);
}
/**
* Takes LHS and emits a series of assignments into its components
* from the UBO variable at variable_offset + deref_offset.
*
* Recursively calls itself to break the deref down to the point that
* the ir_binop_ubo_load expressions generated are contiguous scalars
* or vectors.
*/
void
lower_ubo_reference_visitor::emit_ubo_loads(ir_dereference *deref,
ir_variable *base_offset,
unsigned int deref_offset)
{
if (deref->type->is_record()) {
unsigned int field_offset = 0;
for (unsigned i = 0; i < deref->type->length; i++) {
const struct glsl_struct_field *field =
&deref->type->fields.structure[i];
ir_dereference *field_deref =
new(mem_ctx) ir_dereference_record(deref->clone(mem_ctx, NULL),
field->name);
field_offset =
glsl_align(field_offset,
field->type->std140_base_alignment(ubo_var->RowMajor));
emit_ubo_loads(field_deref, base_offset, deref_offset + field_offset);
field_offset += field->type->std140_size(ubo_var->RowMajor);
}
return;
}
if (deref->type->is_array()) {
unsigned array_stride =
glsl_align(deref->type->fields.array->std140_size(ubo_var->RowMajor),
16);
for (unsigned i = 0; i < deref->type->length; i++) {
ir_constant *element = new(mem_ctx) ir_constant(i);
ir_dereference *element_deref =
new(mem_ctx) ir_dereference_array(deref->clone(mem_ctx, NULL),
element);
emit_ubo_loads(element_deref, base_offset,
deref_offset + i * array_stride);
}
return;
}
if (deref->type->is_matrix()) {
for (unsigned i = 0; i < deref->type->matrix_columns; i++) {
ir_constant *col = new(mem_ctx) ir_constant(i);
ir_dereference *col_deref =
new(mem_ctx) ir_dereference_array(deref->clone(mem_ctx, NULL),
col);
/* std140 always rounds the stride of arrays (and matrices)
* to a vec4, so matrices are always 16 between columns/rows.
*/
emit_ubo_loads(col_deref, base_offset, deref_offset + i * 16);
}
return;
}
assert(deref->type->is_scalar() ||
deref->type->is_vector());
if (!ubo_var->RowMajor) {
ir_rvalue *offset = add(base_offset,
new(mem_ctx) ir_constant(deref_offset));
base_ir->insert_before(assign(deref->clone(mem_ctx, NULL),
ubo_load(deref->type, offset)));
} else {
/* We're dereffing a column out of a row-major matrix, so we
* gather the vector from each stored row.
*/
assert(deref->type->base_type == GLSL_TYPE_FLOAT);
/* Matrices, row_major or not, are stored as if they were
* arrays of vectors of the appropriate size in std140.
* Arrays have their strides rounded up to a vec4, so the
* matrix stride is always 16.
*/
unsigned matrix_stride = 16;
for (unsigned i = 0; i < deref->type->vector_elements; i++) {
ir_rvalue *chan_offset =
add(base_offset,
new(mem_ctx) ir_constant(deref_offset + i * matrix_stride));
base_ir->insert_before(assign(deref->clone(mem_ctx, NULL),
ubo_load(glsl_type::float_type,
chan_offset),
(1U << i)));
}
}
}
} /* unnamed namespace */
void
lower_ubo_reference(struct gl_shader *shader, exec_list *instructions)
{
lower_ubo_reference_visitor v(shader);
/* Loop over the instructions lowering references, because we take
* a deref of a UBO array using a UBO dereference as the index will
* produce a collection of instructions all of which have cloned
* UBO dereferences for that array index.
*/
do {
v.progress = false;
visit_list_elements(&v, instructions);
} while (v.progress);
}
|
Use constant_expression_value instead of as_constant
|
glsl: Use constant_expression_value instead of as_constant
Just a few lines earlier we may have wrapped the index expression with
ir_unop_i2u expression. Whenever that happens, as_constant will return
NULL, and that almost always happens.
Signed-off-by: Ian Romanick <[email protected]>
Reviewed-by: Connor Abbott <[email protected]>
|
C++
|
mit
|
tokyovigilante/glsl-optimizer,bkaradzic/glsl-optimizer,wolf96/glsl-optimizer,jbarczak/glsl-optimizer,dellis1972/glsl-optimizer,jbarczak/glsl-optimizer,tokyovigilante/glsl-optimizer,bkaradzic/glsl-optimizer,wolf96/glsl-optimizer,zeux/glsl-optimizer,wolf96/glsl-optimizer,zz85/glsl-optimizer,benaadams/glsl-optimizer,jbarczak/glsl-optimizer,benaadams/glsl-optimizer,bkaradzic/glsl-optimizer,djreep81/glsl-optimizer,zz85/glsl-optimizer,wolf96/glsl-optimizer,mcanthony/glsl-optimizer,mcanthony/glsl-optimizer,dellis1972/glsl-optimizer,djreep81/glsl-optimizer,dellis1972/glsl-optimizer,zz85/glsl-optimizer,mcanthony/glsl-optimizer,zz85/glsl-optimizer,dellis1972/glsl-optimizer,djreep81/glsl-optimizer,zz85/glsl-optimizer,wolf96/glsl-optimizer,zeux/glsl-optimizer,bkaradzic/glsl-optimizer,tokyovigilante/glsl-optimizer,bkaradzic/glsl-optimizer,benaadams/glsl-optimizer,metora/MesaGLSLCompiler,metora/MesaGLSLCompiler,djreep81/glsl-optimizer,zz85/glsl-optimizer,metora/MesaGLSLCompiler,zeux/glsl-optimizer,jbarczak/glsl-optimizer,benaadams/glsl-optimizer,tokyovigilante/glsl-optimizer,tokyovigilante/glsl-optimizer,djreep81/glsl-optimizer,mcanthony/glsl-optimizer,jbarczak/glsl-optimizer,benaadams/glsl-optimizer,benaadams/glsl-optimizer,zeux/glsl-optimizer,dellis1972/glsl-optimizer,mcanthony/glsl-optimizer,zeux/glsl-optimizer
|
d2b0c111e64732f052d8609e0511178533e80d0a
|
core/src/gameengine/entities/animatable.cc
|
core/src/gameengine/entities/animatable.cc
|
//
// animatable.cpp
// GameEngine
//
// Created by Jon Sharkey on 2013-02-26.
// Copyright 2013 Sharkable. All rights reserved.
//
#include "gameengine/entities/animatable.h"
Animatable::Animatable()
: delegate_(nullptr),
position_(kGamePointZero),
angle_(0),
alpha_(1),
zoom_(1) {
}
Animatable::Animatable(GamePoint position)
: delegate_(nullptr),
position_(position),
angle_(0),
alpha_(1),
zoom_(1) {
}
void Animatable::AnimateToPosition(GamePoint position, AnimationType animation_type, int ticks) {
x_animation_.Reset(position_.x, position.x, ticks, animation_type);
y_animation_.Reset(position_.y, position.y, ticks, animation_type);
}
void Animatable::AnimateToAngle(double angle, AnimationType animation_type, int ticks) {
angle_animation_.Reset(angle_, angle, ticks, animation_type);
}
void Animatable::AnimateToAlpha(double alpha, AnimationType animation_type, int ticks) {
alpha_animation_.Reset(alpha_, alpha, ticks, animation_type);
}
void Animatable::AnimateToZoom(double zoom, AnimationType animation_type, int ticks) {
zoom_animation_.Reset(zoom_, zoom, ticks, animation_type);
}
#pragma mark - Simulator
void Animatable::SimulateStep() {
bool call_delegate = false;
if (x_animation_.IsActive()) {
position_.x = x_animation_.Update();
call_delegate = !x_animation_.IsActive();
}
if (y_animation_.IsActive()) {
position_.y = y_animation_.Update();
call_delegate = !y_animation_.IsActive();
}
if (angle_animation_.IsActive()) {
angle_ = angle_animation_.Update();
call_delegate = !angle_animation_.IsActive();
}
if (alpha_animation_.IsActive()) {
alpha_ = alpha_animation_.Update();
call_delegate = !alpha_animation_.IsActive();
}
if (zoom_animation_.IsActive()) {
zoom_ = zoom_animation_.Update();
call_delegate = !zoom_animation_.IsActive();
}
if (delegate_ && call_delegate) {
delegate_->AnimationFinished(this);
}
}
|
//
// animatable.cc
// GameEngine
//
// Created by Jon Sharkey on 2013-02-26.
// Copyright 2013 Sharkable. All rights reserved.
//
#include "gameengine/entities/animatable.h"
Animatable::Animatable()
: delegate_(nullptr),
position_(kGamePointZero),
angle_(0),
alpha_(1),
zoom_(1) {
}
Animatable::Animatable(GamePoint position)
: delegate_(nullptr),
position_(position),
angle_(0),
alpha_(1),
zoom_(1) {
}
void Animatable::AnimateToPosition(GamePoint position, AnimationType animation_type, int ticks) {
x_animation_.Reset(position_.x, position.x, ticks, animation_type);
y_animation_.Reset(position_.y, position.y, ticks, animation_type);
}
void Animatable::AnimateToAngle(double angle, AnimationType animation_type, int ticks) {
angle_animation_.Reset(angle_, angle, ticks, animation_type);
}
void Animatable::AnimateToAlpha(double alpha, AnimationType animation_type, int ticks) {
alpha_animation_.Reset(alpha_, alpha, ticks, animation_type);
}
void Animatable::AnimateToZoom(double zoom, AnimationType animation_type, int ticks) {
zoom_animation_.Reset(zoom_, zoom, ticks, animation_type);
}
#pragma mark - Simulator
void Animatable::SimulateStep() {
bool call_delegate = false;
if (x_animation_.IsActive()) {
position_.x = x_animation_.Update();
call_delegate = !x_animation_.IsActive();
}
if (y_animation_.IsActive()) {
position_.y = y_animation_.Update();
call_delegate = !y_animation_.IsActive();
}
if (angle_animation_.IsActive()) {
angle_ = angle_animation_.Update();
call_delegate = !angle_animation_.IsActive();
}
if (alpha_animation_.IsActive()) {
alpha_ = alpha_animation_.Update();
call_delegate = !alpha_animation_.IsActive();
}
if (zoom_animation_.IsActive()) {
zoom_ = zoom_animation_.Update();
call_delegate = !zoom_animation_.IsActive();
}
if (delegate_ && call_delegate) {
delegate_->AnimationFinished(this);
}
}
|
Fix typo in header.
|
Fix typo in header.
|
C++
|
apache-2.0
|
sharkable/sharkengine,sharkable/sharkengine,sharkable/sharkengine,sharkable/sharkengine,sharkable/sharkengine
|
173a9683f4cb92e7d689e1f5b7e1627c1ff40403
|
Code/GraphMol/RGroupDecomposition/RGroupFingerprintScore.cpp
|
Code/GraphMol/RGroupDecomposition/RGroupFingerprintScore.cpp
|
//
// Copyright (C) 2020 Gareth Jones, Glysade LLC
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include "RGroupFingerprintScore.h"
#include "GraphMol/Fingerprints/Fingerprints.h"
#include "GraphMol//Fingerprints/MorganFingerprints.h"
#include "../../../External/GA/util/Util.h"
#include <memory>
#include <utility>
#include <vector>
#include <map>
#ifdef RDK_THREADSAFE_SSS
#include <mutex>
#endif
// #define DEBUG
namespace RDKit {
static const int fingerprintSize = 512;
static const bool useTopologicalFingerprints = false;
// TODO scale variance by the number of separate attachments (as that variance
// will be counted for each attachment).
// Add fingerprint information to RGroupData
void addFingerprintToRGroupData(RGroupData *rgroupData) {
if (rgroupData->fingerprint == nullptr) {
RWMol mol(*rgroupData->combinedMol);
for (auto atom : mol.atoms()) {
// replace attachment atom by Boron
// TODO- Handle multiple attachments differently?
if (atom->getAtomicNum() == 0) {
atom->setAtomicNum(5);
if (atom->getIsotope() > 0) {
atom->setIsotope(0);
}
}
}
try {
MolOps::sanitizeMol(mol);
} catch (MolSanitizeException &) {
BOOST_LOG(rdWarningLog)
<< "Failed to sanitize RGroup fingerprint mol for "
<< rgroupData->smiles << std::endl;
}
#ifdef DEBUG
std::cerr << "Fingerprint mol smiles " << MolToSmiles(mol) << std::endl;
#endif
auto fingerprint = useTopologicalFingerprints
? RDKFingerprintMol(mol, 1, 7, fingerprintSize)
: MorganFingerprints::getFingerprintAsBitVect(
mol, 2, fingerprintSize);
fingerprint->getOnBits(rgroupData->fingerprintOnBits);
rgroupData->fingerprint = std::unique_ptr<ExplicitBitVect>(fingerprint);
#ifdef DEBUG
std::cerr << "Combined mol smiles " << MolToSmiles(*rgroupData->combinedMol)
<< std::endl;
#endif
}
}
// Adds or subtracts a molecule match to the rgroup fingerprint bit counts
// vectors
void FingerprintVarianceScoreData::modifyVarianceData(
int matchNumber, int permutationNumber,
const std::vector<std::vector<RGroupMatch>> &matches,
const std::set<int> &labels, bool add) {
// For each label (group)
const auto &match = matches.at(matchNumber).at(permutationNumber);
for (int l : labels) {
auto rg = match.rgroups.find(l);
if (rg != match.rgroups.end()) {
auto rgroupData = rg->second;
std::shared_ptr<VarianceDataForLabel> variableDataForLabel;
auto df = labelsToVarianceData.find(l);
if (df == labelsToVarianceData.end()) {
variableDataForLabel = std::make_shared<VarianceDataForLabel>(l);
labelsToVarianceData.emplace(l, variableDataForLabel);
} else {
variableDataForLabel = df->second;
}
if (add) {
variableDataForLabel->addRgroupData(rgroupData.get());
} else {
variableDataForLabel->removeRgroupData(rgroupData.get());
}
}
}
auto rgroupsMissing = match.numberMissingUserRGroups;
if (add) {
numberOfMissingUserRGroups += rgroupsMissing;
numberOfMolecules++;
} else {
numberOfMissingUserRGroups -= rgroupsMissing;
numberOfMolecules--;
}
}
// Adds a molecule match to the rgroup fingerprint bit counts
// vectors
void FingerprintVarianceScoreData::addVarianceData(
int matchNumber, int permutationNumber,
const std::vector<std::vector<RGroupMatch>> &matches,
const std::set<int> &labels) {
modifyVarianceData(matchNumber, permutationNumber, matches, labels, true);
}
// Subtracts a molecule match from the rgroup fingerprint bit counts
// vectors
void FingerprintVarianceScoreData::removeVarianceData(
int matchNumber, int permutationNumber,
const std::vector<std::vector<RGroupMatch>> &matches,
const std::set<int> &labels) {
modifyVarianceData(matchNumber, permutationNumber, matches, labels, false);
}
// fingerprint variance score
// The arithmetic mean of the mean fingerprint bit variances for the
// fingerprints at each rgroup position.
double fingerprintVarianceScore(
const std::vector<size_t> &permutation,
const std::vector<std::vector<RGroupMatch>> &matches,
const std::set<int> &labels,
FingerprintVarianceScoreData *fingerprintVarianceScoreData) {
#ifdef DEBUG
std::cerr << "---------------------------------------------------"
<< std::endl;
std::cerr << "Fingerprint Scoring permutation "
<< " num matches: " << matches.size() << std::endl;
#endif
CHECK_INVARIANT(permutation.size() <= matches.size(), "");
FingerprintVarianceScoreData fingerprintVarianceScoreData2;
if (!fingerprintVarianceScoreData) {
fingerprintVarianceScoreData = &fingerprintVarianceScoreData2;
}
auto &labelsToVarianceData =
fingerprintVarianceScoreData->labelsToVarianceData;
// For each label (group)
for (int l : labels) {
#ifdef DEBUG
std::cerr << "Label: " << l << std::endl;
#endif
std::shared_ptr<VarianceDataForLabel> variableDataForLabel;
auto d = labelsToVarianceData.find(l);
if (d == labelsToVarianceData.end()) {
variableDataForLabel = std::make_shared<VarianceDataForLabel>(l);
labelsToVarianceData.emplace(l, variableDataForLabel);
} else {
variableDataForLabel = d->second;
}
for (size_t m = 0; m < permutation.size(); ++m) { // for each molecule
const auto &match = matches[m].at(permutation[m]);
auto rg = match.rgroups.find(l);
if (rg != match.rgroups.end()) {
auto rgroupData = rg->second;
variableDataForLabel->addRgroupData(rgroupData.get());
}
}
}
size_t numberMissingRGroups = 0;
for (size_t m = 0; m < permutation.size(); ++m) { // for each molecule
numberMissingRGroups +=
matches[m].at(permutation[m]).numberMissingUserRGroups;
}
fingerprintVarianceScoreData->numberOfMissingUserRGroups +=
numberMissingRGroups;
fingerprintVarianceScoreData->numberOfMolecules += permutation.size();
return fingerprintVarianceScoreData->fingerprintVarianceGroupScore();
}
// calculates fingerprint variance score from rgroup bit counts
double FingerprintVarianceScoreData::fingerprintVarianceGroupScore() {
// arithmetic mean of scores for each label
#ifdef DEBUG
std::cerr << "fingerprint variance score: ";
#endif
auto sum = std::accumulate(
labelsToVarianceData.cbegin(), labelsToVarianceData.cend(), 0.0,
[](double sum,
std::pair<int, std::shared_ptr<VarianceDataForLabel>> pair) {
auto variance = pair.second->variance();
// perhaps here the variance should be weighted by occupancy- so that
// sparsely populated rgroups are penalized
// e.g variance *= ((double) numberOfMolecules) /
// ((double)pair.second->numberFingerprints);
#ifdef DEBUG
std::cerr << variance << ',';
#endif
return sum + variance;
});
// Heuristic correction of missing user r_groups - equivalent to a variance
// penalty of 1 for each missing user R-group across the entire dataset
CHECK_INVARIANT(numberOfMolecules > 0, "No compounds to be scored!");
double rgroupPenalty =
(double)numberOfMissingUserRGroups / (double)numberOfMolecules;
// double the penalty to catch systems like
// https://github.com/rdkit/rdkit/issues/3896
auto score = sum + 2.0 * rgroupPenalty;
#ifdef DEBUG
std::cerr << " sum " << sum << " rgroup penalty " << rgroupPenalty
<< " score " << score << std::endl;
#endif
// want to minimize this score
return -score;
}
VarianceDataForLabel::VarianceDataForLabel(const int &label,
int numberFingerprints,
std::vector<int> bitCounts)
: label(label),
numberFingerprints(numberFingerprints),
bitCounts(std::move(bitCounts)) {}
VarianceDataForLabel::VarianceDataForLabel(const int &label) : label(label) {
numberFingerprints = 0;
bitCounts = std::vector<int>(fingerprintSize, 0.0);
}
#ifdef RDK_THREADSAFE_SSS
static std::mutex groupMutex;
#endif
// add an rgroup structure to a bit counts array
void VarianceDataForLabel::addRgroupData(RGroupData *rgroupData) {
if (rgroupData->fingerprint == nullptr) {
#ifdef RDK_THREADSAFE_SSS
const std::lock_guard<std::mutex> lock(groupMutex);
#endif
if (rgroupData->fingerprint == nullptr) {
addFingerprintToRGroupData(rgroupData);
}
}
++numberFingerprints;
const auto &onBits = rgroupData->fingerprintOnBits;
for (int b : onBits) {
++bitCounts[b];
}
}
// remove an rgroup structure to a bit counts array
void VarianceDataForLabel::removeRgroupData(RGroupData *rgroupData) {
if (rgroupData->fingerprint == nullptr) {
addFingerprintToRGroupData(rgroupData);
}
--numberFingerprints;
const auto &onBits = rgroupData->fingerprintOnBits;
for (int b : onBits) {
--bitCounts[b];
}
}
// calculate the mean variance for a bit counts array
double VarianceDataForLabel::variance() const {
auto lambda = [this](double sum, int bitCount) {
if (bitCount == 0) {
return sum;
}
// variance calculation because fingerprint is binary:
// sum == squared sum == bit count
// ss = sqrSum - (sum * sum) / cnt;
auto ss = bitCount - (bitCount * bitCount) / (double)numberFingerprints;
double variancePerBit = ss / (double)numberFingerprints;
#ifdef DEBUG
std::cerr << variancePerBit << ',';
#endif
return sum + variancePerBit;
};
#ifdef DEBUG
std::cerr << "Bitcounts " << GarethUtil::collectionToString(bitCounts, ",")
<< std::endl;
std::cerr << "Variance per bit ";
#endif
auto totalVariance =
std::accumulate(bitCounts.begin(), bitCounts.end(), 0.0, lambda);
#ifdef DEBUG
std::cerr << std::endl;
#endif
auto rmsVariance = sqrt(totalVariance);
#ifdef DEBUG
std::cerr << "Total Variance " << totalVariance << " RMS Variance "
<< rmsVariance << std::endl;
#endif
return rmsVariance;
}
void FingerprintVarianceScoreData::clear() {
numberOfMissingUserRGroups = 0;
numberOfMolecules = 0;
labelsToVarianceData.clear();
}
} // namespace RDKit
|
//
// Copyright (C) 2020 Gareth Jones, Glysade LLC
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include "RGroupFingerprintScore.h"
#include "GraphMol/Fingerprints/Fingerprints.h"
#include "GraphMol//Fingerprints/MorganFingerprints.h"
#include "../../../External/GA/util/Util.h"
#include <memory>
#include <utility>
#include <vector>
#include <map>
#ifdef RDK_THREADSAFE_SSS
#include <mutex>
#endif
// #define DEBUG
namespace RDKit {
static const int fingerprintSize = 512;
static const bool useTopologicalFingerprints = false;
// TODO scale variance by the number of separate attachments (as that variance
// will be counted for each attachment).
// Add fingerprint information to RGroupData
void addFingerprintToRGroupData(RGroupData *rgroupData) {
if (rgroupData->fingerprint == nullptr) {
RWMol mol(*rgroupData->combinedMol);
for (auto atom : mol.atoms()) {
// replace attachment atom by Boron
// TODO- Handle multiple attachments differently?
if (atom->getAtomicNum() == 0) {
atom->setAtomicNum(5);
if (atom->getIsotope() > 0) {
atom->setIsotope(0);
}
}
}
try {
MolOps::sanitizeMol(mol);
} catch (MolSanitizeException &) {
BOOST_LOG(rdWarningLog)
<< "Failed to sanitize RGroup fingerprint mol for "
<< rgroupData->smiles << std::endl;
}
#ifdef DEBUG
std::cerr << "Fingerprint mol smiles " << MolToSmiles(mol) << std::endl;
#endif
auto fingerprint = useTopologicalFingerprints
? RDKFingerprintMol(mol, 1, 7, fingerprintSize)
: MorganFingerprints::getFingerprintAsBitVect(
mol, 2, fingerprintSize);
fingerprint->getOnBits(rgroupData->fingerprintOnBits);
rgroupData->fingerprint.reset(fingerprint);
#ifdef DEBUG
std::cerr << "Combined mol smiles " << MolToSmiles(*rgroupData->combinedMol)
<< std::endl;
#endif
}
}
// Adds or subtracts a molecule match to the rgroup fingerprint bit counts
// vectors
void FingerprintVarianceScoreData::modifyVarianceData(
int matchNumber, int permutationNumber,
const std::vector<std::vector<RGroupMatch>> &matches,
const std::set<int> &labels, bool add) {
// For each label (group)
const auto &match = matches.at(matchNumber).at(permutationNumber);
for (int l : labels) {
auto rg = match.rgroups.find(l);
if (rg != match.rgroups.end()) {
auto rgroupData = rg->second;
std::shared_ptr<VarianceDataForLabel> variableDataForLabel;
auto df = labelsToVarianceData.find(l);
if (df == labelsToVarianceData.end()) {
variableDataForLabel = std::make_shared<VarianceDataForLabel>(l);
labelsToVarianceData.emplace(l, variableDataForLabel);
} else {
variableDataForLabel = df->second;
}
if (add) {
variableDataForLabel->addRgroupData(rgroupData.get());
} else {
variableDataForLabel->removeRgroupData(rgroupData.get());
}
}
}
auto rgroupsMissing = match.numberMissingUserRGroups;
if (add) {
numberOfMissingUserRGroups += rgroupsMissing;
numberOfMolecules++;
} else {
numberOfMissingUserRGroups -= rgroupsMissing;
numberOfMolecules--;
}
}
// Adds a molecule match to the rgroup fingerprint bit counts
// vectors
void FingerprintVarianceScoreData::addVarianceData(
int matchNumber, int permutationNumber,
const std::vector<std::vector<RGroupMatch>> &matches,
const std::set<int> &labels) {
modifyVarianceData(matchNumber, permutationNumber, matches, labels, true);
}
// Subtracts a molecule match from the rgroup fingerprint bit counts
// vectors
void FingerprintVarianceScoreData::removeVarianceData(
int matchNumber, int permutationNumber,
const std::vector<std::vector<RGroupMatch>> &matches,
const std::set<int> &labels) {
modifyVarianceData(matchNumber, permutationNumber, matches, labels, false);
}
// fingerprint variance score
// The arithmetic mean of the mean fingerprint bit variances for the
// fingerprints at each rgroup position.
double fingerprintVarianceScore(
const std::vector<size_t> &permutation,
const std::vector<std::vector<RGroupMatch>> &matches,
const std::set<int> &labels,
FingerprintVarianceScoreData *fingerprintVarianceScoreData) {
#ifdef DEBUG
std::cerr << "---------------------------------------------------"
<< std::endl;
std::cerr << "Fingerprint Scoring permutation "
<< " num matches: " << matches.size() << std::endl;
#endif
CHECK_INVARIANT(permutation.size() <= matches.size(), "");
FingerprintVarianceScoreData fingerprintVarianceScoreData2;
if (!fingerprintVarianceScoreData) {
fingerprintVarianceScoreData = &fingerprintVarianceScoreData2;
}
auto &labelsToVarianceData =
fingerprintVarianceScoreData->labelsToVarianceData;
// For each label (group)
for (int l : labels) {
#ifdef DEBUG
std::cerr << "Label: " << l << std::endl;
#endif
std::shared_ptr<VarianceDataForLabel> variableDataForLabel;
auto d = labelsToVarianceData.find(l);
if (d == labelsToVarianceData.end()) {
variableDataForLabel = std::make_shared<VarianceDataForLabel>(l);
labelsToVarianceData.emplace(l, variableDataForLabel);
} else {
variableDataForLabel = d->second;
}
for (size_t m = 0; m < permutation.size(); ++m) { // for each molecule
const auto &match = matches[m].at(permutation[m]);
auto rg = match.rgroups.find(l);
if (rg != match.rgroups.end()) {
auto rgroupData = rg->second;
variableDataForLabel->addRgroupData(rgroupData.get());
}
}
}
size_t numberMissingRGroups = 0;
for (size_t m = 0; m < permutation.size(); ++m) { // for each molecule
numberMissingRGroups +=
matches[m].at(permutation[m]).numberMissingUserRGroups;
}
fingerprintVarianceScoreData->numberOfMissingUserRGroups +=
numberMissingRGroups;
fingerprintVarianceScoreData->numberOfMolecules += permutation.size();
return fingerprintVarianceScoreData->fingerprintVarianceGroupScore();
}
// calculates fingerprint variance score from rgroup bit counts
double FingerprintVarianceScoreData::fingerprintVarianceGroupScore() {
// arithmetic mean of scores for each label
#ifdef DEBUG
std::cerr << "fingerprint variance score: ";
#endif
auto sum = std::accumulate(
labelsToVarianceData.cbegin(), labelsToVarianceData.cend(), 0.0,
[](double sum,
std::pair<int, std::shared_ptr<VarianceDataForLabel>> pair) {
auto variance = pair.second->variance();
// perhaps here the variance should be weighted by occupancy- so that
// sparsely populated rgroups are penalized
// e.g variance *= ((double) numberOfMolecules) /
// ((double)pair.second->numberFingerprints);
#ifdef DEBUG
std::cerr << variance << ',';
#endif
return sum + variance;
});
// Heuristic correction of missing user r_groups - equivalent to a variance
// penalty of 1 for each missing user R-group across the entire dataset
CHECK_INVARIANT(numberOfMolecules > 0, "No compounds to be scored!");
double rgroupPenalty =
(double)numberOfMissingUserRGroups / (double)numberOfMolecules;
// double the penalty to catch systems like
// https://github.com/rdkit/rdkit/issues/3896
auto score = sum + 2.0 * rgroupPenalty;
#ifdef DEBUG
std::cerr << " sum " << sum << " rgroup penalty " << rgroupPenalty
<< " score " << score << std::endl;
#endif
// want to minimize this score
return -score;
}
VarianceDataForLabel::VarianceDataForLabel(const int &label,
int numberFingerprints,
std::vector<int> bitCounts)
: label(label),
numberFingerprints(numberFingerprints),
bitCounts(std::move(bitCounts)) {}
VarianceDataForLabel::VarianceDataForLabel(const int &label) : label(label) {
numberFingerprints = 0;
bitCounts = std::vector<int>(fingerprintSize, 0.0);
}
#ifdef RDK_THREADSAFE_SSS
static std::mutex groupMutex;
#endif
// add an rgroup structure to a bit counts array
void VarianceDataForLabel::addRgroupData(RGroupData *rgroupData) {
{
#ifdef RDK_THREADSAFE_SSS
const std::lock_guard<std::mutex> lock(groupMutex);
#endif
if (rgroupData->fingerprint == nullptr) {
addFingerprintToRGroupData(rgroupData);
}
}
++numberFingerprints;
const auto &onBits = rgroupData->fingerprintOnBits;
for (int b : onBits) {
++bitCounts[b];
}
}
// remove an rgroup structure to a bit counts array
void VarianceDataForLabel::removeRgroupData(RGroupData *rgroupData) {
if (rgroupData->fingerprint == nullptr) {
addFingerprintToRGroupData(rgroupData);
}
--numberFingerprints;
const auto &onBits = rgroupData->fingerprintOnBits;
for (int b : onBits) {
--bitCounts[b];
}
}
// calculate the mean variance for a bit counts array
double VarianceDataForLabel::variance() const {
auto lambda = [this](double sum, int bitCount) {
if (bitCount == 0) {
return sum;
}
// variance calculation because fingerprint is binary:
// sum == squared sum == bit count
// ss = sqrSum - (sum * sum) / cnt;
auto ss = bitCount - (bitCount * bitCount) / (double)numberFingerprints;
double variancePerBit = ss / (double)numberFingerprints;
#ifdef DEBUG
std::cerr << variancePerBit << ',';
#endif
return sum + variancePerBit;
};
#ifdef DEBUG
std::cerr << "Bitcounts " << GarethUtil::collectionToString(bitCounts, ",")
<< std::endl;
std::cerr << "Variance per bit ";
#endif
auto totalVariance =
std::accumulate(bitCounts.begin(), bitCounts.end(), 0.0, lambda);
#ifdef DEBUG
std::cerr << std::endl;
#endif
auto rmsVariance = sqrt(totalVariance);
#ifdef DEBUG
std::cerr << "Total Variance " << totalVariance << " RMS Variance "
<< rmsVariance << std::endl;
#endif
return rmsVariance;
}
void FingerprintVarianceScoreData::clear() {
numberOfMissingUserRGroups = 0;
numberOfMolecules = 0;
labelsToVarianceData.clear();
}
} // namespace RDKit
|
Fix duplicate non thread safe check in VarianceDataForLabel (#5212)
|
Fix duplicate non thread safe check in VarianceDataForLabel (#5212)
* fix non thread safe check in VarianceDataForLabel::addRgroupData()
* scope mutex
|
C++
|
bsd-3-clause
|
greglandrum/rdkit,bp-kelley/rdkit,ptosco/rdkit,bp-kelley/rdkit,rdkit/rdkit,greglandrum/rdkit,rdkit/rdkit,greglandrum/rdkit,ptosco/rdkit,ptosco/rdkit,greglandrum/rdkit,greglandrum/rdkit,ptosco/rdkit,rdkit/rdkit,bp-kelley/rdkit,rdkit/rdkit,rdkit/rdkit,ptosco/rdkit,greglandrum/rdkit,bp-kelley/rdkit,greglandrum/rdkit,bp-kelley/rdkit,bp-kelley/rdkit,bp-kelley/rdkit,ptosco/rdkit,rdkit/rdkit,ptosco/rdkit,greglandrum/rdkit,rdkit/rdkit,rdkit/rdkit,ptosco/rdkit,bp-kelley/rdkit
|
a9519ea536b43195134669a62821207d94d1e750
|
src/file_storage.cpp
|
src/file_storage.cpp
|
/*
Copyright (c) 2003-2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include "libtorrent/file_storage.hpp"
#include "libtorrent/utf8.hpp"
#include <boost/bind.hpp>
namespace libtorrent
{
file_storage::file_storage()
: m_piece_length(0)
, m_total_size(0)
, m_num_pieces(0)
{}
int file_storage::piece_size(int index) const
{
TORRENT_ASSERT(index >= 0 && index < num_pieces());
if (index == num_pieces()-1)
{
int size = int(total_size()
- size_type(num_pieces() - 1) * piece_length());
TORRENT_ASSERT(size > 0);
TORRENT_ASSERT(size <= piece_length());
return int(size);
}
else
return piece_length();
}
#ifndef BOOST_FILESYSTEM_NARROW_ONLY
void file_storage::set_name(std::wstring const& n)
{
std::string utf8;
wchar_utf8(n, utf8);
m_name = utf8;
}
void file_storage::rename_file(int index, std::wstring const& new_filename)
{
TORRENT_ASSERT(index >= 0 && index < int(m_files.size()));
std::string utf8;
wchar_utf8(new_filename, utf8);
m_files[index].path = utf8;
}
void file_storage::add_file(fs::wpath const& file, size_type size, int flags)
{
std::string utf8;
wchar_utf8(file.string(), utf8);
add_file(utf8, size, flags);
}
#endif
void file_storage::rename_file(int index, std::string const& new_filename)
{
TORRENT_ASSERT(index >= 0 && index < int(m_files.size()));
m_files[index].path = new_filename;
}
file_storage::iterator file_storage::file_at_offset(size_type offset) const
{
// TODO: do a binary search
std::vector<file_entry>::const_iterator i;
for (i = begin(); i != end(); ++i)
{
if (i->offset <= offset && i->offset + i->size > offset)
return i;
}
return i;
}
namespace
{
bool compare_file_offset(file_entry const& lhs, file_entry const& rhs)
{
return lhs.offset < rhs.offset;
}
}
std::vector<file_slice> file_storage::map_block(int piece, size_type offset
, int size) const
{
TORRENT_ASSERT(num_files() > 0);
std::vector<file_slice> ret;
if (m_files.empty()) return ret;
// find the file iterator and file offset
file_entry target;
target.offset = piece * (size_type)m_piece_length + offset;
TORRENT_ASSERT(target.offset + size <= m_total_size);
TORRENT_ASSERT(!compare_file_offset(target, m_files.front()));
std::vector<file_entry>::const_iterator file_iter = std::upper_bound(
begin(), end(), target, compare_file_offset);
TORRENT_ASSERT(file_iter != begin());
--file_iter;
size_type file_offset = target.offset - file_iter->offset;
for (; size > 0; file_offset -= file_iter->size, ++file_iter)
{
TORRENT_ASSERT(file_iter != end());
if (file_offset < file_iter->size)
{
file_slice f;
f.file_index = file_iter - begin();
f.offset = file_offset + file_iter->file_base;
f.size = (std::min)(file_iter->size - file_offset, (size_type)size);
size -= f.size;
file_offset += f.size;
ret.push_back(f);
}
TORRENT_ASSERT(size >= 0);
}
return ret;
}
peer_request file_storage::map_file(int file_index, size_type file_offset
, int size) const
{
TORRENT_ASSERT(file_index < num_files());
TORRENT_ASSERT(file_index >= 0);
size_type offset = file_offset + at(file_index).offset;
peer_request ret;
ret.piece = int(offset / piece_length());
ret.start = int(offset - ret.piece * piece_length());
ret.length = size;
return ret;
}
void file_storage::add_file(fs::path const& file, size_type size, int flags)
{
TORRENT_ASSERT(size >= 0);
#if BOOST_VERSION < 103600
if (!file.has_branch_path())
#else
if (!file.has_parent_path())
#endif
{
// you have already added at least one file with a
// path to the file (branch_path), which means that
// all the other files need to be in the same top
// directory as the first file.
TORRENT_ASSERT(m_files.empty());
m_name = file.string();
}
else
{
if (m_files.empty())
m_name = *file.begin();
}
TORRENT_ASSERT(m_name == *file.begin());
m_files.push_back(file_entry());
file_entry& e = m_files.back();
e.size = size;
e.path = file;
e.offset = m_total_size;
e.pad_file = bool(flags & pad_file);
e.hidden_attribute = bool(flags & attribute_hidden);
e.executable_attribute = bool(flags & attribute_executable);
m_total_size += size;
}
void file_storage::add_file(file_entry const& ent)
{
#if BOOST_VERSION < 103600
if (!ent.path.has_branch_path())
#else
if (!ent.path.has_parent_path())
#endif
{
// you have already added at least one file with a
// path to the file (branch_path), which means that
// all the other files need to be in the same top
// directory as the first file.
TORRENT_ASSERT(m_files.empty());
m_name = ent.path.string();
}
else
{
if (m_files.empty())
m_name = *ent.path.begin();
}
m_files.push_back(ent);
file_entry& e = m_files.back();
e.offset = m_total_size;
m_total_size += ent.size;
}
void file_storage::optimize(int pad_file_limit)
{
// the main purpuse of padding is to optimize disk
// I/O. This is a conservative memory page size assumption
int alignment = 8*1024;
// it doesn't make any sense to pad files that
// are smaller than one piece
if (pad_file_limit >= 0 && pad_file_limit < alignment)
pad_file_limit = alignment;
// put the largest file at the front, to make sure
// it's aligned
std::vector<file_entry>::iterator i = std::max_element(m_files.begin(), m_files.end()
, boost::bind(&file_entry::size, _1) < boost::bind(&file_entry::size, _2));
using std::iter_swap;
iter_swap(i, m_files.begin());
size_type off = 0;
int padding_file = 0;
for (std::vector<file_entry>::iterator i = m_files.begin();
i != m_files.end(); ++i)
{
if (pad_file_limit >= 0
&& (off & (alignment-1)) != 0
&& i->size > pad_file_limit
&& i->pad_file == false)
{
// if we have pad files enabled, and this file is
// not piece-aligned and the file size exceeds the
// limit, and it's not a padding file itself.
// so add a padding file in front of it
int pad_size = alignment - (off & (alignment-1));
// find the largest file that fits in pad_size
std::vector<file_entry>::iterator best_match = m_files.end();
for (std::vector<file_entry>::iterator j = i+1; j < m_files.end(); ++j)
{
if (j->size > pad_size) continue;
if (best_match == m_files.end() || j->size > best_match->size)
best_match = j;
}
if (best_match != m_files.end())
{
// we found one
file_entry e = *best_match;
m_files.erase(best_match);
i = m_files.insert(i, e);
i->offset = off;
off += i->size;
continue;
}
// we could not find a file that fits in pad_size
// add a padding file
file_entry e;
i = m_files.insert(i, e);
i->size = pad_size;
i->offset = off;
i->file_base = 0;
char name[10];
std::sprintf(name, "%d", padding_file);
i->path = *(i+1)->path.begin();
i->path /= "_____padding_file_";
i->path /= name;
i->pad_file = true;
off += pad_size;
++padding_file;
++i;
}
i->offset = off;
off += i->size;
}
m_total_size = off;
}
}
|
/*
Copyright (c) 2003-2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include "libtorrent/file_storage.hpp"
#include "libtorrent/utf8.hpp"
#include <boost/bind.hpp>
#include <cstdio>
namespace libtorrent
{
file_storage::file_storage()
: m_piece_length(0)
, m_total_size(0)
, m_num_pieces(0)
{}
int file_storage::piece_size(int index) const
{
TORRENT_ASSERT(index >= 0 && index < num_pieces());
if (index == num_pieces()-1)
{
int size = int(total_size()
- size_type(num_pieces() - 1) * piece_length());
TORRENT_ASSERT(size > 0);
TORRENT_ASSERT(size <= piece_length());
return int(size);
}
else
return piece_length();
}
#ifndef BOOST_FILESYSTEM_NARROW_ONLY
void file_storage::set_name(std::wstring const& n)
{
std::string utf8;
wchar_utf8(n, utf8);
m_name = utf8;
}
void file_storage::rename_file(int index, std::wstring const& new_filename)
{
TORRENT_ASSERT(index >= 0 && index < int(m_files.size()));
std::string utf8;
wchar_utf8(new_filename, utf8);
m_files[index].path = utf8;
}
void file_storage::add_file(fs::wpath const& file, size_type size, int flags)
{
std::string utf8;
wchar_utf8(file.string(), utf8);
add_file(utf8, size, flags);
}
#endif
void file_storage::rename_file(int index, std::string const& new_filename)
{
TORRENT_ASSERT(index >= 0 && index < int(m_files.size()));
m_files[index].path = new_filename;
}
file_storage::iterator file_storage::file_at_offset(size_type offset) const
{
// TODO: do a binary search
std::vector<file_entry>::const_iterator i;
for (i = begin(); i != end(); ++i)
{
if (i->offset <= offset && i->offset + i->size > offset)
return i;
}
return i;
}
namespace
{
bool compare_file_offset(file_entry const& lhs, file_entry const& rhs)
{
return lhs.offset < rhs.offset;
}
}
std::vector<file_slice> file_storage::map_block(int piece, size_type offset
, int size) const
{
TORRENT_ASSERT(num_files() > 0);
std::vector<file_slice> ret;
if (m_files.empty()) return ret;
// find the file iterator and file offset
file_entry target;
target.offset = piece * (size_type)m_piece_length + offset;
TORRENT_ASSERT(target.offset + size <= m_total_size);
TORRENT_ASSERT(!compare_file_offset(target, m_files.front()));
std::vector<file_entry>::const_iterator file_iter = std::upper_bound(
begin(), end(), target, compare_file_offset);
TORRENT_ASSERT(file_iter != begin());
--file_iter;
size_type file_offset = target.offset - file_iter->offset;
for (; size > 0; file_offset -= file_iter->size, ++file_iter)
{
TORRENT_ASSERT(file_iter != end());
if (file_offset < file_iter->size)
{
file_slice f;
f.file_index = file_iter - begin();
f.offset = file_offset + file_iter->file_base;
f.size = (std::min)(file_iter->size - file_offset, (size_type)size);
size -= f.size;
file_offset += f.size;
ret.push_back(f);
}
TORRENT_ASSERT(size >= 0);
}
return ret;
}
peer_request file_storage::map_file(int file_index, size_type file_offset
, int size) const
{
TORRENT_ASSERT(file_index < num_files());
TORRENT_ASSERT(file_index >= 0);
size_type offset = file_offset + at(file_index).offset;
peer_request ret;
ret.piece = int(offset / piece_length());
ret.start = int(offset - ret.piece * piece_length());
ret.length = size;
return ret;
}
void file_storage::add_file(fs::path const& file, size_type size, int flags)
{
TORRENT_ASSERT(size >= 0);
#if BOOST_VERSION < 103600
if (!file.has_branch_path())
#else
if (!file.has_parent_path())
#endif
{
// you have already added at least one file with a
// path to the file (branch_path), which means that
// all the other files need to be in the same top
// directory as the first file.
TORRENT_ASSERT(m_files.empty());
m_name = file.string();
}
else
{
if (m_files.empty())
m_name = *file.begin();
}
TORRENT_ASSERT(m_name == *file.begin());
m_files.push_back(file_entry());
file_entry& e = m_files.back();
e.size = size;
e.path = file;
e.offset = m_total_size;
e.pad_file = bool(flags & pad_file);
e.hidden_attribute = bool(flags & attribute_hidden);
e.executable_attribute = bool(flags & attribute_executable);
m_total_size += size;
}
void file_storage::add_file(file_entry const& ent)
{
#if BOOST_VERSION < 103600
if (!ent.path.has_branch_path())
#else
if (!ent.path.has_parent_path())
#endif
{
// you have already added at least one file with a
// path to the file (branch_path), which means that
// all the other files need to be in the same top
// directory as the first file.
TORRENT_ASSERT(m_files.empty());
m_name = ent.path.string();
}
else
{
if (m_files.empty())
m_name = *ent.path.begin();
}
m_files.push_back(ent);
file_entry& e = m_files.back();
e.offset = m_total_size;
m_total_size += ent.size;
}
void file_storage::optimize(int pad_file_limit)
{
// the main purpuse of padding is to optimize disk
// I/O. This is a conservative memory page size assumption
int alignment = 8*1024;
// it doesn't make any sense to pad files that
// are smaller than one piece
if (pad_file_limit >= 0 && pad_file_limit < alignment)
pad_file_limit = alignment;
// put the largest file at the front, to make sure
// it's aligned
std::vector<file_entry>::iterator i = std::max_element(m_files.begin(), m_files.end()
, boost::bind(&file_entry::size, _1) < boost::bind(&file_entry::size, _2));
using std::iter_swap;
iter_swap(i, m_files.begin());
size_type off = 0;
int padding_file = 0;
for (std::vector<file_entry>::iterator i = m_files.begin();
i != m_files.end(); ++i)
{
if (pad_file_limit >= 0
&& (off & (alignment-1)) != 0
&& i->size > pad_file_limit
&& i->pad_file == false)
{
// if we have pad files enabled, and this file is
// not piece-aligned and the file size exceeds the
// limit, and it's not a padding file itself.
// so add a padding file in front of it
int pad_size = alignment - (off & (alignment-1));
// find the largest file that fits in pad_size
std::vector<file_entry>::iterator best_match = m_files.end();
for (std::vector<file_entry>::iterator j = i+1; j < m_files.end(); ++j)
{
if (j->size > pad_size) continue;
if (best_match == m_files.end() || j->size > best_match->size)
best_match = j;
}
if (best_match != m_files.end())
{
// we found one
file_entry e = *best_match;
m_files.erase(best_match);
i = m_files.insert(i, e);
i->offset = off;
off += i->size;
continue;
}
// we could not find a file that fits in pad_size
// add a padding file
file_entry e;
i = m_files.insert(i, e);
i->size = pad_size;
i->offset = off;
i->file_base = 0;
char name[10];
std::sprintf(name, "%d", padding_file);
i->path = *(i+1)->path.begin();
i->path /= "_____padding_file_";
i->path /= name;
i->pad_file = true;
off += pad_size;
++padding_file;
++i;
}
i->offset = off;
off += i->size;
}
m_total_size = off;
}
}
|
Fix build on GCC 4.4.
|
Fix build on GCC 4.4.
git-svn-id: 6ed3528c1be4534134272ad6dd050eeaa1f628d3@3670 f43f7eb3-cfe1-5f9d-1b5f-e45aa6702bda
|
C++
|
bsd-3-clause
|
steeve/libtorrent,steeve/libtorrent,steeve/libtorrent,steeve/libtorrent,steeve/libtorrent,steeve/libtorrent
|
aacea7da465b6667e80d87a6c074e092a8908cf6
|
cppuhelper/inc/cppuhelper/implementationentry.hxx
|
cppuhelper/inc/cppuhelper/implementationentry.hxx
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _CPPUHELPER_IMPLEMENTATIONENTRY_HXX_
#define _CPPUHELPER_IMPLEMENTATIONENTRY_HXX_
#include <cppuhelper/factory.hxx>
#include "cppuhelperdllapi.h"
namespace cppu
{
/** One struct instance represents all data necessary for registering one service implementation.
*/
struct ImplementationEntry
{
/** Function that creates an instance of the implementation
*/
ComponentFactoryFunc create;
/** Function that returns the implementation-name of the implementation
(same as XServiceInfo.getImplementationName() ).
*/
rtl::OUString SAL_CALL ( * getImplementationName )();
/** Function that returns all supported servicenames of the implementation
( same as XServiceInfo.getSupportedServiceNames() ).
*/
com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL ( * getSupportedServiceNames ) ();
/** Function that creates a SingleComponentFactory.
*/
::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleComponentFactory > SAL_CALL
( * createFactory )(
ComponentFactoryFunc fptr,
::rtl::OUString const & rImplementationName,
::com::sun::star::uno::Sequence< ::rtl::OUString > const & rServiceNames,
rtl_ModuleCount * pModCount );
/** The shared-library module-counter of the implementation. Maybe 0. The module-counter
is used during by the createFactory()-function.
*/
rtl_ModuleCount * moduleCounter;
/** Must be set to 0 !
For future extensions.
*/
sal_Int32 nFlags;
};
/** Helper function for implementation of the component_writeInfo()-function.
@deprecated component_writeInfo should no longer be used in new components
@param pServiceManager The first parameter passed to component_writeInfo()-function
(This is an instance of the service manager, that creates the factory).
@param pRegistryKey The second parameter passed to the component_writeInfo()-function.
This is a reference to the registry key, into which the implementation
data shall be written to.
@param entries Each element of the entries-array must contains a function pointer
table for registering an implementation. The end of the array
must be marked with a 0 entry in the create-function.
@return sal_True, if all implementations could be registered, otherwise sal_False.
*/
CPPUHELPER_DLLPUBLIC sal_Bool component_writeInfoHelper(
void *pServiceManager, void *pRegistryKey , const struct ImplementationEntry entries[] );
/** Helper function for implementation of the component_getFactory()-function,
that must be implemented by every shared library component.
@param pImplName The implementation-name to be instantiated ( This is the
first parameter passed to the component_getFactory
@param pServiceManager The second parameter passed to component_getFactory()-function
(This is a of the service manager, that creates the factory).
@param pRegistryKey The third parameter passed to the component_getFactory()-function.
This is a reference to the registry key, where the implementation
data has been written to.
@param entries Each element of the entries-array must contains a function pointer
table for creating a factor of the implementation. The end of the array
must be marked with a 0 entry in the create-function.
@return 0 if the helper failed to instantiate a factory, otherwise an acquired pointer
to a factory.
*/
CPPUHELPER_DLLPUBLIC void *component_getFactoryHelper(
const sal_Char * pImplName,
void * pServiceManager,
void * pRegistryKey,
const struct ImplementationEntry entries[] );
}
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _CPPUHELPER_IMPLEMENTATIONENTRY_HXX_
#define _CPPUHELPER_IMPLEMENTATIONENTRY_HXX_
#include <cppuhelper/factory.hxx>
#include "cppuhelperdllapi.h"
// MinGW wants it the one way around while MSVC wants it the other (and
// everywhere else, SAL_CALL is empty, so doesn't matter):
#if defined __GNUC__
#define MY_FN_PTR(name) SAL_CALL (* name)
#else
#define MY_FN_PTR(name) (SAL_CALL * name)
#endif
namespace cppu
{
/** One struct instance represents all data necessary for registering one service implementation.
*/
struct ImplementationEntry
{
/** Function that creates an instance of the implementation
*/
ComponentFactoryFunc create;
/** Function that returns the implementation-name of the implementation
(same as XServiceInfo.getImplementationName() ).
*/
rtl::OUString MY_FN_PTR( getImplementationName )();
/** Function that returns all supported servicenames of the implementation
( same as XServiceInfo.getSupportedServiceNames() ).
*/
com::sun::star::uno::Sequence< rtl::OUString > MY_FN_PTR( getSupportedServiceNames ) ();
/** Function that creates a SingleComponentFactory.
*/
::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleComponentFactory >
MY_FN_PTR( createFactory )(
ComponentFactoryFunc fptr,
::rtl::OUString const & rImplementationName,
::com::sun::star::uno::Sequence< ::rtl::OUString > const & rServiceNames,
rtl_ModuleCount * pModCount );
/** The shared-library module-counter of the implementation. Maybe 0. The module-counter
is used during by the createFactory()-function.
*/
rtl_ModuleCount * moduleCounter;
/** Must be set to 0 !
For future extensions.
*/
sal_Int32 nFlags;
};
/** Helper function for implementation of the component_writeInfo()-function.
@deprecated component_writeInfo should no longer be used in new components
@param pServiceManager The first parameter passed to component_writeInfo()-function
(This is an instance of the service manager, that creates the factory).
@param pRegistryKey The second parameter passed to the component_writeInfo()-function.
This is a reference to the registry key, into which the implementation
data shall be written to.
@param entries Each element of the entries-array must contains a function pointer
table for registering an implementation. The end of the array
must be marked with a 0 entry in the create-function.
@return sal_True, if all implementations could be registered, otherwise sal_False.
*/
CPPUHELPER_DLLPUBLIC sal_Bool component_writeInfoHelper(
void *pServiceManager, void *pRegistryKey , const struct ImplementationEntry entries[] );
/** Helper function for implementation of the component_getFactory()-function,
that must be implemented by every shared library component.
@param pImplName The implementation-name to be instantiated ( This is the
first parameter passed to the component_getFactory
@param pServiceManager The second parameter passed to component_getFactory()-function
(This is a of the service manager, that creates the factory).
@param pRegistryKey The third parameter passed to the component_getFactory()-function.
This is a reference to the registry key, where the implementation
data has been written to.
@param entries Each element of the entries-array must contains a function pointer
table for creating a factor of the implementation. The end of the array
must be marked with a 0 entry in the create-function.
@return 0 if the helper failed to instantiate a factory, otherwise an acquired pointer
to a factory.
*/
CPPUHELPER_DLLPUBLIC void *component_getFactoryHelper(
const sal_Char * pImplName,
void * pServiceManager,
void * pRegistryKey,
const struct ImplementationEntry entries[] );
}
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
Make SAL_CALL placement work with both MinGW and MSVC
|
Make SAL_CALL placement work with both MinGW and MSVC
|
C++
|
mpl-2.0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
c39e20a0c27da3733804c3848454b5d4c4f0e66b
|
src/libmv/autotrack/autotrack.cc
|
src/libmv/autotrack/autotrack.cc
|
// Copyright (c) 2014 libmv authors.
//
// 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.
//
// Author: [email protected] (Keir Mierle)
#include "libmv/autotrack/autotrack.h"
#include "libmv/autotrack/quad.h"
#include "libmv/autotrack/frame_accessor.h"
#include "libmv/logging/logging.h"
#include "libmv/numeric/numeric.h"
namespace mv {
namespace {
template<typename QuadT, typename ArrayT>
void QuadToArrays(const QuadT& quad, ArrayT* x, ArrayT* y) {
for (int i = 0; i < 4; ++i) {
x[i] = quad.coordinates(i, 0);
y[i] = quad.coordinates(i, 1);
}
}
void MarkerToArrays(const Marker& marker,
Vec2i* origin,
double* x, double* y) {
*origin = marker.center.cast<int>() + marker.search_region.min;
Quad2Df offset_quad = marker.patch;
for (int i = 0; i < 4; ++i) {
offset_quad.coordinates.row(i) -= origin->cast<float>();
}
QuadToArrays(offset_quad, x, y);
x[4] = marker.center.x() - (*origin)(0);
y[4] = marker.center.y() - (*origin)(1);
}
FrameAccessor::Key GetImageForMarker(const Marker& marker,
FrameAccessor* frame_accessor,
FloatImage* image) {
// The input region has the coordinate centered around the marker center
// (e.g. a typical window would have (-20, -20, 20, 20) as the coordinates);
// so shift the region so it is centered on the marker in the frame's
// coordinate system.
// TODO(keir): Perhaps this should be a marker helper?
Region region_in_frame = marker.search_region;
region_in_frame.Offset(marker.center);
return frame_accessor->GetImage(marker.clip,
marker.frame,
FrameAccessor::MONO,
0, // No downscale for now.
®ion_in_frame,
NULL,
image);
}
} // namespace
bool AutoTrack::TrackMarkerToFrame(const Marker& reference_marker,
const TrackRegionOptions& track_options,
Marker* tracked_marker,
TrackRegionResult* result) {
// Convert markers into the format expected by TrackRegion.
double x1[5], y1[5];
Vec2i reference_origin;
MarkerToArrays(reference_marker, &reference_origin, x1, y1);
double x2[5], y2[5];
Vec2i tracked_origin;
MarkerToArrays(*tracked_marker, &tracked_origin, x2, y2);
// TODO(keir): Technically this could take a smaller slice from the source
// image instead of taking one the size of the search window.
FloatImage reference_image;
FrameAccessor::Key reference_key = GetImageForMarker(reference_marker,
frame_accessor_,
&reference_image);
if (!reference_key) {
LG << "Couldn't get frame for reference marker: " << reference_marker;
return false;
}
FloatImage tracked_image;
FrameAccessor::Key tracked_key = GetImageForMarker(*tracked_marker,
frame_accessor_,
&tracked_image);
if (!tracked_key) {
LG << "Couldn't get frame for tracked marker: " << tracked_marker;
return false;
}
// Do the tracking!
TrackRegionOptions local_track_region_options = track_options;
local_track_region_options.num_extra_points = 1; // For extra center point.
TrackRegion(reference_image,
tracked_image,
x1, y1,
local_track_region_options,
x2, y2,
result);
// Copy results over the tracked marker.
for (int i = 0; i < 4; ++i) {
tracked_marker->patch.coordinates(i, 0) = x2[i] + tracked_origin[0];
tracked_marker->patch.coordinates(i, 1) = y2[i] + tracked_origin[1];
}
tracked_marker->center(0) = x2[4] + tracked_origin[0];
tracked_marker->center(1) = y2[4] + tracked_origin[1];
tracked_marker->source = Marker::TRACKED;
tracked_marker->status = Marker::UNKNOWN;
tracked_marker->reference_clip = reference_marker.clip;
tracked_marker->reference_frame = reference_marker.frame;
// Release the images from the accessor cache.
frame_accessor_->ReleaseImage(reference_key);
frame_accessor_->ReleaseImage(tracked_key);
// TODO(keir): Possibly the return here should get removed since the results
// are part of TrackResult. However, eventually the autotrack stuff will have
// extra status (e.g. prediction fail, etc) that should get included.
return true;
}
void AutoTrack::AddMarker(const Marker& marker) {
tracks_.AddMarker(marker);
}
void AutoTrack::SetMarkers(vector<Marker>* markers) {
tracks_.SetMarkers(markers);
}
void AutoTrack::GetMarker(int clip, int frame, int track, Marker* markers) {
tracks_.GetMarker(clip, frame, track, markers);
}
} // namespace mv
|
// Copyright (c) 2014 libmv authors.
//
// 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.
//
// Author: [email protected] (Keir Mierle)
#include "libmv/autotrack/autotrack.h"
#include "libmv/autotrack/quad.h"
#include "libmv/autotrack/frame_accessor.h"
#include "libmv/logging/logging.h"
#include "libmv/numeric/numeric.h"
namespace mv {
namespace {
template<typename QuadT, typename ArrayT>
void QuadToArrays(const QuadT& quad, ArrayT* x, ArrayT* y) {
for (int i = 0; i < 4; ++i) {
x[i] = quad.coordinates(i, 0);
y[i] = quad.coordinates(i, 1);
}
}
void MarkerToArrays(const Marker& marker,
Vec2i* origin,
double* x, double* y) {
*origin = marker.center.cast<int>() + marker.search_region.min;
Quad2Df offset_quad = marker.patch;
for (int i = 0; i < 4; ++i) {
offset_quad.coordinates.row(i) -= origin->cast<float>();
}
QuadToArrays(offset_quad, x, y);
x[4] = marker.center.x() - (*origin)(0);
y[4] = marker.center.y() - (*origin)(1);
}
FrameAccessor::Key GetImageForMarker(const Marker& marker,
FrameAccessor* frame_accessor,
FloatImage* image) {
// The input region has the coordinate centered around the marker center
// (e.g. a typical window would have (-20, -20, 20, 20) as the coordinates);
// so shift the region so it is centered on the marker in the frame's
// coordinate system.
// TODO(keir): Perhaps this should be a marker helper?
Region region_in_frame = marker.search_region;
region_in_frame.Offset(marker.center);
return frame_accessor->GetImage(marker.clip,
marker.frame,
FrameAccessor::MONO,
0, // No downscale for now.
®ion_in_frame,
NULL,
image);
}
} // namespace
bool AutoTrack::TrackMarkerToFrame(const Marker& reference_marker,
const TrackRegionOptions& track_options,
Marker* tracked_marker,
TrackRegionResult* result) {
// Convert markers into the format expected by TrackRegion.
double x1[5], y1[5];
Vec2i reference_origin;
MarkerToArrays(reference_marker, &reference_origin, x1, y1);
double x2[5], y2[5];
Vec2i tracked_origin;
MarkerToArrays(*tracked_marker, &tracked_origin, x2, y2);
// TODO(keir): Technically this could take a smaller slice from the source
// image instead of taking one the size of the search window.
FloatImage reference_image;
FrameAccessor::Key reference_key = GetImageForMarker(reference_marker,
frame_accessor_,
&reference_image);
if (!reference_key) {
LG << "Couldn't get frame for reference marker: " << reference_marker;
return false;
}
FloatImage tracked_image;
FrameAccessor::Key tracked_key = GetImageForMarker(*tracked_marker,
frame_accessor_,
&tracked_image);
if (!tracked_key) {
LG << "Couldn't get frame for tracked marker: " << tracked_marker;
return false;
}
// Do the tracking!
TrackRegionOptions local_track_region_options = track_options;
local_track_region_options.num_extra_points = 1; // For center point.
TrackRegion(reference_image,
tracked_image,
x1, y1,
local_track_region_options,
x2, y2,
result);
// Copy results over the tracked marker.
for (int i = 0; i < 4; ++i) {
tracked_marker->patch.coordinates(i, 0) = x2[i] + tracked_origin[0];
tracked_marker->patch.coordinates(i, 1) = y2[i] + tracked_origin[1];
}
tracked_marker->center(0) = x2[4] + tracked_origin[0];
tracked_marker->center(1) = y2[4] + tracked_origin[1];
tracked_marker->source = Marker::TRACKED;
tracked_marker->status = Marker::UNKNOWN;
tracked_marker->reference_clip = reference_marker.clip;
tracked_marker->reference_frame = reference_marker.frame;
// Release the images from the accessor cache.
frame_accessor_->ReleaseImage(reference_key);
frame_accessor_->ReleaseImage(tracked_key);
// TODO(keir): Possibly the return here should get removed since the results
// are part of TrackResult. However, eventually the autotrack stuff will have
// extra status (e.g. prediction fail, etc) that should get included.
return true;
}
void AutoTrack::AddMarker(const Marker& marker) {
tracks_.AddMarker(marker);
}
void AutoTrack::SetMarkers(vector<Marker>* markers) {
tracks_.SetMarkers(markers);
}
bool AutoTrack::GetMarker(int clip, int frame, int track,
Marker* markers) const {
return tracks_.GetMarker(clip, frame, track, markers);
}
} // namespace mv
|
Fix GetMarker compilation issue
|
Fix GetMarker compilation issue
|
C++
|
mit
|
rgkoo/libmv-blender,SoylentGraham/libmv,SoylentGraham/libmv,rgkoo/libmv-blender,rgkoo/libmv-blender,petertsoi/libmv,petertsoi/libmv,rgkoo/libmv-blender,rgkoo/libmv-blender,SoylentGraham/libmv,SoylentGraham/libmv,petertsoi/libmv,petertsoi/libmv
|
3739919dd1fae5df81df60f5fa3609c7c42c7c9a
|
src/librawspeed/tiff/CiffIFD.cpp
|
src/librawspeed/tiff/CiffIFD.cpp
|
/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
Copyright (C) 2014 Pedro Côrte-Real
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "tiff/CiffIFD.h"
#include "common/Common.h" // for uint32, ushort16
#include "io/Buffer.h" // for Buffer
#include "io/Endianness.h" // for getU16LE, getU32LE
#include "io/IOException.h" // for IOException
#include "parsers/CiffParserException.h" // for ThrowCPE, CiffParserException
#include "tiff/CiffEntry.h" // for CiffEntry, CiffDataType::CI...
#include <map> // for map, _Rb_tree_iterator
#include <memory> // for unique_ptr
#include <string> // for allocator, operator==, string
#include <utility> // for pair
#include <vector> // for vector
using namespace std;
namespace RawSpeed {
#define CIFF_DEPTH(_depth) \
if ((depth = (_depth) + 1) > 10) \
ThrowCPE("sub-micron matryoshka dolls are ignored");
CiffIFD::CiffIFD(Buffer* f, uint32 start, uint32 end, uint32 _depth) {
CIFF_DEPTH(_depth);
mFile = f;
uint32 valuedata_size = getU32LE(f->getData(end-4, 4));
ushort16 dircount = getU16LE(f->getData(start+valuedata_size, 2));
// fprintf(stderr, "Found %d entries between %d and %d after %d data bytes\n",
// dircount, start, end, valuedata_size);
for (uint32 i = 0; i < dircount; i++) {
int entry_offset = start+valuedata_size+2+i*10;
// If the space for the entry is no longer valid stop reading any more as
// the file is broken or truncated
if (!mFile->isValid(entry_offset, 10))
break;
unique_ptr<CiffEntry> t(nullptr);
try {
t = make_unique<CiffEntry>(f, start, entry_offset);
} catch (IOException &) { // Ignore unparsable entry
continue;
}
if (t->type == CIFF_SUB1 || t->type == CIFF_SUB2) {
try {
mSubIFD.push_back(make_unique<CiffIFD>(
f, t->data_offset, t->data_offset + t->bytesize, depth));
} catch (
CiffParserException &) { // Unparsable subifds are added as entries
mEntry[t->tag] = move(t);
} catch (IOException &) { // Unparsable private data are added as entries
mEntry[t->tag] = move(t);
}
} else {
mEntry[t->tag] = move(t);
}
}
}
bool __attribute__((pure)) CiffIFD::hasEntryRecursive(CiffTag tag) {
if (mEntry.find(tag) != mEntry.end())
return true;
for (auto &i : mSubIFD) {
if (i->hasEntryRecursive(tag))
return true;
}
return false;
}
vector<CiffIFD*> CiffIFD::getIFDsWithTag(CiffTag tag) {
vector<CiffIFD*> matchingIFDs;
if (mEntry.find(tag) != mEntry.end()) {
matchingIFDs.push_back(this);
}
for (auto &i : mSubIFD) {
vector<CiffIFD *> t = i->getIFDsWithTag(tag);
for (auto j : t) {
matchingIFDs.push_back(j);
}
}
return matchingIFDs;
}
vector<CiffIFD*> CiffIFD::getIFDsWithTagWhere(CiffTag tag, uint32 isValue) {
vector<CiffIFD*> matchingIFDs;
if (mEntry.find(tag) != mEntry.end()) {
CiffEntry* entry = mEntry[tag].get();
if (entry->isInt() && entry->getU32() == isValue)
matchingIFDs.push_back(this);
}
for (auto &i : mSubIFD) {
vector<CiffIFD *> t = i->getIFDsWithTag(tag);
for (auto j : t) {
matchingIFDs.push_back(j);
}
}
return matchingIFDs;
}
vector<CiffIFD *> CiffIFD::getIFDsWithTagWhere(CiffTag tag,
const string &isValue) {
vector<CiffIFD*> matchingIFDs;
if (mEntry.find(tag) != mEntry.end()) {
CiffEntry* entry = mEntry[tag].get();
if (entry->isString() && isValue == entry->getString())
matchingIFDs.push_back(this);
}
for (auto &i : mSubIFD) {
vector<CiffIFD *> t = i->getIFDsWithTag(tag);
for (auto j : t) {
matchingIFDs.push_back(j);
}
}
return matchingIFDs;
}
CiffEntry* CiffIFD::getEntryRecursive(CiffTag tag) {
if (mEntry.find(tag) != mEntry.end()) {
return mEntry[tag].get();
}
for (auto &i : mSubIFD) {
CiffEntry *entry = i->getEntryRecursive(tag);
if (entry)
return entry;
}
return nullptr;
}
CiffEntry* CiffIFD::getEntryRecursiveWhere(CiffTag tag, uint32 isValue) {
if (mEntry.find(tag) != mEntry.end()) {
CiffEntry* entry = mEntry[tag].get();
if (entry->isInt() && entry->getU32() == isValue)
return entry;
}
for (auto &i : mSubIFD) {
CiffEntry *entry = i->getEntryRecursive(tag);
if (entry)
return entry;
}
return nullptr;
}
CiffEntry *CiffIFD::getEntryRecursiveWhere(CiffTag tag, const string &isValue) {
if (mEntry.find(tag) != mEntry.end()) {
CiffEntry* entry = mEntry[tag].get();
if (entry->isString() && isValue == entry->getString())
return entry;
}
for (auto &i : mSubIFD) {
CiffEntry *entry = i->getEntryRecursive(tag);
if (entry)
return entry;
}
return nullptr;
}
CiffEntry* CiffIFD::getEntry(CiffTag tag) {
if (mEntry.find(tag) != mEntry.end()) {
return mEntry[tag].get();
}
ThrowCPE("Entry 0x%x not found.", tag);
return nullptr;
}
bool __attribute__((pure)) CiffIFD::hasEntry(CiffTag tag) {
return mEntry.find(tag) != mEntry.end();
}
} // namespace RawSpeed
|
/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
Copyright (C) 2014 Pedro Côrte-Real
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "tiff/CiffIFD.h"
#include "common/Common.h" // for uint32, ushort16
#include "io/Buffer.h" // for Buffer
#include "io/Endianness.h" // for getU16LE, getU32LE
#include "io/IOException.h" // for IOException
#include "parsers/CiffParserException.h" // for ThrowCPE, CiffParserException
#include "tiff/CiffEntry.h" // for CiffEntry, CiffDataType::CI...
#include <map> // for map, _Rb_tree_iterator
#include <memory> // for unique_ptr
#include <string> // for allocator, operator==, string
#include <utility> // for pair
#include <vector> // for vector
using namespace std;
namespace RawSpeed {
#define CIFF_DEPTH(_depth) \
if ((depth = (_depth) + 1) > 10) \
ThrowCPE("sub-micron matryoshka dolls are ignored");
CiffIFD::CiffIFD(Buffer* f, uint32 start, uint32 end, uint32 _depth) {
CIFF_DEPTH(_depth);
mFile = f;
if (end < 4)
ThrowCPE("File is probably corrupted.");
uint32 valuedata_size = getU32LE(f->getData(end-4, 4));
ushort16 dircount = getU16LE(f->getData(start+valuedata_size, 2));
// fprintf(stderr, "Found %d entries between %d and %d after %d data bytes\n",
// dircount, start, end, valuedata_size);
for (uint32 i = 0; i < dircount; i++) {
int entry_offset = start+valuedata_size+2+i*10;
// If the space for the entry is no longer valid stop reading any more as
// the file is broken or truncated
if (!mFile->isValid(entry_offset, 10))
break;
unique_ptr<CiffEntry> t(nullptr);
try {
t = make_unique<CiffEntry>(f, start, entry_offset);
} catch (IOException &) { // Ignore unparsable entry
continue;
}
if (t->type == CIFF_SUB1 || t->type == CIFF_SUB2) {
try {
mSubIFD.push_back(make_unique<CiffIFD>(
f, t->data_offset, t->data_offset + t->bytesize, depth));
} catch (
CiffParserException &) { // Unparsable subifds are added as entries
mEntry[t->tag] = move(t);
} catch (IOException &) { // Unparsable private data are added as entries
mEntry[t->tag] = move(t);
}
} else {
mEntry[t->tag] = move(t);
}
}
}
bool __attribute__((pure)) CiffIFD::hasEntryRecursive(CiffTag tag) {
if (mEntry.find(tag) != mEntry.end())
return true;
for (auto &i : mSubIFD) {
if (i->hasEntryRecursive(tag))
return true;
}
return false;
}
vector<CiffIFD*> CiffIFD::getIFDsWithTag(CiffTag tag) {
vector<CiffIFD*> matchingIFDs;
if (mEntry.find(tag) != mEntry.end()) {
matchingIFDs.push_back(this);
}
for (auto &i : mSubIFD) {
vector<CiffIFD *> t = i->getIFDsWithTag(tag);
for (auto j : t) {
matchingIFDs.push_back(j);
}
}
return matchingIFDs;
}
vector<CiffIFD*> CiffIFD::getIFDsWithTagWhere(CiffTag tag, uint32 isValue) {
vector<CiffIFD*> matchingIFDs;
if (mEntry.find(tag) != mEntry.end()) {
CiffEntry* entry = mEntry[tag].get();
if (entry->isInt() && entry->getU32() == isValue)
matchingIFDs.push_back(this);
}
for (auto &i : mSubIFD) {
vector<CiffIFD *> t = i->getIFDsWithTag(tag);
for (auto j : t) {
matchingIFDs.push_back(j);
}
}
return matchingIFDs;
}
vector<CiffIFD *> CiffIFD::getIFDsWithTagWhere(CiffTag tag,
const string &isValue) {
vector<CiffIFD*> matchingIFDs;
if (mEntry.find(tag) != mEntry.end()) {
CiffEntry* entry = mEntry[tag].get();
if (entry->isString() && isValue == entry->getString())
matchingIFDs.push_back(this);
}
for (auto &i : mSubIFD) {
vector<CiffIFD *> t = i->getIFDsWithTag(tag);
for (auto j : t) {
matchingIFDs.push_back(j);
}
}
return matchingIFDs;
}
CiffEntry* CiffIFD::getEntryRecursive(CiffTag tag) {
if (mEntry.find(tag) != mEntry.end()) {
return mEntry[tag].get();
}
for (auto &i : mSubIFD) {
CiffEntry *entry = i->getEntryRecursive(tag);
if (entry)
return entry;
}
return nullptr;
}
CiffEntry* CiffIFD::getEntryRecursiveWhere(CiffTag tag, uint32 isValue) {
if (mEntry.find(tag) != mEntry.end()) {
CiffEntry* entry = mEntry[tag].get();
if (entry->isInt() && entry->getU32() == isValue)
return entry;
}
for (auto &i : mSubIFD) {
CiffEntry *entry = i->getEntryRecursive(tag);
if (entry)
return entry;
}
return nullptr;
}
CiffEntry *CiffIFD::getEntryRecursiveWhere(CiffTag tag, const string &isValue) {
if (mEntry.find(tag) != mEntry.end()) {
CiffEntry* entry = mEntry[tag].get();
if (entry->isString() && isValue == entry->getString())
return entry;
}
for (auto &i : mSubIFD) {
CiffEntry *entry = i->getEntryRecursive(tag);
if (entry)
return entry;
}
return nullptr;
}
CiffEntry* CiffIFD::getEntry(CiffTag tag) {
if (mEntry.find(tag) != mEntry.end()) {
return mEntry[tag].get();
}
ThrowCPE("Entry 0x%x not found.", tag);
return nullptr;
}
bool __attribute__((pure)) CiffIFD::hasEntry(CiffTag tag) {
return mEntry.find(tag) != mEntry.end();
}
} // namespace RawSpeed
|
check that end is >= 4
|
CiffIFD::CiffIFD(): check that end is >= 4
|
C++
|
lgpl-2.1
|
darktable-org/rawspeed,LebedevRI/rawspeed,darktable-org/rawspeed,darktable-org/rawspeed,LebedevRI/rawspeed,darktable-org/rawspeed,LebedevRI/rawspeed,LebedevRI/rawspeed,darktable-org/rawspeed,LebedevRI/rawspeed
|
74f666c725f6ff767cac91a18d81c31d2297c016
|
exotations/task_maps/task_map/src/SmoothCollisionDistance.cpp
|
exotations/task_maps/task_map/src/SmoothCollisionDistance.cpp
|
/*
* Author: Wolfgang Merkt
*
* Copyright (c) 2017, Wolfgang Merkt
* 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 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 "task_map/SmoothCollisionDistance.h"
REGISTER_TASKMAP_TYPE("SmoothCollisionDistance",
exotica::SmoothCollisionDistance);
namespace exotica
{
SmoothCollisionDistance::SmoothCollisionDistance() {}
void SmoothCollisionDistance::update(Eigen::VectorXdRefConst x,
Eigen::VectorXdRef phi)
{
if (phi.rows() != dim_) throw_named("Wrong size of phi!");
phi.setZero();
Eigen::MatrixXd J;
update(x, phi, J, false);
}
void SmoothCollisionDistance::update(Eigen::VectorXdRefConst x,
Eigen::VectorXdRef phi,
Eigen::MatrixXdRef J)
{
if (phi.rows() != dim_) throw_named("Wrong size of phi!");
if (!scene_->alwaysUpdatesCollisionScene())
cscene_->updateCollisionObjectTransforms();
phi.setZero();
J.setZero();
update(x, phi, J, true);
}
void SmoothCollisionDistance::update(Eigen::VectorXdRefConst x,
Eigen::VectorXdRef phi,
Eigen::MatrixXdRef J,
bool updateJacobian)
{
double& d = phi(0);
for (const auto& link : robotLinks_)
{
// Get all world collision links, then iterate through them
// std::vector<CollisionProxy> proxies = cscene_->getCollisionDistance(scene_->getControlledLinkToCollisionLinkMap()[link], check_self_collision_);
std::vector<CollisionProxy> proxies = cscene_->getCollisionDistance(link, check_self_collision_);
for (const auto& proxy : proxies)
{
bool isRobotToRobot = (proxy.e1->isRobotLink || proxy.e1->ClosestRobotLink.lock()) && (proxy.e2->isRobotLink || proxy.e2->ClosestRobotLink.lock());
double& margin = isRobotToRobot ? robot_margin_ : world_margin_;
if (proxy.distance < margin)
{
// Cost
d += std::pow((1. - proxy.distance / margin), linear_ ? 1 : 2);
if (updateJacobian)
{
// Jacobian
KDL::Frame arel = KDL::Frame(proxy.e1->Frame.Inverse(KDL::Vector(
proxy.contact1(0), proxy.contact1(1), proxy.contact1(2))));
KDL::Frame brel = KDL::Frame(proxy.e2->Frame.Inverse(KDL::Vector(
proxy.contact2(0), proxy.contact2(1), proxy.contact2(2))));
if (!linear_)
{
Eigen::MatrixXd tmpJ = scene_->getSolver().Jacobian(
proxy.e1, arel, nullptr, KDL::Frame());
J += (2. / (margin * margin)) * (proxy.normal1.transpose() * tmpJ);
tmpJ = scene_->getSolver().Jacobian(proxy.e2, brel, nullptr,
KDL::Frame());
J -= (2. / (margin * margin)) * (proxy.normal1.transpose() * tmpJ);
}
else
{
Eigen::MatrixXd tmpJ = scene_->getSolver().Jacobian(
proxy.e1, arel, nullptr, KDL::Frame());
J += 1 / margin * (proxy.normal1.transpose() * tmpJ);
tmpJ = scene_->getSolver().Jacobian(proxy.e2, brel, nullptr,
KDL::Frame());
J -= 1 / margin * (proxy.normal1.transpose() * tmpJ);
}
}
}
}
}
}
void SmoothCollisionDistance::Instantiate(
SmoothCollisionDistanceInitializer& init)
{
init_ = init;
}
void SmoothCollisionDistance::assignScene(Scene_ptr scene)
{
scene_ = scene;
Initialize();
}
void SmoothCollisionDistance::Initialize()
{
cscene_ = scene_->getCollisionScene();
world_margin_ = init_.WorldMargin;
robot_margin_ = init_.RobotMargin;
linear_ = init_.Linear;
check_self_collision_ = init_.CheckSelfCollision;
HIGHLIGHT_NAMED("Smooth Collision Distance",
"World Margin: " << world_margin_ << " Robot Margin: " << robot_margin_ << "\t Linear: " << linear_);
// Get names of all controlled joints and their corresponding child links
robotLinks_ = scene_->getControlledLinkNames();
}
int SmoothCollisionDistance::taskSpaceDim() { return dim_; }
}
|
/*
* Author: Wolfgang Merkt
*
* Copyright (c) 2017, Wolfgang Merkt
* 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 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 "task_map/SmoothCollisionDistance.h"
REGISTER_TASKMAP_TYPE("SmoothCollisionDistance",
exotica::SmoothCollisionDistance);
namespace exotica
{
SmoothCollisionDistance::SmoothCollisionDistance() {}
void SmoothCollisionDistance::update(Eigen::VectorXdRefConst x,
Eigen::VectorXdRef phi)
{
if (phi.rows() != dim_) throw_named("Wrong size of phi!");
phi.setZero();
Eigen::MatrixXd J;
update(x, phi, J, false);
}
void SmoothCollisionDistance::update(Eigen::VectorXdRefConst x,
Eigen::VectorXdRef phi,
Eigen::MatrixXdRef J)
{
if (phi.rows() != dim_) throw_named("Wrong size of phi!");
if (!scene_->alwaysUpdatesCollisionScene())
cscene_->updateCollisionObjectTransforms();
phi.setZero();
J.setZero();
update(x, phi, J, true);
}
void SmoothCollisionDistance::update(Eigen::VectorXdRefConst x,
Eigen::VectorXdRef phi,
Eigen::MatrixXdRef J,
bool updateJacobian)
{
// Get all world collision links, then iterate through them
std::vector<CollisionProxy> proxies = cscene_->getCollisionDistance(robotLinks_, check_self_collision_);
double& d = phi(0);
for (const auto& link : robotLinks_)
{
// Get all world collision links, then iterate through them
// std::vector<CollisionProxy> proxies = cscene_->getCollisionDistance(scene_->getControlledLinkToCollisionLinkMap()[link], check_self_collision_);
std::vector<CollisionProxy> proxies = cscene_->getCollisionDistance(link, check_self_collision_);
for (const auto& proxy : proxies)
{
bool isRobotToRobot = (proxy.e1->isRobotLink || proxy.e1->ClosestRobotLink.lock()) && (proxy.e2->isRobotLink || proxy.e2->ClosestRobotLink.lock());
double& margin = isRobotToRobot ? robot_margin_ : world_margin_;
if (proxy.distance < margin)
{
// Cost
d += std::pow((1. - proxy.distance / margin), linear_ ? 1 : 2);
if (updateJacobian)
{
// Jacobian
KDL::Frame arel = KDL::Frame(proxy.e1->Frame.Inverse(KDL::Vector(
proxy.contact1(0), proxy.contact1(1), proxy.contact1(2))));
KDL::Frame brel = KDL::Frame(proxy.e2->Frame.Inverse(KDL::Vector(
proxy.contact2(0), proxy.contact2(1), proxy.contact2(2))));
if (!linear_)
{
Eigen::MatrixXd tmpJ = scene_->getSolver().Jacobian(
proxy.e1, arel, nullptr, KDL::Frame());
J += (2. / (margin * margin)) * (proxy.normal1.transpose() * tmpJ);
tmpJ = scene_->getSolver().Jacobian(proxy.e2, brel, nullptr,
KDL::Frame());
J -= (2. / (margin * margin)) * (proxy.normal1.transpose() * tmpJ);
}
else
{
Eigen::MatrixXd tmpJ = scene_->getSolver().Jacobian(
proxy.e1, arel, nullptr, KDL::Frame());
J += 1 / margin * (proxy.normal1.transpose() * tmpJ);
tmpJ = scene_->getSolver().Jacobian(proxy.e2, brel, nullptr,
KDL::Frame());
J -= 1 / margin * (proxy.normal1.transpose() * tmpJ);
}
}
}
}
}
}
void SmoothCollisionDistance::Instantiate(
SmoothCollisionDistanceInitializer& init)
{
init_ = init;
}
void SmoothCollisionDistance::assignScene(Scene_ptr scene)
{
scene_ = scene;
Initialize();
}
void SmoothCollisionDistance::Initialize()
{
cscene_ = scene_->getCollisionScene();
world_margin_ = init_.WorldMargin;
robot_margin_ = init_.RobotMargin;
linear_ = init_.Linear;
check_self_collision_ = init_.CheckSelfCollision;
HIGHLIGHT_NAMED("Smooth Collision Distance",
"World Margin: " << world_margin_ << " Robot Margin: " << robot_margin_ << "\t Linear: " << linear_);
// Get names of all controlled joints and their corresponding child links
robotLinks_ = scene_->getControlledLinkNames();
}
int SmoothCollisionDistance::taskSpaceDim() { return dim_; }
}
|
Use mapping considering unactuated links.
|
SmoothCollisionDistance: Use mapping considering unactuated links.
|
C++
|
bsd-3-clause
|
openhumanoids/exotica,openhumanoids/exotica,openhumanoids/exotica,openhumanoids/exotica
|
95aa5809c5aec0d6e4644e8ebdb47c5fb0891b71
|
src/ast/DebugVisitor.cpp
|
src/ast/DebugVisitor.cpp
|
//=======================================================================
// 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 <iostream>
#include "ast/DebugVisitor.hpp"
#include "ast/SourceFile.hpp"
#include "VisitorUtils.hpp"
#include "Variable.hpp"
using namespace eddic;
ast::DebugVisitor::DebugVisitor() : level(0) {}
std::string ast::DebugVisitor::indent() const {
std::string acc = "";
for(int i = 0; i < level; ++i){
acc += "\t";
}
return acc;
}
void ast::DebugVisitor::operator()(ast::SourceFile& program) const {
std::cout << indent() << "SourceFile" << std::endl;
++level;
visit_each(*this, program.Content->blocks);
}
void ast::DebugVisitor::operator()(ast::Import& import) const {
std::cout << indent() << "include \"" << import.file << "\"" << std::endl;
}
void ast::DebugVisitor::operator()(ast::StandardImport& import) const {
std::cout << indent() << "include <" << import.header << ">" << std::endl;
}
template<typename Visitor, typename Container>
void print_each_sub(Visitor& visitor, Container& container){
visitor.level++;
visit_each(visitor, container);
visitor.level--;
}
template<typename Visitor, typename Container>
void print_sub(Visitor& visitor, Container& container){
visitor.level++;
visit(visitor, container);
visitor.level--;
}
void ast::DebugVisitor::operator()(ast::FunctionDeclaration& declaration) const {
std::cout << indent() << "Function " << declaration.Content->functionName << std::endl;
print_each_sub(*this, declaration.Content->instructions);
}
void ast::DebugVisitor::operator()(ast::GlobalVariableDeclaration&) const {
std::cout << indent() << "Global Variable" << std::endl;
}
void ast::DebugVisitor::operator()(ast::GlobalArrayDeclaration&) const {
std::cout << indent() << "Global Array" << std::endl;
}
void ast::DebugVisitor::operator()(ast::For& for_) const {
std::cout << indent() << "For" << std::endl;
print_each_sub(*this, for_.Content->instructions);
}
void ast::DebugVisitor::operator()(ast::Foreach& for_) const {
std::cout << indent() << "Foreach" << std::endl;
print_each_sub(*this, for_.Content->instructions);
}
void ast::DebugVisitor::operator()(ast::ForeachIn& for_) const {
std::cout << indent() << "Foreach in " << std::endl;
print_each_sub(*this, for_.Content->instructions);
}
void ast::DebugVisitor::operator()(ast::While& while_) const {
std::cout << indent() << "While" << std::endl;
std::cout << indent() << "Condition:" << std::endl;
print_sub(*this, while_.Content->condition);
print_each_sub(*this, while_.Content->instructions);
}
void ast::DebugVisitor::operator()(ast::DoWhile& while_) const {
std::cout << indent() << "Do while" << std::endl;
std::cout << indent() << "Condition:" << std::endl;
print_sub(*this, while_.Content->condition);
print_each_sub(*this, while_.Content->instructions);
}
void ast::DebugVisitor::operator()(ast::Swap&) const {
std::cout << indent() << "Swap" << std::endl;
}
void ast::DebugVisitor::operator()(ast::If& if_) const {
std::cout << indent() << "If" << std::endl;
std::cout << indent() << "Condition:" << std::endl;
print_sub(*this, if_.Content->condition);
std::cout << indent() << "Body:" << std::endl;
print_each_sub(*this, if_.Content->instructions);
}
void ast::DebugVisitor::operator()(ast::FunctionCall& call) const {
std::cout << indent() << "FunctionCall " << call.Content->functionName << std::endl;
print_each_sub(*this, call.Content->values);
}
void ast::DebugVisitor::operator()(ast::BuiltinOperator& builtin) const {
std::cout << indent() << "Builtin Operator " << (int) builtin.Content->type << std::endl;
print_each_sub(*this, builtin.Content->values);
}
void ast::DebugVisitor::operator()(ast::VariableDeclaration& declaration) const {
std::cout << indent() << "Variable declaration" << std::endl;
if(declaration.Content->value){
print_sub(*this, *declaration.Content->value);
}
}
void ast::DebugVisitor::operator()(ast::ArrayDeclaration&) const {
std::cout << indent() << "Array declaration" << std::endl;
}
void ast::DebugVisitor::operator()(ast::SuffixOperation& op) const {
std::cout << indent() << op.Content->variableName << "(suffix)" << (int)op.Content->op << std::endl;
}
void ast::DebugVisitor::operator()(ast::PrefixOperation& op) const {
std::cout << indent() << (int)op.Content->op << "(prefix)" << op.Content->variableName << std::endl;
}
void ast::DebugVisitor::operator()(ast::Assignment& assign) const {
std::cout << indent() << "Variable assignment" << std::endl;
print_sub(*this, assign.Content->value);
}
void ast::DebugVisitor::operator()(ast::CompoundAssignment& assign) const {
std::cout << indent() << "Compound variable assignment [operator = " << (int) assign.Content->op << " ]" << std::endl;
print_sub(*this, assign.Content->value);
}
void ast::DebugVisitor::operator()(ast::Return& return_) const {
std::cout << indent() << "Function return" << std::endl;
print_sub(*this, return_.Content->value);
}
void ast::DebugVisitor::operator()(ast::ArrayAssignment& assign) const {
std::cout << indent() << "Array assignment" << std::endl;
print_sub(*this, assign.Content->value);
}
void ast::DebugVisitor::operator()(ast::Litteral& litteral) const {
std::cout << indent() << "Litteral [" << litteral.value << "]" << std::endl;
}
void ast::DebugVisitor::operator()(ast::Integer& integer) const {
std::cout << indent() << "Integer [" << integer.value << "]" << std::endl;
}
void ast::DebugVisitor::operator()(ast::Float& float_) const {
std::cout << indent() << "Float [" << float_.value << "]" << std::endl;
}
void ast::DebugVisitor::operator()(ast::True&) const {
std::cout << indent() << "true" << std::endl;
}
void ast::DebugVisitor::operator()(ast::False&) const {
std::cout << indent() << "false" << std::endl;
}
void ast::DebugVisitor::operator()(ast::VariableValue& value) const {
std::cout << indent() << "Variable [" << value.Content->var->name() << "]" << std::endl;
}
void ast::DebugVisitor::operator()(ast::ArrayValue&) const {
std::cout << indent() << "Array value" << std::endl;
}
void ast::DebugVisitor::operator()(ast::Expression& value) const {
std::cout << indent() << "Composed value [" << value.Content->operations.size() << "]" << std::endl;
++level;
visit(*this, value.Content->first);
for(auto& operation : value.Content->operations){
std::cout << indent() << (int) operation.get<0>() << std::endl;
visit(*this, operation.get<1>());
}
--level;
}
void ast::DebugVisitor::operator()(ast::Minus& value) const {
std::cout << indent() << "Unary +" << std::endl;
print_sub(*this, value.Content->value);
}
void ast::DebugVisitor::operator()(ast::Plus& value) const {
std::cout << indent() << "Unary -" << std::endl;
print_sub(*this, value.Content->value);
}
|
//=======================================================================
// 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 <iostream>
#include "ast/DebugVisitor.hpp"
#include "ast/SourceFile.hpp"
#include "VisitorUtils.hpp"
#include "Variable.hpp"
using namespace eddic;
ast::DebugVisitor::DebugVisitor() : level(0) {}
std::string ast::DebugVisitor::indent() const {
std::string acc = "";
for(int i = 0; i < level; ++i){
acc += "\t";
}
return acc;
}
void ast::DebugVisitor::operator()(ast::SourceFile& program) const {
std::cout << indent() << "SourceFile" << std::endl;
++level;
visit_each(*this, program.Content->blocks);
}
void ast::DebugVisitor::operator()(ast::Import& import) const {
std::cout << indent() << "include \"" << import.file << "\"" << std::endl;
}
void ast::DebugVisitor::operator()(ast::StandardImport& import) const {
std::cout << indent() << "include <" << import.header << ">" << std::endl;
}
template<typename Visitor, typename Container>
void print_each_sub(Visitor& visitor, Container& container){
visitor.level++;
visit_each(visitor, container);
visitor.level--;
}
template<typename Visitor, typename Container>
void print_sub(Visitor& visitor, Container& container){
visitor.level++;
visit(visitor, container);
visitor.level--;
}
void ast::DebugVisitor::operator()(ast::FunctionDeclaration& declaration) const {
std::cout << indent() << "Function " << declaration.Content->functionName << std::endl;
print_each_sub(*this, declaration.Content->instructions);
}
void ast::DebugVisitor::operator()(ast::GlobalVariableDeclaration&) const {
std::cout << indent() << "Global Variable" << std::endl;
}
void ast::DebugVisitor::operator()(ast::GlobalArrayDeclaration&) const {
std::cout << indent() << "Global Array" << std::endl;
}
void ast::DebugVisitor::operator()(ast::For& for_) const {
std::cout << indent() << "For" << std::endl;
print_each_sub(*this, for_.Content->instructions);
}
void ast::DebugVisitor::operator()(ast::Foreach& for_) const {
std::cout << indent() << "Foreach" << std::endl;
print_each_sub(*this, for_.Content->instructions);
}
void ast::DebugVisitor::operator()(ast::ForeachIn& for_) const {
std::cout << indent() << "Foreach in " << std::endl;
print_each_sub(*this, for_.Content->instructions);
}
void ast::DebugVisitor::operator()(ast::While& while_) const {
std::cout << indent() << "While" << std::endl;
std::cout << indent() << "Condition:" << std::endl;
print_sub(*this, while_.Content->condition);
print_each_sub(*this, while_.Content->instructions);
}
void ast::DebugVisitor::operator()(ast::DoWhile& while_) const {
std::cout << indent() << "Do while" << std::endl;
std::cout << indent() << "Condition:" << std::endl;
print_sub(*this, while_.Content->condition);
print_each_sub(*this, while_.Content->instructions);
}
void ast::DebugVisitor::operator()(ast::Swap&) const {
std::cout << indent() << "Swap" << std::endl;
}
void ast::DebugVisitor::operator()(ast::If& if_) const {
std::cout << indent() << "If" << std::endl;
std::cout << indent() << "Condition:" << std::endl;
print_sub(*this, if_.Content->condition);
std::cout << indent() << "Body:" << std::endl;
print_each_sub(*this, if_.Content->instructions);
}
void ast::DebugVisitor::operator()(ast::FunctionCall& call) const {
std::cout << indent() << "FunctionCall " << call.Content->functionName << std::endl;
print_each_sub(*this, call.Content->values);
}
void ast::DebugVisitor::operator()(ast::BuiltinOperator& builtin) const {
std::cout << indent() << "Builtin Operator " << (int) builtin.Content->type << std::endl;
print_each_sub(*this, builtin.Content->values);
}
void ast::DebugVisitor::operator()(ast::VariableDeclaration& declaration) const {
std::cout << indent() << "Variable declaration" << std::endl;
if(declaration.Content->value){
print_sub(*this, *declaration.Content->value);
}
}
void ast::DebugVisitor::operator()(ast::ArrayDeclaration&) const {
std::cout << indent() << "Array declaration" << std::endl;
}
void ast::DebugVisitor::operator()(ast::SuffixOperation& op) const {
std::cout << indent() << op.Content->variableName << "(suffix)" << (int)op.Content->op << std::endl;
}
void ast::DebugVisitor::operator()(ast::PrefixOperation& op) const {
std::cout << indent() << (int)op.Content->op << "(prefix)" << op.Content->variableName << std::endl;
}
void ast::DebugVisitor::operator()(ast::Assignment& assign) const {
std::cout << indent() << "Variable assignment" << std::endl;
print_sub(*this, assign.Content->value);
}
void ast::DebugVisitor::operator()(ast::CompoundAssignment& assign) const {
std::cout << indent() << "Compound variable assignment [operator = " << (int) assign.Content->op << " ]" << std::endl;
print_sub(*this, assign.Content->value);
}
void ast::DebugVisitor::operator()(ast::Return& return_) const {
std::cout << indent() << "Function return" << std::endl;
print_sub(*this, return_.Content->value);
}
void ast::DebugVisitor::operator()(ast::ArrayAssignment& assign) const {
std::cout << indent() << "Array assignment" << std::endl;
print_sub(*this, assign.Content->value);
}
void ast::DebugVisitor::operator()(ast::Litteral& litteral) const {
std::cout << indent() << "Litteral [" << litteral.value << "]" << std::endl;
}
void ast::DebugVisitor::operator()(ast::Integer& integer) const {
std::cout << indent() << "Integer [" << integer.value << "]" << std::endl;
}
void ast::DebugVisitor::operator()(ast::Float& float_) const {
std::cout << indent() << "Float [" << float_.value << "]" << std::endl;
}
void ast::DebugVisitor::operator()(ast::True&) const {
std::cout << indent() << "true" << std::endl;
}
void ast::DebugVisitor::operator()(ast::False&) const {
std::cout << indent() << "false" << std::endl;
}
void ast::DebugVisitor::operator()(ast::VariableValue& value) const {
std::cout << indent() << "Variable [" << value.Content->var->name() << "]" << std::endl;
}
void ast::DebugVisitor::operator()(ast::ArrayValue&) const {
std::cout << indent() << "Array value" << std::endl;
}
void ast::DebugVisitor::operator()(ast::Expression& value) const {
std::cout << indent() << "Expression [" << value.Content->operations.size() << "]" << std::endl;
++level;
visit(*this, value.Content->first);
for(auto& operation : value.Content->operations){
std::cout << indent() << (int) operation.get<0>() << std::endl;
visit(*this, operation.get<1>());
}
--level;
}
void ast::DebugVisitor::operator()(ast::Minus& value) const {
std::cout << indent() << "Unary +" << std::endl;
print_sub(*this, value.Content->value);
}
void ast::DebugVisitor::operator()(ast::Plus& value) const {
std::cout << indent() << "Unary -" << std::endl;
print_sub(*this, value.Content->value);
}
|
Rename also in the debug message
|
Rename also in the debug message
|
C++
|
mit
|
wichtounet/eddic,vogelsgesang/eddic,wichtounet/eddic,vogelsgesang/eddic,vogelsgesang/eddic,wichtounet/eddic
|
8f310598b2cf7d89e70cc357a27137632c28d001
|
igvc/include/igvc/CVUtils.hpp
|
igvc/include/igvc/CVUtils.hpp
|
#ifndef CVUTILS_H
#define CVUTILS_H
pcl::PointXYZ PointFromPixel(const cv::Point& pixel, const tf::Transform& cameraFrameToWorldFrame, image_geometry::PinholeCameraModel cam) {
cv::Point3d cameraRay = cam.projectPixelTo3dRay(pixel);
tf::Point worldCameraOrigin = cameraFrameToWorldFrame * tf::Vector3(0, 0, 0);
tf::Point worldCameraStep = cameraFrameToWorldFrame * tf::Vector3(cameraRay.x, cameraRay.y, cameraRay.z) - worldCameraOrigin;
double zScale = -worldCameraOrigin.z()/worldCameraStep.z();
tf::Point ret = worldCameraOrigin + zScale * worldCameraStep;
return pcl::PointXYZ(ret.x(), ret.y(), 0);
}
pcl::PointXYZ PointFromPixelNoCam(const cv::Point& p, int height, int width, double HFOV, double VFOV, double origin_z, double origin_y, double pitch) {
int xP = p.x;
int yP = p.y + (height / 2 - 100);
double pitch_offset = ((float) (yP - height / 2) / height) * VFOV;
double y = origin_z /tan(pitch + pitch_offset) + origin_y;
double theta = ((float) (xP - width / 2) / width) * HFOV;
double x = y * tan(theta);
return pcl::PointXYZ(x, y, 0);
}
double toRadians(double degrees) {
return degrees / 180.0 * M_PI;
}
std::vector<std::vector<cv::Point>> MatToContours(const cv::Mat img) {
std::vector<std::vector<cv::Point>> contours;
for(int r = 0; r < img.rows; r++) {
std::vector<cv::Point> currentCont;
for(int c = 0; c < img.cols; c++) {
if(img.at<uchar>(r, c) > 0) {
currentCont.push_back(cv::Point(c, r));
}
}
contours.push_back(currentCont);
}
return contours;
}
pcl::PointCloud<pcl::PointXYZ>::Ptr toPointCloud(tf::TransformListener &tf_listener, std::vector<std::vector<cv::Point>> contours, image_geometry::PinholeCameraModel cam, std::string topic) {
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
tf::StampedTransform transform;
tf_listener.lookupTransform("/base_footprint", "/optical_cam_center", ros::Time(0), transform);
for (std::vector<cv::Point> contour : contours) {
for (cv::Point p : contour) {
cloud->points.push_back(PointFromPixel(p, transform, cam));
}
}
cloud->header.frame_id = "base_footprint";
return cloud;
}
pcl::PointCloud<pcl::PointXYZ>::Ptr toPointCloud(tf::TransformListener &tf_listener, std::vector<std::vector<cv::Point>> contours, int height, int width, std::string topic) {
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
tf::StampedTransform transform;
tf_listener.lookupTransform("/base_footprint", "/optical_cam_center", ros::Time(0), transform);
double roll, pitch, yaw;
tf::Matrix3x3(transform.getRotation()).getRPY(roll, pitch, yaw);
double origin_z = transform.getOrigin().getZ();
double origin_y = transform.getOrigin().getY();
double HFOV = toRadians(66.0);
double VFOV = toRadians(47.6);
pitch = -roll;
for (std::vector<cv::Point> contour : contours) {
for (cv::Point p : contour) {
cloud->points.push_back(PointFromPixelNoCam(p, height, width, HFOV, VFOV, origin_z, origin_y, pitch));
}
}
cloud->header.frame_id = "base_footprint";
return cloud;
}
#endif // CVUTILS_H
|
#ifndef CVUTILS_H
#define CVUTILS_H
pcl::PointXYZ PointFromPixel(const cv::Point& pixel, const tf::Transform& cameraFrameToWorldFrame, image_geometry::PinholeCameraModel cam) {
cv::Point3d cameraRay = cam.projectPixelTo3dRay(pixel);
tf::Point worldCameraOrigin = cameraFrameToWorldFrame * tf::Vector3(0, 0, 0);
tf::Point worldCameraStep = cameraFrameToWorldFrame * tf::Vector3(cameraRay.x, cameraRay.y, cameraRay.z) - worldCameraOrigin;
double zScale = -worldCameraOrigin.z()/worldCameraStep.z();
tf::Point ret = worldCameraOrigin + zScale * worldCameraStep;
return pcl::PointXYZ(ret.x(), ret.y(), 0);
}
pcl::PointXYZ PointFromPixelNoCam(const cv::Point& p, int height, int width, double HFOV, double VFOV, double origin_z, double origin_y, double pitch) {
int xP = p.x;
int yP = p.y + (height / 2 - 100);
double pitch_offset = ((float) (yP - height / 2) / height) * VFOV;
double y = origin_z /tan(pitch + pitch_offset) + origin_y;
double theta = ((float) (xP - width / 2) / width) * HFOV;
double x = y * tan(theta);
return pcl::PointXYZ(x, y, 0);
}
double toRadians(double degrees) {
return degrees / 180.0 * M_PI;
}
std::vector<std::vector<cv::Point>> MatToContours(const cv::Mat img) {
std::vector<std::vector<cv::Point>> contours;
for(int r = 0; r < img.rows; r++) {
std::vector<cv::Point> currentCont;
for(int c = 0; c < img.cols; c++) {
if(img.at<uchar>(r, c) > 0) {
currentCont.push_back(cv::Point(c, r));
}
}
contours.push_back(currentCont);
}
return contours;
}
bool replace(std::string& str, const std::string& from, const std::string& to) {
size_t start_pos = str.find(from);
if(start_pos == std::string::npos)
return false;
str.replace(start_pos, from.length(), to);
return true;
}
pcl::PointCloud<pcl::PointXYZ>::Ptr toPointCloud(tf::TransformListener &tf_listener, std::vector<std::vector<cv::Point>> contours, image_geometry::PinholeCameraModel cam, std::string topic) {
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
tf::StampedTransform transform;
std::string topicCopy = topic;
replace(topicCopy, "usb", "optical");
tf_listener.lookupTransform("/base_footprint", topicCopy, ros::Time(0), transform);
for (std::vector<cv::Point> contour : contours) {
for (cv::Point p : contour) {
cloud->points.push_back(PointFromPixel(p, transform, cam));
}
}
cloud->header.frame_id = "base_footprint";
return cloud;
}
pcl::PointCloud<pcl::PointXYZ>::Ptr toPointCloud(tf::TransformListener &tf_listener, std::vector<std::vector<cv::Point>> contours, int height, int width, std::string topic) {
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
tf::StampedTransform transform;
std::string topicCopy = topic;
replace(topicCopy, "usb", "optical");
tf_listener.lookupTransform("/base_footprint", topicCopy, ros::Time(0), transform);
double roll, pitch, yaw;
tf::Matrix3x3(transform.getRotation()).getRPY(roll, pitch, yaw);
double origin_z = transform.getOrigin().getZ();
double origin_y = transform.getOrigin().getY();
double HFOV = toRadians(66.0);
double VFOV = toRadians(47.6);
pitch = -roll;
for (std::vector<cv::Point> contour : contours) {
for (cv::Point p : contour) {
cloud->points.push_back(PointFromPixelNoCam(p, height, width, HFOV, VFOV, origin_z, origin_y, pitch));
}
}
cloud->header.frame_id = "base_footprint";
return cloud;
}
#endif // CVUTILS_H
|
Generalize optical_cam topics
|
Generalize optical_cam topics
|
C++
|
mit
|
RoboJackets/igvc-software,jzheng84/igvc-software,RoboJackets/igvc-software,rmkeezer/igvc-software,dpattison3/igvc-software,RoboJackets/igvc-software,kscharm/igvc-software,monstorium/igvc-software,kscharm/igvc-software,jzheng84/igvc-software,dpattison3/igvc-software,kscharm/igvc-software,RoboJackets/igvc-software,dpattison3/igvc-software,kscharm/igvc-software,monstorium/igvc-software,dpattison3/igvc-software,jzheng84/igvc-software,rmkeezer/igvc-software,monstorium/igvc-software,monstorium/igvc-software,rmkeezer/igvc-software,jzheng84/igvc-software,monstorium/igvc-software
|
d245f8a90412ca91200e5cda2858cba721f7c798
|
src/visualizer/show_imagenet.cpp
|
src/visualizer/show_imagenet.cpp
|
// Visualize the ImageNet dataset.
#include "loader/loader_imagenet_det.h"
#include <iostream>
#include <string>
using std::string;
int main (int argc, char *argv[]) {
if (argc < 3) {
std::cerr << "Usage: " << argv[0]
<< " alov_videos_folder alov_annotations_folder"
<< std::endl;
return 1;
}
int arg_index = 1;
const string& videos_folder = argv[arg_index++];
const string& annotations = argv[arg_index++];
LoaderImagenetDet loader(videos_folder, annotations);
// Different visualization options; uncomment to select the option you would like to use.
//loader.ShowImages();
//loader.ShowAnnotations();
//loader.ShowAnnotationsRand();
loader.ShowAnnotationsShift();
return 0;
}
|
// Visualize the ImageNet dataset.
#define CPU_ONLY 1
#include "loader/loader_imagenet_det.h"
#include <iostream>
#include <string>
using std::string;
int main (int argc, char *argv[]) {
if (argc < 3) {
std::cerr << "Usage: " << argv[0]
<< " alov_videos_folder alov_annotations_folder"
<< std::endl;
return 1;
}
int arg_index = 1;
const string& videos_folder = argv[arg_index++];
const string& annotations = argv[arg_index++];
LoaderImagenetDet loader(videos_folder, annotations);
// Different visualization options; uncomment to select the option you would like to use.
//loader.ShowImages();
//loader.ShowAnnotations();
//loader.ShowAnnotationsRand();
loader.ShowAnnotationsShift();
return 0;
}
|
Update show_imagenet.cpp
|
Update show_imagenet.cpp
|
C++
|
mit
|
shuochen99/goturn,shuochen99/goturn,shuochen99/goturn,shuochen99/goturn
|
6cb33a000f92c48fa54041fb8626efdf2f8aee48
|
src/deleglise-rivat/S2_easy.cpp
|
src/deleglise-rivat/S2_easy.cpp
|
///
/// @file S2_easy.cpp
/// @brief Calculate the contribution of the clustered easy leaves
/// and the sparse easy leaves in parallel using OpenMP
/// (Deleglise-Rivat algorithm).
///
/// Copyright (C) 2015 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <PiTable.hpp>
#include <primesum-internal.hpp>
#include <fast_div.hpp>
#include <generate.hpp>
#include <int128_t.hpp>
#include <min_max.hpp>
#include <imath.hpp>
#include <S2Status.hpp>
#include <S2.hpp>
#include <stdint.h>
#include <vector>
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
using namespace primesum;
namespace {
/// Calculate the contribution of the clustered easy leaves
/// and the sparse easy leaves.
/// @param T either int64_t or uint128_t.
///
template <typename Primes, typename PrimeSums>
maxint_t S2_easy_OpenMP(uint128_t x,
int64_t y,
int64_t z,
int64_t c,
Primes& primes,
PrimeSums& prime_sums,
int threads)
{
maxint_t s2_easy = 0;
int64_t x13 = iroot<3>(x);
int64_t thread_threshold = 1000;
threads = ideal_num_threads(threads, x13, thread_threshold);
PiTable pi(y);
int64_t pi_sqrty = pi[isqrt(y)];
int64_t pi_x13 = pi[x13];
S2Status status(x);
#pragma omp parallel for schedule(dynamic) num_threads(threads) reduction(+: s2_easy)
for (int64_t b = max(c, pi_sqrty) + 1; b <= pi_x13; b++)
{
int64_t prime = primes[b];
uint128_t x2 = x / prime;
int64_t min_trivial = min(x2 / prime, y);
int64_t min_clustered = (int64_t) isqrt(x2);
int64_t min_sparse = z / prime;
int64_t min_hard = max(y / prime, prime);
min_clustered = in_between(min_hard, min_clustered, y);
min_sparse = in_between(min_hard, min_sparse, y);
int64_t l = pi[min_trivial];
int64_t pi_min_clustered = pi[min_clustered];
int64_t pi_min_sparse = pi[min_sparse];
// Find all clustered easy leaves:
// n = primes[b] * primes[l]
// x / n <= y && phi(x / n, b - 1) == phi(x / m, b - 1)
// where phi(x / n, b - 1) = pi(x / n) - b + 2
while (l > pi_min_clustered)
{
int64_t xn = (int64_t) fast_div(x2, primes[l]);
int64_t phi_xn = pi[xn] - b + 2;
maxint_t phi_xn_sum = 1 + prime_sums[pi[xn]] - prime_sums[b - 1];
int64_t xm = (int64_t) fast_div(x2, primes[b + phi_xn - 1]);
xm = max(xm, min_clustered);
int64_t l2 = pi[xm];
s2_easy += prime * phi_xn_sum * (prime_sums[l] - prime_sums[l2]);
l = l2;
}
// Find all sparse easy leaves:
// n = primes[b] * primes[l]
// x / n <= y && phi(x / n, b - 1) = pi(x / n) - b + 2
for (; l > pi_min_sparse; l--)
{
int64_t xn = (int64_t) fast_div(x2, primes[l]);
maxint_t phi = 1 + prime_sums[pi[xn]] - prime_sums[b - 1];
s2_easy += prime * (primes[l] * phi);
}
if (print_status())
status.print(b, pi_x13);
}
return s2_easy;
}
} // namespace
namespace primesum {
maxint_t S2_easy(int128_t x,
int64_t y,
int64_t z,
int64_t c,
int threads)
{
#ifdef HAVE_MPI
if (mpi_num_procs() > 1)
return S2_easy_mpi(x, y, z, c, threads);
#endif
print("");
print("=== S2_easy(x, y) ===");
print("Computation of the easy special leaves");
print(x, y, c, threads);
double time = get_wtime();
maxint_t s2_easy;
// uses less memory
if (y <= numeric_limits<uint32_t>::max())
{
vector<uint32_t> primes = generate_primes<uint32_t>(y);
vector<uint64_t> prime_sums = generate_prime_sums<uint64_t>(y);
s2_easy = S2_easy_OpenMP(x, y, z, c, primes, prime_sums, threads);
}
else
{
vector<int64_t> primes = generate_primes<int64_t>(y);
vector<int128_t> prime_sums = generate_prime_sums<int128_t>(y);
s2_easy = S2_easy_OpenMP(x, y, z, c, primes, prime_sums, threads);
}
print("S2_easy", s2_easy, time);
return s2_easy;
}
} // namespace
|
///
/// @file S2_easy.cpp
/// @brief Calculate the contribution of the clustered easy leaves
/// and the sparse easy leaves in parallel using OpenMP
/// (Deleglise-Rivat algorithm).
///
/// Copyright (C) 2015 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <PiTable.hpp>
#include <primesum-internal.hpp>
#include <fast_div.hpp>
#include <generate.hpp>
#include <int128_t.hpp>
#include <min_max.hpp>
#include <imath.hpp>
#include <S2Status.hpp>
#include <S2.hpp>
#include <stdint.h>
#include <vector>
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
using namespace primesum;
namespace {
/// Calculate the contribution of the clustered easy leaves
/// and the sparse easy leaves.
/// @param T either int64_t or uint128_t.
///
template <typename Primes, typename PrimeSums>
maxint_t S2_easy_OpenMP(uint128_t x,
int64_t y,
int64_t z,
int64_t c,
Primes& primes,
PrimeSums& prime_sums,
int threads)
{
maxint_t s2_easy = 0;
int64_t x13 = iroot<3>(x);
int64_t thread_threshold = 1000;
threads = ideal_num_threads(threads, x13, thread_threshold);
PiTable pi(y);
int64_t pi_sqrty = pi[isqrt(y)];
int64_t pi_x13 = pi[x13];
S2Status status(x);
#pragma omp parallel for schedule(dynamic) num_threads(threads) reduction(+: s2_easy)
for (int64_t b = max(c, pi_sqrty) + 1; b <= pi_x13; b++)
{
int64_t prime = primes[b];
uint128_t x2 = x / prime;
int64_t min_trivial = min(x2 / prime, y);
int64_t min_clustered = (int64_t) isqrt(x2);
int64_t min_sparse = z / prime;
int64_t min_hard = max(y / prime, prime);
min_clustered = in_between(min_hard, min_clustered, y);
min_sparse = in_between(min_hard, min_sparse, y);
int64_t l = pi[min_trivial];
int64_t pi_min_clustered = pi[min_clustered];
int64_t pi_min_sparse = pi[min_sparse];
maxint_t prime256 = prime;
maxint_t phi;
maxint_t diff;
// Find all clustered easy leaves:
// n = primes[b] * primes[l]
// x / n <= y && phi(x / n, b - 1) == phi(x / m, b - 1)
// where phi(x / n, b - 1) = pi(x / n) - b + 2
while (l > pi_min_clustered)
{
int64_t xn = (int64_t) fast_div(x2, primes[l]);
int64_t phi_xn = pi[xn] - b + 2;
phi = prime_sums[pi[xn]] - prime_sums[b - 1];
phi += 1;
int64_t xm = (int64_t) fast_div(x2, primes[b + phi_xn - 1]);
xm = max(xm, min_clustered);
int64_t l2 = pi[xm];
diff = prime_sums[l] - prime_sums[l2];
phi *= prime256;
phi *= diff;
s2_easy += phi;
l = l2;
}
// Find all sparse easy leaves:
// n = primes[b] * primes[l]
// x / n <= y && phi(x / n, b - 1) = pi(x / n) - b + 2
for (; l > pi_min_sparse; l--)
{
int64_t xn = (int64_t) fast_div(x2, primes[l]);
phi = prime_sums[pi[xn]] - prime_sums[b - 1];
phi += 1;
phi *= primes[l];
phi *= prime256;
s2_easy += phi;
}
if (print_status())
status.print(b, pi_x13);
}
return s2_easy;
}
} // namespace
namespace primesum {
maxint_t S2_easy(int128_t x,
int64_t y,
int64_t z,
int64_t c,
int threads)
{
#ifdef HAVE_MPI
if (mpi_num_procs() > 1)
return S2_easy_mpi(x, y, z, c, threads);
#endif
print("");
print("=== S2_easy(x, y) ===");
print("Computation of the easy special leaves");
print(x, y, c, threads);
double time = get_wtime();
maxint_t s2_easy;
// uses less memory
if (y <= numeric_limits<uint32_t>::max())
{
vector<uint32_t> primes = generate_primes<uint32_t>(y);
vector<uint64_t> prime_sums = generate_prime_sums<uint64_t>(y);
s2_easy = S2_easy_OpenMP(x, y, z, c, primes, prime_sums, threads);
}
else
{
vector<int64_t> primes = generate_primes<int64_t>(y);
vector<int128_t> prime_sums = generate_prime_sums<int128_t>(y);
s2_easy = S2_easy_OpenMP(x, y, z, c, primes, prime_sums, threads);
}
print("S2_easy", s2_easy, time);
return s2_easy;
}
} // namespace
|
Optimize int256_t
|
Optimize int256_t
|
C++
|
bsd-2-clause
|
kimwalisch/primesum,kimwalisch/primesum,kimwalisch/primesum
|
a6cf832c114e15a069a410b721d35551e31ea088
|
benchmarks/symplectic_partitioned_runge_kutta_integrator.cpp
|
benchmarks/symplectic_partitioned_runge_kutta_integrator.cpp
|
// .\Release\benchmarks_tests.exe --benchmark_repetitions=5 --benchmark_min_time=300
// Benchmarking on 1 X 3310 MHz CPU
// 2014/05/30-17:19:56
// Benchmark Time(ns) CPU(ns) Iterations
// ------------------------------------------------------------------
// BM_SolveHarmonicOscillator 5503073850 5488398818 11 1.37019e-013, 1.37057e-013
// BM_SolveHarmonicOscillator 5066959920 5054432400 12 1.37019e-013, 1.37057e-013
// BM_SolveHarmonicOscillator 5647669798 5640145245 11 1.37019e-013, 1.37057e-013
// BM_SolveHarmonicOscillator 5107097166 5098832685 13 1.37019e-013, 1.37057e-013
// BM_SolveHarmonicOscillator 4840442968 4828830954 13 1.37019e-013, 1.37057e-013
// BM_SolveHarmonicOscillator_mean 5212995348 5202113347 60 1.37019e-013, 1.37057e-013
// BM_SolveHarmonicOscillator_stddev 294675070 295069109 60 1.37019e-013, 1.37057e-013
// .\Release\benchmarks_tests.exe --benchmark_repetitions=5 --benchmark_min_time=300
// Benchmarking on 1 X 3310 MHz CPU
// 2014/05/30-18:44:00
// Benchmark Time(ns) CPU(ns) Iterations
// ------------------------------------------------------------------
// BM_SolveHarmonicOscillator 2086500672 2086253373 30 1.37019e-013, 1.37057e-013
// BM_SolveHarmonicOscillator 1835725206 1830411733 33 1.37019e-013, 1.37057e-013
// BM_SolveHarmonicOscillator 2041165435 2025932987 30 1.37019e-013, 1.37057e-013
// BM_SolveHarmonicOscillator 2016562322 2011372893 30 1.37019e-013, 1.37057e-013
// BM_SolveHarmonicOscillator 1941378110 1930024872 32 1.37019e-013, 1.37057e-013
// BM_SolveHarmonicOscillator_mean 1980837962 1973362327 155 1.37019e-013, 1.37057e-013
// BM_SolveHarmonicOscillator_stddev 88977645 89552186 155 1.37019e-013, 1.37057e-013
#define GLOG_NO_ABBREVIATED_SEVERITIES
#undef TRACE_SYMPLECTIC_PARTITIONED_RUNGE_KUTTA_INTEGRATOR
#include <algorithm>
#include <vector>
#include "integrators/symplectic_partitioned_runge_kutta_integrator.hpp"
// Must come last to avoid conflicts when defining the CHECK macros.
#include "benchmark/benchmark.h"
using principia::integrators::SPRKIntegrator;
namespace principia {
namespace benchmarks {
namespace {
inline void compute_harmonic_oscillator_force(double const t,
std::vector<double> const& q,
std::vector<double>* result) {
(*result)[0] = -q[0];
}
inline void compute_harmonic_oscillator_velocity(std::vector<double> const& p,
std::vector<double>* result) {
(*result)[0] = p[0];
}
} // namespace
void SolveHarmonicOscillator(benchmark::State* state,
double* q_error,
double* p_error) {
SPRKIntegrator integrator;
SPRKIntegrator::Parameters parameters;
SPRKIntegrator::Solution solution;
parameters.q0 = {1.0};
parameters.p0 = {0.0};
parameters.t0 = 0.0;
#ifdef _DEBUG
parameters.tmax = 100.0;
#else
parameters.tmax = 1000.0;
#endif
parameters.Δt = 1.0E-4;
parameters.coefficients = integrator.Order5Optimal();
parameters.sampling_period = 1;
integrator.Solve(&compute_harmonic_oscillator_force,
&compute_harmonic_oscillator_velocity,
parameters,
&solution);
state->PauseTiming();
*q_error = 0;
*p_error = 0;
for (size_t i = 0; i < solution.time.quantities.size(); ++i) {
*q_error = std::max(*q_error,
std::abs(solution.position[0].quantities[i] -
std::cos(solution.time.quantities[i])));
*p_error = std::max(*p_error,
std::abs(solution.momentum[0].quantities[i] +
std::sin(solution.time.quantities[i])));
}
state->ResumeTiming();
}
static void BM_SolveHarmonicOscillator(
benchmark::State& state) { // NOLINT(runtime/references)
double q_error;
double p_error;
while (state.KeepRunning()) {
SolveHarmonicOscillator(&state, &q_error, &p_error);
}
std::stringstream ss;
ss << q_error << ", " << p_error;
state.SetLabel(ss.str());
}
BENCHMARK(BM_SolveHarmonicOscillator);
} // namespace benchmarks
} // namespace principia
int main(int argc, const char* argv[]) {
benchmark::Initialize(&argc, argv);
benchmark::RunSpecifiedBenchmarks();
}
|
// .\Release\benchmarks_tests.exe --benchmark_repetitions=5 --benchmark_min_time=300
// Benchmarking on 1 X 3310 MHz CPU
// 2014/05/30-18:44:00
// Benchmark Time(ns) CPU(ns) Iterations
// ------------------------------------------------------------------
// BM_SolveHarmonicOscillator 2086500672 2086253373 30 1.37019e-013, 1.37057e-013
// BM_SolveHarmonicOscillator 1835725206 1830411733 33 1.37019e-013, 1.37057e-013
// BM_SolveHarmonicOscillator 2041165435 2025932987 30 1.37019e-013, 1.37057e-013
// BM_SolveHarmonicOscillator 2016562322 2011372893 30 1.37019e-013, 1.37057e-013
// BM_SolveHarmonicOscillator 1941378110 1930024872 32 1.37019e-013, 1.37057e-013
// BM_SolveHarmonicOscillator_mean 1980837962 1973362327 155 1.37019e-013, 1.37057e-013
// BM_SolveHarmonicOscillator_stddev 88977645 89552186 155 1.37019e-013, 1.37057e-013
#define GLOG_NO_ABBREVIATED_SEVERITIES
#undef TRACE_SYMPLECTIC_PARTITIONED_RUNGE_KUTTA_INTEGRATOR
#include <algorithm>
#include <vector>
#include "integrators/symplectic_partitioned_runge_kutta_integrator.hpp"
// Must come last to avoid conflicts when defining the CHECK macros.
#include "benchmark/benchmark.h"
using principia::integrators::SPRKIntegrator;
namespace principia {
namespace benchmarks {
namespace {
inline void compute_harmonic_oscillator_force(double const t,
std::vector<double> const& q,
std::vector<double>* result) {
(*result)[0] = -q[0];
}
inline void compute_harmonic_oscillator_velocity(std::vector<double> const& p,
std::vector<double>* result) {
(*result)[0] = p[0];
}
} // namespace
void SolveHarmonicOscillator(benchmark::State* state,
double* q_error,
double* p_error) {
SPRKIntegrator integrator;
SPRKIntegrator::Parameters parameters;
SPRKIntegrator::Solution solution;
parameters.q0 = {1.0};
parameters.p0 = {0.0};
parameters.t0 = 0.0;
#ifdef _DEBUG
parameters.tmax = 100.0;
#else
parameters.tmax = 1000.0;
#endif
parameters.Δt = 1.0E-4;
parameters.coefficients = integrator.Order5Optimal();
parameters.sampling_period = 1;
integrator.Solve(&compute_harmonic_oscillator_force,
&compute_harmonic_oscillator_velocity,
parameters,
&solution);
state->PauseTiming();
*q_error = 0;
*p_error = 0;
for (size_t i = 0; i < solution.time.quantities.size(); ++i) {
*q_error = std::max(*q_error,
std::abs(solution.position[0].quantities[i] -
std::cos(solution.time.quantities[i])));
*p_error = std::max(*p_error,
std::abs(solution.momentum[0].quantities[i] +
std::sin(solution.time.quantities[i])));
}
state->ResumeTiming();
}
static void BM_SolveHarmonicOscillator(
benchmark::State& state) { // NOLINT(runtime/references)
double q_error;
double p_error;
while (state.KeepRunning()) {
SolveHarmonicOscillator(&state, &q_error, &p_error);
}
std::stringstream ss;
ss << q_error << ", " << p_error;
state.SetLabel(ss.str());
}
BENCHMARK(BM_SolveHarmonicOscillator);
} // namespace benchmarks
} // namespace principia
int main(int argc, const char* argv[]) {
benchmark::Initialize(&argc, argv);
benchmark::RunSpecifiedBenchmarks();
}
|
Remove old numbers.
|
Remove old numbers.
|
C++
|
mit
|
pleroy/Principia,mockingbirdnest/Principia,mockingbirdnest/Principia,mockingbirdnest/Principia,mockingbirdnest/Principia,pleroy/Principia,Norgg/Principia,eggrobin/Principia,Norgg/Principia,pleroy/Principia,Norgg/Principia,Norgg/Principia,eggrobin/Principia,pleroy/Principia,eggrobin/Principia
|
24834ca79103614ab234f5b30528f0401a45ca2e
|
server/src/bash/analyzer/detail/classificator/classificator.cpp
|
server/src/bash/analyzer/detail/classificator/classificator.cpp
|
/*
* Copyright 2016 Adam Chyła, [email protected]
* All rights reserved. Distributed under the terms of the MIT License.
*/
#include "classificator.h"
#include <patlms/util/run_partially.h>
#include <algorithm>
#include <vector>
#include <fstream>
#include <boost/log/trivial.hpp>
#include "src/bash/analyzer/detail/command_summary_divider/command_summary_divider.h"
#include "src/library/fann/fann_wrapper.h"
#include "src/library/fann/fann_guard.h"
namespace bash
{
namespace analyzer
{
namespace detail
{
namespace classificator
{
ClassificatorPtr Classificator::Create(::bash::database::detail::DatabaseFunctionsInterfacePtr database_functions,
::database::detail::GeneralDatabaseFunctionsInterfacePtr general_database_functions,
const std::string &neural_network_data_directory) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Create: Function call";
auto fann_wrapper = ::library::fann::FannWrapper::Create();
return Create(database_functions, general_database_functions, neural_network_data_directory, fann_wrapper);
}
ClassificatorPtr Classificator::Create(::bash::database::detail::DatabaseFunctionsInterfacePtr database_functions,
::database::detail::GeneralDatabaseFunctionsInterfacePtr general_database_functions,
const std::string &neural_network_data_directory,
::library::fann::detail::FannWrapperInterfacePtr fann_wrapper) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Create: Function call";
return ClassificatorPtr(new Classificator(database_functions, general_database_functions, neural_network_data_directory, fann_wrapper));
}
void Classificator::Analyze() {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Analyze: Function call";
constexpr int MAX_ROWS_IN_MEMORY = 100;
command_summary_divider::CommandSummaryDivider divider;
unsigned selected_commands_position = 0;
unsigned commands_statistics_position = 0;
fann_type *calc_out;
fann_type input[100];
auto configurations = database_functions_->GetAnomalyDetectionConfigurations();
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Analyze: Found " << configurations.size() << " configurations";
for (const auto &c : configurations) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Analyze: Create neural network";
struct fann *ann = fann_wrapper_->CreateFromFile(neural_network_data_directory_ + "/network-" + std::to_string(c.id) + ".data");
::library::fann::FannGuard fann_guard(ann);
auto selected_commands_ids = database_functions_->GetMarkedCommandsIds(c.id);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Analyze: Found " << selected_commands_ids.size() << " selected commands ids";
for (const auto &id : selected_commands_ids)
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Analyze: id: " << id;
auto users = database_functions_->GetUsersIdsFromSelectedDailyStatisticsInConfiguration(c.id);
auto daily_user_statistics_count = database_functions_->CountDailyUserStatisticsForAgentWithClassification(c.agent_name_id, ::database::type::Classification::UNKNOWN);
util::RunPartially(MAX_ROWS_IN_MEMORY, daily_user_statistics_count, [&](long long part_count, long long offset) {
auto daily_user_statistics = database_functions_->GetDailyUserStatisticsForAgentWithClassification(c.agent_name_id, ::database::type::Classification::UNKNOWN, part_count, 0);
for (const auto &statistic : daily_user_statistics) {
std::fill(input, input + 100, 0);
auto commands_statistics = database_functions_->GetSelectedDailyUserCommandsStatistics(statistic.id);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Analyze: Found " << commands_statistics.size() << " commands statistics";
selected_commands_position = 0;
commands_statistics_position = 0;
while (selected_commands_position < selected_commands_ids.size()
&& commands_statistics_position < commands_statistics.size()) {
const auto &command_statistic = commands_statistics.at(commands_statistics_position);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Analyze: Position " << selected_commands_position;
if (command_statistic.command_id == selected_commands_ids.at(selected_commands_position)) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Analyze: Found command with id " << command_statistic.command_id;
input[selected_commands_position] = command_statistic.summary;
commands_statistics_position++;
}
selected_commands_position++;
}
std::transform(input, input + 100, input, divider);
for (int i = 0; i < 100; i++) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Analyze: Input value " << i << " : " << input[i];
}
calc_out = fann_wrapper_->Run(ann, input);
::database::type::RowIds::size_type user_position = 0;
fann_type output_value = 0;
for (::database::type::RowIds::size_type i = 0; i < users.size(); i++) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Analyze: Output value " << i << " : " << calc_out[i];
if (calc_out[i] >= output_value) {
output_value = calc_out[i];
user_position = i;
}
}
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Analyze: Found max output value for user_id " << users.at(user_position) << " at position " << user_position << ": " << calc_out[user_position];
constexpr double anomaly_threshold = 0.5;
if (output_value > anomaly_threshold && users.at(user_position) == statistic.user_id) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Analyze: Marking statistic with id " << statistic.id << " as normal";
database_functions_->SetDailyUserStatisticsClassification({statistic.id}, ::database::type::Classification::NORMAL);
}
else {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Analyze: Marking statistic with id " << statistic.id << " as anomaly";
database_functions_->SetDailyUserStatisticsClassification({statistic.id}, ::database::type::Classification::ANOMALY);
}
}
});
}
}
Classificator::Classificator(::bash::database::detail::DatabaseFunctionsInterfacePtr database_functions,
::database::detail::GeneralDatabaseFunctionsInterfacePtr general_database_functions,
const std::string &neural_network_data_directory,
::library::fann::detail::FannWrapperInterfacePtr fann_wrapper) :
database_functions_(database_functions),
general_database_functions_(general_database_functions),
neural_network_data_directory_(neural_network_data_directory),
fann_wrapper_(fann_wrapper) {
}
}
}
}
}
|
/*
* Copyright 2016 Adam Chyła, [email protected]
* All rights reserved. Distributed under the terms of the MIT License.
*/
#include "classificator.h"
#include <patlms/util/run_partially.h>
#include <algorithm>
#include <vector>
#include <fstream>
#include <boost/log/trivial.hpp>
#include "src/bash/analyzer/detail/command_summary_divider/command_summary_divider.h"
#include "src/library/fann/fann_wrapper.h"
#include "src/library/fann/fann_guard.h"
namespace bash
{
namespace analyzer
{
namespace detail
{
namespace classificator
{
ClassificatorPtr Classificator::Create(::bash::database::detail::DatabaseFunctionsInterfacePtr database_functions,
::database::detail::GeneralDatabaseFunctionsInterfacePtr general_database_functions,
const std::string &neural_network_data_directory) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Create: Function call";
auto fann_wrapper = ::library::fann::FannWrapper::Create();
return Create(database_functions, general_database_functions, neural_network_data_directory, fann_wrapper);
}
ClassificatorPtr Classificator::Create(::bash::database::detail::DatabaseFunctionsInterfacePtr database_functions,
::database::detail::GeneralDatabaseFunctionsInterfacePtr general_database_functions,
const std::string &neural_network_data_directory,
::library::fann::detail::FannWrapperInterfacePtr fann_wrapper) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Create: Function call";
return ClassificatorPtr(new Classificator(database_functions, general_database_functions, neural_network_data_directory, fann_wrapper));
}
void Classificator::Analyze() {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Analyze: Function call";
constexpr int MAX_ROWS_IN_MEMORY = 100;
command_summary_divider::CommandSummaryDivider divider;
unsigned selected_commands_position = 0;
unsigned commands_statistics_position = 0;
fann_type *calc_out;
fann_type input[100];
auto configurations = database_functions_->GetAnomalyDetectionConfigurations();
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Analyze: Found " << configurations.size() << " configurations";
for (const auto &c : configurations) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Analyze: Create neural network";
struct fann *ann = fann_wrapper_->CreateFromFile(neural_network_data_directory_ + "/network-" + std::to_string(c.id) + ".data");
::library::fann::FannGuard fann_guard(ann);
auto selected_commands_ids = database_functions_->GetMarkedCommandsIds(c.id);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Analyze: Found " << selected_commands_ids.size() << " selected commands ids";
for (const auto &id : selected_commands_ids)
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Analyze: id: " << id;
auto users = database_functions_->GetUsersIdsFromSelectedDailyStatisticsInConfiguration(c.id);
auto daily_user_statistics_count = database_functions_->CountDailyUserStatisticsForAgentWithClassification(c.agent_name_id, ::database::type::Classification::UNKNOWN);
util::RunPartially(MAX_ROWS_IN_MEMORY, daily_user_statistics_count, [&](long long part_count, long long offset) {
auto daily_user_statistics = database_functions_->GetDailyUserStatisticsForAgentWithClassification(c.agent_name_id, ::database::type::Classification::UNKNOWN, part_count, 0);
for (const auto &statistic : daily_user_statistics) {
std::fill(input, input + 100, 0);
auto commands_statistics = database_functions_->GetSelectedDailyUserCommandsStatistics(statistic.id);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Analyze: Found " << commands_statistics.size() << " commands statistics";
selected_commands_position = 0;
commands_statistics_position = 0;
while (selected_commands_position < selected_commands_ids.size()
&& commands_statistics_position < commands_statistics.size()) {
const auto &command_statistic = commands_statistics.at(commands_statistics_position);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Analyze: Position " << selected_commands_position;
if (command_statistic.command_id == selected_commands_ids.at(selected_commands_position)) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Analyze: Found command with id " << command_statistic.command_id;
input[selected_commands_position] = command_statistic.summary;
commands_statistics_position++;
}
selected_commands_position++;
}
std::transform(input, input + 100, input, divider);
for (int i = 0; i < 100; i++) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Analyze: Input value " << i << " : " << input[i];
}
calc_out = fann_wrapper_->Run(ann, input);
::database::type::RowIds::size_type user_position = 0;
fann_type output_value = 0;
for (::database::type::RowIds::size_type i = 0; i < users.size(); i++) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Analyze: Output value " << i << " : " << calc_out[i];
if (calc_out[i] >= output_value) {
output_value = calc_out[i];
user_position = i;
}
}
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Analyze: Found max output value for user_id " << users.at(user_position) << " at position " << user_position << ": " << calc_out[user_position];
constexpr double anomaly_threshold = 0.5;
if (output_value >= anomaly_threshold && users.at(user_position) == statistic.user_id) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Analyze: Marking statistic with id " << statistic.id << " as normal";
database_functions_->SetDailyUserStatisticsClassification({statistic.id}, ::database::type::Classification::NORMAL);
}
else {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::classificator::Classificator::Analyze: Marking statistic with id " << statistic.id << " as anomaly";
database_functions_->SetDailyUserStatisticsClassification({statistic.id}, ::database::type::Classification::ANOMALY);
}
}
});
}
}
Classificator::Classificator(::bash::database::detail::DatabaseFunctionsInterfacePtr database_functions,
::database::detail::GeneralDatabaseFunctionsInterfacePtr general_database_functions,
const std::string &neural_network_data_directory,
::library::fann::detail::FannWrapperInterfacePtr fann_wrapper) :
database_functions_(database_functions),
general_database_functions_(general_database_functions),
neural_network_data_directory_(neural_network_data_directory),
fann_wrapper_(fann_wrapper) {
}
}
}
}
}
|
Change anomaly threshold
|
Change anomaly threshold
|
C++
|
mit
|
chyla/slas,chyla/slas,chyla/slas,chyla/slas,chyla/pat-lms,chyla/slas,chyla/pat-lms,chyla/pat-lms,chyla/pat-lms,chyla/pat-lms,chyla/pat-lms,chyla/slas,chyla/pat-lms,chyla/slas
|
a1f02d0cd84d3885e9c39f229a1ac2d6bc64a64d
|
Storage/Disk/DiskImage/Formats/AmigaADF.cpp
|
Storage/Disk/DiskImage/Formats/AmigaADF.cpp
|
//
// AmigaADF.cpp
// Clock Signal
//
// Created by Thomas Harte on 16/07/2021.
// Copyright © 2021 Thomas Harte. All rights reserved.
//
#include "AmigaADF.hpp"
#include "../../Encodings/MFM/Constants.hpp"
#include "../../Encodings/MFM/Encoder.hpp"
#include "../../Track/PCMTrack.hpp"
#include <type_traits>
using namespace Storage::Disk;
namespace {
/// Builds a buffer containing the bytes between @c begin and @c end split up so that the nibbles in the first half of the buffer
/// consist of the odd bits of the source bytes — b1, b3, b5 and b7 — ordered so that most-significant nibbles come before
/// least-significant ones, and the second half of the buffer contains the even bits.
///
/// Nibbles are written to @c first; it is assumed that an even number of source bytes have been supplied.
template <typename IteratorT, class OutputIt> void encode_block(IteratorT begin, IteratorT end, OutputIt first) {
// Parse 1: combine odd bits.
auto cursor = begin;
while(cursor != end) {
auto source = uint8_t(
((*cursor & 0x02) << 3) |
((*cursor & 0x08) << 2) |
((*cursor & 0x20) << 1) |
((*cursor & 0x80) << 0)
);
++cursor;
source |=
((*cursor & 0x02) >> 1) |
((*cursor & 0x08) >> 2) |
((*cursor & 0x20) >> 3) |
((*cursor & 0x80) >> 4);
++cursor;
*first = source;
++first;
}
// Parse 2: combine even bits.
cursor = begin;
while(cursor != end) {
auto source = uint8_t(
((*cursor & 0x01) << 4) |
((*cursor & 0x04) << 3) |
((*cursor & 0x10) << 2) |
((*cursor & 0x40) << 1)
);
++cursor;
source |=
((*cursor & 0x01) >> 0) |
((*cursor & 0x04) >> 1) |
((*cursor & 0x10) >> 2) |
((*cursor & 0x40) >> 3);
++cursor;
*first = source;
++first;
}
}
/// Construsts the Amiga-style checksum of the bytes between @c begin and @c end, which is a 32-bit exclusive OR of the source data
/// with each byte converted into a 16-bit word by inserting a 0 bit between every data bit, and then combined into 32-bit words in
/// big endian order.
template <typename IteratorT> auto checksum(IteratorT begin, IteratorT end) {
uint16_t checksum[2]{};
int offset = 0;
while(begin != end) {
const uint8_t value = *begin;
++begin;
// Do a clockless MFM encode.
const auto spread = uint16_t(
((value&0x80) << 7) |
((value&0x40) << 6) |
((value&0x20) << 5) |
((value&0x10) << 4) |
((value&0x08) << 3) |
((value&0x04) << 2) |
((value&0x02) << 1) |
((value&0x01) << 0)
);
checksum[offset] ^= spread;
offset ^= 1;
}
return std::array<uint8_t, 4>{
uint8_t(checksum[0] >> 8),
uint8_t(checksum[0]),
uint8_t(checksum[1] >> 8),
uint8_t(checksum[1]),
};
}
/// Obtains the Amiga-style checksum of the data between @c begin and @c end, then odd-even encodes it and writes
/// it out to @c encoder.
template <typename IteratorT> void write_checksum(IteratorT begin, IteratorT end, std::unique_ptr<Storage::Encodings::MFM::Encoder> &encoder) {
// Believe it or not, this appears to be the actual checksum algorithm on the Amiga:
//
// (1) calculate the XOR checksum of the MFM-encoded data, read as 32-bit words;
// (2) throw away the clock bits;
// (3) Take the resulting 32-bit value and perform an odd-even MFM encoding on those.
const auto raw_checksum = checksum(begin, end);
std::decay_t<decltype(raw_checksum)> encoded_checksum{};
encode_block(raw_checksum.begin(), raw_checksum.end(), encoded_checksum.begin());
encoder->add_bytes(encoded_checksum.begin(), encoded_checksum.end());
}
}
AmigaADF::AmigaADF(const std::string &file_name) :
file_(file_name) {
// Dumb validation only for now: a size check.
if(file_.stats().st_size != 901120) throw Error::InvalidFormat;
}
HeadPosition AmigaADF::get_maximum_head_position() {
return HeadPosition(80);
}
int AmigaADF::get_head_count() {
return 2;
}
std::shared_ptr<Track> AmigaADF::get_track_at_position(Track::Address address) {
using namespace Storage::Encodings;
// Create an MFM encoder.
Storage::Disk::PCMSegment encoded_segment;
encoded_segment.data.reserve(102'400); // i.e. 0x1900 bytes.
auto encoder = MFM::GetMFMEncoder(encoded_segment.data);
// Each track begins with two sync words.
encoder->output_short(MFM::MFMSync);
encoder->output_short(MFM::MFMSync);
// Grab the unencoded track.
file_.seek(get_file_offset_for_position(address), SEEK_SET);
const std::vector<uint8_t> track_data = file_.read(512 * 11);
// Eleven sectors are then encoded.
for(size_t s = 0; s < 11; s++) {
// Two bytes of 0x00 act as an inter-sector gap.
encoder->add_byte(0);
encoder->add_byte(0);
// Add additional sync.
encoder->output_short(MFM::MFMSync);
encoder->output_short(MFM::MFMSync);
// Encode and write the header.
const uint8_t header[4] = {
0xff, // Amiga v1.0 format.
uint8_t(address.position.as_int() * 2 + address.head), // Track.
uint8_t(s), // Sector.
uint8_t(11 - s), // Sectors remaining.
};
std::array<uint8_t, 4> encoded_header;
encode_block(std::begin(header), std::end(header), std::begin(encoded_header));
encoder->add_bytes(std::begin(encoded_header), std::end(encoded_header));
// Write the sector label.
const std::array<uint8_t, 16> os_recovery{};
encoder->add_bytes(os_recovery.begin(), os_recovery.end());
// Encode the data.
std::array<uint8_t, 512> encoded_data;
encode_block(&track_data[s * 512], &track_data[(s + 1) * 512], std::begin(encoded_data));
// Write checksums.
write_checksum(std::begin(encoded_header), std::end(encoded_header), encoder);
write_checksum(std::begin(encoded_data), std::end(encoded_data), encoder);
// Write data.
encoder->add_bytes(std::begin(encoded_data), std::end(encoded_data));
}
return std::make_shared<Storage::Disk::PCMTrack>(std::move(encoded_segment));
}
long AmigaADF::get_file_offset_for_position(Track::Address address) {
return (address.position.as_int() * 2 + address.head) * 512 * 11;
}
|
//
// AmigaADF.cpp
// Clock Signal
//
// Created by Thomas Harte on 16/07/2021.
// Copyright © 2021 Thomas Harte. All rights reserved.
//
#include "AmigaADF.hpp"
#include "../../Encodings/MFM/Constants.hpp"
#include "../../Encodings/MFM/Encoder.hpp"
#include "../../Track/PCMTrack.hpp"
#include <type_traits>
using namespace Storage::Disk;
namespace {
/// Builds a buffer containing the bytes between @c begin and @c end split up so that the nibbles in the first half of the buffer
/// consist of the odd bits of the source bytes — b1, b3, b5 and b7 — ordered so that most-significant nibbles come before
/// least-significant ones, and the second half of the buffer contains the even bits.
///
/// Nibbles are written to @c first; it is assumed that an even number of source bytes have been supplied.
template <typename IteratorT, class OutputIt> void encode_block(IteratorT begin, IteratorT end, OutputIt first) {
// Parse 1: combine odd bits.
auto cursor = begin;
while(cursor != end) {
auto source = uint8_t(
((*cursor & 0x02) << 3) |
((*cursor & 0x08) << 2) |
((*cursor & 0x20) << 1) |
((*cursor & 0x80) << 0)
);
++cursor;
source |=
((*cursor & 0x02) >> 1) |
((*cursor & 0x08) >> 2) |
((*cursor & 0x20) >> 3) |
((*cursor & 0x80) >> 4);
++cursor;
*first = source;
++first;
}
// Parse 2: combine even bits.
cursor = begin;
while(cursor != end) {
auto source = uint8_t(
((*cursor & 0x01) << 4) |
((*cursor & 0x04) << 3) |
((*cursor & 0x10) << 2) |
((*cursor & 0x40) << 1)
);
++cursor;
source |=
((*cursor & 0x01) >> 0) |
((*cursor & 0x04) >> 1) |
((*cursor & 0x10) >> 2) |
((*cursor & 0x40) >> 3);
++cursor;
*first = source;
++first;
}
}
/// Construsts the Amiga-style checksum of the bytes between @c begin and @c end, which is a 32-bit exclusive OR of the source data
/// with each byte converted into a 16-bit word by inserting a 0 bit between every data bit, and then combined into 32-bit words in
/// big endian order.
template <typename IteratorT> auto checksum(IteratorT begin, IteratorT end) {
uint16_t checksum[2]{};
int offset = 0;
while(begin != end) {
const uint8_t value = *begin;
++begin;
// Do a clockless MFM encode.
const auto spread = uint16_t(
((value&0x80) << 7) |
((value&0x40) << 6) |
((value&0x20) << 5) |
((value&0x10) << 4) |
((value&0x08) << 3) |
((value&0x04) << 2) |
((value&0x02) << 1) |
((value&0x01) << 0)
);
checksum[offset] ^= spread;
offset ^= 1;
}
return std::array<uint8_t, 4>{
uint8_t(checksum[0] >> 8),
uint8_t(checksum[0]),
uint8_t(checksum[1] >> 8),
uint8_t(checksum[1]),
};
}
/// Obtains the Amiga-style checksum of the data between @c begin and @c end, then odd-even encodes it and writes
/// it out to @c encoder.
template <typename IteratorT> void write_checksum(IteratorT begin, IteratorT end, std::unique_ptr<Storage::Encodings::MFM::Encoder> &encoder) {
// Believe it or not, this appears to be the actual checksum algorithm on the Amiga:
//
// (1) calculate the XOR checksum of the MFM-encoded data, read as 32-bit words;
// (2) throw away the clock bits;
// (3) Take the resulting 32-bit value and perform an odd-even MFM encoding on those.
const auto raw_checksum = checksum(begin, end);
std::decay_t<decltype(raw_checksum)> encoded_checksum{};
encode_block(raw_checksum.begin(), raw_checksum.end(), encoded_checksum.begin());
encoder->add_bytes(encoded_checksum.begin(), encoded_checksum.end());
}
}
AmigaADF::AmigaADF(const std::string &file_name) :
file_(file_name) {
// Dumb validation only for now: a size check.
if(file_.stats().st_size != 901120) throw Error::InvalidFormat;
}
HeadPosition AmigaADF::get_maximum_head_position() {
return HeadPosition(80);
}
int AmigaADF::get_head_count() {
return 2;
}
std::shared_ptr<Track> AmigaADF::get_track_at_position(Track::Address address) {
using namespace Storage::Encodings;
// Create an MFM encoder.
Storage::Disk::PCMSegment encoded_segment;
encoded_segment.data.reserve(102'400); // i.e. 0x1900 bytes.
auto encoder = MFM::GetMFMEncoder(encoded_segment.data);
// Each track begins with two sync words.
encoder->output_short(MFM::MFMSync);
encoder->output_short(MFM::MFMSync);
// Grab the unencoded track.
file_.seek(get_file_offset_for_position(address), SEEK_SET);
const std::vector<uint8_t> track_data = file_.read(512 * 11);
// Eleven sectors are then encoded.
for(size_t s = 0; s < 11; s++) {
// Two bytes of 0x00 act as an inter-sector gap.
encoder->add_byte(0);
encoder->add_byte(0);
// Add additional sync.
encoder->output_short(MFM::MFMSync);
encoder->output_short(MFM::MFMSync);
// Encode and write the header.
const uint8_t header[4] = {
0xff, // Amiga v1.0 format.
uint8_t(address.position.as_int() * 2 + address.head), // Track.
uint8_t(s), // Sector.
uint8_t(11 - s), // Sectors remaining.
};
std::array<uint8_t, 4> encoded_header;
encode_block(std::begin(header), std::end(header), std::begin(encoded_header));
encoder->add_bytes(std::begin(encoded_header), std::end(encoded_header));
// Write the sector label.
const std::array<uint8_t, 16> os_recovery{};
encoder->add_bytes(os_recovery.begin(), os_recovery.end());
// Encode the data.
std::array<uint8_t, 512> encoded_data;
encode_block(&track_data[s * 512], &track_data[(s + 1) * 512], std::begin(encoded_data));
// Write checksums.
write_checksum(std::begin(encoded_header), std::end(encoded_header), encoder);
write_checksum(std::begin(encoded_data), std::end(encoded_data), encoder);
// Write data.
encoder->add_bytes(std::begin(encoded_data), std::end(encoded_data));
}
// Throw in an '830-byte' gap (that's in MFM, I think — 830 bytes prior to decoding).
// Cf. https://www.techtravels.org/2007/01/syncing-to-the-0x4489-0x4489/#comment-295
for(int c = 0; c < 415; c++) {
encoder->add_byte(0xff);
}
return std::make_shared<Storage::Disk::PCMTrack>(std::move(encoded_segment));
}
long AmigaADF::get_file_offset_for_position(Track::Address address) {
return (address.position.as_int() * 2 + address.head) * 512 * 11;
}
|
Add track padding.
|
Add track padding.
|
C++
|
mit
|
TomHarte/CLK,TomHarte/CLK,TomHarte/CLK,TomHarte/CLK,TomHarte/CLK
|
633cf683acbb1e701d54995ee20ec43f3328e31e
|
apps/bench/BenchScriptHandler.cpp
|
apps/bench/BenchScriptHandler.cpp
|
// ======================================================================== //
// Copyright 2009-2016 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#ifdef OSPRAY_APPS_ENABLE_SCRIPTING
#include <ospcommon/vec.h>
#include <ospray/common/OSPCommon.h>
#include "pico_bench/pico_bench.h"
#include "chaiscript/utility/utility.hpp"
#include "tfn_lib/tfn_lib.h"
#include "common/importer/Importer.h"
#include "BenchScriptHandler.h"
BenchScriptHandler::BenchScriptHandler(OSPRayFixture *fixture)
: OSPRayScriptHandler(fixture->model->handle(), fixture->renderer->handle(), fixture->camera->handle())
{
registerScriptTypes();
registerScriptFunctions();
}
void BenchScriptHandler::registerScriptFunctions() {
auto &chai = this->scriptEngine();
auto benchmark = [&]() {
fixture->fb->clear(OSP_FB_ACCUM | OSP_FB_COLOR);
auto stats = (*fixture->benchmarker)([&]() {
fixture->renderer->renderFrame(*(fixture->fb), OSP_FB_COLOR | OSP_FB_ACCUM);
});
stats.time_suffix = "ms";
if (OSPRayFixture::logFrameTimes) {
for (size_t i = 0; i < stats.size(); ++i) {
std::cout << stats[i].count() << stats.time_suffix << "\n";
}
}
return stats;
};
auto printStats = [](const BenchStats &stats) {
std::cout << stats << "\n";
};
auto setRenderer = [&](ospray::cpp::Renderer &r) {
*fixture->renderer = r;
fixture->fb->clear(OSP_FB_ACCUM | OSP_FB_COLOR);
};
auto saveImage = [&](const std::string &file) {
auto *lfb = (uint32_t*)fixture->fb->map(OSP_FB_COLOR);
bench::writePPM(file + ".ppm", fixture->width, fixture->height, lfb);
fixture->fb->unmap(lfb);
};
auto refresh = [&]() {
fixture->fb->clear(OSP_FB_ACCUM | OSP_FB_COLOR);
};
auto loadTransferFunction = [&](const std::string &fname) {
using namespace ospcommon;
tfn::TransferFunction fcn(fname);
ospray::cpp::TransferFunction transferFunction("piecewise_linear");
auto colorsData = ospray::cpp::Data(fcn.rgbValues.size(), OSP_FLOAT3,
fcn.rgbValues.data());
transferFunction.set("colors", colorsData);
const float tf_scale = fcn.opacityScaling;
// Sample the opacity values, taking 256 samples to match the volume viewer
// the volume viewer does the sampling a bit differently so we match that
// instead of what's done in createDefault
std::vector<float> opacityValues;
const int N_OPACITIES = 256;
size_t lo = 0;
size_t hi = 1;
for (int i = 0; i < N_OPACITIES; ++i) {
const float x = float(i) / float(N_OPACITIES - 1);
float opacity = 0;
if (i == 0) {
opacity = fcn.opacityValues[0].y;
} else if (i == N_OPACITIES - 1) {
opacity = fcn.opacityValues.back().y;
} else {
// If we're over this val, find the next segment
if (x > fcn.opacityValues[lo].x) {
for (size_t j = lo; j < fcn.opacityValues.size() - 1; ++j) {
if (x <= fcn.opacityValues[j + 1].x) {
lo = j;
hi = j + 1;
break;
}
}
}
const float delta = x - fcn.opacityValues[lo].x;
const float interval = fcn.opacityValues[hi].x - fcn.opacityValues[lo].x;
if (delta == 0 || interval == 0) {
opacity = fcn.opacityValues[lo].y;
} else {
opacity = fcn.opacityValues[lo].y + delta / interval
* (fcn.opacityValues[hi].y - fcn.opacityValues[lo].y);
}
}
opacityValues.push_back(tf_scale * opacity);
}
auto opacityValuesData = ospray::cpp::Data(opacityValues.size(),
OSP_FLOAT,
opacityValues.data());
transferFunction.set("opacities", opacityValuesData);
transferFunction.set("valueRange", vec2f(fcn.dataValueMin, fcn.dataValueMax));
transferFunction.commit();
return transferFunction;
};
// load the first volume in the file. This isn't really a great solution for
// final support of loading data from scripts but will work ok.
auto loadVolume = [&](const std::string &fname) {
ospray::importer::Group *imported = ospray::importer::import(fname);
if (imported->volume.empty()) {
throw std::runtime_error("Volume file " + fname + " contains no volumes");
}
return ospray::cpp::Volume(imported->volume[0]->handle);
};
// Get an string environment variable
auto getEnvString = [](const std::string &var){
return ospray::getEnvVar<std::string>(var).second;
};
chai.add(chaiscript::fun(benchmark), "benchmark");
chai.add(chaiscript::fun(printStats), "printStats");
chai.add(chaiscript::fun(setRenderer), "setRenderer");
chai.add(chaiscript::fun(saveImage), "saveImage");
chai.add(chaiscript::fun(refresh), "refresh");
chai.add(chaiscript::fun(loadTransferFunction), "loadTransferFunction");
chai.add(chaiscript::fun(loadVolume), "loadVolume");
chai.add(chaiscript::fun(getEnvString), "getEnvString");
}
void BenchScriptHandler::registerScriptTypes() {
using Millis = OSPRayFixture::Millis;
auto &chai = this->scriptEngine();
chaiscript::ModulePtr m = chaiscript::ModulePtr(new chaiscript::Module());
chaiscript::utility::add_class<Millis>(*m, "Millis",
{},
{
{chaiscript::fun(static_cast<double (Millis::*)() const>(&Millis::count)), "count"}
}
);
chaiscript::utility::add_class<BenchStats>(*m, "Statistics",
{},
{
{chaiscript::fun(static_cast<Millis (BenchStats::*)(const float) const>(&BenchStats::percentile)), "percentile"},
{chaiscript::fun(static_cast<void (BenchStats::*)(const float)>(&BenchStats::winsorize)), "winsorize"},
{chaiscript::fun(static_cast<Millis (BenchStats::*)() const>(&BenchStats::median)), "median"},
{chaiscript::fun(static_cast<Millis (BenchStats::*)() const>(&BenchStats::median_abs_dev)), "median_abs_dev"},
{chaiscript::fun(static_cast<Millis (BenchStats::*)() const>(&BenchStats::mean)), "mean"},
{chaiscript::fun(static_cast<Millis (BenchStats::*)() const>(&BenchStats::std_dev)), "std_dev"},
{chaiscript::fun(static_cast<Millis (BenchStats::*)() const>(&BenchStats::min)), "min"},
{chaiscript::fun(static_cast<Millis (BenchStats::*)() const>(&BenchStats::max)), "max"},
{chaiscript::fun(static_cast<size_t (BenchStats::*)() const>(&BenchStats::size)), "size"},
{chaiscript::fun(static_cast<const Millis& (BenchStats::*)(size_t) const>(&BenchStats::operator[])), "at"},
{chaiscript::fun(static_cast<BenchStats& (BenchStats::*)(const BenchStats&)>(&BenchStats::operator=)), "="}
}
);
chai.add(m);
}
#endif
|
// ======================================================================== //
// Copyright 2009-2016 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#ifdef OSPRAY_APPS_ENABLE_SCRIPTING
#include <ospcommon/vec.h>
#include <ospray/common/OSPCommon.h>
#include "pico_bench/pico_bench.h"
#include "chaiscript/utility/utility.hpp"
#include "tfn_lib/tfn_lib.h"
#include "common/importer/Importer.h"
#include "BenchScriptHandler.h"
BenchScriptHandler::BenchScriptHandler(OSPRayFixture *fixture)
: OSPRayScriptHandler(fixture->model->handle(), fixture->renderer->handle(), fixture->camera->handle())
{
registerScriptTypes();
registerScriptFunctions();
}
void BenchScriptHandler::registerScriptFunctions() {
auto &chai = this->scriptEngine();
auto benchmark = [&]() {
fixture->fb->clear(OSP_FB_ACCUM | OSP_FB_COLOR);
auto stats = (*fixture->benchmarker)([&]() {
fixture->renderer->renderFrame(*(fixture->fb), OSP_FB_COLOR | OSP_FB_ACCUM);
});
stats.time_suffix = "ms";
if (OSPRayFixture::logFrameTimes) {
for (size_t i = 0; i < stats.size(); ++i) {
std::cout << stats[i].count() << stats.time_suffix << "\n";
}
}
return stats;
};
auto printStats = [](const BenchStats &stats) {
std::cout << stats << "\n";
};
auto setRenderer = [&](ospray::cpp::Renderer &r) {
*fixture->renderer = r;
fixture->fb->clear(OSP_FB_ACCUM | OSP_FB_COLOR);
};
auto saveImage = [&](const std::string &file) {
auto *lfb = (uint32_t*)fixture->fb->map(OSP_FB_COLOR);
bench::writePPM(file + ".ppm", fixture->width, fixture->height, lfb);
fixture->fb->unmap(lfb);
};
auto refresh = [&]() {
fixture->fb->clear(OSP_FB_ACCUM | OSP_FB_COLOR);
};
auto loadTransferFunction = [&](const std::string &fname) {
using namespace ospcommon;
tfn::TransferFunction fcn(fname);
ospray::cpp::TransferFunction transferFunction("piecewise_linear");
auto colorsData = ospray::cpp::Data(fcn.rgbValues.size(), OSP_FLOAT3,
fcn.rgbValues.data());
transferFunction.set("colors", colorsData);
const float tf_scale = fcn.opacityScaling;
// Sample the opacity values, taking 256 samples to match the volume viewer
// the volume viewer does the sampling a bit differently so we match that
// instead of what's done in createDefault
std::vector<float> opacityValues;
const int N_OPACITIES = 256;
size_t lo = 0;
size_t hi = 1;
for (int i = 0; i < N_OPACITIES; ++i) {
const float x = float(i) / float(N_OPACITIES - 1);
float opacity = 0;
if (i == 0) {
opacity = fcn.opacityValues[0].y;
} else if (i == N_OPACITIES - 1) {
opacity = fcn.opacityValues.back().y;
} else {
// If we're over this val, find the next segment
if (x > fcn.opacityValues[lo].x) {
for (size_t j = lo; j < fcn.opacityValues.size() - 1; ++j) {
if (x <= fcn.opacityValues[j + 1].x) {
lo = j;
hi = j + 1;
break;
}
}
}
const float delta = x - fcn.opacityValues[lo].x;
const float interval = fcn.opacityValues[hi].x - fcn.opacityValues[lo].x;
if (delta == 0 || interval == 0) {
opacity = fcn.opacityValues[lo].y;
} else {
opacity = fcn.opacityValues[lo].y + delta / interval
* (fcn.opacityValues[hi].y - fcn.opacityValues[lo].y);
}
}
opacityValues.push_back(tf_scale * opacity);
}
auto opacityValuesData = ospray::cpp::Data(opacityValues.size(),
OSP_FLOAT,
opacityValues.data());
transferFunction.set("opacities", opacityValuesData);
transferFunction.set("valueRange", vec2f(fcn.dataValueMin, fcn.dataValueMax));
transferFunction.commit();
return transferFunction;
};
// load the first volume in the file. This isn't really a great solution for
// final support of loading data from scripts but will work ok.
auto loadVolume = [&](const std::string &fname) {
ospray::importer::Group *imported = ospray::importer::import(fname);
if (imported->volume.empty()) {
throw std::runtime_error("Volume file " + fname + " contains no volumes");
}
return ospray::cpp::Volume(imported->volume[0]->handle);
};
// Get an string environment variable
auto getEnvString = [](const std::string &var){
return ospray::getEnvVar<std::string>(var).second;
};
chai.add(chaiscript::fun(benchmark), "benchmark");
chai.add(chaiscript::fun(printStats), "printStats");
chai.add(chaiscript::fun(setRenderer), "setRenderer");
chai.add(chaiscript::fun(saveImage), "saveImage");
chai.add(chaiscript::fun(refresh), "refresh");
chai.add(chaiscript::fun(loadTransferFunction), "loadTransferFunction");
chai.add(chaiscript::fun(loadVolume), "loadVolume");
chai.add(chaiscript::fun(getEnvString), "getEnvString");
}
void BenchScriptHandler::registerScriptTypes() {
using Millis = OSPRayFixture::Millis;
auto &chai = this->scriptEngine();
chaiscript::ModulePtr m = chaiscript::ModulePtr(new chaiscript::Module());
auto millisToString = [](const Millis &m) {
return std::to_string(m.count()) + "ms";
};
chaiscript::utility::add_class<Millis>(*m, "Millis",
{},
{
{chaiscript::fun(static_cast<double (Millis::*)() const>(&Millis::count)), "count"},
{chaiscript::fun(millisToString), "to_string"}
}
);
chaiscript::utility::add_class<BenchStats>(*m, "Statistics",
{},
{
{chaiscript::fun(static_cast<Millis (BenchStats::*)(const float) const>(&BenchStats::percentile)), "percentile"},
{chaiscript::fun(static_cast<void (BenchStats::*)(const float)>(&BenchStats::winsorize)), "winsorize"},
{chaiscript::fun(static_cast<Millis (BenchStats::*)() const>(&BenchStats::median)), "median"},
{chaiscript::fun(static_cast<Millis (BenchStats::*)() const>(&BenchStats::median_abs_dev)), "median_abs_dev"},
{chaiscript::fun(static_cast<Millis (BenchStats::*)() const>(&BenchStats::mean)), "mean"},
{chaiscript::fun(static_cast<Millis (BenchStats::*)() const>(&BenchStats::std_dev)), "std_dev"},
{chaiscript::fun(static_cast<Millis (BenchStats::*)() const>(&BenchStats::min)), "min"},
{chaiscript::fun(static_cast<Millis (BenchStats::*)() const>(&BenchStats::max)), "max"},
{chaiscript::fun(static_cast<size_t (BenchStats::*)() const>(&BenchStats::size)), "size"},
{chaiscript::fun(static_cast<const Millis& (BenchStats::*)(size_t) const>(&BenchStats::operator[])), "[]"},
{chaiscript::fun(static_cast<BenchStats& (BenchStats::*)(const BenchStats&)>(&BenchStats::operator=)), "="}
}
);
chai.add(m);
}
#endif
|
Add a to_string function for the milliseconds type
|
Add a to_string function for the milliseconds type
|
C++
|
apache-2.0
|
MengjiaoH/ospray,wilsonCernWq/ospray,wilsonCernWq/ospray,ospray/OSPRay,MengjiaoH/ospray,wilsonCernWq/ospray,MengjiaoH/ospray,MengjiaoH/ospray,MengjiaoH/ospray,ospray/OSPRay,ospray/OSPRay,ospray/OSPRay
|
2e6b97654f2c1eb79f92846f4169c2387c61c2d8
|
Modules/Segmentation/Interactions/mitkFastMarchingTool3D.cpp
|
Modules/Segmentation/Interactions/mitkFastMarchingTool3D.cpp
|
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "mitkFastMarchingTool3D.h"
#include "mitkToolManager.h"
#include "mitkBaseRenderer.h"
#include "mitkInteractionConst.h"
#include "mitkRenderingManager.h"
#include "mitkImageAccessByItk.h"
// itk filter
#include "itkBinaryThresholdImageFilter.h"
#include "itkCurvatureAnisotropicDiffusionImageFilter.h"
#include "itkGradientMagnitudeRecursiveGaussianImageFilter.h"
#include "itkSigmoidImageFilter.h"
// us
#include <usGetModuleContext.h>
#include <usModule.h>
#include <usModuleContext.h>
#include <usModuleResource.h>
namespace mitk
{
MITK_TOOL_MACRO(MITKSEGMENTATION_EXPORT, FastMarchingTool3D, "FastMarching3D tool");
}
mitk::FastMarchingTool3D::FastMarchingTool3D()
: AutoSegmentationWithPreviewTool(),
m_LowerThreshold(0),
m_UpperThreshold(200),
m_StoppingValue(100),
m_Sigma(1.0),
m_Alpha(-0.5),
m_Beta(3.0),
m_PointSetAddObserverTag(0),
m_PointSetRemoveObserverTag(0)
{
}
mitk::FastMarchingTool3D::~FastMarchingTool3D()
{
}
bool mitk::FastMarchingTool3D::CanHandle(const BaseData* referenceData, const BaseData* workingData) const
{
if(!Superclass::CanHandle(referenceData, workingData))
return false;
if (referenceData == nullptr)
return false;
auto *image = dynamic_cast<const Image *>(referenceData);
if (image == nullptr)
return false;
if (image->GetDimension() < 3)
return false;
return true;
}
const char **mitk::FastMarchingTool3D::GetXPM() const
{
return nullptr; // mitkFastMarchingTool3D_xpm;
}
us::ModuleResource mitk::FastMarchingTool3D::GetIconResource() const
{
us::Module *module = us::GetModuleContext()->GetModule();
us::ModuleResource resource = module->GetResource("FastMarching_48x48.png");
return resource;
}
const char *mitk::FastMarchingTool3D::GetName() const
{
return "Fast Marching 3D";
}
void mitk::FastMarchingTool3D::SetUpperThreshold(double value)
{
m_UpperThreshold = value / 10.0;
}
void mitk::FastMarchingTool3D::SetLowerThreshold(double value)
{
m_LowerThreshold = value / 10.0;
}
void mitk::FastMarchingTool3D::SetBeta(double value)
{
if (m_Beta != value)
{
m_Beta = value;
}
}
void mitk::FastMarchingTool3D::SetSigma(double value)
{
if (m_Sigma != value)
{
if (value > 0.0)
{
m_Sigma = value;
}
}
}
void mitk::FastMarchingTool3D::SetAlpha(double value)
{
if (m_Alpha != value)
{
m_Alpha = value;
}
}
void mitk::FastMarchingTool3D::SetStoppingValue(double value)
{
if (m_StoppingValue != value)
{
m_StoppingValue = value;
}
}
void mitk::FastMarchingTool3D::Activated()
{
Superclass::Activated();
m_SeedsAsPointSet = mitk::PointSet::New();
m_SeedsAsPointSetNode = mitk::DataNode::New();
m_SeedsAsPointSetNode->SetData(m_SeedsAsPointSet);
m_SeedsAsPointSetNode->SetName("3D_FastMarching_PointSet");
m_SeedsAsPointSetNode->SetBoolProperty("helper object", true);
m_SeedsAsPointSetNode->SetColor(0.0, 1.0, 0.0);
m_SeedsAsPointSetNode->SetVisibility(true);
// Create PointSetData Interactor
m_SeedPointInteractor = mitk::PointSetDataInteractor::New();
// Load the according state machine for regular point set interaction
m_SeedPointInteractor->LoadStateMachine("PointSet.xml");
// Set the configuration file that defines the triggers for the transitions
m_SeedPointInteractor->SetEventConfig("PointSetConfig.xml");
// set the DataNode (which already is added to the DataStorage
m_SeedPointInteractor->SetDataNode(m_SeedsAsPointSetNode);
m_ToolManager->GetDataStorage()->Add(m_SeedsAsPointSetNode, m_ToolManager->GetWorkingData(0));
m_SeedContainer = NodeContainer::New();
m_SeedContainer->Initialize();
itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::Pointer pointAddedCommand =
itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::New();
pointAddedCommand->SetCallbackFunction(this, &mitk::FastMarchingTool3D::OnAddPoint);
m_PointSetAddObserverTag = m_SeedsAsPointSet->AddObserver(mitk::PointSetAddEvent(), pointAddedCommand);
itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::Pointer pointRemovedCommand =
itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::New();
pointRemovedCommand->SetCallbackFunction(this, &mitk::FastMarchingTool3D::OnDelete);
m_PointSetRemoveObserverTag = m_SeedsAsPointSet->AddObserver(mitk::PointSetRemoveEvent(), pointRemovedCommand);
}
void mitk::FastMarchingTool3D::Deactivated()
{
this->ClearSeeds();
// Deactivate Interaction
m_SeedPointInteractor->SetDataNode(nullptr);
m_ToolManager->GetDataStorage()->Remove(m_SeedsAsPointSetNode);
m_SeedsAsPointSetNode = nullptr;
m_SeedsAsPointSet->RemoveObserver(m_PointSetAddObserverTag);
m_SeedsAsPointSet->RemoveObserver(m_PointSetRemoveObserverTag);
m_SeedsAsPointSet = nullptr;
Superclass::Deactivated();
}
void mitk::FastMarchingTool3D::OnAddPoint()
{
// Add a new seed point for FastMarching algorithm
mitk::Point3D clickInIndex;
this->GetReferenceData()->GetGeometry()->WorldToIndex(m_SeedsAsPointSet->GetPoint(m_SeedsAsPointSet->GetSize() - 1),
clickInIndex);
itk::Index<3> seedPosition;
seedPosition[0] = clickInIndex[0];
seedPosition[1] = clickInIndex[1];
seedPosition[2] = clickInIndex[2];
NodeType node;
const double seedValue = 0.0;
node.SetValue(seedValue);
node.SetIndex(seedPosition);
this->m_SeedContainer->InsertElement(this->m_SeedContainer->Size(), node);
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
this->UpdatePreview();
}
void mitk::FastMarchingTool3D::OnDelete()
{
// delete last seed point
if (!(this->m_SeedContainer->empty()))
{
// delete last element of seeds container
this->m_SeedContainer->pop_back();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
this->UpdatePreview();
}
}
void mitk::FastMarchingTool3D::ClearSeeds()
{
// clear seeds for FastMarching as well as the PointSet for visualization
if (this->m_SeedContainer.IsNotNull())
this->m_SeedContainer->Initialize();
if (this->m_SeedsAsPointSet.IsNotNull())
{
// remove observers from current pointset
m_SeedsAsPointSet->RemoveObserver(m_PointSetAddObserverTag);
m_SeedsAsPointSet->RemoveObserver(m_PointSetRemoveObserverTag);
// renew pointset
this->m_SeedsAsPointSet = mitk::PointSet::New();
this->m_SeedsAsPointSetNode->SetData(this->m_SeedsAsPointSet);
m_SeedsAsPointSetNode->SetName("Seeds_Preview");
m_SeedsAsPointSetNode->SetBoolProperty("helper object", true);
m_SeedsAsPointSetNode->SetColor(0.0, 1.0, 0.0);
m_SeedsAsPointSetNode->SetVisibility(true);
// add callback function for adding and removing points
itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::Pointer pointAddedCommand =
itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::New();
pointAddedCommand->SetCallbackFunction(this, &mitk::FastMarchingTool3D::OnAddPoint);
m_PointSetAddObserverTag = m_SeedsAsPointSet->AddObserver(mitk::PointSetAddEvent(), pointAddedCommand);
itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::Pointer pointRemovedCommand =
itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::New();
pointRemovedCommand->SetCallbackFunction(this, &mitk::FastMarchingTool3D::OnDelete);
m_PointSetRemoveObserverTag = m_SeedsAsPointSet->AddObserver(mitk::PointSetRemoveEvent(), pointRemovedCommand);
}
}
template <typename TPixel, unsigned int VImageDimension>
void mitk::FastMarchingTool3D::DoITKFastMarching(const itk::Image<TPixel, VImageDimension>* inputImage,
mitk::Image* segmentation, unsigned int timeStep)
{
typedef itk::Image<TPixel, VImageDimension> InputImageType;
/* typedefs for itk pipeline */
typedef mitk::Tool::DefaultSegmentationDataType OutputPixelType;
typedef itk::Image<OutputPixelType, VImageDimension> OutputImageType;
typedef itk::CurvatureAnisotropicDiffusionImageFilter<InputImageType, InternalImageType> SmoothingFilterType;
typedef itk::GradientMagnitudeRecursiveGaussianImageFilter<InternalImageType, InternalImageType> GradientFilterType;
typedef itk::SigmoidImageFilter<InternalImageType, InternalImageType> SigmoidFilterType;
typedef itk::BinaryThresholdImageFilter<InternalImageType, OutputImageType> ThresholdingFilterType;
auto smoothFilter = SmoothingFilterType::New();
smoothFilter->AddObserver(itk::ProgressEvent(), m_ProgressCommand);
smoothFilter->SetTimeStep(0.05);
smoothFilter->SetNumberOfIterations(2);
smoothFilter->SetConductanceParameter(9.0);
auto gradientMagnitudeFilter = GradientFilterType::New();
gradientMagnitudeFilter->AddObserver(itk::ProgressEvent(), m_ProgressCommand);
gradientMagnitudeFilter->SetSigma(m_Sigma);
auto sigmoidFilter = SigmoidFilterType::New();
sigmoidFilter->AddObserver(itk::ProgressEvent(), m_ProgressCommand);
sigmoidFilter->SetAlpha(m_Alpha);
sigmoidFilter->SetBeta(m_Beta);
sigmoidFilter->SetOutputMinimum(0.0);
sigmoidFilter->SetOutputMaximum(1.0);
auto fastMarchingFilter = FastMarchingFilterType::New();
fastMarchingFilter->AddObserver(itk::ProgressEvent(), m_ProgressCommand);
fastMarchingFilter->SetStoppingValue(m_StoppingValue);
fastMarchingFilter->SetTrialPoints(m_SeedContainer);
auto thresholdFilter = ThresholdingFilterType::New();
thresholdFilter->SetLowerThreshold(m_LowerThreshold);
thresholdFilter->SetUpperThreshold(m_UpperThreshold);
thresholdFilter->SetOutsideValue(0);
thresholdFilter->SetInsideValue(1.0);
// set up pipeline
smoothFilter->SetInput(inputImage);
gradientMagnitudeFilter->SetInput(smoothFilter->GetOutput());
sigmoidFilter->SetInput(gradientMagnitudeFilter->GetOutput());
fastMarchingFilter->SetInput(sigmoidFilter->GetOutput());
thresholdFilter->SetInput(fastMarchingFilter->GetOutput());
thresholdFilter->Update();
segmentation->SetVolume((void*)(thresholdFilter->GetOutput()->GetPixelContainer()->GetBufferPointer()), timeStep);
}
void mitk::FastMarchingTool3D::UpdatePrepare()
{
// remove interaction with poinset while updating
if (m_SeedPointInteractor.IsNotNull())
m_SeedPointInteractor->SetDataNode(nullptr);
}
void mitk::FastMarchingTool3D::UpdateCleanUp()
{
// add interaction with poinset again
if (m_SeedPointInteractor.IsNotNull())
m_SeedPointInteractor->SetDataNode(m_SeedsAsPointSetNode);
}
void mitk::FastMarchingTool3D::DoUpdatePreview(const Image* inputAtTimeStep, Image* previewImage, TimeStepType timeStep)
{
if (nullptr != inputAtTimeStep && nullptr != previewImage && m_SeedContainer.IsNotNull() && !m_SeedContainer->empty())
{
AccessFixedDimensionByItk_n(inputAtTimeStep, DoITKFastMarching, 3, (previewImage, timeStep));
}
}
|
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "mitkFastMarchingTool3D.h"
#include "mitkToolManager.h"
#include "mitkBaseRenderer.h"
#include "mitkInteractionConst.h"
#include "mitkRenderingManager.h"
#include "mitkImageAccessByItk.h"
// itk filter
#include "itkBinaryThresholdImageFilter.h"
#include "itkCurvatureAnisotropicDiffusionImageFilter.h"
#include "itkGradientMagnitudeRecursiveGaussianImageFilter.h"
#include "itkSigmoidImageFilter.h"
// us
#include <usGetModuleContext.h>
#include <usModule.h>
#include <usModuleContext.h>
#include <usModuleResource.h>
namespace mitk
{
MITK_TOOL_MACRO(MITKSEGMENTATION_EXPORT, FastMarchingTool3D, "FastMarching3D tool");
}
mitk::FastMarchingTool3D::FastMarchingTool3D()
: AutoSegmentationWithPreviewTool(),
m_LowerThreshold(0),
m_UpperThreshold(200),
m_StoppingValue(100),
m_Sigma(1.0),
m_Alpha(-0.5),
m_Beta(3.0),
m_PointSetAddObserverTag(0),
m_PointSetRemoveObserverTag(0)
{
}
mitk::FastMarchingTool3D::~FastMarchingTool3D()
{
}
bool mitk::FastMarchingTool3D::CanHandle(const BaseData* referenceData, const BaseData* workingData) const
{
if(!Superclass::CanHandle(referenceData, workingData))
return false;
if (referenceData == nullptr)
return false;
auto *image = dynamic_cast<const Image *>(referenceData);
if (image == nullptr)
return false;
if (image->GetDimension() < 3)
return false;
return true;
}
const char **mitk::FastMarchingTool3D::GetXPM() const
{
return nullptr; // mitkFastMarchingTool3D_xpm;
}
us::ModuleResource mitk::FastMarchingTool3D::GetIconResource() const
{
us::Module *module = us::GetModuleContext()->GetModule();
us::ModuleResource resource = module->GetResource("FastMarching_48x48.png");
return resource;
}
const char *mitk::FastMarchingTool3D::GetName() const
{
return "Fast Marching 3D";
}
void mitk::FastMarchingTool3D::SetUpperThreshold(double value)
{
m_UpperThreshold = value / 10.0;
}
void mitk::FastMarchingTool3D::SetLowerThreshold(double value)
{
m_LowerThreshold = value / 10.0;
}
void mitk::FastMarchingTool3D::SetBeta(double value)
{
if (m_Beta != value)
{
m_Beta = value;
}
}
void mitk::FastMarchingTool3D::SetSigma(double value)
{
if (m_Sigma != value)
{
if (value > 0.0)
{
m_Sigma = value;
}
}
}
void mitk::FastMarchingTool3D::SetAlpha(double value)
{
if (m_Alpha != value)
{
m_Alpha = value;
}
}
void mitk::FastMarchingTool3D::SetStoppingValue(double value)
{
if (m_StoppingValue != value)
{
m_StoppingValue = value;
}
}
void mitk::FastMarchingTool3D::Activated()
{
Superclass::Activated();
m_SeedsAsPointSet = mitk::PointSet::New();
m_SeedsAsPointSetNode = mitk::DataNode::New();
m_SeedsAsPointSetNode->SetData(m_SeedsAsPointSet);
m_SeedsAsPointSetNode->SetName("3D_FastMarching_PointSet");
m_SeedsAsPointSetNode->SetBoolProperty("helper object", true);
m_SeedsAsPointSetNode->SetColor(0.0, 1.0, 0.0);
m_SeedsAsPointSetNode->SetVisibility(true);
// Create PointSetData Interactor
m_SeedPointInteractor = mitk::PointSetDataInteractor::New();
// Load the according state machine for regular point set interaction
m_SeedPointInteractor->LoadStateMachine("PointSet.xml");
// Set the configuration file that defines the triggers for the transitions
m_SeedPointInteractor->SetEventConfig("PointSetConfig.xml");
// set the DataNode (which already is added to the DataStorage
m_SeedPointInteractor->SetDataNode(m_SeedsAsPointSetNode);
m_ToolManager->GetDataStorage()->Add(m_SeedsAsPointSetNode, m_ToolManager->GetWorkingData(0));
m_SeedContainer = NodeContainer::New();
m_SeedContainer->Initialize();
itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::Pointer pointAddedCommand =
itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::New();
pointAddedCommand->SetCallbackFunction(this, &mitk::FastMarchingTool3D::OnAddPoint);
m_PointSetAddObserverTag = m_SeedsAsPointSet->AddObserver(mitk::PointSetAddEvent(), pointAddedCommand);
itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::Pointer pointRemovedCommand =
itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::New();
pointRemovedCommand->SetCallbackFunction(this, &mitk::FastMarchingTool3D::OnDelete);
m_PointSetRemoveObserverTag = m_SeedsAsPointSet->AddObserver(mitk::PointSetRemoveEvent(), pointRemovedCommand);
}
void mitk::FastMarchingTool3D::Deactivated()
{
this->ClearSeeds();
// Deactivate Interaction
m_SeedPointInteractor->SetDataNode(nullptr);
m_ToolManager->GetDataStorage()->Remove(m_SeedsAsPointSetNode);
m_SeedsAsPointSetNode = nullptr;
m_SeedsAsPointSet->RemoveObserver(m_PointSetAddObserverTag);
m_SeedsAsPointSet->RemoveObserver(m_PointSetRemoveObserverTag);
m_SeedsAsPointSet = nullptr;
Superclass::Deactivated();
}
void mitk::FastMarchingTool3D::OnAddPoint()
{
// Add a new seed point for FastMarching algorithm
mitk::Point3D clickInIndex;
this->GetReferenceData()->GetGeometry()->WorldToIndex(m_SeedsAsPointSet->GetPoint(m_SeedsAsPointSet->GetSize() - 1),
clickInIndex);
itk::Index<3> seedPosition;
seedPosition[0] = clickInIndex[0];
seedPosition[1] = clickInIndex[1];
seedPosition[2] = clickInIndex[2];
NodeType node;
const double seedValue = 0.0;
node.SetValue(seedValue);
node.SetIndex(seedPosition);
this->m_SeedContainer->InsertElement(this->m_SeedContainer->Size(), node);
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
this->UpdatePreview();
}
void mitk::FastMarchingTool3D::OnDelete()
{
// delete last seed point
if (!(this->m_SeedContainer->empty()))
{
// delete last element of seeds container
this->m_SeedContainer->pop_back();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
this->UpdatePreview();
}
}
void mitk::FastMarchingTool3D::ClearSeeds()
{
// clear seeds for FastMarching as well as the PointSet for visualization
if (this->m_SeedContainer.IsNotNull())
this->m_SeedContainer->Initialize();
if (this->m_SeedsAsPointSet.IsNotNull())
{
// remove observers from current pointset
m_SeedsAsPointSet->RemoveObserver(m_PointSetAddObserverTag);
m_SeedsAsPointSet->RemoveObserver(m_PointSetRemoveObserverTag);
// renew pointset
this->m_SeedsAsPointSet = mitk::PointSet::New();
this->m_SeedsAsPointSetNode->SetData(this->m_SeedsAsPointSet);
m_SeedsAsPointSetNode->SetName("Seeds_Preview");
m_SeedsAsPointSetNode->SetBoolProperty("helper object", true);
m_SeedsAsPointSetNode->SetColor(0.0, 1.0, 0.0);
m_SeedsAsPointSetNode->SetVisibility(true);
// add callback function for adding and removing points
itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::Pointer pointAddedCommand =
itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::New();
pointAddedCommand->SetCallbackFunction(this, &mitk::FastMarchingTool3D::OnAddPoint);
m_PointSetAddObserverTag = m_SeedsAsPointSet->AddObserver(mitk::PointSetAddEvent(), pointAddedCommand);
itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::Pointer pointRemovedCommand =
itk::SimpleMemberCommand<mitk::FastMarchingTool3D>::New();
pointRemovedCommand->SetCallbackFunction(this, &mitk::FastMarchingTool3D::OnDelete);
m_PointSetRemoveObserverTag = m_SeedsAsPointSet->AddObserver(mitk::PointSetRemoveEvent(), pointRemovedCommand);
}
}
template <typename TPixel, unsigned int VImageDimension>
void mitk::FastMarchingTool3D::DoITKFastMarching(const itk::Image<TPixel, VImageDimension>* inputImage,
mitk::Image* segmentation, unsigned int timeStep)
{
typedef itk::Image<TPixel, VImageDimension> InputImageType;
/* typedefs for itk pipeline */
typedef mitk::Tool::DefaultSegmentationDataType OutputPixelType;
typedef itk::Image<OutputPixelType, VImageDimension> OutputImageType;
typedef itk::CurvatureAnisotropicDiffusionImageFilter<InputImageType, InternalImageType> SmoothingFilterType;
typedef itk::GradientMagnitudeRecursiveGaussianImageFilter<InternalImageType, InternalImageType> GradientFilterType;
typedef itk::SigmoidImageFilter<InternalImageType, InternalImageType> SigmoidFilterType;
typedef itk::BinaryThresholdImageFilter<InternalImageType, OutputImageType> ThresholdingFilterType;
auto smoothFilter = SmoothingFilterType::New();
smoothFilter->AddObserver(itk::ProgressEvent(), m_ProgressCommand);
smoothFilter->SetTimeStep(0.05);
smoothFilter->SetNumberOfIterations(2);
smoothFilter->SetConductanceParameter(9.0);
auto gradientMagnitudeFilter = GradientFilterType::New();
gradientMagnitudeFilter->AddObserver(itk::ProgressEvent(), m_ProgressCommand);
gradientMagnitudeFilter->SetSigma(m_Sigma);
auto sigmoidFilter = SigmoidFilterType::New();
sigmoidFilter->AddObserver(itk::ProgressEvent(), m_ProgressCommand);
sigmoidFilter->SetAlpha(m_Alpha);
sigmoidFilter->SetBeta(m_Beta);
sigmoidFilter->SetOutputMinimum(0.0);
sigmoidFilter->SetOutputMaximum(1.0);
auto fastMarchingFilter = FastMarchingFilterType::New();
fastMarchingFilter->AddObserver(itk::ProgressEvent(), m_ProgressCommand);
fastMarchingFilter->SetStoppingValue(m_StoppingValue);
fastMarchingFilter->SetTrialPoints(m_SeedContainer);
auto thresholdFilter = ThresholdingFilterType::New();
thresholdFilter->SetLowerThreshold(m_LowerThreshold);
thresholdFilter->SetUpperThreshold(m_UpperThreshold);
thresholdFilter->SetOutsideValue(0);
thresholdFilter->SetInsideValue(1.0);
// set up pipeline
smoothFilter->SetInput(inputImage);
gradientMagnitudeFilter->SetInput(smoothFilter->GetOutput());
sigmoidFilter->SetInput(gradientMagnitudeFilter->GetOutput());
fastMarchingFilter->SetInput(sigmoidFilter->GetOutput());
thresholdFilter->SetInput(fastMarchingFilter->GetOutput());
thresholdFilter->Update();
segmentation->SetVolume((void*)(thresholdFilter->GetOutput()->GetPixelContainer()->GetBufferPointer()), timeStep);
}
void mitk::FastMarchingTool3D::UpdatePrepare()
{
// remove interaction with poinset while updating
if (m_SeedPointInteractor.IsNotNull())
m_SeedPointInteractor->SetDataNode(nullptr);
}
void mitk::FastMarchingTool3D::UpdateCleanUp()
{
// add interaction with poinset again
if (m_SeedPointInteractor.IsNotNull())
m_SeedPointInteractor->SetDataNode(m_SeedsAsPointSetNode);
}
void mitk::FastMarchingTool3D::DoUpdatePreview(const Image* inputAtTimeStep, Image* previewImage, TimeStepType timeStep)
{
if (nullptr != inputAtTimeStep && nullptr != previewImage && m_SeedContainer.IsNotNull())
{
AccessFixedDimensionByItk_n(inputAtTimeStep, DoITKFastMarching, 3, (previewImage, timeStep));
}
}
|
Update also if the seed points are empty
|
Update also if the seed points are empty
This will automatically remove the preview segmentation after all seed points have been removed.
This is required for the "Clear"-button to work correctly.
|
C++
|
bsd-3-clause
|
MITK/MITK,MITK/MITK,MITK/MITK,MITK/MITK,MITK/MITK,MITK/MITK
|
a7fc7a353fbd5c863363e5e5a34d41dea8e43b4f
|
src/base/paged_memory.cc
|
src/base/paged_memory.cc
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "perfetto/ext/base/paged_memory.h"
#include <algorithm>
#include <cmath>
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
#include <Windows.h>
#else // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
#include <sys/mman.h>
#endif // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
#include "perfetto/base/logging.h"
#include "perfetto/ext/base/container_annotations.h"
#include "perfetto/ext/base/utils.h"
namespace perfetto {
namespace base {
namespace {
constexpr size_t kGuardSize = kPageSize;
#if TRACK_COMMITTED_SIZE()
constexpr size_t kCommitChunkSize = kPageSize * 1024; // 4mB
#endif // TRACK_COMMITTED_SIZE()
} // namespace
// static
PagedMemory PagedMemory::Allocate(size_t size, int flags) {
PERFETTO_DCHECK(size % kPageSize == 0);
size_t outer_size = size + kGuardSize * 2;
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
void* ptr = VirtualAlloc(nullptr, outer_size, MEM_RESERVE, PAGE_NOACCESS);
if (!ptr && (flags & kMayFail))
return PagedMemory();
PERFETTO_CHECK(ptr);
char* usable_region = reinterpret_cast<char*>(ptr) + kGuardSize;
#else // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
void* ptr = mmap(nullptr, outer_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (ptr == MAP_FAILED && (flags & kMayFail))
return PagedMemory();
PERFETTO_CHECK(ptr && ptr != MAP_FAILED);
char* usable_region = reinterpret_cast<char*>(ptr) + kGuardSize;
int res = mprotect(ptr, kGuardSize, PROT_NONE);
res |= mprotect(usable_region + size, kGuardSize, PROT_NONE);
PERFETTO_CHECK(res == 0);
#endif // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
auto memory = PagedMemory(usable_region, size);
#if TRACK_COMMITTED_SIZE()
size_t initial_commit = size;
if (flags & kDontCommit)
initial_commit = std::min(initial_commit, kCommitChunkSize);
memory.EnsureCommitted(initial_commit);
#endif // TRACK_COMMITTED_SIZE()
return memory;
}
PagedMemory::PagedMemory() {}
PagedMemory::PagedMemory(char* p, size_t size)
: p_(p),
size_(size){ANNOTATE_NEW_BUFFER(p_, size_, committed_size_)}
PagedMemory::PagedMemory(PagedMemory && other) noexcept {
*this = other;
other.p_ = nullptr;
}
PagedMemory& PagedMemory::operator=(PagedMemory&& other) {
*this = other;
other.p_ = nullptr;
return *this;
}
PagedMemory::~PagedMemory() {
if (!p_)
return;
PERFETTO_CHECK(size_);
char* start = p_ - kGuardSize;
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
BOOL res = VirtualFree(start, 0, MEM_RELEASE);
PERFETTO_CHECK(res != 0);
#else // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
const size_t outer_size = size_ + kGuardSize * 2;
int res = munmap(start, outer_size);
PERFETTO_CHECK(res == 0);
#endif // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
ANNOTATE_DELETE_BUFFER(p_, size_, committed_size_)
}
bool PagedMemory::AdviseDontNeed(void* p, size_t size) {
PERFETTO_DCHECK(p_);
PERFETTO_DCHECK(p >= p_);
PERFETTO_DCHECK(static_cast<char*>(p) + size <= p_ + size_);
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
// Discarding pages on Windows has more CPU cost than is justified for the
// possible memory savings.
return false;
#else // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
// http://man7.org/linux/man-pages/man2/madvise.2.html
int res = madvise(p, size, MADV_DONTNEED);
PERFETTO_DCHECK(res == 0);
return true;
#endif // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
}
#if TRACK_COMMITTED_SIZE()
void PagedMemory::EnsureCommitted(size_t committed_size) {
PERFETTO_DCHECK(committed_size > 0u);
PERFETTO_DCHECK(committed_size <= size_);
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
if (committed_size_ >= committed_size)
return;
// Rounding up.
size_t delta = committed_size - committed_size_;
size_t num_additional_chunks =
(delta + kCommitChunkSize - 1) / kCommitChunkSize;
PERFETTO_DCHECK(num_additional_chunks * kCommitChunkSize >= delta);
// Don't commit more than the total size.
size_t commit_size = std::min(num_additional_chunks * kCommitChunkSize,
size_ - committed_size_);
void* res = VirtualAlloc(p_ + committed_size_, commit_size, MEM_COMMIT,
PAGE_READWRITE);
PERFETTO_CHECK(res);
ANNOTATE_CHANGE_SIZE(p_, size_, committed_size_,
committed_size_ + commit_size)
committed_size_ += commit_size;
#else // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
// mmap commits automatically as needed, so we only track here for ASAN.
committed_size = std::max(committed_size_, committed_size);
ANNOTATE_CHANGE_SIZE(p_, size_, committed_size_, committed_size)
committed_size_ = committed_size;
#endif // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
}
#endif // TRACK_COMMITTED_SIZE()
} // namespace base
} // namespace perfetto
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "perfetto/ext/base/paged_memory.h"
#include <algorithm>
#include <cmath>
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
#include <Windows.h>
#else // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
#include <sys/mman.h>
#endif // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
#include "perfetto/base/logging.h"
#include "perfetto/ext/base/container_annotations.h"
#include "perfetto/ext/base/utils.h"
namespace perfetto {
namespace base {
namespace {
constexpr size_t kGuardSize = kPageSize;
#if TRACK_COMMITTED_SIZE()
constexpr size_t kCommitChunkSize = kPageSize * 1024; // 4mB
#endif // TRACK_COMMITTED_SIZE()
} // namespace
// static
PagedMemory PagedMemory::Allocate(size_t size, int flags) {
PERFETTO_DCHECK(size % kPageSize == 0);
size_t outer_size = size + kGuardSize * 2;
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
void* ptr = VirtualAlloc(nullptr, outer_size, MEM_RESERVE, PAGE_NOACCESS);
if (!ptr && (flags & kMayFail))
return PagedMemory();
PERFETTO_CHECK(ptr);
char* usable_region = reinterpret_cast<char*>(ptr) + kGuardSize;
#else // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
void* ptr = mmap(nullptr, outer_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (ptr == MAP_FAILED && (flags & kMayFail))
return PagedMemory();
PERFETTO_CHECK(ptr && ptr != MAP_FAILED);
char* usable_region = reinterpret_cast<char*>(ptr) + kGuardSize;
int res = mprotect(ptr, kGuardSize, PROT_NONE);
res |= mprotect(usable_region + size, kGuardSize, PROT_NONE);
PERFETTO_CHECK(res == 0);
#endif // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
auto memory = PagedMemory(usable_region, size);
#if TRACK_COMMITTED_SIZE()
size_t initial_commit = size;
if (flags & kDontCommit)
initial_commit = std::min(initial_commit, kCommitChunkSize);
memory.EnsureCommitted(initial_commit);
#endif // TRACK_COMMITTED_SIZE()
return memory;
}
PagedMemory::PagedMemory() {}
// clang-format off
PagedMemory::PagedMemory(char* p, size_t size) : p_(p), size_(size) {
ANNOTATE_NEW_BUFFER(p_, size_, committed_size_)
}
PagedMemory::PagedMemory(PagedMemory&& other) noexcept {
*this = other;
other.p_ = nullptr;
}
// clang-format on
PagedMemory& PagedMemory::operator=(PagedMemory&& other) {
this->~PagedMemory();
new (this) PagedMemory(std::move(other));
return *this;
}
PagedMemory::~PagedMemory() {
if (!p_)
return;
PERFETTO_CHECK(size_);
char* start = p_ - kGuardSize;
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
BOOL res = VirtualFree(start, 0, MEM_RELEASE);
PERFETTO_CHECK(res != 0);
#else // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
const size_t outer_size = size_ + kGuardSize * 2;
int res = munmap(start, outer_size);
PERFETTO_CHECK(res == 0);
#endif // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
ANNOTATE_DELETE_BUFFER(p_, size_, committed_size_)
}
bool PagedMemory::AdviseDontNeed(void* p, size_t size) {
PERFETTO_DCHECK(p_);
PERFETTO_DCHECK(p >= p_);
PERFETTO_DCHECK(static_cast<char*>(p) + size <= p_ + size_);
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
// Discarding pages on Windows has more CPU cost than is justified for the
// possible memory savings.
return false;
#else // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
// http://man7.org/linux/man-pages/man2/madvise.2.html
int res = madvise(p, size, MADV_DONTNEED);
PERFETTO_DCHECK(res == 0);
return true;
#endif // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
}
#if TRACK_COMMITTED_SIZE()
void PagedMemory::EnsureCommitted(size_t committed_size) {
PERFETTO_DCHECK(committed_size > 0u);
PERFETTO_DCHECK(committed_size <= size_);
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
if (committed_size_ >= committed_size)
return;
// Rounding up.
size_t delta = committed_size - committed_size_;
size_t num_additional_chunks =
(delta + kCommitChunkSize - 1) / kCommitChunkSize;
PERFETTO_DCHECK(num_additional_chunks * kCommitChunkSize >= delta);
// Don't commit more than the total size.
size_t commit_size = std::min(num_additional_chunks * kCommitChunkSize,
size_ - committed_size_);
void* res = VirtualAlloc(p_ + committed_size_, commit_size, MEM_COMMIT,
PAGE_READWRITE);
PERFETTO_CHECK(res);
ANNOTATE_CHANGE_SIZE(p_, size_, committed_size_,
committed_size_ + commit_size)
committed_size_ += commit_size;
#else // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
// mmap commits automatically as needed, so we only track here for ASAN.
committed_size = std::max(committed_size_, committed_size);
ANNOTATE_CHANGE_SIZE(p_, size_, committed_size_, committed_size)
committed_size_ = committed_size;
#endif // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
}
#endif // TRACK_COMMITTED_SIZE()
} // namespace base
} // namespace perfetto
|
fix move-assignment (call dtor) + formatting
|
PagedMemory: fix move-assignment (call dtor) + formatting
Change-Id: I03d433a8a911548487fdcadffa92902fa8e5f54c
|
C++
|
apache-2.0
|
google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto
|
42832dd782ecb15170daa87d6fda35cdba3b4c75
|
include/apollo/converters.hpp
|
include/apollo/converters.hpp
|
#ifndef APOLLO_CONVERTERS_HPP_INCLUDED
#define APOLLO_CONVERTERS_HPP_INCLUDED APOLLO_CONVERTERS_HPP_INCLUDED
#include <apollo/converters_fwd.hpp>
#include <apollo/error.hpp>
#include <apollo/detail/meta_util.hpp>
#include <apollo/detail/ref_binder.hpp>
#include <boost/exception/errinfo_type_info_name.hpp>
#include <boost/exception/info.hpp>
#include <boost/throw_exception.hpp>
#include <boost/type_index.hpp>
#include <apollo/lua_include.hpp>
#include <type_traits>
namespace apollo {
struct raw_function;
template <typename Converter>
using to_type_of = typename detail::remove_qualifiers<Converter>::type::to_type;
namespace detail {
// Lua type constants //
template <typename T, typename Enable=void> // Default to userdata.
struct lua_type_id: std::integral_constant<int, LUA_TUSERDATA> {};
template <typename T> // Any arithmetic type except bool is a number.
struct lua_type_id<T,
typename std::enable_if<
std::is_same<T, typename detail::remove_qualifiers<T>::type>::value
&& (
std::is_arithmetic<T>::value
|| std::is_enum<T>::value)>::type>
: std::integral_constant<int, LUA_TNUMBER> {};
template <> // boolean
struct lua_type_id<bool>: std::integral_constant<int, LUA_TBOOLEAN> {};
template <> struct lua_type_id<void>: std::integral_constant<int, LUA_TNIL> {};
template <>
struct lua_type_id<void*>: std::integral_constant<int, LUA_TLIGHTUSERDATA> {};
// string
template <>
struct lua_type_id<char*>: std::integral_constant<int, LUA_TSTRING> {};
template <> struct lua_type_id<char const*>: lua_type_id<char*> {};
template <> struct lua_type_id<char>: lua_type_id<char*> {};
template <std::size_t N> struct lua_type_id<char[N]>: lua_type_id<char*> {};
template <> struct lua_type_id<std::string>: lua_type_id<char*> {};
template <> // thread (lua_State*)
struct lua_type_id<lua_State*>: std::integral_constant<int, LUA_TTHREAD> {};
template <typename T>
struct is_plain_function: std::integral_constant<bool,
std::is_function<typename std::remove_pointer<T>::type>::value>
{ };
// function (plain function (pointer), boost and std function templates)
template <typename T>
struct lua_type_id<T,
typename std::enable_if<
detail::is_plain_function<T>::value ||
std::is_member_function_pointer<T>::value>::type>
: std::integral_constant<int, LUA_TFUNCTION> {};
template <template <class> class FObj, typename R, typename... Args>
struct lua_type_id<FObj<R(Args...)>>
: std::integral_constant<int, LUA_TFUNCTION> {};
template <> struct lua_type_id<raw_function>
: std::integral_constant<int, LUA_TFUNCTION> {};
} // namespace detail
template <typename T, typename Enable=void>
struct convert_cref_by_val: std::integral_constant<bool,
detail::lua_type_id<T>::value != LUA_TUSERDATA>
{};
// Const references to primitive types are handled as non-references.
template<typename T>
struct converter<T, typename std::enable_if<
detail::is_const_reference<T>::value &&
convert_cref_by_val<typename detail::remove_qualifiers<T>::type>::value
>::type
>: converter<typename detail::remove_qualifiers<T>::type>
{};
template <typename T>
using push_converter_for = converter<
typename detail::remove_qualifiers<T>::type>;
template <typename T>
using pull_converter_for = converter<typename std::remove_cv<T>::type>;
namespace detail {
inline int push_impl(lua_State*)
{
return 0;
}
template <typename Head, typename... Tail>
int push_impl(lua_State* L, Head&& head, Tail&&... tail)
{
int const n_pushed = push_converter_for<Head>().push(
L, std::forward<Head>(head));
return n_pushed + push_impl(L, std::forward<Tail>(tail)...);
}
} // namespace detail
template <typename T, typename... MoreTs>
int push(lua_State* L, T&& v, MoreTs&&... more)
{
return detail::push_impl(L,
std::forward<T>(v), std::forward<MoreTs>(more)...);
}
namespace detail {
failure_t converter_has_idx_param_impl(...);
template <typename Converter>
auto converter_has_idx_param_impl(Converter conv)
-> decltype(conv.n_conversion_steps(
std::declval<lua_State*>(), 0, std::declval<int*>()));
template <typename Converter>
struct converter_has_idx_param: std::integral_constant<bool, !has_failed<
decltype(converter_has_idx_param_impl(std::declval<Converter>()))
>::value>
{};
}
template <typename Converter>
typename std::enable_if<
!detail::converter_has_idx_param<Converter>::value,
to_type_of<Converter>>::type
unchecked_to_with(
Converter&& conv, lua_State* L, int idx, int* next_idx = nullptr)
{
(void)conv; // Silence MSVC.
if (next_idx)
*next_idx = idx + conv.n_consumed;
return conv.to(L, idx);
}
template <typename Converter>
typename std::enable_if<
detail::converter_has_idx_param<Converter>::value,
to_type_of<Converter>>::type
unchecked_to_with(
Converter&& conv, lua_State* L, int idx, int* next_idx = nullptr)
{
return conv.to(L, idx, next_idx);
}
template <typename T>
to_type_of<pull_converter_for<T>> unchecked_to(lua_State* L, int idx)
{
return unchecked_to_with(pull_converter_for<T>(), L, idx);
}
template <typename Converter>
typename std::enable_if<
!detail::converter_has_idx_param<Converter>::value,
unsigned>::type
n_conversion_steps_with(
Converter&& conv, lua_State* L, int idx, int* next_idx = nullptr)
{
(void)conv;
if (next_idx)
*next_idx = idx + conv.n_consumed;
return conv.n_conversion_steps(L, idx);
}
template <typename Converter>
typename std::enable_if<
detail::converter_has_idx_param<Converter>::value,
unsigned>::type
n_conversion_steps_with(
Converter&& conv, lua_State* L, int idx, int* next_idx = nullptr)
{
return conv.n_conversion_steps(L, idx, next_idx);
}
template <typename T>
unsigned n_conversion_steps(lua_State* L, int idx)
{
return n_conversion_steps_with(pull_converter_for<T>(), L, idx);
}
template <typename Converter>
bool is_convertible_with(Converter const& conv, lua_State* L, int idx)
{
(void)conv; // Silence MSVC.
return n_conversion_steps_with(conv, L, idx) != no_conversion;
}
template <typename T>
bool is_convertible(lua_State* L, int idx)
{
return is_convertible_with(pull_converter_for<T>(), L, idx);
}
template <typename Converter>
to_type_of<Converter> to_with(
Converter&& conv, lua_State* L, int idx, int* next_idx = nullptr)
{
if (!is_convertible_with(conv, L, idx)) {
BOOST_THROW_EXCEPTION(to_cpp_conversion_error()
<< boost::errinfo_type_info_name(
boost::typeindex::type_id<to_type_of<Converter>>()
.pretty_name())
<< errinfo::msg("conversion from Lua to C++ failed")
<< errinfo::stack_index(idx)
<< errinfo::lua_state(L));
}
return unchecked_to_with(conv, L, idx, next_idx);
}
template <typename T>
to_type_of<pull_converter_for<T>> to(lua_State* L, int idx)
{
return to_with(pull_converter_for<T>(), L, idx);
}
// Cannot use function here, it would potentially return a reference to local.
#define APOLLO_TO_ARG(L, idx, ...) \
::apollo::unwrap_ref(::apollo::to<__VA_ARGS__>(L, idx))
template <typename T>
to_type_of<pull_converter_for<T>> to(lua_State* L, int idx, T&& fallback)
{
if (!is_convertible<T>(L, idx))
return fallback;
return unchecked_to<T>(L, idx);
}
} // namepace apollo
#endif // APOLLO_CONVERTERS_HPP_INCLUDED
|
#ifndef APOLLO_CONVERTERS_HPP_INCLUDED
#define APOLLO_CONVERTERS_HPP_INCLUDED APOLLO_CONVERTERS_HPP_INCLUDED
#include <apollo/converters_fwd.hpp>
#include <apollo/error.hpp>
#include <apollo/detail/meta_util.hpp>
#include <apollo/detail/ref_binder.hpp>
#include <boost/exception/errinfo_type_info_name.hpp>
#include <boost/exception/info.hpp>
#include <boost/throw_exception.hpp>
#include <boost/type_index.hpp>
#include <apollo/lua_include.hpp>
#include <type_traits>
namespace apollo {
struct raw_function;
template <typename Converter>
using to_type_of = typename detail::remove_qualifiers<Converter>::type::to_type;
namespace detail {
// Lua type constants //
template <typename T, typename Enable=void> // Default to userdata.
struct lua_type_id: std::integral_constant<int, LUA_TUSERDATA> {};
template <typename T> // Any arithmetic type except bool is a number.
struct lua_type_id<T,
typename std::enable_if<
std::is_same<T, typename detail::remove_qualifiers<T>::type>::value
&& (
std::is_arithmetic<T>::value
|| std::is_enum<T>::value)>::type>
: std::integral_constant<int, LUA_TNUMBER> {};
template <> // boolean
struct lua_type_id<bool>: std::integral_constant<int, LUA_TBOOLEAN> {};
template <> struct lua_type_id<void>: std::integral_constant<int, LUA_TNIL> {};
template <>
struct lua_type_id<void*>: std::integral_constant<int, LUA_TLIGHTUSERDATA> {};
// string
template <>
struct lua_type_id<char*>: std::integral_constant<int, LUA_TSTRING> {};
template <> struct lua_type_id<char const*>: lua_type_id<char*> {};
template <> struct lua_type_id<char>: lua_type_id<char*> {};
template <std::size_t N> struct lua_type_id<char[N]>: lua_type_id<char*> {};
template <> struct lua_type_id<std::string>: lua_type_id<char*> {};
template <> // thread (lua_State*)
struct lua_type_id<lua_State*>: std::integral_constant<int, LUA_TTHREAD> {};
template <typename T>
struct is_plain_function: std::integral_constant<bool,
std::is_function<typename std::remove_pointer<T>::type>::value>
{ };
// function (plain function (pointer), boost and std function templates)
template <typename T>
struct lua_type_id<T,
typename std::enable_if<
detail::is_plain_function<T>::value ||
std::is_member_function_pointer<T>::value>::type>
: std::integral_constant<int, LUA_TFUNCTION> {};
template <template <class> class FObj, typename R, typename... Args>
struct lua_type_id<FObj<R(Args...)>>
: std::integral_constant<int, LUA_TFUNCTION> {};
template <> struct lua_type_id<raw_function>
: std::integral_constant<int, LUA_TFUNCTION> {};
} // namespace detail
template <typename T, typename Enable=void>
struct convert_cref_by_val: std::integral_constant<bool,
detail::lua_type_id<T>::value != LUA_TUSERDATA>
{};
// Const references to primitive types are handled as non-references.
template<typename T>
struct converter<T, typename std::enable_if<
detail::is_const_reference<T>::value &&
convert_cref_by_val<typename detail::remove_qualifiers<T>::type>::value
>::type
>: converter<typename detail::remove_qualifiers<T>::type>
{};
template <typename T>
using push_converter_for = converter<
typename detail::remove_qualifiers<T>::type>;
template <typename T>
using pull_converter_for = converter<typename std::remove_cv<T>::type>;
namespace detail {
inline int push_impl(lua_State*)
{
return 0;
}
template <typename Head, typename... Tail>
int push_impl(lua_State* L, Head&& head, Tail&&... tail)
{
int const n_pushed = push_converter_for<Head>().push(
L, std::forward<Head>(head));
return n_pushed + push_impl(L, std::forward<Tail>(tail)...);
}
} // namespace detail
template <typename T, typename... MoreTs>
int push(lua_State* L, T&& v, MoreTs&&... more)
{
return detail::push_impl(L,
std::forward<T>(v), std::forward<MoreTs>(more)...);
}
namespace detail {
failure_t converter_has_idx_param_impl(...);
template <typename Converter>
auto converter_has_idx_param_impl(Converter conv)
-> decltype(conv.n_conversion_steps(
std::declval<lua_State*>(), 0, std::declval<int*>()));
template <typename Converter>
struct converter_has_idx_param: std::integral_constant<bool, !has_failed<
decltype(converter_has_idx_param_impl(std::declval<Converter>()))
>::value>
{};
}
template <typename Converter>
typename std::enable_if<
!detail::converter_has_idx_param<Converter>::value,
to_type_of<Converter>>::type
unchecked_to_with(
Converter&& conv, lua_State* L, int idx, int* next_idx = nullptr)
{
(void)conv; // Silence MSVC.
if (next_idx)
*next_idx = idx + conv.n_consumed;
return conv.to(L, idx);
}
template <typename Converter>
typename std::enable_if<
detail::converter_has_idx_param<Converter>::value,
to_type_of<Converter>>::type
unchecked_to_with(
Converter&& conv, lua_State* L, int idx, int* next_idx = nullptr)
{
return conv.to(L, idx, next_idx);
}
template <typename T>
to_type_of<pull_converter_for<T>> unchecked_to(lua_State* L, int idx)
{
return unchecked_to_with(pull_converter_for<T>(), L, idx);
}
template <typename Converter>
typename std::enable_if<
!detail::converter_has_idx_param<Converter>::value,
unsigned>::type
n_conversion_steps_with(
Converter&& conv, lua_State* L, int idx, int* next_idx = nullptr)
{
(void)conv;
if (next_idx)
*next_idx = idx + conv.n_consumed;
return conv.n_conversion_steps(L, idx);
}
template <typename Converter>
typename std::enable_if<
detail::converter_has_idx_param<Converter>::value,
unsigned>::type
n_conversion_steps_with(
Converter&& conv, lua_State* L, int idx, int* next_idx = nullptr)
{
return conv.n_conversion_steps(L, idx, next_idx);
}
template <typename T>
unsigned n_conversion_steps(lua_State* L, int idx)
{
return n_conversion_steps_with(pull_converter_for<T>(), L, idx);
}
template <typename Converter>
bool is_convertible_with(Converter const& conv, lua_State* L, int idx)
{
(void)conv; // Silence MSVC.
return n_conversion_steps_with(conv, L, idx) != no_conversion;
}
template <typename T>
bool is_convertible(lua_State* L, int idx)
{
return is_convertible_with(pull_converter_for<T>(), L, idx);
}
template <typename Converter>
to_type_of<Converter> to_with(
Converter&& conv, lua_State* L, int idx, int* next_idx = nullptr)
{
if (!is_convertible_with(conv, L, idx)) {
BOOST_THROW_EXCEPTION(to_cpp_conversion_error()
<< boost::errinfo_type_info_name(
boost::typeindex::type_id<to_type_of<Converter>>()
.pretty_name())
<< errinfo::msg("conversion from Lua to C++ failed")
<< errinfo::stack_index(idx)
<< errinfo::lua_state(L));
}
return unchecked_to_with(conv, L, idx, next_idx);
}
template <typename T>
to_type_of<pull_converter_for<T>> to(lua_State* L, int idx)
{
return to_with(pull_converter_for<T>(), L, idx);
}
// Cannot use function here, it would potentially return a reference to local.
#define APOLLO_TO_ARG(L, idx, ...) \
::apollo::unwrap_ref(::apollo::to<__VA_ARGS__>(L, idx))
template <typename T>
to_type_of<pull_converter_for<T>> to(lua_State* L, int idx, T&& fallback)
{
if (!is_convertible<T>(L, idx))
return std::forward<T>(fallback);
return unchecked_to<T>(L, idx);
}
} // namepace apollo
#endif // APOLLO_CONVERTERS_HPP_INCLUDED
|
Fix forwarding in to() with fallback.
|
Fix forwarding in to() with fallback.
|
C++
|
bsd-2-clause
|
Oberon00/apollo,Oberon00/apollo
|
1a268c26c641ea85443a1a86670d3a9f58da22e9
|
src/functiontype.cpp
|
src/functiontype.cpp
|
/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#include <qitype/signature.hpp>
#include <qitype/functiontype.hpp>
#include <qitype/functiontypefactory.hpp>
qiLogCategory("qitype.functiontype");
namespace qi
{
GenericValuePtr callManyArgs(FunctionType* type, void* func,
const std::vector<GenericValuePtr>& args)
{
const std::vector<Type*>& target = type->argumentsType();
void** convertedArgs = new void*[args.size()];
std::vector<GenericValuePtr> toDestroy;
for (unsigned i=0; i<target.size(); ++i)
{
//qiLogDebug() << "argument " << i
// << " " << args[i].type->infoString() << ' ' << args[i].value
// << " to " << target[i]->infoString();
if (args[i].type == target[i] || args[i].type->info() == target[i]->info())
convertedArgs[i] = args[i].value;
else
{
//qiLogDebug() << "needs conversion "
//<< args[i].type->infoString() << " -> "
//<< target[i]->infoString();
std::pair<GenericValuePtr,bool> v = args[i].convert(target[i]);
if (v.second)
toDestroy.push_back(v.first);
convertedArgs[i] = v.first.value;
}
}
void* res = type->call(func, convertedArgs, args.size());
GenericValuePtr result;
result.type = type->resultType();
result.value = res;
for (unsigned i=0; i<toDestroy.size(); ++i)
toDestroy[i].destroy();
delete[] convertedArgs;
return result;
}
GenericValuePtr FunctionType::call(void* func,
const std::vector<GenericValuePtr>& args)
{
unsigned argsSize = args.size();
if (argsSize > 8)
return callManyArgs(this, func, args);
const std::vector<Type*>& target = argumentsType();
void* stackArgs[8];
void** convertedArgs = stackArgs;
GenericValuePtr toDestroy[8];
unsigned int toDestroyPos = 0;
for (unsigned i=0; i<argsSize; ++i)
{
//qiLogDebug() << "argument " << i
// << " " << args[i].type->infoString() << ' ' << args[i].value
// << " to " << target[i]->infoString();
if (args[i].type == target[i] || args[i].type->info() == target[i]->info())
convertedArgs[i] = args[i].value;
else
{
//qiLogDebug() << "needs conversion "
//<< args[i].type->infoString() << " -> "
//<< target[i]->infoString();
std::pair<GenericValuePtr,bool> v = args[i].convert(target[i]);
if (!v.first.type)
{
qiLogError() << "Conversion failure from " << args[i].type->infoString()
<< " to " << target[i]->infoString() <<", aborting call";
return GenericValuePtr();
}
if (v.second)
toDestroy[toDestroyPos++] = v.first;
convertedArgs[i] = v.first.value;
}
}
void* res = call(func, convertedArgs, argsSize);
GenericValuePtr result;
result.type = resultType();
result.value = res;
for (unsigned i=0; i<toDestroyPos; ++i)
toDestroy[i].destroy();
return result;
}
std::string CallableType::signature() const
{
std::string res("(");
for (unsigned i=0; i<_argumentsType.size(); ++i)
res += _argumentsType[i]->signature();
res += ')';
return res;
}
std::string CallableType::sigreturn() const
{
return _resultType->signature();
}
GenericFunctionParameters::GenericFunctionParameters()
{
}
GenericFunctionParameters::GenericFunctionParameters(const std::vector<GenericValuePtr>& args)
:std::vector<GenericValuePtr>(args)
{
}
GenericFunctionParameters GenericFunctionParameters::copy(bool notFirst) const
{
GenericFunctionParameters result(*this);
for (unsigned i=notFirst?1:0; i<size(); ++i)
result[i] = result[i].clone();
return result;
}
void GenericFunctionParameters::destroy(bool notFirst)
{
for (unsigned i = notFirst ? 1 : 0; i < size(); ++i)
(*this)[i].destroy();
}
GenericFunctionParameters
GenericFunctionParameters::convert(const Signature& sig) const
{
GenericFunctionParameters dst;
const std::vector<GenericValuePtr>& src = *this;
if (sig.size() != src.size())
{
qiLogError() << "convert: signature/params size mismatch"
<< sig.toString() << " " << sig.size() << " " << src.size();
return dst;
}
Signature::iterator it = sig.begin();
int idx = 0;
for (;it != sig.end(); ++it,++idx)
{
Type* compatible = qi::Type::fromSignature(*it);
if (!compatible)
{
qiLogError() <<"convert: unknown type " << *it;
compatible = src[idx].type;
}
dst.push_back(src[idx].convertCopy(compatible));
}
return dst;
}
// GenericFunctionParameters
// GenericFunctionParameters::fromBuffer(const Signature& sig, const qi::Buffer& buffer)
// {
// GenericFunctionParameters result;
// IDataStream in(buffer);
// Signature::iterator it = sig.begin();
// while (it != sig.end())
// {
// Type* compatible = qi::Type::fromSignature(*it);
// if (!compatible)
// {
// qiLogError() <<"fromBuffer: unknown type " << *it;
// throw std::runtime_error("Could not construct type for " + *it);
// }
// result.push_back(compatible->deserialize(in));
// ++it;
// }
// return result;
// }
// Buffer GenericFunctionParameters::toBuffer() const
// {
// Buffer buf;
// ODataStream out(buf);
// for (unsigned i=0; i<size(); ++i)
// (*this)[i].serialize(out);
// return buf;
// }
class DynamicFunctionType: public FunctionType
{
public:
virtual void* call(void* func, void** args, unsigned int argc)
{
qiLogError() << "Dynamic function called without type information";
return 0;
}
virtual GenericValuePtr call(void* func, const std::vector<GenericValuePtr>& args)
{
DynamicFunction* f = (DynamicFunction*)func;
return (*f)(args);
}
_QI_BOUNCE_TYPE_METHODS(DefaultTypeImplMethods<DynamicFunction>);
};
FunctionType* dynamicFunctionType()
{
static FunctionType* type = 0;
if (!type)
type = new DynamicFunctionType();
return type;
}
GenericFunction makeDynamicGenericFunction(DynamicFunction f)
{
GenericFunction result;
result.type = dynamicFunctionType();
result.value = result.type->clone(result.type->initializeStorage(&f));
return result;
}
}
|
/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#include <qitype/signature.hpp>
#include <qitype/functiontype.hpp>
#include <qitype/functiontypefactory.hpp>
qiLogCategory("qitype.functiontype");
namespace qi
{
GenericValuePtr callManyArgs(FunctionType* type, void* func,
const std::vector<GenericValuePtr>& args)
{
const std::vector<Type*>& target = type->argumentsType();
if (target.size() != args.size())
{
qiLogErrorF("Argument count mismatch, expected %s, got %s",
target.size(), args.size());
return GenericValuePtr();
}
void** convertedArgs = new void*[args.size()];
std::vector<GenericValuePtr> toDestroy;
for (unsigned i=0; i<target.size(); ++i)
{
//qiLogDebug() << "argument " << i
// << " " << args[i].type->infoString() << ' ' << args[i].value
// << " to " << target[i]->infoString();
if (args[i].type == target[i] || args[i].type->info() == target[i]->info())
convertedArgs[i] = args[i].value;
else
{
//qiLogDebug() << "needs conversion "
//<< args[i].type->infoString() << " -> "
//<< target[i]->infoString();
std::pair<GenericValuePtr,bool> v = args[i].convert(target[i]);
if (v.second)
toDestroy.push_back(v.first);
convertedArgs[i] = v.first.value;
}
}
void* res = type->call(func, convertedArgs, args.size());
GenericValuePtr result;
result.type = type->resultType();
result.value = res;
for (unsigned i=0; i<toDestroy.size(); ++i)
toDestroy[i].destroy();
delete[] convertedArgs;
return result;
}
GenericValuePtr FunctionType::call(void* func,
const std::vector<GenericValuePtr>& args)
{
unsigned argsSize = args.size();
if (argsSize > 8)
return callManyArgs(this, func, args);
const std::vector<Type*>& target = argumentsType();
if (target.size() != args.size())
{
qiLogErrorF("Argument count mismatch, expected %s, got %s",
target.size(), args.size());
return GenericValuePtr();
}
void* stackArgs[8];
void** convertedArgs = stackArgs;
GenericValuePtr toDestroy[8];
unsigned int toDestroyPos = 0;
for (unsigned i=0; i<argsSize; ++i)
{
//qiLogDebug() << "argument " << i
// << " " << args[i].type->infoString() << ' ' << args[i].value
// << " to " << target[i]->infoString();
if (args[i].type == target[i] || args[i].type->info() == target[i]->info())
convertedArgs[i] = args[i].value;
else
{
//qiLogDebug() << "needs conversion "
//<< args[i].type->infoString() << " -> "
//<< target[i]->infoString();
std::pair<GenericValuePtr,bool> v = args[i].convert(target[i]);
if (!v.first.type)
{
qiLogError() << "Conversion failure from " << args[i].type->infoString()
<< " to " << target[i]->infoString() <<", aborting call";
return GenericValuePtr();
}
if (v.second)
toDestroy[toDestroyPos++] = v.first;
convertedArgs[i] = v.first.value;
}
}
void* res = call(func, convertedArgs, argsSize);
GenericValuePtr result;
result.type = resultType();
result.value = res;
for (unsigned i=0; i<toDestroyPos; ++i)
toDestroy[i].destroy();
return result;
}
std::string CallableType::signature() const
{
std::string res("(");
for (unsigned i=0; i<_argumentsType.size(); ++i)
res += _argumentsType[i]->signature();
res += ')';
return res;
}
std::string CallableType::sigreturn() const
{
return _resultType->signature();
}
GenericFunctionParameters::GenericFunctionParameters()
{
}
GenericFunctionParameters::GenericFunctionParameters(const std::vector<GenericValuePtr>& args)
:std::vector<GenericValuePtr>(args)
{
}
GenericFunctionParameters GenericFunctionParameters::copy(bool notFirst) const
{
GenericFunctionParameters result(*this);
for (unsigned i=notFirst?1:0; i<size(); ++i)
result[i] = result[i].clone();
return result;
}
void GenericFunctionParameters::destroy(bool notFirst)
{
for (unsigned i = notFirst ? 1 : 0; i < size(); ++i)
(*this)[i].destroy();
}
GenericFunctionParameters
GenericFunctionParameters::convert(const Signature& sig) const
{
GenericFunctionParameters dst;
const std::vector<GenericValuePtr>& src = *this;
if (sig.size() != src.size())
{
qiLogError() << "convert: signature/params size mismatch"
<< sig.toString() << " " << sig.size() << " " << src.size();
return dst;
}
Signature::iterator it = sig.begin();
int idx = 0;
for (;it != sig.end(); ++it,++idx)
{
Type* compatible = qi::Type::fromSignature(*it);
if (!compatible)
{
qiLogError() <<"convert: unknown type " << *it;
compatible = src[idx].type;
}
dst.push_back(src[idx].convertCopy(compatible));
}
return dst;
}
// GenericFunctionParameters
// GenericFunctionParameters::fromBuffer(const Signature& sig, const qi::Buffer& buffer)
// {
// GenericFunctionParameters result;
// IDataStream in(buffer);
// Signature::iterator it = sig.begin();
// while (it != sig.end())
// {
// Type* compatible = qi::Type::fromSignature(*it);
// if (!compatible)
// {
// qiLogError() <<"fromBuffer: unknown type " << *it;
// throw std::runtime_error("Could not construct type for " + *it);
// }
// result.push_back(compatible->deserialize(in));
// ++it;
// }
// return result;
// }
// Buffer GenericFunctionParameters::toBuffer() const
// {
// Buffer buf;
// ODataStream out(buf);
// for (unsigned i=0; i<size(); ++i)
// (*this)[i].serialize(out);
// return buf;
// }
class DynamicFunctionType: public FunctionType
{
public:
virtual void* call(void* func, void** args, unsigned int argc)
{
qiLogError() << "Dynamic function called without type information";
return 0;
}
virtual GenericValuePtr call(void* func, const std::vector<GenericValuePtr>& args)
{
DynamicFunction* f = (DynamicFunction*)func;
return (*f)(args);
}
_QI_BOUNCE_TYPE_METHODS(DefaultTypeImplMethods<DynamicFunction>);
};
FunctionType* dynamicFunctionType()
{
static FunctionType* type = 0;
if (!type)
type = new DynamicFunctionType();
return type;
}
GenericFunction makeDynamicGenericFunction(DynamicFunction f)
{
GenericFunction result;
result.type = dynamicFunctionType();
result.value = result.type->clone(result.type->initializeStorage(&f));
return result;
}
}
|
Handle argument count mismatch.
|
FunctionType::call: Handle argument count mismatch.
Change-Id: I4af661b55f48ac0fc52bdb2681fac1e2cee391da
Reviewed-on: http://gerrit.aldebaran.lan:8080/13534
Reviewed-by: cgestes <[email protected]>
Reviewed-by: mnottale <[email protected]>
Tested-by: mnottale <[email protected]>
|
C++
|
bsd-3-clause
|
vbarbaresi/libqi,aldebaran/libqi,bsautron/libqi,aldebaran/libqi,aldebaran/libqi
|
4199d0f43d29658347a68c07b10253be2830ad4f
|
jpegenc/jpegenc/segments/JPEGSegments.cpp
|
jpegenc/jpegenc/segments/JPEGSegments.cpp
|
//
// JPEGImage.cpp
// jpegenc
//
// Created by Christian Braun on 16/11/16.
// Copyright © 2016 FHWS. All rights reserved.
//
#include "JPEGSegments.hpp"
#include <iostream>
#include "../Quantization.hpp"
#include "../dct/Arai.hpp"
#include "ImageDataEncoding.hpp"
using namespace JPEGSegments;
void APP0::addToStream(Bitstream &stream) {
stream.add(type, 16);
stream.add(length, 16);
stream.add(JFIF[0], 8);
stream.add(JFIF[1], 8);
stream.add(JFIF[2], 8);
stream.add(JFIF[3], 8);
stream.add(JFIF[4], 8);
stream.add(MAJOR_REVISION_NUMBER, 8);
stream.add(MINOR_REVISION_NUMBER, 8);
stream.add(PIXEL_UNIT, 8);
stream.add(X_DENSITY, 16);
stream.add(Y_DENSITY, 16);
stream.add(PREVIEW_WIDTH, 8);
stream.add(PREVIEW_HEIGHT, 8);
}
void StartOfFrame0::addToStream(Bitstream &stream) {
stream.add(type, 16);
stream.add(length, 16);
stream.add(precision, 8);
stream.add(height, 16);
stream.add(width, 16);
stream.add(numberOfComponents, 8);
while (numberOfComponents--) {
stream.add(0x01, 8); // ID (Y)
stream.add(0x22, 8); // Subsampling
stream.add(0x00, 8); // Quantisierungstabelle
}
}
void StartOfImage::addToStream(Bitstream &stream) {
stream.add(type, 16);
}
void EndOfImage::addToStream(Bitstream &stream) {
stream.add(type, 16);
}
void DefineHuffmanTable::addToStream(Bitstream &stream) {
stream.add(type, 16);
stream.add(length, 16);
addTableData(0, 0, Y_DC, stream);
addTableData(1, 1, Y_AC, stream);
addTableData(2, 0, CbCr_DC, stream);
addTableData(3, 1, CbCr_AC, stream);
}
void DefineHuffmanTable::addTableData(uint8_t htNumber, uint8_t htType, EncodingTable table, Bitstream &stream) {
// HT Information
stream.add(htNumber, 4);
stream.add(htType, 1);
stream.add(0, 3); // rest
// number of symbols per level
unsigned char symbolsPerLevel[16] = {0};
for (const std::pair<Symbol, Encoding> &encoding : table) {
unsigned short numberOfBits = encoding.second.numberOfBits;
symbolsPerLevel[numberOfBits - 1] += 1;
}
for (int i = 0; i < 16; ++i) {
stream.add(symbolsPerLevel[i], 8);
}
for (const std::pair<Symbol, Encoding> &encoding : table) {
stream.add(encoding.first, 8);
}
}
void DefineQuantizationTable::addToStream(Bitstream &stream) {
stream.add(type, 16);
stream.add(length, 16);
stream.add(qt_number, 4); // 0 = Y
stream.add(precision, 4);
for (int i = 0; i < 64; ++i) {
stream.add(table[i], 8);
}
}
void StartOfScan::addToStream(Bitstream &stream) {
stream.add(type, 16);
stream.add(length, 16);
stream.add(numberOfComponents, 8);
//todo add components
//stream.add(ignorableBytes, 24);
}
void JPEGWriter::writeJPEGImage(std::shared_ptr<Image> image, const char *pathToFile) {
const uint8_t *luminanceQT = Quantization::getLuminanceQT();
const uint8_t *chrominanceQT = Quantization::getChrominanceQT();
StartOfImage* soi = new StartOfImage();
segments.push_back(soi);
APP0* app0 = new APP0();
segments.push_back(app0);
DefineQuantizationTable* Y_dqt = new DefineQuantizationTable(0, 0, luminanceQT);
segments.push_back(Y_dqt);
DefineQuantizationTable* CbCr_dqt = new DefineQuantizationTable(1, 0, chrominanceQT);
segments.push_back(CbCr_dqt);
StartOfFrame0* sof0 = new StartOfFrame0(1, image); // 1 = numberOfComponents
segments.push_back(sof0);
float *copyOfChannel1 = new float[image->channel1->numberOfPixel()];
float *copyOfChannel2 = new float[image->channel2->numberOfPixel()];
float *copyOfChannel3 = new float[image->channel3->numberOfPixel()];
memcpy(copyOfChannel1, image->channel1, image->channel1->numberOfPixel() * sizeof(float));
memcpy(copyOfChannel2, image->channel2, image->channel2->numberOfPixel() * sizeof(float));
memcpy(copyOfChannel3, image->channel3, image->channel3->numberOfPixel() * sizeof(float));
Arai::transform(copyOfChannel1, image->channel1->imageSize.width, image->channel1->imageSize.height);
Arai::transform(copyOfChannel2, image->channel2->imageSize.width, image->channel2->imageSize.height);
Arai::transform(copyOfChannel3, image->channel3->imageSize.width, image->channel3->imageSize.height);
Quantization::run(copyOfChannel1, image->channel1->imageSize.width, image->channel1->imageSize.height, luminanceQT);
Quantization::run(copyOfChannel2, image->channel2->imageSize.width, image->channel2->imageSize.height, chrominanceQT);
Quantization::run(copyOfChannel3, image->channel3->imageSize.width, image->channel3->imageSize.height, chrominanceQT);
ImageDataEncoding channel1Encoder(copyOfChannel1, image->channel1->imageSize.width, image->channel1->imageSize.height);
ImageDataEncoding channel2Encoder(copyOfChannel2, image->channel2->imageSize.width, image->channel2->imageSize.height);
ImageDataEncoding channel3Encoder(copyOfChannel3, image->channel3->imageSize.width, image->channel3->imageSize.height);
channel1Encoder.init();
channel2Encoder.init();
channel3Encoder.init();
std::vector<Encoding> Y_DC_encoding;
auto Y_DC = channel1Encoder.generateDCEncodingTable(Y_DC_encoding);
std::vector<uint8_t> Y_AC_byteReps;
std::vector<Encoding> Y_AC_encoding;
auto Y_AC = channel1Encoder.generateACEncodingTable(Y_AC_byteReps, Y_AC_encoding);
std::vector<Encoding> Cb_DC_encoding = channel2Encoder.differenceEncoding();
std::vector<Encoding> Cr_DC_encoding = channel3Encoder.differenceEncoding();
Huffman DC_huffman;
for (auto ¤t : Cb_DC_encoding) {
DC_huffman.addSymbol(current.numberOfBits);
}
for (auto ¤t : Cr_DC_encoding) {
DC_huffman.addSymbol(current.numberOfBits);
}
DC_huffman.generateNodeList();
auto CbCr_DC = DC_huffman.canonicalEncoding(16);
std::vector<Encoding> Cb_AC_encoding;
std::vector<Encoding> Cr_AC_encoding;
std::vector<uint8_t> Cb_AC_byteReps;
std::vector<uint8_t> Cr_AC_byteReps;
channel2Encoder.runLengthEncoding(Cb_AC_byteReps, Cb_AC_encoding);
channel3Encoder.runLengthEncoding(Cr_AC_byteReps, Cr_AC_encoding);
Huffman AC_huffman;
for (auto ¤t : Cb_AC_byteReps)
{
AC_huffman.addSymbol(current);
}
for (auto ¤t : Cr_AC_byteReps)
{
AC_huffman.addSymbol(current);
}
AC_huffman.generateNodeList();
auto CbCr_AC = AC_huffman.canonicalEncoding(16);
DefineHuffmanTable* dht = new DefineHuffmanTable(Y_DC, Y_AC, CbCr_DC, CbCr_AC);
segments.push_back(dht);
// sos
EndOfImage* eoi = new EndOfImage();
segments.push_back(eoi);
for (size_t i = 0; i < segments.size(); ++i) {
segments[i]->addToStream(stream);
}
stream.saveToFile(pathToFile);
}
|
//
// JPEGImage.cpp
// jpegenc
//
// Created by Christian Braun on 16/11/16.
// Copyright © 2016 FHWS. All rights reserved.
//
#include "JPEGSegments.hpp"
#include <iostream>
#include "../Quantization.hpp"
#include "../dct/Arai.hpp"
#include "ImageDataEncoding.hpp"
using namespace JPEGSegments;
void APP0::addToStream(Bitstream &stream) {
stream.add(type, 16);
stream.add(length, 16);
stream.add(JFIF[0], 8);
stream.add(JFIF[1], 8);
stream.add(JFIF[2], 8);
stream.add(JFIF[3], 8);
stream.add(JFIF[4], 8);
stream.add(MAJOR_REVISION_NUMBER, 8);
stream.add(MINOR_REVISION_NUMBER, 8);
stream.add(PIXEL_UNIT, 8);
stream.add(X_DENSITY, 16);
stream.add(Y_DENSITY, 16);
stream.add(PREVIEW_WIDTH, 8);
stream.add(PREVIEW_HEIGHT, 8);
}
void StartOfFrame0::addToStream(Bitstream &stream) {
stream.add(type, 16);
stream.add(length, 16);
stream.add(precision, 8);
stream.add(height, 16);
stream.add(width, 16);
stream.add(numberOfComponents, 8);
while (numberOfComponents--) {
stream.add(0x01, 8); // ID (Y)
stream.add(0x22, 8); // Subsampling
stream.add(0x00, 8); // Quantisierungstabelle
}
}
void StartOfImage::addToStream(Bitstream &stream) {
stream.add(type, 16);
}
void EndOfImage::addToStream(Bitstream &stream) {
stream.add(type, 16);
}
void DefineHuffmanTable::addToStream(Bitstream &stream) {
stream.add(type, 16);
stream.add(length, 16);
addTableData(0, 0, Y_DC, stream);
addTableData(1, 1, Y_AC, stream);
addTableData(2, 0, CbCr_DC, stream);
addTableData(3, 1, CbCr_AC, stream);
}
void DefineHuffmanTable::addTableData(uint8_t htNumber, uint8_t htType, EncodingTable table, Bitstream &stream) {
// HT Information
stream.add(0, 3); // rest
stream.add(htType, 1);
stream.add(htNumber, 4);
// number of symbols per level
unsigned char symbolsPerLevel[16] = {0};
for (const std::pair<Symbol, Encoding> &encoding : table) {
unsigned short numberOfBits = encoding.second.numberOfBits;
symbolsPerLevel[numberOfBits - 1] += 1;
}
for (int i = 0; i < 16; ++i) {
stream.add(symbolsPerLevel[i], 8);
}
for (const std::pair<Symbol, Encoding> &encoding : table) {
stream.add(encoding.first, 8);
}
}
void DefineQuantizationTable::addToStream(Bitstream &stream) {
stream.add(type, 16);
stream.add(length, 16);
stream.add(precision, 4);
stream.add(qt_number, 4);
for (int i = 0; i < 64; ++i) {
stream.add(table[i], 8);
}
}
void StartOfScan::addToStream(Bitstream &stream) {
stream.add(type, 16);
stream.add(length, 16);
stream.add(numberOfComponents, 8);
//todo add components
//stream.add(ignorableBytes, 24);
}
void JPEGWriter::writeJPEGImage(std::shared_ptr<Image> image, const char *pathToFile) {
const uint8_t *luminanceQT = Quantization::getLuminanceQT();
const uint8_t *chrominanceQT = Quantization::getChrominanceQT();
StartOfImage* soi = new StartOfImage();
segments.push_back(soi);
APP0* app0 = new APP0();
segments.push_back(app0);
DefineQuantizationTable* Y_dqt = new DefineQuantizationTable(0, 0, luminanceQT);
segments.push_back(Y_dqt);
DefineQuantizationTable* CbCr_dqt = new DefineQuantizationTable(1, 0, chrominanceQT);
segments.push_back(CbCr_dqt);
StartOfFrame0* sof0 = new StartOfFrame0(1, image); // 1 = numberOfComponents
segments.push_back(sof0);
float *copyOfChannel1 = new float[image->channel1->numberOfPixel()];
float *copyOfChannel2 = new float[image->channel2->numberOfPixel()];
float *copyOfChannel3 = new float[image->channel3->numberOfPixel()];
memcpy(copyOfChannel1, image->channel1, image->channel1->numberOfPixel() * sizeof(float));
memcpy(copyOfChannel2, image->channel2, image->channel2->numberOfPixel() * sizeof(float));
memcpy(copyOfChannel3, image->channel3, image->channel3->numberOfPixel() * sizeof(float));
Arai::transform(copyOfChannel1, image->channel1->imageSize.width, image->channel1->imageSize.height);
Arai::transform(copyOfChannel2, image->channel2->imageSize.width, image->channel2->imageSize.height);
Arai::transform(copyOfChannel3, image->channel3->imageSize.width, image->channel3->imageSize.height);
Quantization::run(copyOfChannel1, image->channel1->imageSize.width, image->channel1->imageSize.height, luminanceQT);
Quantization::run(copyOfChannel2, image->channel2->imageSize.width, image->channel2->imageSize.height, chrominanceQT);
Quantization::run(copyOfChannel3, image->channel3->imageSize.width, image->channel3->imageSize.height, chrominanceQT);
ImageDataEncoding channel1Encoder(copyOfChannel1, image->channel1->imageSize.width, image->channel1->imageSize.height);
ImageDataEncoding channel2Encoder(copyOfChannel2, image->channel2->imageSize.width, image->channel2->imageSize.height);
ImageDataEncoding channel3Encoder(copyOfChannel3, image->channel3->imageSize.width, image->channel3->imageSize.height);
channel1Encoder.init();
channel2Encoder.init();
channel3Encoder.init();
std::vector<Encoding> Y_DC_encoding;
auto Y_DC = channel1Encoder.generateDCEncodingTable(Y_DC_encoding);
std::vector<uint8_t> Y_AC_byteReps;
std::vector<Encoding> Y_AC_encoding;
auto Y_AC = channel1Encoder.generateACEncodingTable(Y_AC_byteReps, Y_AC_encoding);
std::vector<Encoding> Cb_DC_encoding = channel2Encoder.differenceEncoding();
std::vector<Encoding> Cr_DC_encoding = channel3Encoder.differenceEncoding();
Huffman DC_huffman;
for (auto ¤t : Cb_DC_encoding) {
DC_huffman.addSymbol(current.numberOfBits);
}
for (auto ¤t : Cr_DC_encoding) {
DC_huffman.addSymbol(current.numberOfBits);
}
DC_huffman.generateNodeList();
auto CbCr_DC = DC_huffman.canonicalEncoding(16);
std::vector<Encoding> Cb_AC_encoding;
std::vector<Encoding> Cr_AC_encoding;
std::vector<uint8_t> Cb_AC_byteReps;
std::vector<uint8_t> Cr_AC_byteReps;
channel2Encoder.runLengthEncoding(Cb_AC_byteReps, Cb_AC_encoding);
channel3Encoder.runLengthEncoding(Cr_AC_byteReps, Cr_AC_encoding);
Huffman AC_huffman;
for (auto ¤t : Cb_AC_byteReps)
{
AC_huffman.addSymbol(current);
}
for (auto ¤t : Cr_AC_byteReps)
{
AC_huffman.addSymbol(current);
}
AC_huffman.generateNodeList();
auto CbCr_AC = AC_huffman.canonicalEncoding(16);
DefineHuffmanTable* dht = new DefineHuffmanTable(Y_DC, Y_AC, CbCr_DC, CbCr_AC);
segments.push_back(dht);
// sos
EndOfImage* eoi = new EndOfImage();
segments.push_back(eoi);
for (size_t i = 0; i < segments.size(); ++i) {
segments[i]->addToStream(stream);
}
stream.saveToFile(pathToFile);
}
|
Fix DQT segment
|
Fix DQT segment
|
C++
|
mit
|
relikd/jpeg-encoder,relikd/jpeg-encoder
|
a21ef72a13bc49d6097d1881ecca6bbf4df7bc97
|
OVR_SDL2_app.cpp
|
OVR_SDL2_app.cpp
|
// Copyright (c) 2014 Robert Kooima
//
// 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 "OVR_SDL2_app.hpp"
//------------------------------------------------------------------------------
/// Initialize an OVR HMD and SDL2 window.
OVR_SDL2_app::OVR_SDL2_app() : hmd(0), eye(ovrEye_Left), window(0)
{
if (init_OVR())
{
running = init_SDL(hmd->WindowsPos.x,
hmd->WindowsPos.y,
hmd->Resolution.w,
hmd->Resolution.h);
conf_OVR();
}
}
/// Finalize the SDL and OVR.
OVR_SDL2_app::~OVR_SDL2_app()
{
if (buffer[1]) delete buffer[1];
if (buffer[0]) delete buffer[0];
if (context) SDL_GL_DeleteContext(context);
if (window) SDL_DestroyWindow(window);
if (hmd) ovrHmd_Destroy(hmd);
ovr_Shutdown();
}
//------------------------------------------------------------------------------
/// Initialize an SDL window and GL context with the given position and size.
bool OVR_SDL2_app::init_SDL(int x, int y, int w, int h)
{
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER) == 0)
{
int f = SDL_WINDOW_BORDERLESS | SDL_WINDOW_OPENGL;
// Choose an OpenGL 3.2 Core Profile. This choice is arbitrary, and
// any later version supported by the hardware may be substituted.
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,
SDL_GL_CONTEXT_PROFILE_CORE);
// Configure 24-bit color and 24-bit depth. This is a common choice,
// but may be altered as needed.
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
// Create the window and initialize the OpenGL context.
if ((window = SDL_CreateWindow("OVR_SDL2", x, y, w, h, f)))
{
context = SDL_GL_CreateContext(window);
SDL_GameControllerEventState(SDL_ENABLE);
#ifdef GLEW_VERSION
glewExperimental = GL_TRUE;
glewInit();
#endif
return true;
}
}
return false;
}
/// Initialize the Oculus SDK and return success.
bool OVR_SDL2_app::init_OVR()
{
ovr_Initialize();
// Use the first connected HMD.
hmd = ovrHmd_Create(0);
// Fall back on a DK1 debug configuration if no HMD is available.
if (hmd == 0)
hmd = ovrHmd_CreateDebug(ovrHmd_DK1);
// Enable all tracking capabilities on this HMD.
if (hmd)
ovrHmd_ConfigureTracking(hmd, ovrTrackingCap_Orientation |
ovrTrackingCap_MagYawCorrection |
ovrTrackingCap_Position, 0);
return (hmd != 0);
}
/// Configure the Oculus SDK renderer. This requires the presence of OpenGL
/// state, so it much be performed AFTER the SDL window has been created.
void OVR_SDL2_app::conf_OVR()
{
// Configure the renderer. Zeroing the configuration stucture causes all
// display, window, and device specifications to take on current values
// as put in place by SDL. This trick works cross-platform, freeing us
// from dealing with any platform issues.
ovrGLConfig cfg;
memset(&cfg, 0, sizeof (ovrGLConfig));
cfg.OGL.Header.API = ovrRenderAPI_OpenGL;
cfg.OGL.Header.RTSize.w = hmd->Resolution.w;
cfg.OGL.Header.RTSize.h = hmd->Resolution.h;
// Set the configuration and receive eye render descriptors in return.
ovrHmd_ConfigureRendering(hmd, &cfg.Config, ovrDistortionCap_Chromatic
| ovrDistortionCap_TimeWarp
| ovrDistortionCap_Overdrive,
hmd->DefaultEyeFov, erd);
offset[0] = erd[0].HmdToEyeViewOffset;
offset[1] = erd[1].HmdToEyeViewOffset;
// Determine the buffer size required by each eye of the current HMD.
ovrSizei size[2];
size[0] = ovrHmd_GetFovTextureSize(hmd, ovrEye_Left, hmd->DefaultEyeFov[0], 1);
size[1] = ovrHmd_GetFovTextureSize(hmd, ovrEye_Right, hmd->DefaultEyeFov[1], 1);
// Initialize the off-screen render buffers. We're using one buffer per-eye
// instead of concatenating both eyes into a single buffer.
for (int i = 0; i < 2; i++)
{
if ((buffer[i] = new framebuffer(size[i].w, size[i].h)))
{
ovrGLTexture *p = reinterpret_cast<ovrGLTexture*>(tex + i);
memset(p, 0, sizeof (ovrGLTexture));
p->OGL.Header.API = ovrRenderAPI_OpenGL;
p->OGL.Header.TextureSize = size[i];
p->OGL.Header.RenderViewport.Size = size[i];
p->OGL.TexId = buffer[i]->color;
}
}
}
//------------------------------------------------------------------------------
/// Application main loop.
void OVR_SDL2_app::run()
{
SDL_Event e;
while (running)
{
// Dispatch all pending SDL events.
while (SDL_PollEvent(&e))
dispatch(e);
// Let the application animate.
step();
// Render both views and let the Oculus SDK display them on-screen.
// 'eye' is a private member variable that notes which eye is being
// rendered. This is used when the application calls back down to
// learn the view and projection matrices.
ovrHmd_BeginFrame(hmd, 0);
{
ovrHmd_GetEyePoses(hmd, 0, offset, pose, NULL);
for (int i = 0; i < 2; i++)
{
eye = hmd->EyeRenderOrder[i];
buffer[eye]->bind();
draw();
}
}
ovrHmd_EndFrame(hmd, pose, tex);
}
}
/// Dispatch an SDL event.
void OVR_SDL2_app::dispatch(SDL_Event& e)
{
switch (e.type)
{
case SDL_KEYDOWN:
keyboard(e.key.keysym.scancode, true, (e.key.repeat != 0));
break;
case SDL_KEYUP:
keyboard(e.key.keysym.scancode, false, (e.key.repeat != 0));
break;
case SDL_MOUSEBUTTONDOWN:
mouse_button(e.button.button, true);
break;
case SDL_MOUSEBUTTONUP:
mouse_button(e.button.button, false);
break;
case SDL_MOUSEMOTION:
mouse_motion(e.motion.xrel, e.motion.yrel);
break;
case SDL_MOUSEWHEEL:
mouse_wheel(e.wheel.x, e.wheel.y);
break;
case SDL_CONTROLLERAXISMOTION:
game_axis(e.caxis.which, e.caxis.axis, e.caxis.value / 32768.f);
break;
case SDL_CONTROLLERBUTTONDOWN:
game_button(e.caxis.which, e.cbutton.button, true);
break;
case SDL_CONTROLLERBUTTONUP:
game_button(e.caxis.which, e.cbutton.button, false);
break;
case SDL_CONTROLLERDEVICEADDED:
game_connect(e.cdevice.which, true);
break;
case SDL_CONTROLLERDEVICEREMOVED:
game_connect(e.cdevice.which, false);
break;
case SDL_QUIT:
running = false;
break;
}
}
//------------------------------------------------------------------------------
/// Handle a key press or release.
void OVR_SDL2_app::keyboard(int key, bool down, bool repeat)
{
dismiss_warning();
if (key == SDL_SCANCODE_ESCAPE && down == false)
running = false;
}
/// Handle a mouse button press or release.
void OVR_SDL2_app::mouse_button(int button, bool down)
{
dismiss_warning();
}
/// Handle mouse wheel rotation.
void OVR_SDL2_app::mouse_wheel(int dx, int dy)
{
}
/// Handle mouse pointer motion.
void OVR_SDL2_app::mouse_motion(int x, int y)
{
}
/// Handle gamepad connection or disconnection
void OVR_SDL2_app::game_connect(int device, bool connected)
{
controller.resize(device + 1);
if (controller[device])
SDL_GameControllerClose(controller[device]);
if (connected)
controller[device] = SDL_GameControllerOpen(device);
else
controller[device] = 0;
}
/// Handle gamepad button press or release.
void OVR_SDL2_app::game_button(int device, int button, bool down)
{
dismiss_warning();
}
/// Handle gamepad axis motion.
void OVR_SDL2_app::game_axis(int device, int axis, float value)
{
}
//------------------------------------------------------------------------------
/// Convert an OVR matrix to a GLFundamentals matrix.
static mat4 getMatrix4f(const OVR::Matrix4f& m)
{
return mat4(m.M[0][0], m.M[0][1], m.M[0][2], m.M[0][3],
m.M[1][0], m.M[1][1], m.M[1][2], m.M[1][3],
m.M[2][0], m.M[2][1], m.M[2][2], m.M[2][3],
m.M[3][0], m.M[3][1], m.M[3][2], m.M[3][3]);
}
/// Return the current projection matrix as determined by the current OVR eye
/// render descriptor.
mat4 OVR_SDL2_app::projection() const
{
return getMatrix4f(ovrMatrix4f_Projection(erd[eye].Fov, 0.1f, 100.0f, true));
}
/// Return the current view matrix as determined by the current OVR eye render
/// descriptor and head pose.
mat4 OVR_SDL2_app::view() const
{
// Orientation of the head
OVR::Quatf q = OVR::Quatf(pose[eye].Orientation);
mat4 O = getMatrix4f(OVR::Matrix4f(q.Inverted()));
// Offset of the head from the center of the world
mat4 P = translation(vec3(-pose[eye].Position.x,
-pose[eye].Position.y,
-pose[eye].Position.z));
// return E * O * P;
return O * P;
}
//------------------------------------------------------------------------------
/// Check if the OVR health & safety warning is visible and try to dismiss it.
void OVR_SDL2_app::dismiss_warning()
{
ovrHSWDisplayState state;
ovrHmd_GetHSWDisplayState(hmd, &state);
if (state.Displayed)
ovrHmd_DismissHSWDisplay(hmd);
}
|
// Copyright (c) 2014 Robert Kooima
//
// 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 "OVR_SDL2_app.hpp"
#include <SDL2/SDL_syswm.h>
//------------------------------------------------------------------------------
/// Initialize an OVR HMD and SDL2 window.
OVR_SDL2_app::OVR_SDL2_app() : hmd(0), eye(ovrEye_Left), window(0)
{
if (init_OVR())
{
running = init_SDL(hmd->WindowsPos.x,
hmd->WindowsPos.y,
hmd->Resolution.w,
hmd->Resolution.h);
conf_OVR();
}
}
/// Finalize the SDL and OVR.
OVR_SDL2_app::~OVR_SDL2_app()
{
if (buffer[1]) delete buffer[1];
if (buffer[0]) delete buffer[0];
if (context) SDL_GL_DeleteContext(context);
if (window) SDL_DestroyWindow(window);
if (hmd) ovrHmd_Destroy(hmd);
ovr_Shutdown();
}
//------------------------------------------------------------------------------
/// Initialize an SDL window and GL context with the given position and size.
bool OVR_SDL2_app::init_SDL(int x, int y, int w, int h)
{
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER) == 0)
{
int f = SDL_WINDOW_BORDERLESS | SDL_WINDOW_OPENGL;
// Choose an OpenGL 3.2 Core Profile. This choice is arbitrary, and
// any later version supported by the hardware may be substituted.
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,
SDL_GL_CONTEXT_PROFILE_CORE);
// Configure 24-bit color and 24-bit depth. This is a common choice,
// but may be altered as needed.
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
// Create the window and initialize the OpenGL context.
if ((window = SDL_CreateWindow("OVR_SDL2", x, y, w, h, f)))
{
context = SDL_GL_CreateContext(window);
SDL_GameControllerEventState(SDL_ENABLE);
#ifdef GLEW_VERSION
glewExperimental = GL_TRUE;
glewInit();
#endif
return true;
}
}
return false;
}
/// Initialize the Oculus SDK and return success.
bool OVR_SDL2_app::init_OVR()
{
ovr_Initialize();
// Use the first connected HMD.
hmd = ovrHmd_Create(0);
// Fall back on a DK1 debug configuration if no HMD is available.
if (hmd == 0)
hmd = ovrHmd_CreateDebug(ovrHmd_DK1);
// Enable all tracking capabilities on this HMD.
if (hmd)
ovrHmd_ConfigureTracking(hmd, ovrTrackingCap_Orientation |
ovrTrackingCap_MagYawCorrection |
ovrTrackingCap_Position, 0);
return (hmd != 0);
}
/// Configure the Oculus SDK renderer. This requires the presence of OpenGL
/// state, so it much be performed AFTER the SDL window has been created.
void OVR_SDL2_app::conf_OVR()
{
// Configure the renderer. Zeroing the configuration stucture causes all
// display, window, and device specifications to take on current values
// as put in place by SDL. This should work cross-platform, but doesn't.
// A workaround is currently (0.4.3b) required under linux.
SDL_SysWMinfo info;
ovrGLConfig cfg;
memset(&info, 0, sizeof (SDL_SysWMinfo));
memset(&cfg, 0, sizeof (ovrGLConfig));
SDL_VERSION(&info.version);
SDL_GetWindowWMInfo(window, &info);
cfg.OGL.Header.API = ovrRenderAPI_OpenGL;
cfg.OGL.Header.RTSize.w = hmd->Resolution.w;
cfg.OGL.Header.RTSize.h = hmd->Resolution.h;
#ifdef __linux__
cfg.OGL.Disp = info.info.x11.display;
cfg.OGL.Win = info.info.x11.window;
#endif
// Set the configuration and receive eye render descriptors in return.
ovrHmd_ConfigureRendering(hmd, &cfg.Config, ovrDistortionCap_Chromatic
| ovrDistortionCap_TimeWarp
| ovrDistortionCap_Overdrive,
hmd->DefaultEyeFov, erd);
offset[0] = erd[0].HmdToEyeViewOffset;
offset[1] = erd[1].HmdToEyeViewOffset;
// Determine the buffer size required by each eye of the current HMD.
ovrSizei size[2];
size[0] = ovrHmd_GetFovTextureSize(hmd, ovrEye_Left, hmd->DefaultEyeFov[0], 1);
size[1] = ovrHmd_GetFovTextureSize(hmd, ovrEye_Right, hmd->DefaultEyeFov[1], 1);
// Initialize the off-screen render buffers. We're using one buffer per-eye
// instead of concatenating both eyes into a single buffer.
for (int i = 0; i < 2; i++)
{
if ((buffer[i] = new framebuffer(size[i].w, size[i].h)))
{
ovrGLTexture *p = reinterpret_cast<ovrGLTexture*>(tex + i);
memset(p, 0, sizeof (ovrGLTexture));
p->OGL.Header.API = ovrRenderAPI_OpenGL;
p->OGL.Header.TextureSize = size[i];
p->OGL.Header.RenderViewport.Size = size[i];
p->OGL.TexId = buffer[i]->color;
}
}
}
//------------------------------------------------------------------------------
/// Application main loop.
void OVR_SDL2_app::run()
{
SDL_Event e;
while (running)
{
// Dispatch all pending SDL events.
while (SDL_PollEvent(&e))
dispatch(e);
// Let the application animate.
step();
// Render both views and let the Oculus SDK display them on-screen.
// 'eye' is a private member variable that notes which eye is being
// rendered. This is used when the application calls back down to
// learn the view and projection matrices.
ovrHmd_BeginFrame(hmd, 0);
{
ovrHmd_GetEyePoses(hmd, 0, offset, pose, NULL);
for (int i = 0; i < 2; i++)
{
eye = hmd->EyeRenderOrder[i];
buffer[eye]->bind();
draw();
}
}
ovrHmd_EndFrame(hmd, pose, tex);
}
}
/// Dispatch an SDL event.
void OVR_SDL2_app::dispatch(SDL_Event& e)
{
switch (e.type)
{
case SDL_KEYDOWN:
keyboard(e.key.keysym.scancode, true, (e.key.repeat != 0));
break;
case SDL_KEYUP:
keyboard(e.key.keysym.scancode, false, (e.key.repeat != 0));
break;
case SDL_MOUSEBUTTONDOWN:
mouse_button(e.button.button, true);
break;
case SDL_MOUSEBUTTONUP:
mouse_button(e.button.button, false);
break;
case SDL_MOUSEMOTION:
mouse_motion(e.motion.xrel, e.motion.yrel);
break;
case SDL_MOUSEWHEEL:
mouse_wheel(e.wheel.x, e.wheel.y);
break;
case SDL_CONTROLLERAXISMOTION:
game_axis(e.caxis.which, e.caxis.axis, e.caxis.value / 32768.f);
break;
case SDL_CONTROLLERBUTTONDOWN:
game_button(e.caxis.which, e.cbutton.button, true);
break;
case SDL_CONTROLLERBUTTONUP:
game_button(e.caxis.which, e.cbutton.button, false);
break;
case SDL_CONTROLLERDEVICEADDED:
game_connect(e.cdevice.which, true);
break;
case SDL_CONTROLLERDEVICEREMOVED:
game_connect(e.cdevice.which, false);
break;
case SDL_QUIT:
running = false;
break;
}
}
//------------------------------------------------------------------------------
/// Handle a key press or release.
void OVR_SDL2_app::keyboard(int key, bool down, bool repeat)
{
dismiss_warning();
if (key == SDL_SCANCODE_ESCAPE && down == false)
running = false;
}
/// Handle a mouse button press or release.
void OVR_SDL2_app::mouse_button(int button, bool down)
{
dismiss_warning();
}
/// Handle mouse wheel rotation.
void OVR_SDL2_app::mouse_wheel(int dx, int dy)
{
}
/// Handle mouse pointer motion.
void OVR_SDL2_app::mouse_motion(int x, int y)
{
}
/// Handle gamepad connection or disconnection
void OVR_SDL2_app::game_connect(int device, bool connected)
{
controller.resize(device + 1);
if (controller[device])
SDL_GameControllerClose(controller[device]);
if (connected)
controller[device] = SDL_GameControllerOpen(device);
else
controller[device] = 0;
}
/// Handle gamepad button press or release.
void OVR_SDL2_app::game_button(int device, int button, bool down)
{
dismiss_warning();
}
/// Handle gamepad axis motion.
void OVR_SDL2_app::game_axis(int device, int axis, float value)
{
}
//------------------------------------------------------------------------------
/// Convert an OVR matrix to a GLFundamentals matrix.
static mat4 getMatrix4f(const OVR::Matrix4f& m)
{
return mat4(m.M[0][0], m.M[0][1], m.M[0][2], m.M[0][3],
m.M[1][0], m.M[1][1], m.M[1][2], m.M[1][3],
m.M[2][0], m.M[2][1], m.M[2][2], m.M[2][3],
m.M[3][0], m.M[3][1], m.M[3][2], m.M[3][3]);
}
/// Return the current projection matrix as determined by the current OVR eye
/// render descriptor.
mat4 OVR_SDL2_app::projection() const
{
return getMatrix4f(ovrMatrix4f_Projection(erd[eye].Fov, 0.1f, 100.0f, true));
}
/// Return the current view matrix as determined by the current OVR eye render
/// descriptor and head pose.
mat4 OVR_SDL2_app::view() const
{
// Orientation of the head
OVR::Quatf q = OVR::Quatf(pose[eye].Orientation);
mat4 O = getMatrix4f(OVR::Matrix4f(q.Inverted()));
// Offset of the head from the center of the world
mat4 P = translation(vec3(-pose[eye].Position.x,
-pose[eye].Position.y,
-pose[eye].Position.z));
// return E * O * P;
return O * P;
}
//------------------------------------------------------------------------------
/// Check if the OVR health & safety warning is visible and try to dismiss it.
void OVR_SDL2_app::dismiss_warning()
{
ovrHSWDisplayState state;
ovrHmd_GetHSWDisplayState(hmd, &state);
if (state.Displayed)
ovrHmd_DismissHSWDisplay(hmd);
}
|
Add XDisplay workaround for Linux port
|
Add XDisplay workaround for Linux port
|
C++
|
mit
|
rlk/OVR_SDL2,rlk/OVR_SDL2
|
742fdd0c857a9e4d85196c5a3750ae1029027d85
|
RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESLinkProgram.cpp
|
RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESLinkProgram.cpp
|
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreGLSLESLinkProgram.h"
#include "OgreGLSLESExtSupport.h"
#include "OgreGLSLESGpuProgram.h"
#include "OgreGLSLESProgram.h"
#include "OgreGLSLESLinkProgramManager.h"
#include "OgreGLES2RenderSystem.h"
#include "OgreStringVector.h"
#include "OgreLogManager.h"
#include "OgreGpuProgramManager.h"
#include "OgreStringConverter.h"
namespace Ogre {
//-----------------------------------------------------------------------
GLSLESLinkProgram::GLSLESLinkProgram(GLSLESGpuProgram* vertexProgram, GLSLESGpuProgram* fragmentProgram)
: mVertexProgram(vertexProgram)
, mFragmentProgram(fragmentProgram)
, mUniformRefsBuilt(false)
, mLinked(false)
, mTriedToLinkAndFailed(false)
{
// init CustomAttributesIndexs
for(size_t i = 0 ; i < VES_COUNT; i++)
for(size_t j = 0 ; j < OGRE_MAX_TEXTURE_COORD_SETS; j++)
{
mCustomAttributesIndexes[i][j] = NULL_CUSTOM_ATTRIBUTES_INDEX;
}
if (!mVertexProgram && !mFragmentProgram)
{
OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
"Attempted to create a shader program without both a vertex and fragment program.",
"GLSLESLinkProgram::GLSLESLinkProgram");
}
}
//-----------------------------------------------------------------------
GLSLESLinkProgram::~GLSLESLinkProgram(void)
{
glDeleteProgram(mGLHandle);
GL_CHECK_ERROR;
}
//-----------------------------------------------------------------------
Ogre::String GLSLESLinkProgram::getCombinedName()
{
String name;
if (mVertexProgram)
{
name += "Vertex Program:" ;
name += mVertexProgram->getName();
}
if (mFragmentProgram)
{
name += " Fragment Program:" ;
name += mFragmentProgram->getName();
}
return name;
}
//-----------------------------------------------------------------------
void GLSLESLinkProgram::activate(void)
{
if (!mLinked && !mTriedToLinkAndFailed)
{
glGetError(); // Clean up the error. Otherwise will flood log.
mGLHandle = glCreateProgram();
GL_CHECK_ERROR
if ( GpuProgramManager::getSingleton().canGetCompiledShaderBuffer() &&
GpuProgramManager::getSingleton().isMicrocodeAvailableInCache(getCombinedName()) )
{
getMicrocodeFromCache();
}
else
{
#ifdef OGRE_USE_GLES2_GLSL_OPTIMISER
// check CmdParams for each shader type to see if we should optimize
String paramStr = mVertexProgram->getGLSLProgram()->getParameter("use_optimiser");
if((paramStr == "true") || paramStr.empty())
{
GLSLESLinkProgramManager::getSingleton().optimiseShaderSource(mVertexProgram);
}
paramStr = mFragmentProgram->getGLSLProgram()->getParameter("use_optimiser");
if((paramStr == "true") || paramStr.empty())
{
GLSLESLinkProgramManager::getSingleton().optimiseShaderSource(mFragmentProgram);
}
#endif
compileAndLink();
}
buildGLUniformReferences();
}
if (mLinked)
{
GL_CHECK_ERROR
glUseProgram( mGLHandle );
GL_CHECK_ERROR
}
}
//-----------------------------------------------------------------------
void GLSLESLinkProgram::getMicrocodeFromCache(void)
{
GpuProgramManager::Microcode cacheMicrocode =
GpuProgramManager::getSingleton().getMicrocodeFromCache(getCombinedName());
// add to the microcode to the cache
String name;
name = getCombinedName();
// turns out we need this param when loading
GLenum binaryFormat = 0;
cacheMicrocode->seek(0);
// get size of binary
cacheMicrocode->read(&binaryFormat, sizeof(GLenum));
#if GL_OES_get_program_binary
GLint binaryLength = cacheMicrocode->size() - sizeof(GLenum);
// load binary
glProgramBinaryOES( mGLHandle,
binaryFormat,
cacheMicrocode->getPtr(),
binaryLength
);
GL_CHECK_ERROR;
#endif
GLint success = 0;
glGetProgramiv(mGLHandle, GL_LINK_STATUS, &success);
GL_CHECK_ERROR;
if (!success)
{
//
// Something must have changed since the program binaries
// were cached away. Fallback to source shader loading path,
// and then retrieve and cache new program binaries once again.
//
compileAndLink();
}
}
//-----------------------------------------------------------------------
void GLSLESLinkProgram::compileAndLink()
{
// compile and attach Vertex Program
if (!mVertexProgram->getGLSLProgram()->compile(true))
{
// todo error
mTriedToLinkAndFailed = true;
return;
}
mVertexProgram->getGLSLProgram()->attachToProgramObject(mGLHandle);
setSkeletalAnimationIncluded(mVertexProgram->isSkeletalAnimationIncluded());
// compile and attach Fragment Program
if (!mFragmentProgram->getGLSLProgram()->compile(true))
{
// todo error
mTriedToLinkAndFailed = true;
return;
}
mFragmentProgram->getGLSLProgram()->attachToProgramObject(mGLHandle);
// the link
glLinkProgram( mGLHandle );
GL_CHECK_ERROR
glGetProgramiv( mGLHandle, GL_LINK_STATUS, &mLinked );
GL_CHECK_ERROR
mTriedToLinkAndFailed = !mLinked;
logObjectInfo( getCombinedName() + String("GLSL link result : "), mGLHandle );
if(mLinked)
{
if ( GpuProgramManager::getSingleton().getSaveMicrocodesToCache() )
{
// add to the microcode to the cache
String name;
name = getCombinedName();
// get buffer size
GLint binaryLength = 0;
#if GL_OES_get_program_binary
glGetProgramiv(mGLHandle, GL_PROGRAM_BINARY_LENGTH_OES, &binaryLength);
GL_CHECK_ERROR;
#endif
// create microcode
GpuProgramManager::Microcode newMicrocode =
GpuProgramManager::getSingleton().createMicrocode(binaryLength + sizeof(GLenum));
#if GL_OES_get_program_binary
// get binary
glGetProgramBinaryOES(mGLHandle, binaryLength, NULL, (GLenum *)newMicrocode->getPtr(), newMicrocode->getPtr() + sizeof(GLenum));
GL_CHECK_ERROR;
#endif
// add to the microcode to the cache
GpuProgramManager::getSingleton().addMicrocodeToCache(name, newMicrocode);
}
}
}
//-----------------------------------------------------------------------
const char * getAttributeSemanticString(VertexElementSemantic semantic)
{
switch(semantic)
{
case VES_POSITION:
return "vertex";
case VES_BLEND_WEIGHTS:
return "blendWeights";
case VES_NORMAL:
return "normal";
case VES_DIFFUSE:
return "colour";
case VES_SPECULAR:
return "secondary_colour";
case VES_BLEND_INDICES:
return "blendIndices";
case VES_TANGENT:
return "tangent";
case VES_BINORMAL:
return "binormal";
case VES_TEXTURE_COORDINATES:
return "uv";
default:
assert(false && "Missing attribute!");
return 0;
};
}
//-----------------------------------------------------------------------
GLuint GLSLESLinkProgram::getAttributeIndex(VertexElementSemantic semantic, uint index)
{
GLint res = mCustomAttributesIndexes[semantic-1][index];
if (res == NULL_CUSTOM_ATTRIBUTES_INDEX)
{
const char * attString = getAttributeSemanticString(semantic);
GLint attrib = glGetAttribLocation(mGLHandle, attString);
GL_CHECK_ERROR;
// sadly position is a special case
if (attrib == NOT_FOUND_CUSTOM_ATTRIBUTES_INDEX && semantic == VES_POSITION)
{
attrib = glGetAttribLocation(mGLHandle, "position");
GL_CHECK_ERROR;
}
// for uv and other case the index is a part of the name
if (attrib == NOT_FOUND_CUSTOM_ATTRIBUTES_INDEX)
{
String attStringWithSemantic = String(attString) + StringConverter::toString(index);
attrib = glGetAttribLocation(mGLHandle, attStringWithSemantic.c_str());
GL_CHECK_ERROR;
}
// update mCustomAttributesIndexes with the index we found (or didn't find)
mCustomAttributesIndexes[semantic-1][index] = attrib;
res = attrib;
}
return (GLuint)res;
}
//-----------------------------------------------------------------------
bool GLSLESLinkProgram::isAttributeValid(VertexElementSemantic semantic, uint index)
{
return (GLint)(getAttributeIndex(semantic, index)) != NOT_FOUND_CUSTOM_ATTRIBUTES_INDEX;
}
//-----------------------------------------------------------------------
void GLSLESLinkProgram::buildGLUniformReferences(void)
{
if (!mUniformRefsBuilt)
{
const GpuConstantDefinitionMap* vertParams = 0;
const GpuConstantDefinitionMap* fragParams = 0;
if (mVertexProgram)
{
vertParams = &(mVertexProgram->getGLSLProgram()->getConstantDefinitions().map);
}
if (mFragmentProgram)
{
fragParams = &(mFragmentProgram->getGLSLProgram()->getConstantDefinitions().map);
}
GLSLESLinkProgramManager::getSingleton().extractUniforms(
mGLHandle, vertParams, fragParams, mGLUniformReferences);
mUniformRefsBuilt = true;
}
}
//-----------------------------------------------------------------------
void GLSLESLinkProgram::updateUniforms(GpuProgramParametersSharedPtr params,
uint16 mask, GpuProgramType fromProgType)
{
// Iterate through uniform reference list and update uniform values
GLUniformReferenceIterator currentUniform = mGLUniformReferences.begin();
GLUniformReferenceIterator endUniform = mGLUniformReferences.end();
for (;currentUniform != endUniform; ++currentUniform)
{
// Only pull values from buffer it's supposed to be in (vertex or fragment)
// This method will be called twice, once for vertex program params,
// and once for fragment program params.
if (fromProgType == currentUniform->mSourceProgType)
{
const GpuConstantDefinition* def = currentUniform->mConstantDef;
if (def->variability & mask)
{
GLsizei glArraySize = (GLsizei)def->arraySize;
// Get the index in the parameter real list
switch (def->constType)
{
case GCT_FLOAT1:
glUniform1fv(currentUniform->mLocation, glArraySize,
params->getFloatPointer(def->physicalIndex));
break;
case GCT_FLOAT2:
glUniform2fv(currentUniform->mLocation, glArraySize,
params->getFloatPointer(def->physicalIndex));
break;
case GCT_FLOAT3:
glUniform3fv(currentUniform->mLocation, glArraySize,
params->getFloatPointer(def->physicalIndex));
break;
case GCT_FLOAT4:
glUniform4fv(currentUniform->mLocation, glArraySize,
params->getFloatPointer(def->physicalIndex));
break;
case GCT_MATRIX_2X2:
glUniformMatrix2fv(currentUniform->mLocation, glArraySize,
GL_FALSE, params->getFloatPointer(def->physicalIndex));
break;
case GCT_MATRIX_3X3:
glUniformMatrix3fv(currentUniform->mLocation, glArraySize,
GL_FALSE, params->getFloatPointer(def->physicalIndex));
break;
case GCT_MATRIX_4X4:
glUniformMatrix4fv(currentUniform->mLocation, glArraySize,
GL_FALSE, params->getFloatPointer(def->physicalIndex));
break;
case GCT_INT1:
glUniform1iv(currentUniform->mLocation, glArraySize,
(GLint*)params->getIntPointer(def->physicalIndex));
break;
case GCT_INT2:
glUniform2iv(currentUniform->mLocation, glArraySize,
(GLint*)params->getIntPointer(def->physicalIndex));
break;
case GCT_INT3:
glUniform3iv(currentUniform->mLocation, glArraySize,
(GLint*)params->getIntPointer(def->physicalIndex));
break;
case GCT_INT4:
glUniform4iv(currentUniform->mLocation, glArraySize,
(GLint*)params->getIntPointer(def->physicalIndex));
break;
case GCT_SAMPLER1D:
case GCT_SAMPLER1DSHADOW:
case GCT_SAMPLER2D:
case GCT_SAMPLER2DSHADOW:
case GCT_SAMPLER3D:
case GCT_SAMPLERCUBE:
// Samplers handled like 1-element ints
glUniform1iv(currentUniform->mLocation, 1,
(GLint*)params->getIntPointer(def->physicalIndex));
break;
case GCT_MATRIX_2X3:
case GCT_MATRIX_2X4:
case GCT_MATRIX_3X2:
case GCT_MATRIX_3X4:
case GCT_MATRIX_4X2:
case GCT_MATRIX_4X3:
case GCT_UNKNOWN:
break;
} // End switch
GL_CHECK_ERROR;
} // Variability & mask
} // fromProgType == currentUniform->mSourceProgType
} // End for
}
//-----------------------------------------------------------------------
void GLSLESLinkProgram::updatePassIterationUniforms(GpuProgramParametersSharedPtr params)
{
if (params->hasPassIterationNumber())
{
size_t index = params->getPassIterationNumberIndex();
GLUniformReferenceIterator currentUniform = mGLUniformReferences.begin();
GLUniformReferenceIterator endUniform = mGLUniformReferences.end();
// Need to find the uniform that matches the multi pass entry
for (;currentUniform != endUniform; ++currentUniform)
{
// Get the index in the parameter real list
if (index == currentUniform->mConstantDef->physicalIndex)
{
glUniform1fv(currentUniform->mLocation, 1, params->getFloatPointer(index));
GL_CHECK_ERROR;
// There will only be one multipass entry
return;
}
}
}
}
} // namespace Ogre
|
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreGLSLESLinkProgram.h"
#include "OgreGLSLESExtSupport.h"
#include "OgreGLSLESGpuProgram.h"
#include "OgreGLSLESProgram.h"
#include "OgreGLSLESLinkProgramManager.h"
#include "OgreGLES2RenderSystem.h"
#include "OgreStringVector.h"
#include "OgreLogManager.h"
#include "OgreGpuProgramManager.h"
#include "OgreStringConverter.h"
namespace Ogre {
//-----------------------------------------------------------------------
GLSLESLinkProgram::GLSLESLinkProgram(GLSLESGpuProgram* vertexProgram, GLSLESGpuProgram* fragmentProgram)
: mVertexProgram(vertexProgram)
, mFragmentProgram(fragmentProgram)
, mUniformRefsBuilt(false)
, mLinked(false)
, mTriedToLinkAndFailed(false)
{
// init CustomAttributesIndexs
for(size_t i = 0 ; i < VES_COUNT; i++)
for(size_t j = 0 ; j < OGRE_MAX_TEXTURE_COORD_SETS; j++)
{
mCustomAttributesIndexes[i][j] = NULL_CUSTOM_ATTRIBUTES_INDEX;
}
if (!mVertexProgram || !mFragmentProgram)
{
OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
"Attempted to create a shader program without both a vertex and fragment program.",
"GLSLESLinkProgram::GLSLESLinkProgram");
}
}
//-----------------------------------------------------------------------
GLSLESLinkProgram::~GLSLESLinkProgram(void)
{
glDeleteProgram(mGLHandle);
GL_CHECK_ERROR;
}
//-----------------------------------------------------------------------
Ogre::String GLSLESLinkProgram::getCombinedName()
{
String name;
if (mVertexProgram)
{
name += "Vertex Program:" ;
name += mVertexProgram->getName();
}
if (mFragmentProgram)
{
name += " Fragment Program:" ;
name += mFragmentProgram->getName();
}
return name;
}
//-----------------------------------------------------------------------
void GLSLESLinkProgram::activate(void)
{
if (!mLinked && !mTriedToLinkAndFailed)
{
glGetError(); // Clean up the error. Otherwise will flood log.
mGLHandle = glCreateProgram();
GL_CHECK_ERROR
if ( GpuProgramManager::getSingleton().canGetCompiledShaderBuffer() &&
GpuProgramManager::getSingleton().isMicrocodeAvailableInCache(getCombinedName()) )
{
getMicrocodeFromCache();
}
else
{
#ifdef OGRE_USE_GLES2_GLSL_OPTIMISER
// check CmdParams for each shader type to see if we should optimize
String paramStr = mVertexProgram->getGLSLProgram()->getParameter("use_optimiser");
if((paramStr == "true") || paramStr.empty())
{
GLSLESLinkProgramManager::getSingleton().optimiseShaderSource(mVertexProgram);
}
paramStr = mFragmentProgram->getGLSLProgram()->getParameter("use_optimiser");
if((paramStr == "true") || paramStr.empty())
{
GLSLESLinkProgramManager::getSingleton().optimiseShaderSource(mFragmentProgram);
}
#endif
compileAndLink();
}
buildGLUniformReferences();
}
if (mLinked)
{
GL_CHECK_ERROR
glUseProgram( mGLHandle );
GL_CHECK_ERROR
}
}
//-----------------------------------------------------------------------
void GLSLESLinkProgram::getMicrocodeFromCache(void)
{
GpuProgramManager::Microcode cacheMicrocode =
GpuProgramManager::getSingleton().getMicrocodeFromCache(getCombinedName());
// add to the microcode to the cache
String name;
name = getCombinedName();
// turns out we need this param when loading
GLenum binaryFormat = 0;
cacheMicrocode->seek(0);
// get size of binary
cacheMicrocode->read(&binaryFormat, sizeof(GLenum));
#if GL_OES_get_program_binary
GLint binaryLength = cacheMicrocode->size() - sizeof(GLenum);
// load binary
glProgramBinaryOES( mGLHandle,
binaryFormat,
cacheMicrocode->getPtr(),
binaryLength
);
GL_CHECK_ERROR;
#endif
GLint success = 0;
glGetProgramiv(mGLHandle, GL_LINK_STATUS, &success);
GL_CHECK_ERROR;
if (!success)
{
//
// Something must have changed since the program binaries
// were cached away. Fallback to source shader loading path,
// and then retrieve and cache new program binaries once again.
//
compileAndLink();
}
}
//-----------------------------------------------------------------------
void GLSLESLinkProgram::compileAndLink()
{
// compile and attach Vertex Program
if (!mVertexProgram->getGLSLProgram()->compile(true))
{
// todo error
mTriedToLinkAndFailed = true;
return;
}
mVertexProgram->getGLSLProgram()->attachToProgramObject(mGLHandle);
setSkeletalAnimationIncluded(mVertexProgram->isSkeletalAnimationIncluded());
// compile and attach Fragment Program
if (!mFragmentProgram->getGLSLProgram()->compile(true))
{
// todo error
mTriedToLinkAndFailed = true;
return;
}
mFragmentProgram->getGLSLProgram()->attachToProgramObject(mGLHandle);
// the link
glLinkProgram( mGLHandle );
GL_CHECK_ERROR
glGetProgramiv( mGLHandle, GL_LINK_STATUS, &mLinked );
GL_CHECK_ERROR
mTriedToLinkAndFailed = !mLinked;
logObjectInfo( getCombinedName() + String("GLSL link result : "), mGLHandle );
if(mLinked)
{
if ( GpuProgramManager::getSingleton().getSaveMicrocodesToCache() )
{
// add to the microcode to the cache
String name;
name = getCombinedName();
// get buffer size
GLint binaryLength = 0;
#if GL_OES_get_program_binary
glGetProgramiv(mGLHandle, GL_PROGRAM_BINARY_LENGTH_OES, &binaryLength);
GL_CHECK_ERROR;
#endif
// create microcode
GpuProgramManager::Microcode newMicrocode =
GpuProgramManager::getSingleton().createMicrocode(binaryLength + sizeof(GLenum));
#if GL_OES_get_program_binary
// get binary
glGetProgramBinaryOES(mGLHandle, binaryLength, NULL, (GLenum *)newMicrocode->getPtr(), newMicrocode->getPtr() + sizeof(GLenum));
GL_CHECK_ERROR;
#endif
// add to the microcode to the cache
GpuProgramManager::getSingleton().addMicrocodeToCache(name, newMicrocode);
}
}
}
//-----------------------------------------------------------------------
const char * getAttributeSemanticString(VertexElementSemantic semantic)
{
switch(semantic)
{
case VES_POSITION:
return "vertex";
case VES_BLEND_WEIGHTS:
return "blendWeights";
case VES_NORMAL:
return "normal";
case VES_DIFFUSE:
return "colour";
case VES_SPECULAR:
return "secondary_colour";
case VES_BLEND_INDICES:
return "blendIndices";
case VES_TANGENT:
return "tangent";
case VES_BINORMAL:
return "binormal";
case VES_TEXTURE_COORDINATES:
return "uv";
default:
assert(false && "Missing attribute!");
return 0;
};
}
//-----------------------------------------------------------------------
GLuint GLSLESLinkProgram::getAttributeIndex(VertexElementSemantic semantic, uint index)
{
GLint res = mCustomAttributesIndexes[semantic-1][index];
if (res == NULL_CUSTOM_ATTRIBUTES_INDEX)
{
const char * attString = getAttributeSemanticString(semantic);
GLint attrib = glGetAttribLocation(mGLHandle, attString);
GL_CHECK_ERROR;
// sadly position is a special case
if (attrib == NOT_FOUND_CUSTOM_ATTRIBUTES_INDEX && semantic == VES_POSITION)
{
attrib = glGetAttribLocation(mGLHandle, "position");
GL_CHECK_ERROR;
}
// for uv and other case the index is a part of the name
if (attrib == NOT_FOUND_CUSTOM_ATTRIBUTES_INDEX)
{
String attStringWithSemantic = String(attString) + StringConverter::toString(index);
attrib = glGetAttribLocation(mGLHandle, attStringWithSemantic.c_str());
GL_CHECK_ERROR;
}
// update mCustomAttributesIndexes with the index we found (or didn't find)
mCustomAttributesIndexes[semantic-1][index] = attrib;
res = attrib;
}
return (GLuint)res;
}
//-----------------------------------------------------------------------
bool GLSLESLinkProgram::isAttributeValid(VertexElementSemantic semantic, uint index)
{
return (GLint)(getAttributeIndex(semantic, index)) != NOT_FOUND_CUSTOM_ATTRIBUTES_INDEX;
}
//-----------------------------------------------------------------------
void GLSLESLinkProgram::buildGLUniformReferences(void)
{
if (!mUniformRefsBuilt)
{
const GpuConstantDefinitionMap* vertParams = 0;
const GpuConstantDefinitionMap* fragParams = 0;
if (mVertexProgram)
{
vertParams = &(mVertexProgram->getGLSLProgram()->getConstantDefinitions().map);
}
if (mFragmentProgram)
{
fragParams = &(mFragmentProgram->getGLSLProgram()->getConstantDefinitions().map);
}
GLSLESLinkProgramManager::getSingleton().extractUniforms(
mGLHandle, vertParams, fragParams, mGLUniformReferences);
mUniformRefsBuilt = true;
}
}
//-----------------------------------------------------------------------
void GLSLESLinkProgram::updateUniforms(GpuProgramParametersSharedPtr params,
uint16 mask, GpuProgramType fromProgType)
{
// Iterate through uniform reference list and update uniform values
GLUniformReferenceIterator currentUniform = mGLUniformReferences.begin();
GLUniformReferenceIterator endUniform = mGLUniformReferences.end();
for (;currentUniform != endUniform; ++currentUniform)
{
// Only pull values from buffer it's supposed to be in (vertex or fragment)
// This method will be called twice, once for vertex program params,
// and once for fragment program params.
if (fromProgType == currentUniform->mSourceProgType)
{
const GpuConstantDefinition* def = currentUniform->mConstantDef;
if (def->variability & mask)
{
GLsizei glArraySize = (GLsizei)def->arraySize;
// Get the index in the parameter real list
switch (def->constType)
{
case GCT_FLOAT1:
glUniform1fv(currentUniform->mLocation, glArraySize,
params->getFloatPointer(def->physicalIndex));
break;
case GCT_FLOAT2:
glUniform2fv(currentUniform->mLocation, glArraySize,
params->getFloatPointer(def->physicalIndex));
break;
case GCT_FLOAT3:
glUniform3fv(currentUniform->mLocation, glArraySize,
params->getFloatPointer(def->physicalIndex));
break;
case GCT_FLOAT4:
glUniform4fv(currentUniform->mLocation, glArraySize,
params->getFloatPointer(def->physicalIndex));
break;
case GCT_MATRIX_2X2:
glUniformMatrix2fv(currentUniform->mLocation, glArraySize,
GL_FALSE, params->getFloatPointer(def->physicalIndex));
break;
case GCT_MATRIX_3X3:
glUniformMatrix3fv(currentUniform->mLocation, glArraySize,
GL_FALSE, params->getFloatPointer(def->physicalIndex));
break;
case GCT_MATRIX_4X4:
glUniformMatrix4fv(currentUniform->mLocation, glArraySize,
GL_FALSE, params->getFloatPointer(def->physicalIndex));
break;
case GCT_INT1:
glUniform1iv(currentUniform->mLocation, glArraySize,
(GLint*)params->getIntPointer(def->physicalIndex));
break;
case GCT_INT2:
glUniform2iv(currentUniform->mLocation, glArraySize,
(GLint*)params->getIntPointer(def->physicalIndex));
break;
case GCT_INT3:
glUniform3iv(currentUniform->mLocation, glArraySize,
(GLint*)params->getIntPointer(def->physicalIndex));
break;
case GCT_INT4:
glUniform4iv(currentUniform->mLocation, glArraySize,
(GLint*)params->getIntPointer(def->physicalIndex));
break;
case GCT_SAMPLER1D:
case GCT_SAMPLER1DSHADOW:
case GCT_SAMPLER2D:
case GCT_SAMPLER2DSHADOW:
case GCT_SAMPLER3D:
case GCT_SAMPLERCUBE:
// Samplers handled like 1-element ints
glUniform1iv(currentUniform->mLocation, 1,
(GLint*)params->getIntPointer(def->physicalIndex));
break;
case GCT_MATRIX_2X3:
case GCT_MATRIX_2X4:
case GCT_MATRIX_3X2:
case GCT_MATRIX_3X4:
case GCT_MATRIX_4X2:
case GCT_MATRIX_4X3:
case GCT_UNKNOWN:
break;
} // End switch
GL_CHECK_ERROR;
} // Variability & mask
} // fromProgType == currentUniform->mSourceProgType
} // End for
}
//-----------------------------------------------------------------------
void GLSLESLinkProgram::updatePassIterationUniforms(GpuProgramParametersSharedPtr params)
{
if (params->hasPassIterationNumber())
{
size_t index = params->getPassIterationNumberIndex();
GLUniformReferenceIterator currentUniform = mGLUniformReferences.begin();
GLUniformReferenceIterator endUniform = mGLUniformReferences.end();
// Need to find the uniform that matches the multi pass entry
for (;currentUniform != endUniform; ++currentUniform)
{
// Get the index in the parameter real list
if (index == currentUniform->mConstantDef->physicalIndex)
{
glUniform1fv(currentUniform->mLocation, 1, params->getFloatPointer(index));
GL_CHECK_ERROR;
// There will only be one multipass entry
return;
}
}
}
}
} // namespace Ogre
|
Fix a typo. We should be checking if either the fragment OR vertex program is null. GL ES 2 requires that both be valid. Thanks to fanlansen for pointing this out.
|
GLES2: Fix a typo. We should be checking if either the fragment OR vertex program is null. GL ES 2 requires that both be valid. Thanks to fanlansen for pointing this out.
|
C++
|
mit
|
digimatic/ogre,digimatic/ogre,digimatic/ogre,digimatic/ogre,digimatic/ogre,digimatic/ogre,digimatic/ogre
|
3a6900f1daa4dbb763b0004a80add6d931cd9657
|
include/hpp/core/container.hh
|
include/hpp/core/container.hh
|
// Copyright (c) 2015, LAAS-CNRS
// Authors: Joseph Mirabel ([email protected])
//
// This file is part of hpp-core.
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core. If not, see <http://www.gnu.org/licenses/>.
#ifndef HPP_CORE_CONTAINER_HH
# define HPP_CORE_CONTAINER_HH
# include <map>
# include <list>
# include <boost/smart_ptr/shared_ptr.hpp>
# include <boost/mpl/inherit_linearly.hpp>
# include <boost/mpl/fold.hpp>
# include <boost/mpl/inherit.hpp>
# include <boost/mpl/vector.hpp>
# include <boost/mpl/for_each.hpp>
# include <hpp/core/config.hh>
namespace hpp {
namespace core {
/// @cond INTERNAL
namespace internal {
template <typename Key, typename Type>
struct field
{
typedef std::map <Key, Type> Map_t;
Map_t map;
template <bool deref_ptr>
void print (std::ostream& os) const
{
for (typename Map_t::const_iterator
it = map.begin (); it != map.end (); ++it)
{
if (deref_ptr) os << it->first << " : " << *it->second << std::endl;
else os << it->first << " : " << it->second << std::endl;
}
}
};
template <typename Types, typename Key>
struct container_traits
{
typedef typename boost::mpl::inherit_linearly <
Types, boost::mpl::inherit < boost::mpl::arg<1>,
field< Key, boost::mpl::arg<2> >
>
>::type
type;
};
template <bool deref_ptr>
struct print {
std::ostream& os;
print (std::ostream& osio) : os (osio) {}
template <class Field>
void operator () (const Field& f)
{
f.Field::template print <deref_ptr> (os);
}
};
}
/// @endcond
template < typename Element, typename Key = std::string>
class HPP_CORE_DLLAPI Container
{
public:
typedef std::map <Key, Element> ElementMap_t;
typedef typename ElementMap_t::iterator iterator;
typedef typename ElementMap_t::const_iterator const_iterator;
typedef Key Key_t;
typedef Element Element_t;
/// Add an element
void add (const Key& name, const Element& element)
{
map_[name] = element;
}
/// Return the element named name
bool has (const Key& name) const
{
return (map_.find (name) != map_.end ());
}
/// Return the element named name
const Element& get (const Key& name) const
{
typename ElementMap_t::const_iterator it = map_.find (name);
if (it == map_.end ()) throw std::runtime_error ("invalid key");
return it->second;
}
/// Return a list of all elements
/// \tparam ReturnType must have a push_back method.
template <typename ReturnType>
ReturnType getAllAs () const
{
ReturnType l;
for (typename ElementMap_t::const_iterator it = map_.begin ();
it != map_.end (); ++it)
l.push_back (it->second);
return l;
}
template <typename ReturnType>
ReturnType getKeys () const
{
ReturnType l;
for (typename ElementMap_t::const_iterator it = map_.begin ();
it != map_.end (); ++it)
l.push_back (it->first);
return l;
}
/// Return the underlying map.
const ElementMap_t& getAll () const
{
return map_;
}
/// Print object in a stream
std::ostream& print (std::ostream& os) const
{
for (typename ElementMap_t::const_iterator it = map_.begin ();
it != map_.end (); ++it) {
os << it->first << " : " << it->second << std::endl;
}
return os;
}
/// Print object in a stream
std::ostream& printPointer (std::ostream& os) const
{
for (typename ElementMap_t::const_iterator it = map_.begin ();
it != map_.end (); ++it) {
os << it->first << " : " << *(it->second) << std::endl;
}
return os;
}
protected:
/// Constructor
Container () : map_ ()
{}
private:
ElementMap_t map_;
}; // class Container
template <typename Types, typename Key = std::string >
class Containers : private internal::container_traits <Types, Key>::type
{
public:
template <typename Element> struct traits {
typedef internal::field<Key, Element> Container;
typedef typename Container::Map_t Map_t;
};
private:
template <typename Element> struct _F {
typedef internal::field<Key, Element> T;
typedef typename T::Map_t Map_t;
};
/// Return the underlying map.
template <typename Element>
typename _F <Element>::Map_t& _map ()
{
return this->_F <Element>::T::map;
}
public:
/// Return the underlying map.
template <typename Element>
const typename traits<Element>::Map_t& map () const
{
return this->_F <Element>::T::map;
}
/// Add an element
template <typename Element>
void add (const Key& name, const Element& element)
{
_map <Element>()[name] = element;
}
/// Return the element named name
template <typename Element>
bool has (const Key& name) const
{
return (map<Element>().find (name) != map<Element>().end ());
}
/// Return the element named name
template <typename Element>
const Element& get (const Key& name) const
{
typename _F<Element>::Map_t::const_iterator it
= map<Element>().find (name);
if (it == map<Element>().end ())
throw std::runtime_error ("invalid key");
return it->second;
}
/// Return a list of all elements
/// \tparam ReturnType must have a push_back method.
template <typename Element, typename ReturnType>
ReturnType getAllAs () const
{
ReturnType l;
for (typename _F<Element>::Map_t::const_iterator
it = map<Element>().begin ();
it != map<Element>().end ();
++it)
l.push_back (it->second);
return l;
}
template <typename Element, typename ReturnType>
ReturnType getKeys () const
{
ReturnType l;
for (typename _F<Element>::Map_t::const_iterator
it = map<Element>().begin ();
it != map<Element>().end ();
++it)
l.push_back (it->first);
return l;
}
/// Print object in a stream
std::ostream& print (std::ostream& os) const
{
boost::mpl::for_each < Types > (print <false> (os));
return os;
}
/// Print object in a stream
std::ostream& printPointer (std::ostream& os) const
{
boost::mpl::for_each < Types > (print <true> (os));
return os;
}
};
} // namespace core
} // namespace hpp
#endif // HPP_CORE_CONTAINER_HH
|
// Copyright (c) 2015, LAAS-CNRS
// Authors: Joseph Mirabel ([email protected])
//
// This file is part of hpp-core.
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core. If not, see <http://www.gnu.org/licenses/>.
#ifndef HPP_CORE_CONTAINER_HH
# define HPP_CORE_CONTAINER_HH
# include <map>
# include <list>
# include <boost/smart_ptr/shared_ptr.hpp>
# include <boost/mpl/inherit_linearly.hpp>
# include <boost/mpl/fold.hpp>
# include <boost/mpl/inherit.hpp>
# include <boost/mpl/vector.hpp>
# include <boost/mpl/for_each.hpp>
# include <hpp/core/config.hh>
namespace hpp {
namespace core {
/// @cond INTERNAL
namespace internal {
template <typename Key, typename Type>
struct field
{
typedef std::map <Key, Type> Map_t;
Map_t map;
template <bool deref_ptr>
void print (std::ostream& os) const
{
for (typename Map_t::const_iterator
it = map.begin (); it != map.end (); ++it)
{
if (deref_ptr) os << it->first << " : " << *it->second << std::endl;
else os << it->first << " : " << it->second << std::endl;
}
}
};
template <typename Types, typename Key>
struct container_traits
{
typedef typename boost::mpl::inherit_linearly <
Types, boost::mpl::inherit < boost::mpl::arg<1>,
field< Key, boost::mpl::arg<2> >
>
>::type
type;
};
template <bool deref_ptr>
struct print {
std::ostream& os;
print (std::ostream& osio) : os (osio) {}
template <class Field>
void operator () (const Field& f)
{
f.Field::template print <deref_ptr> (os);
}
};
}
/// @endcond
template <typename Types, typename Key = std::string >
class Containers : private internal::container_traits <Types, Key>::type
{
public:
template <typename Element> struct traits {
typedef internal::field<Key, Element> Container;
typedef typename Container::Map_t Map_t;
};
private:
template <typename Element> struct _F {
typedef internal::field<Key, Element> T;
typedef typename T::Map_t Map_t;
};
/// Return the underlying map.
template <typename Element>
typename _F <Element>::Map_t& _map ()
{
return this->_F <Element>::T::map;
}
public:
/// Return the underlying map.
template <typename Element>
const typename traits<Element>::Map_t& map () const
{
return this->_F <Element>::T::map;
}
/// Add an element
template <typename Element>
void add (const Key& name, const Element& element)
{
_map <Element>()[name] = element;
}
/// Return the element named name
template <typename Element>
bool has (const Key& name) const
{
return (map<Element>().find (name) != map<Element>().end ());
}
/// Return the element named name
template <typename Element>
const Element& get (const Key& name) const
{
typename _F<Element>::Map_t::const_iterator it
= map<Element>().find (name);
if (it == map<Element>().end ())
throw std::runtime_error ("invalid key");
return it->second;
}
/// Return a list of all elements
/// \tparam ReturnType must have a push_back method.
template <typename Element, typename ReturnType>
ReturnType getAllAs () const
{
ReturnType l;
for (typename _F<Element>::Map_t::const_iterator
it = map<Element>().begin ();
it != map<Element>().end ();
++it)
l.push_back (it->second);
return l;
}
template <typename Element, typename ReturnType>
ReturnType getKeys () const
{
ReturnType l;
for (typename _F<Element>::Map_t::const_iterator
it = map<Element>().begin ();
it != map<Element>().end ();
++it)
l.push_back (it->first);
return l;
}
/// Print object in a stream
std::ostream& print (std::ostream& os) const
{
boost::mpl::for_each < Types > (print <false> (os));
return os;
}
/// Print object in a stream
std::ostream& printPointer (std::ostream& os) const
{
boost::mpl::for_each < Types > (print <true> (os));
return os;
}
};
} // namespace core
} // namespace hpp
#endif // HPP_CORE_CONTAINER_HH
|
Remove unused class Container
|
Remove unused class Container
|
C++
|
bsd-2-clause
|
humanoid-path-planner/hpp-core
|
244af332fcf8dee5362692731c5d591a956c763a
|
include/libtorrent/alloca.hpp
|
include/libtorrent/alloca.hpp
|
/*
Copyright (c) 2008, 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.
*/
#ifndef TORRENT_ALLOCA
#include "libtorrent/config.hpp"
#ifdef TORRENT_WINDOWS
#include <malloc.h>
#define TORRENT_ALLOCA(t, n) static_cast<t*>(_alloca(sizeof(t) * (n)));
#else
#include <alloca.h>
#define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n)));
#endif
#endif
|
/*
Copyright (c) 2008, 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.
*/
#ifndef TORRENT_ALLOCA
#include "libtorrent/config.hpp"
#ifdef TORRENT_WINDOWS
#include <malloc.h>
#define TORRENT_ALLOCA(t, n) static_cast<t*>(_alloca(sizeof(t) * (n)))
#else
#include <alloca.h>
#define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n)))
#endif
#endif
|
remove unnecessary semicolon
|
remove unnecessary semicolon
|
C++
|
bsd-3-clause
|
hamedramzi/libtorrent,snowyu/libtorrent,TeoTwawki/libtorrent,snowyu/libtorrent,TeoTwawki/libtorrent,hamedramzi/libtorrent,TeoTwawki/libtorrent,TeoTwawki/libtorrent,snowyu/libtorrent,hamedramzi/libtorrent,snowyu/libtorrent,TeoTwawki/libtorrent,TeoTwawki/libtorrent,hamedramzi/libtorrent,snowyu/libtorrent,snowyu/libtorrent,hamedramzi/libtorrent,hamedramzi/libtorrent
|
7cce7f2a876511b641efab1132dbe555c676453c
|
source/type/tests/accessible.cpp
|
source/type/tests/accessible.cpp
|
/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.
This file is part of Navitia,
the software to build cool stuff with public transport.
Hope you'll enjoy and contribute to this project,
powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
a non ending quest to the responsive locomotion way of traveling!
LICENCE: 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/>.
Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE test_navimake
#include <boost/test/unit_test.hpp>
#include "type/type.h"
using namespace navitia::type;
BOOST_AUTO_TEST_CASE(required_false_properties_false) {
Properties required_properties= 0;
StopPoint sp;
BOOST_CHECK_EQUAL(sp.accessible(required_properties), true);
}
BOOST_AUTO_TEST_CASE(required_false_properties_true) {
Properties required_properties = 0;
StopPoint sp;
sp.set_property(hasProperties::WHEELCHAIR_BOARDING);
BOOST_CHECK_EQUAL(sp.accessible(required_properties), true);
}
BOOST_AUTO_TEST_CASE(required_true_properties_false) {
Properties required_properties = 1;
StopPoint sp;
BOOST_CHECK_EQUAL(sp.accessible(required_properties), false);
}
BOOST_AUTO_TEST_CASE(required_true_properties_true) {
Properties required_properties = 1;
StopPoint sp;
sp.set_property(hasProperties::WHEELCHAIR_BOARDING);
BOOST_CHECK_EQUAL(sp.accessible(required_properties), true);
}
BOOST_AUTO_TEST_CASE(required_false_properties_false_const) {
Properties required_properties= 0;
StopPoint tmp_sp;
const StopPoint sp = tmp_sp;
BOOST_CHECK_EQUAL(sp.accessible(required_properties), true);
}
BOOST_AUTO_TEST_CASE(required_false_properties_true_const) {
Properties required_properties = 0;
StopPoint tmp_sp;
tmp_sp.set_property(hasProperties::WHEELCHAIR_BOARDING);
const StopPoint sp = tmp_sp;
BOOST_CHECK_EQUAL(sp.accessible(required_properties), true);
}
BOOST_AUTO_TEST_CASE(required_true_properties_false_const) {
Properties required_properties = 1;
StopPoint tmp_sp;
const StopPoint sp = tmp_sp;
BOOST_CHECK_EQUAL(sp.accessible(required_properties), false);
}
BOOST_AUTO_TEST_CASE(required_true_properties_true_const) {
Properties required_properties = 1;
StopPoint tmp_sp;
tmp_sp.set_property(hasProperties::WHEELCHAIR_BOARDING);
const StopPoint sp = tmp_sp;
BOOST_CHECK_EQUAL(sp.accessible(required_properties), true);
}
|
/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.
This file is part of Navitia,
the software to build cool stuff with public transport.
Hope you'll enjoy and contribute to this project,
powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
a non ending quest to the responsive locomotion way of traveling!
LICENCE: 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/>.
Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE test_navimake
#include <boost/test/unit_test.hpp>
#include "type/type.h"
using namespace navitia::type;
BOOST_AUTO_TEST_CASE(wcb_required_false_properties_false) {
Properties required_properties= 0;
StopPoint sp;
BOOST_CHECK_EQUAL(sp.accessible(required_properties), true);
}
BOOST_AUTO_TEST_CASE(wcb_required_false_properties_true) {
Properties required_properties = 0;
StopPoint sp;
sp.set_property(hasProperties::WHEELCHAIR_BOARDING);
BOOST_CHECK_EQUAL(sp.accessible(required_properties), true);
}
BOOST_AUTO_TEST_CASE(wcb_required_true_properties_false) {
Properties required_properties = 1;
StopPoint sp;
BOOST_CHECK_EQUAL(sp.accessible(required_properties), false);
}
BOOST_AUTO_TEST_CASE(wcb_required_true_properties_true) {
Properties required_properties = 1;
StopPoint sp;
sp.set_property(hasProperties::WHEELCHAIR_BOARDING);
BOOST_CHECK_EQUAL(sp.accessible(required_properties), true);
}
BOOST_AUTO_TEST_CASE(wcb_required_false_properties_false_const) {
Properties required_properties= 0;
StopPoint tmp_sp;
const StopPoint sp = tmp_sp;
BOOST_CHECK_EQUAL(sp.accessible(required_properties), true);
}
BOOST_AUTO_TEST_CASE(wcb_required_false_properties_true_const) {
Properties required_properties = 0;
StopPoint tmp_sp;
tmp_sp.set_property(hasProperties::WHEELCHAIR_BOARDING);
const StopPoint sp = tmp_sp;
BOOST_CHECK_EQUAL(sp.accessible(required_properties), true);
}
BOOST_AUTO_TEST_CASE(wcb_required_true_properties_false_const) {
Properties required_properties = 1;
StopPoint tmp_sp;
const StopPoint sp = tmp_sp;
BOOST_CHECK_EQUAL(sp.accessible(required_properties), false);
}
BOOST_AUTO_TEST_CASE(wcb_required_true_properties_true_const) {
Properties required_properties = 1;
StopPoint tmp_sp;
tmp_sp.set_property(hasProperties::WHEELCHAIR_BOARDING);
const StopPoint sp = tmp_sp;
BOOST_CHECK_EQUAL(sp.accessible(required_properties), true);
}
BOOST_AUTO_TEST_CASE(ba_required_false_properties_false) {
Properties required_properties= 0;
StopPoint sp;
BOOST_CHECK_EQUAL(sp.accessible(required_properties), true);
}
BOOST_AUTO_TEST_CASE(ba_required_false_properties_true) {
Properties required_properties = 0;
StopPoint sp;
sp.set_property(hasProperties::BIKE_ACCEPTED);
BOOST_CHECK_EQUAL(sp.accessible(required_properties), true);
}
BOOST_AUTO_TEST_CASE(ba_required_true_properties_false) {
Properties required_properties = 16;
StopPoint sp;
BOOST_CHECK_EQUAL(sp.accessible(required_properties), false);
}
BOOST_AUTO_TEST_CASE(ba_required_true_properties_true) {
Properties required_properties = 0;
StopPoint sp;
sp.set_property(hasProperties::BIKE_ACCEPTED);
BOOST_CHECK_EQUAL(sp.accessible(required_properties), true);
}
BOOST_AUTO_TEST_CASE(ba_required_false_properties_false_const) {
Properties required_properties= 0;
StopPoint tmp_sp;
const StopPoint sp = tmp_sp;
BOOST_CHECK_EQUAL(sp.accessible(required_properties), true);
}
BOOST_AUTO_TEST_CASE(ba_required_false_properties_true_const) {
Properties required_properties = 0;
StopPoint tmp_sp;
tmp_sp.set_property(hasProperties::BIKE_ACCEPTED);
const StopPoint sp = tmp_sp;
BOOST_CHECK_EQUAL(sp.accessible(required_properties), true);
}
BOOST_AUTO_TEST_CASE(ba_required_true_properties_false_const) {
Properties required_properties = 16;
StopPoint tmp_sp;
const StopPoint sp = tmp_sp;
BOOST_CHECK_EQUAL(sp.accessible(required_properties), false);
}
BOOST_AUTO_TEST_CASE(ba_required_true_properties_true_const) {
Properties required_properties = 16;
StopPoint tmp_sp;
tmp_sp.set_property(hasProperties::BIKE_ACCEPTED);
const StopPoint sp = tmp_sp;
BOOST_CHECK_EQUAL(sp.accessible(required_properties), true);
}
|
add accessible test
|
kraken: add accessible test
|
C++
|
agpl-3.0
|
xlqian/navitia,pbougue/navitia,Tisseo/navitia,xlqian/navitia,Tisseo/navitia,kinnou02/navitia,Tisseo/navitia,kadhikari/navitia,patochectp/navitia,patochectp/navitia,kinnou02/navitia,kadhikari/navitia,kadhikari/navitia,patochectp/navitia,Tisseo/navitia,pbougue/navitia,antoine-de/navitia,pbougue/navitia,xlqian/navitia,CanalTP/navitia,CanalTP/navitia,kadhikari/navitia,antoine-de/navitia,CanalTP/navitia,xlqian/navitia,CanalTP/navitia,antoine-de/navitia,kinnou02/navitia,pbougue/navitia,CanalTP/navitia,xlqian/navitia,Tisseo/navitia,patochectp/navitia,kinnou02/navitia,antoine-de/navitia
|
575281f3812f27966749d25bf34e5adb655be4ff
|
src/cbang/json/Value.cpp
|
src/cbang/json/Value.cpp
|
/******************************************************************************\
This file is part of the C! library. A.K.A the cbang library.
Copyright (c) 2003-2017, Cauldron Development LLC
Copyright (c) 2003-2017, Stanford University
All rights reserved.
The C! 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.
The C! 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 the C! library. If not, see
<http://www.gnu.org/licenses/>.
In addition, BSD licensing may be granted on a case by case basis
by written permission from at least one of the copyright holders.
You may request written permission by emailing the authors.
For information regarding this software email:
Joseph Coffland
[email protected]
\******************************************************************************/
#include "Value.h"
#include <sstream>
#include <limits>
using namespace std;
using namespace cb::JSON;
void Value::appendDict() {append(createDict());}
void Value::appendList() {append(createList());}
void Value::appendUndefined() {append(createUndefined());}
void Value::appendNull() {append(createNull());}
void Value::appendBoolean(bool value) {append(createBoolean(value));}
void Value::append(double value) {append(create(value));}
void Value::append(int64_t value) {append(create(value));}
void Value::append(uint64_t value) {append(create(value));}
void Value::append(const string &value) {append(create(value));}
void Value::setDict(unsigned i) {set(i, createDict());}
void Value::setList(unsigned i) {set(i, createList());}
void Value::setUndefined(unsigned i) {set(i, createUndefined());}
void Value::setNull(unsigned i) {set(i, createNull());}
void Value::setBoolean(unsigned i, bool value) {set(i, createBoolean(value));}
void Value::set(unsigned i, double value) {set(i, create(value));}
void Value::set(unsigned i, int64_t value) {set(i, create(value));}
void Value::set(unsigned i, uint64_t value) {set(i, create(value));}
void Value::set(unsigned i, const string &value) {set(i, create(value));}
void Value::insertDict(const string &key) {insert(key, createDict());}
void Value::insertList(const string &key) {insert(key, createList());}
void Value::insertUndefined(const string &key) {insert(key, createUndefined());}
void Value::insertNull(const string &key) {insert(key, createNull());}
void Value::insertBoolean(const string &key, bool value) {
insert(key, createBoolean(value));
}
void Value::insert(const string &key, double value) {
insert(key, create(value));
}
void Value::insert(const string &key, uint64_t value) {
insert(key, create(value));
}
void Value::insert(const string &key, int64_t value) {
insert(key, create(value));
}
void Value::insert(const string &key, const string &value) {
insert(key, create(value));
}
void Value::merge(const Value &value) {
// Merge lists
if (isList() && value.isList()) {
for (unsigned i = 0; i < value.size(); i++)
append(value.get(i));
return;
}
if (!isDict() || !value.isDict())
THROWS("Cannot merge JSON nodes of type " << getType() << " and "
<< value.getType());
// Merge dicts
for (unsigned i = 0; i < value.size(); i++) {
const string &key = value.keyAt(i);
ValuePtr src = value.get(i);
if (has(key)) {
ValuePtr dst = get(key);
if ((src->isDict() && dst->isDict()) ||
(src->isList() && dst->isList())) {
dst->merge(*src);
continue;
}
}
insert(key, src);
}
}
string Value::format(char type) const {
switch (type) {
case 'b': return String(getBoolean());
case 'f': return String(getNumber());
case 'i': return String(getS32());
case 'u': return String(getU32());
case 's': return "\"" + String::escapeC(asString()) + "\"";
}
THROWS("Unsupported format type specifier '"
<< String::escapeC(string(1, type)) << "'");
}
string Value::format(char type, int index, const string &name,
const String::FormatCB &cb) const {
if (index < 0) {
if (has(name)) return get(name)->format(type);
} else if ((unsigned)index < size()) return get(index)->format(type);
return cb(type, index, name);
}
string Value::format(const string &s, const String::FormatCB &cb) const {
class FormatCB : public String::FormatCB {
const Value &value;
const String::FormatCB &cb;
public:
FormatCB(const Value &value, const String::FormatCB &cb) :
value(value), cb(cb) {}
string operator()(char type, int index, const string &name) const {
return value.format(type, index, name, cb);
}
};
return String(s).format(FormatCB(*this, cb));
}
string Value::format(const string &s, const string &defaultValue) const {
return String(s).format(String::DefaultFormatCB(defaultValue));
}
string Value::toString(unsigned indent, bool compact) const {
ostringstream str;
Writer writer(str, indent, compact);
write(writer);
str << flush;
return str.str();
}
string Value::asString() const {return isString() ? getString() : toString();}
|
/******************************************************************************\
This file is part of the C! library. A.K.A the cbang library.
Copyright (c) 2003-2017, Cauldron Development LLC
Copyright (c) 2003-2017, Stanford University
All rights reserved.
The C! 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.
The C! 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 the C! library. If not, see
<http://www.gnu.org/licenses/>.
In addition, BSD licensing may be granted on a case by case basis
by written permission from at least one of the copyright holders.
You may request written permission by emailing the authors.
For information regarding this software email:
Joseph Coffland
[email protected]
\******************************************************************************/
#include "Value.h"
#include <sstream>
#include <limits>
using namespace std;
using namespace cb::JSON;
void Value::appendDict() {append(createDict());}
void Value::appendList() {append(createList());}
void Value::appendUndefined() {append(createUndefined());}
void Value::appendNull() {append(createNull());}
void Value::appendBoolean(bool value) {append(createBoolean(value));}
void Value::append(double value) {append(create(value));}
void Value::append(int64_t value) {append(create(value));}
void Value::append(uint64_t value) {append(create(value));}
void Value::append(const string &value) {append(create(value));}
void Value::setDict(unsigned i) {set(i, createDict());}
void Value::setList(unsigned i) {set(i, createList());}
void Value::setUndefined(unsigned i) {set(i, createUndefined());}
void Value::setNull(unsigned i) {set(i, createNull());}
void Value::setBoolean(unsigned i, bool value) {set(i, createBoolean(value));}
void Value::set(unsigned i, double value) {set(i, create(value));}
void Value::set(unsigned i, int64_t value) {set(i, create(value));}
void Value::set(unsigned i, uint64_t value) {set(i, create(value));}
void Value::set(unsigned i, const string &value) {set(i, create(value));}
void Value::insertDict(const string &key) {insert(key, createDict());}
void Value::insertList(const string &key) {insert(key, createList());}
void Value::insertUndefined(const string &key) {insert(key, createUndefined());}
void Value::insertNull(const string &key) {insert(key, createNull());}
void Value::insertBoolean(const string &key, bool value) {
insert(key, createBoolean(value));
}
void Value::insert(const string &key, double value) {
insert(key, create(value));
}
void Value::insert(const string &key, uint64_t value) {
insert(key, create(value));
}
void Value::insert(const string &key, int64_t value) {
insert(key, create(value));
}
void Value::insert(const string &key, const string &value) {
insert(key, create(value));
}
void Value::merge(const Value &value) {
// Merge lists
if (isList() && value.isList()) {
for (unsigned i = 0; i < value.size(); i++)
append(value.get(i));
return;
}
if (!isDict() || !value.isDict())
THROWS("Cannot merge JSON nodes of type " << getType() << " and "
<< value.getType());
// Merge dicts
for (unsigned i = 0; i < value.size(); i++) {
const string &key = value.keyAt(i);
ValuePtr src = value.get(i);
if (has(key)) {
ValuePtr dst = get(key);
if ((src->isDict() && dst->isDict()) ||
(src->isList() && dst->isList())) {
dst->merge(*src);
continue;
}
}
insert(key, src);
}
}
string Value::format(char type) const {
switch (type) {
case 'b': return String(getBoolean());
case 'f': return String(getNumber());
case 'i': return String(getS32());
case 'u': return String(getU32());
case 's': return "\"" + String::escapeC(asString()) + "\"";
}
THROWS("Unsupported format type specifier '"
<< String::escapeC(string(1, type)) << "'");
}
string Value::format(char type, int index, const string &name,
const String::FormatCB &cb) const {
if (index < 0) {
if (has(name)) return get(name)->format(type);
} else if ((unsigned)index < size()) return get(index)->format(type);
return cb(type, index, name);
}
string Value::format(const string &s, const String::FormatCB &cb) const {
class FormatCB : public String::FormatCB {
const Value &value;
const String::FormatCB &cb;
public:
FormatCB(const Value &value, const String::FormatCB &cb) :
value(value), cb(cb) {}
string operator()(char type, int index, const string &name) const {
return value.format(type, index, name, cb);
}
};
return String(s).format(FormatCB(*this, cb));
}
string Value::format(const string &s, const string &defaultValue) const {
return format(s, String::DefaultFormatCB(defaultValue));
}
string Value::toString(unsigned indent, bool compact) const {
ostringstream str;
Writer writer(str, indent, compact);
write(writer);
str << flush;
return str.str();
}
string Value::asString() const {return isString() ? getString() : toString();}
|
Fix JSON string formatting
|
Fix JSON string formatting
|
C++
|
lgpl-2.1
|
CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang
|
de9dea771b50aeef8db854a37bd74737dedbe498
|
libnd4j/include/ops/declarable/generic/broadcastable/multiply.cpp
|
libnd4j/include/ops/declarable/generic/broadcastable/multiply.cpp
|
/* ******************************************************************************
*
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* 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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// @author [email protected]
// @author Yurii Shyrma ([email protected])
//
#include <system/op_boilerplate.h>
#if NOT_EXCLUDED(OP_multiply)
#include <ops/declarable/CustomOperations.h>
namespace sd {
namespace ops {
BROADCASTABLE_OP_IMPL(multiply, 0, 0) {
auto x = INPUT_VARIABLE(0);
auto y = INPUT_VARIABLE(1);
auto z = OUTPUT_VARIABLE(0);
BROADCAST_CHECK_EMPTY(x, y, z);
const sd::LongType* zShapeInfo = nullptr;
const bool areShapesBroadcastable =
ShapeUtils::evalBroadcastShapeInfo(x->shapeInfo(), y->shapeInfo(), true, zShapeInfo, block.getWorkspace());
REQUIRE_TRUE(areShapesBroadcastable, 0, "MULTIPLY OP: the shapes of x %s and y %s are not suitable for broadcast !",
ShapeUtils::shapeAsString(x).c_str(), ShapeUtils::shapeAsString(y).c_str());
auto tZ = BroadcastHelper::broadcastApply(sd::BroadcastOpsTuple::Multiply(), x, y, z);
if (tZ == nullptr)
return sd::Status::KERNEL_FAILURE;
else if (tZ != z)
throw std::runtime_error("multiply: result was replaced");
return sd::Status::OK;
}
DECLARE_SYN(Mul, multiply);
DECLARE_TYPES(multiply) {
getOpDescriptor()
->setAllowedInputTypes(0, DataType::ANY)
->setAllowedInputTypes(1, DataType::ANY)
->setAllowedOutputTypes(0, DataType::INHERIT);
}
DECLARE_TYPES(multiply_bp) {
getOpDescriptor()->setAllowedInputTypes(DataType::ANY)->setAllowedOutputTypes({ALL_FLOATS});
}
///////////////////////////////////////////////////////////////////
CUSTOM_OP_IMPL(multiply_bp, 3, 2, false, 0, 0) {
auto x = INPUT_VARIABLE(0);
auto y = INPUT_VARIABLE(1);
auto dLdz = INPUT_VARIABLE(2);
auto dLdx = OUTPUT_VARIABLE(0);
auto dLdy = OUTPUT_VARIABLE(1);
const sd::LongType* dLdzShapeInfo = nullptr;
const bool areShapesBroadcastable =
ShapeUtils::evalBroadcastShapeInfo(x->shapeInfo(), y->shapeInfo(), true, dLdzShapeInfo, block.getWorkspace());
REQUIRE_TRUE(areShapesBroadcastable, 0,
"MULTIPLY_BP OP: the shapes of x %s and y %s are not suitable for broadcast !",
ShapeUtils::shapeAsString(x).c_str(), ShapeUtils::shapeAsString(y).c_str());
REQUIRE_TRUE(shape::equalsSoft(dLdz->shapeInfo(), dLdzShapeInfo), 0,
"MULTIPLY_BP OP: wrong shape of next epsilon array (dLdOut), expected is %s, but got %s instead !",
ShapeUtils::shapeAsString(dLdzShapeInfo).c_str(), ShapeUtils::shapeAsString(dLdz).c_str());
const sd::LongType xLen = x->lengthOf();
const sd::LongType yLen = y->lengthOf();
if (x->isScalar() && y->isScalar()) { // both are scalars
y->applyPairwiseTransform(pairwise::Multiply, *dLdz, *dLdx);
x->applyPairwiseTransform(pairwise::Multiply, *dLdz, *dLdy);
// dLdx->assign((*y) * (*dLdz));
// dLdy->assign((*x) * (*dLdz));
} else if (x->isScalar()) { // x is scalar and y is not
dLdx->assign((*y * *dLdz).reduceNumber(reduce::Sum));
dLdz->applyScalarArr(scalar::Multiply, *x, *dLdy);
// dLdz->applyTrueBroadcast(broadcast::Multiply, x, dLdy, true);
} else if (y->isScalar()) { // y is scalar and x is not
dLdy->assign((*x * *dLdz).reduceNumber(reduce::Sum));
dLdz->applyScalarArr(scalar::Multiply, *y, *dLdx);
} else if (x->isSameShape(y)) {
x->applyPairwiseTransform(pairwise::Multiply, *dLdz, *dLdy);
y->applyPairwiseTransform(pairwise::Multiply, *dLdz, *dLdx);
} else if (x->isSameShape(dLdz)) {
auto yTiled = NDArray(dLdz, false, block.launchContext());
y->tile(yTiled);
std::vector<int> axesForY = ShapeUtils::evalBroadcastBackwardAxis(y->shapeInfo(), dLdz->shapeInfo());
dLdy->assign((*x * *dLdz).reduceAlongDimension(reduce::Sum, axesForY));
yTiled.applyPairwiseTransform(pairwise::Multiply, *dLdz, *dLdx);
} else if (y->isSameShape(dLdz)) {
auto xTiled = NDArray(dLdz, false, block.launchContext());
x->tile(xTiled);
std::vector<int> axesForX = ShapeUtils::evalBroadcastBackwardAxis(x->shapeInfo(), dLdz->shapeInfo());
dLdx->assign((*y * *dLdz).reduceAlongDimension(reduce::Sum, axesForX));
xTiled.applyPairwiseTransform(pairwise::Multiply, *dLdz, *dLdy);
} else {
auto xTiled = NDArray(dLdz, false, block.launchContext());
auto yTiled = NDArray(dLdz, false, block.launchContext());
x->tile(xTiled);
y->tile(yTiled);
std::vector<int> axesForX = ShapeUtils::evalBroadcastBackwardAxis(x->shapeInfo(), dLdz->shapeInfo());
std::vector<int> axesForY = ShapeUtils::evalBroadcastBackwardAxis(y->shapeInfo(), dLdz->shapeInfo());
dLdx->assign((*y * *dLdz).reduceAlongDimension(reduce::Sum, axesForX));
dLdy->assign((*x * *dLdz).reduceAlongDimension(reduce::Sum, axesForY));
}
return sd::Status::OK;
}
DECLARE_SHAPE_FN(multiply_bp) {
auto xShapeInfo = inputShape->at(0);
auto yShapeInfo = inputShape->at(1);
sd::LongType* dLdxShapeInfo = nullptr;
sd::LongType* dLdyShapeInfo = nullptr;
COPY_SHAPE(xShapeInfo, dLdxShapeInfo);
COPY_SHAPE(yShapeInfo, dLdyShapeInfo);
return SHAPELIST(CONSTANT(dLdxShapeInfo), CONSTANT(dLdyShapeInfo));
}
/*
CUSTOM_OP_IMPL(multiply_bp, 3, 2, false, 0, 0) {
auto x = INPUT_VARIABLE(0);
auto y = INPUT_VARIABLE(1);
auto epsNext = INPUT_VARIABLE(2);
auto gradX = OUTPUT_VARIABLE(0);
auto gradY = OUTPUT_VARIABLE(1);
auto lambdaX = LAMBDA_TT(_e, _y) {
return _e * _y;
};
auto lambdaY = LAMBDA_TT(_e, _x) {
return _e * _x;
};
if (x->isSameShape(y)) {
// PWT case case
// X gradient
epsNext->applyPairwiseLambda(y, lambdaX, gradX);
// Y gradient
epsNext->applyPairwiseLambda(x, lambdaY, gradY);
} else if (y->isScalar()) {
// scalar case
T _y = y->e(0);
auto lambdaS = LAMBDA_T(_e, _y) {
return _e * _y;
};
T tmpX = x->template reduceNumber<simdOps::Sum<T>>();
gradY->assign(tmpX);
epsNext->applyLambda(lambdaS, *gradX);
} else {
// broadcast case
auto preX = x->dup();
auto preY = y->dup();
auto targetShape = epsNext->getShapeAsVector();
preX->tileToShape(targetShape);
preY->tileToShape(targetShape);
auto axisX = ShapeUtils::evalBroadcastBackwardAxis(x->shapeInfo(), epsNext->shapeInfo());
auto axisY = ShapeUtils::evalBroadcastBackwardAxis(y->shapeInfo(), epsNext->shapeInfo());
if (axisX.size() > 0) {
auto sum = preX->template reduceAlongDimension<simdOps::Sum<T>>(axisX);
gradX->assign(sum);
delete sum;
} else
gradX->assign(preX);
if (axisY.size() > 0) {
auto sum = preY->template reduceAlongDimension<simdOps::Sum<T>>(axisY);
gradY->assign(sum);
delete sum;
} else
gradY->assign(preY);
delete preX;
delete preY;
}
return sd::Status::OK;
}
*/
} // namespace ops
} // namespace sd
#endif
|
/* ******************************************************************************
*
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* 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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// @author [email protected]
// @author Yurii Shyrma ([email protected])
//
#include <system/op_boilerplate.h>
#if NOT_EXCLUDED(OP_multiply)
#include <ops/declarable/CustomOperations.h>
namespace sd {
namespace ops {
BROADCASTABLE_OP_IMPL(multiply, 0, 0) {
auto x = INPUT_VARIABLE(0);
auto y = INPUT_VARIABLE(1);
auto z = OUTPUT_VARIABLE(0);
BROADCAST_CHECK_EMPTY(x, y, z);
const sd::LongType* zShapeInfo = nullptr;
const bool areShapesBroadcastable =
ShapeUtils::evalBroadcastShapeInfo(x->shapeInfo(), y->shapeInfo(), true, zShapeInfo, block.getWorkspace());
REQUIRE_TRUE(areShapesBroadcastable, 0, "MULTIPLY OP: the shapes of x %s and y %s are not suitable for broadcast !",
ShapeUtils::shapeAsString(x).c_str(), ShapeUtils::shapeAsString(y).c_str());
auto tZ = BroadcastHelper::broadcastApply(sd::BroadcastOpsTuple::Multiply(), x, y, z);
if (tZ == nullptr)
return sd::Status::KERNEL_FAILURE;
else if (tZ != z)
throw std::runtime_error("multiply: result was replaced");
return sd::Status::OK;
}
DECLARE_SYN(Mul, multiply);
DECLARE_TYPES(multiply) {
getOpDescriptor()
->setAllowedInputTypes(0, DataType::ANY)
->setAllowedInputTypes(1, DataType::ANY)
->setAllowedOutputTypes(0, DataType::INHERIT);
}
DECLARE_TYPES(multiply_bp) {
getOpDescriptor()->setAllowedInputTypes(DataType::ANY)->setAllowedOutputTypes({ALL_FLOATS});
}
///////////////////////////////////////////////////////////////////
CUSTOM_OP_IMPL(multiply_bp, 3, 2, false, 0, 0) {
auto x = INPUT_VARIABLE(0);
auto y = INPUT_VARIABLE(1);
auto dLdz = INPUT_VARIABLE(2);
auto dLdx = OUTPUT_VARIABLE(0);
auto dLdy = OUTPUT_VARIABLE(1);
const sd::LongType* dLdzShapeInfo = nullptr;
const bool areShapesBroadcastable =
ShapeUtils::evalBroadcastShapeInfo(x->shapeInfo(), y->shapeInfo(), true, dLdzShapeInfo, block.getWorkspace());
REQUIRE_TRUE(areShapesBroadcastable, 0,
"MULTIPLY_BP OP: the shapes of x %s and y %s are not suitable for broadcast !",
ShapeUtils::shapeAsString(x).c_str(), ShapeUtils::shapeAsString(y).c_str());
const sd::LongType xLen = x->lengthOf();
const sd::LongType yLen = y->lengthOf();
if (x->isScalar() && y->isScalar()) { // both are scalars
y->applyPairwiseTransform(pairwise::Multiply, *dLdz, *dLdx);
x->applyPairwiseTransform(pairwise::Multiply, *dLdz, *dLdy);
// dLdx->assign((*y) * (*dLdz));
// dLdy->assign((*x) * (*dLdz));
} else if (x->isScalar()) { // x is scalar and y is not
dLdx->assign((*y * *dLdz).reduceNumber(reduce::Sum));
dLdz->applyScalarArr(scalar::Multiply, *x, *dLdy);
// dLdz->applyTrueBroadcast(broadcast::Multiply, x, dLdy, true);
} else if (y->isScalar()) { // y is scalar and x is not
dLdy->assign((*x * *dLdz).reduceNumber(reduce::Sum));
dLdz->applyScalarArr(scalar::Multiply, *y, *dLdx);
} else if (x->isSameShape(y)) {
x->applyPairwiseTransform(pairwise::Multiply, *dLdz, *dLdy);
y->applyPairwiseTransform(pairwise::Multiply, *dLdz, *dLdx);
} else if (x->isSameShape(dLdz)) {
auto yTiled = NDArray(dLdz, false, block.launchContext());
y->tile(yTiled);
std::vector<int> axesForY = ShapeUtils::evalBroadcastBackwardAxis(y->shapeInfo(), dLdz->shapeInfo());
dLdy->assign((*x * *dLdz).reduceAlongDimension(reduce::Sum, axesForY));
yTiled.applyPairwiseTransform(pairwise::Multiply, *dLdz, *dLdx);
} else if (y->isSameShape(dLdz)) {
auto xTiled = NDArray(dLdz, false, block.launchContext());
x->tile(xTiled);
std::vector<int> axesForX = ShapeUtils::evalBroadcastBackwardAxis(x->shapeInfo(), dLdz->shapeInfo());
dLdx->assign((*y * *dLdz).reduceAlongDimension(reduce::Sum, axesForX));
xTiled.applyPairwiseTransform(pairwise::Multiply, *dLdz, *dLdy);
} else {
auto xTiled = NDArray(dLdz, false, block.launchContext());
auto yTiled = NDArray(dLdz, false, block.launchContext());
x->tile(xTiled);
y->tile(yTiled);
std::vector<int> axesForX = ShapeUtils::evalBroadcastBackwardAxis(x->shapeInfo(), dLdz->shapeInfo());
std::vector<int> axesForY = ShapeUtils::evalBroadcastBackwardAxis(y->shapeInfo(), dLdz->shapeInfo());
dLdx->assign((*y * *dLdz).reduceAlongDimension(reduce::Sum, axesForX));
dLdy->assign((*x * *dLdz).reduceAlongDimension(reduce::Sum, axesForY));
}
return sd::Status::OK;
}
DECLARE_SHAPE_FN(multiply_bp) {
auto xShapeInfo = inputShape->at(0);
auto yShapeInfo = inputShape->at(1);
sd::LongType* dLdxShapeInfo = nullptr;
sd::LongType* dLdyShapeInfo = nullptr;
COPY_SHAPE(xShapeInfo, dLdxShapeInfo);
COPY_SHAPE(yShapeInfo, dLdyShapeInfo);
return SHAPELIST(CONSTANT(dLdxShapeInfo), CONSTANT(dLdyShapeInfo));
}
/*
CUSTOM_OP_IMPL(multiply_bp, 3, 2, false, 0, 0) {
auto x = INPUT_VARIABLE(0);
auto y = INPUT_VARIABLE(1);
auto epsNext = INPUT_VARIABLE(2);
auto gradX = OUTPUT_VARIABLE(0);
auto gradY = OUTPUT_VARIABLE(1);
auto lambdaX = LAMBDA_TT(_e, _y) {
return _e * _y;
};
auto lambdaY = LAMBDA_TT(_e, _x) {
return _e * _x;
};
if (x->isSameShape(y)) {
// PWT case case
// X gradient
epsNext->applyPairwiseLambda(y, lambdaX, gradX);
// Y gradient
epsNext->applyPairwiseLambda(x, lambdaY, gradY);
} else if (y->isScalar()) {
// scalar case
T _y = y->e(0);
auto lambdaS = LAMBDA_T(_e, _y) {
return _e * _y;
};
T tmpX = x->template reduceNumber<simdOps::Sum<T>>();
gradY->assign(tmpX);
epsNext->applyLambda(lambdaS, *gradX);
} else {
// broadcast case
auto preX = x->dup();
auto preY = y->dup();
auto targetShape = epsNext->getShapeAsVector();
preX->tileToShape(targetShape);
preY->tileToShape(targetShape);
auto axisX = ShapeUtils::evalBroadcastBackwardAxis(x->shapeInfo(), epsNext->shapeInfo());
auto axisY = ShapeUtils::evalBroadcastBackwardAxis(y->shapeInfo(), epsNext->shapeInfo());
if (axisX.size() > 0) {
auto sum = preX->template reduceAlongDimension<simdOps::Sum<T>>(axisX);
gradX->assign(sum);
delete sum;
} else
gradX->assign(preX);
if (axisY.size() > 0) {
auto sum = preY->template reduceAlongDimension<simdOps::Sum<T>>(axisY);
gradY->assign(sum);
delete sum;
} else
gradY->assign(preY);
delete preX;
delete preY;
}
return sd::Status::OK;
}
*/
} // namespace ops
} // namespace sd
#endif
|
Allow scalar on mul_bp
|
Allow scalar on mul_bp
|
C++
|
apache-2.0
|
deeplearning4j/deeplearning4j,deeplearning4j/deeplearning4j,deeplearning4j/deeplearning4j,deeplearning4j/deeplearning4j,deeplearning4j/deeplearning4j,deeplearning4j/deeplearning4j,deeplearning4j/deeplearning4j,deeplearning4j/deeplearning4j,deeplearning4j/deeplearning4j,deeplearning4j/deeplearning4j
|
25d524c942896446bfd540464c51174c754105bf
|
src/omnicore/rpcrequirements.cpp
|
src/omnicore/rpcrequirements.cpp
|
#include "omnicore/rpcrequirements.h"
#include "omnicore/dex.h"
#include "omnicore/omnicore.h"
#include "omnicore/sp.h"
#include "amount.h"
#include "main.h"
#include "rpcprotocol.h"
#include "tinyformat.h"
#include <stdint.h>
#include <string>
void RequireBalance(const std::string& address, uint32_t propertyId, int64_t amount)
{
int64_t balance = getMPbalance(address, propertyId, BALANCE);
if (balance < amount) {
throw JSONRPCError(RPC_TYPE_ERROR, "Sender has insufficient balance");
}
int64_t balanceUnconfirmed = getUserAvailableMPbalance(address, propertyId);
if (balanceUnconfirmed < amount) {
throw JSONRPCError(RPC_TYPE_ERROR, "Sender has insufficient balance (due to pending transactions)");
}
}
void RequirePrimaryToken(uint32_t propertyId)
{
if (propertyId < 1 || 2 < propertyId) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Property identifier must be 1 (MSC) or 2 (TMSC)");
}
}
void RequirePropertyName(const std::string& name)
{
if (name.empty()) {
throw JSONRPCError(RPC_TYPE_ERROR, "Property name must not be empty");
}
}
void RequireExistingProperty(uint32_t propertyId)
{
if (!mastercore::_my_sps->hasSP(propertyId)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Property identifier does not exist");
}
}
void RequireSameEcosystem(uint32_t propertyId, uint32_t otherId)
{
if (mastercore::isTestEcosystemProperty(propertyId) != mastercore::isTestEcosystemProperty(otherId)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Properties must be in the same ecosystem");
}
}
void RequireDifferentIds(uint32_t propertyId, uint32_t otherId)
{
if (propertyId == otherId) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Property identifiers must not be the same");
}
}
void RequireCrowdsale(uint32_t propertyId)
{
CMPSPInfo::Entry sp;
if (!mastercore::_my_sps->getSP(propertyId, sp)) {
throw JSONRPCError(RPC_DATABASE_ERROR, "Failed to retrieve property");
}
if (sp.fixed || sp.manual) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Property identifier does not refer to a crowdsale");
}
}
void RequireActiveCrowdsale(uint32_t propertyId)
{
if (!mastercore::isCrowdsaleActive(propertyId)) {
throw JSONRPCError(RPC_TYPE_ERROR, "Property identifier does not refer to an active crowdsale");
}
}
void RequireManagedProperty(uint32_t propertyId)
{
CMPSPInfo::Entry sp;
if (!mastercore::_my_sps->getSP(propertyId, sp)) {
throw JSONRPCError(RPC_DATABASE_ERROR, "Failed to retrieve property");
}
if (sp.fixed || !sp.manual) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Property identifier does not refer to a managed property");
}
}
void RequireTokenIssuer(const std::string& address, uint32_t propertyId)
{
CMPSPInfo::Entry sp;
if (!mastercore::_my_sps->getSP(propertyId, sp)) {
throw JSONRPCError(RPC_DATABASE_ERROR, "Failed to retrieve property");
}
if (address != sp.issuer) {
throw JSONRPCError(RPC_TYPE_ERROR, "Sender is not authorized to manage the property");
}
}
void RequireMatchingDExOffer(const std::string& address, uint32_t propertyId)
{
if (!mastercore::DEx_offerExists(address, propertyId)) {
throw JSONRPCError(RPC_TYPE_ERROR, "No matching sell offer on the distributed exchange");
}
}
void RequireNoOtherDExOffer(const std::string& address, uint32_t propertyId)
{
if (mastercore::DEx_offerExists(address, propertyId)) {
throw JSONRPCError(RPC_TYPE_ERROR, "Another active sell offer from the given address already exists on the distributed exchange");
}
}
void RequireSaneReferenceAmount(int64_t amount)
{
if ((0.01 * COIN) < amount) {
throw JSONRPCError(RPC_TYPE_ERROR, "Reference amount higher is than 0.01 BTC");
}
}
void RequireSaneDExPaymentWindow(const std::string& address, uint32_t propertyId)
{
CMPOffer* poffer = mastercore::DEx_getOffer(address, propertyId);
if (poffer == NULL) {
throw JSONRPCError(RPC_DATABASE_ERROR, "Unable to load sell offer from the distributed exchange");
}
if (poffer->getBlockTimeLimit() < 10) {
throw JSONRPCError(RPC_TYPE_ERROR, "Payment window is less than 10 blocks (use override = true to continue)");
}
}
void RequireSaneDExFee(const std::string& address, uint32_t propertyId)
{
CMPOffer* poffer = mastercore::DEx_getOffer(address, propertyId);
if (poffer == NULL) {
throw JSONRPCError(RPC_DATABASE_ERROR, "Unable to load sell offer from the distributed exchange");
}
if (poffer->getMinFee() > 1000000) {
throw JSONRPCError(RPC_TYPE_ERROR, "Minimum accept fee is higher than 0.01 BTC (use override = true to continue)");
}
}
void RequireHeightInChain(int blockHeight)
{
if (blockHeight < 0 || chainActive.Height() < blockHeight) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height is out of range");
}
}
|
#include "omnicore/rpcrequirements.h"
#include "omnicore/dex.h"
#include "omnicore/omnicore.h"
#include "omnicore/sp.h"
#include "amount.h"
#include "main.h"
#include "rpcprotocol.h"
#include "sync.h"
#include "tinyformat.h"
#include <stdint.h>
#include <string>
void RequireBalance(const std::string& address, uint32_t propertyId, int64_t amount)
{
int64_t balance = getMPbalance(address, propertyId, BALANCE);
if (balance < amount) {
throw JSONRPCError(RPC_TYPE_ERROR, "Sender has insufficient balance");
}
int64_t balanceUnconfirmed = getUserAvailableMPbalance(address, propertyId);
if (balanceUnconfirmed < amount) {
throw JSONRPCError(RPC_TYPE_ERROR, "Sender has insufficient balance (due to pending transactions)");
}
}
void RequirePrimaryToken(uint32_t propertyId)
{
if (propertyId < 1 || 2 < propertyId) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Property identifier must be 1 (MSC) or 2 (TMSC)");
}
}
void RequirePropertyName(const std::string& name)
{
if (name.empty()) {
throw JSONRPCError(RPC_TYPE_ERROR, "Property name must not be empty");
}
}
void RequireExistingProperty(uint32_t propertyId)
{
LOCK(cs_tally);
if (!mastercore::_my_sps->hasSP(propertyId)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Property identifier does not exist");
}
}
void RequireSameEcosystem(uint32_t propertyId, uint32_t otherId)
{
if (mastercore::isTestEcosystemProperty(propertyId) != mastercore::isTestEcosystemProperty(otherId)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Properties must be in the same ecosystem");
}
}
void RequireDifferentIds(uint32_t propertyId, uint32_t otherId)
{
if (propertyId == otherId) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Property identifiers must not be the same");
}
}
void RequireCrowdsale(uint32_t propertyId)
{
LOCK(cs_tally);
CMPSPInfo::Entry sp;
if (!mastercore::_my_sps->getSP(propertyId, sp)) {
throw JSONRPCError(RPC_DATABASE_ERROR, "Failed to retrieve property");
}
if (sp.fixed || sp.manual) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Property identifier does not refer to a crowdsale");
}
}
void RequireActiveCrowdsale(uint32_t propertyId)
{
LOCK(cs_tally);
if (!mastercore::isCrowdsaleActive(propertyId)) {
throw JSONRPCError(RPC_TYPE_ERROR, "Property identifier does not refer to an active crowdsale");
}
}
void RequireManagedProperty(uint32_t propertyId)
{
LOCK(cs_tally);
CMPSPInfo::Entry sp;
if (!mastercore::_my_sps->getSP(propertyId, sp)) {
throw JSONRPCError(RPC_DATABASE_ERROR, "Failed to retrieve property");
}
if (sp.fixed || !sp.manual) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Property identifier does not refer to a managed property");
}
}
void RequireTokenIssuer(const std::string& address, uint32_t propertyId)
{
LOCK(cs_tally);
CMPSPInfo::Entry sp;
if (!mastercore::_my_sps->getSP(propertyId, sp)) {
throw JSONRPCError(RPC_DATABASE_ERROR, "Failed to retrieve property");
}
if (address != sp.issuer) {
throw JSONRPCError(RPC_TYPE_ERROR, "Sender is not authorized to manage the property");
}
}
void RequireMatchingDExOffer(const std::string& address, uint32_t propertyId)
{
LOCK(cs_tally);
if (!mastercore::DEx_offerExists(address, propertyId)) {
throw JSONRPCError(RPC_TYPE_ERROR, "No matching sell offer on the distributed exchange");
}
}
void RequireNoOtherDExOffer(const std::string& address, uint32_t propertyId)
{
LOCK(cs_tally);
if (mastercore::DEx_offerExists(address, propertyId)) {
throw JSONRPCError(RPC_TYPE_ERROR, "Another active sell offer from the given address already exists on the distributed exchange");
}
}
void RequireSaneReferenceAmount(int64_t amount)
{
if ((0.01 * COIN) < amount) {
throw JSONRPCError(RPC_TYPE_ERROR, "Reference amount higher is than 0.01 BTC");
}
}
void RequireSaneDExPaymentWindow(const std::string& address, uint32_t propertyId)
{
LOCK(cs_tally);
const CMPOffer* poffer = mastercore::DEx_getOffer(address, propertyId);
if (poffer == NULL) {
throw JSONRPCError(RPC_DATABASE_ERROR, "Unable to load sell offer from the distributed exchange");
}
if (poffer->getBlockTimeLimit() < 10) {
throw JSONRPCError(RPC_TYPE_ERROR, "Payment window is less than 10 blocks (use override = true to continue)");
}
}
void RequireSaneDExFee(const std::string& address, uint32_t propertyId)
{
LOCK(cs_tally);
const CMPOffer* poffer = mastercore::DEx_getOffer(address, propertyId);
if (poffer == NULL) {
throw JSONRPCError(RPC_DATABASE_ERROR, "Unable to load sell offer from the distributed exchange");
}
if (poffer->getMinFee() > 1000000) {
throw JSONRPCError(RPC_TYPE_ERROR, "Minimum accept fee is higher than 0.01 BTC (use override = true to continue)");
}
}
void RequireHeightInChain(int blockHeight)
{
if (blockHeight < 0 || mastercore::GetHeight() < blockHeight) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height is out of range");
}
}
|
Add locks for RPC requirement checks
|
Add locks for RPC requirement checks
|
C++
|
mit
|
OmniLayer/omnicore,OmniLayer/omnicore,OmniLayer/omnicore,OmniLayer/omnicore,OmniLayer/omnicore,OmniLayer/omnicore
|
b309d8241cc78fe99d8ca559d2c6463fc072c27e
|
sdc-plugin/sdc.cc
|
sdc-plugin/sdc.cc
|
/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <[email protected]>
* Copyright (C) 2020 The Symbiflow Authors
*
* 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 "kernel/register.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
void register_in_tcl_interpreter(const std::string& command) {
Tcl_Interp* interp = yosys_get_tcl_interp();
std::string tcl_script = stringf("proc %s args { return [yosys %s {*}$args] }", command.c_str(), command.c_str());
Tcl_Eval(interp, tcl_script.c_str());
}
struct ReadSdc : public Frontend {
ReadSdc()
: Frontend("sdc", "Read SDC file"){}
void help() override {
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" read_sdc <filename>\n");
log("\n");
log("Read SDC file.\n");
log("\n");
}
void execute(std::istream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design*) override {
if (args.size() < 2) {
log_cmd_error("Missing script file.\n");
}
size_t argidx = 1;
extra_args(f, filename, args, argidx);
std::string content{std::istreambuf_iterator<char>(*f), std::istreambuf_iterator<char>()};
log("%s\n", content.c_str());
Tcl_Interp* interp = yosys_get_tcl_interp();
if (Tcl_EvalFile(interp, args[argidx].c_str()) != TCL_OK) {
log_cmd_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(interp));
}
}
} ReadSdc;
PRIVATE_NAMESPACE_END
|
/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <[email protected]>
* Copyright (C) 2020 The Symbiflow Authors
*
* 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 "kernel/register.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct ReadSdcCmd : public Frontend {
ReadSdcCmd()
: Frontend("sdc", "Read SDC file"){}
void help() override {
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" read_sdc <filename>\n");
log("\n");
log("Read SDC file.\n");
log("\n");
}
void execute(std::istream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design*) override {
if (args.size() < 2) {
log_cmd_error("Missing script file.\n");
}
size_t argidx = 1;
extra_args(f, filename, args, argidx);
std::string content{std::istreambuf_iterator<char>(*f), std::istreambuf_iterator<char>()};
log("%s\n", content.c_str());
Tcl_Interp* interp = yosys_get_tcl_interp();
if (Tcl_EvalFile(interp, args[argidx].c_str()) != TCL_OK) {
log_cmd_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(interp));
}
}
};
using Clocks = std::vector<RTLIL::Wire*>;
struct CreateClockCmd : public Pass {
CreateClockCmd(Clocks& clocks)
: Pass("create_clock", "Create clock object")
, clocks_(clocks)
{}
void help() override
{
log("\n");
log(" create_clock [ -name clock_name ] -period period_value [-waveform <edge_list>] <target>\n");
log("Define a clock.\n");
log("If name is not specified then the name of the first target is selected as the clock's name.\n");
log("Period is expressed in nanoseconds.\n");
log("The waveform option specifies the duty cycle (the rising a falling edges) of the clock.\n");
log("It is specified as a list of two elements/time values: the first rising edge and the next falling edge.\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) override
{
size_t argidx;
std::string name;
float rising_edge(0);
float falling_edge(0);
float period(0);
for (argidx = 1; argidx < args.size(); argidx++)
{
std::string arg = args[argidx];
if (arg == "-name" && argidx + 1 < args.size()) {
name = args[++argidx];
continue;
}
if (arg == "-period" && argidx + 1 < args.size()) {
period = std::stof(args[++argidx]);
continue;
}
if (arg == "-waveform" && argidx + 2 < args.size()) {
rising_edge = std::stof(args[++argidx]);
falling_edge = std::stof(args[++argidx]);
continue;
}
break;
}
// Add "w:" prefix to selection arguments to enforce wire object selection
AddWirePrefix(args, argidx);
extra_args(args, argidx, design);
// If clock name is not specified then take the name of the first target
for (auto module : design->modules()) {
if (!design->selected(module)) {
continue;
}
for (auto wire : module->wires()) {
if (design->selected(module, wire)) {
log("Selected wire %s\n", wire->name.c_str());
clocks_.push_back(wire);
}
}
}
if (name.empty()) {
name = clocks_.at(0)->name.str();
}
log("Created clock %s with period %f, waveform %f,%f\n", name.c_str(), period, rising_edge, falling_edge);
}
void AddWirePrefix(std::vector<std::string>& args, size_t argidx) {
auto selection_begin = args.begin() + argidx;
std::transform(selection_begin, args.end(), selection_begin, [](std::string& w) {return "w:" + w;});
}
Clocks& clocks_;
};
class SdcPlugin {
public:
SdcPlugin()
: create_clock_cmd_(clocks_)
{log("Loaded SDC plugin\n");}
ReadSdcCmd read_sdc_cmd_;
CreateClockCmd create_clock_cmd_;
private:
Clocks clocks_;
} SdcPlugin;
PRIVATE_NAMESPACE_END
|
Add create_clock command
|
SDC: Add create_clock command
Signed-off-by: Tomasz Michalak <[email protected]>
|
C++
|
apache-2.0
|
chipsalliance/yosys-f4pga-plugins,SymbiFlow/yosys-f4pga-plugins,SymbiFlow/yosys-symbiflow-plugins,antmicro/yosys-symbiflow-plugins,antmicro/yosys-symbiflow-plugins,SymbiFlow/yosys-symbiflow-plugins,SymbiFlow/yosys-symbiflow-plugins,chipsalliance/yosys-f4pga-plugins,SymbiFlow/yosys-f4pga-plugins,antmicro/yosys-symbiflow-plugins,SymbiFlow/yosys-f4pga-plugins
|
0746c2f6c34ef541d15b29da7089c72270aa9b56
|
sdwa/sdwa_dp4.cpp
|
sdwa/sdwa_dp4.cpp
|
#include<hip/hip_runtime.h>
#include<hip/hip_runtime_api.h>
#include<iostream>
#define LEN 64
#define SIZE LEN<<2
#define fileName "sdwa_dp4.co"
#define kernelName "sdwa_dp4"
#define VAL 0x01010101
int main() {
unsigned *Ah, *Bh, *Ch, *Dh;
hipDeviceptr_t Ad, Bd, Cd, Dd;
Ah = new unsigned[LEN];
Bh = new unsigned[LEN];
Ch = new unsigned[LEN];
Dh = new unsigned[LEN];
for(unsigned i=0;i<LEN;i++) {
Ah[i] = VAL;
Bh[i] = VAL;
Ch[i] = 0;
Dh[i] = 0;
}
hipInit(0);
hipDevice_t device;
hipCtx_t context;
hipDeviceGet(&device, 0);
hipCtxCreate(&context, 0, device);
hipModule_t Module;
hipFunction_t Function;
hipMalloc((void**)&Ad, SIZE);
hipMalloc((void**)&Bd, SIZE);
hipMalloc((void**)&Cd, SIZE);
hipMalloc((void**)&Dd, SIZE);
hipMemcpyHtoD(Ad, Ah, SIZE);
hipMemcpyHtoD(Bd, Bh, SIZE);
hipMemcpyHtoD(Cd, Ch, SIZE);
hipModuleLoad(&Module, fileName);
hipModuleGetFunction(&Function, Module, kernelName);
struct {
void *Ad;
void *Bd;
void *Cd;
void *Dd;
} args;
args.Ad = Ad;
args.Bd = Bd;
args.Cd = Cd;
args.Dd = Dd;
size_t size = sizeof(args);
void *config[] = {
HIP_LAUNCH_PARAM_BUFFER_POINTER, &args,
HIP_LAUNCH_PARAM_BUFFER_SIZE, &size,
HIP_LAUNCH_PARAM_END
};
hipModuleLaunchKernel(Function, 1,1,1, LEN,1,1, 0, 0, NULL, (void**)&config);
hipMemcpyDtoH(Dh, Dd, SIZE);
std::cout<<Dh[10]<<" "<<Dh[11]<<std::endl;
}
|
/*
Copyright (c) 2016 Aditya Atluri. All rights reserved.
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<hip/hip_runtime.h>
#include<hip/hip_runtime_api.h>
#include<iostream>
#define LEN 64
#define SIZE LEN<<2
#define fileName "sdwa_dp4.co"
#define kernelName "sdwa_dp4"
#define VAL 0x01010101
int main() {
unsigned *Ah, *Bh, *Ch, *Dh;
hipDeviceptr_t Ad, Bd, Cd, Dd;
Ah = new unsigned[LEN];
Bh = new unsigned[LEN];
Ch = new unsigned[LEN];
Dh = new unsigned[LEN];
for(unsigned i=0;i<LEN;i++) {
Ah[i] = VAL;
Bh[i] = VAL;
Ch[i] = 0;
Dh[i] = 0;
}
hipInit(0);
hipDevice_t device;
hipCtx_t context;
hipDeviceGet(&device, 0);
hipCtxCreate(&context, 0, device);
hipModule_t Module;
hipFunction_t Function;
hipMalloc((void**)&Ad, SIZE);
hipMalloc((void**)&Bd, SIZE);
hipMalloc((void**)&Cd, SIZE);
hipMalloc((void**)&Dd, SIZE);
hipMemcpyHtoD(Ad, Ah, SIZE);
hipMemcpyHtoD(Bd, Bh, SIZE);
hipMemcpyHtoD(Cd, Ch, SIZE);
hipModuleLoad(&Module, fileName);
hipModuleGetFunction(&Function, Module, kernelName);
struct {
void *Ad;
void *Bd;
void *Cd;
void *Dd;
} args;
args.Ad = Ad;
args.Bd = Bd;
args.Cd = Cd;
args.Dd = Dd;
size_t size = sizeof(args);
void *config[] = {
HIP_LAUNCH_PARAM_BUFFER_POINTER, &args,
HIP_LAUNCH_PARAM_BUFFER_SIZE, &size,
HIP_LAUNCH_PARAM_END
};
hipModuleLaunchKernel(Function, 1,1,1, LEN,1,1, 0, 0, NULL, (void**)&config);
hipMemcpyDtoH(Dh, Dd, SIZE);
std::cout<<Dh[10]<<" "<<Dh[11]<<std::endl;
}
|
Update sdwa_dp4.cpp
|
Update sdwa_dp4.cpp
|
C++
|
mit
|
gpu0/amdgpu-code,gpu0/amdgpu-code
|
32d0d155c7515c74824d67f971da6f94b5dc5234
|
re2jit/threads.cc
|
re2jit/threads.cc
|
#include <stdlib.h>
#include <string.h>
#include "threads.h"
void rejit_thread_free(struct rejit_threadset_t *r)
{
struct rejit_thread_t *a, *b;
#define FREE_LIST(init, end) do { \
for (a = init; a != end; ) { \
b = a; \
a = a->next; \
free(b); \
} \
} while (0)
FREE_LIST(r->free, NULL);
FREE_LIST(r->threads.first, rejit_list_end(&r->threads));
#undef FREE_LIST
rejit_list_init(&r->threads);
rejit_list_init(&r->queues[0]);
rejit_list_init(&r->queues[1]);
r->flags |= RE2JIT_UNDEFINED;
}
static struct rejit_thread_t *rejit_thread_acquire(struct rejit_threadset_t *r)
{
if (r->flags & RE2JIT_UNDEFINED)
return NULL;
struct rejit_thread_t *t = r->free;
if (t) {
r->free = t->next;
return t;
}
t = (struct rejit_thread_t *) malloc(sizeof(struct rejit_thread_t)
+ sizeof(int) * r->groups);
if (t == NULL)
rejit_thread_free(r);
return t;
}
static struct rejit_thread_t *rejit_thread_fork(struct rejit_threadset_t *r)
{
struct rejit_thread_t *t = rejit_thread_acquire(r);
struct rejit_thread_t *c = r->running;
if (t == NULL) return NULL;
rejit_list_append(c->prev, t);
memcpy(t->groups, c->groups, sizeof(int) * r->groups);
t->queue.bitmap = c->queue.bitmap;
return c->prev = t;
}
static struct rejit_thread_t *rejit_thread_initial(struct rejit_threadset_t *r)
{
struct rejit_thread_t *t = rejit_thread_acquire(r);
if (t == NULL) return NULL;
memset(t->groups, 255, sizeof(int) * r->groups);
t->queue.wait = 0;
t->queue.bitmap = 0;
t->groups[0] = r->offset;
t->state = r->initial;
rejit_list_append(r->threads.last, t);
rejit_list_append(r->queues[r->queue].last, &t->queue);
return t;
}
int rejit_thread_dispatch(struct rejit_threadset_t *r, int **groups)
{
unsigned char queue = 0;
unsigned char small_map = r->space <= sizeof(size_t);
size_t __bitmap;
r->bitmap_id_last = 0;
r->offset = 0;
r->queue = 0;
r->free = NULL;
rejit_list_init(&r->threads);
rejit_list_init(&r->queues[0]);
rejit_list_init(&r->queues[1]);
if (small_map)
r->bitmap = (uint8_t *) &__bitmap;
else if ((r->bitmap = (uint8_t *) malloc(r->space)) == NULL)
return -1;
do {
// if this is volatile, gcc generates better code for some reason.
volatile unsigned bitmap_id = -1;
if (!((r->flags & RE2JIT_ANCHOR_START) && r->offset))
rejit_thread_initial(r);
struct rejit_thread_t *t;
struct rejit_threadq_t *q = r->queues[queue].first;
if (q == rejit_list_end(&r->queues[queue]))
// if this queue is empty, the next will be too, and the one after that...
break;
do {
rejit_list_remove(q);
if (q->wait) {
q->wait--;
rejit_list_append(r->queues[!queue].last, q);
continue;
}
if (bitmap_id != q->bitmap) {
bitmap_id = q->bitmap;
if (small_map)
__bitmap = 0;
else
memset(r->bitmap, 0, r->space);
}
rejit_list_remove(t = rejit_list_container(struct rejit_thread_t, queue, q));
r->running = t;
r->entry(r, t->state);
t->next = r->free;
r->free = t;
} while ((q = r->queues[queue].first) != rejit_list_end(&r->queues[queue]));
r->input++;
r->offset++;
r->queue = queue = !queue;
} while (r->length--);
if (!small_map)
free(r->bitmap);
if (r->flags & RE2JIT_UNDEFINED)
// XOO < *ac was completely screwed out of memory
// and nothing can fix that!!*
return -1;
if (r->threads.first == rejit_list_end(&r->threads))
return 0;
*groups = r->threads.first->groups;
return 1;
}
int rejit_thread_match(struct rejit_threadset_t *r)
{
if ((r->flags & RE2JIT_ANCHOR_END) && r->length)
// no, it did not. not EOF yet.
return 0;
struct rejit_thread_t *t = rejit_thread_fork(r);
if (t == NULL)
// visiting other paths will not help us now.
return 1;
rejit_list_init(&t->queue);
t->groups[1] = r->offset;
while (t->next != rejit_list_end(&r->threads)) {
struct rejit_thread_t *q = t->next;
// it doesn't matter what less important threads return, so why run them?
rejit_list_remove(q);
rejit_list_remove(&q->queue);
q->next = r->free;
r->free = q;
}
// don't spawn new threads in the initial state for the same reason.
r->flags |= RE2JIT_ANCHOR_START;
return 1;
}
int rejit_thread_wait(struct rejit_threadset_t *r, const void *state, size_t shift)
{
struct rejit_thread_t *t = rejit_thread_fork(r);
if (t == NULL) return 1;
t->state = state;
t->queue.wait = shift - 1;
rejit_list_append(r->queues[!r->queue].last, &t->queue);
return 0;
}
int rejit_thread_satisfies(struct rejit_threadset_t *r, enum RE2JIT_EMPTY_FLAGS empty)
{
if (empty & RE2JIT_EMPTY_BEGIN_TEXT)
if (r->offset)
return 0;
if (empty & RE2JIT_EMPTY_END_TEXT)
if (r->length)
return 0;
if (empty & RE2JIT_EMPTY_BEGIN_LINE)
if (r->offset && r->input[-1] != '\n')
return 0;
if (empty & RE2JIT_EMPTY_END_LINE)
if (r->length && r->input[0] != '\n')
return 0;
if (empty & (RE2JIT_EMPTY_WORD_BOUNDARY | RE2JIT_EMPTY_NON_WORD_BOUNDARY))
return 0; // TODO read UTF-8 chars or something
return 1;
}
struct _bitmap
{
uint8_t *old_map;
unsigned old_id;
uint8_t bitmap[];
};
void rejit_thread_bitmap_save(struct rejit_threadset_t *r)
{
struct _bitmap *s = (struct _bitmap *) malloc(sizeof(struct _bitmap) + r->space);
if (s == NULL) {
rejit_thread_free(r);
return;
}
memset(s->bitmap, 0, r->space);
s->old_id = r->running->queue.bitmap;
s->old_map = r->bitmap;
r->bitmap = s->bitmap;
r->running->queue.bitmap = ++r->bitmap_id_last;
}
void rejit_thread_bitmap_restore(struct rejit_threadset_t *r)
{
struct _bitmap *s = (struct _bitmap *) (r->bitmap - offsetof(struct _bitmap, bitmap));
r->bitmap = s->old_map;
r->running->queue.bitmap = s->old_id;
free(s);
}
|
#include <stdlib.h>
#include <string.h>
#include "threads.h"
void rejit_thread_free(struct rejit_threadset_t *r)
{
struct rejit_thread_t *a, *b;
#define FREE_LIST(init, end) do { \
for (a = init; a != end; ) { \
b = a; \
a = a->next; \
free(b); \
} \
} while (0)
FREE_LIST(r->free, NULL);
FREE_LIST(r->threads.first, rejit_list_end(&r->threads));
#undef FREE_LIST
rejit_list_init(&r->threads);
rejit_list_init(&r->queues[0]);
rejit_list_init(&r->queues[1]);
r->flags |= RE2JIT_UNDEFINED;
}
static struct rejit_thread_t *rejit_thread_acquire(struct rejit_threadset_t *r)
{
if (r->flags & RE2JIT_UNDEFINED)
return NULL;
struct rejit_thread_t *t = r->free;
if (t) {
r->free = t->next;
return t;
}
t = (struct rejit_thread_t *) malloc(sizeof(struct rejit_thread_t)
+ sizeof(int) * r->groups);
if (t == NULL)
rejit_thread_free(r);
return t;
}
static struct rejit_thread_t *rejit_thread_fork(struct rejit_threadset_t *r)
{
struct rejit_thread_t *t = rejit_thread_acquire(r);
struct rejit_thread_t *c = r->running;
if (t == NULL) return NULL;
rejit_list_append(c->prev, t);
memcpy(t->groups, c->groups, sizeof(int) * r->groups);
t->queue.bitmap = c->queue.bitmap;
return c->prev = t;
}
static struct rejit_thread_t *rejit_thread_initial(struct rejit_threadset_t *r)
{
struct rejit_thread_t *t = rejit_thread_acquire(r);
if (t == NULL) return NULL;
memset(t->groups, 255, sizeof(int) * r->groups);
t->queue.wait = 0;
t->queue.bitmap = 0;
t->groups[0] = r->offset;
t->state = r->initial;
rejit_list_append(r->threads.last, t);
rejit_list_append(r->queues[r->queue].last, &t->queue);
return t;
}
int rejit_thread_dispatch(struct rejit_threadset_t *r, int **groups)
{
unsigned char queue = 0;
unsigned char small_map = r->space <= sizeof(size_t);
volatile size_t __bitmap;
r->bitmap_id_last = 0;
r->offset = 0;
r->queue = 0;
r->free = NULL;
rejit_list_init(&r->threads);
rejit_list_init(&r->queues[0]);
rejit_list_init(&r->queues[1]);
if (small_map)
r->bitmap = (uint8_t *) &__bitmap;
else if ((r->bitmap = (uint8_t *) malloc(r->space)) == NULL)
return -1;
do {
// if this is volatile, gcc generates better code for some reason.
volatile unsigned bitmap_id = -1;
if (!((r->flags & RE2JIT_ANCHOR_START) && r->offset))
rejit_thread_initial(r);
struct rejit_thread_t *t;
struct rejit_threadq_t *q = r->queues[queue].first;
if (q == rejit_list_end(&r->queues[queue]))
// if this queue is empty, the next will be too, and the one after that...
break;
do {
rejit_list_remove(q);
if (q->wait) {
q->wait--;
rejit_list_append(r->queues[!queue].last, q);
continue;
}
if (bitmap_id != q->bitmap) {
bitmap_id = q->bitmap;
if (small_map)
__bitmap = 0;
else
memset(r->bitmap, 0, r->space);
}
rejit_list_remove(t = rejit_list_container(struct rejit_thread_t, queue, q));
r->running = t;
r->entry(r, t->state);
t->next = r->free;
r->free = t;
} while ((q = r->queues[queue].first) != rejit_list_end(&r->queues[queue]));
r->input++;
r->offset++;
r->queue = queue = !queue;
} while (r->length--);
if (!small_map)
free(r->bitmap);
if (r->flags & RE2JIT_UNDEFINED)
// XOO < *ac was completely screwed out of memory
// and nothing can fix that!!*
return -1;
if (r->threads.first == rejit_list_end(&r->threads))
return 0;
*groups = r->threads.first->groups;
return 1;
}
int rejit_thread_match(struct rejit_threadset_t *r)
{
if ((r->flags & RE2JIT_ANCHOR_END) && r->length)
// no, it did not. not EOF yet.
return 0;
struct rejit_thread_t *t = rejit_thread_fork(r);
if (t == NULL)
// visiting other paths will not help us now.
return 1;
rejit_list_init(&t->queue);
t->groups[1] = r->offset;
while (t->next != rejit_list_end(&r->threads)) {
struct rejit_thread_t *q = t->next;
// it doesn't matter what less important threads return, so why run them?
rejit_list_remove(q);
rejit_list_remove(&q->queue);
q->next = r->free;
r->free = q;
}
// don't spawn new threads in the initial state for the same reason.
r->flags |= RE2JIT_ANCHOR_START;
return 1;
}
int rejit_thread_wait(struct rejit_threadset_t *r, const void *state, size_t shift)
{
struct rejit_thread_t *t = rejit_thread_fork(r);
if (t == NULL) return 1;
t->state = state;
t->queue.wait = shift - 1;
rejit_list_append(r->queues[!r->queue].last, &t->queue);
return 0;
}
int rejit_thread_satisfies(struct rejit_threadset_t *r, enum RE2JIT_EMPTY_FLAGS empty)
{
if (empty & RE2JIT_EMPTY_BEGIN_TEXT)
if (r->offset)
return 0;
if (empty & RE2JIT_EMPTY_END_TEXT)
if (r->length)
return 0;
if (empty & RE2JIT_EMPTY_BEGIN_LINE)
if (r->offset && r->input[-1] != '\n')
return 0;
if (empty & RE2JIT_EMPTY_END_LINE)
if (r->length && r->input[0] != '\n')
return 0;
if (empty & (RE2JIT_EMPTY_WORD_BOUNDARY | RE2JIT_EMPTY_NON_WORD_BOUNDARY))
return 0; // TODO read UTF-8 chars or something
return 1;
}
struct _bitmap
{
uint8_t *old_map;
unsigned old_id;
uint8_t bitmap[];
};
void rejit_thread_bitmap_save(struct rejit_threadset_t *r)
{
struct _bitmap *s = (struct _bitmap *) malloc(sizeof(struct _bitmap) + r->space);
if (s == NULL) {
rejit_thread_free(r);
return;
}
memset(s->bitmap, 0, r->space);
s->old_id = r->running->queue.bitmap;
s->old_map = r->bitmap;
r->bitmap = s->bitmap;
r->running->queue.bitmap = ++r->bitmap_id_last;
}
void rejit_thread_bitmap_restore(struct rejit_threadset_t *r)
{
struct _bitmap *s = (struct _bitmap *) (r->bitmap - offsetof(struct _bitmap, bitmap));
r->bitmap = s->old_map;
r->running->queue.bitmap = s->old_id;
free(s);
}
|
Mark packed bitmap variable as volatile.
|
Mark packed bitmap variable as volatile.
|
C++
|
mit
|
pyos/re2jit,pyos/re2jit,pyos/re2jit
|
6a7caa639237d6655d6591e3af3f9046c5860c97
|
src/http_request.cxx
|
src/http_request.cxx
|
/*
* High level HTTP client.
*
* author: Max Kellermann <[email protected]>
*/
#include "http_request.hxx"
#include "http_response.hxx"
#include "http_client.hxx"
#include "http_headers.hxx"
#include "http_address.hxx"
#include "header_writer.hxx"
#include "tcp_stock.hxx"
#include "tcp_balancer.hxx"
#include "stock.hxx"
#include "async.hxx"
#include "growing_buffer.hxx"
#include "lease.hxx"
#include "abort_close.hxx"
#include "failure.hxx"
#include "istream.h"
#include "filtered_socket.hxx"
#include "pool.hxx"
#include "net/SocketAddress.hxx"
#include <inline/compiler.h>
#include <string.h>
struct http_request {
struct pool *pool;
struct tcp_balancer *tcp_balancer;
unsigned session_sticky;
const SocketFilter *filter;
void *filter_ctx;
StockItem *stock_item;
SocketAddress current_address;
http_method_t method;
const struct http_address *uwa;
HttpHeaders headers;
struct istream *body;
unsigned retries;
struct http_response_handler_ref handler;
struct async_operation_ref *async_ref;
};
/**
* Is the specified error a server failure, that justifies
* blacklisting the server for a while?
*/
static bool
is_server_failure(GError *error)
{
return error->domain == http_client_quark() &&
error->code != HTTP_CLIENT_UNSPECIFIED;
}
extern const StockGetHandler http_request_stock_handler;
/*
* HTTP response handler
*
*/
static void
http_request_response_response(http_status_t status, struct strmap *headers,
struct istream *body, void *ctx)
{
struct http_request *hr = (struct http_request *)ctx;
failure_unset(hr->current_address, FAILURE_RESPONSE);
hr->handler.InvokeResponse(status, headers, body);
}
static void
http_request_response_abort(GError *error, void *ctx)
{
struct http_request *hr = (struct http_request *)ctx;
if (hr->retries > 0 && hr->body == nullptr &&
error->domain == http_client_quark() &&
error->code == HTTP_CLIENT_REFUSED) {
/* the server has closed the connection prematurely, maybe
because it didn't want to get any further requests on that
TCP connection. Let's try again. */
g_error_free(error);
--hr->retries;
tcp_balancer_get(*hr->tcp_balancer, *hr->pool,
false, SocketAddress::Null(),
hr->session_sticky,
hr->uwa->addresses,
30,
http_request_stock_handler, hr,
*hr->async_ref);
} else {
if (is_server_failure(error))
failure_set(hr->current_address, FAILURE_RESPONSE, 20);
hr->handler.InvokeAbort(error);
}
}
static const struct http_response_handler http_request_response_handler = {
.response = http_request_response_response,
.abort = http_request_response_abort,
};
/*
* socket lease
*
*/
static void
http_socket_release(bool reuse, void *ctx)
{
struct http_request *hr = (struct http_request *)ctx;
tcp_balancer_put(*hr->tcp_balancer, *hr->stock_item, !reuse);
}
static const struct lease http_socket_lease = {
.release = http_socket_release,
};
/*
* stock callback
*
*/
static void
http_request_stock_ready(StockItem &item, void *ctx)
{
struct http_request *hr = (struct http_request *)ctx;
hr->stock_item = &item;
hr->current_address = tcp_balancer_get_last();
http_client_request(*hr->pool,
tcp_stock_item_get(item),
tcp_stock_item_get_domain(item) == AF_LOCAL
? ISTREAM_SOCKET : ISTREAM_TCP,
http_socket_lease, hr,
hr->filter, hr->filter_ctx,
hr->method, hr->uwa->path, std::move(hr->headers),
hr->body, true,
http_request_response_handler, hr,
*hr->async_ref);
}
static void
http_request_stock_error(GError *error, void *ctx)
{
struct http_request *hr = (struct http_request *)ctx;
if (hr->body != nullptr)
istream_close_unused(hr->body);
if (hr->filter != nullptr)
hr->filter->close(hr->filter_ctx);
hr->handler.InvokeAbort(error);
}
constexpr StockGetHandler http_request_stock_handler = {
.ready = http_request_stock_ready,
.error = http_request_stock_error,
};
/*
* constructor
*
*/
void
http_request(struct pool &pool,
struct tcp_balancer &tcp_balancer,
unsigned session_sticky,
const SocketFilter *filter, void *filter_ctx,
http_method_t method,
const struct http_address &uwa,
HttpHeaders &&headers,
struct istream *body,
const struct http_response_handler &handler,
void *handler_ctx,
struct async_operation_ref &_async_ref)
{
assert(uwa.host_and_port != nullptr);
assert(uwa.path != nullptr);
assert(handler.response != nullptr);
assert(body == nullptr || !istream_has_handler(body));
auto hr = NewFromPool<struct http_request>(pool);
hr->pool = &pool;
hr->tcp_balancer = &tcp_balancer;
hr->session_sticky = session_sticky;
hr->filter = filter;
hr->filter_ctx = filter_ctx;
hr->method = method;
hr->uwa = &uwa;
hr->headers = std::move(headers);
hr->handler.Set(handler, handler_ctx);
hr->async_ref = &_async_ref;
struct async_operation_ref *async_ref = &_async_ref;
if (body != nullptr) {
body = istream_hold_new(&pool, body);
async_ref = &async_close_on_abort(pool, *body, *async_ref);
}
hr->body = body;
GrowingBuffer &headers2 = hr->headers.MakeBuffer(pool, 256);
if (uwa.host_and_port != nullptr)
header_write(&headers2, "host", uwa.host_and_port);
header_write(&headers2, "connection", "keep-alive");
hr->retries = 2;
tcp_balancer_get(tcp_balancer, pool,
false, SocketAddress::Null(),
session_sticky,
uwa.addresses,
30,
http_request_stock_handler, hr,
*async_ref);
}
|
/*
* High level HTTP client.
*
* author: Max Kellermann <[email protected]>
*/
#include "http_request.hxx"
#include "http_response.hxx"
#include "http_client.hxx"
#include "http_headers.hxx"
#include "http_address.hxx"
#include "header_writer.hxx"
#include "tcp_stock.hxx"
#include "tcp_balancer.hxx"
#include "stock.hxx"
#include "async.hxx"
#include "growing_buffer.hxx"
#include "lease.hxx"
#include "abort_close.hxx"
#include "failure.hxx"
#include "istream.h"
#include "filtered_socket.hxx"
#include "pool.hxx"
#include "net/SocketAddress.hxx"
#include <inline/compiler.h>
#include <string.h>
struct http_request {
struct pool *pool;
struct tcp_balancer *tcp_balancer;
unsigned session_sticky;
const SocketFilter *filter;
void *filter_ctx;
StockItem *stock_item;
SocketAddress current_address;
http_method_t method;
const struct http_address *uwa;
HttpHeaders headers;
struct istream *body;
unsigned retries;
struct http_response_handler_ref handler;
struct async_operation_ref *async_ref;
void Dispose() {
if (body != nullptr)
istream_close_unused(body);
if (filter != nullptr)
filter->close(filter_ctx);
}
void Failed(GError *error) {
Dispose();
handler.InvokeAbort(error);
}
};
/**
* Is the specified error a server failure, that justifies
* blacklisting the server for a while?
*/
static bool
is_server_failure(GError *error)
{
return error->domain == http_client_quark() &&
error->code != HTTP_CLIENT_UNSPECIFIED;
}
extern const StockGetHandler http_request_stock_handler;
/*
* HTTP response handler
*
*/
static void
http_request_response_response(http_status_t status, struct strmap *headers,
struct istream *body, void *ctx)
{
struct http_request *hr = (struct http_request *)ctx;
failure_unset(hr->current_address, FAILURE_RESPONSE);
hr->handler.InvokeResponse(status, headers, body);
}
static void
http_request_response_abort(GError *error, void *ctx)
{
struct http_request *hr = (struct http_request *)ctx;
if (hr->retries > 0 && hr->body == nullptr &&
error->domain == http_client_quark() &&
error->code == HTTP_CLIENT_REFUSED) {
/* the server has closed the connection prematurely, maybe
because it didn't want to get any further requests on that
TCP connection. Let's try again. */
g_error_free(error);
--hr->retries;
tcp_balancer_get(*hr->tcp_balancer, *hr->pool,
false, SocketAddress::Null(),
hr->session_sticky,
hr->uwa->addresses,
30,
http_request_stock_handler, hr,
*hr->async_ref);
} else {
if (is_server_failure(error))
failure_set(hr->current_address, FAILURE_RESPONSE, 20);
hr->handler.InvokeAbort(error);
}
}
static const struct http_response_handler http_request_response_handler = {
.response = http_request_response_response,
.abort = http_request_response_abort,
};
/*
* socket lease
*
*/
static void
http_socket_release(bool reuse, void *ctx)
{
struct http_request *hr = (struct http_request *)ctx;
tcp_balancer_put(*hr->tcp_balancer, *hr->stock_item, !reuse);
}
static const struct lease http_socket_lease = {
.release = http_socket_release,
};
/*
* stock callback
*
*/
static void
http_request_stock_ready(StockItem &item, void *ctx)
{
struct http_request *hr = (struct http_request *)ctx;
hr->stock_item = &item;
hr->current_address = tcp_balancer_get_last();
http_client_request(*hr->pool,
tcp_stock_item_get(item),
tcp_stock_item_get_domain(item) == AF_LOCAL
? ISTREAM_SOCKET : ISTREAM_TCP,
http_socket_lease, hr,
hr->filter, hr->filter_ctx,
hr->method, hr->uwa->path, std::move(hr->headers),
hr->body, true,
http_request_response_handler, hr,
*hr->async_ref);
}
static void
http_request_stock_error(GError *error, void *ctx)
{
struct http_request *hr = (struct http_request *)ctx;
hr->Failed(error);
}
constexpr StockGetHandler http_request_stock_handler = {
.ready = http_request_stock_ready,
.error = http_request_stock_error,
};
/*
* constructor
*
*/
void
http_request(struct pool &pool,
struct tcp_balancer &tcp_balancer,
unsigned session_sticky,
const SocketFilter *filter, void *filter_ctx,
http_method_t method,
const struct http_address &uwa,
HttpHeaders &&headers,
struct istream *body,
const struct http_response_handler &handler,
void *handler_ctx,
struct async_operation_ref &_async_ref)
{
assert(uwa.host_and_port != nullptr);
assert(uwa.path != nullptr);
assert(handler.response != nullptr);
assert(body == nullptr || !istream_has_handler(body));
auto hr = NewFromPool<struct http_request>(pool);
hr->pool = &pool;
hr->tcp_balancer = &tcp_balancer;
hr->session_sticky = session_sticky;
hr->filter = filter;
hr->filter_ctx = filter_ctx;
hr->method = method;
hr->uwa = &uwa;
hr->headers = std::move(headers);
hr->handler.Set(handler, handler_ctx);
hr->async_ref = &_async_ref;
struct async_operation_ref *async_ref = &_async_ref;
if (body != nullptr) {
body = istream_hold_new(&pool, body);
async_ref = &async_close_on_abort(pool, *body, *async_ref);
}
hr->body = body;
GrowingBuffer &headers2 = hr->headers.MakeBuffer(pool, 256);
if (uwa.host_and_port != nullptr)
header_write(&headers2, "host", uwa.host_and_port);
header_write(&headers2, "connection", "keep-alive");
hr->retries = 2;
tcp_balancer_get(tcp_balancer, pool,
false, SocketAddress::Null(),
session_sticky,
uwa.addresses,
30,
http_request_stock_handler, hr,
*async_ref);
}
|
move code to methods
|
http_request: move code to methods
|
C++
|
bsd-2-clause
|
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
|
765fe56b5702284193c9c3afefdf1ce972da5e0f
|
src/http_request.cxx
|
src/http_request.cxx
|
/*
* High level HTTP client.
*
* author: Max Kellermann <[email protected]>
*/
#include "http_request.hxx"
#include "http_response.hxx"
#include "http_client.hxx"
#include "http_headers.hxx"
#include "http_address.hxx"
#include "header_writer.hxx"
#include "tcp_stock.hxx"
#include "tcp_balancer.hxx"
#include "stock/GetHandler.hxx"
#include "stock/Item.hxx"
#include "stock/Lease.hxx"
#include "failure.hxx"
#include "istream/istream.hxx"
#include "istream/UnusedHoldPtr.hxx"
#include "filtered_socket.hxx"
#include "pool.hxx"
#include "GException.hxx"
#include "net/SocketAddress.hxx"
#include "util/Cancellable.hxx"
#include <inline/compiler.h>
#include <string.h>
struct HttpRequest final
: Cancellable, StockGetHandler, HttpResponseHandler {
struct pool &pool;
EventLoop &event_loop;
TcpBalancer &tcp_balancer;
const sticky_hash_t session_sticky;
const SocketFilter *const filter;
SocketFilterFactory *const filter_factory;
StockItem *stock_item;
const http_method_t method;
const HttpAddress &address;
HttpHeaders headers;
UnusedHoldIstreamPtr body;
unsigned retries;
HttpResponseHandler &handler;
CancellablePointer cancel_ptr;
HttpRequest(struct pool &_pool, EventLoop &_event_loop,
TcpBalancer &_tcp_balancer,
sticky_hash_t _session_sticky,
const SocketFilter *_filter,
SocketFilterFactory *_filter_factory,
http_method_t _method,
const HttpAddress &_address,
HttpHeaders &&_headers,
Istream *_body,
HttpResponseHandler &_handler,
CancellablePointer &_cancel_ptr)
:pool(_pool), event_loop(_event_loop), tcp_balancer(_tcp_balancer),
session_sticky(_session_sticky),
filter(_filter), filter_factory(_filter_factory),
method(_method), address(_address),
headers(std::move(_headers)), body(pool, _body),
/* can only retry if there is no request body */
retries(_body != nullptr ? 2 : 0),
handler(_handler)
{
_cancel_ptr = *this;
if (address.host_and_port != nullptr)
headers.Write("host", address.host_and_port);
headers.Write("connection", "keep-alive");
}
void Destroy() {
DeleteFromPool(pool, this);
}
void ResponseSent() {
Destroy();
}
void BeginConnect() {
tcp_balancer_get(tcp_balancer, pool,
false, SocketAddress::Null(),
session_sticky,
address.addresses,
30,
*this, cancel_ptr);
}
void Failed(GError *error) {
body.Clear();
handler.InvokeError(error);
ResponseSent();
}
/* virtual methods from class Cancellable */
void Cancel() override {
body.Clear();
CancellablePointer c(std::move(cancel_ptr));
Destroy();
c.Cancel();
}
/* virtual methods from class StockGetHandler */
void OnStockItemReady(StockItem &item) override;
void OnStockItemError(GError *error) override;
private:
/* virtual methods from class HttpResponseHandler */
void OnHttpResponse(http_status_t status, StringMap &&headers,
Istream *body) override;
void OnHttpError(GError *error) override;
};
/**
* Is the specified error a server failure, that justifies
* blacklisting the server for a while?
*/
static bool
is_server_failure(GError *error)
{
return error->domain == http_client_quark() &&
error->code != HTTP_CLIENT_UNSPECIFIED;
}
/*
* HTTP response handler
*
*/
void
HttpRequest::OnHttpResponse(http_status_t status, StringMap &&_headers,
Istream *_body)
{
failure_unset(tcp_stock_item_get_address(*stock_item), FAILURE_RESPONSE);
handler.InvokeResponse(status, std::move(_headers), _body);
ResponseSent();
}
void
HttpRequest::OnHttpError(GError *error)
{
if (retries > 0 &&
error->domain == http_client_quark() &&
error->code == HTTP_CLIENT_REFUSED) {
/* the server has closed the connection prematurely, maybe
because it didn't want to get any further requests on that
TCP connection. Let's try again. */
g_error_free(error);
--retries;
BeginConnect();
} else {
if (is_server_failure(error))
failure_set(tcp_stock_item_get_address(*stock_item),
FAILURE_RESPONSE,
std::chrono::seconds(20));
Failed(error);
}
}
/*
* stock callback
*
*/
void
HttpRequest::OnStockItemReady(StockItem &item)
{
stock_item = &item;
void *filter_ctx = nullptr;
if (filter_factory != nullptr) {
try {
filter_ctx = filter_factory->CreateFilter();
} catch (const std::runtime_error &e) {
item.Put(false);
Failed(ToGError(e));
return;
}
}
auto *lease = NewFromPool<StockItemLease>(pool, item);
http_client_request(pool, event_loop,
tcp_stock_item_get(item),
tcp_stock_item_get_domain(item) == AF_LOCAL
? FdType::FD_SOCKET : FdType::FD_TCP,
*lease,
item.GetStockName(),
filter, filter_ctx,
method, address.path, std::move(headers),
body.Steal(), true,
*this, cancel_ptr);
}
void
HttpRequest::OnStockItemError(GError *error)
{
Failed(error);
}
/*
* constructor
*
*/
void
http_request(struct pool &pool, EventLoop &event_loop,
TcpBalancer &tcp_balancer,
sticky_hash_t session_sticky,
const SocketFilter *filter, SocketFilterFactory *filter_factory,
http_method_t method,
const HttpAddress &uwa,
HttpHeaders &&headers,
Istream *body,
HttpResponseHandler &handler,
CancellablePointer &_cancel_ptr)
{
assert(uwa.host_and_port != nullptr);
assert(uwa.path != nullptr);
assert(body == nullptr || !body->HasHandler());
auto hr = NewFromPool<HttpRequest>(pool, pool, event_loop, tcp_balancer,
session_sticky, filter, filter_factory,
method, uwa, std::move(headers), body,
handler, _cancel_ptr);
hr->BeginConnect();
}
|
/*
* High level HTTP client.
*
* author: Max Kellermann <[email protected]>
*/
#include "http_request.hxx"
#include "http_response.hxx"
#include "http_client.hxx"
#include "http_headers.hxx"
#include "http_address.hxx"
#include "header_writer.hxx"
#include "tcp_stock.hxx"
#include "tcp_balancer.hxx"
#include "stock/GetHandler.hxx"
#include "stock/Item.hxx"
#include "stock/Lease.hxx"
#include "failure.hxx"
#include "istream/istream.hxx"
#include "istream/UnusedHoldPtr.hxx"
#include "filtered_socket.hxx"
#include "pool.hxx"
#include "GException.hxx"
#include "net/SocketAddress.hxx"
#include "util/Cancellable.hxx"
#include <inline/compiler.h>
#include <string.h>
class HttpRequest final
: Cancellable, StockGetHandler, HttpResponseHandler {
struct pool &pool;
EventLoop &event_loop;
TcpBalancer &tcp_balancer;
const sticky_hash_t session_sticky;
const SocketFilter *const filter;
SocketFilterFactory *const filter_factory;
StockItem *stock_item;
const http_method_t method;
const HttpAddress &address;
HttpHeaders headers;
UnusedHoldIstreamPtr body;
unsigned retries;
HttpResponseHandler &handler;
CancellablePointer cancel_ptr;
public:
HttpRequest(struct pool &_pool, EventLoop &_event_loop,
TcpBalancer &_tcp_balancer,
sticky_hash_t _session_sticky,
const SocketFilter *_filter,
SocketFilterFactory *_filter_factory,
http_method_t _method,
const HttpAddress &_address,
HttpHeaders &&_headers,
Istream *_body,
HttpResponseHandler &_handler,
CancellablePointer &_cancel_ptr)
:pool(_pool), event_loop(_event_loop), tcp_balancer(_tcp_balancer),
session_sticky(_session_sticky),
filter(_filter), filter_factory(_filter_factory),
method(_method), address(_address),
headers(std::move(_headers)), body(pool, _body),
/* can only retry if there is no request body */
retries(_body != nullptr ? 2 : 0),
handler(_handler)
{
_cancel_ptr = *this;
if (address.host_and_port != nullptr)
headers.Write("host", address.host_and_port);
headers.Write("connection", "keep-alive");
}
void BeginConnect() {
tcp_balancer_get(tcp_balancer, pool,
false, SocketAddress::Null(),
session_sticky,
address.addresses,
30,
*this, cancel_ptr);
}
private:
void Destroy() {
DeleteFromPool(pool, this);
}
void ResponseSent() {
Destroy();
}
void Failed(GError *error) {
body.Clear();
handler.InvokeError(error);
ResponseSent();
}
/* virtual methods from class Cancellable */
void Cancel() override {
body.Clear();
CancellablePointer c(std::move(cancel_ptr));
Destroy();
c.Cancel();
}
/* virtual methods from class StockGetHandler */
void OnStockItemReady(StockItem &item) override;
void OnStockItemError(GError *error) override;
/* virtual methods from class HttpResponseHandler */
void OnHttpResponse(http_status_t status, StringMap &&headers,
Istream *body) override;
void OnHttpError(GError *error) override;
};
/**
* Is the specified error a server failure, that justifies
* blacklisting the server for a while?
*/
static bool
is_server_failure(GError *error)
{
return error->domain == http_client_quark() &&
error->code != HTTP_CLIENT_UNSPECIFIED;
}
/*
* HTTP response handler
*
*/
void
HttpRequest::OnHttpResponse(http_status_t status, StringMap &&_headers,
Istream *_body)
{
failure_unset(tcp_stock_item_get_address(*stock_item), FAILURE_RESPONSE);
handler.InvokeResponse(status, std::move(_headers), _body);
ResponseSent();
}
void
HttpRequest::OnHttpError(GError *error)
{
if (retries > 0 &&
error->domain == http_client_quark() &&
error->code == HTTP_CLIENT_REFUSED) {
/* the server has closed the connection prematurely, maybe
because it didn't want to get any further requests on that
TCP connection. Let's try again. */
g_error_free(error);
--retries;
BeginConnect();
} else {
if (is_server_failure(error))
failure_set(tcp_stock_item_get_address(*stock_item),
FAILURE_RESPONSE,
std::chrono::seconds(20));
Failed(error);
}
}
/*
* stock callback
*
*/
void
HttpRequest::OnStockItemReady(StockItem &item)
{
stock_item = &item;
void *filter_ctx = nullptr;
if (filter_factory != nullptr) {
try {
filter_ctx = filter_factory->CreateFilter();
} catch (const std::runtime_error &e) {
item.Put(false);
Failed(ToGError(e));
return;
}
}
auto *lease = NewFromPool<StockItemLease>(pool, item);
http_client_request(pool, event_loop,
tcp_stock_item_get(item),
tcp_stock_item_get_domain(item) == AF_LOCAL
? FdType::FD_SOCKET : FdType::FD_TCP,
*lease,
item.GetStockName(),
filter, filter_ctx,
method, address.path, std::move(headers),
body.Steal(), true,
*this, cancel_ptr);
}
void
HttpRequest::OnStockItemError(GError *error)
{
Failed(error);
}
/*
* constructor
*
*/
void
http_request(struct pool &pool, EventLoop &event_loop,
TcpBalancer &tcp_balancer,
sticky_hash_t session_sticky,
const SocketFilter *filter, SocketFilterFactory *filter_factory,
http_method_t method,
const HttpAddress &uwa,
HttpHeaders &&headers,
Istream *body,
HttpResponseHandler &handler,
CancellablePointer &_cancel_ptr)
{
assert(uwa.host_and_port != nullptr);
assert(uwa.path != nullptr);
assert(body == nullptr || !body->HasHandler());
auto hr = NewFromPool<HttpRequest>(pool, pool, event_loop, tcp_balancer,
session_sticky, filter, filter_factory,
method, uwa, std::move(headers), body,
handler, _cancel_ptr);
hr->BeginConnect();
}
|
convert to class
|
http_request: convert to class
|
C++
|
bsd-2-clause
|
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
|
733bb198941d35b358df55026d30a1d1dafab207
|
src/import/chips/p9/procedures/hwp/memory/lib/spd/spd_factory.H
|
src/import/chips/p9/procedures/hwp/memory/lib/spd/spd_factory.H
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/spd/spd_factory.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file spd_factory.H
/// @brief SPD factory and functions
///
// *HWP HWP Owner: Andre Marin <[email protected]>
// *HWP HWP Backup: Brian Silver <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP
#ifndef _MSS_SPD_FACTORY_H_
#define _MSS_SPD_FACTORY_H_
// std lib
#include <cstdint>
#include <map>
#include <memory>
// fapi2
#include <fapi2.H>
// mss lib
#include <lib/spd/common/spd_decoder.H>
namespace mss
{
namespace spd
{
///
/// @brief Decodes SPD Revision encoding level
/// @param[in] i_target dimm target
/// @param[in] i_spd_data SPD data
/// @param[out] o_value encoding revision num
/// @return FAPI2_RC_SUCCESS if okay
/// @note Decodes SPD Byte 1 (3~0).
/// @note Item JC-45-2220.01x
/// @note Page 14-15
/// @note DDR4 SPD Document Release 3
///
fapi2::ReturnCode rev_encoding_level(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const std::vector<uint8_t>& i_spd_data,
uint8_t& o_value);
///
/// @brief Decodes SPD Revision additions level
/// @param[in] i_target dimm target
/// @param[in] i_spd_data SPD blob
/// @param[out] o_value additions revision num
/// @return FAPI2_RC_SUCCESS if okay
/// @note Decodes SPD Byte 1 (bits 7~4).
/// @note Item JC-45-2220.01x
/// @note Page 14-15
/// @note DDR4 SPD Document Release 3
///
fapi2::ReturnCode rev_additions_level(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const std::vector<uint8_t>& i_spd_data,
uint8_t& o_value);
///
/// @brief Decodes base module type (DIMM type) from SPD
/// @param[in] i_target dimm target
/// @param[in] i_spd_data SPD data
/// @param[out] o_value base module type
/// @return FAPI2_RC_SUCCESS if okay
/// @note Decodes SPD Byte 3 (bits 3~0)
/// @note Item JC-45-2220.01x
/// @note Page 17
/// @note DDR4 SPD Document Release 3
///
fapi2::ReturnCode base_module_type(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const std::vector<uint8_t>& i_spd_data,
uint8_t& o_value);
///
/// @brief Decodes DRAM Device Type
/// @param[in] i_target dimm target
/// @param[out] o_value dram device type enumeration
/// @return FAPI2_RC_SUCCESS if okay
/// @note Decodes SPD Byte 2
/// @note Item JC-45-2220.01x
/// @note Page 16
/// @note DDR4 SPD Document Release 3
///
fapi2::ReturnCode dram_device_type(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const std::vector<uint8_t>& i_spd_data,
uint8_t& o_value);
///
/// @brief Decodes reference raw card
/// @param[in] i_target dimm target
/// @param[in] i_spd_data SPD data
/// @param[out] o_output encoding from SPD
/// @return FAPI2_RC_SUCCESS if okay
/// @note SPD Byte 130 (Bits 7~0)
/// @note Item JEDEC Standard No. 21-C
/// @note DDR4 SPD Document Release 2
/// @Note Page 4.1.2.12 - 49
///
fapi2::ReturnCode reference_raw_card(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const std::vector<uint8_t>& i_spd_data,
uint8_t& o_output);
///
/// @brief Retrieve current raw card settings
/// based on dimm type and raw card reference rev
/// @param[in] i_target dimm target
/// @param[in] i_spd_data SPD data
/// @param[out] o_raw_card raw card settings
/// @return FAPI2_RC_SUCCESS if okay
///
fapi2::ReturnCode raw_card_factory(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const std::vector<uint8_t>& i_spd_data,
rcw_settings& o_raw_card);
///
/// @brief Object factory to select correct decoder
/// @param[in] i_target dimm target
/// @param[in] i_spd_data SPD data
/// @param[out] o_fact_obj shared pointer to the factory object
/// @return FAPI2_RC_SUCCESS if okay
/// @note Factory dependent on SPD revision & dimm type
///
fapi2::ReturnCode factory(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const std::vector<uint8_t>& i_spd_data,
std::shared_ptr<decoder>& o_fact_obj);
///
/// @brief Creates factory object & SPD data caches
/// @param[in] i_target the fapi2 target
/// @param[out] o_factory_caches map of factory objects with a dimm position key
/// @param[in] i_pDecoder optional input decoder to insert custom decoder, defaulted to nullptr
/// @return FAPI2_RC_SUCCESS if okay
///
template<fapi2::TargetType T>
fapi2::ReturnCode populate_decoder_caches(const fapi2::Target<T>& i_target,
std::map< uint32_t, std::shared_ptr<decoder> >& o_factory_caches,
const std::shared_ptr<decoder>& i_pDecoder = nullptr);
}// spd
}// mss
#endif //_MSS_SPD_FACTORY_H_
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/spd/spd_factory.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file spd_factory.H
/// @brief SPD factory and functions
///
// *HWP HWP Owner: Andre Marin <[email protected]>
// *HWP HWP Backup: Brian Silver <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP
#ifndef _MSS_SPD_FACTORY_H_
#define _MSS_SPD_FACTORY_H_
// std lib
#include <cstdint>
#include <map>
#include <memory>
// fapi2
#include <fapi2.H>
// mss lib
#include <lib/spd/common/spd_decoder.H>
namespace mss
{
namespace spd
{
///
/// @brief Decodes SPD Revision encoding level
/// @param[in] i_target dimm target
/// @param[in] i_spd_data SPD data
/// @param[out] o_value encoding revision num
/// @return FAPI2_RC_SUCCESS if okay
/// @note Decodes SPD Byte 1 (3~0).
/// @note Item JC-45-2220.01x
/// @note Page 14-15
/// @note DDR4 SPD Document Release 3
///
fapi2::ReturnCode rev_encoding_level(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const std::vector<uint8_t>& i_spd_data,
uint8_t& o_value);
///
/// @brief Decodes SPD Revision additions level
/// @param[in] i_target dimm target
/// @param[in] i_spd_data SPD blob
/// @param[out] o_value additions revision num
/// @return FAPI2_RC_SUCCESS if okay
/// @note Decodes SPD Byte 1 (bits 7~4).
/// @note Item JC-45-2220.01x
/// @note Page 14-15
/// @note DDR4 SPD Document Release 3
///
fapi2::ReturnCode rev_additions_level(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const std::vector<uint8_t>& i_spd_data,
uint8_t& o_value);
///
/// @brief Decodes base module type (DIMM type) from SPD
/// @param[in] i_target dimm target
/// @param[in] i_spd_data SPD data
/// @param[out] o_value base module type
/// @return FAPI2_RC_SUCCESS if okay
/// @note Decodes SPD Byte 3 (bits 3~0)
/// @note Item JC-45-2220.01x
/// @note Page 17
/// @note DDR4 SPD Document Release 3
///
fapi2::ReturnCode base_module_type(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const std::vector<uint8_t>& i_spd_data,
uint8_t& o_value);
///
/// @brief Decodes DRAM Device Type
/// @param[in] i_target dimm target
/// @param[out] o_value dram device type enumeration
/// @return FAPI2_RC_SUCCESS if okay
/// @note Decodes SPD Byte 2
/// @note Item JC-45-2220.01x
/// @note Page 16
/// @note DDR4 SPD Document Release 3
///
fapi2::ReturnCode dram_device_type(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const std::vector<uint8_t>& i_spd_data,
uint8_t& o_value);
///
/// @brief Decodes reference raw card
/// @param[in] i_target dimm target
/// @param[in] i_spd_data SPD data
/// @param[out] o_output encoding from SPD
/// @return FAPI2_RC_SUCCESS if okay
/// @note SPD Byte 130 (Bits 7~0)
/// @note Item JEDEC Standard No. 21-C
/// @note DDR4 SPD Document Release 2
/// @Note Page 4.1.2.12 - 49
///
fapi2::ReturnCode reference_raw_card(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const std::vector<uint8_t>& i_spd_data,
uint8_t& o_output);
///
/// @brief Retrieve current raw card settings
/// based on dimm type and raw card reference rev
/// @param[in] i_target dimm target
/// @param[in] i_spd_data SPD data
/// @param[out] o_raw_card raw card settings
/// @return FAPI2_RC_SUCCESS if okay
///
fapi2::ReturnCode raw_card_factory(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const std::vector<uint8_t>& i_spd_data,
rcw_settings& o_raw_card);
///
/// @brief Object factory to select correct decoder
/// @param[in] i_target dimm target
/// @param[in] i_spd_data SPD data
/// @param[out] o_fact_obj shared pointer to the factory object
/// @return FAPI2_RC_SUCCESS if okay
/// @note Factory dependent on SPD revision & dimm type
///
fapi2::ReturnCode factory(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const std::vector<uint8_t>& i_spd_data,
std::shared_ptr<decoder>& o_fact_obj);
///
/// @brief Creates factory object & SPD data caches
/// @param[in] i_target the fapi2 target
/// @param[out] o_factory_caches vector of factory objects
/// @param[in] i_pDecoder optional input decoder to insert custom decoder (nullptr default)
/// @return FAPI2_RC_SUCCESS if okay
///
template<fapi2::TargetType T>
fapi2::ReturnCode populate_decoder_caches(const fapi2::Target<T>& i_target,
std::vector< std::shared_ptr<decoder> >& o_factory_caches,
const std::shared_ptr<decoder>& i_pDecoder = nullptr);
}// spd
}// mss
#endif //_MSS_SPD_FACTORY_H_
|
Simplify spd factory mapping to share among controllers
|
Simplify spd factory mapping to share among controllers
Also happened to address RTC 163150 and RTC:152390
with this refactoring.
Change-Id: I309ad21270f38222e85dbb9a3a97a705eef7fab2
Original-Change-Id: Iaba29d96f577c74bda7c3b147c16749eb1d861e5
Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/36766
Reviewed-by: STEPHEN GLANCY <[email protected]>
Reviewed-by: Louis Stermole <[email protected]>
Reviewed-by: Brian R. Silver <[email protected]>
Reviewed-by: JACOB L. HARVEY <[email protected]>
Tested-by: Jenkins Server <[email protected]>
Tested-by: Hostboot CI <[email protected]>
Reviewed-by: Jennifer A. Stofer <[email protected]>
|
C++
|
apache-2.0
|
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
|
6b09b08a22028c4e699f4afdc6c00eef7de8e3fe
|
util/file/string_file.cc
|
util/file/string_file.cc
|
// Copyright 2014 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "util/file/string_file.h"
#include <string.h>
#include <algorithm>
#include <limits>
#include "base/logging.h"
#include "base/numerics/safe_math.h"
#include "util/misc/implicit_cast.h"
#include "util/numeric/safe_assignment.h"
namespace crashpad {
StringFile::StringFile() : string_(), offset_(0) {
}
StringFile::~StringFile() {
}
void StringFile::SetString(const std::string& string) {
CHECK_LE(
string.size(),
implicit_cast<size_t>(std::numeric_limits<FileOperationResult>::max()));
string_ = string;
offset_ = 0;
}
void StringFile::Reset() {
string_.clear();
offset_ = 0;
}
FileOperationResult StringFile::Read(void* data, size_t size) {
DCHECK(offset_.IsValid());
const size_t offset = offset_.ValueOrDie();
if (offset >= string_.size()) {
return 0;
}
const size_t nread = std::min(size, string_.size() - offset);
base::CheckedNumeric<FileOperationResult> new_offset = offset_;
new_offset += nread;
if (!new_offset.IsValid()) {
LOG(ERROR) << "Read(): file too large";
return -1;
}
memcpy(data, &string_[offset], nread);
offset_ = new_offset;
return nread;
}
bool StringFile::Write(const void* data, size_t size) {
DCHECK(offset_.IsValid());
const size_t offset = offset_.ValueOrDie();
if (offset > string_.size()) {
string_.resize(offset);
}
base::CheckedNumeric<FileOperationResult> new_offset = offset_;
new_offset += size;
if (!new_offset.IsValid()) {
LOG(ERROR) << "Write(): file too large";
return false;
}
string_.replace(offset, size, reinterpret_cast<const char*>(data), size);
offset_ = new_offset;
return true;
}
bool StringFile::WriteIoVec(std::vector<WritableIoVec>* iovecs) {
DCHECK(offset_.IsValid());
if (iovecs->empty()) {
LOG(ERROR) << "WriteIoVec(): no iovecs";
return false;
}
// Avoid writing anything at all if it would cause an overflow.
base::CheckedNumeric<FileOperationResult> new_offset = offset_;
for (const WritableIoVec& iov : *iovecs) {
new_offset += iov.iov_len;
if (!new_offset.IsValid()) {
LOG(ERROR) << "WriteIoVec(): file too large";
return false;
}
}
for (const WritableIoVec& iov : *iovecs) {
if (!Write(iov.iov_base, iov.iov_len)) {
return false;
}
}
#ifndef NDEBUG
// The interface says that |iovecs| is not sacred, so scramble it to make sure
// that nobody depends on it.
memset(&(*iovecs)[0], 0xa5, sizeof((*iovecs)[0]) * iovecs->size());
#endif
return true;
}
FileOffset StringFile::Seek(FileOffset offset, int whence) {
DCHECK(offset_.IsValid());
size_t base_offset;
switch (whence) {
case SEEK_SET:
base_offset = 0;
break;
case SEEK_CUR:
base_offset = offset_.ValueOrDie();
break;
case SEEK_END:
base_offset = string_.size();
break;
default:
LOG(ERROR) << "Seek(): invalid whence " << whence;
return -1;
}
FileOffset base_offset_fileoffset;
if (!AssignIfInRange(&base_offset_fileoffset, base_offset)) {
LOG(ERROR) << "Seek(): base_offset " << base_offset
<< " invalid for FileOffset";
return -1;
}
base::CheckedNumeric<FileOffset> new_offset(base_offset_fileoffset);
new_offset += offset;
if (!new_offset.IsValid()) {
LOG(ERROR) << "Seek(): new_offset invalid";
return -1;
}
FileOffset new_offset_fileoffset = new_offset.ValueOrDie();
size_t new_offset_sizet;
if (!AssignIfInRange(&new_offset_sizet, new_offset_fileoffset)) {
LOG(ERROR) << "Seek(): new_offset " << new_offset_fileoffset
<< " invalid for size_t";
return -1;
}
offset_ = new_offset_sizet;
return offset_.ValueOrDie();
}
} // namespace crashpad
|
// Copyright 2014 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "util/file/string_file.h"
#include <string.h>
#include <algorithm>
#include <limits>
#include "base/logging.h"
#include "base/numerics/safe_math.h"
#include "util/misc/implicit_cast.h"
#include "util/numeric/safe_assignment.h"
namespace crashpad {
StringFile::StringFile() : string_(), offset_(0) {
}
StringFile::~StringFile() {
}
void StringFile::SetString(const std::string& string) {
CHECK_LE(
string.size(),
implicit_cast<size_t>(std::numeric_limits<FileOperationResult>::max()));
string_ = string;
offset_ = 0;
}
void StringFile::Reset() {
string_.clear();
offset_ = 0;
}
FileOperationResult StringFile::Read(void* data, size_t size) {
DCHECK(offset_.IsValid());
const size_t offset = offset_.ValueOrDie();
if (offset >= string_.size()) {
return 0;
}
const size_t nread = std::min(size, string_.size() - offset);
base::CheckedNumeric<FileOperationResult> new_offset = offset_;
new_offset += nread;
if (!new_offset.IsValid()) {
LOG(ERROR) << "Read(): file too large";
return -1;
}
memcpy(data, &string_[offset], nread);
offset_ = new_offset;
return nread;
}
bool StringFile::Write(const void* data, size_t size) {
DCHECK(offset_.IsValid());
const size_t offset = offset_.ValueOrDie();
if (offset > string_.size()) {
string_.resize(offset);
}
base::CheckedNumeric<FileOperationResult> new_offset = offset_;
new_offset += size;
if (!new_offset.IsValid()) {
LOG(ERROR) << "Write(): file too large";
return false;
}
string_.replace(offset, size, reinterpret_cast<const char*>(data), size);
offset_ = new_offset;
return true;
}
bool StringFile::WriteIoVec(std::vector<WritableIoVec>* iovecs) {
DCHECK(offset_.IsValid());
if (iovecs->empty()) {
LOG(ERROR) << "WriteIoVec(): no iovecs";
return false;
}
// Avoid writing anything at all if it would cause an overflow.
base::CheckedNumeric<FileOperationResult> new_offset = offset_;
for (const WritableIoVec& iov : *iovecs) {
new_offset += iov.iov_len;
if (!new_offset.IsValid()) {
LOG(ERROR) << "WriteIoVec(): file too large";
return false;
}
}
for (const WritableIoVec& iov : *iovecs) {
if (!Write(iov.iov_base, iov.iov_len)) {
return false;
}
}
#ifndef NDEBUG
// The interface says that |iovecs| is not sacred, so scramble it to make sure
// that nobody depends on it.
memset(&(*iovecs)[0], 0xa5, sizeof((*iovecs)[0]) * iovecs->size());
#endif
return true;
}
FileOffset StringFile::Seek(FileOffset offset, int whence) {
DCHECK(offset_.IsValid());
size_t base_offset;
switch (whence) {
case SEEK_SET:
base_offset = 0;
break;
case SEEK_CUR:
base_offset = offset_.ValueOrDie();
break;
case SEEK_END:
base_offset = string_.size();
break;
default:
LOG(ERROR) << "Seek(): invalid whence " << whence;
return -1;
}
FileOffset base_offset_fileoffset;
if (!AssignIfInRange(&base_offset_fileoffset, base_offset)) {
LOG(ERROR) << "Seek(): base_offset " << base_offset
<< " invalid for FileOffset";
return -1;
}
base::CheckedNumeric<FileOffset> new_offset(base_offset_fileoffset);
new_offset += offset;
if (!new_offset.IsValid()) {
LOG(ERROR) << "Seek(): new_offset invalid";
return -1;
}
size_t new_offset_sizet;
if (!new_offset.AssignIfValid(&new_offset_sizet)) {
LOG(ERROR) << "Seek(): new_offset " << new_offset.ValueOrDie()
<< " invalid for size_t";
return -1;
}
offset_ = new_offset_sizet;
return base::ValueOrDieForType<FileOffset>(offset_);
}
} // namespace crashpad
|
Update util/file/string_file.cc for new base/numerics API
|
Update util/file/string_file.cc for new base/numerics API
The code was not incorrect before, but this expression is simpler.
Upstream of change made at https://codereview.chromium.org/2528243002.
[email protected]
BUG=chromium:668713
Change-Id: Idae36bd8312666a3254eda02713869776fec0248
Reviewed-on: https://chromium-review.googlesource.com/417981
Reviewed-by: Mark Mentovai <[email protected]>
|
C++
|
apache-2.0
|
atom/crashpad,atom/crashpad,chromium/crashpad,chromium/crashpad,chromium/crashpad,atom/crashpad
|
2c7b8fee89a044af091c7a19db1aee795f52ac05
|
util/read_write_lock.hpp
|
util/read_write_lock.hpp
|
/* Copyright (c) 2017-2020 Hans-Kristian Arntzen
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include <atomic>
#ifdef __SSE2__
#include <emmintrin.h>
#endif
namespace Util
{
class RWSpinLock
{
public:
enum { Reader = 2, Writer = 1 };
RWSpinLock()
{
counter.store(0);
}
inline void lock_read()
{
unsigned v = counter.fetch_add(Reader, std::memory_order_acquire);
while ((v & Writer) != 0)
{
#ifdef __SSE2__
_mm_pause();
#endif
v = counter.load(std::memory_order_acquire);
}
}
inline void unlock_read()
{
counter.fetch_sub(Reader, std::memory_order_release);
}
inline void lock_write()
{
uint32_t expected = 0;
while (!counter.compare_exchange_weak(expected, Writer,
std::memory_order_acquire,
std::memory_order_relaxed))
{
#ifdef __SSE2__
_mm_pause();
#endif
expected = 0;
}
}
inline void unlock_write()
{
counter.fetch_and(~Writer, std::memory_order_release);
}
inline void promote_reader_to_writer()
{
uint32_t expected = Reader;
while (!counter.compare_exchange_weak(expected, Writer,
std::memory_order_acquire,
std::memory_order_relaxed))
{
#ifdef __SSE2__
_mm_pause();
#endif
expected = Reader;
}
}
private:
std::atomic<uint32_t> counter;
};
}
|
/* Copyright (c) 2017-2020 Hans-Kristian Arntzen
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include <atomic>
#ifdef __SSE2__
#include <emmintrin.h>
#endif
namespace Util
{
class RWSpinLock
{
public:
enum { Reader = 2, Writer = 1 };
RWSpinLock()
{
counter.store(0);
}
inline void lock_read()
{
unsigned v = counter.fetch_add(Reader, std::memory_order_acquire);
while ((v & Writer) != 0)
{
#ifdef __SSE2__
_mm_pause();
#endif
v = counter.load(std::memory_order_acquire);
}
}
inline void unlock_read()
{
counter.fetch_sub(Reader, std::memory_order_release);
}
inline void lock_write()
{
uint32_t expected = 0;
while (!counter.compare_exchange_weak(expected, Writer,
std::memory_order_acquire,
std::memory_order_relaxed))
{
#ifdef __SSE2__
_mm_pause();
#endif
expected = 0;
}
}
inline void unlock_write()
{
counter.fetch_and(~Writer, std::memory_order_release);
}
inline void promote_reader_to_writer()
{
uint32_t expected = Reader;
if (!counter.compare_exchange_strong(expected, Writer,
std::memory_order_acquire,
std::memory_order_relaxed))
{
unlock_read();
lock_write();
}
}
private:
std::atomic<uint32_t> counter;
};
}
|
Fix RWSpinlock::promote_to_writer().
|
Fix RWSpinlock::promote_to_writer().
If multiple threads enter it, it will spin. Just fallback to unlock(),
lock() if we fail the first CAS.
|
C++
|
mit
|
Themaister/Granite,Themaister/Granite,Themaister/Granite,Themaister/Granite,Themaister/Granite,Themaister/Granite
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.