text
stringlengths 54
60.6k
|
|---|
<commit_before>/**************************************************************************************/
/* */
/* Visualization Library */
/* http://www.visualizationlibrary.org */
/* */
/* Copyright (c) 2005-2010, Michele Bosi */
/* 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. */
/* */
/* 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 <vlGraphics/SceneManagerPortals.hpp>
#include <vlGraphics/Geometry.hpp>
#include <vlCore/Say.hpp>
#include <vlGraphics/Camera.hpp>
using namespace vl;
//-----------------------------------------------------------------------------
// Portal
//-----------------------------------------------------------------------------
bool Portal::computeNormal()
{
mNormal = 0;
if (geometry().size() < 3)
{
vl::Log::error("Portal::computeNormal() error, no portal geometry defined.\n");
return false;
}
if (!mTargetSector)
{
vl::Log::error("Portal::computeNormal() error, no sector bound to this portal.\n");
return false;
}
fvec3 v0 = geometry()[0];
fvec3 v1 = geometry()[1] - v0;
fvec3 v2 = geometry()[2] - v0;
mNormal = cross(v1,v2);
return true;
}
//-----------------------------------------------------------------------------
// Sector
//-----------------------------------------------------------------------------
AABB Sector::computeBoundingBox()
{
AABB aabb;
for(int i=0; i<actors()->size(); ++i)
{
actors()->at(i)->computeBounds();
aabb += actors()->at(i)->boundingBox();
}
return aabb;
}
//-----------------------------------------------------------------------------
void Sector::executeCallbacks(const Camera*cam,SceneManagerPortals* psm, Portal*p)
{
for(unsigned i=0; i<callbacks().size(); ++i)
callbacks()[i]->operator()(cam,psm,this,p);
}
//-----------------------------------------------------------------------------
// SceneManagerPortals
//-----------------------------------------------------------------------------
void SceneManagerPortals::initialize()
{
computePortalNormals();
for(unsigned i=0; i<mSectors.size(); ++i)
{
if (mSectors[i]->volumes().empty())
vl::Log::error( vl::Say("Sector #%n does not have any volume!\n") << i );
for(unsigned j=0; j<mSectors[i]->portals().size(); ++j)
if (!mSectors[i]->portals()[j]->targetSector())
vl::Log::error( vl::Say("In Sector #%n Portal #%n does not have any target sector!\n") << i << j);
}
}
//-----------------------------------------------------------------------------
void SceneManagerPortals::renderPortal(Portal* portal)
{
if (mPortalActorMap.find(portal) == mPortalActorMap.end())
{
const fvec4 portal_color = fvec4(1,0,0,0.25f);
vl::ref<vl::Effect> portal_fx = new vl::Effect;
/*portal_fx->shader()->enable(vl::EN_DEPTH_TEST);
portal_fx->shader()->gocDepthFunc()->set(vl::FU_LEQUAL);*/
portal_fx->shader()->enable(vl::EN_BLEND);
portal_fx->shader()->gocLineWidth()->set(2.0f);
portal_fx->shader()->gocColor()->setValue(portal_color);
vl::ref<vl::Geometry> portal_geom = new vl::Geometry;
vl::ref<vl::ArrayFloat3> vert_array = new vl::ArrayFloat3;
portal_geom->setVertexArray(vert_array.get());
vert_array->resize(portal->geometry().size());
for(unsigned int i=0; i<portal->geometry().size(); ++i)
vert_array->at(i) = portal->geometry()[i];
portal_geom->drawCalls()->push_back( new vl::DrawArrays(vl::PT_LINE_LOOP, 0, (int)vert_array->size()) );
#if defined(VL_OPENGL)
portal_geom->drawCalls()->push_back( new vl::DrawArrays(vl::PT_POLYGON, 0, (int)vert_array->size()) );
#endif
mPortalActorMap[portal] = new vl::Actor(portal_geom.get(), portal_fx.get(), NULL);
}
}
//-----------------------------------------------------------------------------
void SceneManagerPortals::extractActors(ActorCollection& list)
{
for(unsigned i=0; i<mSectors.size(); ++i)
for(int j=0; j<mSectors[i]->actors()->size(); ++j)
list.push_back( mSectors[i]->actors()->at(j) );
}
//-----------------------------------------------------------------------------
void SceneManagerPortals::extractVisibleActors(ActorCollection& list, const Camera* camera)
{
if (cullingEnabled())
{
Sector* start = computeStartingSector(camera);
if (!start)
extractActors(list);
else
{
++mVisitTick;
mTempActors.clear();
mFrustumStack.clear();
mFrustumStack.push_back(camera->frustum());
start->executeCallbacks(camera,this,NULL);
visitSector(NULL, start, camera->modelingMatrix().getT(), camera);
// insert portal actors
if (showPortals())
{
for(std::map<Portal*, ref<Actor> >::const_iterator it = mPortalActorMap.begin(); it != mPortalActorMap.end(); ++it)
mTempActors.push_back(it->second);
}
// mic fixme: isn't quicker to use sets instead of sort()+unique()?
// avoid reporting duplicates
std::sort(mTempActors.begin(), mTempActors.end());
std::vector< ref<Actor> >::iterator new_end = std::unique(mTempActors.begin(), mTempActors.end());
for(std::vector< ref<Actor> >::iterator it = mTempActors.begin(); it != new_end; ++it)
list.push_back(it->get());
}
}
else
extractActors(list);
}
//-----------------------------------------------------------------------------
void SceneManagerPortals::visitSector(Sector* prev, Sector* sector, const vec3& eye, const Camera* camera)
{
// this sector is visible so we add the visible objects
for(int j=0; j<sector->actors()->size(); ++j)
{
if (isEnabled(sector->actors()->at(j)))
{
sector->actors()->at(j)->computeBounds();
bool visible = true;
for(unsigned i=0; visible && i<mFrustumStack.size(); ++i)
visible = visible & !mFrustumStack[i].cull( sector->actors()->at(j)->boundingBox() );
if( visible )
mTempActors.push_back( sector->actors()->at(j) );
}
}
// check the visible portals
for(unsigned j=0; j<sector->portals().size(); ++j)
{
if(showPortals())
renderPortal(sector->portals()[j].get());
// open/closed portals.
if(!sector->portals()[j]->isOpen())
continue;
if (sector->portals()[j]->mVisitTick == mVisitTick)
continue;
else
sector->portals()[j]->mVisitTick = mVisitTick;
Sector* target_sec = sector->portals()[j]->targetSector();
VL_CHECK(target_sec != sector)
if ( target_sec != prev )
{
bool visible = true;
for(unsigned i=0; visible && i<mFrustumStack.size(); ++i)
visible = visible & !mFrustumStack[i].cull( sector->portals()[j]->geometry() );
if (visible)
{
// make visiting_portal_frustum
Frustum portal_frustum;
portal_frustum.planes().resize(sector->portals()[j]->geometry().size());
bool flip = dot((fvec3)eye - sector->portals()[j]->geometry()[0], sector->portals()[j]->normal()) < 0;
for(unsigned i=0; i<sector->portals()[j]->geometry().size(); ++i)
{
int i2 = (i+1) % sector->portals()[j]->geometry().size();
vec3 v1 = (vec3)sector->portals()[j]->geometry()[i] - eye;
vec3 v2 = (vec3)sector->portals()[j]->geometry()[i2] - eye;
vec3 n = cross(v1,v2);
n.normalize();
if (flip)
n = -n;
portal_frustum.setPlane(i, Plane(dot(n,eye),n));
}
mFrustumStack.push_back(portal_frustum);
sector->executeCallbacks(camera,this,sector->portals()[j].get());
visitSector(sector, sector->portals()[j]->targetSector(), eye, camera);
mFrustumStack.pop_back();
}
}
}
}
//-----------------------------------------------------------------------------
void SceneManagerPortals::computePortalNormals()
{
for(unsigned i=0; i<mSectors.size(); ++i)
for(unsigned j=0; j<mSectors[i]->portals().size(); ++j)
mSectors[i]->portals()[j]->computeNormal();
}
//-----------------------------------------------------------------------------
Sector* SceneManagerPortals::computeStartingSector(const Camera* camera)
{
vec3 eye = camera->modelingMatrix().getT();
for(unsigned i=0; i<mSectors.size(); ++i)
{
for(unsigned j=0; j<mSectors[i]->volumes().size(); ++j)
{
if (sectors()[i]->volumes()[j].isInside(eye))
return sectors()[i].get();
}
}
return externalSector();
}
//-----------------------------------------------------------------------------
<commit_msg>SceneManagerPortals.cpp fixed rendering of portals.<commit_after>/**************************************************************************************/
/* */
/* Visualization Library */
/* http://www.visualizationlibrary.org */
/* */
/* Copyright (c) 2005-2010, Michele Bosi */
/* 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. */
/* */
/* 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 <vlGraphics/SceneManagerPortals.hpp>
#include <vlGraphics/Geometry.hpp>
#include <vlCore/Say.hpp>
#include <vlGraphics/Camera.hpp>
using namespace vl;
//-----------------------------------------------------------------------------
// Portal
//-----------------------------------------------------------------------------
bool Portal::computeNormal()
{
mNormal = 0;
if (geometry().size() < 3)
{
vl::Log::error("Portal::computeNormal() error, no portal geometry defined.\n");
return false;
}
if (!mTargetSector)
{
vl::Log::error("Portal::computeNormal() error, no sector bound to this portal.\n");
return false;
}
fvec3 v0 = geometry()[0];
fvec3 v1 = geometry()[1] - v0;
fvec3 v2 = geometry()[2] - v0;
mNormal = cross(v1,v2);
return true;
}
//-----------------------------------------------------------------------------
// Sector
//-----------------------------------------------------------------------------
AABB Sector::computeBoundingBox()
{
AABB aabb;
for(int i=0; i<actors()->size(); ++i)
{
actors()->at(i)->computeBounds();
aabb += actors()->at(i)->boundingBox();
}
return aabb;
}
//-----------------------------------------------------------------------------
void Sector::executeCallbacks(const Camera*cam,SceneManagerPortals* psm, Portal*p)
{
for(unsigned i=0; i<callbacks().size(); ++i)
callbacks()[i]->operator()(cam,psm,this,p);
}
//-----------------------------------------------------------------------------
// SceneManagerPortals
//-----------------------------------------------------------------------------
void SceneManagerPortals::initialize()
{
computePortalNormals();
for(unsigned i=0; i<mSectors.size(); ++i)
{
if (mSectors[i]->volumes().empty())
vl::Log::error( vl::Say("Sector #%n does not have any volume!\n") << i );
for(unsigned j=0; j<mSectors[i]->portals().size(); ++j)
if (!mSectors[i]->portals()[j]->targetSector())
vl::Log::error( vl::Say("In Sector #%n Portal #%n does not have any target sector!\n") << i << j);
}
}
//-----------------------------------------------------------------------------
void SceneManagerPortals::renderPortal(Portal* portal)
{
std::map<Portal*, ref<Actor> >::iterator it = mPortalActorMap.find(portal);
if (it == mPortalActorMap.end())
{
const fvec4 portal_color = fvec4(1,0,0,0.25f);
vl::ref<vl::Effect> portal_fx = new vl::Effect;
/*portal_fx->shader()->enable(vl::EN_DEPTH_TEST);
portal_fx->shader()->gocDepthFunc()->set(vl::FU_LEQUAL);*/
portal_fx->shader()->enable(vl::EN_BLEND);
portal_fx->shader()->gocLineWidth()->set(2.0f);
portal_fx->shader()->gocColor()->setValue(portal_color);
vl::ref<vl::Geometry> portal_geom = new vl::Geometry;
vl::ref<vl::ArrayFloat3> vert_array = new vl::ArrayFloat3;
portal_geom->setVertexArray(vert_array.get());
vert_array->resize(portal->geometry().size());
for(unsigned int i=0; i<portal->geometry().size(); ++i)
vert_array->at(i) = portal->geometry()[i];
portal_geom->drawCalls()->push_back( new vl::DrawArrays(vl::PT_LINE_LOOP, 0, (int)vert_array->size()) );
#if defined(VL_OPENGL)
portal_geom->drawCalls()->push_back( new vl::DrawArrays(vl::PT_POLYGON, 0, (int)vert_array->size()) );
#endif
ref<Actor> actor = new vl::Actor(portal_geom.get(), portal_fx.get(), NULL);
mPortalActorMap[portal] = actor;
mTempActors.push_back(actor);
}
else
mTempActors.push_back(it->second);
}
//-----------------------------------------------------------------------------
void SceneManagerPortals::extractActors(ActorCollection& list)
{
for(unsigned i=0; i<mSectors.size(); ++i)
for(int j=0; j<mSectors[i]->actors()->size(); ++j)
list.push_back( mSectors[i]->actors()->at(j) );
}
//-----------------------------------------------------------------------------
void SceneManagerPortals::extractVisibleActors(ActorCollection& list, const Camera* camera)
{
if (cullingEnabled())
{
Sector* start = computeStartingSector(camera);
if (!start)
extractActors(list);
else
{
++mVisitTick;
mTempActors.clear();
mFrustumStack.clear();
mFrustumStack.push_back(camera->frustum());
start->executeCallbacks(camera,this,NULL);
visitSector(NULL, start, camera->modelingMatrix().getT(), camera);
// remove duplicates
std::sort(mTempActors.begin(), mTempActors.end());
std::vector< ref<Actor> >::iterator new_end = std::unique(mTempActors.begin(), mTempActors.end());
for(std::vector< ref<Actor> >::iterator it = mTempActors.begin(); it != new_end; ++it)
list.push_back(it->get());
}
}
else
extractActors(list);
}
//-----------------------------------------------------------------------------
void SceneManagerPortals::visitSector(Sector* prev, Sector* sector, const vec3& eye, const Camera* camera)
{
// this sector is visible so we add the visible objects
for(int j=0; j<sector->actors()->size(); ++j)
{
if (isEnabled(sector->actors()->at(j)))
{
sector->actors()->at(j)->computeBounds();
bool visible = true;
for(unsigned i=0; visible && i<mFrustumStack.size(); ++i)
visible = visible & !mFrustumStack[i].cull( sector->actors()->at(j)->boundingBox() );
if( visible )
mTempActors.push_back( sector->actors()->at(j) );
}
}
// check the visible portals
for(unsigned j=0; j<sector->portals().size(); ++j)
{
if(showPortals())
renderPortal(sector->portals()[j].get());
// open/closed portals.
if(!sector->portals()[j]->isOpen())
continue;
if (sector->portals()[j]->mVisitTick == mVisitTick)
continue;
else
sector->portals()[j]->mVisitTick = mVisitTick;
Sector* target_sec = sector->portals()[j]->targetSector();
VL_CHECK(target_sec != sector)
if ( target_sec != prev )
{
bool visible = true;
for(unsigned i=0; visible && i<mFrustumStack.size(); ++i)
visible = visible & !mFrustumStack[i].cull( sector->portals()[j]->geometry() );
if (visible)
{
// make visiting_portal_frustum
Frustum portal_frustum;
portal_frustum.planes().resize(sector->portals()[j]->geometry().size());
bool flip = dot((fvec3)eye - sector->portals()[j]->geometry()[0], sector->portals()[j]->normal()) < 0;
for(unsigned i=0; i<sector->portals()[j]->geometry().size(); ++i)
{
int i2 = (i+1) % sector->portals()[j]->geometry().size();
vec3 v1 = (vec3)sector->portals()[j]->geometry()[i] - eye;
vec3 v2 = (vec3)sector->portals()[j]->geometry()[i2] - eye;
vec3 n = cross(v1,v2);
n.normalize();
if (flip)
n = -n;
portal_frustum.setPlane(i, Plane(dot(n,eye),n));
}
mFrustumStack.push_back(portal_frustum);
sector->executeCallbacks(camera,this,sector->portals()[j].get());
visitSector(sector, sector->portals()[j]->targetSector(), eye, camera);
mFrustumStack.pop_back();
}
}
}
}
//-----------------------------------------------------------------------------
void SceneManagerPortals::computePortalNormals()
{
for(unsigned i=0; i<mSectors.size(); ++i)
for(unsigned j=0; j<mSectors[i]->portals().size(); ++j)
mSectors[i]->portals()[j]->computeNormal();
}
//-----------------------------------------------------------------------------
Sector* SceneManagerPortals::computeStartingSector(const Camera* camera)
{
vec3 eye = camera->modelingMatrix().getT();
for(unsigned i=0; i<mSectors.size(); ++i)
{
for(unsigned j=0; j<mSectors[i]->volumes().size(); ++j)
{
if (sectors()[i]->volumes()[j].isInside(eye))
return sectors()[i].get();
}
}
return externalSector();
}
//-----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before><commit_msg>fix: GAMxVEN register class<commit_after><|endoftext|>
|
<commit_before>#ifndef MIMOSA_FORMAT_FORMAT_STREAM_HH
# define MIMOSA_FORMAT_FORMAT_STREAM_HH
# include "format.hh"
# include "../stream/stream.hh"
namespace mimosa
{
namespace format
{
template <typename ... Args>
inline
bool format(stream::Stream::Ptr stream,
runtime::Time timeout,
const char * fmt,
Args ... args)
{
std::string str(format::str(fmt, args...));
int64_t bytes = stream->loopWrite(str.data(), str.size(), timeout);
return static_cast<std::string::size_type> (bytes) == str.size();
}
template <typename ... Args>
inline
bool format(stream::Stream::Ptr stream,
const char * fmt,
Args ... args)
{
return format(stream, static_cast<runtime::Time>(0), fmt, args...);
}
}
}
#endif /* !MIMOSA_FORMAT_FORMAT_STREAM_HH */
<commit_msg>Fixed a case where the formated string is empty<commit_after>#ifndef MIMOSA_FORMAT_FORMAT_STREAM_HH
# define MIMOSA_FORMAT_FORMAT_STREAM_HH
# include "format.hh"
# include "../stream/stream.hh"
namespace mimosa
{
namespace format
{
template <typename ... Args>
inline
bool format(stream::Stream::Ptr stream,
runtime::Time timeout,
const char * fmt,
Args ... args)
{
std::string str(format::str(fmt, args...));
if (str.empty())
return true;
int64_t bytes = stream->loopWrite(str.data(), str.size(), timeout);
return static_cast<std::string::size_type> (bytes) == str.size();
}
template <typename ... Args>
inline
bool format(stream::Stream::Ptr stream,
const char * fmt,
Args ... args)
{
return format(stream, static_cast<runtime::Time>(0), fmt, args...);
}
}
}
#endif /* !MIMOSA_FORMAT_FORMAT_STREAM_HH */
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: svarray.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-10-12 15:23:09 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#define _SVARRAY_CXX
#define _SVSTDARR_BOOLS
#define _SVSTDARR_BYTES
#define _SVSTDARR_ULONGS
#define _SVSTDARR_ULONGSSORT
#define _SVSTDARR_USHORTS
#define _SVSTDARR_LONGS
#define _SVSTDARR_LONGSSORT
#define _SVSTDARR_SHORTS
#define _SVSTDARR_STRINGS
#define _SVSTDARR_STRINGSDTOR
#define _SVSTDARR_STRINGSSORT
#define _SVSTDARR_STRINGSSORTDTOR
#define _SVSTDARR_STRINGSISORT
#define _SVSTDARR_STRINGSISORTDTOR
#define _SVSTDARR_USHORTSSORT
#define _SVSTDARR_BYTESTRINGS
#define _SVSTDARR_BYTESTRINGSDTOR
#define _SVSTDARR_BYTESTRINGSSORT
#define _SVSTDARR_BYTESTRINGSSORTDTOR
#define _SVSTDARR_BYTESTRINGSISORT
#define _SVSTDARR_BYTESTRINGSISORTDTOR
#define _SVSTDARR_XUB_STRLEN
#define _SVSTDARR_XUB_STRLENSORT
#include <svstdarr.hxx>
#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#ifdef MAC
#pragma segment NEVER_PURGE
#endif
SV_IMPL_VARARR(SvPtrarr,VoidPtr)
SV_IMPL_VARARR_PLAIN(SvPtrarrPlain,VoidPtr)
USHORT SvPtrarr::GetPos( const VoidPtr& aElement ) const
{ USHORT n;
for( n=0; n < nA && *(GetData()+n) != aElement; ) n++;
return ( n >= nA ? USHRT_MAX : n );
}
USHORT SvPtrarrPlain::GetPos( const VoidPtr aElement ) const
{ USHORT n;
for( n=0; n < nA && *(GetData()+n) != aElement; ) n++;
return ( n >= nA ? USHRT_MAX : n );
}
SV_IMPL_VARARR( SvBools, BOOL )
SV_IMPL_VARARR( SvBytes, BYTE )
SV_IMPL_VARARR( SvULongs, ULONG )
SV_IMPL_VARARR( SvUShorts, USHORT )
SV_IMPL_VARARR( SvLongs, long)
SV_IMPL_VARARR( SvShorts, short )
SV_IMPL_VARARR_SORT( SvULongsSort, ULONG )
SV_IMPL_VARARR_SORT( SvLongsSort, long )
SV_IMPL_VARARR_SORT( SvXub_StrLensSort, xub_StrLen )
SV_IMPL_VARARR( SvXub_StrLens, xub_StrLen )
SV_IMPL_PTRARR( SvStrings, StringPtr )
SV_IMPL_PTRARR( SvStringsDtor, StringPtr )
SV_IMPL_OP_PTRARR_SORT( SvStringsSort, StringPtr )
SV_IMPL_OP_PTRARR_SORT( SvStringsSortDtor, StringPtr )
SV_IMPL_PTRARR( SvByteStrings, ByteStringPtr )
SV_IMPL_PTRARR( SvByteStringsDtor, ByteStringPtr )
SV_IMPL_OP_PTRARR_SORT( SvByteStringsSort, ByteStringPtr )
SV_IMPL_OP_PTRARR_SORT( SvByteStringsSortDtor, ByteStringPtr )
// ---------------- strings -------------------------------------
// Array mit anderer Seek-Methode!
_SV_IMPL_SORTAR_ALG( SvStringsISort, StringPtr )
void SvStringsISort::DeleteAndDestroy( USHORT nP, USHORT nL )
{
if( nL )
{
DBG_ASSERT( nP < nA && nP + nL <= nA, "ERR_VAR_DEL" );
for( USHORT n=nP; n < nP + nL; n++ )
delete *((StringPtr*)pData+n);
SvPtrarr::Remove( nP, nL );
}
}
BOOL SvStringsISort::Seek_Entry( const StringPtr aE, USHORT* pP ) const
{
register USHORT nO = SvStringsISort_SAR::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
StringCompare eCmp = (*((StringPtr*)pData + nM))->
CompareIgnoreCaseToAscii( *(aE) );
if( COMPARE_EQUAL == eCmp )
{
if( pP ) *pP = nM;
return TRUE;
}
else if( COMPARE_LESS == eCmp )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return FALSE;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return FALSE;
}
// ---------------- strings -------------------------------------
// Array mit anderer Seek-Methode!
_SV_IMPL_SORTAR_ALG( SvStringsISortDtor, StringPtr )
void SvStringsISortDtor::DeleteAndDestroy( USHORT nP, USHORT nL )
{
if( nL )
{
DBG_ASSERT( nP < nA && nP + nL <= nA, "ERR_VAR_DEL" );
for( USHORT n=nP; n < nP + nL; n++ )
delete *((StringPtr*)pData+n);
SvPtrarr::Remove( nP, nL );
}
}
BOOL SvStringsISortDtor::Seek_Entry( const StringPtr aE, USHORT* pP ) const
{
register USHORT nO = SvStringsISortDtor_SAR::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
StringCompare eCmp = (*((StringPtr*)pData + nM))->
CompareIgnoreCaseToAscii( *(aE) );
if( COMPARE_EQUAL == eCmp )
{
if( pP ) *pP = nM;
return TRUE;
}
else if( COMPARE_LESS == eCmp )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return FALSE;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return FALSE;
}
// ---------------- Ushorts -------------------------------------
/* SortArray fuer UShorts */
BOOL SvUShortsSort::Seek_Entry( const USHORT aE, USHORT* pP ) const
{
register USHORT nO = SvUShorts::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
if( *(pData + nM) == aE )
{
if( pP ) *pP = nM;
return TRUE;
}
else if( *(pData + nM) < aE )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return FALSE;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return FALSE;
}
void SvUShortsSort::Insert( const SvUShortsSort * pI, USHORT nS, USHORT nE )
{
if( USHRT_MAX == nE )
nE = pI->Count();
USHORT nP;
const USHORT * pIArr = pI->GetData();
for( ; nS < nE; ++nS )
{
if( ! Seek_Entry( *(pIArr+nS), &nP) )
SvUShorts::Insert( *(pIArr+nS), nP );
if( ++nP >= Count() )
{
SvUShorts::Insert( pI, nP, nS+1, nE );
nS = nE;
}
}
}
BOOL SvUShortsSort::Insert( const USHORT aE )
{
USHORT nP;
BOOL bExist = Seek_Entry( aE, &nP );
if( !bExist )
SvUShorts::Insert( aE, nP );
return !bExist;
}
BOOL SvUShortsSort::Insert( const USHORT aE, USHORT& rP )
{
BOOL bExist = Seek_Entry( aE, &rP );
if( !bExist )
SvUShorts::Insert( aE, rP );
return !bExist;
}
void SvUShortsSort::Insert( const USHORT* pE, USHORT nL)
{
USHORT nP;
for( USHORT n = 0; n < nL; ++n )
if( ! Seek_Entry( *(pE+n), &nP ))
SvUShorts::Insert( *(pE+n), nP );
}
// remove ab Pos
void SvUShortsSort::RemoveAt( const USHORT nP, USHORT nL )
{
if( nL )
SvUShorts::Remove( nP, nL);
}
// remove ab dem Eintrag
void SvUShortsSort::Remove( const USHORT aE, USHORT nL )
{
USHORT nP;
if( nL && Seek_Entry( aE, &nP ) )
SvUShorts::Remove( nP, nL);
}
// ---------------- bytestrings -------------------------------------
// Array mit anderer Seek-Methode!
_SV_IMPL_SORTAR_ALG( SvByteStringsISort, ByteStringPtr )
void SvByteStringsISort::DeleteAndDestroy( USHORT nP, USHORT nL )
{
if( nL )
{
DBG_ASSERT( nP < nA && nP + nL <= nA, "ERR_VAR_DEL" );
for( USHORT n=nP; n < nP + nL; n++ )
delete *((ByteStringPtr*)pData+n);
SvPtrarr::Remove( nP, nL );
}
}
BOOL SvByteStringsISort::Seek_Entry( const ByteStringPtr aE, USHORT* pP ) const
{
register USHORT nO = SvByteStringsISort_SAR::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
StringCompare eCmp = (*((ByteStringPtr*)pData + nM))->
CompareIgnoreCaseToAscii( *(aE) );
if( COMPARE_EQUAL == eCmp )
{
if( pP ) *pP = nM;
return TRUE;
}
else if( COMPARE_LESS == eCmp )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return FALSE;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return FALSE;
}
// Array mit anderer Seek-Methode!
_SV_IMPL_SORTAR_ALG( SvByteStringsISortDtor, ByteStringPtr )
void SvByteStringsISortDtor::DeleteAndDestroy( USHORT nP, USHORT nL )
{
if( nL )
{
DBG_ASSERT( nP < nA && nP + nL <= nA, "ERR_VAR_DEL" );
for( USHORT n=nP; n < nP + nL; n++ )
delete *((ByteStringPtr*)pData+n);
SvPtrarr::Remove( nP, nL );
}
}
BOOL SvByteStringsISortDtor::Seek_Entry( const ByteStringPtr aE, USHORT* pP ) const
{
register USHORT nO = SvByteStringsISortDtor_SAR::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
StringCompare eCmp = (*((ByteStringPtr*)pData + nM))->
CompareIgnoreCaseToAscii( *(aE) );
if( COMPARE_EQUAL == eCmp )
{
if( pP ) *pP = nM;
return TRUE;
}
else if( COMPARE_LESS == eCmp )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return FALSE;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return FALSE;
}
<commit_msg>INTEGRATION: CWS vgbugs07 (1.5.182); FILE MERGED 2007/06/04 13:31:42 vg 1.5.182.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: svarray.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2007-06-27 21:48:00 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#define _SVARRAY_CXX
#define _SVSTDARR_BOOLS
#define _SVSTDARR_BYTES
#define _SVSTDARR_ULONGS
#define _SVSTDARR_ULONGSSORT
#define _SVSTDARR_USHORTS
#define _SVSTDARR_LONGS
#define _SVSTDARR_LONGSSORT
#define _SVSTDARR_SHORTS
#define _SVSTDARR_STRINGS
#define _SVSTDARR_STRINGSDTOR
#define _SVSTDARR_STRINGSSORT
#define _SVSTDARR_STRINGSSORTDTOR
#define _SVSTDARR_STRINGSISORT
#define _SVSTDARR_STRINGSISORTDTOR
#define _SVSTDARR_USHORTSSORT
#define _SVSTDARR_BYTESTRINGS
#define _SVSTDARR_BYTESTRINGSDTOR
#define _SVSTDARR_BYTESTRINGSSORT
#define _SVSTDARR_BYTESTRINGSSORTDTOR
#define _SVSTDARR_BYTESTRINGSISORT
#define _SVSTDARR_BYTESTRINGSISORTDTOR
#define _SVSTDARR_XUB_STRLEN
#define _SVSTDARR_XUB_STRLENSORT
#include <svtools/svstdarr.hxx>
#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#ifdef MAC
#pragma segment NEVER_PURGE
#endif
SV_IMPL_VARARR(SvPtrarr,VoidPtr)
SV_IMPL_VARARR_PLAIN(SvPtrarrPlain,VoidPtr)
USHORT SvPtrarr::GetPos( const VoidPtr& aElement ) const
{ USHORT n;
for( n=0; n < nA && *(GetData()+n) != aElement; ) n++;
return ( n >= nA ? USHRT_MAX : n );
}
USHORT SvPtrarrPlain::GetPos( const VoidPtr aElement ) const
{ USHORT n;
for( n=0; n < nA && *(GetData()+n) != aElement; ) n++;
return ( n >= nA ? USHRT_MAX : n );
}
SV_IMPL_VARARR( SvBools, BOOL )
SV_IMPL_VARARR( SvBytes, BYTE )
SV_IMPL_VARARR( SvULongs, ULONG )
SV_IMPL_VARARR( SvUShorts, USHORT )
SV_IMPL_VARARR( SvLongs, long)
SV_IMPL_VARARR( SvShorts, short )
SV_IMPL_VARARR_SORT( SvULongsSort, ULONG )
SV_IMPL_VARARR_SORT( SvLongsSort, long )
SV_IMPL_VARARR_SORT( SvXub_StrLensSort, xub_StrLen )
SV_IMPL_VARARR( SvXub_StrLens, xub_StrLen )
SV_IMPL_PTRARR( SvStrings, StringPtr )
SV_IMPL_PTRARR( SvStringsDtor, StringPtr )
SV_IMPL_OP_PTRARR_SORT( SvStringsSort, StringPtr )
SV_IMPL_OP_PTRARR_SORT( SvStringsSortDtor, StringPtr )
SV_IMPL_PTRARR( SvByteStrings, ByteStringPtr )
SV_IMPL_PTRARR( SvByteStringsDtor, ByteStringPtr )
SV_IMPL_OP_PTRARR_SORT( SvByteStringsSort, ByteStringPtr )
SV_IMPL_OP_PTRARR_SORT( SvByteStringsSortDtor, ByteStringPtr )
// ---------------- strings -------------------------------------
// Array mit anderer Seek-Methode!
_SV_IMPL_SORTAR_ALG( SvStringsISort, StringPtr )
void SvStringsISort::DeleteAndDestroy( USHORT nP, USHORT nL )
{
if( nL )
{
DBG_ASSERT( nP < nA && nP + nL <= nA, "ERR_VAR_DEL" );
for( USHORT n=nP; n < nP + nL; n++ )
delete *((StringPtr*)pData+n);
SvPtrarr::Remove( nP, nL );
}
}
BOOL SvStringsISort::Seek_Entry( const StringPtr aE, USHORT* pP ) const
{
register USHORT nO = SvStringsISort_SAR::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
StringCompare eCmp = (*((StringPtr*)pData + nM))->
CompareIgnoreCaseToAscii( *(aE) );
if( COMPARE_EQUAL == eCmp )
{
if( pP ) *pP = nM;
return TRUE;
}
else if( COMPARE_LESS == eCmp )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return FALSE;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return FALSE;
}
// ---------------- strings -------------------------------------
// Array mit anderer Seek-Methode!
_SV_IMPL_SORTAR_ALG( SvStringsISortDtor, StringPtr )
void SvStringsISortDtor::DeleteAndDestroy( USHORT nP, USHORT nL )
{
if( nL )
{
DBG_ASSERT( nP < nA && nP + nL <= nA, "ERR_VAR_DEL" );
for( USHORT n=nP; n < nP + nL; n++ )
delete *((StringPtr*)pData+n);
SvPtrarr::Remove( nP, nL );
}
}
BOOL SvStringsISortDtor::Seek_Entry( const StringPtr aE, USHORT* pP ) const
{
register USHORT nO = SvStringsISortDtor_SAR::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
StringCompare eCmp = (*((StringPtr*)pData + nM))->
CompareIgnoreCaseToAscii( *(aE) );
if( COMPARE_EQUAL == eCmp )
{
if( pP ) *pP = nM;
return TRUE;
}
else if( COMPARE_LESS == eCmp )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return FALSE;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return FALSE;
}
// ---------------- Ushorts -------------------------------------
/* SortArray fuer UShorts */
BOOL SvUShortsSort::Seek_Entry( const USHORT aE, USHORT* pP ) const
{
register USHORT nO = SvUShorts::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
if( *(pData + nM) == aE )
{
if( pP ) *pP = nM;
return TRUE;
}
else if( *(pData + nM) < aE )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return FALSE;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return FALSE;
}
void SvUShortsSort::Insert( const SvUShortsSort * pI, USHORT nS, USHORT nE )
{
if( USHRT_MAX == nE )
nE = pI->Count();
USHORT nP;
const USHORT * pIArr = pI->GetData();
for( ; nS < nE; ++nS )
{
if( ! Seek_Entry( *(pIArr+nS), &nP) )
SvUShorts::Insert( *(pIArr+nS), nP );
if( ++nP >= Count() )
{
SvUShorts::Insert( pI, nP, nS+1, nE );
nS = nE;
}
}
}
BOOL SvUShortsSort::Insert( const USHORT aE )
{
USHORT nP;
BOOL bExist = Seek_Entry( aE, &nP );
if( !bExist )
SvUShorts::Insert( aE, nP );
return !bExist;
}
BOOL SvUShortsSort::Insert( const USHORT aE, USHORT& rP )
{
BOOL bExist = Seek_Entry( aE, &rP );
if( !bExist )
SvUShorts::Insert( aE, rP );
return !bExist;
}
void SvUShortsSort::Insert( const USHORT* pE, USHORT nL)
{
USHORT nP;
for( USHORT n = 0; n < nL; ++n )
if( ! Seek_Entry( *(pE+n), &nP ))
SvUShorts::Insert( *(pE+n), nP );
}
// remove ab Pos
void SvUShortsSort::RemoveAt( const USHORT nP, USHORT nL )
{
if( nL )
SvUShorts::Remove( nP, nL);
}
// remove ab dem Eintrag
void SvUShortsSort::Remove( const USHORT aE, USHORT nL )
{
USHORT nP;
if( nL && Seek_Entry( aE, &nP ) )
SvUShorts::Remove( nP, nL);
}
// ---------------- bytestrings -------------------------------------
// Array mit anderer Seek-Methode!
_SV_IMPL_SORTAR_ALG( SvByteStringsISort, ByteStringPtr )
void SvByteStringsISort::DeleteAndDestroy( USHORT nP, USHORT nL )
{
if( nL )
{
DBG_ASSERT( nP < nA && nP + nL <= nA, "ERR_VAR_DEL" );
for( USHORT n=nP; n < nP + nL; n++ )
delete *((ByteStringPtr*)pData+n);
SvPtrarr::Remove( nP, nL );
}
}
BOOL SvByteStringsISort::Seek_Entry( const ByteStringPtr aE, USHORT* pP ) const
{
register USHORT nO = SvByteStringsISort_SAR::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
StringCompare eCmp = (*((ByteStringPtr*)pData + nM))->
CompareIgnoreCaseToAscii( *(aE) );
if( COMPARE_EQUAL == eCmp )
{
if( pP ) *pP = nM;
return TRUE;
}
else if( COMPARE_LESS == eCmp )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return FALSE;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return FALSE;
}
// Array mit anderer Seek-Methode!
_SV_IMPL_SORTAR_ALG( SvByteStringsISortDtor, ByteStringPtr )
void SvByteStringsISortDtor::DeleteAndDestroy( USHORT nP, USHORT nL )
{
if( nL )
{
DBG_ASSERT( nP < nA && nP + nL <= nA, "ERR_VAR_DEL" );
for( USHORT n=nP; n < nP + nL; n++ )
delete *((ByteStringPtr*)pData+n);
SvPtrarr::Remove( nP, nL );
}
}
BOOL SvByteStringsISortDtor::Seek_Entry( const ByteStringPtr aE, USHORT* pP ) const
{
register USHORT nO = SvByteStringsISortDtor_SAR::Count(),
nM,
nU = 0;
if( nO > 0 )
{
nO--;
while( nU <= nO )
{
nM = nU + ( nO - nU ) / 2;
StringCompare eCmp = (*((ByteStringPtr*)pData + nM))->
CompareIgnoreCaseToAscii( *(aE) );
if( COMPARE_EQUAL == eCmp )
{
if( pP ) *pP = nM;
return TRUE;
}
else if( COMPARE_LESS == eCmp )
nU = nM + 1;
else if( nM == 0 )
{
if( pP ) *pP = nU;
return FALSE;
}
else
nO = nM - 1;
}
}
if( pP ) *pP = nU;
return FALSE;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "PhotonWaveOut.h"
static WaveOut *current = NULL;
static void playback_handler(void) {
int v = current->advance();
// manual PWM, we map value to pulse-width
if (v >= 0x80) {
v = 0xFF-v;
if (v > 0) {
pinSetFast(current->pin_n);
delayMicroseconds(v);
pinResetFast(current->pin_n);
}
} else {
if (v > 0) {
pinSetFast(current->pin_p);
delayMicroseconds(v);
pinResetFast(current->pin_p);
}
}
}
bool WaveOut::play(char *wave, unsigned int wave_len, bool loop) {
if (playing)
stop();
this->wave = wave;
this->wave_len = wave_len;
this->loop = loop;
this->wave_ix = 0;
current = this;
// for 8000 Hz this should be 125, but we cheat a bit to be able to map the samples straight
audio_clock->begin(playback_handler, 127, uSec);
this->playing = true;
return true;
}
void WaveOut::stop(void) {
if (!playing)
return;
audio_clock->end();
pinResetFast(pin_p);
pinResetFast(pin_n);
this->playing = false;
current = NULL;
}
int WaveOut::advance(void) {
int v = wave[wave_ix];
wave_ix++;
if (wave_ix >= wave_len) {
wave_ix = 0;
// TODO: do loop = false
}
return v;
}
<commit_msg>Add loop support.<commit_after>/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "PhotonWaveOut.h"
static WaveOut *current = NULL;
static void playback_handler(void) {
int v = current->advance();
// manual PWM, we map value to pulse-width
if (v >= 0x80) {
v = 0xFF-v;
if (v > 0) {
pinSetFast(current->pin_n);
delayMicroseconds(v);
pinResetFast(current->pin_n);
}
} else {
if (v > 0) {
pinSetFast(current->pin_p);
delayMicroseconds(v);
pinResetFast(current->pin_p);
}
}
}
bool WaveOut::play(char *wave, unsigned int wave_len, bool loop) {
if (playing)
stop();
this->wave = wave;
this->wave_len = wave_len;
this->loop = loop;
this->wave_ix = 0;
current = this;
// for 8000 Hz this should be 125, but we cheat a bit to be able to map the samples straight
audio_clock->begin(playback_handler, 127, uSec);
this->playing = true;
return true;
}
void WaveOut::stop(void) {
if (!playing)
return;
audio_clock->end();
pinResetFast(pin_p);
pinResetFast(pin_n);
this->playing = false;
current = NULL;
}
int WaveOut::advance(void) {
int v = wave[wave_ix];
wave_ix++;
if (wave_ix >= wave_len) {
if (loop) {
wave_ix = 0;
} else {
stop();
}
}
return v;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fmtwrapinfluenceonobjpos.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2008-03-12 12:11:56 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _FMTWRAPINFLUENCEONOBJPOS_HXX
#define _FMTWRAPINFLUENCEONOBJPOS_HXX
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _FORMAT_HXX
#include <format.hxx>
#endif
#ifndef _SFXPOOLITEM_HXX
#include <svtools/poolitem.hxx>
#endif
#ifndef _COM_SUN_STAR_TEXT_WRAPINFLUENCEONPOSITION_HPP_
#include <com/sun/star/text/WrapInfluenceOnPosition.hpp>
#endif
class SwFmtWrapInfluenceOnObjPos: public SfxPoolItem
{
private:
sal_Int16 mnWrapInfluenceOnPosition;
public:
TYPEINFO();
// --> OD 2004-10-18 #i35017# - constant name has changed
SwFmtWrapInfluenceOnObjPos(
sal_Int16 _nWrapInfluenceOnPosition =
com::sun::star::text::WrapInfluenceOnPosition::ONCE_CONCURRENT );
// <--
SwFmtWrapInfluenceOnObjPos(
const SwFmtWrapInfluenceOnObjPos& _rCpy );
~SwFmtWrapInfluenceOnObjPos();
SwFmtWrapInfluenceOnObjPos& operator=(
const SwFmtWrapInfluenceOnObjPos& _rSource );
// pure virtual methods of class <SfxPoolItem>
virtual int operator==( const SfxPoolItem& _rAttr ) const;
virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const;
virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );
// direct accessors to data
void SetWrapInfluenceOnObjPos( sal_Int16 _nWrapInfluenceOnPosition );
// --> OD 2004-10-18 #i35017# - add parameter <_bIterativeAsOnceConcurrent>
// to control, if value <ITERATIVE> has to be treated as <ONCE_CONCURRENT>
sal_Int16 GetWrapInfluenceOnObjPos(
const bool _bIterativeAsOnceConcurrent = false ) const;
// <--
};
inline const SwFmtWrapInfluenceOnObjPos& SwAttrSet::GetWrapInfluenceOnObjPos(BOOL bInP) const
{ return (const SwFmtWrapInfluenceOnObjPos&)Get( RES_WRAP_INFLUENCE_ON_OBJPOS,bInP); }
inline const SwFmtWrapInfluenceOnObjPos& SwFmt::GetWrapInfluenceOnObjPos(BOOL bInP) const
{ return aSet.GetWrapInfluenceOnObjPos(bInP); }
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.6.34); FILE MERGED 2008/04/01 15:56:13 thb 1.6.34.3: #i85898# Stripping all external header guards 2008/04/01 12:53:31 thb 1.6.34.2: #i85898# Stripping all external header guards 2008/03/31 16:52:38 rt 1.6.34.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fmtwrapinfluenceonobjpos.hxx,v $
* $Revision: 1.7 $
*
* 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 _FMTWRAPINFLUENCEONOBJPOS_HXX
#define _FMTWRAPINFLUENCEONOBJPOS_HXX
#include <hintids.hxx>
#include <format.hxx>
#include <svtools/poolitem.hxx>
#include <com/sun/star/text/WrapInfluenceOnPosition.hpp>
class SwFmtWrapInfluenceOnObjPos: public SfxPoolItem
{
private:
sal_Int16 mnWrapInfluenceOnPosition;
public:
TYPEINFO();
// --> OD 2004-10-18 #i35017# - constant name has changed
SwFmtWrapInfluenceOnObjPos(
sal_Int16 _nWrapInfluenceOnPosition =
com::sun::star::text::WrapInfluenceOnPosition::ONCE_CONCURRENT );
// <--
SwFmtWrapInfluenceOnObjPos(
const SwFmtWrapInfluenceOnObjPos& _rCpy );
~SwFmtWrapInfluenceOnObjPos();
SwFmtWrapInfluenceOnObjPos& operator=(
const SwFmtWrapInfluenceOnObjPos& _rSource );
// pure virtual methods of class <SfxPoolItem>
virtual int operator==( const SfxPoolItem& _rAttr ) const;
virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const;
virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );
// direct accessors to data
void SetWrapInfluenceOnObjPos( sal_Int16 _nWrapInfluenceOnPosition );
// --> OD 2004-10-18 #i35017# - add parameter <_bIterativeAsOnceConcurrent>
// to control, if value <ITERATIVE> has to be treated as <ONCE_CONCURRENT>
sal_Int16 GetWrapInfluenceOnObjPos(
const bool _bIterativeAsOnceConcurrent = false ) const;
// <--
};
inline const SwFmtWrapInfluenceOnObjPos& SwAttrSet::GetWrapInfluenceOnObjPos(BOOL bInP) const
{ return (const SwFmtWrapInfluenceOnObjPos&)Get( RES_WRAP_INFLUENCE_ON_OBJPOS,bInP); }
inline const SwFmtWrapInfluenceOnObjPos& SwFmt::GetWrapInfluenceOnObjPos(BOOL bInP) const
{ return aSet.GetWrapInfluenceOnObjPos(bInP); }
#endif
<|endoftext|>
|
<commit_before>/**
* \file ConvolutionFilter.cpp
*/
#include "ConvolutionFilter.h"
#include <cassert>
namespace ATK
{
template <typename DataType>
ConvolutionFilter<DataType>::ConvolutionFilter()
:Parent(1, 1), split_position(0), split_size(0)
{
}
template<typename DataType_>
void ConvolutionFilter<DataType_>::set_impulse(std::vector<DataType> impulse)
{
this->impulse = std::move(impulse);
setup();
}
template<typename DataType_>
void ConvolutionFilter<DataType_>::set_split_size(int split_size)
{
this->split_size = split_size;
setup();
}
template<typename DataType_>
void ConvolutionFilter<DataType_>::setup()
{
if(impulse.size() == 0 || split_size == 0)
{
return;
}
auto nb_splits = (impulse.size() + split_size - 1) / split_size;
partial_frequency_input.assign(nb_splits - 1, std::vector<std::complex<DataType> >(split_size * 2, 0));
// Pad with zeros so the convolution is easier created.
impulse.resize((partial_frequency_input.size() + 1) * split_size, 0);
temp_out_buffer.assign(split_size * 2, 0);
processor.set_size(split_size * 2);
// The size is twice as big than the impulse, less
partial_frequency_impulse.assign(split_size * 2 * (nb_splits - 1), 0);
for(int i = 1; i < nb_splits; ++i)
{
processor.process_forward(impulse.data() + i * split_size, partial_frequency_impulse.data() + (i - 1) * split_size * 2, split_size);
}
input_delay = split_size - 1;
Parent::setup();
}
template<typename DataType_>
void ConvolutionFilter<DataType_>::compute_convolutions() const
{
for(int i = 0; i < split_size; ++i)
{
temp_out_buffer[i] = temp_out_buffer[i + split_size];
temp_out_buffer[i + split_size] = 0;
}
std::vector<std::complex<DataType> > result(2 * split_size, 0);
const std::complex<DataType>* ATK_RESTRICT partial_frequency_impulse_ptr = partial_frequency_impulse.data();
std::complex<DataType>* ATK_RESTRICT result_ptr = result.data();
// offset in the impulse frequencies
int64_t offset = 0;
for(const auto& buffer: partial_frequency_input)
{
const std::complex<DataType>* ATK_RESTRICT buffer_ptr = buffer.data();
// Add the frequency result of this partial FFT
for(int64_t i = 0; i < 2*split_size; ++i)
{
result_ptr[i] += buffer_ptr[i] * partial_frequency_impulse_ptr[i + offset];
}
offset += 2 * split_size;
}
std::vector<DataType> ifft_result(2*split_size, 0);
processor.process_backward(result.data(), ifft_result.data(), 2*split_size);
for(int i = 0; i < 2*split_size; ++i)
{
temp_out_buffer[i] += ifft_result[i] * split_size * 2;
}
}
template<typename DataType_>
void ConvolutionFilter<DataType_>::process_new_chunk(int64_t position) const
{
if(partial_frequency_input.empty())
return;
partial_frequency_input.pop_back();
std::vector<std::complex<double> > chunk(2 * split_size);
processor.process_forward(converted_inputs[0] + position - split_size, chunk.data(), split_size);
partial_frequency_input.push_front(std::move(chunk));
compute_convolutions();
}
template<typename DataType_>
void ConvolutionFilter<DataType_>::process_impulse_beginning(int64_t processed_size, int64_t size_to_process) const
{
const DataType* ATK_RESTRICT input = converted_inputs[0];
DataType* ATK_RESTRICT output = outputs[0];
for(int64_t i = 0; i < size_to_process; ++i)
{
DataType tempout = temp_out_buffer[split_position + i];
for(int j = 0; j < input_delay + 1; ++j)
{
tempout += impulse[j] * input[processed_size + i - j];
}
output[processed_size + i] = tempout;
}
}
template<typename DataType_>
void ConvolutionFilter<DataType_>::process_impl(int64_t size) const
{
assert(input_sampling_rate == output_sampling_rate);
assert(nb_input_ports == nb_output_ports);
int processed_size = 0;
do
{
// We can only process split_size elements at a time, but if we already have some elements in the buffer,
// we need to take them into account.
int64_t size_to_process = std::min(split_size - split_position, size - processed_size);
process_impulse_beginning(processed_size, size_to_process);
split_position += size_to_process;
processed_size += size_to_process;
if(split_position == split_size)
{
process_new_chunk(processed_size);
split_position = 0;
}
}while(processed_size != size);
}
template class ConvolutionFilter<double>;
}
<commit_msg>Optimized the impulse processing as well as the complex FMA<commit_after>/**
* \file ConvolutionFilter.cpp
*/
#include "ConvolutionFilter.h"
#include <cassert>
namespace ATK
{
template <typename DataType>
ConvolutionFilter<DataType>::ConvolutionFilter()
:Parent(1, 1), split_position(0), split_size(0)
{
}
template<typename DataType_>
void ConvolutionFilter<DataType_>::set_impulse(std::vector<DataType> impulse)
{
this->impulse = std::move(impulse);
setup();
}
template<typename DataType_>
void ConvolutionFilter<DataType_>::set_split_size(int split_size)
{
this->split_size = split_size;
setup();
}
template<typename DataType_>
void ConvolutionFilter<DataType_>::setup()
{
if(impulse.size() == 0 || split_size == 0)
{
return;
}
auto nb_splits = (impulse.size() + split_size - 1) / split_size;
partial_frequency_input.assign(nb_splits - 1, std::vector<std::complex<DataType> >(split_size * 2, 0));
// Pad with zeros so the convolution is easier created.
impulse.resize((partial_frequency_input.size() + 1) * split_size, 0);
temp_out_buffer.assign(split_size * 2, 0);
processor.set_size(split_size * 2);
// The size is twice as big than the impulse, less
partial_frequency_impulse.assign(split_size * 2 * (nb_splits - 1), 0);
for(int i = 1; i < nb_splits; ++i)
{
processor.process_forward(impulse.data() + i * split_size, partial_frequency_impulse.data() + (i - 1) * split_size * 2, split_size);
}
input_delay = split_size - 1;
Parent::setup();
}
template<typename DataType_>
void ConvolutionFilter<DataType_>::compute_convolutions() const
{
for(int i = 0; i < split_size; ++i)
{
temp_out_buffer[i] = temp_out_buffer[i + split_size];
temp_out_buffer[i + split_size] = 0;
}
std::vector<std::complex<DataType> > result(2 * split_size, 0);
const std::complex<DataType>* ATK_RESTRICT partial_frequency_impulse_ptr = partial_frequency_impulse.data();
std::complex<DataType>* ATK_RESTRICT result_ptr = result.data();
// offset in the impulse frequencies
int64_t offset = 0;
for(const auto& buffer: partial_frequency_input)
{
const std::complex<DataType>* ATK_RESTRICT buffer_ptr = buffer.data();
// Add the frequency result of this partial FFT
for(int64_t i = 0; i < 2*split_size; ++i)
{
DataType br = buffer_ptr[i].real();
DataType bi = buffer_ptr[i].imag();
DataType pr = partial_frequency_impulse_ptr[i + offset].real();
DataType pi = partial_frequency_impulse_ptr[i + offset].imag();
result_ptr[i] += std::complex<DataType>(br*pr-bi*pi, br*pi+pr*bi);
}
offset += 2 * split_size;
}
std::vector<DataType> ifft_result(2*split_size, 0);
processor.process_backward(result.data(), ifft_result.data(), 2*split_size);
for(int i = 0; i < 2*split_size; ++i)
{
temp_out_buffer[i] += ifft_result[i] * split_size * 2;
}
}
template<typename DataType_>
void ConvolutionFilter<DataType_>::process_new_chunk(int64_t position) const
{
if(partial_frequency_input.empty())
return;
partial_frequency_input.pop_back();
std::vector<std::complex<double> > chunk(2 * split_size);
processor.process_forward(converted_inputs[0] + position - split_size, chunk.data(), split_size);
partial_frequency_input.push_front(std::move(chunk));
compute_convolutions();
}
template<typename DataType_>
void ConvolutionFilter<DataType_>::process_impulse_beginning(int64_t processed_size, int64_t size_to_process) const
{
const DataType* ATK_RESTRICT input = converted_inputs[0] + processed_size;
const DataType* ATK_RESTRICT impulse_ptr = impulse.data();
DataType* ATK_RESTRICT output = outputs[0] + processed_size;
for(int64_t i = 0; i < size_to_process; ++i)
{
output[i] = temp_out_buffer[split_position + i];
}
for(int j = 0; j < input_delay + 1; ++j)
{
for(int64_t i = 0; i < size_to_process; ++i)
{
output[i] += impulse_ptr[j] * input[i - j];
}
}
}
template<typename DataType_>
void ConvolutionFilter<DataType_>::process_impl(int64_t size) const
{
assert(input_sampling_rate == output_sampling_rate);
assert(nb_input_ports == nb_output_ports);
int processed_size = 0;
do
{
// We can only process split_size elements at a time, but if we already have some elements in the buffer,
// we need to take them into account.
int64_t size_to_process = std::min(split_size - split_position, size - processed_size);
process_impulse_beginning(processed_size, size_to_process);
split_position += size_to_process;
processed_size += size_to_process;
if(split_position == split_size)
{
process_new_chunk(processed_size);
split_position = 0;
}
}while(processed_size != size);
}
template class ConvolutionFilter<double>;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: txatbase.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-09-09 05:14:31 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#pragma hdrstop
#ifndef _SFXITEMPOOL_HXX
#include <svtools/itempool.hxx>
#endif
#ifndef _TXATBASE_HXX
#include <txatbase.hxx>
#endif
SwTxtAttr::SwTxtAttr( const SfxPoolItem& rAttr, xub_StrLen nStt )
: pAttr( &rAttr ), nStart( nStt )
{
bDontExpand = bLockExpandFlag = bDontMergeAttr = bDontMoveAttr =
bCharFmtAttr = bOverlapAllowedAttr = bPriorityAttr =
bDontExpandStart = FALSE;
}
SwTxtAttr::~SwTxtAttr( )
{
}
xub_StrLen* SwTxtAttr::GetEnd()
{
return 0;
}
// RemoveFromPool muss immer vorm DTOR Aufruf erfolgen!!
// Meldet sein Attribut beim Pool ab
void SwTxtAttr::RemoveFromPool( SfxItemPool& rPool )
{
rPool.Remove( GetAttr() );
pAttr = 0;
}
int SwTxtAttr::operator==( const SwTxtAttr& rAttr ) const
{
return GetAttr() == rAttr.GetAttr();
}
SwTxtAttrEnd::SwTxtAttrEnd( const SfxPoolItem& rAttr, xub_StrLen nS,
xub_StrLen nE )
: SwTxtAttr( rAttr, nS ), nEnd( nE )
{
}
xub_StrLen* SwTxtAttrEnd::GetEnd()
{
return &nEnd;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.8.476); FILE MERGED 2006/09/01 17:52:13 kaib 1.8.476.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: txatbase.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2006-09-16 21:47:32 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifndef _SFXITEMPOOL_HXX
#include <svtools/itempool.hxx>
#endif
#ifndef _TXATBASE_HXX
#include <txatbase.hxx>
#endif
SwTxtAttr::SwTxtAttr( const SfxPoolItem& rAttr, xub_StrLen nStt )
: pAttr( &rAttr ), nStart( nStt )
{
bDontExpand = bLockExpandFlag = bDontMergeAttr = bDontMoveAttr =
bCharFmtAttr = bOverlapAllowedAttr = bPriorityAttr =
bDontExpandStart = FALSE;
}
SwTxtAttr::~SwTxtAttr( )
{
}
xub_StrLen* SwTxtAttr::GetEnd()
{
return 0;
}
// RemoveFromPool muss immer vorm DTOR Aufruf erfolgen!!
// Meldet sein Attribut beim Pool ab
void SwTxtAttr::RemoveFromPool( SfxItemPool& rPool )
{
rPool.Remove( GetAttr() );
pAttr = 0;
}
int SwTxtAttr::operator==( const SwTxtAttr& rAttr ) const
{
return GetAttr() == rAttr.GetAttr();
}
SwTxtAttrEnd::SwTxtAttrEnd( const SfxPoolItem& rAttr, xub_StrLen nS,
xub_StrLen nE )
: SwTxtAttr( rAttr, nS ), nEnd( nE )
{
}
xub_StrLen* SwTxtAttrEnd::GetEnd()
{
return &nEnd;
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <hintids.hxx>
#include <com/sun/star/i18n/ScriptType.hpp>
#include <tools/string.hxx>
#include <editeng/langitem.hxx>
#include <txatritr.hxx>
#include <fchrfmt.hxx>
#include <charfmt.hxx>
#include <breakit.hxx>
#include <ndtxt.hxx>
#include <txatbase.hxx>
using namespace ::com::sun::star::i18n;
SwScriptIterator::SwScriptIterator( const String& rStr, xub_StrLen nStt, bool bFrwrd )
: rText( rStr ),
nChgPos( rStr.Len() ),
nCurScript( ScriptType::WEAK ),
bForward( bFrwrd )
{
if( pBreakIt->GetBreakIter().is() )
{
if ( ! bFrwrd && nStt )
--nStt;
xub_StrLen nPos = nStt;
nCurScript = pBreakIt->GetBreakIter()->getScriptType( rText, nPos );
if( ScriptType::WEAK == nCurScript )
{
if( nPos )
{
nPos = (xub_StrLen)pBreakIt->GetBreakIter()->beginOfScript(
rText, nPos, nCurScript );
if( nPos && nPos < rText.Len() )
{
nStt = --nPos;
nCurScript = pBreakIt->GetBreakIter()->getScriptType( rText,nPos);
}
}
}
nChgPos = bForward ?
(xub_StrLen)pBreakIt->GetBreakIter()->endOfScript( rText, nStt, nCurScript ) :
(xub_StrLen)pBreakIt->GetBreakIter()->beginOfScript( rText, nStt, nCurScript );
}
}
bool SwScriptIterator::Next()
{
bool bRet = false;
if( pBreakIt->GetBreakIter().is() )
{
if ( bForward && nChgPos < rText.Len() )
{
nCurScript = pBreakIt->GetBreakIter()->getScriptType( rText, nChgPos );
nChgPos = (xub_StrLen)pBreakIt->GetBreakIter()->endOfScript(
rText, nChgPos, nCurScript );
bRet = true;
}
else if ( ! bForward && nChgPos )
{
--nChgPos;
nCurScript = pBreakIt->GetBreakIter()->getScriptType( rText, nChgPos );
nChgPos = (xub_StrLen)pBreakIt->GetBreakIter()->beginOfScript(
rText, nChgPos, nCurScript );
bRet = true;
}
}
else
nChgPos = rText.Len();
return bRet;
}
// --------------------------------------------------------------------
SwTxtAttrIterator::SwTxtAttrIterator( const SwTxtNode& rTNd, sal_uInt16 nWhchId,
xub_StrLen nStt,
bool bUseGetWhichOfScript )
: aSIter( rTNd.GetTxt(), nStt ), rTxtNd( rTNd ),
pParaItem( 0 ), nChgPos( nStt ), nAttrPos( 0 ), nWhichId( nWhchId ),
bIsUseGetWhichOfScript( bUseGetWhichOfScript )
{
SearchNextChg();
}
bool SwTxtAttrIterator::Next()
{
bool bRet = false;
if( nChgPos < aSIter.GetText().Len() )
{
bRet = true;
if( !aStack.empty() )
{
do {
const SwTxtAttr* pHt = aStack.front();
sal_uInt16 nEndPos = *pHt->GetEnd();
if( nChgPos >= nEndPos )
aStack.pop_front();
else
break;
} while( !aStack.empty() );
}
if( !aStack.empty() )
{
sal_uInt16 nSavePos = nAttrPos;
SearchNextChg();
if( !aStack.empty() )
{
const SwTxtAttr* pHt = aStack.front();
sal_uInt16 nEndPos = *pHt->GetEnd();
if( nChgPos >= nEndPos )
{
nChgPos = nEndPos;
nAttrPos = nSavePos;
if( RES_TXTATR_CHARFMT == pHt->Which() )
{
sal_uInt16 nWId = bIsUseGetWhichOfScript ?
GetWhichOfScript( nWhichId,
aSIter.GetCurrScript() ) : nWhichId;
pCurItem = &pHt->GetCharFmt().GetCharFmt()->GetFmtAttr(nWId);
}
else
pCurItem = &pHt->GetAttr();
aStack.pop_front();
}
}
}
else
SearchNextChg();
}
return bRet;
}
void SwTxtAttrIterator::AddToStack( const SwTxtAttr& rAttr )
{
sal_uInt16 nIns = 0, nEndPos = *rAttr.GetEnd();
for( ; nIns < aStack.size(); ++nIns )
if( *aStack[ nIns ]->GetEnd() > nEndPos )
break;
aStack.insert( aStack.begin() + nIns, &rAttr );
}
void SwTxtAttrIterator::SearchNextChg()
{
sal_uInt16 nWh = 0;
if( nChgPos == aSIter.GetScriptChgPos() )
{
aSIter.Next();
pParaItem = 0;
nAttrPos = 0; // must be restart at the beginning, because
// some attributes can start before or inside
// the current scripttype!
aStack.clear();
}
if( !pParaItem )
{
nWh = bIsUseGetWhichOfScript ?
GetWhichOfScript( nWhichId,
aSIter.GetCurrScript() ) : nWhichId;
pParaItem = &rTxtNd.GetSwAttrSet().Get( nWh );
}
xub_StrLen nStt = nChgPos;
nChgPos = aSIter.GetScriptChgPos();
pCurItem = pParaItem;
const SwpHints* pHts = rTxtNd.GetpSwpHints();
if( pHts )
{
if( !nWh )
{
nWh = bIsUseGetWhichOfScript ?
GetWhichOfScript( nWhichId,
aSIter.GetCurrScript() ) : nWhichId;
}
const SfxPoolItem* pItem = 0;
for( ; nAttrPos < pHts->Count(); ++nAttrPos )
{
const SwTxtAttr* pHt = (*pHts)[ nAttrPos ];
const sal_uInt16* pEnd = pHt->GetEnd();
const sal_uInt16 nHtStt = *pHt->GetStart();
if( nHtStt < nStt && ( !pEnd || *pEnd <= nStt ))
continue;
if( nHtStt >= nChgPos )
break;
pItem = CharFmt::GetItem( *pHt, nWh );
if ( pItem )
{
if( nHtStt > nStt )
{
if( nChgPos > nHtStt )
nChgPos = nHtStt;
break;
}
AddToStack( *pHt );
pCurItem = pItem;
if( *pEnd < nChgPos )
nChgPos = *pEnd;
}
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>remove unnecessary #include<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <txatritr.hxx>
#include <com/sun/star/i18n/ScriptType.hpp>
#include <tools/string.hxx>
#include <fchrfmt.hxx>
#include <charfmt.hxx>
#include <breakit.hxx>
#include <ndtxt.hxx>
#include <txatbase.hxx>
using namespace ::com::sun::star::i18n;
SwScriptIterator::SwScriptIterator( const String& rStr, xub_StrLen nStt, bool bFrwrd )
: rText( rStr ),
nChgPos( rStr.Len() ),
nCurScript( ScriptType::WEAK ),
bForward( bFrwrd )
{
if( pBreakIt->GetBreakIter().is() )
{
if ( ! bFrwrd && nStt )
--nStt;
xub_StrLen nPos = nStt;
nCurScript = pBreakIt->GetBreakIter()->getScriptType( rText, nPos );
if( ScriptType::WEAK == nCurScript )
{
if( nPos )
{
nPos = (xub_StrLen)pBreakIt->GetBreakIter()->beginOfScript(
rText, nPos, nCurScript );
if( nPos && nPos < rText.Len() )
{
nStt = --nPos;
nCurScript = pBreakIt->GetBreakIter()->getScriptType( rText,nPos);
}
}
}
nChgPos = bForward ?
(xub_StrLen)pBreakIt->GetBreakIter()->endOfScript( rText, nStt, nCurScript ) :
(xub_StrLen)pBreakIt->GetBreakIter()->beginOfScript( rText, nStt, nCurScript );
}
}
bool SwScriptIterator::Next()
{
bool bRet = false;
if( pBreakIt->GetBreakIter().is() )
{
if ( bForward && nChgPos < rText.Len() )
{
nCurScript = pBreakIt->GetBreakIter()->getScriptType( rText, nChgPos );
nChgPos = (xub_StrLen)pBreakIt->GetBreakIter()->endOfScript(
rText, nChgPos, nCurScript );
bRet = true;
}
else if ( ! bForward && nChgPos )
{
--nChgPos;
nCurScript = pBreakIt->GetBreakIter()->getScriptType( rText, nChgPos );
nChgPos = (xub_StrLen)pBreakIt->GetBreakIter()->beginOfScript(
rText, nChgPos, nCurScript );
bRet = true;
}
}
else
nChgPos = rText.Len();
return bRet;
}
// --------------------------------------------------------------------
SwTxtAttrIterator::SwTxtAttrIterator( const SwTxtNode& rTNd, sal_uInt16 nWhchId,
xub_StrLen nStt,
bool bUseGetWhichOfScript )
: aSIter( rTNd.GetTxt(), nStt ), rTxtNd( rTNd ),
pParaItem( 0 ), nChgPos( nStt ), nAttrPos( 0 ), nWhichId( nWhchId ),
bIsUseGetWhichOfScript( bUseGetWhichOfScript )
{
SearchNextChg();
}
bool SwTxtAttrIterator::Next()
{
bool bRet = false;
if( nChgPos < aSIter.GetText().Len() )
{
bRet = true;
if( !aStack.empty() )
{
do {
const SwTxtAttr* pHt = aStack.front();
sal_uInt16 nEndPos = *pHt->GetEnd();
if( nChgPos >= nEndPos )
aStack.pop_front();
else
break;
} while( !aStack.empty() );
}
if( !aStack.empty() )
{
sal_uInt16 nSavePos = nAttrPos;
SearchNextChg();
if( !aStack.empty() )
{
const SwTxtAttr* pHt = aStack.front();
sal_uInt16 nEndPos = *pHt->GetEnd();
if( nChgPos >= nEndPos )
{
nChgPos = nEndPos;
nAttrPos = nSavePos;
if( RES_TXTATR_CHARFMT == pHt->Which() )
{
sal_uInt16 nWId = bIsUseGetWhichOfScript ?
GetWhichOfScript( nWhichId,
aSIter.GetCurrScript() ) : nWhichId;
pCurItem = &pHt->GetCharFmt().GetCharFmt()->GetFmtAttr(nWId);
}
else
pCurItem = &pHt->GetAttr();
aStack.pop_front();
}
}
}
else
SearchNextChg();
}
return bRet;
}
void SwTxtAttrIterator::AddToStack( const SwTxtAttr& rAttr )
{
sal_uInt16 nIns = 0, nEndPos = *rAttr.GetEnd();
for( ; nIns < aStack.size(); ++nIns )
if( *aStack[ nIns ]->GetEnd() > nEndPos )
break;
aStack.insert( aStack.begin() + nIns, &rAttr );
}
void SwTxtAttrIterator::SearchNextChg()
{
sal_uInt16 nWh = 0;
if( nChgPos == aSIter.GetScriptChgPos() )
{
aSIter.Next();
pParaItem = 0;
nAttrPos = 0; // must be restart at the beginning, because
// some attributes can start before or inside
// the current scripttype!
aStack.clear();
}
if( !pParaItem )
{
nWh = bIsUseGetWhichOfScript ?
GetWhichOfScript( nWhichId,
aSIter.GetCurrScript() ) : nWhichId;
pParaItem = &rTxtNd.GetSwAttrSet().Get( nWh );
}
xub_StrLen nStt = nChgPos;
nChgPos = aSIter.GetScriptChgPos();
pCurItem = pParaItem;
const SwpHints* pHts = rTxtNd.GetpSwpHints();
if( pHts )
{
if( !nWh )
{
nWh = bIsUseGetWhichOfScript ?
GetWhichOfScript( nWhichId,
aSIter.GetCurrScript() ) : nWhichId;
}
const SfxPoolItem* pItem = 0;
for( ; nAttrPos < pHts->Count(); ++nAttrPos )
{
const SwTxtAttr* pHt = (*pHts)[ nAttrPos ];
const sal_uInt16* pEnd = pHt->GetEnd();
const sal_uInt16 nHtStt = *pHt->GetStart();
if( nHtStt < nStt && ( !pEnd || *pEnd <= nStt ))
continue;
if( nHtStt >= nChgPos )
break;
pItem = CharFmt::GetItem( *pHt, nWh );
if ( pItem )
{
if( nHtStt > nStt )
{
if( nChgPos > nHtStt )
nChgPos = nHtStt;
break;
}
AddToStack( *pHt );
pCurItem = pItem;
if( *pEnd < nChgPos )
nChgPos = *pEnd;
}
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>/* database.cpp
*
* Copyright (C) 2012 Matthias Klumpp
*
* Licensed under the GNU General Public License Version 3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "database.hpp"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
Database::Database () :
m_rwXapianDB(0)
{
}
Database::~Database ()
{
if (m_rwXapianDB) {
delete m_rwXapianDB;
}
}
bool Database::init (const gchar *dbPath)
{
m_dbPath = dbPath;
try {
m_rwXapianDB = new Xapian::WritableDatabase (m_dbPath,
Xapian::DB_CREATE_OR_OPEN);
} catch (const Xapian::Error &error) {
cout << "ERROR!" << endl;
g_warning ("Exception: %s", error.get_msg ().c_str ());
return false;
}
return true;
}
bool Database::rebuild (GArray *apps)
{
string old_path = m_dbPath + "_old";
string rebuild_path = m_dbPath + "_rb";
// Create the rebuild directory
if (!uai_utils_touch_dir (rebuild_path.c_str ()))
return false;
// check if old unrequired version of db still exists on filesystem
if (g_file_test (old_path.c_str (), G_FILE_TEST_EXISTS)) {
g_warning ("Existing xapian old db was not previously cleaned: '%s'.", old_path.c_str ());
uai_utils_delete_dir_recursive (old_path.c_str ());
}
// check if old unrequired version of db still exists on filesystem
if (g_file_test (rebuild_path.c_str (), G_FILE_TEST_EXISTS)) {
cout << "Removing old rebuild-dir from previous database rebuild." << endl;
uai_utils_delete_dir_recursive (rebuild_path.c_str ());
}
Xapian::WritableDatabase db (rebuild_path, Xapian::DB_CREATE_OR_OVERWRITE);
Xapian::TermGenerator term_generator;
term_generator.set_database(db);
try {
/* this tests if we have spelling suggestions (there must be
* a better way?!?) - this is needed as inmemory does not have
* spelling corrections, but it allows setting the flag and will
* raise a exception much later
*/
db.add_spelling("test");
db.remove_spelling("test");
/* this enables the flag for it (we only reach this line if
* the db supports spelling suggestions)
*/
term_generator.set_flags(Xapian::TermGenerator::FLAG_SPELLING);
} catch (const Xapian::UnimplementedError &error) {
// Ignore
}
for (guint i=0; i < apps->len; i++) {
UaiAppInfo *app = g_array_index (apps, UaiAppInfo*, i);
Xapian::Document doc;
cout << "Adding application: " << uai_app_info_to_string (app) << endl;
doc.set_data (uai_app_info_get_name (app));
doc.add_value (APPNAME_UNTRANSLATED, uai_app_info_get_name_original (app));
doc.add_value (PKGNAME, uai_app_info_get_pkgname (app));
doc.add_value (DESKTOP_FILE, uai_app_info_get_desktop_file (app));
doc.add_value (SUPPORT_SITE_URL, uai_app_info_get_url (app));
doc.add_value (ICON, uai_app_info_get_icon (app));
doc.add_value (CATEGORIES, uai_app_info_get_categories (app));
doc.add_value (SUMMARY, uai_app_info_get_summary (app));
doc.add_value (SC_DESCRIPTION, uai_app_info_get_description (app));
// TODO: Register more values and add TERMs
term_generator.set_document (doc);
// TODO: Register terms
db.add_document (doc);
}
db.set_metadata("db-schema-version", DB_SCHEMA_VERSION);
db.flush ();
return true;
}
bool Database::addApplication (UaiAppInfo *app)
{
// TODO
return false;
}
<commit_msg>Move Xapian DB to correct path<commit_after>/* database.cpp
*
* Copyright (C) 2012 Matthias Klumpp
*
* Licensed under the GNU General Public License Version 3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "database.hpp"
#include <iostream>
#include <string>
#include <vector>
#include <glib/gstdio.h>
using namespace std;
Database::Database () :
m_rwXapianDB(0)
{
}
Database::~Database ()
{
if (m_rwXapianDB) {
delete m_rwXapianDB;
}
}
bool Database::init (const gchar *dbPath)
{
m_dbPath = dbPath;
try {
m_rwXapianDB = new Xapian::WritableDatabase (m_dbPath,
Xapian::DB_CREATE_OR_OPEN);
} catch (const Xapian::Error &error) {
cout << "ERROR!" << endl;
g_warning ("Exception: %s", error.get_msg ().c_str ());
return false;
}
return true;
}
bool Database::rebuild (GArray *apps)
{
string old_path = m_dbPath + "_old";
string rebuild_path = m_dbPath + "_rb";
// Create the rebuild directory
if (!uai_utils_touch_dir (rebuild_path.c_str ()))
return false;
// check if old unrequired version of db still exists on filesystem
if (g_file_test (old_path.c_str (), G_FILE_TEST_EXISTS)) {
g_warning ("Existing xapian old db was not previously cleaned: '%s'.", old_path.c_str ());
uai_utils_delete_dir_recursive (old_path.c_str ());
}
// check if old unrequired version of db still exists on filesystem
if (g_file_test (rebuild_path.c_str (), G_FILE_TEST_EXISTS)) {
cout << "Removing old rebuild-dir from previous database rebuild." << endl;
uai_utils_delete_dir_recursive (rebuild_path.c_str ());
}
Xapian::WritableDatabase db (rebuild_path, Xapian::DB_CREATE_OR_OVERWRITE);
Xapian::TermGenerator term_generator;
term_generator.set_database(db);
try {
/* this tests if we have spelling suggestions (there must be
* a better way?!?) - this is needed as inmemory does not have
* spelling corrections, but it allows setting the flag and will
* raise a exception much later
*/
db.add_spelling("test");
db.remove_spelling("test");
/* this enables the flag for it (we only reach this line if
* the db supports spelling suggestions)
*/
term_generator.set_flags(Xapian::TermGenerator::FLAG_SPELLING);
} catch (const Xapian::UnimplementedError &error) {
// Ignore
}
for (guint i=0; i < apps->len; i++) {
UaiAppInfo *app = g_array_index (apps, UaiAppInfo*, i);
Xapian::Document doc;
cout << "Adding application: " << uai_app_info_to_string (app) << endl;
doc.set_data (uai_app_info_get_name (app));
doc.add_value (APPNAME_UNTRANSLATED, uai_app_info_get_name_original (app));
doc.add_value (PKGNAME, uai_app_info_get_pkgname (app));
doc.add_value (DESKTOP_FILE, uai_app_info_get_desktop_file (app));
doc.add_value (SUPPORT_SITE_URL, uai_app_info_get_url (app));
doc.add_value (ICON, uai_app_info_get_icon (app));
doc.add_value (CATEGORIES, uai_app_info_get_categories (app));
doc.add_value (SUMMARY, uai_app_info_get_summary (app));
doc.add_value (SC_DESCRIPTION, uai_app_info_get_description (app));
// TODO: Register more values and add TERMs
term_generator.set_document (doc);
// TODO: Register terms
db.add_document (doc);
}
db.set_metadata("db-schema-version", DB_SCHEMA_VERSION);
db.flush ();
if (g_rename (m_dbPath.c_str (), old_path.c_str ()) < 0) {
g_critical ("Error while moving old database out of the way.");
return false;
}
if (g_rename (rebuild_path.c_str (), m_dbPath.c_str ()) < 0) {
g_critical ("Error while moving rebuilt database.");
return false;
}
uai_utils_delete_dir_recursive (old_path.c_str ());
return true;
}
bool Database::addApplication (UaiAppInfo *app)
{
// TODO
return false;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
*
* Copyright RTK Consortium
*
* 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 "rtkfdk_ggo.h"
#include "rtkGgoFunctions.h"
#include "rtkConfiguration.h"
#include "rtkThreeDCircularProjectionGeometryXMLFile.h"
#include "rtkDisplacedDetectorImageFilter.h"
#include "rtkParkerShortScanImageFilter.h"
#include "rtkFDKConeBeamReconstructionFilter.h"
#ifdef RTK_USE_CUDA
# include "rtkCudaFDKConeBeamReconstructionFilter.h"
#endif
#ifdef RTK_USE_OPENCL
# include "rtkOpenCLFDKConeBeamReconstructionFilter.h"
#endif
#include "rtkFDKWarpBackProjectionImageFilter.h"
#include "rtkCyclicDeformationImageFilter.h"
#include <itkStreamingImageFilter.h>
#include <itkImageFileWriter.h>
int main(int argc, char * argv[])
{
GGO(rtkfdk, args_info);
typedef float OutputPixelType;
const unsigned int Dimension = 3;
typedef itk::Image< OutputPixelType, Dimension > CPUOutputImageType;
#ifdef RTK_USE_CUDA
typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType;
#else
typedef CPUOutputImageType OutputImageType;
#endif
// Projections reader
typedef rtk::ProjectionsReader< OutputImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
rtk::SetProjectionsReaderFromGgo<ReaderType, args_info_rtkfdk>(reader, args_info);
itk::TimeProbe readerProbe;
if(!args_info.lowmem_flag)
{
if(args_info.verbose_flag)
std::cout << "Reading... " << std::flush;
readerProbe.Start();
TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->Update() )
readerProbe.Stop();
if(args_info.verbose_flag)
std::cout << "It took " << readerProbe.GetMean() << ' ' << readerProbe.GetUnit() << std::endl;
}
// Geometry
if(args_info.verbose_flag)
std::cout << "Reading geometry information from "
<< args_info.geometry_arg
<< "..."
<< std::endl;
rtk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geometryReader;
geometryReader = rtk::ThreeDCircularProjectionGeometryXMLFileReader::New();
geometryReader->SetFilename(args_info.geometry_arg);
TRY_AND_EXIT_ON_ITK_EXCEPTION( geometryReader->GenerateOutputInformation() )
// Displaced detector weighting
typedef rtk::DisplacedDetectorImageFilter< OutputImageType > DDFType;
DDFType::Pointer ddf = DDFType::New();
ddf->SetInput( reader->GetOutput() );
ddf->SetGeometry( geometryReader->GetOutputObject() );
// Short scan image filter
typedef rtk::ParkerShortScanImageFilter< OutputImageType > PSSFType;
PSSFType::Pointer pssf = PSSFType::New();
pssf->SetInput( ddf->GetOutput() );
pssf->SetGeometry( geometryReader->GetOutputObject() );
pssf->InPlaceOff();
// Create reconstructed image
typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;
ConstantImageSourceType::Pointer constantImageSource = ConstantImageSourceType::New();
rtk::SetConstantImageSourceFromGgo<ConstantImageSourceType, args_info_rtkfdk>(constantImageSource, args_info);
// Motion-compensated objects for the compensation of a cyclic deformation.
// Although these will only be used if the command line options for motion
// compensation are set, we still create the object before hand to avoid auto
// destruction.
typedef itk::Vector<float,3> DVFPixelType;
typedef itk::Image< DVFPixelType, 3 > DVFImageType;
typedef rtk::CyclicDeformationImageFilter< DVFImageType > DeformationType;
typedef itk::ImageFileReader<DeformationType::InputImageType> DVFReaderType;
DVFReaderType::Pointer dvfReader = DVFReaderType::New();
DeformationType::Pointer def = DeformationType::New();
def->SetInput(dvfReader->GetOutput());
typedef rtk::FDKWarpBackProjectionImageFilter<OutputImageType, OutputImageType, DeformationType> WarpBPType;
WarpBPType::Pointer bp = WarpBPType::New();
bp->SetDeformation(def);
bp->SetGeometry( geometryReader->GetOutputObject() );
// This macro sets options for fdk filter which I can not see how to do better
// because TFFTPrecision is not the same, e.g. for CPU and CUDA (SR)
#define SET_FELDKAMP_OPTIONS(f) \
f->SetInput( 0, constantImageSource->GetOutput() ); \
f->SetInput( 1, pssf->GetOutput() ); \
f->SetGeometry( geometryReader->GetOutputObject() ); \
f->GetRampFilter()->SetTruncationCorrection(args_info.pad_arg); \
f->GetRampFilter()->SetHannCutFrequency(args_info.hann_arg); \
f->GetRampFilter()->SetHannCutFrequencyY(args_info.hannY_arg); \
f->SetProjectionSubsetSize(args_info.subsetsize_arg)
// FDK reconstruction filtering
typedef rtk::FDKConeBeamReconstructionFilter< OutputImageType > FDKCPUType;
FDKCPUType::Pointer feldkamp = FDKCPUType::New();
#ifdef RTK_USE_OPENCL
typedef rtk::OpenCLFDKConeBeamReconstructionFilter FDKOPENCLType;
FDKOPENCLType::Pointer feldkampOCL = FDKOPENCLType::New();
#endif
#ifdef RTK_USE_CUDA
typedef rtk::CudaFDKConeBeamReconstructionFilter FDKCUDAType;
FDKCUDAType::Pointer feldkampCUDA = FDKCUDAType::New();
#endif
itk::Image< OutputPixelType, Dimension > *pfeldkamp = NULL;
if(!strcmp(args_info.hardware_arg, "cpu") )
{
typedef rtk::FDKConeBeamReconstructionFilter< OutputImageType > FDKCPUType;
feldkamp = FDKCPUType::New();
SET_FELDKAMP_OPTIONS( feldkamp );
// Motion compensated CBCT settings
if(args_info.signal_given && args_info.dvf_given)
{
dvfReader->SetFileName(args_info.dvf_arg);
def->SetSignalFilename(args_info.signal_arg);
feldkamp->SetBackProjectionFilter( bp.GetPointer() );
}
pfeldkamp = feldkamp->GetOutput();
}
else if(!strcmp(args_info.hardware_arg, "cuda") )
{
#ifdef RTK_USE_CUDA
SET_FELDKAMP_OPTIONS( feldkampCUDA );
pfeldkamp = feldkampCUDA->GetOutput();
#else
std::cerr << "The program has not been compiled with cuda option" << std::endl;
return EXIT_FAILURE;
#endif
}
else if(!strcmp(args_info.hardware_arg, "opencl") )
{
#ifdef RTK_USE_OPENCL
SET_FELDKAMP_OPTIONS( feldkampOCL );
pfeldkamp = feldkampOCL->GetOutput();
#else
std::cerr << "The program has not been compiled with opencl option" << std::endl;
return EXIT_FAILURE;
#endif
}
// Streaming depending on streaming capability of writer
typedef itk::StreamingImageFilter<CPUOutputImageType, CPUOutputImageType> StreamerType;
StreamerType::Pointer streamerBP = StreamerType::New();
streamerBP->SetInput( pfeldkamp );
streamerBP->SetNumberOfStreamDivisions( args_info.divisions_arg );
// Write
typedef itk::ImageFileWriter<CPUOutputImageType> WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( args_info.output_arg );
writer->SetInput( streamerBP->GetOutput() );
if(args_info.verbose_flag)
std::cout << "Reconstructing and writing... " << std::flush;
itk::TimeProbe writerProbe;
writerProbe.Start();
TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() );
writerProbe.Stop();
if(args_info.verbose_flag)
{
std::cout << "It took " << writerProbe.GetMean() << ' ' << readerProbe.GetUnit() << std::endl;
if(!strcmp(args_info.hardware_arg, "cpu") )
feldkamp->PrintTiming(std::cout);
#ifdef RTK_USE_CUDA
else if(!strcmp(args_info.hardware_arg, "cuda") )
feldkampCUDA->PrintTiming(std::cout);
#endif
#ifdef RTK_USE_OPENCL
else if(!strcmp(args_info.hardware_arg, "opencl") )
feldkampOCL->PrintTiming(std::cout);
#endif
std::cout << std::endl;
}
return EXIT_SUCCESS;
}
<commit_msg>Remove unnecessary New() and typedef of FDK recon filters<commit_after>/*=========================================================================
*
* Copyright RTK Consortium
*
* 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 "rtkfdk_ggo.h"
#include "rtkGgoFunctions.h"
#include "rtkConfiguration.h"
#include "rtkThreeDCircularProjectionGeometryXMLFile.h"
#include "rtkDisplacedDetectorImageFilter.h"
#include "rtkParkerShortScanImageFilter.h"
#include "rtkFDKConeBeamReconstructionFilter.h"
#ifdef RTK_USE_CUDA
# include "rtkCudaFDKConeBeamReconstructionFilter.h"
#endif
#ifdef RTK_USE_OPENCL
# include "rtkOpenCLFDKConeBeamReconstructionFilter.h"
#endif
#include "rtkFDKWarpBackProjectionImageFilter.h"
#include "rtkCyclicDeformationImageFilter.h"
#include <itkStreamingImageFilter.h>
#include <itkImageFileWriter.h>
int main(int argc, char * argv[])
{
GGO(rtkfdk, args_info);
typedef float OutputPixelType;
const unsigned int Dimension = 3;
typedef itk::Image< OutputPixelType, Dimension > CPUOutputImageType;
#ifdef RTK_USE_CUDA
typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType;
#else
typedef CPUOutputImageType OutputImageType;
#endif
// Projections reader
typedef rtk::ProjectionsReader< OutputImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
rtk::SetProjectionsReaderFromGgo<ReaderType, args_info_rtkfdk>(reader, args_info);
itk::TimeProbe readerProbe;
if(!args_info.lowmem_flag)
{
if(args_info.verbose_flag)
std::cout << "Reading... " << std::flush;
readerProbe.Start();
TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->Update() )
readerProbe.Stop();
if(args_info.verbose_flag)
std::cout << "It took " << readerProbe.GetMean() << ' ' << readerProbe.GetUnit() << std::endl;
}
// Geometry
if(args_info.verbose_flag)
std::cout << "Reading geometry information from "
<< args_info.geometry_arg
<< "..."
<< std::endl;
rtk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geometryReader;
geometryReader = rtk::ThreeDCircularProjectionGeometryXMLFileReader::New();
geometryReader->SetFilename(args_info.geometry_arg);
TRY_AND_EXIT_ON_ITK_EXCEPTION( geometryReader->GenerateOutputInformation() )
// Displaced detector weighting
typedef rtk::DisplacedDetectorImageFilter< OutputImageType > DDFType;
DDFType::Pointer ddf = DDFType::New();
ddf->SetInput( reader->GetOutput() );
ddf->SetGeometry( geometryReader->GetOutputObject() );
// Short scan image filter
typedef rtk::ParkerShortScanImageFilter< OutputImageType > PSSFType;
PSSFType::Pointer pssf = PSSFType::New();
pssf->SetInput( ddf->GetOutput() );
pssf->SetGeometry( geometryReader->GetOutputObject() );
pssf->InPlaceOff();
// Create reconstructed image
typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;
ConstantImageSourceType::Pointer constantImageSource = ConstantImageSourceType::New();
rtk::SetConstantImageSourceFromGgo<ConstantImageSourceType, args_info_rtkfdk>(constantImageSource, args_info);
// Motion-compensated objects for the compensation of a cyclic deformation.
// Although these will only be used if the command line options for motion
// compensation are set, we still create the object before hand to avoid auto
// destruction.
typedef itk::Vector<float,3> DVFPixelType;
typedef itk::Image< DVFPixelType, 3 > DVFImageType;
typedef rtk::CyclicDeformationImageFilter< DVFImageType > DeformationType;
typedef itk::ImageFileReader<DeformationType::InputImageType> DVFReaderType;
DVFReaderType::Pointer dvfReader = DVFReaderType::New();
DeformationType::Pointer def = DeformationType::New();
def->SetInput(dvfReader->GetOutput());
typedef rtk::FDKWarpBackProjectionImageFilter<OutputImageType, OutputImageType, DeformationType> WarpBPType;
WarpBPType::Pointer bp = WarpBPType::New();
bp->SetDeformation(def);
bp->SetGeometry( geometryReader->GetOutputObject() );
// This macro sets options for fdk filter which I can not see how to do better
// because TFFTPrecision is not the same, e.g. for CPU and CUDA (SR)
#define SET_FELDKAMP_OPTIONS(f) \
f->SetInput( 0, constantImageSource->GetOutput() ); \
f->SetInput( 1, pssf->GetOutput() ); \
f->SetGeometry( geometryReader->GetOutputObject() ); \
f->GetRampFilter()->SetTruncationCorrection(args_info.pad_arg); \
f->GetRampFilter()->SetHannCutFrequency(args_info.hann_arg); \
f->GetRampFilter()->SetHannCutFrequencyY(args_info.hannY_arg); \
f->SetProjectionSubsetSize(args_info.subsetsize_arg)
// FDK reconstruction filtering
typedef rtk::FDKConeBeamReconstructionFilter< OutputImageType > FDKCPUType;
FDKCPUType::Pointer feldkamp;
#ifdef RTK_USE_OPENCL
typedef rtk::OpenCLFDKConeBeamReconstructionFilter FDKOPENCLType;
FDKOPENCLType::Pointer feldkampOCL;
#endif
#ifdef RTK_USE_CUDA
typedef rtk::CudaFDKConeBeamReconstructionFilter FDKCUDAType;
FDKCUDAType::Pointer feldkampCUDA;
#endif
itk::Image< OutputPixelType, Dimension > *pfeldkamp = NULL;
if(!strcmp(args_info.hardware_arg, "cpu") )
{
feldkamp = FDKCPUType::New();
SET_FELDKAMP_OPTIONS( feldkamp );
// Motion compensated CBCT settings
if(args_info.signal_given && args_info.dvf_given)
{
dvfReader->SetFileName(args_info.dvf_arg);
def->SetSignalFilename(args_info.signal_arg);
feldkamp->SetBackProjectionFilter( bp.GetPointer() );
}
pfeldkamp = feldkamp->GetOutput();
}
else if(!strcmp(args_info.hardware_arg, "cuda") )
{
#ifdef RTK_USE_CUDA
feldkampCUDA = FDKCUDAType::New();
SET_FELDKAMP_OPTIONS( feldkampCUDA );
pfeldkamp = feldkampCUDA->GetOutput();
#else
std::cerr << "The program has not been compiled with cuda option" << std::endl;
return EXIT_FAILURE;
#endif
}
else if(!strcmp(args_info.hardware_arg, "opencl") )
{
#ifdef RTK_USE_OPENCL
feldkampOCL = FDKOPENCLType::New();
SET_FELDKAMP_OPTIONS( feldkampOCL );
pfeldkamp = feldkampOCL->GetOutput();
#else
std::cerr << "The program has not been compiled with opencl option" << std::endl;
return EXIT_FAILURE;
#endif
}
// Streaming depending on streaming capability of writer
typedef itk::StreamingImageFilter<CPUOutputImageType, CPUOutputImageType> StreamerType;
StreamerType::Pointer streamerBP = StreamerType::New();
streamerBP->SetInput( pfeldkamp );
streamerBP->SetNumberOfStreamDivisions( args_info.divisions_arg );
// Write
typedef itk::ImageFileWriter<CPUOutputImageType> WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( args_info.output_arg );
writer->SetInput( streamerBP->GetOutput() );
if(args_info.verbose_flag)
std::cout << "Reconstructing and writing... " << std::flush;
itk::TimeProbe writerProbe;
writerProbe.Start();
TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() );
writerProbe.Stop();
if(args_info.verbose_flag)
{
std::cout << "It took " << writerProbe.GetMean() << ' ' << readerProbe.GetUnit() << std::endl;
if(!strcmp(args_info.hardware_arg, "cpu") )
feldkamp->PrintTiming(std::cout);
#ifdef RTK_USE_CUDA
else if(!strcmp(args_info.hardware_arg, "cuda") )
feldkampCUDA->PrintTiming(std::cout);
#endif
#ifdef RTK_USE_OPENCL
else if(!strcmp(args_info.hardware_arg, "opencl") )
feldkampOCL->PrintTiming(std::cout);
#endif
std::cout << std::endl;
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include <common/endian.h>
#include <event/event_callback.h>
#include <io/pipe/pipe.h>
#include <io/pipe/pipe_link.h>
#include <io/pipe/pipe_null.h>
#include <io/pipe/pipe_pair.h>
#include <xcodec/xcodec.h>
#include <xcodec/xcodec_decoder.h>
#include <xcodec/xcodec_encoder.h>
#include <xcodec/xcodec_pipe_pair.h>
#include <zlib/deflate_pipe.h>
#include <zlib/inflate_pipe.h>
#include "wanproxy_codec.h"
#include "wanproxy_codec_pipe_pair.h"
WANProxyCodecPipePair::WANProxyCodecPipePair(WANProxyCodec *incoming, WANProxyCodec *outgoing)
: incoming_pipe_(NULL),
outgoing_pipe_(NULL),
pipes_(),
pipe_pairs_(),
pipe_links_()
{
std::deque<std::pair<Pipe *, Pipe *> > pipe_list;
if (incoming != NULL) {
if (incoming->compressor_) {
std::pair<Pipe *, Pipe *> pipe_pair(new DeflatePipe(incoming->compressor_level_), new InflatePipe());
pipes_.insert(pipe_pair.first);
pipes_.insert(pipe_pair.second);
pipe_list.push_back(pipe_pair);
}
if (incoming->codec_ != NULL) {
PipePair *pair = new XCodecPipePair("/wanproxy/codec/" + incoming->name_, incoming->codec_, XCodecPipePairTypeServer);
pipe_pairs_.insert(pair);
std::pair<Pipe *, Pipe *> pipe_pair(pair->get_incoming(), pair->get_outgoing());
pipe_list.push_back(pipe_pair);
}
}
if (outgoing != NULL) {
if (outgoing->codec_ != NULL) {
PipePair *pair = new XCodecPipePair("/wanproxy/codec/" + outgoing->name_, outgoing->codec_, XCodecPipePairTypeClient);
pipe_pairs_.insert(pair);
std::pair<Pipe *, Pipe *> pipe_pair(pair->get_incoming(), pair->get_outgoing());
pipe_list.push_back(pipe_pair);
}
if (outgoing->compressor_) {
std::pair<Pipe *, Pipe *> pipe_pair(new InflatePipe(), new DeflatePipe(outgoing->compressor_level_));
pipes_.insert(pipe_pair.first);
pipes_.insert(pipe_pair.second);
pipe_list.push_back(pipe_pair);
}
}
if (pipe_list.empty()) {
incoming_pipe_ = new PipeNull();
outgoing_pipe_ = new PipeNull();
pipes_.insert(incoming_pipe_);
pipes_.insert(outgoing_pipe_);
return;
}
/*
* XXX
* I think the incoming Pipes may be in the wrong order.
*/
incoming_pipe_ = pipe_list.front().first;
outgoing_pipe_ = pipe_list.front().second;
pipe_list.pop_front();
while (!pipe_list.empty()) {
incoming_pipe_ = new PipeLink(incoming_pipe_, pipe_list.front().first);
outgoing_pipe_ = new PipeLink(outgoing_pipe_, pipe_list.front().second);
pipe_links_.push_front(incoming_pipe_);
pipe_links_.push_front(outgoing_pipe_);
pipe_list.pop_front();
}
}
WANProxyCodecPipePair::~WANProxyCodecPipePair()
{
/*
* We need to delete the PipeLinks first, since they may have
* actions running internally.
*/
std::list<Pipe *>::iterator plit;
while ((plit = pipe_links_.begin()) != pipe_links_.end()) {
Pipe *pipe_link = *plit;
pipe_links_.erase(plit);
delete pipe_link;
}
std::set<Pipe *>::iterator pit;
while ((pit = pipes_.begin()) != pipes_.end()) {
Pipe *pipe = *pit;
pipes_.erase(pit);
delete pipe;
}
std::set<PipePair *>::iterator ppit;
while ((ppit = pipe_pairs_.begin()) != pipe_pairs_.end()) {
PipePair *pipe_pair = *ppit;
pipe_pairs_.erase(ppit);
delete pipe_pair;
}
}
Pipe *
WANProxyCodecPipePair::get_incoming(void)
{
return (incoming_pipe_);
}
Pipe *
WANProxyCodecPipePair::get_outgoing(void)
{
return (outgoing_pipe_);
}
<commit_msg>Attempt to get XCodec+zlib Pipe order correct.<commit_after>#include <common/endian.h>
#include <event/event_callback.h>
#include <io/pipe/pipe.h>
#include <io/pipe/pipe_link.h>
#include <io/pipe/pipe_null.h>
#include <io/pipe/pipe_pair.h>
#include <xcodec/xcodec.h>
#include <xcodec/xcodec_decoder.h>
#include <xcodec/xcodec_encoder.h>
#include <xcodec/xcodec_pipe_pair.h>
#include <zlib/deflate_pipe.h>
#include <zlib/inflate_pipe.h>
#include "wanproxy_codec.h"
#include "wanproxy_codec_pipe_pair.h"
WANProxyCodecPipePair::WANProxyCodecPipePair(WANProxyCodec *incoming, WANProxyCodec *outgoing)
: incoming_pipe_(NULL),
outgoing_pipe_(NULL),
pipes_(),
pipe_pairs_(),
pipe_links_()
{
std::deque<Pipe *> incoming_pipe_list, outgoing_pipe_list;
if (incoming != NULL) {
if (incoming->compressor_) {
Pipe *deflate_pipe = new DeflatePipe(incoming->compressor_level_);
Pipe *inflate_pipe = new InflatePipe();
incoming_pipe_list.push_back(inflate_pipe);
outgoing_pipe_list.push_front(deflate_pipe);
pipes_.insert(deflate_pipe);
pipes_.insert(inflate_pipe);
}
if (incoming->codec_ != NULL) {
PipePair *pair = new XCodecPipePair("/wanproxy/codec/" + incoming->name_, incoming->codec_, XCodecPipePairTypeServer);
pipe_pairs_.insert(pair);
incoming_pipe_list.push_back(pair->get_incoming());
outgoing_pipe_list.push_front(pair->get_outgoing());
}
}
if (outgoing != NULL) {
if (outgoing->codec_ != NULL) {
PipePair *pair = new XCodecPipePair("/wanproxy/codec/" + outgoing->name_, outgoing->codec_, XCodecPipePairTypeClient);
pipe_pairs_.insert(pair);
incoming_pipe_list.push_back(pair->get_incoming());
outgoing_pipe_list.push_front(pair->get_outgoing());
}
if (outgoing->compressor_) {
Pipe *deflate_pipe = new DeflatePipe(outgoing->compressor_level_);
Pipe *inflate_pipe = new InflatePipe();
incoming_pipe_list.push_back(deflate_pipe);
outgoing_pipe_list.push_front(inflate_pipe);
pipes_.insert(deflate_pipe);
pipes_.insert(inflate_pipe);
}
}
ASSERT(incoming_pipe_list.empty() == outgoing_pipe_list.empty());
if (incoming_pipe_list.empty() && outgoing_pipe_list.empty()) {
incoming_pipe_ = new PipeNull();
outgoing_pipe_ = new PipeNull();
pipes_.insert(incoming_pipe_);
pipes_.insert(outgoing_pipe_);
return;
}
ASSERT(incoming_pipe_list.size() == outgoing_pipe_list.size());
incoming_pipe_ = incoming_pipe_list.front();
incoming_pipe_list.pop_front();
outgoing_pipe_ = outgoing_pipe_list.front();
outgoing_pipe_list.pop_front();
while (!incoming_pipe_list.empty() && !outgoing_pipe_list.empty()) {
incoming_pipe_ = new PipeLink(incoming_pipe_, incoming_pipe_list.front());
outgoing_pipe_ = new PipeLink(outgoing_pipe_, outgoing_pipe_list.front());
pipe_links_.push_front(incoming_pipe_);
pipe_links_.push_front(outgoing_pipe_);
incoming_pipe_list.pop_front();
outgoing_pipe_list.pop_front();
}
ASSERT(incoming_pipe_list.empty() && outgoing_pipe_list.empty());
}
WANProxyCodecPipePair::~WANProxyCodecPipePair()
{
/*
* We need to delete the PipeLinks first, since they may have
* actions running internally.
*/
std::list<Pipe *>::iterator plit;
while ((plit = pipe_links_.begin()) != pipe_links_.end()) {
Pipe *pipe_link = *plit;
pipe_links_.erase(plit);
delete pipe_link;
}
std::set<Pipe *>::iterator pit;
while ((pit = pipes_.begin()) != pipes_.end()) {
Pipe *pipe = *pit;
pipes_.erase(pit);
delete pipe;
}
std::set<PipePair *>::iterator ppit;
while ((ppit = pipe_pairs_.begin()) != pipe_pairs_.end()) {
PipePair *pipe_pair = *ppit;
pipe_pairs_.erase(ppit);
delete pipe_pair;
}
}
Pipe *
WANProxyCodecPipePair::get_incoming(void)
{
return (incoming_pipe_);
}
Pipe *
WANProxyCodecPipePair::get_outgoing(void)
{
return (outgoing_pipe_);
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* 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. *
*******************************************************************************
* SOFA :: Applications *
* *
* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, *
* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include "SofaGUI.h"
#include <sofa/component/init.h>
#include <sofa/simulation/tree/xml/initXml.h>
namespace sofa
{
namespace gui
{
SOFA_LINK_CLASS(BatchGUI)
#ifdef SOFA_GUI_GLUT
SOFA_LINK_CLASS(SimpleGUI)
#endif
#ifdef SOFA_GUI_QGLVIEWER
SOFA_LINK_CLASS(QGLViewerGUI)
#endif
#ifdef SOFA_GUI_QTVIEWER
SOFA_LINK_CLASS(QTGUI)
#endif
#ifdef SOFA_GUI_QTOGREVIEWER
SOFA_LINK_CLASS(OgreGUI)
#endif
// ligne 1 et 3
#ifdef __GNUC__ 4
#ifdef __GNUC__MINOR__ 2
int fish
#endif
#endif
#ifndef SOFA_DEV
int fish
#endif
#ifdef __APPLE__
int fish
#endif
// ligne 2
//#ifdef __GNUC__ 4
// #ifdef __GNUC__MINOR__ 3
// int fish
// #endif
//#endif
//
//#ifdef __GNUC__ 4
// #ifdef __GNUC__MINOR__ 1
// int fish
// #endif
//#endif
//
//#ifdef SOFA_GPU_CUDA
// int fish
//#endif
int SofaGUI::Init()
{
sofa::component::init();
sofa::simulation::tree::xml::initXml();
if (guiCreators().empty())
{
std::cerr << "ERROR(SofaGUI): No GUI registered."<<std::endl;
return 1;
}
const char* name = GetGUIName();
if (currentGUI)
return 0; // already initialized
GUICreator* creator = GetGUICreator(name);
if (!creator)
{
return 1;
}
if (creator->init)
return (*creator->init)(name, guiOptions);
else
return 0;
}
int SofaGUI::createGUI(sofa::simulation::Node* groot, const char* filename)
{
const char* name = GetGUIName();
if (!currentGUI)
{
GUICreator* creator = GetGUICreator(name);
if (!creator)
{
return 1;
}
currentGUI = (*creator->creator)(name, guiOptions, groot, filename);
if (!currentGUI)
{
std::cerr << "ERROR(SofaGUI): GUI "<<name<<" creation failed."<<std::endl;
return 1;
}
}
return 0;
}
int SofaGUI::MainLoop(sofa::simulation::Node* groot, const char* filename)
{
int ret = 0;
const char* name = GetGUIName();
if (!currentGUI)
{
createGUI(groot, filename);
}
ret = currentGUI->mainLoop();
if (ret)
{
std::cerr << "ERROR(SofaGUI): GUI "<<name<<" main loop failed (code "<<ret<<")."<<std::endl;
return ret;
}
return ret;
}
} // namespace gui
} // namespace sofa
<commit_msg>r4606/sofa-dev : <commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* 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. *
*******************************************************************************
* SOFA :: Applications *
* *
* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, *
* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include "SofaGUI.h"
#include <sofa/component/init.h>
#include <sofa/simulation/tree/xml/initXml.h>
namespace sofa
{
namespace gui
{
SOFA_LINK_CLASS(BatchGUI)
#ifdef SOFA_GUI_GLUT
SOFA_LINK_CLASS(SimpleGUI)
#endif
#ifdef SOFA_GUI_QGLVIEWER
SOFA_LINK_CLASS(QGLViewerGUI)
#endif
#ifdef SOFA_GUI_QTVIEWER
SOFA_LINK_CLASS(QTGUI)
#endif
#ifdef SOFA_GUI_QTOGREVIEWER
SOFA_LINK_CLASS(OgreGUI)
#endif
int SofaGUI::Init()
{
sofa::component::init();
sofa::simulation::tree::xml::initXml();
if (guiCreators().empty())
{
std::cerr << "ERROR(SofaGUI): No GUI registered."<<std::endl;
return 1;
}
const char* name = GetGUIName();
if (currentGUI)
return 0; // already initialized
GUICreator* creator = GetGUICreator(name);
if (!creator)
{
return 1;
}
if (creator->init)
return (*creator->init)(name, guiOptions);
else
return 0;
}
int SofaGUI::createGUI(sofa::simulation::Node* groot, const char* filename)
{
const char* name = GetGUIName();
if (!currentGUI)
{
GUICreator* creator = GetGUICreator(name);
if (!creator)
{
return 1;
}
currentGUI = (*creator->creator)(name, guiOptions, groot, filename);
if (!currentGUI)
{
std::cerr << "ERROR(SofaGUI): GUI "<<name<<" creation failed."<<std::endl;
return 1;
}
}
return 0;
}
int SofaGUI::MainLoop(sofa::simulation::Node* groot, const char* filename)
{
int ret = 0;
const char* name = GetGUIName();
if (!currentGUI)
{
createGUI(groot, filename);
}
ret = currentGUI->mainLoop();
if (ret)
{
std::cerr << "ERROR(SofaGUI): GUI "<<name<<" main loop failed (code "<<ret<<")."<<std::endl;
return ret;
}
return ret;
}
} // namespace gui
} // namespace sofa
<|endoftext|>
|
<commit_before><commit_msg>-Werror,-Winconsistent-missing-override<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dump8.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: obo $ $Date: 2005-11-16 13:54:06 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
#ifndef _SV_WRKWIN_HXX //autogen
#include <vcl/wrkwin.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#include <sot/storage.hxx>
// globale Vars
char** pPara;
// Deklarationen
int PrepareConvert( String& rName, String& rOutName, String& rMess );
int DoConvert( const String& rName, BYTE nVersion );
void DeInit();
// -----------------------------------------------------------------------
class MyApp : public Application
{
public:
void Main();
};
// -----------------------------------------------------------------------
MyApp aMyApp;
// -----------------------------------------------------------------------
class MyWin : public WorkWindow
{
String& rMessg;
public:
MyWin( Window* pParent, WinBits aWinStyle, String& rMess ) :
WorkWindow(pParent, aWinStyle), rMessg( rMess ) {}
void Paint( const Rectangle& );
void Resize();
void MouseButtonDown( const MouseEvent& rMEvt );
void KeyInput( const KeyEvent& rKEvt );
};
// -----------------------------------------------------------------------
extern SvStorageStreamRef xStrm;
void MyApp::Main()
{
SvFactory::Init();
String aMess, aName, aOutName;
BYTE nVersion = 8;
int nArgs = GetCommandLineParamCount();
if (nArgs)
{
aName = GetCommandLineParam( 0 );
if (aName.Search('.') == STRING_NOTFOUND)
aName.AppendAscii( ".doc" );
if (nArgs >= 2)
{
aOutName = GetCommandLineParam( 1 );
if (nArgs > 2)
{
nVersion = GetCommandLineParam( 2 ).ToInt32();
if( 6 > nVersion || 8 < nVersion )
{
aMess.AssignAscii( "Aufruf: Dump1 InFile [OutFile] [6|7|8]" );
}
}
}
else
{
aOutName = aName;
aOutName.Erase(aOutName.Search('.'));
aOutName.AppendAscii( ".dmp" );
}
}
BOOL bOk = !aMess.Len()
&& !PrepareConvert( aName, aOutName, aMess )
&& !DoConvert( aName, nVersion );
if( !bOk )
{
MyWin aMainWin( NULL, WB_APP | WB_STDWORK, aMess );
aMainWin.SetText( String::CreateFromAscii( "WW8-Dumper" ));
aMainWin.Show();
aMainWin.Invalidate();
Execute();
}
DeInit();
// SvFactory::DeInit();
}
// -----------------------------------------------------------------------
void MyWin::Paint( const Rectangle& )
{
String aText( String::CreateFromAscii( "Dumper fuer WinWord-Dateien !\n"
"Die Wandlung ging schief. Ist es wirklich ein WW-File ?" ));
Size aWinSize = GetOutputSizePixel();
Size aTextSize( GetTextWidth( aText ), GetTextHeight());
Point aPos( aWinSize.Width() / 2 - aTextSize.Width() / 2,
aWinSize.Height() / 2 - aTextSize.Height() / 2 );
DrawText( aPos, aText );
aPos.Y() += 20;
DrawText( aPos, rMessg );
}
// -----------------------------------------------------------------------
void MyWin::Resize()
{
Invalidate();
}
// -----------------------------------------------------------------------
void MyWin::MouseButtonDown( const MouseEvent& )
{
}
// -----------------------------------------------------------------------
void MyWin::KeyInput( const KeyEvent& rKEvt )
{
WorkWindow::KeyInput( rKEvt );
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.7.390); FILE MERGED 2006/09/01 17:52:44 kaib 1.7.390.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dump8.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2006-09-16 22:25:42 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
#ifndef _SV_WRKWIN_HXX //autogen
#include <vcl/wrkwin.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#include <sot/storage.hxx>
// globale Vars
char** pPara;
// Deklarationen
int PrepareConvert( String& rName, String& rOutName, String& rMess );
int DoConvert( const String& rName, BYTE nVersion );
void DeInit();
// -----------------------------------------------------------------------
class MyApp : public Application
{
public:
void Main();
};
// -----------------------------------------------------------------------
MyApp aMyApp;
// -----------------------------------------------------------------------
class MyWin : public WorkWindow
{
String& rMessg;
public:
MyWin( Window* pParent, WinBits aWinStyle, String& rMess ) :
WorkWindow(pParent, aWinStyle), rMessg( rMess ) {}
void Paint( const Rectangle& );
void Resize();
void MouseButtonDown( const MouseEvent& rMEvt );
void KeyInput( const KeyEvent& rKEvt );
};
// -----------------------------------------------------------------------
extern SvStorageStreamRef xStrm;
void MyApp::Main()
{
SvFactory::Init();
String aMess, aName, aOutName;
BYTE nVersion = 8;
int nArgs = GetCommandLineParamCount();
if (nArgs)
{
aName = GetCommandLineParam( 0 );
if (aName.Search('.') == STRING_NOTFOUND)
aName.AppendAscii( ".doc" );
if (nArgs >= 2)
{
aOutName = GetCommandLineParam( 1 );
if (nArgs > 2)
{
nVersion = GetCommandLineParam( 2 ).ToInt32();
if( 6 > nVersion || 8 < nVersion )
{
aMess.AssignAscii( "Aufruf: Dump1 InFile [OutFile] [6|7|8]" );
}
}
}
else
{
aOutName = aName;
aOutName.Erase(aOutName.Search('.'));
aOutName.AppendAscii( ".dmp" );
}
}
BOOL bOk = !aMess.Len()
&& !PrepareConvert( aName, aOutName, aMess )
&& !DoConvert( aName, nVersion );
if( !bOk )
{
MyWin aMainWin( NULL, WB_APP | WB_STDWORK, aMess );
aMainWin.SetText( String::CreateFromAscii( "WW8-Dumper" ));
aMainWin.Show();
aMainWin.Invalidate();
Execute();
}
DeInit();
// SvFactory::DeInit();
}
// -----------------------------------------------------------------------
void MyWin::Paint( const Rectangle& )
{
String aText( String::CreateFromAscii( "Dumper fuer WinWord-Dateien !\n"
"Die Wandlung ging schief. Ist es wirklich ein WW-File ?" ));
Size aWinSize = GetOutputSizePixel();
Size aTextSize( GetTextWidth( aText ), GetTextHeight());
Point aPos( aWinSize.Width() / 2 - aTextSize.Width() / 2,
aWinSize.Height() / 2 - aTextSize.Height() / 2 );
DrawText( aPos, aText );
aPos.Y() += 20;
DrawText( aPos, rMessg );
}
// -----------------------------------------------------------------------
void MyWin::Resize()
{
Invalidate();
}
// -----------------------------------------------------------------------
void MyWin::MouseButtonDown( const MouseEvent& )
{
}
// -----------------------------------------------------------------------
void MyWin::KeyInput( const KeyEvent& rKEvt )
{
WorkWindow::KeyInput( rKEvt );
}
<|endoftext|>
|
<commit_before>#pragma once
#include <cstdint>
#include <functional>
#include <optional>
#include <unordered_map>
#include "utils/Concepts.hpp"
namespace utils {
template <NumericIntegral TValue>
class DisjointSets {
public:
using ValueType = TValue;
[[nodiscard]] int64_t size() const noexcept {
return static_cast<int64_t>(this->m_parents.size());
}
bool add(const ValueType value) {
if (this->m_parents.contains(value)) {
return false;
}
this->m_parents.emplace(value, value);
return true;
}
std::optional<ValueType> find(const ValueType value) {
if (auto it = this->m_parents.find(value); it != this->m_parents.end()) {
return this->findParent(it)->first;
}
return std::nullopt;
}
bool merge(const ValueType lhs, const ValueType rhs) {
auto lhsIts = this->m_parents.find(lhs);
if (lhsIts == this->m_parents.end()) {
return false;
}
auto rhsIts = this->m_parents.find(rhs);
if (rhsIts == this->m_parents.end()) {
return false;
}
auto lhsParent = this->findParent(lhsIts);
auto rhsParent = this->findParent(rhsIts);
if (&lhsParent == &rhsParent) {
return false;
}
if (lhsParent->first < rhsParent->first) {
rhsParent->second = lhsParent->first;
} else {
lhsParent->second = rhsParent->first;
}
return true;
}
private:
using NoteIterator = typename std::unordered_map<ValueType, ValueType>::iterator;
[[nodiscard]] NoteIterator findParent(NoteIterator it) {
std::vector<typename std::unordered_map<ValueType, ValueType>::iterator> visitedNodesIts;
while (it->first != it->second) {
visitedNodesIts.push_back(it);
it = this->m_parents.find(it->second);
}
for (auto &visitedNodeIt: visitedNodesIts) {
visitedNodeIt->second = it->second;
}
return it;
}
std::unordered_map<ValueType, ValueType> m_parents;
};
} // namespace utils<commit_msg>Fix usage of NodeIterator<commit_after>#pragma once
#include <cstdint>
#include <functional>
#include <optional>
#include <unordered_map>
#include "utils/Concepts.hpp"
namespace utils {
template <NumericIntegral TValue>
class DisjointSets {
public:
using ValueType = TValue;
[[nodiscard]] int64_t size() const noexcept {
return static_cast<int64_t>(this->m_parents.size());
}
bool add(const ValueType value) {
if (this->m_parents.contains(value)) {
return false;
}
this->m_parents.emplace(value, value);
return true;
}
std::optional<ValueType> find(const ValueType value) {
if (auto it = this->m_parents.find(value); it != this->m_parents.end()) {
return this->findParent(it)->first;
}
return std::nullopt;
}
bool merge(const ValueType lhs, const ValueType rhs) {
auto lhsIts = this->m_parents.find(lhs);
if (lhsIts == this->m_parents.end()) {
return false;
}
auto rhsIts = this->m_parents.find(rhs);
if (rhsIts == this->m_parents.end()) {
return false;
}
auto lhsParent = this->findParent(lhsIts);
auto rhsParent = this->findParent(rhsIts);
if (&lhsParent == &rhsParent) {
return false;
}
if (lhsParent->first < rhsParent->first) {
rhsParent->second = lhsParent->first;
} else {
lhsParent->second = rhsParent->first;
}
return true;
}
private:
using NodeIterator = typename std::unordered_map<ValueType, ValueType>::iterator;
[[nodiscard]] NodeIterator findParent(NodeIterator it) {
std::vector<NodeIterator> visitedNodesIts;
while (it->first != it->second) {
visitedNodesIts.push_back(it);
it = this->m_parents.find(it->second);
}
for (auto &visitedNodeIt: visitedNodesIts) {
visitedNodeIt->second = it->second;
}
return it;
}
std::unordered_map<ValueType, ValueType> m_parents;
};
} // namespace utils<|endoftext|>
|
<commit_before>// Filename: main.cpp
// Author: Christopher Goes
// Course: CS 404 Machine Learning and Data Mining
// Semester: Spring 2016
// Description: Assignment 3 main program logic
// Github: https://github.com/GhostofGoes/cgoes-cs404
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <vector>
#include <cmath>
#include "matrix.h"
#define DEBUG 0
#define DEBUGINPUT 0
#define DEBUG_RESULTS 0
using namespace std;
double sigmoid( double input ); // Sigmoid function
int main() {
// Initialization
// weird init values are paranoia for error catching
int numInputs = 0;
int numOutputs = 0;
int rows = 0;
int cols = 0;
int testRows = 0;
int testCols = 0;
double temp = -99;
double bias = -1.0; // -1 is what the book uses.
double eta = 0.025; // 0.25 is what the book uses. open to tweaking.
int attempts = 1; // if debugging, SET THIS TO A SMALL NUMBER!
//int num_hidden_layers = 1; // is this a thing
int num_hidden_nodes = 0;
double max = 1;
double min = 1;
// Training Data Input //
cin >> numInputs;
cin >> num_hidden_nodes;
cin >> rows;
cin >> cols;
numOutputs = cols - numInputs;
Matrix* tinput = new Matrix(rows, numInputs + 1); // +1 for bias
Matrix* toutput = new Matrix(rows, numOutputs);
if(DEBUGINPUT) {
cout << "Inputs: " << numInputs << "\nHidden Nodes: " << num_hidden_nodes << "\nRows: " << rows << "\nCols: " << cols << endl;
}
// Fill the matrix
for(int r = 0; r < rows; r++) {
for(int c = 0; c < numInputs; c++) {
cin >> temp;
if( temp > max ) max = temp;
else if( temp < min ) min = temp;
tinput->setValue( r, c, temp);
}
for(int c = 0; c < numOutputs; c++ ) {
cin >> temp;
if( temp > max ) max = temp;
else if( temp < min ) min = temp;
toutput->setValue( r, c, temp);
}
}
// Append the bias
for( int r = 0; r < rows; r++ ) {
tinput->setValue(r, numInputs, bias);
}
numInputs++;
if(DEBUGINPUT) {
cout << "\nTraining Inputs..." << endl;
tinput->printAll();
cout << "\nTraining Outputs..." << endl;
toutput->printAll();
}
// Test Data Input //
cin >> testRows;
cin >> testCols;
Matrix * testInput = new Matrix(testRows, testCols + 1);
// Fill the matrix
for(int r = 0; r < testRows; r++) {
for(int c = 0; c < testCols; c++) {
cin >> temp;
if( temp > max ) max = temp;
else if( temp < min ) min = temp;
testInput->setValue(r, c, temp);
}
}
// Append the bias
for( int r = 0; r < testRows; r++ ) {
testInput->setValue(r, testCols, bias);
}
testCols;
if(DEBUGINPUT) {
cout << "\nTest Inputs matrix" << endl;
testInput->printAll();
}
// //
// * Training * //
Matrix * hw = new Matrix(num_hidden_nodes, numOutputs, 2);
Matrix * ow = new Matrix(num_hidden_nodes + 1, numOutputs, 2); // +1 for the extra bias between hidden and output layers
Matrix * tempmat;
Matrix * deltah; // error in hidden layer
Matrix * deltao; // error in output layer
Matrix * a; // hidden layer output
Matrix * y; // output layer output
Matrix * hVec;
Matrix * inVec;
Matrix * t;
temp = -99;
if(DEBUG) {
cout << "\nInitialized Hidden Weight matrix..." << endl;
hw->printAll();
}
// Normalize our input
tinput->normalize(min, max);
// re-re-implementation
for( int attempt = 0; attempt < attempts; attempt++ ) {
// TODO randomize order rows are done each attempt?
for( int r = 0; r < rows; r++ ) {
inVec = tinput->getRow(r);
t = toutput->getRow(r);
if(DEBUG) {
cout << "inVec" << endl;
inVec->printAll();
cout << endl;
}
// hidden layer
a = inVec->dot(hw);
a->sigmoid();
if(DEBUG) {
cout << "a" << endl;
a->printAll();
cout << endl;
}
hVec = new Matrix(a);
hVec->data[0].push_back(bias);
hVec->numCols++;
if(DEBUG) {
cout << "hVec" << endl;
hVec->printAll();
cout << endl;
}
// output layer
y = hVec->dot(hw);
y->sigmoid();
if(DEBUG) {
cout << "y" << endl;
y->printAll();
cout << endl;
}
// output error
t = t->sub(y);
t = t->dot(y);
if(DEBUG) {
cout << "y" << endl;
t->printAll();
cout << endl;
}
y->scalarPreSub(1.0);
deltao = t->mult(y);
if(DEBUG) {
cout << "deltao" << endl;
deltao->printAll();
cout << endl;
}
// hidden error
deltah = hVec;
hVec->scalarPreSub(1.0);
deltah->mult(hVec);
hVec->scalarPreSub(1.0);
tempmat = deltao->dot(ow);
tempmat = tempmat->transpose();
deltah = deltah->mult(tempmat);
if(DEBUG) {
cout << "deltah" << endl;
deltah->printAll();
cout << endl;
}
// update matricies
hVec = hVec->transpose();
hVec = hVec->dot(deltao);
hVec = hVec->dot(eta);
ow = ow->add(tempmat);
deltah->data[0].pop_back();
deltah->numCols--;
tempmat = inVec->transpose();
tempmat = inVec->dot(deltah);
tempmat = tempmat->dot(eta);
hw = hw->add(tempmat);
delete deltao;
delete deltah;
delete a;
delete y;
delete hVec;
delete inVec;
delete t;
} // rows
} // attempts
// //
// Testing //
cout << "BEGIN TESTING" << endl;
testInput->normalize(min, max);
for( int r = 0; r < testRows; r++ ) { // Each row in testing set
inVec = testInput->getRow(r);
for (int i = 0; i < testCols; i++) {
cout << fixed << setprecision(2) << testInput->getValue(r, i) << " ";
}
// hidden layer
a = inVec->dot(hw);
a->sigmoid();
hVec = new Matrix(a);
hVec->data[0].push_back(bias);
hVec->numCols++;
// output layer
y = hVec->dot(hw);
y->sigmoid();
for( int i = 0; i < numOutputs; i++ ) {
cout << fixed << setprecision(2) << y->getValue(0, i) << " ";
}
cout << endl; // end the row's output
} // row in set loop
// Final Cleanup //
delete hw;
delete ow;
delete tinput;
delete toutput;
delete testInput;
return(0);
}
double sigmoid( double input ) {
return (2 / (1 + exp(-25 * input)) - 1);
}
<commit_msg>Minor edits before final HW3 submission<commit_after>// Filename: main.cpp
// Author: Christopher Goes
// Course: CS 404 Machine Learning and Data Mining
// Semester: Spring 2016
// Description: Assignment 3 main program logic
// Github: https://github.com/GhostofGoes/cgoes-cs404
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <vector>
#include <cmath>
#include "matrix.h"
#define DEBUG 0
#define DEBUGINPUT 0
#define DEBUG_RESULTS 0
using namespace std;
double sigmoid( double input ); // Sigmoid function
int main() {
// Initialization
// weird init values are paranoia for error catching
int numInputs = 0;
int numOutputs = 0;
int rows = 0;
int cols = 0;
int testRows = 0;
int testCols = 0;
double temp = -99;
double bias = -1.0; // -1 is what the book uses.
double eta = 0.025; // 0.25 is what the book uses. open to tweaking.
int attempts = 1; // if debugging, SET THIS TO A SMALL NUMBER!
//int num_hidden_layers = 1; // is this a thing
int num_hidden_nodes = 0;
double max = 1;
double min = 1;
// Training Data Input //
cin >> numInputs;
cin >> num_hidden_nodes;
cin >> rows;
cin >> cols;
numOutputs = cols - numInputs;
Matrix* tinput = new Matrix(rows, numInputs + 1); // +1 for bias
Matrix* toutput = new Matrix(rows, numOutputs);
if(DEBUGINPUT) {
cout << "Inputs: " << numInputs << "\nHidden Nodes: " << num_hidden_nodes << "\nRows: " << rows << "\nCols: " << cols << endl;
}
// Fill the matrix
for(int r = 0; r < rows; r++) {
for(int c = 0; c < numInputs; c++) {
cin >> temp;
if( temp > max ) max = temp;
else if( temp < min ) min = temp;
tinput->setValue( r, c, temp);
}
for(int c = 0; c < numOutputs; c++ ) {
cin >> temp;
if( temp > max ) max = temp;
else if( temp < min ) min = temp;
toutput->setValue( r, c, temp);
}
}
// Append the bias
for( int r = 0; r < rows; r++ ) {
tinput->setValue(r, numInputs, bias);
}
numInputs++;
if(DEBUGINPUT) {
cout << "\nTraining Inputs..." << endl;
tinput->printAll();
cout << "\nTraining Outputs..." << endl;
toutput->printAll();
}
// Test Data Input //
cin >> testRows;
cin >> testCols;
Matrix * testInput = new Matrix(testRows, testCols + 1);
// Fill the matrix
for(int r = 0; r < testRows; r++) {
for(int c = 0; c < testCols; c++) {
cin >> temp;
if( temp > max ) max = temp;
else if( temp < min ) min = temp;
testInput->setValue(r, c, temp);
}
}
// Append the bias
for( int r = 0; r < testRows; r++ ) {
testInput->setValue(r, testCols, bias);
}
testCols;
if(DEBUGINPUT) {
cout << "\nTest Inputs matrix" << endl;
testInput->printAll();
}
// //
// * Training * //
Matrix * hw = new Matrix(num_hidden_nodes, numOutputs, 2);
Matrix * ow = new Matrix(num_hidden_nodes + 1, numOutputs, 2); // +1 for the extra bias between hidden and output layers
Matrix * tempmat;
Matrix * deltah; // error in hidden layer
Matrix * deltao; // error in output layer
Matrix * a; // hidden layer output
Matrix * y; // output layer output
Matrix * hVec;
Matrix * inVec;
Matrix * t;
temp = -99;
if(DEBUG) {
cout << "\nInitialized Hidden Weight matrix..." << endl;
hw->printAll();
}
// Normalize our input
tinput->normalize(min, max);
// re-re-implementation
for( int attempt = 0; attempt < attempts; attempt++ ) {
// TODO randomize order rows are done each attempt?
for( int r = 0; r < rows; r++ ) {
inVec = tinput->getRow(r);
t = toutput->getRow(r);
if(DEBUG) {
cout << "inVec" << endl;
inVec->printAll();
cout << endl;
}
// hidden layer
a = inVec->dot(hw);
a->sigmoid();
if(DEBUG) {
cout << "a" << endl;
a->printAll();
cout << endl;
}
hVec = new Matrix(a);
hVec->data[0].push_back(bias);
hVec->numCols++;
if(DEBUG) {
cout << "hVec" << endl;
hVec->printAll();
cout << endl;
}
// output layer
y = hVec->dot(hw);
y->sigmoid();
if(DEBUG) {
cout << "y" << endl;
y->printAll();
cout << endl;
}
// output error
t = t->sub(y);
t = t->dot(y);
if(DEBUG) {
cout << "y" << endl;
t->printAll();
cout << endl;
}
y->scalarPreSub(1.0);
deltao = t->mult(y);
if(DEBUG) {
cout << "deltao" << endl;
deltao->printAll();
cout << endl;
}
// hidden error
deltah = hVec;
hVec->scalarPreSub(1.0);
deltah->mult(hVec);
hVec->scalarPreSub(1.0);
tempmat = deltao->dot(ow);
tempmat = tempmat->transpose();
deltah = deltah->mult(tempmat);
if(DEBUG) {
cout << "deltah" << endl;
deltah->printAll();
cout << endl;
}
// update matricies
hVec = hVec->transpose();
hVec = hVec->dot(deltao);
hVec = hVec->dot(eta);
ow = ow->add(tempmat);
deltah->data[0].pop_back();
deltah->numCols--;
tempmat = inVec->transpose();
tempmat = inVec->dot(deltah);
tempmat = tempmat->dot(eta);
hw = hw->add(tempmat);
delete deltao;
delete deltah;
delete a;
delete y;
delete hVec;
delete inVec;
delete t;
} // rows
} // attempts
// //
// Testing //
Matrix * normTestInput;
cout << "BEGIN TESTING" << endl;
normTestInput = new Matrix(testInput);
normTestInput->normalize(min, max);
for( int r = 0; r < testRows; r++ ) { // Each row in testing set
inVec = normTestInput->getRow(r);
for (int i = 0; i < testCols; i++) {
cout << fixed << setprecision(2) << testInput->getValue(r, i) << " ";
}
// hidden layer
a = inVec->dot(hw);
a->sigmoid();
hVec = new Matrix(a);
hVec->data[0].push_back(bias);
hVec->numCols++;
// output layer
y = hVec->dot(hw);
y->sigmoid();
for( int i = 0; i < numOutputs; i++ ) {
cout << fixed << setprecision(2) << y->getValue(0, i) << " ";
}
cout << endl; // end the row's output
} // row in set loop
// Final Cleanup //
delete hw;
delete ow;
delete tinput;
delete toutput;
delete testInput;
return(0);
}
double sigmoid( double input ) {
return (2 / (1 + exp(-25 * input)) - 1);
}
<|endoftext|>
|
<commit_before>#include <common/endian.h>
#include <event/event_callback.h>
#include <event/event_main.h>
#include <event/event_system.h>
#include <http/http_protocol.h>
#include <io/net/tcp_server.h>
#include <io/pipe/pipe.h>
#include <io/pipe/pipe_producer.h>
#include <io/pipe/splice.h>
#include <io/socket/simple_server.h>
#include <ssh/ssh_protocol.h>
class SSHTransportPipe : public PipeProducer {
enum State {
GetIdentificationString,
GetPacket
};
State state_;
Buffer input_buffer_;
size_t mac_length_;
EventCallback *receive_callback_;
Action *receive_action_;
public:
SSHTransportPipe(void)
: PipeProducer("/ssh/transport/pipe"),
state_(GetIdentificationString),
mac_length_(0),
receive_callback_(NULL),
receive_action_(NULL)
{
Buffer identification_string("SSH-2.0-WANProxy " + (std::string)log_ + "\r\n");
produce(&identification_string);
}
~SSHTransportPipe()
{
ASSERT(receive_callback_ == NULL);
ASSERT(receive_action_ == NULL);
}
Action *receive(EventCallback *cb)
{
ASSERT(receive_callback_ == NULL);
ASSERT(receive_action_ == NULL);
/*
* XXX
* This pattern is implemented about three different
* ways in the WANProxy codebase, and they are all kind
* of awful. Need a better way to handle code that
* needs executed either on the request of the caller
* or when data comes in that satisfies a deferred
* callback to a caller.
*/
receive_callback_ = cb;
receive_do();
if (receive_callback_ != NULL)
return (cancellation(this, &SSHTransportPipe::receive_cancel));
ASSERT(receive_action_ != NULL);
Action *a = receive_action_;
receive_action_ = NULL;
return (a);
}
private:
void consume(Buffer *in)
{
/* XXX XXX XXX */
if (in->empty()) {
if (!input_buffer_.empty())
DEBUG(log_) << "Received EOS with data outstanding.";
Buffer eos;
produce(&eos);
return;
}
input_buffer_.append(in);
in->clear();
if (state_ == GetIdentificationString) {
HTTPProtocol::ParseStatus status;
while (!input_buffer_.empty()) {
Buffer line;
status = HTTPProtocol::ExtractLine(&line, &input_buffer_);
switch (status) {
case HTTPProtocol::ParseSuccess:
break;
case HTTPProtocol::ParseFailure:
ERROR(log_) << "Invalid line while waiting for identification string.";
produce_error();
return;
case HTTPProtocol::ParseIncomplete:
/* Wait for more. */
return;
}
if (!line.prefix("SSH-"))
continue; /* Next line. */
if (!line.prefix("SSH-2.0")) {
ERROR(log_) << "Unsupported version.";
produce_error();
return;
}
state_ = GetPacket;
break;
}
}
if (state_ == GetPacket && receive_callback_ != NULL)
receive_do();
}
void receive_cancel(void)
{
if (receive_action_ != NULL) {
receive_action_->cancel();
receive_action_ = NULL;
}
if (receive_callback_ != NULL) {
delete receive_callback_;
receive_callback_ = NULL;
}
}
void receive_do(void)
{
ASSERT(receive_action_ == NULL);
ASSERT(receive_callback_ != NULL);
if (state_ != GetPacket)
return;
while (!input_buffer_.empty()) {
Buffer packet;
Buffer mac;
uint32_t packet_len;
uint8_t padding_len;
if (input_buffer_.length() <= sizeof packet_len) {
DEBUG(log_) << "Waiting for packet length.";
return;
}
input_buffer_.extract(&packet_len);
packet_len = BigEndian::decode(packet_len);
if (packet_len == 0) {
ERROR(log_) << "Need to handle 0-length packet.";
produce_error();
return;
}
if (input_buffer_.length() < sizeof packet_len + packet_len + mac_length_) {
DEBUG(log_) << "Need " << sizeof packet_len + packet_len + mac_length_ << "bytes; have " << input_buffer_.length() << ".";
return;
}
input_buffer_.moveout(&packet, sizeof packet_len, packet_len);
if (mac_length_ != 0)
input_buffer_.moveout(&mac, 0, mac_length_);
padding_len = packet.peek();
packet.skip(sizeof padding_len);
if (padding_len != 0) {
if (packet.length() < padding_len) {
ERROR(log_) << "Padding too large for packet.";
produce_error();
return;
}
packet.trim(padding_len);
}
if (packet.empty()) {
ERROR(log_) << "Need to handle empty packet.";
produce_error();
return;
}
/*
* XXX
* Handle Transport messages internally?
*/
receive_callback_->param(Event(Event::Done, packet));
receive_action_ = receive_callback_->schedule();
receive_callback_ = NULL;
return;
}
}
};
class SSHConnection {
LogHandle log_;
Socket *peer_;
SSHTransportPipe *pipe_;
Action *receive_action_;
Splice *splice_;
Action *splice_action_;
Action *close_action_;
public:
SSHConnection(Socket *peer)
: log_("/ssh/connection"),
peer_(peer),
pipe_(NULL),
splice_(NULL),
splice_action_(NULL),
close_action_(NULL)
{
pipe_ = new SSHTransportPipe();
EventCallback *rcb = callback(this, &SSHConnection::receive_complete);
receive_action_ = pipe_->receive(rcb);
splice_ = new Splice(log_ + "/splice", peer_, pipe_, peer_);
EventCallback *cb = callback(this, &SSHConnection::splice_complete);
splice_action_ = splice_->start(cb);
}
~SSHConnection()
{
ASSERT(close_action_ == NULL);
ASSERT(splice_action_ == NULL);
ASSERT(splice_ == NULL);
ASSERT(receive_action_ == NULL);
ASSERT(pipe_ == NULL);
ASSERT(peer_ == NULL);
}
private:
void receive_complete(Event e)
{
receive_action_->cancel();
receive_action_ = NULL;
switch (e.type_) {
case Event::Done:
break;
default:
ERROR(log_) << "Unexpected event while waiting for a packet: " << e;
return;
}
ASSERT(!e.buffer_.empty());
switch (e.buffer_.peek()) {
case SSH::Protocol::KeyExchangeInitializationMessage:
break;
default:
DEBUG(log_) << "Received packet:" << std::endl << e.buffer_.hexdump();
break;
}
EventCallback *rcb = callback(this, &SSHConnection::receive_complete);
receive_action_ = pipe_->receive(rcb);
}
void close_complete(void)
{
close_action_->cancel();
close_action_ = NULL;
ASSERT(peer_ != NULL);
delete peer_;
peer_ = NULL;
delete this;
}
void splice_complete(Event e)
{
splice_action_->cancel();
splice_action_ = NULL;
switch (e.type_) {
case Event::EOS:
DEBUG(log_) << "Peer exiting normally.";
break;
case Event::Error:
ERROR(log_) << "Peer exiting with error: " << e;
break;
default:
ERROR(log_) << "Peer exiting with unknown event: " << e;
break;
}
ASSERT(splice_ != NULL);
delete splice_;
splice_ = NULL;
if (receive_action_ != NULL) {
INFO(log_) << "Peer exiting while waiting for a packet.";
receive_action_->cancel();
receive_action_ = NULL;
}
ASSERT(pipe_ != NULL);
delete pipe_;
pipe_ = NULL;
ASSERT(close_action_ == NULL);
SimpleCallback *cb = callback(this, &SSHConnection::close_complete);
close_action_ = peer_->close(cb);
}
};
class SSHServer : public SimpleServer<TCPServer> {
public:
SSHServer(SocketAddressFamily family, const std::string& interface)
: SimpleServer<TCPServer>("/ssh/server", family, interface)
{ }
~SSHServer()
{ }
void client_connected(Socket *client)
{
new SSHConnection(client);
}
};
int
main(void)
{
new SSHServer(SocketAddressFamilyIP, "[::]:2299");
event_main();
}
<commit_msg>Add a basic transmit function, use it to mirror packets.<commit_after>#include <common/endian.h>
#include <event/event_callback.h>
#include <event/event_main.h>
#include <event/event_system.h>
#include <http/http_protocol.h>
#include <io/net/tcp_server.h>
#include <io/pipe/pipe.h>
#include <io/pipe/pipe_producer.h>
#include <io/pipe/splice.h>
#include <io/socket/simple_server.h>
#include <ssh/ssh_protocol.h>
namespace {
static uint8_t zero_padding[255];
}
class SSHTransportPipe : public PipeProducer {
enum State {
GetIdentificationString,
GetPacket
};
State state_;
Buffer input_buffer_;
/* XXX These parameters are different for receive and send. */
size_t block_size_;
size_t mac_length_;
EventCallback *receive_callback_;
Action *receive_action_;
public:
SSHTransportPipe(void)
: PipeProducer("/ssh/transport/pipe"),
state_(GetIdentificationString),
block_size_(8),
mac_length_(0),
receive_callback_(NULL),
receive_action_(NULL)
{
Buffer identification_string("SSH-2.0-WANProxy " + (std::string)log_ + "\r\n");
produce(&identification_string);
}
~SSHTransportPipe()
{
ASSERT(receive_callback_ == NULL);
ASSERT(receive_action_ == NULL);
}
Action *receive(EventCallback *cb)
{
ASSERT(receive_callback_ == NULL);
ASSERT(receive_action_ == NULL);
/*
* XXX
* This pattern is implemented about three different
* ways in the WANProxy codebase, and they are all kind
* of awful. Need a better way to handle code that
* needs executed either on the request of the caller
* or when data comes in that satisfies a deferred
* callback to a caller.
*/
receive_callback_ = cb;
receive_do();
if (receive_callback_ != NULL)
return (cancellation(this, &SSHTransportPipe::receive_cancel));
ASSERT(receive_action_ != NULL);
Action *a = receive_action_;
receive_action_ = NULL;
return (a);
}
/*
* Because this is primarily for WAN optimization we always use minimal
* padding and zero padding. Quick and dirty. Perhaps revisit later,
* although it makes send() asynchronous unless we add a blocking
* RNG interface.
*/
void send(Buffer *payload)
{
Buffer packet;
uint8_t padding_len;
uint32_t packet_len;
packet_len = sizeof padding_len + payload->length();
padding_len = 4 + (block_size_ - ((sizeof packet_len + packet_len + 4) % block_size_));
packet_len += padding_len;
packet_len = BigEndian::encode(packet_len);
packet.append(&packet_len);
packet.append(padding_len);
packet.append(payload);
packet.append(zero_padding, padding_len);
if (mac_length_ != 0)
NOTREACHED();
payload->clear();
produce(&packet);
}
private:
void consume(Buffer *in)
{
/* XXX XXX XXX */
if (in->empty()) {
if (!input_buffer_.empty())
DEBUG(log_) << "Received EOS with data outstanding.";
Buffer eos;
produce(&eos);
return;
}
input_buffer_.append(in);
in->clear();
if (state_ == GetIdentificationString) {
HTTPProtocol::ParseStatus status;
while (!input_buffer_.empty()) {
Buffer line;
status = HTTPProtocol::ExtractLine(&line, &input_buffer_);
switch (status) {
case HTTPProtocol::ParseSuccess:
break;
case HTTPProtocol::ParseFailure:
ERROR(log_) << "Invalid line while waiting for identification string.";
produce_error();
return;
case HTTPProtocol::ParseIncomplete:
/* Wait for more. */
return;
}
if (!line.prefix("SSH-"))
continue; /* Next line. */
if (!line.prefix("SSH-2.0")) {
ERROR(log_) << "Unsupported version.";
produce_error();
return;
}
state_ = GetPacket;
break;
}
}
if (state_ == GetPacket && receive_callback_ != NULL)
receive_do();
}
void receive_cancel(void)
{
if (receive_action_ != NULL) {
receive_action_->cancel();
receive_action_ = NULL;
}
if (receive_callback_ != NULL) {
delete receive_callback_;
receive_callback_ = NULL;
}
}
void receive_do(void)
{
ASSERT(receive_action_ == NULL);
ASSERT(receive_callback_ != NULL);
if (state_ != GetPacket)
return;
while (!input_buffer_.empty()) {
Buffer packet;
Buffer mac;
uint32_t packet_len;
uint8_t padding_len;
if (input_buffer_.length() <= sizeof packet_len) {
DEBUG(log_) << "Waiting for packet length.";
return;
}
input_buffer_.extract(&packet_len);
packet_len = BigEndian::decode(packet_len);
if (packet_len == 0) {
ERROR(log_) << "Need to handle 0-length packet.";
produce_error();
return;
}
if (input_buffer_.length() < sizeof packet_len + packet_len + mac_length_) {
DEBUG(log_) << "Need " << sizeof packet_len + packet_len + mac_length_ << "bytes; have " << input_buffer_.length() << ".";
return;
}
input_buffer_.moveout(&packet, sizeof packet_len, packet_len);
if (mac_length_ != 0)
input_buffer_.moveout(&mac, 0, mac_length_);
padding_len = packet.peek();
packet.skip(sizeof padding_len);
if (padding_len != 0) {
if (packet.length() < padding_len) {
ERROR(log_) << "Padding too large for packet.";
produce_error();
return;
}
packet.trim(padding_len);
}
if (packet.empty()) {
ERROR(log_) << "Need to handle empty packet.";
produce_error();
return;
}
/*
* XXX
* Handle Transport messages internally?
*/
receive_callback_->param(Event(Event::Done, packet));
receive_action_ = receive_callback_->schedule();
receive_callback_ = NULL;
return;
}
}
};
class SSHConnection {
LogHandle log_;
Socket *peer_;
SSHTransportPipe *pipe_;
Action *receive_action_;
Splice *splice_;
Action *splice_action_;
Action *close_action_;
public:
SSHConnection(Socket *peer)
: log_("/ssh/connection"),
peer_(peer),
pipe_(NULL),
splice_(NULL),
splice_action_(NULL),
close_action_(NULL)
{
pipe_ = new SSHTransportPipe();
EventCallback *rcb = callback(this, &SSHConnection::receive_complete);
receive_action_ = pipe_->receive(rcb);
splice_ = new Splice(log_ + "/splice", peer_, pipe_, peer_);
EventCallback *cb = callback(this, &SSHConnection::splice_complete);
splice_action_ = splice_->start(cb);
}
~SSHConnection()
{
ASSERT(close_action_ == NULL);
ASSERT(splice_action_ == NULL);
ASSERT(splice_ == NULL);
ASSERT(receive_action_ == NULL);
ASSERT(pipe_ == NULL);
ASSERT(peer_ == NULL);
}
private:
void receive_complete(Event e)
{
receive_action_->cancel();
receive_action_ = NULL;
switch (e.type_) {
case Event::Done:
break;
default:
ERROR(log_) << "Unexpected event while waiting for a packet: " << e;
return;
}
ASSERT(!e.buffer_.empty());
/*
* SSH Echo!
*/
pipe_->send(&e.buffer_);
#if 0
switch (e.buffer_.peek()) {
case SSH::Protocol::KeyExchangeInitializationMessage:
break;
default:
DEBUG(log_) << "Received packet:" << std::endl << e.buffer_.hexdump();
break;
}
#endif
EventCallback *rcb = callback(this, &SSHConnection::receive_complete);
receive_action_ = pipe_->receive(rcb);
}
void close_complete(void)
{
close_action_->cancel();
close_action_ = NULL;
ASSERT(peer_ != NULL);
delete peer_;
peer_ = NULL;
delete this;
}
void splice_complete(Event e)
{
splice_action_->cancel();
splice_action_ = NULL;
switch (e.type_) {
case Event::EOS:
DEBUG(log_) << "Peer exiting normally.";
break;
case Event::Error:
ERROR(log_) << "Peer exiting with error: " << e;
break;
default:
ERROR(log_) << "Peer exiting with unknown event: " << e;
break;
}
ASSERT(splice_ != NULL);
delete splice_;
splice_ = NULL;
if (receive_action_ != NULL) {
INFO(log_) << "Peer exiting while waiting for a packet.";
receive_action_->cancel();
receive_action_ = NULL;
}
ASSERT(pipe_ != NULL);
delete pipe_;
pipe_ = NULL;
ASSERT(close_action_ == NULL);
SimpleCallback *cb = callback(this, &SSHConnection::close_complete);
close_action_ = peer_->close(cb);
}
};
class SSHServer : public SimpleServer<TCPServer> {
public:
SSHServer(SocketAddressFamily family, const std::string& interface)
: SimpleServer<TCPServer>("/ssh/server", family, interface)
{ }
~SSHServer()
{ }
void client_connected(Socket *client)
{
new SSHConnection(client);
}
};
int
main(void)
{
new SSHServer(SocketAddressFamilyIP, "[::]:2299");
event_main();
}
<|endoftext|>
|
<commit_before>// terark-db-schema-compile.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#define TERARK_DB_SCHEMA_COMPILER
#include <terark/db/db_conf.cpp>
#if defined(_WIN32) || defined(_WIN64)
#include <getopt.c>
#endif
using namespace std;
using namespace terark;
using namespace terark::db;
int maxColnameLen(const Schema& schema) {
const size_t colnum = schema.columnNum();
int maxNameLen = 0;
for (size_t i = 0; i < colnum; ++i) {
const fstring colname = schema.getColumnName(i);
maxNameLen = std::max(maxNameLen, colname.ilen());
}
return maxNameLen;
}
void compileOneSchema(const Schema& schema, const char* className,
const char* rowClassName) {
const size_t colnum = schema.columnNum();
printf(" struct %s {\n", className);
for (size_t i = 0; i < colnum; ++i) {
const ColumnMeta& colmeta = schema.getColumnMeta(i);
const fstring colname = schema.getColumnName(i);
switch (colmeta.type) {
case ColumnType::Any:
assert(0); // not supported now
break;
case ColumnType::Nested:
assert(0); // not supported now
break;
case ColumnType::Uint08:
printf(" unsigned char %s;\n", colname.p);
break;
case ColumnType::Sint08:
printf(" signed char %s;\n", colname.p);
break;
case ColumnType::Uint16:
printf(" std::uint16_t %s;\n", colname.p);
break;
case ColumnType::Sint16:
printf(" std::int16_t %s;\n", colname.p);
break;
case ColumnType::Uint32:
printf(" std::uint32_t %s;\n", colname.p);
break;
case ColumnType::Sint32:
printf(" std::int32_t %s;\n", colname.p);
break;
case ColumnType::Uint64:
printf(" std::uint64_t %s;\n", colname.p);
break;
case ColumnType::Sint64:
printf(" std::int64_t %s;\n", colname.p);
break;
case ColumnType::Uint128:
printf(" unsigned __int128 %s;\n", colname.p);
break;
case ColumnType::Sint128:
printf(" signed __int128 %s;\n", colname.p);
break;
case ColumnType::Float32:
printf(" float %s;\n", colname.p);
break;
case ColumnType::Float64:
printf(" double %s;\n", colname.p);
break;
case ColumnType::Float128:
printf(" __float128 %s;\n", colname.p);
break;
case ColumnType::Decimal128:
printf(" __decimal128 %s;\n", colname.p);
break;
case ColumnType::Uuid:
printf(" terark::db::Schema::Fixed<16> %s;\n", colname.p);
break;
case ColumnType::Fixed:
if (colmeta.realtype.empty()) {
printf(" terark::db::Schema::Fixed<%d> %s;\n", int(colmeta.fixedLen), colname.p);
}
else {
const char* realtype = colmeta.realtype.c_str();
const int fixlen = int(colmeta.fixedLen);
printf(R"EOS(
%s %s;
// dumpable type does not require sizeof(T)==fixlen, it only requires that
// dump_size(T)==fixlen, but check for dump_size(T)==fixlen is cumbersome
// and requires big changes for terark.dataio
// so we static assert sizeof(T)==fixlen here:
BOOST_STATIC_ASSERT(sizeof(%s) == %d);
BOOST_STATIC_ASSERT((terark::DataIO_is_dump<terark::NativeDataInput<terark::MemIO>, %s >::value));
)EOS", realtype, colname.p, realtype, fixlen, realtype);
}
break;
case ColumnType::VarSint:
printf(" terark::var_int64_t %s;\n", colname.p);
break;
case ColumnType::VarUint:
printf(" terark::var_uint64_t %s;\n", colname.p);
break;
case ColumnType::StrZero:
printf(" std::string %s;\n", colname.p);
break;
case ColumnType::TwoStrZero:
printf(" terark::db::Schema::TwoStrZero %s;\n", colname.p);
break;
case ColumnType::Binary:
if (colmeta.realtype.empty()) {
printf(" std::string %s;\n", colname.p);
}
else {
const char* realtype = colmeta.realtype.c_str();
printf(" %s %s;\n", realtype, colname.p);
}
break;
case ColumnType::CarBin:
if (colmeta.realtype.empty()) {
printf(" terark::db::Schema::CarBin %s;\n", colname.p);
}
else {
const char* realtype = colmeta.realtype.c_str();
printf(" %s %s;\n", realtype, colname.p);
}
break;
}
}
printf("\n");
printf(" DATA_IO_LOAD_SAVE(%s,\n", className);
for (size_t i = 0; i < colnum; ++i) {
const ColumnMeta& colmeta = schema.getColumnMeta(i);
const fstring colname = schema.getColumnName(i);
switch (colmeta.type) {
case ColumnType::Any:
assert(0); // not supported now
break;
case ColumnType::Nested:
assert(0); // not supported now
break;
case ColumnType::Uint08:
case ColumnType::Sint08:
case ColumnType::Uint16:
case ColumnType::Sint16:
case ColumnType::Uint32:
case ColumnType::Sint32:
case ColumnType::Uint64:
case ColumnType::Sint64:
case ColumnType::Uint128:
case ColumnType::Sint128:
case ColumnType::Float32:
case ColumnType::Float64:
case ColumnType::Float128:
case ColumnType::Decimal128:
case ColumnType::Uuid:
case ColumnType::Fixed:
case ColumnType::VarSint:
case ColumnType::VarUint:
printf(" &%s\n", colname.p);
break;
case ColumnType::StrZero:
if (i < colnum-1) {
printf(" &terark::db::Schema::StrZero(%s)\n", colname.p);
} else {
printf(" &terark::RestAll(%s)\n", colname.p);
}
break;
case ColumnType::TwoStrZero:
case ColumnType::Binary:
Case_Binary:
if (i < colnum-1) {
printf(" &%s\n", colname.p);
} else {
printf(" &terark::RestAll(%s)\n", colname.p);
}
break;
case ColumnType::CarBin:
if (colmeta.realtype.empty()) {
goto Case_Binary;
}
if (i < colnum-1) {
// read carbin size and check carbin size with real size
printf(" &terark::db::Schema::CarBinPack(%s)\n", colname.p);
} else {
printf(" &%s\n", colname.p);
}
break;
}
}
printf(" )\n");
printf(
R"EOS(
%s& decode(terark::fstring ___row) {
terark::NativeDataInput<terark::MemIO> ___dio(___row.range());
___dio >> *this;
return *this;
}
terark::fstring
encode(terark::NativeDataOutput<terark::AutoGrownMemIO>& ___dio) const {
___dio.rewind();
___dio << *this;
return ___dio.written();
}
)EOS", className
);
int maxNameLen = maxColnameLen(schema);
printf(" %s& select(const %s& ___row) {\n", className, rowClassName);
for (size_t i = 0; i < colnum; ++i) {
const char* colname = schema.getColumnName(i).c_str();
printf(" %-*s = ___row.%s;\n", maxNameLen, colname, colname);
}
printf(" return *this;\n"); // select
printf(" }\n"); // select
printf(" void assign_to(%s& ___row) const {\n", rowClassName);
for (size_t i = 0; i < colnum; ++i) {
const char* colname = schema.getColumnName(i).c_str();
printf(" ___row.%-*s = %s;\n", maxNameLen, colname, colname);
}
printf(" }\n"); // select
printf(" }; // %s\n\n", className);
}
int usage(const char* prog) {
fprintf(stderr, "usage: %s [ options ] terark-db-schema-file namespace table-name\n", prog);
return 1;
}
int main(int argc, char* argv[]) {
std::vector<const char*> includes;
for (;;) {
int opt = getopt(argc, argv, "i:");
switch (opt) {
case -1:
goto GetoptDone;
case '?':
return usage(argv[0]);
case 'i':
includes.push_back(optarg);
break;
}
}
GetoptDone:
if (argc - optind < 3) {
return usage(argv[0]);
}
const char* jsonFilePath = argv[optind + 0];
const char* ns = argv[optind + 1];
const char* tabName = argv[optind + 2];
SchemaConfig sconf;
try {
sconf.loadJsonFile(jsonFilePath);
}
catch (const std::exception& ex) {
fprintf(stderr, "ERROR: loadJsonFile(%s) failed: %s\n", jsonFilePath, ex.what());
return 1;
}
printf(R"EOS(#pragma once
#include <terark/db/db_table.hpp>
#include <terark/io/DataIO.hpp>
#include <terark/io/MemStream.hpp>
#include <terark/io/RangeStream.hpp>
#include <boost/static_assert.hpp>
)EOS");
for (const char* inc : includes) {
printf("#include \"%s\"\n", inc);
}
printf("\n");
printf("namespace %s {\n", ns);
compileOneSchema(*sconf.m_rowSchema, tabName, tabName);
for (size_t i = 0; i < sconf.m_colgroupSchemaSet->indexNum(); ++i) {
const Schema& schema = *sconf.m_colgroupSchemaSet->getSchema(i);
if (schema.columnNum() == 1)
continue;
std::string cgName = schema.m_name;
std::transform(cgName.begin(), cgName.end(), cgName.begin(),
[](unsigned char ch) -> char {
if (isalnum(ch) || '_' == ch)
return ch;
else
return '_';
});
std::string className = tabName;
className += "_Colgroup_";
className += cgName;
compileOneSchema(schema, className.c_str(), tabName);
if (i < sconf.m_indexSchemaSet->indexNum()) {
printf(" typedef %s %s_Index_%s;\n\n", className.c_str(), tabName, cgName.c_str());
}
}
printf("} // namespace %s\n", ns);
return 0;
}
<commit_msg>terark-db-schema-compile: Add checkSchema()<commit_after>// terark-db-schema-compile.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#define TERARK_DB_SCHEMA_COMPILER
#include <terark/db/db_conf.cpp>
#if defined(_WIN32) || defined(_WIN64)
#include <getopt.c>
#endif
using namespace std;
using namespace terark;
using namespace terark::db;
int maxColnameLen(const Schema& schema) {
const size_t colnum = schema.columnNum();
int maxNameLen = 0;
for (size_t i = 0; i < colnum; ++i) {
const fstring colname = schema.getColumnName(i);
maxNameLen = std::max(maxNameLen, colname.ilen());
}
return maxNameLen;
}
void compileOneSchema(const Schema& schema, const char* className,
const char* rowClassName) {
const size_t colnum = schema.columnNum();
printf(" struct %s {\n", className);
for (size_t i = 0; i < colnum; ++i) {
const ColumnMeta& colmeta = schema.getColumnMeta(i);
const fstring colname = schema.getColumnName(i);
switch (colmeta.type) {
case ColumnType::Any:
assert(0); // not supported now
break;
case ColumnType::Nested:
assert(0); // not supported now
break;
case ColumnType::Uint08:
printf(" unsigned char %s;\n", colname.p);
break;
case ColumnType::Sint08:
printf(" signed char %s;\n", colname.p);
break;
case ColumnType::Uint16:
printf(" std::uint16_t %s;\n", colname.p);
break;
case ColumnType::Sint16:
printf(" std::int16_t %s;\n", colname.p);
break;
case ColumnType::Uint32:
printf(" std::uint32_t %s;\n", colname.p);
break;
case ColumnType::Sint32:
printf(" std::int32_t %s;\n", colname.p);
break;
case ColumnType::Uint64:
printf(" std::uint64_t %s;\n", colname.p);
break;
case ColumnType::Sint64:
printf(" std::int64_t %s;\n", colname.p);
break;
case ColumnType::Uint128:
printf(" unsigned __int128 %s;\n", colname.p);
break;
case ColumnType::Sint128:
printf(" signed __int128 %s;\n", colname.p);
break;
case ColumnType::Float32:
printf(" float %s;\n", colname.p);
break;
case ColumnType::Float64:
printf(" double %s;\n", colname.p);
break;
case ColumnType::Float128:
printf(" __float128 %s;\n", colname.p);
break;
case ColumnType::Decimal128:
printf(" __decimal128 %s;\n", colname.p);
break;
case ColumnType::Uuid:
printf(" terark::db::Schema::Fixed<16> %s;\n", colname.p);
break;
case ColumnType::Fixed:
if (colmeta.realtype.empty()) {
printf(" terark::db::Schema::Fixed<%d> %s;\n", int(colmeta.fixedLen), colname.p);
}
else {
const char* realtype = colmeta.realtype.c_str();
const int fixlen = int(colmeta.fixedLen);
printf(R"EOS(
%s %s;
// dumpable type does not require sizeof(T)==fixlen, it only requires that
// dump_size(T)==fixlen, but check for dump_size(T)==fixlen is cumbersome
// and requires big changes for terark.dataio
// so we static assert sizeof(T)==fixlen here:
BOOST_STATIC_ASSERT(sizeof(%s) == %d);
BOOST_STATIC_ASSERT((terark::DataIO_is_dump<terark::NativeDataInput<terark::MemIO>, %s >::value));
)EOS", realtype, colname.p, realtype, fixlen, realtype);
}
break;
case ColumnType::VarSint:
printf(" terark::var_int64_t %s;\n", colname.p);
break;
case ColumnType::VarUint:
printf(" terark::var_uint64_t %s;\n", colname.p);
break;
case ColumnType::StrZero:
printf(" std::string %s;\n", colname.p);
break;
case ColumnType::TwoStrZero:
printf(" terark::db::Schema::TwoStrZero %s;\n", colname.p);
break;
case ColumnType::Binary:
if (colmeta.realtype.empty()) {
printf(" std::string %s;\n", colname.p);
}
else {
const char* realtype = colmeta.realtype.c_str();
printf(" %s %s;\n", realtype, colname.p);
}
break;
case ColumnType::CarBin:
if (colmeta.realtype.empty()) {
printf(" terark::db::Schema::CarBin %s;\n", colname.p);
}
else {
const char* realtype = colmeta.realtype.c_str();
printf(" %s %s;\n", realtype, colname.p);
}
break;
}
}
printf("\n");
printf(" DATA_IO_LOAD_SAVE(%s,\n", className);
for (size_t i = 0; i < colnum; ++i) {
const ColumnMeta& colmeta = schema.getColumnMeta(i);
const fstring colname = schema.getColumnName(i);
switch (colmeta.type) {
case ColumnType::Any:
assert(0); // not supported now
break;
case ColumnType::Nested:
assert(0); // not supported now
break;
case ColumnType::Uint08:
case ColumnType::Sint08:
case ColumnType::Uint16:
case ColumnType::Sint16:
case ColumnType::Uint32:
case ColumnType::Sint32:
case ColumnType::Uint64:
case ColumnType::Sint64:
case ColumnType::Uint128:
case ColumnType::Sint128:
case ColumnType::Float32:
case ColumnType::Float64:
case ColumnType::Float128:
case ColumnType::Decimal128:
case ColumnType::Uuid:
case ColumnType::Fixed:
case ColumnType::VarSint:
case ColumnType::VarUint:
printf(" &%s\n", colname.p);
break;
case ColumnType::StrZero:
if (i < colnum-1) {
printf(" &terark::db::Schema::StrZero(%s)\n", colname.p);
} else {
printf(" &terark::RestAll(%s)\n", colname.p);
}
break;
case ColumnType::TwoStrZero:
case ColumnType::Binary:
Case_Binary:
if (i < colnum-1) {
printf(" &%s\n", colname.p);
} else {
printf(" &terark::RestAll(%s)\n", colname.p);
}
break;
case ColumnType::CarBin:
if (colmeta.realtype.empty()) {
goto Case_Binary;
}
if (i < colnum-1) {
// read carbin size and check carbin size with real size
printf(" &terark::db::Schema::CarBinPack(%s)\n", colname.p);
} else {
printf(" &%s\n", colname.p);
}
break;
}
}
printf(" )\n");
printf(
R"EOS(
%s& decode(terark::fstring ___row) {
terark::NativeDataInput<terark::MemIO> ___dio(___row.range());
___dio >> *this;
return *this;
}
terark::fstring
encode(terark::NativeDataOutput<terark::AutoGrownMemIO>& ___dio) const {
___dio.rewind();
___dio << *this;
return ___dio.written();
}
)EOS", className
);
if (fstring(className) != rowClassName) {
int maxNameLen = maxColnameLen(schema);
printf(" %s& select(const %s& ___row) {\n", className, rowClassName);
for (size_t i = 0; i < colnum; ++i) {
const char* colname = schema.getColumnName(i).c_str();
printf(" %-*s = ___row.%s;\n", maxNameLen, colname, colname);
}
printf(" return *this;\n"); // select
printf(" }\n"); // select
printf(" void assign_to(%s& ___row) const {\n", rowClassName);
for (size_t i = 0; i < colnum; ++i) {
const char* colname = schema.getColumnName(i).c_str();
printf(" ___row.%-*s = %s;\n", maxNameLen, colname, colname);
}
printf(" }\n"); // select
}
printf(
R"EOS(
static const terark::db::Schema& getSchema() {
using namespace terark::db;
static Schema schema;
// static std::mutex mtx;
// std::unique_lock<std::mutex> lock(mtx);
if (schema.columnNum() == 0) {
)EOS");
for (size_t i = 0; i < colnum; ++i) {
const char* colname = schema.getColumnName(i).c_str();
const auto& colmeta = schema.getColumnMeta(i);
printf(
R"EOS( {
ColumnMeta colmeta(ColumnType::%s);
colmeta.fixedLen = %d;
schema.m_columnsMeta.insert_i("%s", colmeta);
}
)EOS", colmeta.typeNameString(), colmeta.fixedLen, colname
);
}
printf(
R"EOS( }
return schema;
}
)EOS"); // getSchema
printf(
R"EOS(
static bool
checkSchema(const terark::db::Schema& schema, bool checkColname = false) {
using namespace terark;
using namespace terark::db;
if (schema.columnNum() != %zd) {
return false;
}
)EOS", colnum);
for (size_t i = 0; i < colnum; ++i) {
const char* colname = schema.getColumnName(i).c_str();
const auto& colmeta = schema.getColumnMeta(i);
size_t fixlen = colmeta.fixedLen;
printf(
R"EOS( {
const fstring colname = schema.getColumnName(%zd);
const ColumnMeta& colmeta = schema.getColumnMeta(%zd);
if (checkColname && colname != "%s") {
return false;
}
if (colmeta.type != ColumnType::%s) {
return false;
}
if (colmeta.fixedLen != %zd) {
assert(colmeta.type == ColumnType::Fixed);
return false;
}
}
)EOS", i, i, colname, colmeta.typeNameString(), fixlen);
}
printf(
R"EOS( return true;
}
)EOS"); // checkSchema
printf(" }; // %s\n\n", className);
}
int usage(const char* prog) {
fprintf(stderr, "usage: %s [ options ] terark-db-schema-file namespace table-name\n", prog);
return 1;
}
int main(int argc, char* argv[]) {
std::vector<const char*> includes;
for (;;) {
int opt = getopt(argc, argv, "i:");
switch (opt) {
case -1:
goto GetoptDone;
case '?':
return usage(argv[0]);
case 'i':
includes.push_back(optarg);
break;
}
}
GetoptDone:
if (argc - optind < 3) {
return usage(argv[0]);
}
const char* jsonFilePath = argv[optind + 0];
const char* ns = argv[optind + 1];
const char* tabName = argv[optind + 2];
SchemaConfig sconf;
try {
sconf.loadJsonFile(jsonFilePath);
}
catch (const std::exception& ex) {
fprintf(stderr, "ERROR: loadJsonFile(%s) failed: %s\n", jsonFilePath, ex.what());
return 1;
}
printf(R"EOS(#pragma once
#include <terark/db/db_table.hpp>
#include <terark/io/DataIO.hpp>
#include <terark/io/MemStream.hpp>
#include <terark/io/RangeStream.hpp>
#include <boost/static_assert.hpp>
)EOS");
for (const char* inc : includes) {
printf("#include \"%s\"\n", inc);
}
printf("\n");
printf("namespace %s {\n", ns);
compileOneSchema(*sconf.m_rowSchema, tabName, tabName);
for (size_t i = 0; i < sconf.m_colgroupSchemaSet->indexNum(); ++i) {
const Schema& schema = *sconf.m_colgroupSchemaSet->getSchema(i);
if (schema.columnNum() == 1)
continue;
std::string cgName = schema.m_name;
std::transform(cgName.begin(), cgName.end(), cgName.begin(),
[](unsigned char ch) -> char {
if (isalnum(ch) || '_' == ch)
return ch;
else
return '_';
});
std::string className = tabName;
className += "_Colgroup_";
className += cgName;
compileOneSchema(schema, className.c_str(), tabName);
if (i < sconf.m_indexSchemaSet->indexNum()) {
printf(" typedef %s %s_Index_%s;\n\n", className.c_str(), tabName, cgName.c_str());
}
}
printf("} // namespace %s\n", ns);
return 0;
}
<|endoftext|>
|
<commit_before>//=============================================================================================================
/**
* @file main.cpp
* @author Ruben Dörfel <ruben.doerfel@tu-ilmenau.de>;
* Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version 1.0
* @date 11, 2019
*
* @section LICENSE
*
* Copyright (C) 2019, Ruben Doerrfel and Matti Hamalainen. 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 MNE-CPP authors 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.
*
*
* @brief Example for filtering of data with realtime filtering. This example is combined with
* ex_read_write_raw for reading and writing fiff files. So the result of the filtering can be seen
* in MNE-Browse.
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include <iostream>
#include <vector>
#include <math.h>
#include <fiff/fiff.h>
#include <utils/filterTools/filterdata.h>
#include <rtprocessing/rtfilter.h>
#include <utils/ioutils.h>
//*************************************************************************************************************
//=============================================================================================================
// Qt INCLUDES
//=============================================================================================================
#include <QtCore/QCoreApplication>
#include <QFile>
#include <QCommandLineParser>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace FIFFLIB;
using namespace UTILSLIB;
using namespace RTPROCESSINGLIB;
//*************************************************************************************************************
//=============================================================================================================
// MAIN
//=============================================================================================================
//=============================================================================================================
/**
* The function main marks the entry point of the program.
* By default, main has the storage class extern.
*
* @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.
* @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.
* @return the value that was set to exit() (which is 0 if exit() is called via quit()).
*/
int main(int argc, char *argv[])
{
QElapsedTimer timer;
QCoreApplication a(argc, argv);
// Command Line Parser
QCommandLineParser parser;
parser.setApplicationDescription("Read Write Raw Example");
parser.addHelpOption();
QCommandLineOption inputOption("fileIn", "The input file <in>.", "in", QCoreApplication::applicationDirPath() + "/MNE-sample-data/MEG/sample/sample_audvis_raw.fif");
QCommandLineOption outputOption("fileOut", "The output file <out>.", "out", QCoreApplication::applicationDirPath() + "/MNE-sample-data/MEG/sample/test_output.fif");
parser.addOption(inputOption);
parser.addOption(outputOption);
parser.process(a);
// Init data loading and writing
QFile t_fileIn(parser.value(inputOption));
QFile t_fileOut(parser.value(outputOption));
FiffRawData raw(t_fileIn);
// Set up pick list: MEG + STI 014 - bad channels
bool want_meg = true;
bool want_eeg = true;
bool want_stim = true;
QStringList include;
include << "STI 014";
MatrixXi picks = raw.info.pick_types(want_meg, want_eeg, want_stim, include, raw.info.bads);
if(picks.cols() == 0) {
include.clear();
include << "STI101" << "STI201" << "STI301";
picks = raw.info.pick_types(want_meg, want_eeg, want_stim, include, raw.info.bads);
if(picks.cols() == 0) {
printf("channel list may need modification\n");
return -1;
}
}
RowVectorXd cals;
FiffStream::SPtr outfid = FiffStream::start_writing_raw(t_fileOut, raw.info, cals/*, picks*/);
// Set up the reading parameters
fiff_int_t from = raw.first_samp;
fiff_int_t to = raw.last_samp;
// To read the whole file at once set quantum = to - from + 1;
fiff_int_t quantum = to - from + 1;
// Read and write the data
bool first_buffer = true;
fiff_int_t first, last;
MatrixXd data;
MatrixXd times;
// initialize filter settings
QString filter_name = "example_cosine";
FilterData::FilterType type = FilterData::BPF;
double sFreq = raw.info.sfreq; // get Sample freq from Data
double centerfreq = 10/(sFreq/2.0); // normed nyquist freq.
double bandwidth = 10/(sFreq/2.0);
double parkswidth = 1/(sFreq/2.0);
RtFilter rtFilter; // filter object
MatrixXd dataFiltered; // filter output
// channel selection - in this case use every channel
// size = number of channels; value = index channel number
QVector<int> channelList(raw.info.nchan);
for (int i = 0; i < raw.info.nchan; i++){
channelList[i] = i;
}
for(first = from; first < to; first+=quantum) {
last = first+quantum-1;
if (last > to) {
last = to;
}
if(!raw.read_raw_segment(data,times,first,last/*,picks*/)) {
printf("error during read_raw_segment\n");
return -1;
}
//Filtering
printf("Filtering...");
dataFiltered = rtFilter.filterData(data,type,centerfreq,bandwidth,parkswidth,sFreq,channelList);
printf("[done]\n");
//Writing
printf("Writing...");
if(first_buffer) {
if(first > 0) {
outfid->write_int(FIFF_FIRST_SAMPLE, &first);
}
first_buffer = false;
}
outfid->write_raw_buffer(dataFiltered,cals);
printf("[done]\n");
}
outfid->finish_writing_raw();
printf("Finished\n");
return 0;
}
<commit_msg>ex_filtering: remove Timer for performance testing<commit_after>//=============================================================================================================
/**
* @file main.cpp
* @author Ruben Dörfel <ruben.doerfel@tu-ilmenau.de>;
* Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version 1.0
* @date 11, 2019
*
* @section LICENSE
*
* Copyright (C) 2019, Ruben Doerrfel and Matti Hamalainen. 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 MNE-CPP authors 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.
*
*
* @brief Example for filtering of data with realtime filtering. This example is combined with
* ex_read_write_raw for reading and writing fiff files. So the result of the filtering can be seen
* in MNE-Browse.
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include <iostream>
#include <vector>
#include <math.h>
#include <fiff/fiff.h>
#include <utils/filterTools/filterdata.h>
#include <rtprocessing/rtfilter.h>
#include <utils/ioutils.h>
//*************************************************************************************************************
//=============================================================================================================
// Qt INCLUDES
//=============================================================================================================
#include <QtCore/QCoreApplication>
#include <QFile>
#include <QCommandLineParser>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace FIFFLIB;
using namespace UTILSLIB;
using namespace RTPROCESSINGLIB;
//*************************************************************************************************************
//=============================================================================================================
// MAIN
//=============================================================================================================
//=============================================================================================================
/**
* The function main marks the entry point of the program.
* By default, main has the storage class extern.
*
* @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.
* @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.
* @return the value that was set to exit() (which is 0 if exit() is called via quit()).
*/
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// Command Line Parser
QCommandLineParser parser;
parser.setApplicationDescription("Read Write Raw Example");
parser.addHelpOption();
QCommandLineOption inputOption("fileIn", "The input file <in>.", "in", QCoreApplication::applicationDirPath() + "/MNE-sample-data/MEG/sample/sample_audvis_raw.fif");
QCommandLineOption outputOption("fileOut", "The output file <out>.", "out", QCoreApplication::applicationDirPath() + "/MNE-sample-data/MEG/sample/test_output.fif");
parser.addOption(inputOption);
parser.addOption(outputOption);
parser.process(a);
// Init data loading and writing
QFile t_fileIn(parser.value(inputOption));
QFile t_fileOut(parser.value(outputOption));
FiffRawData raw(t_fileIn);
// Set up pick list: MEG + STI 014 - bad channels
bool want_meg = true;
bool want_eeg = true;
bool want_stim = true;
QStringList include;
include << "STI 014";
MatrixXi picks = raw.info.pick_types(want_meg, want_eeg, want_stim, include, raw.info.bads);
if(picks.cols() == 0) {
include.clear();
include << "STI101" << "STI201" << "STI301";
picks = raw.info.pick_types(want_meg, want_eeg, want_stim, include, raw.info.bads);
if(picks.cols() == 0) {
printf("channel list may need modification\n");
return -1;
}
}
RowVectorXd cals;
FiffStream::SPtr outfid = FiffStream::start_writing_raw(t_fileOut, raw.info, cals/*, picks*/);
// Set up the reading parameters
fiff_int_t from = raw.first_samp;
fiff_int_t to = raw.last_samp;
// To read the whole file at once set quantum = to - from + 1;
fiff_int_t quantum = to - from + 1;
// Read and write the data
bool first_buffer = true;
fiff_int_t first, last;
MatrixXd data;
MatrixXd times;
// initialize filter settings
QString filter_name = "example_cosine";
FilterData::FilterType type = FilterData::BPF;
double sFreq = raw.info.sfreq; // get Sample freq from Data
double centerfreq = 10/(sFreq/2.0); // normed nyquist freq.
double bandwidth = 10/(sFreq/2.0);
double parkswidth = 1/(sFreq/2.0);
RtFilter rtFilter; // filter object
MatrixXd dataFiltered; // filter output
// channel selection - in this case use every channel
// size = number of channels; value = index channel number
QVector<int> channelList(raw.info.nchan);
for (int i = 0; i < raw.info.nchan; i++){
channelList[i] = i;
}
for(first = from; first < to; first+=quantum) {
last = first+quantum-1;
if (last > to) {
last = to;
}
if(!raw.read_raw_segment(data,times,first,last/*,picks*/)) {
printf("error during read_raw_segment\n");
return -1;
}
//Filtering
printf("Filtering...");
dataFiltered = rtFilter.filterData(data,type,centerfreq,bandwidth,parkswidth,sFreq,channelList);
printf("[done]\n");
//Writing
printf("Writing...");
if(first_buffer) {
if(first > 0) {
outfid->write_int(FIFF_FIRST_SAMPLE, &first);
}
first_buffer = false;
}
outfid->write_raw_buffer(dataFiltered,cals);
printf("[done]\n");
}
outfid->finish_writing_raw();
printf("Finished\n");
return 0;
}
<|endoftext|>
|
<commit_before>#ifndef STAN_MATH_REV_FUN_SQUARED_DISTANCE_HPP
#define STAN_MATH_REV_FUN_SQUARED_DISTANCE_HPP
#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/squared_distance.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/fun/to_ref.hpp>
#include <stan/math/prim/fun/typedefs.hpp>
#include <vector>
namespace stan {
namespace math {
/**
* Returns the squared distance.
*/
inline var squared_distance(const var& a, const var& b) {
check_finite("squared_distance", "a", a);
check_finite("squared_distance", "b", b);
return make_callback_vari(std::pow(a.val() - b.val(), 2),
[a, b](const auto& vi) mutable {
const double diff = 2.0 * (a.val() - b.val());
a.adj() += vi.adj_ * diff;
b.adj() -= vi.adj_ * diff;
});
}
/**
* Returns the squared distance.
*/
inline var squared_distance(const var& a, double b) {
check_finite("squared_distance", "a", a);
check_finite("squared_distance", "b", b);
return make_callback_vari(std::pow(a.val() - b, 2),
[a, b](const auto& vi) mutable {
a.adj() += vi.adj_ * 2.0 * (a.val() - b);
});
}
/**
* Returns the squared distance.
*/
inline var squared_distance(double a, const var& b) {
return squared_distance(b, a);
}
namespace internal {
class squared_distance_vv_vari : public vari {
protected:
vari** v1_;
vari** v2_;
size_t length_;
public:
template <
typename EigVecVar1, typename EigVecVar2,
require_all_eigen_vector_vt<is_var, EigVecVar1, EigVecVar2>* = nullptr>
squared_distance_vv_vari(const EigVecVar1& v1, const EigVecVar2& v2)
: vari((as_column_vector_or_scalar(v1).val()
- as_column_vector_or_scalar(v2).val())
.squaredNorm()),
length_(v1.size()) {
v1_ = reinterpret_cast<vari**>(
ChainableStack::instance_->memalloc_.alloc(length_ * sizeof(vari*)));
v2_ = reinterpret_cast<vari**>(
ChainableStack::instance_->memalloc_.alloc(length_ * sizeof(vari*)));
Eigen::Map<vector_vi>(v1_, length_) = v1.vi();
Eigen::Map<vector_vi>(v2_, length_) = v2.vi();
}
virtual void chain() {
Eigen::Map<vector_vi> v1_map(v1_, length_);
Eigen::Map<vector_vi> v2_map(v2_, length_);
vector_d di = 2 * adj_ * (v1_map.val() - v2_map.val());
v1_map.adj() += di;
v2_map.adj() -= di;
}
};
class squared_distance_vd_vari : public vari {
protected:
vari** v1_;
double* v2_;
size_t length_;
public:
template <typename EigVecVar, typename EigVecArith,
require_eigen_vector_vt<is_var, EigVecVar>* = nullptr,
require_eigen_vector_vt<std::is_arithmetic, EigVecArith>* = nullptr>
squared_distance_vd_vari(const EigVecVar& v1, const EigVecArith& v2)
: vari((as_column_vector_or_scalar(v1).val()
- as_column_vector_or_scalar(v2))
.squaredNorm()),
length_(v1.size()) {
v1_ = reinterpret_cast<vari**>(
ChainableStack::instance_->memalloc_.alloc(length_ * sizeof(vari*)));
v2_ = reinterpret_cast<double*>(
ChainableStack::instance_->memalloc_.alloc(length_ * sizeof(double)));
Eigen::Map<vector_vi>(v1_, length_) = v1.vi();
Eigen::Map<vector_d>(v2_, length_) = v2;
}
virtual void chain() {
Eigen::Map<vector_vi> v1_map(v1_, length_);
v1_map.adj()
+= 2 * adj_ * (v1_map.val() - Eigen::Map<vector_d>(v2_, length_));
}
};
} // namespace internal
template <
typename EigVecVar1, typename EigVecVar2,
require_all_eigen_vector_vt<is_var, EigVecVar1, EigVecVar2>* = nullptr>
inline var squared_distance(const EigVecVar1& v1, const EigVecVar2& v2) {
check_matching_sizes("squared_distance", "v1", v1, "v2", v2);
return {new internal::squared_distance_vv_vari(to_ref(v1), to_ref(v2))};
}
template <typename EigVecVar, typename EigVecArith,
require_eigen_vector_vt<is_var, EigVecVar>* = nullptr,
require_eigen_vector_vt<std::is_arithmetic, EigVecArith>* = nullptr>
inline var squared_distance(const EigVecVar& v1, const EigVecArith& v2) {
check_matching_sizes("squared_distance", "v1", v1, "v2", v2);
return {new internal::squared_distance_vd_vari(to_ref(v1), to_ref(v2))};
}
template <typename EigVecArith, typename EigVecVar,
require_eigen_vector_vt<std::is_arithmetic, EigVecArith>* = nullptr,
require_eigen_vector_vt<is_var, EigVecVar>* = nullptr>
inline var squared_distance(const EigVecArith& v1, const EigVecVar& v2) {
check_matching_sizes("squared_distance", "v1", v1, "v2", v2);
return {new internal::squared_distance_vd_vari(to_ref(v2), to_ref(v1))};
}
/**
* Compute the squared distance between the elements in
* two inputs.
*
* This overload handles arguments where one of T1 or T2 are
* `var_value<T>` where `T` is an Eigen type. The other type can
* also be a `var_value` or it can be a matrix type that inherits
* from EigenBase
*
* @tparam T1 type of first argument
* @tparam T2 type of second argument
* @param A first argument
* @param B second argument
* @return sum of squared difference of A and B
*/
template <typename T1, typename T2, require_all_vector_t<T1, T2>* = nullptr,
require_any_var_vector_t<T1, T2>* = nullptr>
inline var squared_distance(const T1& A, const T2& B) {
check_matching_sizes("squared_distance", "A", A.val(), "B", B.val());
if (unlikely(A.size() == 0)) {
return var(0.0);
} else if (!is_constant<T1>::value && !is_constant<T2>::value) {
arena_t<promote_scalar_t<var, T1>> arena_A = A;
arena_t<promote_scalar_t<var, T2>> arena_B = B;
arena_t<Eigen::VectorXd> res_diff(arena_A.size());
double res_val = 0.0;
for (size_t i = 0; i < arena_A.size(); ++i) {
const double diff = arena_A.val().coeff(i) - arena_B.val().coeff(i);
res_diff.coeffRef(i) = diff;
res_val += diff * diff;
}
return var(make_callback_vari(
res_val, [arena_A, arena_B, res_diff](const auto& res) mutable {
const double res_adj = 2.0 * res.adj_;
for (size_t i = 0; i < arena_A.size(); ++i) {
const double diff = res_adj * res_diff.coeff(i);
arena_A.adj().coeffRef(i) += diff;
arena_B.adj().coeffRef(i) -= diff;
}
}));
} else if (!is_constant<T1>::value) {
arena_t<promote_scalar_t<var, T1>> arena_A = A;
arena_t<promote_scalar_t<double, T2>> arena_B = value_of(B);
arena_t<Eigen::VectorXd> res_diff(arena_A.size());
double res_val = 0.0;
for (size_t i = 0; i < arena_A.size(); ++i) {
const double diff = arena_A.val().coeff(i) - arena_B.coeff(i);
res_diff.coeffRef(i) = diff;
res_val += diff * diff;
}
return var(make_callback_vari(
res_val, [arena_A, arena_B, res_diff](const auto& res) mutable {
arena_A.adj() += 2.0 * res.adj_ * res_diff;
}));
} else {
arena_t<promote_scalar_t<double, T1>> arena_A = value_of(A);
arena_t<promote_scalar_t<var, T2>> arena_B = B;
arena_t<Eigen::VectorXd> res_diff(arena_A.size());
double res_val = 0.0;
for (size_t i = 0; i < arena_A.size(); ++i) {
const double diff = arena_A.coeff(i) - arena_B.val().coeff(i);
res_diff.coeffRef(i) = diff;
res_val += diff * diff;
}
return var(make_callback_vari(
res_val, [arena_A, arena_B, res_diff](const auto& res) mutable {
arena_B.adj() -= 2.0 * res.adj_ * res_diff;
}));
}
}
} // namespace math
} // namespace stan
#endif
<commit_msg>Update includes (Issue #2101)<commit_after>#ifndef STAN_MATH_REV_FUN_SQUARED_DISTANCE_HPP
#define STAN_MATH_REV_FUN_SQUARED_DISTANCE_HPP
#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/fun/value_of_rec.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/squared_distance.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/fun/to_ref.hpp>
#include <stan/math/prim/fun/typedefs.hpp>
#include <vector>
namespace stan {
namespace math {
/**
* Returns the squared distance.
*/
inline var squared_distance(const var& a, const var& b) {
check_finite("squared_distance", "a", a);
check_finite("squared_distance", "b", b);
return make_callback_vari(std::pow(a.val() - b.val(), 2),
[a, b](const auto& vi) mutable {
const double diff = 2.0 * (a.val() - b.val());
a.adj() += vi.adj_ * diff;
b.adj() -= vi.adj_ * diff;
});
}
/**
* Returns the squared distance.
*/
inline var squared_distance(const var& a, double b) {
check_finite("squared_distance", "a", a);
check_finite("squared_distance", "b", b);
return make_callback_vari(std::pow(a.val() - b, 2),
[a, b](const auto& vi) mutable {
a.adj() += vi.adj_ * 2.0 * (a.val() - b);
});
}
/**
* Returns the squared distance.
*/
inline var squared_distance(double a, const var& b) {
return squared_distance(b, a);
}
namespace internal {
class squared_distance_vv_vari : public vari {
protected:
vari** v1_;
vari** v2_;
size_t length_;
public:
template <
typename EigVecVar1, typename EigVecVar2,
require_all_eigen_vector_vt<is_var, EigVecVar1, EigVecVar2>* = nullptr>
squared_distance_vv_vari(const EigVecVar1& v1, const EigVecVar2& v2)
: vari((as_column_vector_or_scalar(v1).val()
- as_column_vector_or_scalar(v2).val())
.squaredNorm()),
length_(v1.size()) {
v1_ = reinterpret_cast<vari**>(
ChainableStack::instance_->memalloc_.alloc(length_ * sizeof(vari*)));
v2_ = reinterpret_cast<vari**>(
ChainableStack::instance_->memalloc_.alloc(length_ * sizeof(vari*)));
Eigen::Map<vector_vi>(v1_, length_) = v1.vi();
Eigen::Map<vector_vi>(v2_, length_) = v2.vi();
}
virtual void chain() {
Eigen::Map<vector_vi> v1_map(v1_, length_);
Eigen::Map<vector_vi> v2_map(v2_, length_);
vector_d di = 2 * adj_ * (v1_map.val() - v2_map.val());
v1_map.adj() += di;
v2_map.adj() -= di;
}
};
class squared_distance_vd_vari : public vari {
protected:
vari** v1_;
double* v2_;
size_t length_;
public:
template <typename EigVecVar, typename EigVecArith,
require_eigen_vector_vt<is_var, EigVecVar>* = nullptr,
require_eigen_vector_vt<std::is_arithmetic, EigVecArith>* = nullptr>
squared_distance_vd_vari(const EigVecVar& v1, const EigVecArith& v2)
: vari((as_column_vector_or_scalar(v1).val()
- as_column_vector_or_scalar(v2))
.squaredNorm()),
length_(v1.size()) {
v1_ = reinterpret_cast<vari**>(
ChainableStack::instance_->memalloc_.alloc(length_ * sizeof(vari*)));
v2_ = reinterpret_cast<double*>(
ChainableStack::instance_->memalloc_.alloc(length_ * sizeof(double)));
Eigen::Map<vector_vi>(v1_, length_) = v1.vi();
Eigen::Map<vector_d>(v2_, length_) = v2;
}
virtual void chain() {
Eigen::Map<vector_vi> v1_map(v1_, length_);
v1_map.adj()
+= 2 * adj_ * (v1_map.val() - Eigen::Map<vector_d>(v2_, length_));
}
};
} // namespace internal
template <
typename EigVecVar1, typename EigVecVar2,
require_all_eigen_vector_vt<is_var, EigVecVar1, EigVecVar2>* = nullptr>
inline var squared_distance(const EigVecVar1& v1, const EigVecVar2& v2) {
check_matching_sizes("squared_distance", "v1", v1, "v2", v2);
return {new internal::squared_distance_vv_vari(to_ref(v1), to_ref(v2))};
}
template <typename EigVecVar, typename EigVecArith,
require_eigen_vector_vt<is_var, EigVecVar>* = nullptr,
require_eigen_vector_vt<std::is_arithmetic, EigVecArith>* = nullptr>
inline var squared_distance(const EigVecVar& v1, const EigVecArith& v2) {
check_matching_sizes("squared_distance", "v1", v1, "v2", v2);
return {new internal::squared_distance_vd_vari(to_ref(v1), to_ref(v2))};
}
template <typename EigVecArith, typename EigVecVar,
require_eigen_vector_vt<std::is_arithmetic, EigVecArith>* = nullptr,
require_eigen_vector_vt<is_var, EigVecVar>* = nullptr>
inline var squared_distance(const EigVecArith& v1, const EigVecVar& v2) {
check_matching_sizes("squared_distance", "v1", v1, "v2", v2);
return {new internal::squared_distance_vd_vari(to_ref(v2), to_ref(v1))};
}
/**
* Compute the squared distance between the elements in
* two inputs.
*
* This overload handles arguments where one of T1 or T2 are
* `var_value<T>` where `T` is an Eigen type. The other type can
* also be a `var_value` or it can be a matrix type that inherits
* from EigenBase
*
* @tparam T1 type of first argument
* @tparam T2 type of second argument
* @param A first argument
* @param B second argument
* @return sum of squared difference of A and B
*/
template <typename T1, typename T2, require_all_vector_t<T1, T2>* = nullptr,
require_any_var_vector_t<T1, T2>* = nullptr>
inline var squared_distance(const T1& A, const T2& B) {
check_matching_sizes("squared_distance", "A", A.val(), "B", B.val());
if (unlikely(A.size() == 0)) {
return var(0.0);
} else if (!is_constant<T1>::value && !is_constant<T2>::value) {
arena_t<promote_scalar_t<var, T1>> arena_A = A;
arena_t<promote_scalar_t<var, T2>> arena_B = B;
arena_t<Eigen::VectorXd> res_diff(arena_A.size());
double res_val = 0.0;
for (size_t i = 0; i < arena_A.size(); ++i) {
const double diff = arena_A.val().coeff(i) - arena_B.val().coeff(i);
res_diff.coeffRef(i) = diff;
res_val += diff * diff;
}
return var(make_callback_vari(
res_val, [arena_A, arena_B, res_diff](const auto& res) mutable {
const double res_adj = 2.0 * res.adj();
for (size_t i = 0; i < arena_A.size(); ++i) {
const double diff = res_adj * res_diff.coeff(i);
arena_A.adj().coeffRef(i) += diff;
arena_B.adj().coeffRef(i) -= diff;
}
}));
} else if (!is_constant<T1>::value) {
arena_t<promote_scalar_t<var, T1>> arena_A = A;
arena_t<promote_scalar_t<double, T2>> arena_B = value_of(B);
arena_t<Eigen::VectorXd> res_diff(arena_A.size());
double res_val = 0.0;
for (size_t i = 0; i < arena_A.size(); ++i) {
const double diff = arena_A.val().coeff(i) - arena_B.coeff(i);
res_diff.coeffRef(i) = diff;
res_val += diff * diff;
}
return var(make_callback_vari(
res_val, [arena_A, arena_B, res_diff](const auto& res) mutable {
arena_A.adj() += 2.0 * res.adj() * res_diff;
}));
} else {
arena_t<promote_scalar_t<double, T1>> arena_A = value_of(A);
arena_t<promote_scalar_t<var, T2>> arena_B = B;
arena_t<Eigen::VectorXd> res_diff(arena_A.size());
double res_val = 0.0;
for (size_t i = 0; i < arena_A.size(); ++i) {
const double diff = arena_A.coeff(i) - arena_B.val().coeff(i);
res_diff.coeffRef(i) = diff;
res_val += diff * diff;
}
return var(make_callback_vari(
res_val, [arena_A, arena_B, res_diff](const auto& res) mutable {
arena_B.adj() -= 2.0 * res.adj() * res_diff;
}));
}
}
} // namespace math
} // namespace stan
#endif
<|endoftext|>
|
<commit_before>/* dhcpclient.hpp - dhcp client request handling
*
* (c) 2011-2014 Nicholas J. Kain <njkain at gmail dot com>
* 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.
*
* 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.
*/
#ifndef NK_DHCPCLIENT_H
#define NK_DHCPCLIENT_H
#include <string>
#include <unordered_map>
#include <netdb.h>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/enable_shared_from_this.hpp>
#include "dhcp.h"
// There are two hashtables, a 'new' and a 'marked for death' table. If these
// tables are not empty, a timer with period t will wake up and delete all
// entries on the 'm4d' table and move the 'new' table to replace the 'm4d'
// table. If an entry on the 'm4d' table is accessed, it will be moved to the
// 'new' table. New entries will be added to the 'new' table. If both tables
// are emptied, the timer can stop until a new entry is added. We optimize
// the scheme by not actually performing moves: instead, we store an index
// to the 'new' table, and the 'marked for death' table is the unindexed table.
//
// This scheme requires no timestamping and will bound the lifetime of any
// object to be p < lifetime < 2p. A further refinement would be to scale
// p to be inversely proportional to the number of entries on the 'new'
// and 'm4d' tables. This change would cause the deletion rate to increase
// smoothly under heavy load, providing resistance to OOM DoS at the cost of
// making it so that clients will need to complete their transactions quickly.
class ClientStates {
public:
ClientStates(boost::asio::io_service &io_service)
: swapTimer_(io_service)
{
currentMap_ = 0;
swapInterval_ = 60; // 1m
}
~ClientStates() {}
bool stateExists(uint32_t xid, const std::string &chaddr) const {
std::string key(generateKey(xid, chaddr));
return (map_[0].find(key) != map_[0].end()) ||
(map_[1].find(key) != map_[1].end());
}
void stateAdd(uint32_t xid, const std::string &chaddr, uint8_t state)
{
std::string key(generateKey(xid, chaddr));
if (!state)
return;
stateKill(xid, chaddr);
map_[currentMap_][key] = state;
if (swapTimer_.expires_from_now() <=
boost::posix_time::time_duration(0,0,0,0))
setTimer();
}
uint8_t stateGet(uint32_t xid, const std::string &chaddr) {
std::string key(generateKey(xid, chaddr));
auto r = map_[currentMap_].find(key);
if (r != map_[currentMap_].end())
return r->second;
r = map_[!currentMap_].find(key);
if (r != map_[!currentMap_].end()) {
map_[!currentMap_].erase(r);
map_[currentMap_][key] = r->second;
return r->second;
}
return DHCPNULL;
}
void stateKill(uint32_t xid, const std::string &chaddr) {
std::string key(generateKey(xid, chaddr));
auto elt = map_[currentMap_].find(key);
if (elt != map_[currentMap_].end()) {
map_[currentMap_].erase(elt);
return;
}
elt = map_[!currentMap_].find(key);
if (elt != map_[!currentMap_].end())
map_[!currentMap_].erase(elt);
}
private:
std::string generateKey(uint32_t xid, const std::string &chaddr) const {
std::string r;
union {
uint8_t c[4];
uint32_t n;
} xia;
xia.n = xid;
r.push_back(xia.c[0]);
r.push_back(xia.c[1]);
r.push_back(xia.c[2]);
r.push_back(xia.c[3]);
r.append(chaddr);
return r;
}
void doSwap(void) {
int killMap = !currentMap_;
map_[killMap].clear();
currentMap_ = killMap;
}
void setTimer(void) {
swapTimer_.expires_from_now(boost::posix_time::seconds(swapInterval_));
swapTimer_.async_wait
([this](const boost::system::error_code& error)
{
doSwap();
if (map_[0].size() || map_[1].size())
setTimer();
});
}
// Key is concatenation of xid|chaddr. Neither of these need to be stored
// in explicit fields in the state structure.
int currentMap_; // Either 0 or 1.
int swapInterval_;
boost::asio::deadline_timer swapTimer_;
std::unordered_map<std::string, uint8_t> map_[2];
};
void init_client_states_v4(boost::asio::io_service &io_service);
class ClientListener
{
public:
ClientListener(boost::asio::io_service &io_service,
const boost::asio::ip::udp::endpoint &endpoint,
const std::string &ifname);
private:
void start_receive();
uint64_t getNowTs(void) const;
void dhcpmsg_init(struct dhcpmsg *dm, char type,
uint32_t xid, const std::string &chaddr) const;
uint32_t local_ip() const;
std::string ipStr(uint32_t ip) const;
void send_reply(struct dhcpmsg *dm, bool broadcast);
void reply_discover(const std::string &chaddr);
void reply_request(const std::string &chaddr, bool is_direct);
void reply_inform(const std::string &chaddr);
void do_release(const std::string &chaddr);
std::string getChaddr(const struct dhcpmsg &dm) const;
bool validate_dhcp(void) const;
void handle_receive(const boost::system::error_code &error,
std::size_t bytes_xferred);
boost::asio::ip::udp::socket socket_;
//boost::asio::ip::udp::socket broadcast_socket_;
boost::asio::ip::udp::endpoint remote_endpoint_;
std::array<uint8_t, 1024> recv_buffer_;
struct dhcpmsg dhcpmsg_;
boost::asio::ip::address local_ip_;
};
#endif /* NK_DHCPCLIENT_H */
<commit_msg>Remove unused headers.<commit_after>/* dhcpclient.hpp - dhcp client request handling
*
* (c) 2011-2014 Nicholas J. Kain <njkain at gmail dot com>
* 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.
*
* 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.
*/
#ifndef NK_DHCPCLIENT_H
#define NK_DHCPCLIENT_H
#include <string>
#include <memory>
#include <unordered_map>
#include <netdb.h>
#include <boost/asio.hpp>
#include "dhcp.h"
// There are two hashtables, a 'new' and a 'marked for death' table. If these
// tables are not empty, a timer with period t will wake up and delete all
// entries on the 'm4d' table and move the 'new' table to replace the 'm4d'
// table. If an entry on the 'm4d' table is accessed, it will be moved to the
// 'new' table. New entries will be added to the 'new' table. If both tables
// are emptied, the timer can stop until a new entry is added. We optimize
// the scheme by not actually performing moves: instead, we store an index
// to the 'new' table, and the 'marked for death' table is the unindexed table.
//
// This scheme requires no timestamping and will bound the lifetime of any
// object to be p < lifetime < 2p. A further refinement would be to scale
// p to be inversely proportional to the number of entries on the 'new'
// and 'm4d' tables. This change would cause the deletion rate to increase
// smoothly under heavy load, providing resistance to OOM DoS at the cost of
// making it so that clients will need to complete their transactions quickly.
class ClientStates {
public:
ClientStates(boost::asio::io_service &io_service)
: swapTimer_(io_service)
{
currentMap_ = 0;
swapInterval_ = 60; // 1m
}
~ClientStates() {}
bool stateExists(uint32_t xid, const std::string &chaddr) const {
std::string key(generateKey(xid, chaddr));
return (map_[0].find(key) != map_[0].end()) ||
(map_[1].find(key) != map_[1].end());
}
void stateAdd(uint32_t xid, const std::string &chaddr, uint8_t state)
{
std::string key(generateKey(xid, chaddr));
if (!state)
return;
stateKill(xid, chaddr);
map_[currentMap_][key] = state;
if (swapTimer_.expires_from_now() <=
boost::posix_time::time_duration(0,0,0,0))
setTimer();
}
uint8_t stateGet(uint32_t xid, const std::string &chaddr) {
std::string key(generateKey(xid, chaddr));
auto r = map_[currentMap_].find(key);
if (r != map_[currentMap_].end())
return r->second;
r = map_[!currentMap_].find(key);
if (r != map_[!currentMap_].end()) {
map_[!currentMap_].erase(r);
map_[currentMap_][key] = r->second;
return r->second;
}
return DHCPNULL;
}
void stateKill(uint32_t xid, const std::string &chaddr) {
std::string key(generateKey(xid, chaddr));
auto elt = map_[currentMap_].find(key);
if (elt != map_[currentMap_].end()) {
map_[currentMap_].erase(elt);
return;
}
elt = map_[!currentMap_].find(key);
if (elt != map_[!currentMap_].end())
map_[!currentMap_].erase(elt);
}
private:
std::string generateKey(uint32_t xid, const std::string &chaddr) const {
std::string r;
union {
uint8_t c[4];
uint32_t n;
} xia;
xia.n = xid;
r.push_back(xia.c[0]);
r.push_back(xia.c[1]);
r.push_back(xia.c[2]);
r.push_back(xia.c[3]);
r.append(chaddr);
return r;
}
void doSwap(void) {
int killMap = !currentMap_;
map_[killMap].clear();
currentMap_ = killMap;
}
void setTimer(void) {
swapTimer_.expires_from_now(boost::posix_time::seconds(swapInterval_));
swapTimer_.async_wait
([this](const boost::system::error_code& error)
{
doSwap();
if (map_[0].size() || map_[1].size())
setTimer();
});
}
// Key is concatenation of xid|chaddr. Neither of these need to be stored
// in explicit fields in the state structure.
int currentMap_; // Either 0 or 1.
int swapInterval_;
boost::asio::deadline_timer swapTimer_;
std::unordered_map<std::string, uint8_t> map_[2];
};
void init_client_states_v4(boost::asio::io_service &io_service);
class ClientListener
{
public:
ClientListener(boost::asio::io_service &io_service,
const boost::asio::ip::udp::endpoint &endpoint,
const std::string &ifname);
private:
void start_receive();
uint64_t getNowTs(void) const;
void dhcpmsg_init(struct dhcpmsg *dm, char type,
uint32_t xid, const std::string &chaddr) const;
uint32_t local_ip() const;
std::string ipStr(uint32_t ip) const;
void send_reply(struct dhcpmsg *dm, bool broadcast);
void reply_discover(const std::string &chaddr);
void reply_request(const std::string &chaddr, bool is_direct);
void reply_inform(const std::string &chaddr);
void do_release(const std::string &chaddr);
std::string getChaddr(const struct dhcpmsg &dm) const;
bool validate_dhcp(void) const;
void handle_receive(const boost::system::error_code &error,
std::size_t bytes_xferred);
boost::asio::ip::udp::socket socket_;
//boost::asio::ip::udp::socket broadcast_socket_;
boost::asio::ip::udp::endpoint remote_endpoint_;
std::array<uint8_t, 1024> recv_buffer_;
struct dhcpmsg dhcpmsg_;
boost::asio::ip::address local_ip_;
};
#endif /* NK_DHCPCLIENT_H */
<|endoftext|>
|
<commit_before>#include <iostream>
#include "vtrc-server/vtrc-application.h"
#include "vtrc-server/vtrc-listener-tcp.h"
#include "vtrc-common/vtrc-connection-iface.h"
#include "vtrc-common/vtrc-closure-holder.h"
#include "vtrc-common/vtrc-thread-pool.h"
#include "protocol/hello.pb.h" /// hello protocol
#include "google/protobuf/descriptor.h" /// for descriptor( )->full_name( )
#include "boost/lexical_cast.hpp"
using namespace vtrc;
namespace {
class hello_service_impl: public howto::hello_service {
common::connection_iface *cl_;
void send_hello(::google::protobuf::RpcController* /*controller*/,
const ::howto::request_message* request,
::howto::response_message* response,
::google::protobuf::Closure* done) /*override*/
{
common::closure_holder ch( done ); /// instead of done->Run( );
std::ostringstream oss;
oss << "Hello " << request->name( )
<< " from hello_service_impl::send_hello!\n"
<< "Your transport name is '"
<< cl_->name( ) << "'.\nHave a nice day.";
response->set_hello( oss.str( ) );
/// done->Run( ); /// ch will call it
}
public:
hello_service_impl( common::connection_iface *cl )
:cl_(cl)
{ }
static std::string const &service_name( )
{
return howto::hello_service::descriptor( )->full_name( );
}
};
class hello_application: public server::application {
typedef common::rpc_service_wrapper wrapper_type;
typedef vtrc::shared_ptr<wrapper_type> wrapper_sptr;
public:
hello_application( common::thread_pool &tp )
:server::application(tp.get_io_service( ))
{ }
wrapper_sptr get_service_by_name( common::connection_iface* connection,
const std::string &service_name )
{
if( service_name == hello_service_impl::service_name( ) ) {
hello_service_impl *new_impl = new hello_service_impl(connection);
return vtrc::make_shared<wrapper_type>( new_impl );
}
return wrapper_sptr( );
}
};
} // namespace
int main( int argc, const char **argv )
{
const char *address = "127.0.0.1";
unsigned short port = 56560;
if( argc > 2 ) {
address = argv[1];
port = boost::lexical_cast<unsigned short>( argv[2] );
} else if( argc > 1 ) {
port = boost::lexical_cast<unsigned short>( argv[1] );
}
common::thread_pool tp;
hello_application app( tp );
try {
vtrc::shared_ptr<server::listener>
tcp( server::listeners::tcp::create( app, address, port ) );
tcp->start( );
tp.attach( );
} catch( const std::exception &ex ) {
std::cerr << "Hello, world failed: " << ex.what( ) << "\n";
}
tp.join_all( );
/// make valgrind happy.
google::protobuf::ShutdownProtobufLibrary( );
return 0;
}
<commit_msg>howto<commit_after>#include <iostream>
#include "vtrc-server/vtrc-application.h"
#include "vtrc-server/vtrc-listener-tcp.h"
#include "vtrc-common/vtrc-connection-iface.h"
#include "vtrc-common/vtrc-closure-holder.h"
#include "vtrc-common/vtrc-thread-pool.h"
#include "protocol/hello.pb.h" /// hello protocol
#include "google/protobuf/descriptor.h" /// for descriptor( )->full_name( )
#include "boost/lexical_cast.hpp"
using namespace vtrc;
namespace {
class hello_service_impl: public howto::hello_service {
common::connection_iface *cl_;
void send_hello(::google::protobuf::RpcController* /*controller*/,
const ::howto::request_message* request,
::howto::response_message* response,
::google::protobuf::Closure* done) /*override*/
{
common::closure_holder ch( done ); /// instead of done->Run( );
std::ostringstream oss;
oss << "Hello " << request->name( )
<< " from hello_service_impl::send_hello!\n"
<< "Your transport name is '"
<< cl_->name( ) << "'.\nHave a nice day.";
response->set_hello( oss.str( ) );
/// done->Run( ); /// ch will call it
}
public:
hello_service_impl( common::connection_iface *cl )
:cl_(cl)
{ }
static std::string const &service_name( )
{
return howto::hello_service::descriptor( )->full_name( );
}
};
class hello_application: public server::application {
typedef common::rpc_service_wrapper wrapper_type;
typedef vtrc::shared_ptr<wrapper_type> wrapper_sptr;
public:
hello_application( common::thread_pool &tp )
:server::application(tp.get_io_service( ))
{ }
wrapper_sptr get_service_by_name( common::connection_iface* connection,
const std::string &service_name )
{
if( service_name == hello_service_impl::service_name( ) ) {
hello_service_impl *new_impl = new hello_service_impl(connection);
return vtrc::make_shared<wrapper_type>( new_impl );
}
return wrapper_sptr( );
}
};
} // namespace
int main( int argc, const char **argv )
{
const char *address = "127.0.0.1";
unsigned short port = 56560;
if( argc > 2 ) {
address = argv[1];
port = boost::lexical_cast<unsigned short>( argv[2] );
} else if( argc > 1 ) {
port = boost::lexical_cast<unsigned short>( argv[1] );
}
common::thread_pool tp;
hello_application app( tp );
try {
vtrc::shared_ptr<server::listener>
tcp( server::listeners::tcp::create( app, address, port ) );
tcp->start( );
tp.attach( );
} catch( const std::exception &ex ) {
std::cerr << "Hello, world failed: " << ex.what( ) << "\n";
}
tp.join_all( );
/// make valgrind happy.
google::protobuf::ShutdownProtobufLibrary( );
return 0;
}
<|endoftext|>
|
<commit_before>/*!
\copyright (c) RDO-Team, 2011
\file calc_relevant.inl
\authors Барс Александр
\authors Урусов Андрей (rdo@rk9.bmstu.ru)
\date 16.04.2011
\brief RDOCalc для подбора релевантных ресурсов
\indent 4T
*/
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/runtime/rdo_runtime.h"
#include "simulator/runtime/rdo_activity.h"
// --------------------------------------------------------------------------------
OPEN_RDO_RUNTIME_NAMESPACE
// --------------------------------------------------------------------------------
// -------------------- RDOSetRelResParamCalc
// --------------------------------------------------------------------------------
template <SetOperationType::Type setOperationType>
inline RDOSetRelResParamCalc<setOperationType>::RDOSetRelResParamCalc(ruint relResID, ruint paramID, CREF(LPRDOCalc) pCalc)
: m_relResID(relResID)
, m_paramID (paramID )
, m_pCalc (pCalc )
{
if (m_pCalc)
{
setSrcInfo(m_pCalc->srcInfo());
}
}
template <SetOperationType::Type setOperationType>
inline RDOSetRelResParamCalc<setOperationType>::~RDOSetRelResParamCalc()
{}
template <>
inline RDOValue RDOSetRelResParamCalc<SetOperationType::SET>::doCalc(CREF(LPRDORuntime) pRuntime)
{
RDOValue value = m_pCalc->calcValue(pRuntime);
ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
pRuntime->setResParamVal(resID, m_paramID, value);
return value;
}
template <>
inline RDOValue RDOSetRelResParamCalc<SetOperationType::ADDITION>::doCalc(CREF(LPRDORuntime) pRuntime)
{
ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
return pRuntime->getResParamValRaw(resID, m_paramID) += m_pCalc->calcValue(pRuntime);
}
template <>
inline RDOValue RDOSetRelResParamCalc<SetOperationType::SUBTRACTION>::doCalc(CREF(LPRDORuntime) pRuntime)
{
ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
return pRuntime->getResParamValRaw(resID, m_paramID) -= m_pCalc->calcValue(pRuntime);
}
template <>
inline RDOValue RDOSetRelResParamCalc<SetOperationType::MULTIPLY>::doCalc(CREF(LPRDORuntime) pRuntime)
{
ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
return pRuntime->getResParamValRaw(resID, m_paramID) *= m_pCalc->calcValue(pRuntime);
}
template <>
inline RDOValue RDOSetRelResParamCalc<SetOperationType::DIVIDE>::doCalc(CREF(LPRDORuntime) pRuntime)
{
ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
return pRuntime->getResParamValRaw(resID, m_paramID) /= m_pCalc->calcValue(pRuntime);
}
template <>
inline RDOValue RDOSetRelResParamCalc<SetOperationType::INCREMENT>::doCalc(CREF(LPRDORuntime) pRuntime)
{
ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
return pRuntime->getResParamValRaw(resID, m_paramID) += RDOValue(1);
}
template <>
inline RDOValue RDOSetRelResParamCalc<SetOperationType::DECRIMENT>::doCalc(CREF(LPRDORuntime) pRuntime)
{
ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
return pRuntime->getResParamValRaw(resID, m_paramID) -= RDOValue(1);
}
CLOSE_RDO_RUNTIME_NAMESPACE
<commit_msg> - добавлен NOCHANGE<commit_after>/*!
\copyright (c) RDO-Team, 2011
\file calc_relevant.inl
\authors Барс Александр
\authors Урусов Андрей (rdo@rk9.bmstu.ru)
\date 16.04.2011
\brief RDOCalc для подбора релевантных ресурсов
\indent 4T
*/
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/runtime/rdo_runtime.h"
#include "simulator/runtime/rdo_activity.h"
// --------------------------------------------------------------------------------
OPEN_RDO_RUNTIME_NAMESPACE
// --------------------------------------------------------------------------------
// -------------------- RDOSetRelResParamCalc
// --------------------------------------------------------------------------------
template <SetOperationType::Type setOperationType>
inline RDOSetRelResParamCalc<setOperationType>::RDOSetRelResParamCalc(ruint relResID, ruint paramID, CREF(LPRDOCalc) pCalc)
: m_relResID(relResID)
, m_paramID (paramID )
, m_pCalc (pCalc )
{
if (m_pCalc)
{
setSrcInfo(m_pCalc->srcInfo());
}
}
template <SetOperationType::Type setOperationType>
inline RDOSetRelResParamCalc<setOperationType>::~RDOSetRelResParamCalc()
{}
template <>
inline RDOValue RDOSetRelResParamCalc<SetOperationType::NOCHANGE>::doCalc(CREF(LPRDORuntime) pRuntime)
{
UNUSED(pRuntime);
RDOValue value(true);
return value;
}
template <>
inline RDOValue RDOSetRelResParamCalc<SetOperationType::SET>::doCalc(CREF(LPRDORuntime) pRuntime)
{
RDOValue value = m_pCalc->calcValue(pRuntime);
ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
pRuntime->setResParamVal(resID, m_paramID, value);
return value;
}
template <>
inline RDOValue RDOSetRelResParamCalc<SetOperationType::ADDITION>::doCalc(CREF(LPRDORuntime) pRuntime)
{
ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
return pRuntime->getResParamValRaw(resID, m_paramID) += m_pCalc->calcValue(pRuntime);
}
template <>
inline RDOValue RDOSetRelResParamCalc<SetOperationType::SUBTRACTION>::doCalc(CREF(LPRDORuntime) pRuntime)
{
ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
return pRuntime->getResParamValRaw(resID, m_paramID) -= m_pCalc->calcValue(pRuntime);
}
template <>
inline RDOValue RDOSetRelResParamCalc<SetOperationType::MULTIPLY>::doCalc(CREF(LPRDORuntime) pRuntime)
{
ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
return pRuntime->getResParamValRaw(resID, m_paramID) *= m_pCalc->calcValue(pRuntime);
}
template <>
inline RDOValue RDOSetRelResParamCalc<SetOperationType::DIVIDE>::doCalc(CREF(LPRDORuntime) pRuntime)
{
ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
return pRuntime->getResParamValRaw(resID, m_paramID) /= m_pCalc->calcValue(pRuntime);
}
template <>
inline RDOValue RDOSetRelResParamCalc<SetOperationType::INCREMENT>::doCalc(CREF(LPRDORuntime) pRuntime)
{
ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
return pRuntime->getResParamValRaw(resID, m_paramID) += RDOValue(1);
}
template <>
inline RDOValue RDOSetRelResParamCalc<SetOperationType::DECRIMENT>::doCalc(CREF(LPRDORuntime) pRuntime)
{
ruint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);
return pRuntime->getResParamValRaw(resID, m_paramID) -= RDOValue(1);
}
CLOSE_RDO_RUNTIME_NAMESPACE
<|endoftext|>
|
<commit_before>AliAnalysisTaskCheckPerformanceCascadepp276 *AddTaskCheckPerformanceCascadepp276( Int_t minnTPCcls = 70,
Float_t vtxlim = 10.,
Float_t vtxlimmin = 0.,
Bool_t fwithsdd = kFALSE,
Bool_t kextrasel = kFALSE,
Bool_t kacccut = kFALSE,
Bool_t krelaunchvertexers = kFALSE,
Bool_t ksddonselection = kFALSE,
Float_t minptondaughtertracks = 0.0,
Float_t etacutondaughtertracks = 0.8) {
// Creates, configures and attaches to the train a cascades check task.
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskCheckPerformanceCascadepp276", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler()) {
::Error("AddTaskCheckPerformanceCascadepp276", "This task requires an input event handler");
return NULL;
}
TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
// Create and configure the task
//==============================================================================
TString tasknameperf = "TaskCheckPerformanceCascadepp276";
tasknameperf += Form("_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);
AliAnalysisTaskCheckPerformanceCascadepp276 *taskCheckPerfCascadepp276 = new AliAnalysisTaskCheckPerformanceCascadepp276(tasknameperf);
taskCheckPerfCascadepp276->SetAnalysisType (type); // "ESD" or "AOD"
taskCheckPerfCascadepp276->SetRelaunchV0CascVertexers (krelaunchvertexers); // choose if reconstruct the vertex of V0 in the cascades
taskCheckPerfCascadepp276->SetSDDSelection (fwithsdd); // choose if apply SDD event selection
taskCheckPerfCascadepp276->SetQualityCutZprimVtxPos (kTRUE); // choose if apply Z vtx PV position event selection
taskCheckPerfCascadepp276->SetRejectEventPileUp (kFALSE); // choose if apply no Pileup event selection
taskCheckPerfCascadepp276->SetQualityCutNoTPConlyPrimVtx (kTRUE); // choose if apply no TPC only event selection
taskCheckPerfCascadepp276->SetQualityCutTPCrefit (kTRUE); // choose if apply TPC refit on daughter tracks
taskCheckPerfCascadepp276->SetQualityCutnTPCcls (kTRUE); // choose if apply n TPC cluster selection on daughter tracks
taskCheckPerfCascadepp276->SetWithSDDOn (ksddonselection); // which SDD selection do you want apply? [if kTRUE select SDDon events]
taskCheckPerfCascadepp276->SetQualityCutMinnTPCcls (minnTPCcls); // which value do you want apply for the minTPCcls cut?
taskCheckPerfCascadepp276->SetExtraSelections (kextrasel); // choose if apply the extra selection of cascade reco.
taskCheckPerfCascadepp276->SetApplyAccCut (kacccut); // choose if apply acceptance cut
taskCheckPerfCascadepp276->SetVertexRange (vtxlim); // which higher value do you want apply for vtx Z cut?
taskCheckPerfCascadepp276->SetVertexRangeMin (vtxlimmin); // which lower value do you want apply for vtx Z cut?
taskCheckPerfCascadepp276->SetMinptCutOnDaughterTracks (minptondaughtertracks); // which value do you want apply for cut on min pt daughter track?
taskCheckPerfCascadepp276->SetEtaCutOnDaughterTracks (etacutondaughtertracks); // which value do you want apply for cut on eta daughter track?
mgr->AddTask(taskCheckPerfCascadepp276);
// Create ONLY the output containers for the data produced by the task.
// Get and connect other common input/output containers via the manager as below
//==============================================================================
// Directory name
TString outputFileNamePerf = Form("%s:PWGLFStrangeness.outputCheckPerformanceCascadepp276", AliAnalysisManager::GetCommonFileName());
// Objects name
TString outputnameperf0 = "clistCascPerf";
TString outputnameperf1 = "cfcontPIDAsXiM";
TString outputnameperf2 = "cfcontPIDAsXiP";
TString outputnameperf3 = "cfcontPIDAsOmegaM";
TString outputnameperf4 = "cfcontPIDAsOmegaP";
TString outputnameperf5 = "cfcontAsCuts";
outputnameperf0 += Form("_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);
outputnameperf1 += Form("_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);
outputnameperf2 += Form("_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);
outputnameperf3 += Form("_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);
outputnameperf4 += Form("_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);
outputnameperf5 += Form("_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);
//Save objects into the train common file
AliAnalysisDataContainer *coutputperf1 = mgr->CreateContainer(outputnameperf0,
TList::Class(),
AliAnalysisManager::kOutputContainer,
outputFileNamePerf );
AliAnalysisDataContainer *coutputperf2 = mgr->CreateContainer(outputnameperf1,
AliCFContainer::Class(),
AliAnalysisManager::kOutputContainer,
outputFileNamePerf );
AliAnalysisDataContainer *coutputperf3 = mgr->CreateContainer(outputnameperf2,
AliCFContainer::Class(),
AliAnalysisManager::kOutputContainer,
outputFileNamePerf );
AliAnalysisDataContainer *coutputperf4 = mgr->CreateContainer(outputnameperf3,
AliCFContainer::Class(),
AliAnalysisManager::kOutputContainer,
outputFileNamePerf );
AliAnalysisDataContainer *coutputperf5 = mgr->CreateContainer(outputnameperf4,
AliCFContainer::Class(),
AliAnalysisManager::kOutputContainer,
outputFileNamePerf );
AliAnalysisDataContainer *coutputperf6 = mgr->CreateContainer(outputnameperf5,
AliCFContainer::Class(),
AliAnalysisManager::kOutputContainer,
outputFileNamePerf );
mgr->ConnectInput( taskCheckPerfCascadepp276, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(taskCheckPerfCascadepp276, 1, coutputperf1);
mgr->ConnectOutput(taskCheckPerfCascadepp276, 2, coutputperf2);
mgr->ConnectOutput(taskCheckPerfCascadepp276, 3, coutputperf3);
mgr->ConnectOutput(taskCheckPerfCascadepp276, 4, coutputperf4);
mgr->ConnectOutput(taskCheckPerfCascadepp276, 5, coutputperf5);
mgr->ConnectOutput(taskCheckPerfCascadepp276, 6, coutputperf6);
return taskCheckPerfCascadepp276;
}
<commit_msg>Fix to apply pileup selection in MC performance<commit_after>AliAnalysisTaskCheckPerformanceCascadepp276 *AddTaskCheckPerformanceCascadepp276( Int_t minnTPCcls = 70,
Float_t vtxlim = 10.,
Float_t vtxlimmin = 0.,
Bool_t fwithsdd = kFALSE,
Bool_t kextrasel = kFALSE,
Bool_t kacccut = kFALSE,
Bool_t krelaunchvertexers = kFALSE,
Bool_t ksddonselection = kFALSE,
Float_t minptondaughtertracks = 0.0,
Float_t etacutondaughtertracks = 0.8) {
// Creates, configures and attaches to the train a cascades check task.
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskCheckPerformanceCascadepp276", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler()) {
::Error("AddTaskCheckPerformanceCascadepp276", "This task requires an input event handler");
return NULL;
}
TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
// Create and configure the task
//==============================================================================
TString tasknameperf = "TaskCheckPerformanceCascadepp276";
tasknameperf += Form("_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);
AliAnalysisTaskCheckPerformanceCascadepp276 *taskCheckPerfCascadepp276 = new AliAnalysisTaskCheckPerformanceCascadepp276(tasknameperf);
taskCheckPerfCascadepp276->SetAnalysisType (type); // "ESD" or "AOD"
taskCheckPerfCascadepp276->SetRelaunchV0CascVertexers (krelaunchvertexers); // choose if reconstruct the vertex of V0 in the cascades
taskCheckPerfCascadepp276->SetSDDSelection (fwithsdd); // choose if apply SDD event selection
taskCheckPerfCascadepp276->SetQualityCutZprimVtxPos (kTRUE); // choose if apply Z vtx PV position event selection
taskCheckPerfCascadepp276->SetRejectEventPileUp (kTRUE); // choose if apply no Pileup event selection
taskCheckPerfCascadepp276->SetQualityCutNoTPConlyPrimVtx (kTRUE); // choose if apply no TPC only event selection
taskCheckPerfCascadepp276->SetQualityCutTPCrefit (kTRUE); // choose if apply TPC refit on daughter tracks
taskCheckPerfCascadepp276->SetQualityCutnTPCcls (kTRUE); // choose if apply n TPC cluster selection on daughter tracks
taskCheckPerfCascadepp276->SetWithSDDOn (ksddonselection); // which SDD selection do you want apply? [if kTRUE select SDDon events]
taskCheckPerfCascadepp276->SetQualityCutMinnTPCcls (minnTPCcls); // which value do you want apply for the minTPCcls cut?
taskCheckPerfCascadepp276->SetExtraSelections (kextrasel); // choose if apply the extra selection of cascade reco.
taskCheckPerfCascadepp276->SetApplyAccCut (kacccut); // choose if apply acceptance cut
taskCheckPerfCascadepp276->SetVertexRange (vtxlim); // which higher value do you want apply for vtx Z cut?
taskCheckPerfCascadepp276->SetVertexRangeMin (vtxlimmin); // which lower value do you want apply for vtx Z cut?
taskCheckPerfCascadepp276->SetMinptCutOnDaughterTracks (minptondaughtertracks); // which value do you want apply for cut on min pt daughter track?
taskCheckPerfCascadepp276->SetEtaCutOnDaughterTracks (etacutondaughtertracks); // which value do you want apply for cut on eta daughter track?
mgr->AddTask(taskCheckPerfCascadepp276);
// Create ONLY the output containers for the data produced by the task.
// Get and connect other common input/output containers via the manager as below
//==============================================================================
// Directory name
TString outputFileNamePerf = Form("%s:PWGLFStrangeness.outputCheckPerformanceCascadepp276", AliAnalysisManager::GetCommonFileName());
// Objects name
TString outputnameperf0 = "clistCascPerf";
TString outputnameperf1 = "cfcontPIDAsXiM";
TString outputnameperf2 = "cfcontPIDAsXiP";
TString outputnameperf3 = "cfcontPIDAsOmegaM";
TString outputnameperf4 = "cfcontPIDAsOmegaP";
TString outputnameperf5 = "cfcontAsCuts";
outputnameperf0 += Form("_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);
outputnameperf1 += Form("_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);
outputnameperf2 += Form("_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);
outputnameperf3 += Form("_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);
outputnameperf4 += Form("_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);
outputnameperf5 += Form("_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);
//Save objects into the train common file
AliAnalysisDataContainer *coutputperf1 = mgr->CreateContainer(outputnameperf0,
TList::Class(),
AliAnalysisManager::kOutputContainer,
outputFileNamePerf );
AliAnalysisDataContainer *coutputperf2 = mgr->CreateContainer(outputnameperf1,
AliCFContainer::Class(),
AliAnalysisManager::kOutputContainer,
outputFileNamePerf );
AliAnalysisDataContainer *coutputperf3 = mgr->CreateContainer(outputnameperf2,
AliCFContainer::Class(),
AliAnalysisManager::kOutputContainer,
outputFileNamePerf );
AliAnalysisDataContainer *coutputperf4 = mgr->CreateContainer(outputnameperf3,
AliCFContainer::Class(),
AliAnalysisManager::kOutputContainer,
outputFileNamePerf );
AliAnalysisDataContainer *coutputperf5 = mgr->CreateContainer(outputnameperf4,
AliCFContainer::Class(),
AliAnalysisManager::kOutputContainer,
outputFileNamePerf );
AliAnalysisDataContainer *coutputperf6 = mgr->CreateContainer(outputnameperf5,
AliCFContainer::Class(),
AliAnalysisManager::kOutputContainer,
outputFileNamePerf );
mgr->ConnectInput( taskCheckPerfCascadepp276, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(taskCheckPerfCascadepp276, 1, coutputperf1);
mgr->ConnectOutput(taskCheckPerfCascadepp276, 2, coutputperf2);
mgr->ConnectOutput(taskCheckPerfCascadepp276, 3, coutputperf3);
mgr->ConnectOutput(taskCheckPerfCascadepp276, 4, coutputperf4);
mgr->ConnectOutput(taskCheckPerfCascadepp276, 5, coutputperf5);
mgr->ConnectOutput(taskCheckPerfCascadepp276, 6, coutputperf6);
return taskCheckPerfCascadepp276;
}
<|endoftext|>
|
<commit_before>/*
* File: ft_index_data.cpp
* Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)
*/
#include "common/sedna.h"
#include "tr/ft/ft_index_data.h"
#include "common/xptr.h"
#include "tr/crmutils/node_utils.h"
#include "tr/vmm/vmm.h"
#include "tr/executor/base/tuple.h"
#include "tr/ft/FTindex.h"
#include "tr/log/log.h"
#include "tr/structures/schema.h"
#include "tr/executor/fo/casting_operations.h"
//#include "indexes.h"
#include "tr/executor/base/dm_accessors.h"
using namespace std;
pers_sset<ft_index_cell,unsigned short> *ft_indexdata;
index_id *ft_idx_counter;
USemaphore ft_index_sem;//SEMAPHOR!!!
static bool ft_index_initialized = false;
//inits metadata library
void ft_index_on_session_begin(pers_sset<ft_index_cell,unsigned short> * _indexdata_, index_id *_idx_counter_)
{
ft_indexdata = _indexdata_;
ft_idx_counter = _idx_counter_;
//SEMAPHOR INIT SECTION
if (USemaphoreOpen(&ft_index_sem, FT_INDEX_SEMAPHORE_STR, __sys_call_error) != 0)
throw USER_EXCEPTION2(SE4012, "FT_INDEX_SEMAPHORE_STR");
ft_index_initialized = true;
}
void ft_index_on_session_end()
{
if (!ft_index_initialized) return;
//SEMAPHOR RELEASE SECTION
if (USemaphoreClose(ft_index_sem, __sys_call_error) != 0)
throw USER_EXCEPTION2(SE4013, "FT_INDEX_SEMAPHORE_STR");
ft_index_initialized = false;
}
pers_sset<ft_index_cell,unsigned short>::pers_sset_entry* search_ft_indexdata_cell(const char *index_title)
{
return ft_indexdata->get(index_title,NULL);
}
ft_custom_cell* ft_custom_cell::init(xml_ns* _ns, const char* _local,ft_index_type _cm,bool persistent)
{
ft_custom_cell* ftc=(ft_custom_cell*)scm_malloc(sizeof(ft_custom_cell),persistent);
ftc->ns=_ns;
if (_local!=NULL)
{
char* z=(char*)scm_malloc(strlen(_local)+1,persistent);
strcpy(z,_local);
ftc->local=z;
}
else
ftc->local=NULL;
ftc->cm=_cm;
return ftc;
}
void ft_index_cell::delete_custom_tree (pers_sset<ft_custom_cell,unsigned short> * custom_tree)
{
pers_sset<ft_custom_cell,unsigned short>::pers_sset_entry* tmp=custom_tree->rb_minimum(custom_tree->root);
while (tmp!=NULL)
{
//coll->free_metadata(tmp);
ft_custom_cell* mdc=tmp->obj;
if (mdc->local)
scm_free(mdc->local,IS_PH_PTR(mdc));
scm_free(mdc,IS_PH_PTR(mdc));
tmp->obj=NULL;
tmp=custom_tree->rb_successor(tmp);
}
pers_sset<ft_custom_cell,unsigned short>::sset_free(custom_tree);
}
void inline free_ft_indexdata_cell(pers_sset<ft_index_cell,unsigned short>::pers_sset_entry* entry)
{
ft_index_cell* idc=entry->obj;
ft_indexdata->rb_delete(entry);
if (idc->index_title!=NULL)
scm_free(idc->index_title,true);
delete_PathExpr(idc->object);
scm_free(idc->doc_name,true);
if (idc->custom_tree!=NULL)
ft_index_cell::delete_custom_tree(idc->custom_tree);
scm_free(idc,true);
}
bool ft_index_cell::fits_to_index(schema_node* snode)
{
t_scmnodes res;
t_scmnodes objs=execute_abs_path_expr(snode->root,object);
t_scmnodes::iterator it=objs.begin();
while (it!=objs.end())
{
if (*it==snode)
return true;
it++;
}
return false;
}
ft_index_cell* ft_index_cell::create_index (PathExpr *object_path, ft_index_type it, doc_schema_node* schemaroot,const char * index_title, const char* doc_name,bool is_doc,std::vector< std::pair< std::pair<xml_ns*,char*>,ft_index_type> >* templ, bool just_heap)
{
// I. Create and fill new index cell
ft_index_sem_down();
if (search_ft_indexdata_cell(index_title)!=NULL)
{
ft_index_sem_up();
throw USER_EXCEPTION(SE2033);
}
down_concurrent_micro_ops_number();
ft_index_cell* idc=(ft_index_cell*)scm_malloc(sizeof(ft_index_cell),true);
idc->id = *ft_idx_counter;
(*ft_idx_counter)++;
idc->schemaroot = schemaroot;
schemaroot->create_ft_index(idc);
idc->object = object_path;
idc->ftype=it;
idc->index_title=(char*)scm_malloc(strlen(index_title)+1,true);
strcpy(idc->index_title,index_title);
idc->doc_name=(char*)scm_malloc(strlen(doc_name)+1,true);
strcpy(idc->doc_name,doc_name);
idc->is_doc=is_doc;
if (it==ft_customized_value && templ!=NULL)
{
idc->custom_tree= pers_sset<ft_custom_cell,unsigned short>::init();
std::vector<std::pair<std::pair<xml_ns*,char*>,ft_index_type> >::iterator tmp=templ->begin();
while (tmp!=templ->end())
{
idc->custom_tree->put(ft_custom_cell::init((*tmp).first.first,(*tmp).first.second,(*tmp).second));
tmp++;
}
}
/*idc->next = *indexdata;
if ((*indexdata) != NULL) (*indexdata)->pred = idc;
*indexdata = idc;*/
ft_indexdata->put(idc);
ft_index_sem_up();
hl_logical_log_ft_index(object_path, it,(char *) index_title, doc_name,is_doc,idc->custom_tree,true);
up_concurrent_micro_ops_number();
// ALGORITHM: indexing data
//II. Execute abs path (object_path) on the desriptive schema
if (!just_heap)
{
t_scmnodes sobj = execute_abs_path_expr(schemaroot, object_path);
//III. For each schema node found (sn_obj)
std::vector<xptr> start_nodes;
for (int i = 0; i < sobj.size(); i++)
{
xptr blk= sobj[i]->bblk;
sobj[i]->add_ft_index(idc);
if (blk!=XNULL)
{
CHECKP(blk);
start_nodes.push_back((GETBLOCKFIRSTDESCRIPTORABSOLUTE(((node_blk_hdr*)XADDR(blk)))));
}
}
SednaIndexJob sij(idc);
sij.create_index(&start_nodes);
}
return idc;
}
void ft_index_cell::delete_index (const char *index_title, bool just_heap)
{
ft_index_sem_down();
pers_sset<ft_index_cell,unsigned short>::pers_sset_entry* idc=search_ft_indexdata_cell(index_title);
if (idc!=NULL)
{
if (!just_heap)
{
SednaIndexJob sij(idc->obj);
sij.clear_index();
}
down_concurrent_micro_ops_number();
hl_logical_log_ft_index((idc->obj)->object,(idc->obj)->ftype,(idc->obj)->index_title,(idc->obj)->doc_name,(idc->obj)->is_doc,(idc->obj)->custom_tree,false);
ft_index_cell* ic=idc->obj;
doc_schema_node* sm=(idc->obj)->schemaroot;
free_ft_indexdata_cell(idc);
(*ft_idx_counter)--;
sm->delete_ft_index(ic);
ft_index_sem_up();
up_concurrent_micro_ops_number();
}
else
ft_index_sem_up();
}
ft_index_cell* ft_index_cell::find_index(const char* title)
{
xptr res;
ft_index_sem_down();
pers_sset<ft_index_cell,unsigned short>::pers_sset_entry* idc=search_ft_indexdata_cell(title);
if (idc==NULL)
{
ft_index_sem_up();
return NULL;
}
else
{
ft_index_sem_up();
return idc->obj;
}
}
void ft_index_cell::update_index(xptr_sequence* upserted)
{
SednaIndexJob sij(this);
sij.update_index(upserted);
}
void ft_index_cell::insert_to_index(xptr_sequence* upserted)
{
SednaIndexJob sij(this);
sij.insert_into_index(upserted);
}
void ft_index_cell::delete_from_index(xptr_sequence* deleted)
{
SednaIndexJob sij(this);
sij.delete_from_index(deleted);
}
void ft_index_cell::change_index(xptr_sequence* inserted,xptr_sequence* updated,xptr_sequence* deleted)
{
SednaIndexJob sij(this);
sij.insert_into_index(inserted);
sij.update_index(updated);
sij.delete_from_index(deleted);
}
<commit_msg>ftindex fix<commit_after>/*
* File: ft_index_data.cpp
* Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)
*/
#include "common/sedna.h"
#include "tr/ft/ft_index_data.h"
#include "common/xptr.h"
#include "tr/crmutils/node_utils.h"
#include "tr/vmm/vmm.h"
#include "tr/executor/base/tuple.h"
#include "tr/ft/FTindex.h"
#include "tr/log/log.h"
#include "tr/structures/schema.h"
#include "tr/executor/fo/casting_operations.h"
//#include "indexes.h"
#include "tr/executor/base/dm_accessors.h"
using namespace std;
pers_sset<ft_index_cell,unsigned short> *ft_indexdata;
index_id *ft_idx_counter;
USemaphore ft_index_sem;//SEMAPHOR!!!
static bool ft_index_initialized = false;
//inits metadata library
void ft_index_on_session_begin(pers_sset<ft_index_cell,unsigned short> * _indexdata_, index_id *_idx_counter_)
{
ft_indexdata = _indexdata_;
ft_idx_counter = _idx_counter_;
//SEMAPHOR INIT SECTION
if (USemaphoreOpen(&ft_index_sem, FT_INDEX_SEMAPHORE_STR, __sys_call_error) != 0)
throw USER_EXCEPTION2(SE4012, "FT_INDEX_SEMAPHORE_STR");
ft_index_initialized = true;
}
void ft_index_on_session_end()
{
if (!ft_index_initialized) return;
//SEMAPHOR RELEASE SECTION
if (USemaphoreClose(ft_index_sem, __sys_call_error) != 0)
throw USER_EXCEPTION2(SE4013, "FT_INDEX_SEMAPHORE_STR");
ft_index_initialized = false;
}
pers_sset<ft_index_cell,unsigned short>::pers_sset_entry* search_ft_indexdata_cell(const char *index_title)
{
return ft_indexdata->get(index_title,NULL);
}
ft_custom_cell* ft_custom_cell::init(xml_ns* _ns, const char* _local,ft_index_type _cm,bool persistent)
{
ft_custom_cell* ftc=(ft_custom_cell*)scm_malloc(sizeof(ft_custom_cell),persistent);
ftc->ns=_ns;
if (_local!=NULL)
{
char* z=(char*)scm_malloc(strlen(_local)+1,persistent);
strcpy(z,_local);
ftc->local=z;
}
else
ftc->local=NULL;
ftc->cm=_cm;
return ftc;
}
void ft_index_cell::delete_custom_tree (pers_sset<ft_custom_cell,unsigned short> * custom_tree)
{
pers_sset<ft_custom_cell,unsigned short>::pers_sset_entry* tmp=custom_tree->rb_minimum(custom_tree->root);
while (tmp!=NULL)
{
//coll->free_metadata(tmp);
ft_custom_cell* mdc=tmp->obj;
if (mdc->local)
scm_free(mdc->local,IS_PH_PTR(mdc));
scm_free(mdc,IS_PH_PTR(mdc));
tmp->obj=NULL;
tmp=custom_tree->rb_successor(tmp);
}
pers_sset<ft_custom_cell,unsigned short>::sset_free(custom_tree);
}
void inline free_ft_indexdata_cell(pers_sset<ft_index_cell,unsigned short>::pers_sset_entry* entry)
{
ft_index_cell* idc=entry->obj;
ft_indexdata->rb_delete(entry);
if (idc->index_title!=NULL)
scm_free(idc->index_title,true);
delete_PathExpr(idc->object);
scm_free(idc->doc_name,true);
if (idc->custom_tree!=NULL)
ft_index_cell::delete_custom_tree(idc->custom_tree);
scm_free(idc,true);
}
bool ft_index_cell::fits_to_index(schema_node* snode)
{
t_scmnodes res;
t_scmnodes objs=execute_abs_path_expr(snode->root,object);
t_scmnodes::iterator it=objs.begin();
while (it!=objs.end())
{
if (*it==snode)
return true;
it++;
}
return false;
}
ft_index_cell* ft_index_cell::create_index (PathExpr *object_path, ft_index_type it, doc_schema_node* schemaroot,const char * index_title, const char* doc_name,bool is_doc,std::vector< std::pair< std::pair<xml_ns*,char*>,ft_index_type> >* templ, bool just_heap)
{
// I. Create and fill new index cell
ft_index_sem_down();
if (search_ft_indexdata_cell(index_title)!=NULL)
{
ft_index_sem_up();
throw USER_EXCEPTION(SE2033);
}
down_concurrent_micro_ops_number();
ft_index_cell* idc=(ft_index_cell*)scm_malloc(sizeof(ft_index_cell),true);
idc->id = *ft_idx_counter;
(*ft_idx_counter)++;
idc->schemaroot = schemaroot;
schemaroot->create_ft_index(idc);
idc->object = object_path;
idc->ftype=it;
idc->index_title=(char*)scm_malloc(strlen(index_title)+1,true);
strcpy(idc->index_title,index_title);
idc->doc_name=(char*)scm_malloc(strlen(doc_name)+1,true);
strcpy(idc->doc_name,doc_name);
idc->is_doc=is_doc;
if (it==ft_customized_value && templ!=NULL)
{
idc->custom_tree= pers_sset<ft_custom_cell,unsigned short>::init();
std::vector<std::pair<std::pair<xml_ns*,char*>,ft_index_type> >::iterator tmp=templ->begin();
while (tmp!=templ->end())
{
idc->custom_tree->put(ft_custom_cell::init((*tmp).first.first,(*tmp).first.second,(*tmp).second));
tmp++;
}
}
/*idc->next = *indexdata;
if ((*indexdata) != NULL) (*indexdata)->pred = idc;
*indexdata = idc;*/
ft_indexdata->put(idc);
ft_index_sem_up();
hl_logical_log_ft_index(object_path, it,(char *) index_title, doc_name,is_doc,idc->custom_tree,true);
up_concurrent_micro_ops_number();
// ALGORITHM: indexing data
//II. Execute abs path (object_path) on the desriptive schema
if (!just_heap)
{
t_scmnodes sobj = execute_abs_path_expr(schemaroot, object_path);
//III. For each schema node found (sn_obj)
std::vector<xptr> start_nodes;
for (int i = 0; i < sobj.size(); i++)
{
xptr blk= sobj[i]->bblk;
sobj[i]->add_ft_index(idc);
if (blk!=XNULL)
{
CHECKP(blk);
start_nodes.push_back((GETBLOCKFIRSTDESCRIPTORABSOLUTE(((node_blk_hdr*)XADDR(blk)))));
}
}
SednaIndexJob sij(idc);
sij.create_index(&start_nodes);
}
return idc;
}
void ft_index_cell::delete_index (const char *index_title, bool just_heap)
{
ft_index_sem_down();
pers_sset<ft_index_cell,unsigned short>::pers_sset_entry* idc=search_ft_indexdata_cell(index_title);
if (idc!=NULL)
{
down_concurrent_micro_ops_number();
hl_logical_log_ft_index((idc->obj)->object,(idc->obj)->ftype,(idc->obj)->index_title,(idc->obj)->doc_name,(idc->obj)->is_doc,(idc->obj)->custom_tree,false);
if (!just_heap) //FIXME: mb move out of down_concurrent_micro_ops_number() block
{
SednaIndexJob sij(idc->obj);
sij.clear_index();
}
ft_index_cell* ic=idc->obj;
doc_schema_node* sm=(idc->obj)->schemaroot;
free_ft_indexdata_cell(idc);
(*ft_idx_counter)--;
sm->delete_ft_index(ic);
ft_index_sem_up();
up_concurrent_micro_ops_number();
}
else
ft_index_sem_up();
}
ft_index_cell* ft_index_cell::find_index(const char* title)
{
xptr res;
ft_index_sem_down();
pers_sset<ft_index_cell,unsigned short>::pers_sset_entry* idc=search_ft_indexdata_cell(title);
if (idc==NULL)
{
ft_index_sem_up();
return NULL;
}
else
{
ft_index_sem_up();
return idc->obj;
}
}
void ft_index_cell::update_index(xptr_sequence* upserted)
{
SednaIndexJob sij(this);
sij.update_index(upserted);
}
void ft_index_cell::insert_to_index(xptr_sequence* upserted)
{
SednaIndexJob sij(this);
sij.insert_into_index(upserted);
}
void ft_index_cell::delete_from_index(xptr_sequence* deleted)
{
SednaIndexJob sij(this);
sij.delete_from_index(deleted);
}
void ft_index_cell::change_index(xptr_sequence* inserted,xptr_sequence* updated,xptr_sequence* deleted)
{
SednaIndexJob sij(this);
sij.insert_into_index(inserted);
sij.update_index(updated);
sij.delete_from_index(deleted);
}
<|endoftext|>
|
<commit_before>#include "QmitkSimpleExampleFunctionality.h"
#include "QmitkStdMultiWidget.h"
#include "QmitkSelectableGLWidget.h"
#include "QmitkSimpleExampleControls.h"
#include <qaction.h>
#include <qslider.h>
#include "slicer.xpm"
#include "mitkPlaneGeometry.h"
#include <mitkSurfaceData.h>
#include <mitkColorProperty.h>
#include <mitkLookupTable.h>
#include <mitkEventMapper.h>
#include <mitkGlobalInteraction.h>
#include <mitkCoordinateSupplier.h>
#include <mitkPointOperation.h>
#include <mitkDisplayCoordinateOperation.h>
#include <mitkDisplayVectorInteractor.h>
#include <mitkBaseRenderer.h>
#include <mitkInteractionConst.h>
#include <QmitkStepperAdapter.h>
#include <algorithm>
#if (defined(_MSC_VER) && (_MSC_VER <= 1200))
#include <xutility>
#else
#define _MAX max
#define _MIN min
#endif
QmitkSimpleExampleFunctionality::QmitkSimpleExampleFunctionality(QObject *parent, const char *name, QmitkStdMultiWidget *mitkStdMultiWidget, mitk::DataTreeIterator * it) : QmitkFunctionality(parent, name, it) ,
controls(NULL), multiWidget(mitkStdMultiWidget), opacityprop(NULL), lookupTableProp(NULL)
{
setAvailability(true);
mitk::GlobalInteraction* globalInteraction = dynamic_cast<mitk::GlobalInteraction*>(mitk::EventMapper::GetGlobalStateMachine());
if(globalInteraction!=NULL)
{
globalInteraction->AddStateMachine(new mitk::CoordinateSupplier("navigation", this));//sends PointOperations
globalInteraction->AddStateMachine(new mitk::DisplayVectorInteractor("move", this));//sends DisplayCoordinateOperation
globalInteraction->AddStateMachine(new mitk::DisplayVectorInteractor("zoom", this));//sends DisplayCoordinateOperation
}
m_DataTreeIterator->getTree()->addTreeChangeListener(this);
}
QmitkSimpleExampleFunctionality::~QmitkSimpleExampleFunctionality()
{
}
QString QmitkSimpleExampleFunctionality::getFunctionalityName()
{
return "simple example";
}
QWidget * QmitkSimpleExampleFunctionality::createMainWidget(QWidget *parent)
{
if (multiWidget == NULL)
{
return multiWidget = new QmitkStdMultiWidget(parent);
}
else
return NULL;
}
QWidget * QmitkSimpleExampleFunctionality::createControlWidget(QWidget *parent)
{
if (controls == NULL)
{
controls = new QmitkSimpleExampleControls(parent);
sliceNavigatorTransversal = mitk::SliceNavigationController::New();
sliceNavigatorTransversal->SetViewDirection(mitk::SliceNavigationController::Transversal);
sliceNavigatorTransversal->ConnectGeometrySliceEvent(multiWidget->mitkWidget1->GetRenderer().GetPointer());
new QmitkStepperAdapter(controls->getSliceNavigatorTransversal(), sliceNavigatorTransversal->GetSlice(), "sliceNavigatorTransversalFromSimpleExample");
sliceNavigatorSagittal = mitk::SliceNavigationController::New();
sliceNavigatorSagittal->SetViewDirection(mitk::SliceNavigationController::Sagittal);
sliceNavigatorSagittal->ConnectGeometrySliceEvent(multiWidget->mitkWidget2->GetRenderer().GetPointer());
new QmitkStepperAdapter(controls->getSliceNavigatorSagittal(), sliceNavigatorSagittal->GetSlice(), "sliceNavigatorSagittalFromSimpleExample");
sliceNavigatorFrontal = mitk::SliceNavigationController::New();
sliceNavigatorFrontal->SetViewDirection(mitk::SliceNavigationController::Frontal);
sliceNavigatorFrontal->ConnectGeometrySliceEvent(multiWidget->mitkWidget3->GetRenderer().GetPointer());
new QmitkStepperAdapter(controls->getSliceNavigatorFrontal(), sliceNavigatorFrontal->GetSlice(), "sliceNavigatorFrontalFromSimpleExample");
sliceNavigatorTime = mitk::SliceNavigationController::New();
sliceNavigatorTime->ConnectGeometryTimeEvent(multiWidget->mitkWidget1->GetRenderer().GetPointer());
new QmitkStepperAdapter(controls->getSliceNavigatorTime(), sliceNavigatorTime->GetTime(), "sliceNavigatorTimeFromSimpleExample");
}
return controls;
}
void QmitkSimpleExampleFunctionality::createConnections()
{
connect(controls, SIGNAL(xySliderChanged(int)), this, SLOT(selectSliceWidgetXY(int)) );
connect(controls, SIGNAL(yzSliderChanged(int)), this, SLOT(selectSliceWidgetYZ(int)) );
connect(controls, SIGNAL(xzSliderChanged(int)), this, SLOT(selectSliceWidgetXZ(int)) );
connect(controls, SIGNAL(fpSliderChanged(int)), this, SLOT(selectSliceWidgetFP(int)) );
}
QAction * QmitkSimpleExampleFunctionality::createAction(QActionGroup *parent)
{
QAction* action;
action = new QAction( tr( "Left" ), QPixmap((const char**)slicer_xpm), tr( "&Left" ), CTRL + Key_L, parent, "simple example" );
// action = new QAction( tr( "Left" ), QPixmap(textleft_xpm), tr( "&Left" ), CTRL + Key_L, parent, "simple example" );
return action;
}
void QmitkSimpleExampleFunctionality::initNavigators()
{
const mitk::BoundingBox::Pointer boundingbox = mitk::DataTree::ComputeVisibleBoundingBox(m_DataTreeIterator, NULL, "includeInBoundingBox");
if(boundingbox->GetPoints()->Size()>0)
{
mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New();
geometry->Initialize();
geometry->SetBoundingBox(boundingbox);
sliceNavigatorTransversal->SetInputWorldGeometry(geometry.GetPointer()); sliceNavigatorTransversal->Update();
sliceNavigatorFrontal->SetInputWorldGeometry(geometry.GetPointer()); sliceNavigatorFrontal->Update();
sliceNavigatorSagittal->SetInputWorldGeometry(geometry.GetPointer()); sliceNavigatorSagittal->Update();
}
}
void QmitkSimpleExampleFunctionality::treeChanged(mitk::DataTreeIterator& itpos)
{
if(isActivated())
initNavigators();
}
void QmitkSimpleExampleFunctionality::activated()
{
QmitkFunctionality::activated();
assert( multiWidget != NULL );
// init widget 4 as a 3D widget
multiWidget->mitkWidget4->GetRenderer()->SetMapperID(2);
initNavigators();
}
//void QmitkSimpleExampleFunctionality::deactivated()
//{
//
//}
void QmitkSimpleExampleFunctionality::selectSliceWidgetXY( int z )
{
const mitk::Geometry2D* g2d = multiWidget->mitkWidget1->GetRenderer()->GetCurrentWorldGeometry2D();
const mitk::PlaneGeometry* pg = dynamic_cast<const mitk::PlaneGeometry*>(g2d);
mitk::PlaneView pv = pg->GetPlaneView();
pv.point.z = z;
mitk::PlaneGeometry::Pointer plane = mitk::PlaneGeometry::New();
plane->SetPlaneView(pv);
multiWidget->mitkWidget1->GetRenderer()->SetWorldGeometry(plane);
multiWidget->updateMitkWidgets();
//std::cout << "Slider:" << z << std::endl;
}
void QmitkSimpleExampleFunctionality::selectSliceWidgetXZ(int y)
{
const mitk::Geometry2D* g2d = multiWidget->mitkWidget3->GetRenderer()->GetCurrentWorldGeometry2D();
const mitk::PlaneGeometry* pg = dynamic_cast<const mitk::PlaneGeometry*>(g2d);
mitk::PlaneView pv = pg->GetPlaneView();
pv.point.y=y;
mitk::PlaneGeometry::Pointer plane = mitk::PlaneGeometry::New();
plane->SetPlaneView(pv);
multiWidget->mitkWidget3->GetRenderer()->SetWorldGeometry(plane);
multiWidget->updateMitkWidgets();
//std::cout << "Slider:" << y << std::endl;
}
void QmitkSimpleExampleFunctionality::selectSliceWidgetYZ(int x)
{
const mitk::Geometry2D* g2d = multiWidget->mitkWidget2->GetRenderer()->GetCurrentWorldGeometry2D();
const mitk::PlaneGeometry* pg = dynamic_cast<const mitk::PlaneGeometry*>(g2d);
mitk::PlaneView pv = pg->GetPlaneView();
pv.point.x = x;
mitk::PlaneGeometry::Pointer plane = mitk::PlaneGeometry::New();
plane->SetPlaneView(pv);
multiWidget->mitkWidget2->GetRenderer()->SetWorldGeometry(plane);
multiWidget->updateMitkWidgets();
//std::cout << "Slider:" << x << std::endl;
}
void QmitkSimpleExampleFunctionality::selectSliceWidgetFP( int p )
{
bool update=false;
if( opacityprop.IsNotNull() )
{
opacityprop->SetValue(p/100.0);
update = true;
}
if(lookupTableProp.IsNotNull())
{
lookupTableProp->GetLookupTable().ChangeOpacityForAll(p/100.0);
update = true;
}
if(update)
multiWidget->updateMitkWidgets();
}
void QmitkSimpleExampleFunctionality::initWidgets()
{
int count = 0;
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
while (it->hasNext()) {
it->next();
printf("\nrequesting boundingbox\n");
mitk::DataTreeNode::Pointer node = it->get();
mitk::BaseData::Pointer data=node->GetData();
if((data.IsNotNull()) && (dynamic_cast<mitk::Geometry2DData*>(node->GetData()) == NULL ))
{
// get
if ((data->GetUpdatedGeometry())!=NULL )
{
mitk::BoundingBox::ConstPointer bb = data->GetGeometry()->GetBoundingBox();
printf("boundsArrayType\n");
const mitk::BoundingBox::BoundsArrayType bounds = bb->GetBounds();
printf("\nboundingbox\n");
// init slider limits
controls->sliderYZ->setMinValue(std::_MIN<int>(bounds[0],controls->sliderYZ->minValue()));
controls->sliderYZ->setMaxValue(std::_MAX<int>(bounds[1],controls->sliderYZ->maxValue()));
controls->sliderXZ->setMinValue(std::_MIN<int>(bounds[2],controls->sliderXZ->minValue()));
controls->sliderXZ->setMaxValue(std::_MAX<int>(bounds[3],controls->sliderXZ->maxValue()));
controls->sliderXY->setMinValue(std::_MIN<int>(bounds[4],controls->sliderXY->minValue()));
controls->sliderXY->setMaxValue(std::_MAX<int>(bounds[5],controls->sliderXY->maxValue()));
count++;
}
lookupTableProp=NULL;
}
}
delete it;
}
void QmitkSimpleExampleFunctionality::ExecuteOperation(mitk::Operation* operation)
{
bool ok;//as return
mitk::PointOperation* pointoperation=dynamic_cast<mitk::PointOperation*>(operation);
if(pointoperation!=NULL)
{
/****NAVIGATION inside the volume****/
switch (operation->GetOperationType())
{
case mitk::OpMOVE:
{
mitk::ITKPoint3D point;
mitk::Point3D seed;
point = pointoperation->GetPoint();
mitk::itk2vm(point, seed);
const mitk::Geometry2D* g2d;
const mitk::PlaneGeometry* pg;
mitk::PlaneView pv;
mitk::PlaneGeometry::Pointer plane;
int v;
v=(int)seed.x;
if(controls->getSliderYZ()->value()!=v)
{
g2d = multiWidget->mitkWidget2->GetRenderer()->GetCurrentWorldGeometry2D();
pg = dynamic_cast<const mitk::PlaneGeometry*>(g2d);
pv = pg->GetPlaneView();
pv.point.x = v;
plane = mitk::PlaneGeometry::New();
plane->SetPlaneView(pv);
multiWidget->mitkWidget2->GetRenderer()->SetWorldGeometry(plane);
controls->getSliderYZ()->blockSignals(true);
controls->getSliderYZ()->setValue(v);
controls->getSliderYZ()->blockSignals(false);
}
v=(int)seed.y;
if(controls->getSliderXZ()->value()!=v)
{
g2d = multiWidget->mitkWidget3->GetRenderer()->GetCurrentWorldGeometry2D();
pg = dynamic_cast<const mitk::PlaneGeometry*>(g2d);
pv = pg->GetPlaneView();
pv.point.y = v;
plane = mitk::PlaneGeometry::New();
plane->SetPlaneView(pv);
multiWidget->mitkWidget3->GetRenderer()->SetWorldGeometry(plane);
controls->getSliderXZ()->blockSignals(true);
controls->getSliderXZ()->setValue(v);
controls->getSliderXZ()->blockSignals(false);
}
v=(int)seed.z;
if(controls->getSliderXY()->value()!=v)
{
g2d = multiWidget->mitkWidget1->GetRenderer()->GetCurrentWorldGeometry2D();
pg = dynamic_cast<const mitk::PlaneGeometry*>(g2d);
pv = pg->GetPlaneView();
pv.point.z = v;
plane = mitk::PlaneGeometry::New();
plane->SetPlaneView(pv);
multiWidget->mitkWidget1->GetRenderer()->SetWorldGeometry(plane);
controls->getSliderXY()->blockSignals(true);
controls->getSliderXY()->setValue(v);
controls->getSliderXY()->blockSignals(false);
}
multiWidget->updateMitkWidgets();
ok = true;
}
break;
case mitk::OpNOTHING:
break;
default:
;
}
}
mitk::DisplayCoordinateOperation* dcOperation=dynamic_cast<mitk::DisplayCoordinateOperation*>(operation);
if( dcOperation != NULL )
{
/****ZOOM & MOVE of the whole volume****/
mitk::BaseRenderer* renderer = dcOperation->GetRenderer();
if( renderer == NULL )
return;
switch (operation->GetOperationType())
{
case mitk::OpMOVE :
{
renderer->GetDisplayGeometry()->MoveBy(dcOperation->GetLastToCurrentDisplayVector()*(-1.0));
renderer->GetRenderWindow()->Update();
ok = true;
}
break;
case mitk::OpZOOM :
{
float distance = dcOperation->GetLastToCurrentDisplayVector().y;
distance = (distance > 0 ? 1 : (distance < 0 ? -1 : 0));
float factor= 1.0 + distance * 0.05;
renderer->GetDisplayGeometry()->Zoom(factor, dcOperation->GetStartDisplayCoordinate());
renderer->GetRenderWindow()->Update();
ok = true;
}
break;
default:
;
}
}
}
<commit_msg>initialization of time-slicenavigationcontroller. works a bit.<commit_after>#include "QmitkSimpleExampleFunctionality.h"
#include "QmitkStdMultiWidget.h"
#include "QmitkSelectableGLWidget.h"
#include "QmitkSimpleExampleControls.h"
#include <qaction.h>
#include <qslider.h>
#include "slicer.xpm"
#include "mitkPlaneGeometry.h"
#include <mitkSurfaceData.h>
#include <mitkColorProperty.h>
#include <mitkLookupTable.h>
#include <mitkEventMapper.h>
#include <mitkGlobalInteraction.h>
#include <mitkCoordinateSupplier.h>
#include <mitkPointOperation.h>
#include <mitkDisplayCoordinateOperation.h>
#include <mitkDisplayVectorInteractor.h>
#include <mitkBaseRenderer.h>
#include <mitkInteractionConst.h>
#include <QmitkStepperAdapter.h>
#include <algorithm>
#if (defined(_MSC_VER) && (_MSC_VER <= 1200))
#include <xutility>
#else
#define _MAX max
#define _MIN min
#endif
QmitkSimpleExampleFunctionality::QmitkSimpleExampleFunctionality(QObject *parent, const char *name, QmitkStdMultiWidget *mitkStdMultiWidget, mitk::DataTreeIterator * it) : QmitkFunctionality(parent, name, it) ,
controls(NULL), multiWidget(mitkStdMultiWidget), opacityprop(NULL), lookupTableProp(NULL)
{
setAvailability(true);
mitk::GlobalInteraction* globalInteraction = dynamic_cast<mitk::GlobalInteraction*>(mitk::EventMapper::GetGlobalStateMachine());
if(globalInteraction!=NULL)
{
globalInteraction->AddStateMachine(new mitk::CoordinateSupplier("navigation", this));//sends PointOperations
globalInteraction->AddStateMachine(new mitk::DisplayVectorInteractor("move", this));//sends DisplayCoordinateOperation
globalInteraction->AddStateMachine(new mitk::DisplayVectorInteractor("zoom", this));//sends DisplayCoordinateOperation
}
m_DataTreeIterator->getTree()->addTreeChangeListener(this);
}
QmitkSimpleExampleFunctionality::~QmitkSimpleExampleFunctionality()
{
}
QString QmitkSimpleExampleFunctionality::getFunctionalityName()
{
return "simple example";
}
QWidget * QmitkSimpleExampleFunctionality::createMainWidget(QWidget *parent)
{
if (multiWidget == NULL)
{
return multiWidget = new QmitkStdMultiWidget(parent);
}
else
return NULL;
}
QWidget * QmitkSimpleExampleFunctionality::createControlWidget(QWidget *parent)
{
if (controls == NULL)
{
controls = new QmitkSimpleExampleControls(parent);
sliceNavigatorTransversal = mitk::SliceNavigationController::New();
sliceNavigatorTransversal->SetViewDirection(mitk::SliceNavigationController::Transversal);
sliceNavigatorTransversal->ConnectGeometrySliceEvent(multiWidget->mitkWidget1->GetRenderer().GetPointer());
new QmitkStepperAdapter(controls->getSliceNavigatorTransversal(), sliceNavigatorTransversal->GetSlice(), "sliceNavigatorTransversalFromSimpleExample");
sliceNavigatorSagittal = mitk::SliceNavigationController::New();
sliceNavigatorSagittal->SetViewDirection(mitk::SliceNavigationController::Sagittal);
sliceNavigatorSagittal->ConnectGeometrySliceEvent(multiWidget->mitkWidget2->GetRenderer().GetPointer());
new QmitkStepperAdapter(controls->getSliceNavigatorSagittal(), sliceNavigatorSagittal->GetSlice(), "sliceNavigatorSagittalFromSimpleExample");
sliceNavigatorFrontal = mitk::SliceNavigationController::New();
sliceNavigatorFrontal->SetViewDirection(mitk::SliceNavigationController::Frontal);
sliceNavigatorFrontal->ConnectGeometrySliceEvent(multiWidget->mitkWidget3->GetRenderer().GetPointer());
new QmitkStepperAdapter(controls->getSliceNavigatorFrontal(), sliceNavigatorFrontal->GetSlice(), "sliceNavigatorFrontalFromSimpleExample");
sliceNavigatorTime = mitk::SliceNavigationController::New();
sliceNavigatorTime->ConnectGeometryTimeEvent(multiWidget->mitkWidget1->GetRenderer().GetPointer());
new QmitkStepperAdapter(controls->getSliceNavigatorTime(), sliceNavigatorTime->GetTime(), "sliceNavigatorTimeFromSimpleExample");
}
return controls;
}
void QmitkSimpleExampleFunctionality::createConnections()
{
connect(controls, SIGNAL(xySliderChanged(int)), this, SLOT(selectSliceWidgetXY(int)) );
connect(controls, SIGNAL(yzSliderChanged(int)), this, SLOT(selectSliceWidgetYZ(int)) );
connect(controls, SIGNAL(xzSliderChanged(int)), this, SLOT(selectSliceWidgetXZ(int)) );
connect(controls, SIGNAL(fpSliderChanged(int)), this, SLOT(selectSliceWidgetFP(int)) );
}
QAction * QmitkSimpleExampleFunctionality::createAction(QActionGroup *parent)
{
QAction* action;
action = new QAction( tr( "Left" ), QPixmap((const char**)slicer_xpm), tr( "&Left" ), CTRL + Key_L, parent, "simple example" );
// action = new QAction( tr( "Left" ), QPixmap(textleft_xpm), tr( "&Left" ), CTRL + Key_L, parent, "simple example" );
return action;
}
void QmitkSimpleExampleFunctionality::initNavigators()
{
const mitk::BoundingBox::Pointer boundingbox = mitk::DataTree::ComputeVisibleBoundingBox(m_DataTreeIterator, NULL, "includeInBoundingBox");
if(boundingbox->GetPoints()->Size()>0)
{
// const mitk::BoundingBox::Pointer bb=boundingbox;
//const mitk::BoundingBox::BoundsArrayType bounds = bb->GetBounds();
// float boundingbox[6]={-2*bounds[1],2*bounds[1],-2*bounds[3],2*bounds[3],-2*bounds[5],2*bounds[5]};
mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New();
geometry->Initialize();
geometry->SetBoundingBox(boundingbox);
//lets see if we have data with a limited live-span ...
mitk::TimeBounds timebounds = mitk::DataTree::ComputeTimeBoundsInMS(m_DataTreeIterator, NULL, "includeInBoundingBox");
if(timebounds[1]<mitk::ScalarTypeNumericTraits::max())
{
mitk::TimeSlicedGeometry::Pointer timegeometry = mitk::TimeSlicedGeometry::New();
timegeometry->Initialize(10);
timegeometry->SetTimeBoundsInMS(timebounds); //@bug really required?
timegeometry->SetEvenlyTimed();
mitk::ScalarType duration = timebounds[1]-timebounds[0];
timebounds[1] = timebounds[0]+duration/10.0;
timegeometry->SetGeometry3D(geometry, 0);
geometry->SetTimeBoundsInMS(timebounds);
geometry=timegeometry;
}
sliceNavigatorTransversal->SetInputWorldGeometry(geometry.GetPointer()); sliceNavigatorTransversal->Update();
sliceNavigatorFrontal->SetInputWorldGeometry(geometry.GetPointer()); sliceNavigatorFrontal->Update();
sliceNavigatorSagittal->SetInputWorldGeometry(geometry.GetPointer()); sliceNavigatorSagittal->Update();
sliceNavigatorTime->SetInputWorldGeometry(geometry.GetPointer()); sliceNavigatorTime->Update();
}
}
void QmitkSimpleExampleFunctionality::treeChanged(mitk::DataTreeIterator& itpos)
{
if(isActivated())
initNavigators();
}
void QmitkSimpleExampleFunctionality::activated()
{
QmitkFunctionality::activated();
assert( multiWidget != NULL );
// init widget 4 as a 3D widget
multiWidget->mitkWidget4->GetRenderer()->SetMapperID(2);
initNavigators();
}
//void QmitkSimpleExampleFunctionality::deactivated()
//{
//
//}
void QmitkSimpleExampleFunctionality::selectSliceWidgetXY( int z )
{
const mitk::Geometry2D* g2d = multiWidget->mitkWidget1->GetRenderer()->GetCurrentWorldGeometry2D();
const mitk::PlaneGeometry* pg = dynamic_cast<const mitk::PlaneGeometry*>(g2d);
mitk::PlaneView pv = pg->GetPlaneView();
pv.point.z = z;
mitk::PlaneGeometry::Pointer plane = mitk::PlaneGeometry::New();
plane->SetPlaneView(pv);
multiWidget->mitkWidget1->GetRenderer()->SetWorldGeometry(plane);
multiWidget->updateMitkWidgets();
//std::cout << "Slider:" << z << std::endl;
}
void QmitkSimpleExampleFunctionality::selectSliceWidgetXZ(int y)
{
const mitk::Geometry2D* g2d = multiWidget->mitkWidget3->GetRenderer()->GetCurrentWorldGeometry2D();
const mitk::PlaneGeometry* pg = dynamic_cast<const mitk::PlaneGeometry*>(g2d);
mitk::PlaneView pv = pg->GetPlaneView();
pv.point.y=y;
mitk::PlaneGeometry::Pointer plane = mitk::PlaneGeometry::New();
plane->SetPlaneView(pv);
multiWidget->mitkWidget3->GetRenderer()->SetWorldGeometry(plane);
multiWidget->updateMitkWidgets();
//std::cout << "Slider:" << y << std::endl;
}
void QmitkSimpleExampleFunctionality::selectSliceWidgetYZ(int x)
{
const mitk::Geometry2D* g2d = multiWidget->mitkWidget2->GetRenderer()->GetCurrentWorldGeometry2D();
const mitk::PlaneGeometry* pg = dynamic_cast<const mitk::PlaneGeometry*>(g2d);
mitk::PlaneView pv = pg->GetPlaneView();
pv.point.x = x;
mitk::PlaneGeometry::Pointer plane = mitk::PlaneGeometry::New();
plane->SetPlaneView(pv);
multiWidget->mitkWidget2->GetRenderer()->SetWorldGeometry(plane);
multiWidget->updateMitkWidgets();
//std::cout << "Slider:" << x << std::endl;
}
void QmitkSimpleExampleFunctionality::selectSliceWidgetFP( int p )
{
bool update=false;
if( opacityprop.IsNotNull() )
{
opacityprop->SetValue(p/100.0);
update = true;
}
if(lookupTableProp.IsNotNull())
{
lookupTableProp->GetLookupTable().ChangeOpacityForAll(p/100.0);
update = true;
}
if(update)
multiWidget->updateMitkWidgets();
}
void QmitkSimpleExampleFunctionality::initWidgets()
{
int count = 0;
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
while (it->hasNext()) {
it->next();
printf("\nrequesting boundingbox\n");
mitk::DataTreeNode::Pointer node = it->get();
mitk::BaseData::Pointer data=node->GetData();
if((data.IsNotNull()) && (dynamic_cast<mitk::Geometry2DData*>(node->GetData()) == NULL ))
{
// get
if ((data->GetUpdatedGeometry())!=NULL )
{
mitk::BoundingBox::ConstPointer bb = data->GetGeometry()->GetBoundingBox();
printf("boundsArrayType\n");
const mitk::BoundingBox::BoundsArrayType bounds = bb->GetBounds();
printf("\nboundingbox\n");
// init slider limits
controls->sliderYZ->setMinValue(std::_MIN<int>(bounds[0],controls->sliderYZ->minValue()));
controls->sliderYZ->setMaxValue(std::_MAX<int>(bounds[1],controls->sliderYZ->maxValue()));
controls->sliderXZ->setMinValue(std::_MIN<int>(bounds[2],controls->sliderXZ->minValue()));
controls->sliderXZ->setMaxValue(std::_MAX<int>(bounds[3],controls->sliderXZ->maxValue()));
controls->sliderXY->setMinValue(std::_MIN<int>(bounds[4],controls->sliderXY->minValue()));
controls->sliderXY->setMaxValue(std::_MAX<int>(bounds[5],controls->sliderXY->maxValue()));
count++;
}
lookupTableProp=NULL;
}
}
delete it;
}
void QmitkSimpleExampleFunctionality::ExecuteOperation(mitk::Operation* operation)
{
bool ok;//as return
mitk::PointOperation* pointoperation=dynamic_cast<mitk::PointOperation*>(operation);
if(pointoperation!=NULL)
{
/****NAVIGATION inside the volume****/
switch (operation->GetOperationType())
{
case mitk::OpMOVE:
{
mitk::ITKPoint3D point;
mitk::Point3D seed;
point = pointoperation->GetPoint();
mitk::itk2vm(point, seed);
const mitk::Geometry2D* g2d;
const mitk::PlaneGeometry* pg;
mitk::PlaneView pv;
mitk::PlaneGeometry::Pointer plane;
int v;
v=(int)seed.x;
if(controls->getSliderYZ()->value()!=v)
{
g2d = multiWidget->mitkWidget2->GetRenderer()->GetCurrentWorldGeometry2D();
pg = dynamic_cast<const mitk::PlaneGeometry*>(g2d);
pv = pg->GetPlaneView();
pv.point.x = v;
plane = mitk::PlaneGeometry::New();
plane->SetPlaneView(pv);
multiWidget->mitkWidget2->GetRenderer()->SetWorldGeometry(plane);
controls->getSliderYZ()->blockSignals(true);
controls->getSliderYZ()->setValue(v);
controls->getSliderYZ()->blockSignals(false);
}
v=(int)seed.y;
if(controls->getSliderXZ()->value()!=v)
{
g2d = multiWidget->mitkWidget3->GetRenderer()->GetCurrentWorldGeometry2D();
pg = dynamic_cast<const mitk::PlaneGeometry*>(g2d);
pv = pg->GetPlaneView();
pv.point.y = v;
plane = mitk::PlaneGeometry::New();
plane->SetPlaneView(pv);
multiWidget->mitkWidget3->GetRenderer()->SetWorldGeometry(plane);
controls->getSliderXZ()->blockSignals(true);
controls->getSliderXZ()->setValue(v);
controls->getSliderXZ()->blockSignals(false);
}
v=(int)seed.z;
if(controls->getSliderXY()->value()!=v)
{
g2d = multiWidget->mitkWidget1->GetRenderer()->GetCurrentWorldGeometry2D();
pg = dynamic_cast<const mitk::PlaneGeometry*>(g2d);
pv = pg->GetPlaneView();
pv.point.z = v;
plane = mitk::PlaneGeometry::New();
plane->SetPlaneView(pv);
multiWidget->mitkWidget1->GetRenderer()->SetWorldGeometry(plane);
controls->getSliderXY()->blockSignals(true);
controls->getSliderXY()->setValue(v);
controls->getSliderXY()->blockSignals(false);
}
multiWidget->updateMitkWidgets();
ok = true;
}
break;
case mitk::OpNOTHING:
break;
default:
;
}
}
mitk::DisplayCoordinateOperation* dcOperation=dynamic_cast<mitk::DisplayCoordinateOperation*>(operation);
if( dcOperation != NULL )
{
/****ZOOM & MOVE of the whole volume****/
mitk::BaseRenderer* renderer = dcOperation->GetRenderer();
if( renderer == NULL )
return;
switch (operation->GetOperationType())
{
case mitk::OpMOVE :
{
renderer->GetDisplayGeometry()->MoveBy(dcOperation->GetLastToCurrentDisplayVector()*(-1.0));
renderer->GetRenderWindow()->Update();
ok = true;
}
break;
case mitk::OpZOOM :
{
float distance = dcOperation->GetLastToCurrentDisplayVector().y;
distance = (distance > 0 ? 1 : (distance < 0 ? -1 : 0));
float factor= 1.0 + distance * 0.05;
renderer->GetDisplayGeometry()->Zoom(factor, dcOperation->GetStartDisplayCoordinate());
renderer->GetRenderWindow()->Update();
ok = true;
}
break;
default:
;
}
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: AccessibleSlideSorterObject.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: ihi $ $Date: 2006-11-14 14:23:53 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "AccessibleSlideSorterObject.hxx"
#include "controller/SlideSorterController.hxx"
#include "controller/SlsPageSelector.hxx"
#include "controller/SlsFocusManager.hxx"
#include "model/SlideSorterModel.hxx"
#include "model/SlsPageDescriptor.hxx"
#include "view/SlideSorterView.hxx"
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
#endif
#ifndef COMPHELPER_ACCESSIBLE_EVENT_NOTIFIER
#include <comphelper/accessibleeventnotifier.hxx>
#endif
#include <unotools/accessiblestatesethelper.hxx>
#include "sdpage.hxx"
#include "sdresid.hxx"
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#include "glob.hrc"
using ::rtl::OUString;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::accessibility;
namespace accessibility {
AccessibleSlideSorterObject::AccessibleSlideSorterObject(
const Reference<XAccessible>& rxParent,
::sd::slidesorter::controller::SlideSorterController& rSlideSorterController,
sal_uInt16 nPageNumber)
: AccessibleSlideSorterObjectBase(::sd::MutexOwner::maMutex),
mxParent(rxParent),
mnPageNumber(nPageNumber),
mrSlideSorterController(rSlideSorterController),
mnClientId(0)
{
}
AccessibleSlideSorterObject::~AccessibleSlideSorterObject (void)
{
if ( ! IsDisposed())
dispose();
}
sal_uInt16 AccessibleSlideSorterObject::GetPageNumber (void) const
{
return mnPageNumber;
}
void AccessibleSlideSorterObject::FireAccessibleEvent (
short nEventId,
const uno::Any& rOldValue,
const uno::Any& rNewValue)
{
if (mnClientId != 0)
{
AccessibleEventObject aEventObject;
aEventObject.Source = Reference<XWeak>(this);
aEventObject.EventId = nEventId;
aEventObject.NewValue = rNewValue;
aEventObject.OldValue = rOldValue;
comphelper::AccessibleEventNotifier::addEvent(mnClientId, aEventObject);
}
}
void SAL_CALL AccessibleSlideSorterObject::disposing (void)
{
const vos::OGuard aSolarGuard (Application::GetSolarMutex());
// Send a disposing to all listeners.
if (mnClientId != 0)
{
comphelper::AccessibleEventNotifier::revokeClientNotifyDisposing(mnClientId, *this);
mnClientId = 0;
}
}
//===== XAccessible ===========================================================
Reference<XAccessibleContext> SAL_CALL
AccessibleSlideSorterObject::getAccessibleContext (void)
throw (uno::RuntimeException)
{
ThrowIfDisposed();
return this;
}
//===== XAccessibleContext ====================================================
sal_Int32 SAL_CALL AccessibleSlideSorterObject::getAccessibleChildCount (void)
throw (uno::RuntimeException)
{
ThrowIfDisposed();
return 0;
}
Reference<XAccessible> SAL_CALL AccessibleSlideSorterObject::getAccessibleChild (sal_Int32 i)
throw (lang::IndexOutOfBoundsException, RuntimeException)
{
ThrowIfDisposed();
throw lang::IndexOutOfBoundsException();
return Reference<XAccessible>();
}
Reference<XAccessible> SAL_CALL AccessibleSlideSorterObject::getAccessibleParent (void)
throw (uno::RuntimeException)
{
ThrowIfDisposed();
return mxParent;
}
sal_Int32 SAL_CALL AccessibleSlideSorterObject::getAccessibleIndexInParent()
throw (uno::RuntimeException)
{
ThrowIfDisposed();
const vos::OGuard aSolarGuard (Application::GetSolarMutex());
sal_Int32 nIndexInParent(-1);
if (mxParent.is())
{
Reference<XAccessibleContext> xParentContext (mxParent->getAccessibleContext());
if (xParentContext.is())
{
sal_Int32 nChildCount (xParentContext->getAccessibleChildCount());
for (sal_Int32 i=0; i<nChildCount; ++i)
if (xParentContext->getAccessibleChild(i).get()
== static_cast<XAccessible*>(this))
{
nIndexInParent = i;
break;
}
}
}
return nIndexInParent;
}
sal_Int16 SAL_CALL AccessibleSlideSorterObject::getAccessibleRole (void)
throw (uno::RuntimeException)
{
ThrowIfDisposed();
static sal_Int16 nRole = AccessibleRole::LIST_ITEM;
return nRole;
}
::rtl::OUString SAL_CALL AccessibleSlideSorterObject::getAccessibleDescription (void)
throw (uno::RuntimeException)
{
ThrowIfDisposed();
return String(SdResId(STR_PAGE));
}
::rtl::OUString SAL_CALL AccessibleSlideSorterObject::getAccessibleName (void)
throw (uno::RuntimeException)
{
ThrowIfDisposed();
const vos::OGuard aSolarGuard (Application::GetSolarMutex());
SdPage* pPage = GetPage();
if (pPage != NULL)
return pPage->GetName();
else
return String();
}
Reference<XAccessibleRelationSet> SAL_CALL
AccessibleSlideSorterObject::getAccessibleRelationSet (void)
throw (uno::RuntimeException)
{
ThrowIfDisposed();
return Reference<XAccessibleRelationSet>();
}
Reference<XAccessibleStateSet> SAL_CALL
AccessibleSlideSorterObject::getAccessibleStateSet (void)
throw (uno::RuntimeException)
{
ThrowIfDisposed();
const vos::OGuard aSolarGuard (Application::GetSolarMutex());
::utl::AccessibleStateSetHelper* pStateSet = new ::utl::AccessibleStateSetHelper();
if (mxParent.is())
{
// SELECTABLE
pStateSet->AddState(AccessibleStateType::SELECTABLE);
// SELECTED
if (mrSlideSorterController.GetPageSelector().IsPageSelected(mnPageNumber))
pStateSet->AddState(AccessibleStateType::SELECTED);
// FOCUSABLE
pStateSet->AddState(AccessibleStateType::FOCUSABLE);
// FOCUSED
if (mrSlideSorterController.GetFocusManager().GetFocusedPageIndex() == mnPageNumber)
if (mrSlideSorterController.GetFocusManager().IsFocusShowing())
pStateSet->AddState(AccessibleStateType::FOCUSED);
pStateSet->AddState(AccessibleStateType::ENABLED);
pStateSet->AddState(AccessibleStateType::VISIBLE);
pStateSet->AddState(AccessibleStateType::SHOWING);
pStateSet->AddState(AccessibleStateType::ACTIVE);
}
return pStateSet;
}
lang::Locale SAL_CALL AccessibleSlideSorterObject::getLocale (void)
throw (IllegalAccessibleComponentStateException,
RuntimeException)
{
ThrowIfDisposed();
// Delegate request to parent.
if (mxParent.is())
{
Reference<XAccessibleContext> xParentContext (mxParent->getAccessibleContext());
if (xParentContext.is())
return xParentContext->getLocale ();
}
// No locale and no parent. Therefore throw exception to indicate this
// cluelessness.
throw IllegalAccessibleComponentStateException();
}
//===== XAccessibleEventBroadcaster ===========================================
void SAL_CALL AccessibleSlideSorterObject::addEventListener(
const Reference<XAccessibleEventListener>& rxListener)
throw (RuntimeException)
{
if (rxListener.is())
{
const osl::MutexGuard aGuard(maMutex);
if (IsDisposed())
{
uno::Reference<uno::XInterface> x ((lang::XComponent *)this, uno::UNO_QUERY);
rxListener->disposing (lang::EventObject (x));
}
else
{
if (mnClientId == 0)
mnClientId = comphelper::AccessibleEventNotifier::registerClient();
comphelper::AccessibleEventNotifier::addEventListener(mnClientId, rxListener);
}
}
}
void SAL_CALL AccessibleSlideSorterObject::removeEventListener(
const Reference<XAccessibleEventListener>& rxListener)
throw (uno::RuntimeException)
{
ThrowIfDisposed();
if (rxListener.is())
{
const osl::MutexGuard aGuard(maMutex);
sal_Int32 nListenerCount = comphelper::AccessibleEventNotifier::removeEventListener( mnClientId, rxListener );
if ( !nListenerCount )
{
// no listeners anymore
// -> revoke ourself. This may lead to the notifier thread dying (if we were the last client),
// and at least to us not firing any events anymore, in case somebody calls
// NotifyAccessibleEvent, again
comphelper::AccessibleEventNotifier::revokeClient( mnClientId );
mnClientId = 0;
}
}
}
//===== XAccessibleComponent ==================================================
sal_Bool SAL_CALL AccessibleSlideSorterObject::containsPoint(const awt::Point& aPoint)
throw (uno::RuntimeException)
{
ThrowIfDisposed();
const awt::Size aSize (getSize());
return (aPoint.X >= 0)
&& (aPoint.X < aSize.Width)
&& (aPoint.Y >= 0)
&& (aPoint.Y < aSize.Height);
}
Reference<XAccessible> SAL_CALL
AccessibleSlideSorterObject::getAccessibleAtPoint(const awt::Point& aPoint)
throw (uno::RuntimeException)
{
return NULL;
}
awt::Rectangle SAL_CALL AccessibleSlideSorterObject::getBounds (void)
throw (RuntimeException)
{
const vos::OGuard aSolarGuard( Application::GetSolarMutex() );
Rectangle aBBox (mrSlideSorterController.GetView().GetPageBoundingBox (
mnPageNumber,
::sd::slidesorter::view::SlideSorterView::CS_SCREEN,
::sd::slidesorter::view::SlideSorterView::BBT_INFO));
if (mxParent.is())
{
Reference<XAccessibleComponent> xParentComponent(mxParent->getAccessibleContext(), UNO_QUERY);
if (xParentComponent.is())
{
awt::Rectangle aParentBBox (xParentComponent->getBounds());
aBBox.Intersection(Rectangle(
aParentBBox.X,
aParentBBox.Y,
aParentBBox.Width,
aParentBBox.Height));
}
}
return awt::Rectangle(
aBBox.Left(),
aBBox.Top(),
aBBox.GetWidth(),
aBBox.GetHeight());
}
awt::Point SAL_CALL AccessibleSlideSorterObject::getLocation ()
throw (RuntimeException)
{
const awt::Rectangle aBBox (getBounds());
return awt::Point(aBBox.X, aBBox.Y);
}
awt::Point SAL_CALL AccessibleSlideSorterObject::getLocationOnScreen (void)
throw (RuntimeException)
{
const vos::OGuard aSolarGuard( Application::GetSolarMutex() );
awt::Point aLocation (getLocation());
if (mxParent.is())
{
Reference<XAccessibleComponent> xParentComponent(mxParent->getAccessibleContext(),UNO_QUERY);
if (xParentComponent.is())
{
const awt::Point aParentLocationOnScreen(xParentComponent->getLocationOnScreen());
aLocation.X += aParentLocationOnScreen.X;
aLocation.Y += aParentLocationOnScreen.Y;
}
}
return aLocation;
}
awt::Size SAL_CALL AccessibleSlideSorterObject::getSize (void)
throw (RuntimeException)
{
const awt::Rectangle aBBox (getBounds());
return awt::Size(aBBox.Width,aBBox.Height);
}
void SAL_CALL AccessibleSlideSorterObject::grabFocus (void)
throw (RuntimeException)
{
// nothing to do
}
sal_Int32 SAL_CALL AccessibleSlideSorterObject::getForeground (void)
throw (::com::sun::star::uno::RuntimeException)
{
svtools::ColorConfig aColorConfig;
UINT32 nColor = aColorConfig.GetColorValue( svtools::FONTCOLOR ).nColor;
return static_cast<sal_Int32>(nColor);
}
sal_Int32 SAL_CALL AccessibleSlideSorterObject::getBackground (void)
throw (::com::sun::star::uno::RuntimeException)
{
UINT32 nColor = Application::GetSettings().GetStyleSettings().GetWindowColor().GetColor();
return static_cast<sal_Int32>(nColor);
}
//===== XServiceInfo ========================================================
::rtl::OUString SAL_CALL
AccessibleSlideSorterObject::getImplementationName (void)
throw (::com::sun::star::uno::RuntimeException)
{
return OUString(RTL_CONSTASCII_USTRINGPARAM("AccessibleSlideSorterObject"));
}
sal_Bool SAL_CALL
AccessibleSlideSorterObject::supportsService (const OUString& sServiceName)
throw (::com::sun::star::uno::RuntimeException)
{
// Iterate over all supported service names and return true if on of them
// matches the given name.
uno::Sequence< ::rtl::OUString> aSupportedServices (
getSupportedServiceNames ());
for (int i=0; i<aSupportedServices.getLength(); i++)
if (sServiceName == aSupportedServices[i])
return sal_True;
return sal_False;
}
uno::Sequence< ::rtl::OUString> SAL_CALL
AccessibleSlideSorterObject::getSupportedServiceNames (void)
throw (::com::sun::star::uno::RuntimeException)
{
static const OUString sServiceNames[2] = {
OUString(RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.accessibility.Accessible")),
OUString(RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.accessibility.AccessibleContext"))
};
return uno::Sequence<OUString> (sServiceNames, 2);
}
void AccessibleSlideSorterObject::ThrowIfDisposed (void)
throw (lang::DisposedException)
{
if (rBHelper.bDisposed || rBHelper.bInDispose)
{
OSL_TRACE ("Calling disposed object. Throwing exception:");
throw lang::DisposedException (
OUString(RTL_CONSTASCII_USTRINGPARAM("object has been already disposed")),
static_cast<uno::XWeak*>(this));
}
}
sal_Bool AccessibleSlideSorterObject::IsDisposed (void)
{
return (rBHelper.bDisposed || rBHelper.bInDispose);
}
SdPage* AccessibleSlideSorterObject::GetPage (void) const
{
::sd::slidesorter::model::SharedPageDescriptor pDescriptor(
mrSlideSorterController.GetModel().GetPageDescriptor(mnPageNumber));
if (pDescriptor.get() != NULL)
return pDescriptor->GetPage();
else
return NULL;
}
} // end of namespace ::accessibility
<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.7.36); FILE MERGED 2006/11/22 15:00:03 cl 1.7.36.2: RESYNC: (1.7-1.8); FILE MERGED 2006/11/22 12:41:40 cl 1.7.36.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: AccessibleSlideSorterObject.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: kz $ $Date: 2006-12-12 16:49:05 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "AccessibleSlideSorterObject.hxx"
#include "controller/SlideSorterController.hxx"
#include "controller/SlsPageSelector.hxx"
#include "controller/SlsFocusManager.hxx"
#include "model/SlideSorterModel.hxx"
#include "model/SlsPageDescriptor.hxx"
#include "view/SlideSorterView.hxx"
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
#endif
#ifndef COMPHELPER_ACCESSIBLE_EVENT_NOTIFIER
#include <comphelper/accessibleeventnotifier.hxx>
#endif
#include <unotools/accessiblestatesethelper.hxx>
#include "sdpage.hxx"
#include "sdresid.hxx"
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#include "glob.hrc"
using ::rtl::OUString;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::accessibility;
namespace accessibility {
AccessibleSlideSorterObject::AccessibleSlideSorterObject(
const Reference<XAccessible>& rxParent,
::sd::slidesorter::controller::SlideSorterController& rSlideSorterController,
sal_uInt16 nPageNumber)
: AccessibleSlideSorterObjectBase(::sd::MutexOwner::maMutex),
mxParent(rxParent),
mnPageNumber(nPageNumber),
mrSlideSorterController(rSlideSorterController),
mnClientId(0)
{
}
AccessibleSlideSorterObject::~AccessibleSlideSorterObject (void)
{
if ( ! IsDisposed())
dispose();
}
sal_uInt16 AccessibleSlideSorterObject::GetPageNumber (void) const
{
return mnPageNumber;
}
void AccessibleSlideSorterObject::FireAccessibleEvent (
short nEventId,
const uno::Any& rOldValue,
const uno::Any& rNewValue)
{
if (mnClientId != 0)
{
AccessibleEventObject aEventObject;
aEventObject.Source = Reference<XWeak>(this);
aEventObject.EventId = nEventId;
aEventObject.NewValue = rNewValue;
aEventObject.OldValue = rOldValue;
comphelper::AccessibleEventNotifier::addEvent(mnClientId, aEventObject);
}
}
void SAL_CALL AccessibleSlideSorterObject::disposing (void)
{
const vos::OGuard aSolarGuard (Application::GetSolarMutex());
// Send a disposing to all listeners.
if (mnClientId != 0)
{
comphelper::AccessibleEventNotifier::revokeClientNotifyDisposing(mnClientId, *this);
mnClientId = 0;
}
}
//===== XAccessible ===========================================================
Reference<XAccessibleContext> SAL_CALL
AccessibleSlideSorterObject::getAccessibleContext (void)
throw (uno::RuntimeException)
{
ThrowIfDisposed();
return this;
}
//===== XAccessibleContext ====================================================
sal_Int32 SAL_CALL AccessibleSlideSorterObject::getAccessibleChildCount (void)
throw (uno::RuntimeException)
{
ThrowIfDisposed();
return 0;
}
Reference<XAccessible> SAL_CALL AccessibleSlideSorterObject::getAccessibleChild (sal_Int32 )
throw (lang::IndexOutOfBoundsException, RuntimeException)
{
ThrowIfDisposed();
throw lang::IndexOutOfBoundsException();
}
Reference<XAccessible> SAL_CALL AccessibleSlideSorterObject::getAccessibleParent (void)
throw (uno::RuntimeException)
{
ThrowIfDisposed();
return mxParent;
}
sal_Int32 SAL_CALL AccessibleSlideSorterObject::getAccessibleIndexInParent()
throw (uno::RuntimeException)
{
ThrowIfDisposed();
const vos::OGuard aSolarGuard (Application::GetSolarMutex());
sal_Int32 nIndexInParent(-1);
if (mxParent.is())
{
Reference<XAccessibleContext> xParentContext (mxParent->getAccessibleContext());
if (xParentContext.is())
{
sal_Int32 nChildCount (xParentContext->getAccessibleChildCount());
for (sal_Int32 i=0; i<nChildCount; ++i)
if (xParentContext->getAccessibleChild(i).get()
== static_cast<XAccessible*>(this))
{
nIndexInParent = i;
break;
}
}
}
return nIndexInParent;
}
sal_Int16 SAL_CALL AccessibleSlideSorterObject::getAccessibleRole (void)
throw (uno::RuntimeException)
{
ThrowIfDisposed();
static sal_Int16 nRole = AccessibleRole::LIST_ITEM;
return nRole;
}
::rtl::OUString SAL_CALL AccessibleSlideSorterObject::getAccessibleDescription (void)
throw (uno::RuntimeException)
{
ThrowIfDisposed();
return String(SdResId(STR_PAGE));
}
::rtl::OUString SAL_CALL AccessibleSlideSorterObject::getAccessibleName (void)
throw (uno::RuntimeException)
{
ThrowIfDisposed();
const vos::OGuard aSolarGuard (Application::GetSolarMutex());
SdPage* pPage = GetPage();
if (pPage != NULL)
return pPage->GetName();
else
return String();
}
Reference<XAccessibleRelationSet> SAL_CALL
AccessibleSlideSorterObject::getAccessibleRelationSet (void)
throw (uno::RuntimeException)
{
ThrowIfDisposed();
return Reference<XAccessibleRelationSet>();
}
Reference<XAccessibleStateSet> SAL_CALL
AccessibleSlideSorterObject::getAccessibleStateSet (void)
throw (uno::RuntimeException)
{
ThrowIfDisposed();
const vos::OGuard aSolarGuard (Application::GetSolarMutex());
::utl::AccessibleStateSetHelper* pStateSet = new ::utl::AccessibleStateSetHelper();
if (mxParent.is())
{
// SELECTABLE
pStateSet->AddState(AccessibleStateType::SELECTABLE);
// SELECTED
if (mrSlideSorterController.GetPageSelector().IsPageSelected(mnPageNumber))
pStateSet->AddState(AccessibleStateType::SELECTED);
// FOCUSABLE
pStateSet->AddState(AccessibleStateType::FOCUSABLE);
// FOCUSED
if (mrSlideSorterController.GetFocusManager().GetFocusedPageIndex() == mnPageNumber)
if (mrSlideSorterController.GetFocusManager().IsFocusShowing())
pStateSet->AddState(AccessibleStateType::FOCUSED);
pStateSet->AddState(AccessibleStateType::ENABLED);
pStateSet->AddState(AccessibleStateType::VISIBLE);
pStateSet->AddState(AccessibleStateType::SHOWING);
pStateSet->AddState(AccessibleStateType::ACTIVE);
}
return pStateSet;
}
lang::Locale SAL_CALL AccessibleSlideSorterObject::getLocale (void)
throw (IllegalAccessibleComponentStateException,
RuntimeException)
{
ThrowIfDisposed();
// Delegate request to parent.
if (mxParent.is())
{
Reference<XAccessibleContext> xParentContext (mxParent->getAccessibleContext());
if (xParentContext.is())
return xParentContext->getLocale ();
}
// No locale and no parent. Therefore throw exception to indicate this
// cluelessness.
throw IllegalAccessibleComponentStateException();
}
//===== XAccessibleEventBroadcaster ===========================================
void SAL_CALL AccessibleSlideSorterObject::addEventListener(
const Reference<XAccessibleEventListener>& rxListener)
throw (RuntimeException)
{
if (rxListener.is())
{
const osl::MutexGuard aGuard(maMutex);
if (IsDisposed())
{
uno::Reference<uno::XInterface> x ((lang::XComponent *)this, uno::UNO_QUERY);
rxListener->disposing (lang::EventObject (x));
}
else
{
if (mnClientId == 0)
mnClientId = comphelper::AccessibleEventNotifier::registerClient();
comphelper::AccessibleEventNotifier::addEventListener(mnClientId, rxListener);
}
}
}
void SAL_CALL AccessibleSlideSorterObject::removeEventListener(
const Reference<XAccessibleEventListener>& rxListener)
throw (uno::RuntimeException)
{
ThrowIfDisposed();
if (rxListener.is())
{
const osl::MutexGuard aGuard(maMutex);
sal_Int32 nListenerCount = comphelper::AccessibleEventNotifier::removeEventListener( mnClientId, rxListener );
if ( !nListenerCount )
{
// no listeners anymore
// -> revoke ourself. This may lead to the notifier thread dying (if we were the last client),
// and at least to us not firing any events anymore, in case somebody calls
// NotifyAccessibleEvent, again
comphelper::AccessibleEventNotifier::revokeClient( mnClientId );
mnClientId = 0;
}
}
}
//===== XAccessibleComponent ==================================================
sal_Bool SAL_CALL AccessibleSlideSorterObject::containsPoint(const awt::Point& aPoint)
throw (uno::RuntimeException)
{
ThrowIfDisposed();
const awt::Size aSize (getSize());
return (aPoint.X >= 0)
&& (aPoint.X < aSize.Width)
&& (aPoint.Y >= 0)
&& (aPoint.Y < aSize.Height);
}
Reference<XAccessible> SAL_CALL
AccessibleSlideSorterObject::getAccessibleAtPoint(const awt::Point& )
throw (uno::RuntimeException)
{
return NULL;
}
awt::Rectangle SAL_CALL AccessibleSlideSorterObject::getBounds (void)
throw (RuntimeException)
{
const vos::OGuard aSolarGuard( Application::GetSolarMutex() );
Rectangle aBBox (mrSlideSorterController.GetView().GetPageBoundingBox (
mnPageNumber,
::sd::slidesorter::view::SlideSorterView::CS_SCREEN,
::sd::slidesorter::view::SlideSorterView::BBT_INFO));
if (mxParent.is())
{
Reference<XAccessibleComponent> xParentComponent(mxParent->getAccessibleContext(), UNO_QUERY);
if (xParentComponent.is())
{
awt::Rectangle aParentBBox (xParentComponent->getBounds());
aBBox.Intersection(Rectangle(
aParentBBox.X,
aParentBBox.Y,
aParentBBox.Width,
aParentBBox.Height));
}
}
return awt::Rectangle(
aBBox.Left(),
aBBox.Top(),
aBBox.GetWidth(),
aBBox.GetHeight());
}
awt::Point SAL_CALL AccessibleSlideSorterObject::getLocation ()
throw (RuntimeException)
{
const awt::Rectangle aBBox (getBounds());
return awt::Point(aBBox.X, aBBox.Y);
}
awt::Point SAL_CALL AccessibleSlideSorterObject::getLocationOnScreen (void)
throw (RuntimeException)
{
const vos::OGuard aSolarGuard( Application::GetSolarMutex() );
awt::Point aLocation (getLocation());
if (mxParent.is())
{
Reference<XAccessibleComponent> xParentComponent(mxParent->getAccessibleContext(),UNO_QUERY);
if (xParentComponent.is())
{
const awt::Point aParentLocationOnScreen(xParentComponent->getLocationOnScreen());
aLocation.X += aParentLocationOnScreen.X;
aLocation.Y += aParentLocationOnScreen.Y;
}
}
return aLocation;
}
awt::Size SAL_CALL AccessibleSlideSorterObject::getSize (void)
throw (RuntimeException)
{
const awt::Rectangle aBBox (getBounds());
return awt::Size(aBBox.Width,aBBox.Height);
}
void SAL_CALL AccessibleSlideSorterObject::grabFocus (void)
throw (RuntimeException)
{
// nothing to do
}
sal_Int32 SAL_CALL AccessibleSlideSorterObject::getForeground (void)
throw (::com::sun::star::uno::RuntimeException)
{
svtools::ColorConfig aColorConfig;
UINT32 nColor = aColorConfig.GetColorValue( svtools::FONTCOLOR ).nColor;
return static_cast<sal_Int32>(nColor);
}
sal_Int32 SAL_CALL AccessibleSlideSorterObject::getBackground (void)
throw (::com::sun::star::uno::RuntimeException)
{
UINT32 nColor = Application::GetSettings().GetStyleSettings().GetWindowColor().GetColor();
return static_cast<sal_Int32>(nColor);
}
//===== XServiceInfo ========================================================
::rtl::OUString SAL_CALL
AccessibleSlideSorterObject::getImplementationName (void)
throw (::com::sun::star::uno::RuntimeException)
{
return OUString(RTL_CONSTASCII_USTRINGPARAM("AccessibleSlideSorterObject"));
}
sal_Bool SAL_CALL
AccessibleSlideSorterObject::supportsService (const OUString& sServiceName)
throw (::com::sun::star::uno::RuntimeException)
{
// Iterate over all supported service names and return true if on of them
// matches the given name.
uno::Sequence< ::rtl::OUString> aSupportedServices (
getSupportedServiceNames ());
for (int i=0; i<aSupportedServices.getLength(); i++)
if (sServiceName == aSupportedServices[i])
return sal_True;
return sal_False;
}
uno::Sequence< ::rtl::OUString> SAL_CALL
AccessibleSlideSorterObject::getSupportedServiceNames (void)
throw (::com::sun::star::uno::RuntimeException)
{
static const OUString sServiceNames[2] = {
OUString(RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.accessibility.Accessible")),
OUString(RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.accessibility.AccessibleContext"))
};
return uno::Sequence<OUString> (sServiceNames, 2);
}
void AccessibleSlideSorterObject::ThrowIfDisposed (void)
throw (lang::DisposedException)
{
if (rBHelper.bDisposed || rBHelper.bInDispose)
{
OSL_TRACE ("Calling disposed object. Throwing exception:");
throw lang::DisposedException (
OUString(RTL_CONSTASCII_USTRINGPARAM("object has been already disposed")),
static_cast<uno::XWeak*>(this));
}
}
sal_Bool AccessibleSlideSorterObject::IsDisposed (void)
{
return (rBHelper.bDisposed || rBHelper.bInDispose);
}
SdPage* AccessibleSlideSorterObject::GetPage (void) const
{
::sd::slidesorter::model::SharedPageDescriptor pDescriptor(
mrSlideSorterController.GetModel().GetPageDescriptor(mnPageNumber));
if (pDescriptor.get() != NULL)
return pDescriptor->GetPage();
else
return NULL;
}
} // end of namespace ::accessibility
<|endoftext|>
|
<commit_before>#include <osgUtil/DelaunayTriangulator>
#include <osg/GL>
#include <osg/Vec3>
#include <osg/Array>
#include <osg/Notify>
#include <algorithm>
#include <list>
#include <set>
namespace osgUtil
{
//////////////////////////////////////////////////////////////////////////////////////
// MISC MATH FUNCTIONS
// Compute the circumcircle of a triangle (only x and y coordinates are used),
// return (Cx, Cy, r^2)
inline osg::Vec3 compute_circumcircle(
const osg::Vec3 &a,
const osg::Vec3 &b,
const osg::Vec3 &c)
{
float D =
(a.x() - c.x()) * (b.y() - c.y()) -
(b.x() - c.x()) * (a.y() - c.y());
float cx =
(((a.x() - c.x()) * (a.x() + c.x()) +
(a.y() - c.y()) * (a.y() + c.y())) / 2 * (b.y() - c.y()) -
((b.x() - c.x()) * (b.x() + c.x()) +
(b.y() - c.y()) * (b.y() + c.y())) / 2 * (a.y() - c.y())) / D;
float cy =
(((b.x() - c.x()) * (b.x() + c.x()) +
(b.y() - c.y()) * (b.y() + c.y())) / 2 * (a.x() - c.x()) -
((a.x() - c.x()) * (a.x() + c.x()) +
(a.y() - c.y()) * (a.y() + c.y())) / 2 * (b.x() - c.x())) / D;
float r2 = (c.x() - cx) * (c.x() - cx) + (c.y() - cy) * (c.y() - cy);
return osg::Vec3(cx, cy, r2);
}
// Test whether a point (only the x and y coordinates are used) lies inside
// a circle; the circle is passed as a vector: (Cx, Cy, r^2).
inline bool point_in_circle(const osg::Vec3 &point, const osg::Vec3 &circle)
{
float r2 =
(point.x() - circle.x()) * (point.x() - circle.x()) +
(point.y() - circle.y()) * (point.y() - circle.y());
return r2 <= circle.z();
}
//
//////////////////////////////////////////////////////////////////////////////////////
// data type for vertex indices
typedef GLuint Vertex_index;
// CLASS: Edge
// This class describes an edge of a triangle (it stores vertex indices to the two
// endpoints).
class Edge {
public:
// Comparison object (for sorting)
struct Less {
inline bool operator()(const Edge &e1, const Edge &e2) const
{
if (e1.ibs() < e2.ibs()) return true;
if (e1.ibs() > e2.ibs()) return false;
if (e1.ies() < e2.ies()) return true;
return false;
}
};
Edge() {}
Edge(Vertex_index ib, Vertex_index ie) : ib_(ib), ie_(ie), ibs_(osg::minimum(ib, ie)), ies_(osg::maximum(ib, ie)), duplicate_(false) {}
// first endpoint
inline Vertex_index ib() const { return ib_; }
// second endpoint
inline Vertex_index ie() const { return ie_; }
// first sorted endpoint
inline Vertex_index ibs() const { return ibs_; }
// second sorted endpoint
inline Vertex_index ies() const { return ies_; }
// get the "duplicate" flag
inline bool get_duplicate() const { return duplicate_; }
// set the "duplicate" flag
inline void set_duplicate(bool v) { duplicate_ = v; }
private:
Vertex_index ib_, ie_;
Vertex_index ibs_, ies_;
bool duplicate_;
};
// CLASS: Triangle
class Triangle {
public:
Triangle(Vertex_index a, Vertex_index b, Vertex_index c, osg::Vec3Array *points)
: a_(a),
b_(b),
c_(c),
cc_(compute_circumcircle((*points)[a_], (*points)[b_], (*points)[c_]))
{
edge_[0] = Edge(a_, b_);
edge_[1] = Edge(b_, c_);
edge_[2] = Edge(c_, a_);
}
inline Vertex_index a() const { return a_; }
inline Vertex_index b() const { return b_; }
inline Vertex_index c() const { return c_; }
inline const Edge &get_edge(int idx) const { return edge_[idx]; }
inline const osg::Vec3 &get_circumcircle() const { return cc_; }
inline osg::Vec3 compute_normal(osg::Vec3Array *points) const
{
osg::Vec3 N = ((*points)[b_] - (*points)[a_]) ^ ((*points)[c_] - (*points)[a_]);
return N / N.length();
}
private:
Vertex_index a_;
Vertex_index b_;
Vertex_index c_;
osg::Vec3 cc_;
Edge edge_[3];
};
// comparison function for sorting sample points by the X coordinate
bool Sample_point_compare(const osg::Vec3 &p1, const osg::Vec3 &p2)
{
return p1.x() < p2.x();
}
// container types
typedef std::set<Edge, Edge::Less> Edge_set;
typedef std::list<Triangle> Triangle_list;
DelaunayTriangulator::DelaunayTriangulator():
osg::Referenced()
{
}
DelaunayTriangulator::DelaunayTriangulator(osg::Vec3Array *points, osg::Vec3Array *normals):
osg::Referenced(),
points_(points),
normals_(normals)
{
}
DelaunayTriangulator::DelaunayTriangulator(const DelaunayTriangulator ©, const osg::CopyOp ©op):
osg::Referenced(copy),
points_(static_cast<osg::Vec3Array *>(copyop(copy.points_.get()))),
normals_(static_cast<osg::Vec3Array *>(copyop(copy.normals_.get()))),
prim_tris_(static_cast<osg::DrawElementsUInt *>(copyop(copy.prim_tris_.get())))
{
}
DelaunayTriangulator::~DelaunayTriangulator()
{
}
bool DelaunayTriangulator::triangulate()
{
// check validity of input array
if (!points_.valid()) {
osg::notify(osg::WARN) << "Warning: DelaunayTriangulator::triangulate(): invalid sample point array" << std::endl;
return false;
}
osg::Vec3Array *points = points_.get();
if (points->size() < 1) {
osg::notify(osg::WARN) << "Warning: DelaunayTriangulator::triangulate(): too few sample points" << std::endl;
return false;
}
// initialize storage structures
Triangle_list triangles;
Triangle_list discarded_tris;
// pre-sort sample points
osg::notify(osg::INFO) << "DelaunayTriangulator: pre-sorting sample points\n";
std::sort(points->begin(), points->end(), Sample_point_compare);
// set the last valid index for the point list
GLuint last_valid_index = points->size() - 1;
// find the minimum and maximum x values in the point list
float minx = (*points)[0].x();
float maxx = (*points)[last_valid_index].x();
// find the minimum and maximum x values in the point list
float miny = (*points)[0].y();
float maxy = miny;
osg::notify(osg::INFO) << "DelaunayTriangulator: finding minimum and maximum Y values\n";
osg::Vec3Array::const_iterator mmi;
for (mmi=points->begin(); mmi!=points->end(); ++mmi) {
if (mmi->y() < miny) miny = mmi->y();
if (mmi->y() > maxy) maxy = mmi->y();
}
// add supertriangle vertices to the point list
points->push_back(osg::Vec3(minx - (maxx - minx), miny, 0));
points->push_back(osg::Vec3(maxx, miny, 0));
points->push_back(osg::Vec3(maxx, maxy + (maxy - miny), 0));
// add supertriangle to triangle list
triangles.push_back(Triangle(last_valid_index+1, last_valid_index+2, last_valid_index+3, points));
// begin triangulation
GLuint pidx = 0;
osg::Vec3Array::const_iterator i;
osg::notify(osg::INFO) << "DelaunayTriangulator: triangulating vertex grid (" << (points->size()-3) <<" points)\n";
for (i=points->begin(); i!=points->end(); ++i, ++pidx) {
// don't process supertriangle vertices
if (pidx > last_valid_index) break;
Edge_set edges;
// iterate through triangles
Triangle_list::iterator j, next_j;
for (j=triangles.begin(); j!=triangles.end(); j = next_j) {
next_j = j;
++next_j;
// compute the circumcircle
osg::Vec3 cc = j->get_circumcircle();
// OPTIMIZATION: since points are pre-sorted by the X component,
// check whether we can discard this triangle for future operations
float xdist = i->x() - cc.x();
if ((xdist * xdist) > cc.z() && i->x() > cc.x()) {
discarded_tris.push_back(*j);
triangles.erase(j);
} else {
// if the point lies in the triangle's circumcircle then add
// its edges to the edge list and remove the triangle
if (point_in_circle(*i, cc))
{
for (int ei=0; ei<3; ++ei)
{
std::pair<Edge_set::iterator, bool> result = edges.insert(j->get_edge(ei));
if (!result.second)
{
// cast away constness of a set element, which is
// safe in this case since the set_duplicate is
// not used as part of the Less operator.
Edge& edge = const_cast<Edge&>(*(result.first));
edge.set_duplicate(true);
}
}
triangles.erase(j);
}
}
}
// remove duplicate edges and add new triangles
Edge_set::iterator ci;
for (ci=edges.begin(); ci!=edges.end(); ++ci) {
if (!ci->get_duplicate()) {
triangles.push_back(Triangle(pidx, ci->ib(), ci->ie(), points));
}
}
}
osg::notify(osg::INFO) << "DelaunayTriangulator: finalizing and cleaning up structures\n";
// remove supertriangle vertices
points->pop_back();
points->pop_back();
points->pop_back();
// rejoin the two triangle lists
triangles.insert(triangles.begin(), discarded_tris.begin(), discarded_tris.end());
// initialize index storage vector
std::vector<GLuint> pt_indices;
pt_indices.reserve(triangles.size() * 3);
// build osg primitive
osg::notify(osg::INFO) << "DelaunayTriangulator: building primitive(s)\n";
Triangle_list::const_iterator ti;
for (ti=triangles.begin(); ti!=triangles.end(); ++ti) {
// don't add this triangle to the primitive if it shares any vertex with
// the supertriangle
if (ti->a() <= last_valid_index && ti->b() <= last_valid_index && ti->c() <= last_valid_index) {
if (normals_.valid()) {
(normals_.get())->push_back(ti->compute_normal(points));
}
pt_indices.push_back(ti->a());
pt_indices.push_back(ti->b());
pt_indices.push_back(ti->c());
}
}
prim_tris_ = new osg::DrawElementsUInt(GL_TRIANGLES, pt_indices.size(), &(pt_indices.front()));
osg::notify(osg::INFO) << "DelaunayTriangulator: process done, " << (pt_indices.size() / 3) << " triangles created\n";
return true;
}
}
<commit_msg>From David Spilling, fixed the incircle test so it handles colinear points.<commit_after>#include <osgUtil/DelaunayTriangulator>
#include <osg/GL>
#include <osg/Vec3>
#include <osg/Array>
#include <osg/Notify>
#include <algorithm>
#include <list>
#include <set>
namespace osgUtil
{
//////////////////////////////////////////////////////////////////////////////////////
// MISC MATH FUNCTIONS
// Compute the circumcircle of a triangle (only x and y coordinates are used),
// return (Cx, Cy, r^2)
inline osg::Vec3 compute_circumcircle(
const osg::Vec3 &a,
const osg::Vec3 &b,
const osg::Vec3 &c)
{
float D =
(a.x() - c.x()) * (b.y() - c.y()) -
(b.x() - c.x()) * (a.y() - c.y());
float cx, cy, r2;
if(D==0.0)
{
// (Nearly) degenerate condition - either two of the points are equal (which we discount)
// or the three points are colinear. In this case we just determine the average of
// the three points as the centre for correctness, but squirt out a zero radius.
// This method will produce a triangulation with zero area, so we have to check later
cx = (a.x()+b.x()+c.x())/3.0;
cy = (a.y()+b.y()+c.y())/3.0;
r2 = 0.0;
}
else
{
cx =
(((a.x() - c.x()) * (a.x() + c.x()) +
(a.y() - c.y()) * (a.y() + c.y())) / 2 * (b.y() - c.y()) -
((b.x() - c.x()) * (b.x() + c.x()) +
(b.y() - c.y()) * (b.y() + c.y())) / 2 * (a.y() - c.y())) / D;
cy =
(((b.x() - c.x()) * (b.x() + c.x()) +
(b.y() - c.y()) * (b.y() + c.y())) / 2 * (a.x() - c.x()) -
((a.x() - c.x()) * (a.x() + c.x()) +
(a.y() - c.y()) * (a.y() + c.y())) / 2 * (b.x() - c.x())) / D;
r2 = (c.x() - cx) * (c.x() - cx) + (c.y() - cy) * (c.y() - cy);
}
return osg::Vec3(cx, cy, r2);
}
// Test whether a point (only the x and y coordinates are used) lies inside
// a circle; the circle is passed as a vector: (Cx, Cy, r^2).
inline bool point_in_circle(const osg::Vec3 &point, const osg::Vec3 &circle)
{
float r2 =
(point.x() - circle.x()) * (point.x() - circle.x()) +
(point.y() - circle.y()) * (point.y() - circle.y());
return r2 <= circle.z();
}
//
//////////////////////////////////////////////////////////////////////////////////////
// data type for vertex indices
typedef GLuint Vertex_index;
// CLASS: Edge
// This class describes an edge of a triangle (it stores vertex indices to the two
// endpoints).
class Edge {
public:
// Comparison object (for sorting)
struct Less {
inline bool operator()(const Edge &e1, const Edge &e2) const
{
if (e1.ibs() < e2.ibs()) return true;
if (e1.ibs() > e2.ibs()) return false;
if (e1.ies() < e2.ies()) return true;
return false;
}
};
Edge() {}
Edge(Vertex_index ib, Vertex_index ie) : ib_(ib), ie_(ie), ibs_(osg::minimum(ib, ie)), ies_(osg::maximum(ib, ie)), duplicate_(false) {}
// first endpoint
inline Vertex_index ib() const { return ib_; }
// second endpoint
inline Vertex_index ie() const { return ie_; }
// first sorted endpoint
inline Vertex_index ibs() const { return ibs_; }
// second sorted endpoint
inline Vertex_index ies() const { return ies_; }
// get the "duplicate" flag
inline bool get_duplicate() const { return duplicate_; }
// set the "duplicate" flag
inline void set_duplicate(bool v) { duplicate_ = v; }
private:
Vertex_index ib_, ie_;
Vertex_index ibs_, ies_;
bool duplicate_;
};
// CLASS: Triangle
class Triangle {
public:
Triangle(Vertex_index a, Vertex_index b, Vertex_index c, osg::Vec3Array *points)
: a_(a),
b_(b),
c_(c),
cc_(compute_circumcircle((*points)[a_], (*points)[b_], (*points)[c_]))
{
edge_[0] = Edge(a_, b_);
edge_[1] = Edge(b_, c_);
edge_[2] = Edge(c_, a_);
}
inline Vertex_index a() const { return a_; }
inline Vertex_index b() const { return b_; }
inline Vertex_index c() const { return c_; }
inline const Edge &get_edge(int idx) const { return edge_[idx]; }
inline const osg::Vec3 &get_circumcircle() const { return cc_; }
inline osg::Vec3 compute_normal(osg::Vec3Array *points) const
{
osg::Vec3 N = ((*points)[b_] - (*points)[a_]) ^ ((*points)[c_] - (*points)[a_]);
return N / N.length();
}
private:
Vertex_index a_;
Vertex_index b_;
Vertex_index c_;
osg::Vec3 cc_;
Edge edge_[3];
};
// comparison function for sorting sample points by the X coordinate
bool Sample_point_compare(const osg::Vec3 &p1, const osg::Vec3 &p2)
{
return p1.x() < p2.x();
}
// container types
typedef std::set<Edge, Edge::Less> Edge_set;
typedef std::list<Triangle> Triangle_list;
DelaunayTriangulator::DelaunayTriangulator():
osg::Referenced()
{
}
DelaunayTriangulator::DelaunayTriangulator(osg::Vec3Array *points, osg::Vec3Array *normals):
osg::Referenced(),
points_(points),
normals_(normals)
{
}
DelaunayTriangulator::DelaunayTriangulator(const DelaunayTriangulator ©, const osg::CopyOp ©op):
osg::Referenced(copy),
points_(static_cast<osg::Vec3Array *>(copyop(copy.points_.get()))),
normals_(static_cast<osg::Vec3Array *>(copyop(copy.normals_.get()))),
prim_tris_(static_cast<osg::DrawElementsUInt *>(copyop(copy.prim_tris_.get())))
{
}
DelaunayTriangulator::~DelaunayTriangulator()
{
}
bool DelaunayTriangulator::triangulate()
{
// check validity of input array
if (!points_.valid()) {
osg::notify(osg::WARN) << "Warning: DelaunayTriangulator::triangulate(): invalid sample point array" << std::endl;
return false;
}
osg::Vec3Array *points = points_.get();
if (points->size() < 1) {
osg::notify(osg::WARN) << "Warning: DelaunayTriangulator::triangulate(): too few sample points" << std::endl;
return false;
}
// initialize storage structures
Triangle_list triangles;
Triangle_list discarded_tris;
// pre-sort sample points
osg::notify(osg::INFO) << "DelaunayTriangulator: pre-sorting sample points\n";
std::sort(points->begin(), points->end(), Sample_point_compare);
// set the last valid index for the point list
GLuint last_valid_index = points->size() - 1;
// find the minimum and maximum x values in the point list
float minx = (*points)[0].x();
float maxx = (*points)[last_valid_index].x();
// find the minimum and maximum x values in the point list
float miny = (*points)[0].y();
float maxy = miny;
osg::notify(osg::INFO) << "DelaunayTriangulator: finding minimum and maximum Y values\n";
osg::Vec3Array::const_iterator mmi;
for (mmi=points->begin(); mmi!=points->end(); ++mmi) {
if (mmi->y() < miny) miny = mmi->y();
if (mmi->y() > maxy) maxy = mmi->y();
}
// add supertriangle vertices to the point list
points->push_back(osg::Vec3(minx - (maxx - minx), miny, 0));
points->push_back(osg::Vec3(maxx, miny, 0));
points->push_back(osg::Vec3(maxx, maxy + (maxy - miny), 0));
// add supertriangle to triangle list
triangles.push_back(Triangle(last_valid_index+1, last_valid_index+2, last_valid_index+3, points));
// begin triangulation
GLuint pidx = 0;
osg::Vec3Array::const_iterator i;
osg::notify(osg::INFO) << "DelaunayTriangulator: triangulating vertex grid (" << (points->size()-3) <<" points)\n";
for (i=points->begin(); i!=points->end(); ++i, ++pidx) {
// don't process supertriangle vertices
if (pidx > last_valid_index) break;
Edge_set edges;
// iterate through triangles
Triangle_list::iterator j, next_j;
for (j=triangles.begin(); j!=triangles.end(); j = next_j) {
next_j = j;
++next_j;
// compute the circumcircle
osg::Vec3 cc = j->get_circumcircle();
// OPTIMIZATION: since points are pre-sorted by the X component,
// check whether we can discard this triangle for future operations
float xdist = i->x() - cc.x();
if ((xdist * xdist) > cc.z() && i->x() > cc.x()) {
discarded_tris.push_back(*j);
triangles.erase(j);
} else {
// if the point lies in the triangle's circumcircle then add
// its edges to the edge list and remove the triangle
if (point_in_circle(*i, cc))
{
for (int ei=0; ei<3; ++ei)
{
std::pair<Edge_set::iterator, bool> result = edges.insert(j->get_edge(ei));
if (!result.second)
{
// cast away constness of a set element, which is
// safe in this case since the set_duplicate is
// not used as part of the Less operator.
Edge& edge = const_cast<Edge&>(*(result.first));
edge.set_duplicate(true);
}
}
triangles.erase(j);
}
}
}
// remove duplicate edges and add new triangles
Edge_set::iterator ci;
for (ci=edges.begin(); ci!=edges.end(); ++ci) {
if (!ci->get_duplicate()) {
triangles.push_back(Triangle(pidx, ci->ib(), ci->ie(), points));
}
}
}
osg::notify(osg::INFO) << "DelaunayTriangulator: finalizing and cleaning up structures\n";
// remove supertriangle vertices
points->pop_back();
points->pop_back();
points->pop_back();
// rejoin the two triangle lists
triangles.insert(triangles.begin(), discarded_tris.begin(), discarded_tris.end());
// initialize index storage vector
std::vector<GLuint> pt_indices;
pt_indices.reserve(triangles.size() * 3);
// build osg primitive
osg::notify(osg::INFO) << "DelaunayTriangulator: building primitive(s)\n";
Triangle_list::const_iterator ti;
for (ti=triangles.begin(); ti!=triangles.end(); ++ti) {
// don't add this triangle to the primitive if it shares any vertex with
// the supertriangle
// Also don't add degenerate (zero radius) triangles
if (ti->a() <= last_valid_index && ti->b() <= last_valid_index && ti->c() <= last_valid_index && ti->get_circumcircle().z()>0.0) {
if (normals_.valid()) {
(normals_.get())->push_back(ti->compute_normal(points));
}
pt_indices.push_back(ti->a());
pt_indices.push_back(ti->b());
pt_indices.push_back(ti->c());
}
}
prim_tris_ = new osg::DrawElementsUInt(GL_TRIANGLES, pt_indices.size(), &(pt_indices.front()));
osg::notify(osg::INFO) << "DelaunayTriangulator: process done, " << (pt_indices.size() / 3) << " triangles created\n";
return true;
}
}
<|endoftext|>
|
<commit_before>
#include "TStopwatch.h"
#include "TUnuran.h"
#include "TH1.h"
#include "TRandom.h"
#include "TSystem.h"
//#include "TApplication.h"
#include "TVirtualFitter.h"
#include "Math/ProbFunc.h"
#include <iostream>
using std::cout;
using std::endl;
void unuranSimple() {
// simple test of unuran
TUnuran unr;
if (! unr.Init( "normal()", "method=arou") ) {
cout << "Error initializing unuran" << endl;
return;
}
int n = 1000000;
TStopwatch w;
w.Start();
for (int i = 0; i < n; ++i)
unr.Sample();
w.Stop();
cout << "Time using Unuran =\t\t " << w.CpuTime() << endl;
w.Start();
for (int i = 0; i < n; ++i)
gRandom->Gaus(0,1);
w.Stop();
cout << "Time using TRandom::Gaus =\t " << w.CpuTime() << endl;
// test the quality by looking at the cdf
TH1D * h1 = new TH1D("h1","cdf on the data ",100,0,1);
for (int i = 0; i < n; ++i) {
double x = unr.Sample();
// x = gRandom->Gaus(0,1);
h1->Fill( ROOT::Math::normal_quant( x , 1.0) );
}
// gSystem->Load("libMinuit2");
// TVirtualFitter::SetDefaultFitter("Minuit2");
std::cout << "Result of fitting a cdf to a constant function : " << std::endl;
h1->Fit("pol0","Q");
TF1 * f = (TF1*)gROOT->GetFunction("pol0");
std::cout << "Fit chi2 = " << f->GetChisquare() << " ndf = " << f->GetNDF() << std::endl;
std::cout << "Fit Prob = " << f->GetProb() << std::endl;
h1->Draw();
}
#ifndef __CINT__
int main(int /* argc */, char ** /* argv */)
{
// TApplication theApp("App", &argc, argv);
unuranSimple();
// theApp.Run();
return 0;
}
#endif
<commit_msg>fix problem in finding the TFitter on Windows by setting it explicitly<commit_after>
#include "TStopwatch.h"
#include "TUnuran.h"
#include "TH1.h"
#include "TRandom.h"
#include "TSystem.h"
//#include "TApplication.h"
//#include "TRint.h"
#include "TVirtualFitter.h"
#include "TFitter.h"
#include "Math/ProbFunc.h"
#include <iostream>
using std::cout;
using std::endl;
void unuranSimple() {
// simple test of unuran
TUnuran unr;
if (! unr.Init( "normal()", "method=arou") ) {
cout << "Error initializing unuran" << endl;
return;
}
int n = 1000000;
TStopwatch w;
w.Start();
for (int i = 0; i < n; ++i)
unr.Sample();
w.Stop();
cout << "Time using Unuran =\t\t " << w.CpuTime() << endl;
w.Start();
for (int i = 0; i < n; ++i)
gRandom->Gaus(0,1);
w.Stop();
cout << "Time using TRandom::Gaus =\t " << w.CpuTime() << endl;
// test the quality by looking at the cdf
TH1D * h1 = new TH1D("h1","cdf on the data ",100,0,1);
for (int i = 0; i < n; ++i) {
double x = unr.Sample();
// x = gRandom->Gaus(0,1);
h1->Fill( ROOT::Math::normal_quant( x , 1.0) );
}
// gSystem->Load("libMinuit2");
// TVirtualFitter::SetDefaultFitter("Minuit2");
std::cout << "Result of fitting a cdf to a constant function : " << std::endl;
// need TRint();
TFitter * fitter = new TFitter();
TVirtualFitter::SetFitter(fitter);
h1->Fit("pol0","Q");
TF1 * f = (TF1*)gROOT->GetFunction("pol0");
std::cout << "Fit chi2 = " << f->GetChisquare() << " ndf = " << f->GetNDF() << std::endl;
std::cout << "Fit Prob = " << f->GetProb() << std::endl;
h1->Draw();
//delete fitter;
}
#ifndef __CINT__
int main()
{
// TApplication theApp("App", &argc, argv);
//TRint theApp("TRint",&argc, argv);
//theApp.Run();
unuranSimple();
return 0;
}
#endif
<|endoftext|>
|
<commit_before>#ifdef _WIN32
#include <pd_backend.h>
#include <assert.h>
#include <stdio.h>
#include <Dbgeng.h>
#include <string>
struct DbgEngPlugin
{
PDDebugState state = PDDebugState_noTarget;
bool hasValidTarget = false;
std::string targetName;
IDebugClient* debugClient = nullptr;
IDebugControl* debugControl = nullptr;
};
void onRun(DbgEngPlugin* plugin)
{
}
void onStop(DbgEngPlugin* plugin)
{
}
static void onBreak(DbgEngPlugin* plugin)
{
}
static void onStep(DbgEngPlugin* plugin)
{
}
static void onStepOver(DbgEngPlugin* plugin)
{
}
static void onStepOut(DbgEngPlugin* plugin)
{
}
static void doAction(DbgEngPlugin* plugin, PDAction action)
{
switch (action)
{
case PDAction_stop: onStop(plugin); break;
case PDAction_break: onBreak(plugin); break;
case PDAction_run: onRun(plugin); break;
case PDAction_step: onStep(plugin); break;
case PDAction_stepOut: onStepOut(plugin); break;
case PDAction_stepOver: onStepOver(plugin); break;
}
}
static void setExceptionLocation(DbgEngPlugin* plugin, PDWriter* writer)
{
}
static void setCallstack(DbgEngPlugin* plugin, PDWriter* writer)
{
}
static void setExecutable(DbgEngPlugin* plugin, PDReader* reader)
{
const char* filename = 0;
PDRead_findString(reader, &filename, "filename", 0);
if (!filename)
{
printf("Unable to find filename which is required when starting a LLDB debug session\n");
return;
}
printf("found filename \"%s\"\n", filename);
plugin->targetName = filename;
HRESULT hr = plugin->debugClient->CreateProcess(0, PSTR(filename), DEBUG_PROCESS);
assert(SUCCEEDED(hr));
printf("Valid target %s\n", filename);
}
static void setLocals(DbgEngPlugin* plugin, PDWriter* writer)
{
}
static void setBreakpoint(DbgEngPlugin* plugin, PDReader* reader, PDWriter* writer)
{
}
static void eventAction(DbgEngPlugin* plugin, PDReader* reader)
{
uint32_t action = 0;
printf("DbgEngPlugin; %d\n", (PDRead_findU32(reader, &action, "action", 0) & 0xff) >> 8);
printf("DbgEngPlugin: got action (from event) %d\n", action);
doAction(plugin, (PDAction)action);
}
static void processEvents(DbgEngPlugin* plugin, PDReader* reader, PDWriter* writer)
{
PDEventType event;
while ((event = (PDEventType)PDRead_getEvent(reader)))
{
switch (event)
{
case PDEventType_getExceptionLocation: setExceptionLocation(plugin, writer); break;
case PDEventType_getCallstack: setCallstack(plugin, writer); break;
case PDEventType_setExecutable: setExecutable(plugin, reader); break;
case PDEventType_getLocals: setLocals(plugin, writer); break;
case PDEventType_setBreakpoint: setBreakpoint(plugin, reader, writer); break;
case PDEventType_action: eventAction(plugin, reader); break;
}
}
}
void* createInstance(ServiceFunc* serviceFunc)
{
DbgEngPlugin* plugin = new DbgEngPlugin;
HRESULT hr = DebugCreate(__uuidof(IDebugClient), (void**)&plugin->debugClient);
assert(SUCCEEDED(hr));
hr = plugin->debugClient->QueryInterface(__uuidof(IDebugControl), (void**)&plugin->debugControl);
assert(SUCCEEDED(hr));
return plugin;
}
void destroyInstance(void* userData)
{
DbgEngPlugin* plugin = reinterpret_cast<DbgEngPlugin*>(userData);
if (plugin->debugControl)
{
plugin->debugControl->Release();
plugin->debugControl = nullptr;
}
if (plugin->debugClient)
{
plugin->debugClient->Release();
plugin->debugClient = nullptr;
}
delete plugin;
}
static PDDebugState update(void* userData, PDAction action, PDReader* reader, PDWriter* writer)
{
DbgEngPlugin* plugin = reinterpret_cast<DbgEngPlugin*>(userData);
processEvents(plugin, reader, writer);
doAction(plugin, action);
/*
if (plugin->state == PDDebugState_running)
updateDbgEngEvent(plugin, writer);
*/
return plugin->state;
}
static PDBackendPlugin plugin =
{
"Microsoft Debugger Engine",
createInstance,
destroyInstance,
update,
};
extern "C" PD_EXPORT void InitPlugin(RegisterPlugin* registerPlugin, void* privateData)
{
registerPlugin(PD_BACKEND_API_VERSION, &plugin, privateData);
}
#endif
<commit_msg>Added stubs for DebugBaseEventCallbacks interfaces<commit_after>#ifdef _WIN32
#include <pd_backend.h>
#include <assert.h>
#include <stdio.h>
#include <Dbgeng.h>
#include <string>
struct DbgEngPlugin : public DebugBaseEventCallbacks
{
PDDebugState state = PDDebugState_noTarget;
bool hasValidTarget = false;
std::string targetName;
IDebugClient* debugClient = nullptr;
IDebugControl* debugControl = nullptr;
// IUnknown
STDMETHOD_(ULONG, AddRef)(THIS);
STDMETHOD_(ULONG, Release)(THIS);
// IDebugEventCallbacks
STDMETHOD(GetInterestMask)(THIS_
OUT PULONG Mask);
STDMETHOD(Breakpoint)(THIS_
IN PDEBUG_BREAKPOINT Bp);
STDMETHOD(Exception)(THIS_
IN PEXCEPTION_RECORD64 Exception, IN ULONG FirstChance);
STDMETHOD(CreateProcess)(THIS_
IN ULONG64 ImageFileHandle,
IN ULONG64 Handle,
IN ULONG64 BaseOffset,
IN ULONG ModuleSize,
IN PCSTR ModuleName,
IN PCSTR ImageName,
IN ULONG CheckSum,
IN ULONG TimeDateStamp,
IN ULONG64 InitialThreadHandle,
IN ULONG64 ThreadDataOffset,
IN ULONG64 StartOffset);
STDMETHOD(LoadModule)(THIS_
IN ULONG64 ImageFileHandle,
IN ULONG64 BaseOffset,
IN ULONG ModuleSize,
IN PCSTR ModuleName,
IN PCSTR ImageName,
IN ULONG CheckSum,
IN ULONG TimeDateStamp);
STDMETHOD(SessionStatus)(THIS_
IN ULONG Status);
};
STDMETHODIMP_(ULONG) DbgEngPlugin::AddRef(THIS)
{
return 1;
}
STDMETHODIMP_(ULONG) DbgEngPlugin::Release(THIS)
{
return 0;
}
STDMETHODIMP DbgEngPlugin::GetInterestMask(THIS_
OUT PULONG Mask)
{
*Mask =
DEBUG_EVENT_BREAKPOINT |
DEBUG_EVENT_EXCEPTION |
DEBUG_EVENT_CREATE_PROCESS |
DEBUG_EVENT_LOAD_MODULE |
DEBUG_EVENT_SESSION_STATUS;
return S_OK;
}
STDMETHODIMP DbgEngPlugin::Breakpoint(THIS_
IN PDEBUG_BREAKPOINT Bp)
{
return S_OK;
}
STDMETHODIMP DbgEngPlugin::Exception(THIS_
IN PEXCEPTION_RECORD64 Exception,
IN ULONG FirstChance)
{
return S_OK;
}
STDMETHODIMP DbgEngPlugin::CreateProcess(THIS_
IN ULONG64 ImageFileHandle,
IN ULONG64 Handle,
IN ULONG64 BaseOffset,
IN ULONG ModuleSize,
IN PCSTR ModuleName,
IN PCSTR ImageName,
IN ULONG CheckSum,
IN ULONG TimeDateStamp,
IN ULONG64 InitialThreadHandle,
IN ULONG64 ThreadDataOffset,
IN ULONG64 StartOffset)
{
return S_OK;
}
STDMETHODIMP DbgEngPlugin::LoadModule(THIS_
IN ULONG64 ImageFileHandle,
IN ULONG64 BaseOffset,
IN ULONG ModuleSize,
IN PCSTR ModuleName,
IN PCSTR ImageName,
IN ULONG CheckSum,
IN ULONG TimeDateStamp)
{
return S_OK;
}
STDMETHODIMP DbgEngPlugin::SessionStatus(THIS_
IN ULONG Status)
{
return S_OK;
}
static void updateDbgEngEvent(DbgEngPlugin* plugin, PDWriter* writer)
{
HRESULT hr = plugin->debugControl->WaitForEvent(DEBUG_WAIT_DEFAULT, 100);
if (hr == S_FALSE)
{
// WaitForEvent timeout occurred
return;
}
// TODO: check and handle execution status
}
void onRun(DbgEngPlugin* plugin)
{
printf("DbgEngPlugin: onRun\n");
if (plugin->state == PDDebugState_noTarget)
{
assert(!plugin->targetName.empty());
HRESULT hr = plugin->debugClient->CreateProcess(0, PSTR(plugin->targetName.c_str()), DEBUG_ONLY_THIS_PROCESS);
assert(SUCCEEDED(hr));
if (SUCCEEDED(hr))
{
printf("Error: could not create process '%s'\n", plugin->targetName.c_str());
}
else
{
printf("Valid target %s\n", plugin->targetName.c_str());
}
plugin->state = PDDebugState_running;
}
}
void onStop(DbgEngPlugin* plugin)
{
printf("DbgEngPlugin: onStop\n");
}
static void onBreak(DbgEngPlugin* plugin)
{
printf("DbgEngPlugin: onBreak\n");
}
static void onStep(DbgEngPlugin* plugin)
{
printf("DbgEngPlugin: onStep\n");
}
static void onStepOver(DbgEngPlugin* plugin)
{
printf("DbgEngPlugin: onStepOver\n");
}
static void onStepOut(DbgEngPlugin* plugin)
{
printf("DbgEngPlugin: onStepOut\n");
}
static void doAction(DbgEngPlugin* plugin, PDAction action)
{
printf("DbgEngPlugin: doAction\n");
switch (action)
{
case PDAction_stop: onStop(plugin); break;
case PDAction_break: onBreak(plugin); break;
case PDAction_run: onRun(plugin); break;
case PDAction_step: onStep(plugin); break;
case PDAction_stepOut: onStepOut(plugin); break;
case PDAction_stepOver: onStepOver(plugin); break;
}
}
static void setExceptionLocation(DbgEngPlugin* plugin, PDWriter* writer)
{
printf("DbgEngPlugin: setExceptionLocation\n");
}
static void setCallstack(DbgEngPlugin* plugin, PDWriter* writer)
{
printf("DbgEngPlugin: setCallstack\n");
}
static void setExecutable(DbgEngPlugin* plugin, PDReader* reader)
{
printf("DbgEngPlugin: setExecutable\n");
const char* filename = 0;
PDRead_findString(reader, &filename, "filename", 0);
if (!filename)
{
printf("Unable to find filename which is required when starting a LLDB debug session\n");
return;
}
printf("found filename \"%s\"\n", filename);
plugin->targetName = filename;
}
static void setLocals(DbgEngPlugin* plugin, PDWriter* writer)
{
printf("DbgEngPlugin: setLocals\n");
}
static void setBreakpoint(DbgEngPlugin* plugin, PDReader* reader, PDWriter* writer)
{
printf("DbgEngPlugin: setBreakpoint\n");
}
static void eventAction(DbgEngPlugin* plugin, PDReader* reader)
{
printf("DbgEngPlugin: eventAction\n");
uint32_t action = 0;
printf("DbgEngPlugin; %d\n", (PDRead_findU32(reader, &action, "action", 0) & 0xff) >> 8);
printf("DbgEngPlugin: got action (from event) %d\n", action);
doAction(plugin, (PDAction)action);
}
static const char* eventTypes[] =
{
"PDEventType_none",
"PDEventType_getLocals",
"PDEventType_setLocals",
"PDEventType_getCallstack",
"PDEventType_setCallstack",
"PDEventType_getWatch",
"PDEventType_setWatch",
"PDEventType_getRegisters",
"PDEventType_setRegisters",
"PDEventType_getMemory",
"PDEventType_setMemory",
"PDEventType_getTty",
"PDEventType_setTty",
"PDEventType_getExceptionLocation",
"PDEventType_setExceptionLocation",
"PDEventType_getDisassembly",
"PDEventType_setDisassembly",
"PDEventType_setBreakpoint",
"PDEventType_getBreakpoint",
"PDEventType_setExecutable",
"PDEventType_attachToProcess",
"PDEventType_attachToRemoteSession",
"PDEventType_action",
};
static void processEvents(DbgEngPlugin* plugin, PDReader* reader, PDWriter* writer)
{
printf("DbgEngPlugin: processEvents\n");
PDEventType event;
while ((event = (PDEventType)PDRead_getEvent(reader)))
{
printf("DbgEngPlugin: %d Got event %s\n", (int)event, eventTypes[event]);
switch (event)
{
case PDEventType_getExceptionLocation: setExceptionLocation(plugin, writer); break;
case PDEventType_getCallstack: setCallstack(plugin, writer); break;
case PDEventType_setExecutable: setExecutable(plugin, reader); break;
case PDEventType_getLocals: setLocals(plugin, writer); break;
case PDEventType_setBreakpoint: setBreakpoint(plugin, reader, writer); break;
case PDEventType_action: eventAction(plugin, reader); break;
}
}
}
void* createInstance(ServiceFunc* serviceFunc)
{
DbgEngPlugin* plugin = new DbgEngPlugin;
HRESULT hr = DebugCreate(__uuidof(IDebugClient), (void**)&plugin->debugClient);
assert(SUCCEEDED(hr));
hr = plugin->debugClient->SetEventCallbacks(plugin);
assert(SUCCEEDED(hr));
hr = plugin->debugClient->QueryInterface(__uuidof(IDebugControl), (void**)&plugin->debugControl);
assert(SUCCEEDED(hr));
return plugin;
}
void destroyInstance(void* userData)
{
DbgEngPlugin* plugin = reinterpret_cast<DbgEngPlugin*>(userData);
if (plugin->debugControl)
{
plugin->debugControl->Release();
plugin->debugControl = nullptr;
}
if (plugin->debugClient)
{
plugin->debugClient->Release();
plugin->debugClient = nullptr;
}
delete plugin;
}
static PDDebugState update(void* userData, PDAction action, PDReader* reader, PDWriter* writer)
{
DbgEngPlugin* plugin = reinterpret_cast<DbgEngPlugin*>(userData);
processEvents(plugin, reader, writer);
doAction(plugin, action);
if (plugin->state == PDDebugState_running)
{
updateDbgEngEvent(plugin, writer);
}
return plugin->state;
}
static PDBackendPlugin plugin =
{
"Microsoft Debugger Engine",
createInstance,
destroyInstance,
update,
};
extern "C" PD_EXPORT void InitPlugin(RegisterPlugin* registerPlugin, void* privateData)
{
registerPlugin(PD_BACKEND_API_VERSION, &plugin, privateData);
}
#endif
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtSensors module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef Q_OS_BLACKBERRY
#include "genericorientationsensor.h"
#include "genericrotationsensor.h"
#include "genericalssensor.h"
#endif
#include "generictiltsensor.h"
#include <qsensorplugin.h>
#include <qsensorbackend.h>
#include <qsensormanager.h>
#include <QFile>
#include <QDebug>
class genericSensorPlugin : public QObject, public QSensorPluginInterface, public QSensorChangesInterface, public QSensorBackendFactory
{
Q_OBJECT
Q_PLUGIN_METADATA(IID "com.nokia.Qt.QSensorPluginInterface/1.0" FILE "plugin.json")
Q_INTERFACES(QSensorPluginInterface QSensorChangesInterface)
public:
void registerSensors()
{
qDebug() << "loaded the Generic plugin";
// Nothing to register here
}
void sensorsChanged()
{
if (!QSensor::defaultSensorForType(QAccelerometer::type).isEmpty()) {
// There is an accelerometer available. Register the backends
#ifndef Q_OS_BLACKBERRY
if (!QSensorManager::isBackendRegistered(QOrientationSensor::type, genericorientationsensor::id))
QSensorManager::registerBackend(QOrientationSensor::type, genericorientationsensor::id, this);
if (!QSensorManager::isBackendRegistered(QRotationSensor::type, genericrotationsensor::id))
QSensorManager::registerBackend(QRotationSensor::type, genericrotationsensor::id, this);
if (!QSensorManager::isBackendRegistered(QAmbientLightSensor::type, genericalssensor::id))
QSensorManager::registerBackend(QAmbientLightSensor::type, genericalssensor::id, this);
#endif
if (!QSensorManager::isBackendRegistered(QTiltSensor::type, GenericTiltSensor::id))
QSensorManager::registerBackend(QTiltSensor::type, GenericTiltSensor::id, this);
} else {
#ifndef Q_OS_BLACKBERRY
if (QSensorManager::isBackendRegistered(QOrientationSensor::type, genericorientationsensor::id))
QSensorManager::unregisterBackend(QOrientationSensor::type, genericorientationsensor::id);
if (QSensorManager::isBackendRegistered(QRotationSensor::type, genericrotationsensor::id))
QSensorManager::unregisterBackend(QRotationSensor::type, genericrotationsensor::id);
if (QSensorManager::isBackendRegistered(QAmbientLightSensor::type, genericalssensor::id))
QSensorManager::unregisterBackend(QAmbientLightSensor::type, genericalssensor::id);
#endif
if (QSensorManager::isBackendRegistered(QTiltSensor::type, GenericTiltSensor::id))
QSensorManager::unregisterBackend(QTiltSensor::type, GenericTiltSensor::id);
}
}
QSensorBackend *createBackend(QSensor *sensor)
{
#ifndef Q_OS_BLACKBERRY
if (sensor->identifier() == genericorientationsensor::id)
return new genericorientationsensor(sensor);
if (sensor->identifier() == genericrotationsensor::id)
return new genericrotationsensor(sensor);
if (sensor->identifier() == genericalssensor::id)
return new genericalssensor(sensor);
#endif
if (sensor->identifier() == GenericTiltSensor::id)
return new GenericTiltSensor(sensor);
return 0;
}
};
#include "main.moc"
<commit_msg>Generic plugin: Remove debug message noise.<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtSensors module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef Q_OS_BLACKBERRY
#include "genericorientationsensor.h"
#include "genericrotationsensor.h"
#include "genericalssensor.h"
#endif
#include "generictiltsensor.h"
#include <qsensorplugin.h>
#include <qsensorbackend.h>
#include <qsensormanager.h>
#include <QFile>
#include <QDebug>
class genericSensorPlugin : public QObject, public QSensorPluginInterface, public QSensorChangesInterface, public QSensorBackendFactory
{
Q_OBJECT
Q_PLUGIN_METADATA(IID "com.nokia.Qt.QSensorPluginInterface/1.0" FILE "plugin.json")
Q_INTERFACES(QSensorPluginInterface QSensorChangesInterface)
public:
void registerSensors()
{
// Nothing to register here
}
void sensorsChanged()
{
if (!QSensor::defaultSensorForType(QAccelerometer::type).isEmpty()) {
// There is an accelerometer available. Register the backends
#ifndef Q_OS_BLACKBERRY
if (!QSensorManager::isBackendRegistered(QOrientationSensor::type, genericorientationsensor::id))
QSensorManager::registerBackend(QOrientationSensor::type, genericorientationsensor::id, this);
if (!QSensorManager::isBackendRegistered(QRotationSensor::type, genericrotationsensor::id))
QSensorManager::registerBackend(QRotationSensor::type, genericrotationsensor::id, this);
if (!QSensorManager::isBackendRegistered(QAmbientLightSensor::type, genericalssensor::id))
QSensorManager::registerBackend(QAmbientLightSensor::type, genericalssensor::id, this);
#endif
if (!QSensorManager::isBackendRegistered(QTiltSensor::type, GenericTiltSensor::id))
QSensorManager::registerBackend(QTiltSensor::type, GenericTiltSensor::id, this);
} else {
#ifndef Q_OS_BLACKBERRY
if (QSensorManager::isBackendRegistered(QOrientationSensor::type, genericorientationsensor::id))
QSensorManager::unregisterBackend(QOrientationSensor::type, genericorientationsensor::id);
if (QSensorManager::isBackendRegistered(QRotationSensor::type, genericrotationsensor::id))
QSensorManager::unregisterBackend(QRotationSensor::type, genericrotationsensor::id);
if (QSensorManager::isBackendRegistered(QAmbientLightSensor::type, genericalssensor::id))
QSensorManager::unregisterBackend(QAmbientLightSensor::type, genericalssensor::id);
#endif
if (QSensorManager::isBackendRegistered(QTiltSensor::type, GenericTiltSensor::id))
QSensorManager::unregisterBackend(QTiltSensor::type, GenericTiltSensor::id);
}
}
QSensorBackend *createBackend(QSensor *sensor)
{
#ifndef Q_OS_BLACKBERRY
if (sensor->identifier() == genericorientationsensor::id)
return new genericorientationsensor(sensor);
if (sensor->identifier() == genericrotationsensor::id)
return new genericrotationsensor(sensor);
if (sensor->identifier() == genericalssensor::id)
return new genericalssensor(sensor);
#endif
if (sensor->identifier() == GenericTiltSensor::id)
return new GenericTiltSensor(sensor);
return 0;
}
};
#include "main.moc"
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the V4VM module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qv4objectiterator_p.h"
#include "qv4object_p.h"
#include "qv4stringobject_p.h"
#include "qv4identifier_p.h"
using namespace QV4;
ObjectIterator::ObjectIterator(Object *o, uint flags)
: object(o)
, current(o)
, arrayNode(0)
, arrayIndex(0)
, memberIndex(0)
, flags(flags)
{
tmpDynamicProperty.value = Value::undefinedValue();
}
Property *ObjectIterator::next(String **name, uint *index, PropertyAttributes *attrs)
{
Property *p = 0;
*name = 0;
*index = UINT_MAX;
while (1) {
if (!current)
break;
p = current->advanceIterator(this, name, index, attrs);
if (p)
return p;
if (flags & WithProtoChain)
current = current->prototype;
else
current = 0;
arrayIndex = 0;
memberIndex = 0;
}
return 0;
}
Value ObjectIterator::nextPropertyName(Value *value)
{
PropertyAttributes attrs;
uint index;
String *name;
Property *p = next(&name, &index, &attrs);
if (!p)
return Value::nullValue();
if (value)
*value = object->getValue(object->engine()->current, p, attrs);
if (name)
return Value::fromString(name);
assert(index < UINT_MAX);
return Value::fromDouble(index);
}
Value ObjectIterator::nextPropertyNameAsString(Value *value)
{
PropertyAttributes attrs;
uint index;
String *name;
Property *p = next(&name, &index, &attrs);
if (!p)
return Value::nullValue();
if (value)
*value = object->getValue(object->engine()->current, p, attrs);
if (name)
return Value::fromString(name);
assert(index < UINT_MAX);
return Value::fromString(object->engine()->newString(QString::number(index)));
}
<commit_msg>Fix for..in with duplicated properties<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the V4VM module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qv4objectiterator_p.h"
#include "qv4object_p.h"
#include "qv4stringobject_p.h"
#include "qv4identifier_p.h"
using namespace QV4;
ObjectIterator::ObjectIterator(Object *o, uint flags)
: object(o)
, current(o)
, arrayNode(0)
, arrayIndex(0)
, memberIndex(0)
, flags(flags)
{
tmpDynamicProperty.value = Value::undefinedValue();
}
Property *ObjectIterator::next(String **name, uint *index, PropertyAttributes *attrs)
{
Property *p = 0;
*name = 0;
*index = UINT_MAX;
while (1) {
if (!current)
break;
while (p = current->advanceIterator(this, name, index, attrs)) {
// check the property is not already defined earlier in the proto chain
if (current != object) {
Property *pp;
if (*name) {
pp = object->__getPropertyDescriptor__(*name);
} else {
assert (*index != UINT_MAX);
pp = object->__getPropertyDescriptor__(*index);
}
if (pp != p)
continue;
}
return p;
}
if (flags & WithProtoChain)
current = current->prototype;
else
current = 0;
arrayIndex = 0;
memberIndex = 0;
}
return 0;
}
Value ObjectIterator::nextPropertyName(Value *value)
{
PropertyAttributes attrs;
uint index;
String *name;
Property *p = next(&name, &index, &attrs);
if (!p)
return Value::nullValue();
if (value)
*value = object->getValue(object->engine()->current, p, attrs);
if (name)
return Value::fromString(name);
assert(index < UINT_MAX);
return Value::fromDouble(index);
}
Value ObjectIterator::nextPropertyNameAsString(Value *value)
{
PropertyAttributes attrs;
uint index;
String *name;
Property *p = next(&name, &index, &attrs);
if (!p)
return Value::nullValue();
if (value)
*value = object->getValue(object->engine()->current, p, attrs);
if (name)
return Value::fromString(name);
assert(index < UINT_MAX);
return Value::fromString(object->engine()->newString(QString::number(index)));
}
<|endoftext|>
|
<commit_before>#include "rdb_protocol/terms/terms.hpp"
#include <string>
#include "rdb_protocol/op.hpp"
#include "rdb_protocol/error.hpp"
#include "rdb_protocol/pb_utils.hpp"
namespace ql {
// This term is used for functions that are polymorphic on objects and
// sequences, like `pluck`. It will handle the polymorphism; terms inheriting
// from it just need to implement evaluation on objects (`obj_eval`).
class obj_or_seq_op_term_t : public op_term_t {
public:
enum poly_type_t {
MAP = 0,
FILTER = 1
};
obj_or_seq_op_term_t(env_t *env, protob_t<const Term> term,
poly_type_t _poly_type, argspec_t argspec)
: op_term_t(env, term, argspec), poly_type(_poly_type),
func(make_counted_term()) {
int varnum = env->gensym();
Term *body = pb::set_func(func.get(), varnum);
*body = *term;
pb::set_var(pb::reset(body->mutable_args(0)), varnum);
prop_bt(func.get());
}
private:
virtual counted_t<val_t> obj_eval() = 0;
virtual counted_t<val_t> eval_impl() {
counted_t<val_t> v0 = arg(0);
if (v0->get_type().is_convertible(val_t::type_t::DATUM)) {
if (v0->as_datum()->get_type() == datum_t::R_OBJECT) return obj_eval();
}
if (v0->get_type().is_convertible(val_t::type_t::SEQUENCE)) {
switch (poly_type) {
case MAP:
return new_val(v0->as_seq()->map(make_counted<func_t>(env, func)));
case FILTER:
return new_val(v0->as_seq()->filter(make_counted<func_t>(env, func)));
default: unreachable();
}
unreachable();
}
rfail("Cannot perform %s on a non-object non-sequence.", name());
unreachable();
}
poly_type_t poly_type;
protob_t<Term> func;
};
class pluck_term_t : public obj_or_seq_op_term_t {
public:
pluck_term_t(env_t *env, protob_t<const Term> term) :
obj_or_seq_op_term_t(env, term, MAP, argspec_t(1, -1)) { }
private:
virtual counted_t<val_t> obj_eval() {
counted_t<const datum_t> obj = arg(0)->as_datum();
r_sanity_check(obj->get_type() == datum_t::R_OBJECT);
scoped_ptr_t<datum_t> out(new datum_t(datum_t::R_OBJECT));
for (size_t i = 1; i < num_args(); ++i) {
const std::string &key = arg(i)->as_str();
counted_t<const datum_t> el = obj->get(key);
if (el.has()) {
bool conflict = out->add(key, el);
r_sanity_check(!conflict);
}
}
return new_val(counted_t<const datum_t>(out.release()));
}
virtual const char *name() const { return "pluck"; }
};
class without_term_t : public obj_or_seq_op_term_t {
public:
without_term_t(env_t *env, protob_t<const Term> term) :
obj_or_seq_op_term_t(env, term, MAP, argspec_t(1, -1)) { }
private:
virtual counted_t<val_t> obj_eval() {
counted_t<const datum_t> obj = arg(0)->as_datum();
r_sanity_check(obj->get_type() == datum_t::R_OBJECT);
scoped_ptr_t<datum_t> out(new datum_t(obj->as_object()));
for (size_t i = 1; i < num_args(); ++i) {
const std::string &key = arg(i)->as_str();
UNUSED bool b = out->delete_key(key);
}
return new_val(counted_t<const datum_t>(out.release()));
}
virtual const char *name() const { return "without"; }
};
class merge_term_t : public obj_or_seq_op_term_t {
public:
merge_term_t(env_t *env, protob_t<const Term> term) :
obj_or_seq_op_term_t(env, term, MAP, argspec_t(1, -1)) { }
private:
virtual counted_t<val_t> obj_eval() {
counted_t<const datum_t> d = arg(0)->as_datum();
for (size_t i = 1; i < num_args(); ++i) {
d = d->merge(arg(i)->as_datum());
}
return new_val(d);
}
virtual const char *name() const { return "merge"; }
};
class has_fields_term_t : public obj_or_seq_op_term_t {
public:
has_fields_term_t(env_t *env, protob_t<const Term> term)
: obj_or_seq_op_term_t(env, term, FILTER, argspec_t(1, -1)) { }
private:
virtual counted_t<val_t> obj_eval() {
counted_t<const datum_t> obj = arg(0)->as_datum();
for (size_t i = 1; i < num_args(); ++i) {
counted_t<const datum_t> el = obj->get(arg(i)->as_str(), NOTHROW);
if (!el.has() || el->get_type() == datum_t::R_NULL) {
return new_val_bool(false);
}
}
return new_val_bool(true);
}
virtual const char *name() const { return "has_fields"; }
};
counted_t<term_t> make_has_fields_term(env_t *env, protob_t<const Term> term) {
return make_counted<has_fields_term_t>(env, term);
}
counted_t<term_t> make_pluck_term(env_t *env, protob_t<const Term> term) {
return make_counted<pluck_term_t>(env, term);
}
counted_t<term_t> make_without_term(env_t *env, protob_t<const Term> term) {
return make_counted<without_term_t>(env, term);
}
counted_t<term_t> make_merge_term(env_t *env, protob_t<const Term> term) {
return make_counted<merge_term_t>(env, term);
}
} // namespace ql
<commit_msg>fixed pluck and without to not be quadratic<commit_after>#include "rdb_protocol/terms/terms.hpp"
#include <string>
#include "rdb_protocol/op.hpp"
#include "rdb_protocol/error.hpp"
#include "rdb_protocol/pb_utils.hpp"
namespace ql {
// This term is used for functions that are polymorphic on objects and
// sequences, like `pluck`. It will handle the polymorphism; terms inheriting
// from it just need to implement evaluation on objects (`obj_eval`).
class obj_or_seq_op_term_t : public op_term_t {
public:
enum poly_type_t {
MAP = 0,
FILTER = 1
};
obj_or_seq_op_term_t(env_t *env, protob_t<const Term> term,
poly_type_t _poly_type, argspec_t argspec)
: op_term_t(env, term, argspec), poly_type(_poly_type),
func(make_counted_term()) {
int varnum = env->gensym();
Term *body = pb::set_func(func.get(), varnum);
*body = *term;
pb::set_var(pb::reset(body->mutable_args(0)), varnum);
prop_bt(func.get());
}
private:
virtual counted_t<val_t> obj_eval(counted_t<val_t> v0) = 0;
virtual counted_t<val_t> eval_impl() {
counted_t<val_t> v0 = arg(0);
if (v0->get_type().is_convertible(val_t::type_t::DATUM)) {
if (v0->as_datum()->get_type() == datum_t::R_OBJECT) return obj_eval(v0);
}
if (v0->get_type().is_convertible(val_t::type_t::SEQUENCE)) {
switch (poly_type) {
case MAP:
return new_val(v0->as_seq()->map(make_counted<func_t>(env, func)));
case FILTER:
return new_val(v0->as_seq()->filter(make_counted<func_t>(env, func)));
default: unreachable();
}
unreachable();
}
rfail("Cannot perform %s on a non-object non-sequence.", name());
unreachable();
}
poly_type_t poly_type;
protob_t<Term> func;
};
class pluck_term_t : public obj_or_seq_op_term_t {
public:
pluck_term_t(env_t *env, protob_t<const Term> term) :
obj_or_seq_op_term_t(env, term, MAP, argspec_t(1, -1)) { }
private:
virtual counted_t<val_t> obj_eval(counted_t<val_t> v0) {
counted_t<const datum_t> obj = v0->as_datum();
r_sanity_check(obj->get_type() == datum_t::R_OBJECT);
scoped_ptr_t<datum_t> out(new datum_t(datum_t::R_OBJECT));
for (size_t i = 1; i < num_args(); ++i) {
const std::string &key = arg(i)->as_str();
counted_t<const datum_t> el = obj->get(key);
if (el.has()) {
bool conflict = out->add(key, el);
r_sanity_check(!conflict);
}
}
return new_val(counted_t<const datum_t>(out.release()));
}
virtual const char *name() const { return "pluck"; }
};
class without_term_t : public obj_or_seq_op_term_t {
public:
without_term_t(env_t *env, protob_t<const Term> term) :
obj_or_seq_op_term_t(env, term, MAP, argspec_t(1, -1)) { }
private:
virtual counted_t<val_t> obj_eval(counted_t<val_t> v0) {
counted_t<const datum_t> obj = v0->as_datum();
r_sanity_check(obj->get_type() == datum_t::R_OBJECT);
scoped_ptr_t<datum_t> out(new datum_t(obj->as_object()));
for (size_t i = 1; i < num_args(); ++i) {
const std::string &key = arg(i)->as_str();
UNUSED bool b = out->delete_key(key);
}
return new_val(counted_t<const datum_t>(out.release()));
}
virtual const char *name() const { return "without"; }
};
class merge_term_t : public obj_or_seq_op_term_t {
public:
merge_term_t(env_t *env, protob_t<const Term> term) :
obj_or_seq_op_term_t(env, term, MAP, argspec_t(1, -1)) { }
private:
virtual counted_t<val_t> obj_eval(counted_t<val_t> v0) {
counted_t<const datum_t> d = v0->as_datum();
for (size_t i = 1; i < num_args(); ++i) {
d = d->merge(arg(i)->as_datum());
}
return new_val(d);
}
virtual const char *name() const { return "merge"; }
};
class has_fields_term_t : public obj_or_seq_op_term_t {
public:
has_fields_term_t(env_t *env, protob_t<const Term> term)
: obj_or_seq_op_term_t(env, term, FILTER, argspec_t(1, -1)) { }
private:
virtual counted_t<val_t> obj_eval(counted_t<val_t> v0) {
counted_t<const datum_t> obj = v0->as_datum();
for (size_t i = 1; i < num_args(); ++i) {
counted_t<const datum_t> el = obj->get(arg(i)->as_str(), NOTHROW);
if (!el.has() || el->get_type() == datum_t::R_NULL) {
return new_val_bool(false);
}
}
return new_val_bool(true);
}
virtual const char *name() const { return "has_fields"; }
};
counted_t<term_t> make_has_fields_term(env_t *env, protob_t<const Term> term) {
return make_counted<has_fields_term_t>(env, term);
}
counted_t<term_t> make_pluck_term(env_t *env, protob_t<const Term> term) {
return make_counted<pluck_term_t>(env, term);
}
counted_t<term_t> make_without_term(env_t *env, protob_t<const Term> term) {
return make_counted<without_term_t>(env, term);
}
counted_t<term_t> make_merge_term(env_t *env, protob_t<const Term> term) {
return make_counted<merge_term_t>(env, term);
}
} // namespace ql
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <deque>
#include "catch.hpp"
#include "dll/dbn.hpp"
#include "dll/text_reader.hpp"
#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"
TEST_CASE("dbn/mnist_1", "dbn::simple") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::layer_t,
dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::layer_t,
dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::layer_t>,
dll::batch_size<50>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(500);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 10);
REQUIRE(error < 5e-2);
auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
std::cout << "test_error:" << test_error << std::endl;
REQUIRE(test_error < 0.2);
}
TEST_CASE("dbn/mnist_2", "dbn::containers") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::layer_t,
dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::layer_t,
dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::layer_t>,
dll::batch_size<50>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(500);
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(200);
dataset.training_labels.resize(200);
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 5);
auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 5);
REQUIRE(error < 5e-2);
}
TEST_CASE("dbn/mnist_3", "dbn::labels") {
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(1000);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
typedef dll::dbn_desc<
dll::dbn_label_layers<
dll::rbm_desc<28 * 28, 200, dll::batch_size<50>, dll::init_weights, dll::momentum>::layer_t,
dll::rbm_desc<200, 300, dll::batch_size<50>, dll::momentum>::layer_t,
dll::rbm_desc<310, 500, dll::batch_size<50>, dll::momentum>::layer_t>,
dll::batch_size<10>>::dbn_t dbn_t;
auto dbn = std::make_unique<dbn_t>();
dbn->train_with_labels(dataset.training_images, dataset.training_labels, 10, 10);
auto error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::label_predictor());
std::cout << "test_error:" << error << std::endl;
REQUIRE(error < 0.3);
}
TEST_CASE("dbn/mnist_6", "dbn::cg_gaussian") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 200, dll::momentum, dll::batch_size<25>, dll::visible<dll::unit_type::GAUSSIAN>>::layer_t,
dll::rbm_desc<200, 500, dll::momentum, dll::batch_size<25>>::layer_t,
dll::rbm_desc<500, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::layer_t>,
dll::batch_size<50>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(1000);
REQUIRE(!dataset.training_images.empty());
mnist::normalize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 10);
REQUIRE(error < 5e-2);
auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
std::cout << "test_error:" << test_error << std::endl;
REQUIRE(test_error < 0.2);
}
//This test should not perform well, but should not fail
TEST_CASE("dbn/mnist_8", "dbn::cg_relu") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::RELU>, dll::init_weights>::layer_t,
dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::layer_t,
dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::layer_t>,
dll::batch_size<50>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(200);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 10);
REQUIRE(std::isfinite(error));
auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
std::cout << "test_error:" << test_error << std::endl;
}
TEST_CASE("dbn/mnist_15", "dbn::parallel") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 100, dll::momentum, dll::parallel_mode, dll::batch_size<25>, dll::init_weights>::layer_t,
dll::rbm_desc<100, 200, dll::momentum, dll::parallel_mode, dll::batch_size<25>>::layer_t,
dll::rbm_desc<200, 10, dll::momentum, dll::parallel_mode, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::layer_t>,
dll::batch_size<50>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(500);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 10);
REQUIRE(error < 5e-2);
auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
std::cout << "test_error:" << test_error << std::endl;
REQUIRE(test_error < 0.2);
}
TEST_CASE("dbn/mnist_17", "dbn::memory") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::layer_t,
dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::layer_t,
dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::layer_t>,
dll::batch_mode, dll::batch_size<50>, dll::big_batch_size<3>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(1078);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(
dataset.training_images.begin(), dataset.training_images.end(),
dataset.training_labels.begin(), dataset.training_labels.end(),
10);
REQUIRE(error < 5e-2);
auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
std::cout << "test_error:" << test_error << std::endl;
REQUIRE(test_error < 0.2);
//Mostly here to ensure compilation
auto out = dbn->prepare_one_output<etl::dyn_matrix<float, 1>>();
REQUIRE(out.size() > 0);
}
TEST_CASE("dbn/mnist/text/1", "dbn::simple") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::layer_t,
dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::layer_t,
dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::layer_t>,
dll::batch_size<50>>::dbn_t dbn_t;
auto training_images = dll::text::read_images<std::vector, etl::dyn_matrix<float, 1>>(
"/home/wichtounet/datasets/mnist_text/train/images", 500,
[](){ return etl::dyn_matrix<float, 1>(28 * 28);});
auto test_images = dll::text::read_images<std::vector, etl::dyn_matrix<float, 1>>(
"/home/wichtounet/datasets/mnist_text/test/images", 500,
[](){ return etl::dyn_matrix<float, 1>(28 * 28);});
auto training_labels = dll::text::read_labels<std::vector, uint8_t>("/home/wichtounet/datasets/mnist_text/train/labels", 500);
auto test_labels = dll::text::read_labels<std::vector, uint8_t>("/home/wichtounet/datasets/mnist_text/test/labels", 500);
REQUIRE(training_images.size() == 500);
REQUIRE(test_images.size() == 500);
REQUIRE(training_labels.size() == 500);
REQUIRE(test_labels.size() == 500);
mnist::binarize_each(training_images);
mnist::binarize_each(test_images);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(training_images, 20);
auto error = dbn->fine_tune(training_images, training_labels, 10);
REQUIRE(error < 5e-2);
auto test_error = dll::test_set(dbn, test_images, test_labels, dll::predictor());
std::cout << "test_error:" << test_error << std::endl;
REQUIRE(test_error < 0.2);
}
<commit_msg>Review the test<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <deque>
#include "catch.hpp"
#include "dll/dbn.hpp"
#include "dll/text_reader.hpp"
#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"
TEST_CASE("dbn/mnist_1", "dbn::simple") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::layer_t,
dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::layer_t,
dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::layer_t>,
dll::batch_size<50>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(500);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 10);
REQUIRE(error < 5e-2);
auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
std::cout << "test_error:" << test_error << std::endl;
REQUIRE(test_error < 0.2);
}
TEST_CASE("dbn/mnist_2", "dbn::containers") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::layer_t,
dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::layer_t,
dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::layer_t>,
dll::batch_size<50>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(500);
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(200);
dataset.training_labels.resize(200);
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 5);
auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 5);
REQUIRE(error < 5e-2);
}
TEST_CASE("dbn/mnist_3", "dbn::labels") {
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(1000);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
typedef dll::dbn_desc<
dll::dbn_label_layers<
dll::rbm_desc<28 * 28, 200, dll::batch_size<50>, dll::init_weights, dll::momentum>::layer_t,
dll::rbm_desc<200, 300, dll::batch_size<50>, dll::momentum>::layer_t,
dll::rbm_desc<310, 500, dll::batch_size<50>, dll::momentum>::layer_t>,
dll::batch_size<10>>::dbn_t dbn_t;
auto dbn = std::make_unique<dbn_t>();
dbn->train_with_labels(dataset.training_images, dataset.training_labels, 10, 10);
auto error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::label_predictor());
std::cout << "test_error:" << error << std::endl;
REQUIRE(error < 0.3);
}
TEST_CASE("dbn/mnist_6", "dbn::cg_gaussian") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 200, dll::momentum, dll::batch_size<25>, dll::visible<dll::unit_type::GAUSSIAN>>::layer_t,
dll::rbm_desc<200, 500, dll::momentum, dll::batch_size<25>>::layer_t,
dll::rbm_desc<500, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::layer_t>,
dll::batch_size<50>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(1000);
REQUIRE(!dataset.training_images.empty());
mnist::normalize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 10);
REQUIRE(error < 5e-2);
auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
std::cout << "test_error:" << test_error << std::endl;
REQUIRE(test_error < 0.2);
}
//This test should not perform well, but should not fail
TEST_CASE("dbn/mnist_8", "dbn::cg_relu") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::RELU>, dll::init_weights>::layer_t,
dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::layer_t,
dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::layer_t>,
dll::batch_size<50>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(200);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 10);
REQUIRE(std::isfinite(error));
auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
std::cout << "test_error:" << test_error << std::endl;
}
TEST_CASE("dbn/mnist_15", "dbn::parallel") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 100, dll::momentum, dll::parallel_mode, dll::batch_size<25>, dll::init_weights>::layer_t,
dll::rbm_desc<100, 200, dll::momentum, dll::parallel_mode, dll::batch_size<25>>::layer_t,
dll::rbm_desc<200, 10, dll::momentum, dll::parallel_mode, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::layer_t>,
dll::batch_size<50>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(500);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 10);
REQUIRE(error < 5e-2);
auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
std::cout << "test_error:" << test_error << std::endl;
REQUIRE(test_error < 0.2);
}
TEST_CASE("dbn/mnist_17", "dbn::memory") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::layer_t,
dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::layer_t,
dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::layer_t>,
dll::batch_mode, dll::batch_size<50>, dll::big_batch_size<3>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(1078);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(
dataset.training_images.begin(), dataset.training_images.end(),
dataset.training_labels.begin(), dataset.training_labels.end(),
10);
REQUIRE(error < 5e-2);
auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
std::cout << "test_error:" << test_error << std::endl;
REQUIRE(test_error < 0.2);
//Mostly here to ensure compilation
auto out = dbn->prepare_one_output<etl::dyn_matrix<float, 1>>();
REQUIRE(out.size() > 0);
}
TEST_CASE("dbn/mnist/text/1", "dbn::simple") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::layer_t,
dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::layer_t,
dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::layer_t>,
dll::batch_size<50>>::dbn_t dbn_t;
auto training_images = dll::text::read_images<std::vector, etl::dyn_matrix<float, 1>, false>(
"/home/wichtounet/datasets/mnist_text/train/images", 500);
auto test_images = dll::text::read_images<std::vector, etl::dyn_matrix<float, 1>, false>(
"/home/wichtounet/datasets/mnist_text/test/images", 500);
auto training_labels = dll::text::read_labels<std::vector, uint8_t>("/home/wichtounet/datasets/mnist_text/train/labels", 500);
auto test_labels = dll::text::read_labels<std::vector, uint8_t>("/home/wichtounet/datasets/mnist_text/test/labels", 500);
REQUIRE(training_images.size() == 500);
REQUIRE(test_images.size() == 500);
REQUIRE(training_labels.size() == 500);
REQUIRE(test_labels.size() == 500);
mnist::binarize_each(training_images);
mnist::binarize_each(test_images);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(training_images, 20);
auto error = dbn->fine_tune(training_images, training_labels, 10);
REQUIRE(error < 5e-2);
auto test_error = dll::test_set(dbn, test_images, test_labels, dll::predictor());
std::cout << "test_error:" << test_error << std::endl;
REQUIRE(test_error < 0.2);
}
<|endoftext|>
|
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2010 Hauke Heibel <hauke.heibel@gmail.com>
//
// Eigen 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.
//
// Alternatively, 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.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
#include <Eigen/StdList>
#include <Eigen/Geometry>
template<typename MatrixType>
void check_stdlist_matrix(const MatrixType& m)
{
int rows = m.rows();
int cols = m.cols();
MatrixType x = MatrixType::Random(rows,cols), y = MatrixType::Random(rows,cols);
std::list<MatrixType,Eigen::aligned_allocator<MatrixType> > v(10, MatrixType(rows,cols)), w(20, y);
v.front() = x;
w.front() = w.back();
VERIFY_IS_APPROX(w.front(), w.back());
v = w;
typename std::list<MatrixType,Eigen::aligned_allocator<MatrixType> >::iterator vi = v.begin();
typename std::list<MatrixType,Eigen::aligned_allocator<MatrixType> >::iterator wi = w.begin();
for(int i = 0; i < 20; i++)
{
VERIFY_IS_APPROX(*vi, *wi);
++vi;
++wi;
}
v.resize(21);
v.back() = x;
if (!test_ei_isApprox(v.back(),x))
{
std::cout << x << std::endl;
std::cout << v.back() << std::endl;
}
VERIFY_IS_APPROX(v.back(), x);
v.resize(22,y);
VERIFY_IS_APPROX(v.back(), y);
v.push_back(x);
VERIFY_IS_APPROX(v.back(), x);
}
template<typename TransformType>
void check_stdlist_transform(const TransformType&)
{
typedef typename TransformType::MatrixType MatrixType;
TransformType x(MatrixType::Random()), y(MatrixType::Random());
std::list<TransformType,Eigen::aligned_allocator<TransformType> > v(10), w(20, y);
v.front() = x;
w.front() = w.back();
VERIFY_IS_APPROX(w.front(), w.back());
v = w;
typename std::list<TransformType,Eigen::aligned_allocator<TransformType> >::iterator vi = v.begin();
typename std::list<TransformType,Eigen::aligned_allocator<TransformType> >::iterator wi = w.begin();
for(int i = 0; i < 20; i++)
{
VERIFY_IS_APPROX(*vi, *wi);
++vi;
++wi;
}
v.resize(21);
v.back() = x;
VERIFY_IS_APPROX(v.back(), x);
v.resize(22,y);
VERIFY_IS_APPROX(v.back(), y);
v.push_back(x);
VERIFY_IS_APPROX(v.back(), x);
}
template<typename QuaternionType>
void check_stdlist_quaternion(const QuaternionType&)
{
typedef typename QuaternionType::Coefficients Coefficients;
QuaternionType x(Coefficients::Random()), y(Coefficients::Random());
std::list<QuaternionType,Eigen::aligned_allocator<QuaternionType> > v(10), w(20, y);
v.front() = x;
w.front() = w.back();
VERIFY_IS_APPROX(w.front(), w.back());
v = w;
typename std::list<QuaternionType,Eigen::aligned_allocator<QuaternionType> >::iterator vi = v.begin();
typename std::list<QuaternionType,Eigen::aligned_allocator<QuaternionType> >::iterator wi = w.begin();
for(int i = 0; i < 20; i++)
{
VERIFY_IS_APPROX(*vi, *wi);
++vi;
++wi;
}
v.resize(21);
v.back() = x;
VERIFY_IS_APPROX(v.back(), x);
v.resize(22,y);
VERIFY_IS_APPROX(v.back(), y);
v.push_back(x);
if (!test_ei_isApprox(v.back(),x))
{
std::cout << x << std::endl;
std::cout << v.back() << std::endl;
}
VERIFY_IS_APPROX(v.back(), x);
}
void test_stdlist()
{
// some non vectorizable fixed sizes
CALL_SUBTEST_1(check_stdlist_matrix(Vector2f()));
CALL_SUBTEST_1(check_stdlist_matrix(Matrix3f()));
CALL_SUBTEST_2(check_stdlist_matrix(Matrix3d()));
// some vectorizable fixed sizes
CALL_SUBTEST_1(check_stdlist_matrix(Matrix2f()));
CALL_SUBTEST_1(check_stdlist_matrix(Vector4f()));
CALL_SUBTEST_1(check_stdlist_matrix(Matrix4f()));
CALL_SUBTEST_2(check_stdlist_matrix(Matrix4d()));
// some dynamic sizes
CALL_SUBTEST_3(check_stdlist_matrix(MatrixXd(1,1)));
CALL_SUBTEST_3(check_stdlist_matrix(VectorXd(20)));
CALL_SUBTEST_3(check_stdlist_matrix(RowVectorXf(20)));
CALL_SUBTEST_3(check_stdlist_matrix(MatrixXcf(10,10)));
// some Transform
CALL_SUBTEST_4(check_stdlist_transform(Transform2f()));
CALL_SUBTEST_4(check_stdlist_transform(Transform3f()));
CALL_SUBTEST_4(check_stdlist_transform(Transform3d()));
//CALL_SUBTEST(heck_stdvector_transform(Transform4d()));
// some Quaternion
CALL_SUBTEST_5(check_stdlist_quaternion(Quaternionf()));
CALL_SUBTEST_5(check_stdlist_quaternion(Quaterniond()));
}
<commit_msg>Remove printouts.<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2010 Hauke Heibel <hauke.heibel@gmail.com>
//
// Eigen 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.
//
// Alternatively, 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.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
#include <Eigen/StdList>
#include <Eigen/Geometry>
template<typename MatrixType>
void check_stdlist_matrix(const MatrixType& m)
{
int rows = m.rows();
int cols = m.cols();
MatrixType x = MatrixType::Random(rows,cols), y = MatrixType::Random(rows,cols);
std::list<MatrixType,Eigen::aligned_allocator<MatrixType> > v(10, MatrixType(rows,cols)), w(20, y);
v.front() = x;
w.front() = w.back();
VERIFY_IS_APPROX(w.front(), w.back());
v = w;
typename std::list<MatrixType,Eigen::aligned_allocator<MatrixType> >::iterator vi = v.begin();
typename std::list<MatrixType,Eigen::aligned_allocator<MatrixType> >::iterator wi = w.begin();
for(int i = 0; i < 20; i++)
{
VERIFY_IS_APPROX(*vi, *wi);
++vi;
++wi;
}
v.resize(21);
v.back() = x;
VERIFY_IS_APPROX(v.back(), x);
v.resize(22,y);
VERIFY_IS_APPROX(v.back(), y);
v.push_back(x);
VERIFY_IS_APPROX(v.back(), x);
}
template<typename TransformType>
void check_stdlist_transform(const TransformType&)
{
typedef typename TransformType::MatrixType MatrixType;
TransformType x(MatrixType::Random()), y(MatrixType::Random());
std::list<TransformType,Eigen::aligned_allocator<TransformType> > v(10), w(20, y);
v.front() = x;
w.front() = w.back();
VERIFY_IS_APPROX(w.front(), w.back());
v = w;
typename std::list<TransformType,Eigen::aligned_allocator<TransformType> >::iterator vi = v.begin();
typename std::list<TransformType,Eigen::aligned_allocator<TransformType> >::iterator wi = w.begin();
for(int i = 0; i < 20; i++)
{
VERIFY_IS_APPROX(*vi, *wi);
++vi;
++wi;
}
v.resize(21);
v.back() = x;
VERIFY_IS_APPROX(v.back(), x);
v.resize(22,y);
VERIFY_IS_APPROX(v.back(), y);
v.push_back(x);
VERIFY_IS_APPROX(v.back(), x);
}
template<typename QuaternionType>
void check_stdlist_quaternion(const QuaternionType&)
{
typedef typename QuaternionType::Coefficients Coefficients;
QuaternionType x(Coefficients::Random()), y(Coefficients::Random());
std::list<QuaternionType,Eigen::aligned_allocator<QuaternionType> > v(10), w(20, y);
v.front() = x;
w.front() = w.back();
VERIFY_IS_APPROX(w.front(), w.back());
v = w;
typename std::list<QuaternionType,Eigen::aligned_allocator<QuaternionType> >::iterator vi = v.begin();
typename std::list<QuaternionType,Eigen::aligned_allocator<QuaternionType> >::iterator wi = w.begin();
for(int i = 0; i < 20; i++)
{
VERIFY_IS_APPROX(*vi, *wi);
++vi;
++wi;
}
v.resize(21);
v.back() = x;
VERIFY_IS_APPROX(v.back(), x);
v.resize(22,y);
VERIFY_IS_APPROX(v.back(), y);
v.push_back(x);
VERIFY_IS_APPROX(v.back(), x);
}
void test_stdlist()
{
// some non vectorizable fixed sizes
CALL_SUBTEST_1(check_stdlist_matrix(Vector2f()));
CALL_SUBTEST_1(check_stdlist_matrix(Matrix3f()));
CALL_SUBTEST_2(check_stdlist_matrix(Matrix3d()));
// some vectorizable fixed sizes
CALL_SUBTEST_1(check_stdlist_matrix(Matrix2f()));
CALL_SUBTEST_1(check_stdlist_matrix(Vector4f()));
CALL_SUBTEST_1(check_stdlist_matrix(Matrix4f()));
CALL_SUBTEST_2(check_stdlist_matrix(Matrix4d()));
// some dynamic sizes
CALL_SUBTEST_3(check_stdlist_matrix(MatrixXd(1,1)));
CALL_SUBTEST_3(check_stdlist_matrix(VectorXd(20)));
CALL_SUBTEST_3(check_stdlist_matrix(RowVectorXf(20)));
CALL_SUBTEST_3(check_stdlist_matrix(MatrixXcf(10,10)));
// some Transform
CALL_SUBTEST_4(check_stdlist_transform(Transform2f()));
CALL_SUBTEST_4(check_stdlist_transform(Transform3f()));
CALL_SUBTEST_4(check_stdlist_transform(Transform3d()));
//CALL_SUBTEST(heck_stdvector_transform(Transform4d()));
// some Quaternion
CALL_SUBTEST_5(check_stdlist_quaternion(Quaternionf()));
CALL_SUBTEST_5(check_stdlist_quaternion(Quaterniond()));
}
<|endoftext|>
|
<commit_before>#pragma once
//ASSERT_TRUE();
//ASSERT_STREQ(test.c_str(), ans.c_str());
//-----------------------------------------------------------------------------------------------------------------------------------------------
TEST(strEdit, theOthers){
printf("■ strEdit\n");
printf(" □ readAll_bin\n");
std::vector<uint8> raw = sstd::readAll_bin("./test/test.png");
sstd::printn_all(raw.size());
printf(" □ writeAll_bin\n");
if(!sstd::writeAll_bin("./test__writeAll_bin_char.png", raw)){ sstd::pdbg("ERROR: sstd::writeAll_bin()\n"); }
if(!sstd::writeAll_bin(std::string("./test__writeAll_bin_str.png"), raw)){ sstd::pdbg("ERROR: sstd::writeAll_bin()\n"); }
printf(" □ readAll_withoutBOM & splitByLine\n");
// std::string str_tI = sstd::readAll_withoutBOM(R"(./test/tinyInterpreter.txt)");
std::string str_tI = sstd::readAll_withoutBOM(std::string(R"(./test/tinyInterpreter.txt)"));
std::vector<std::string> splitLList = sstd::splitByLine(str_tI);
printf("\n");
printf(" ./test/tinyInterpreter.txt\n");
printf("+----+---------------------------------------------------------------------+\n");
for(uint i=0; i<splitLList.size(); i++){
printf("| %2d | %-67s |\n", i, splitLList[i].c_str());
}
printf("+----+---------------------------------------------------------------------+\n");
printf("\n");
printf(" □ splitByX\n");
std::vector<std::string> vecRow;
vecRow = sstd::split("ABC DEF", ' '); sstd::printn(vecRow); // "ABC DEF" -> ["ABC", "DEF"]
vecRow = sstd::split(" ABC D EF ", ' '); sstd::printn(vecRow); // " ABC D EF " -> ["ABC", "D", "EF"]
vecRow = sstd::split("ABC,DEF", ','); sstd::printn(vecRow); // "ABC,DEF" -> ["ABC", "DEF"]
vecRow = sstd::split(" ABC , D, EF ,GH ", ','); sstd::printn(vecRow); // " ABC , D, EF ,GH " -> ["ABC", "D", "EF", "GH"]
}
//-----------------------------------------------------------------------------------------------------------------------------------------------
TEST(strEdit, lstrip){
std::string str_in = " \t abcd \t ";
std::string str_ans = "abcd \t ";
ASSERT_TRUE(sstd::lstrip(str_in.c_str()) == str_ans);
ASSERT_TRUE(sstd::lstrip(str_in ) == str_ans);
}
TEST(strEdit, lstrip_ow){
std::string str_in = " \t abcd \t ";
std::string str_ans = "abcd \t ";
sstd::lstrip_ow(str_in);
ASSERT_TRUE(str_in == str_ans);
}
TEST(strEdit, rstrip){
std::string str_in = " \t abcd \t ";
std::string str_ans = " \t abcd";
ASSERT_TRUE(sstd::rstrip(str_in.c_str()) == str_ans);
ASSERT_TRUE(sstd::rstrip(str_in ) == str_ans);
}
TEST(strEdit, rstrip_ow){
std::string str_in = " \t abcd \t ";
std::string str_ans = " \t abcd";
sstd::rstrip_ow(str_in);
ASSERT_TRUE(str_in == str_ans);
}
TEST(strEdit, strip){
std::string str_in = " \t abcd \t ";
std::string str_ans = "abcd";
ASSERT_TRUE(sstd::strip(str_in.c_str()) == str_ans);
ASSERT_TRUE(sstd::strip(str_in ) == str_ans);
}
TEST(strEdit, strip_ow){
std::string str_in = " \t abcd \t ";
std::string str_ans = "abcd";
sstd::strip_ow(str_in);
ASSERT_TRUE(str_in == str_ans);
}
TEST(strEdit, strip_vec){
std::vector<std::string> vecStr_in = {" \t abcd01 \t ", " \t abcd02 \t ", " \t abcd03 \t "};
std::vector<std::string> vecStr_ans = {"abcd01", "abcd02", "abcd03"};
ASSERT_TRUE(sstd::strip(vecStr_in) == vecStr_ans);
}
//-----------------------------------------------------------------------------------------------------------------------------------------------
/*
// 実装完了 (処理時間短縮のため,コメントアウト)
TEST(strEdit, strIn){
{
std::string lhs = "";
std::string rhs = "";
bool ret=sstd::strIn(lhs, rhs); ASSERT_TRUE(ret);
}
{
std::string lhs = "ABCD";
std::string rhs = "ABCDEFG";
bool ret=sstd::strIn(lhs, rhs); ASSERT_TRUE(ret);
}
{
std::string lhs = "BCD";
std::string rhs = "ABCDEFG";
bool ret=sstd::strIn(lhs, rhs); ASSERT_TRUE(ret);
}
{
std::string lhs = "DEFG";
std::string rhs = "ABCDEFG";
bool ret=sstd::strIn(lhs, rhs); ASSERT_TRUE(ret);
}
{
std::string lhs = "ABCDEFG";
std::string rhs = "ABCDEFG";
bool ret=sstd::strIn(lhs, rhs); ASSERT_TRUE(ret);
}
{
std::string lhs = "AXCDEFG";
std::string rhs = "ABCDEFG";
bool ret=sstd::strIn(lhs, rhs); ASSERT_TRUE(!ret);
}
}
//*/
//-----------------------------------------------------------------------------------------------------------------------------------------------
<commit_msg>test sort<commit_after>#pragma once
//ASSERT_TRUE();
//ASSERT_STREQ(test.c_str(), ans.c_str());
//-----------------------------------------------------------------------------------------------------------------------------------------------
TEST(strEdit, theOthers){
printf("■ strEdit\n");
printf(" □ readAll_bin\n");
std::vector<uint8> raw = sstd::readAll_bin("./test/test.png");
sstd::printn_all(raw.size());
printf(" □ writeAll_bin\n");
if(!sstd::writeAll_bin("./test__writeAll_bin_char.png", raw)){ sstd::pdbg("ERROR: sstd::writeAll_bin()\n"); }
if(!sstd::writeAll_bin(std::string("./test__writeAll_bin_str.png"), raw)){ sstd::pdbg("ERROR: sstd::writeAll_bin()\n"); }
printf(" □ readAll_withoutBOM & splitByLine\n");
// std::string str_tI = sstd::readAll_withoutBOM(R"(./test/tinyInterpreter.txt)");
std::string str_tI = sstd::readAll_withoutBOM(std::string(R"(./test/tinyInterpreter.txt)"));
std::vector<std::string> splitLList = sstd::splitByLine(str_tI);
printf("\n");
printf(" ./test/tinyInterpreter.txt\n");
printf("+----+---------------------------------------------------------------------+\n");
for(uint i=0; i<splitLList.size(); i++){
printf("| %2d | %-67s |\n", i, splitLList[i].c_str());
}
printf("+----+---------------------------------------------------------------------+\n");
printf("\n");
printf(" □ splitByX\n");
std::vector<std::string> vecRow;
vecRow = sstd::split("ABC DEF", ' '); sstd::printn(vecRow); // "ABC DEF" -> ["ABC", "DEF"]
vecRow = sstd::split(" ABC D EF ", ' '); sstd::printn(vecRow); // " ABC D EF " -> ["ABC", "D", "EF"]
vecRow = sstd::split("ABC,DEF", ','); sstd::printn(vecRow); // "ABC,DEF" -> ["ABC", "DEF"]
vecRow = sstd::split(" ABC , D, EF ,GH ", ','); sstd::printn(vecRow); // " ABC , D, EF ,GH " -> ["ABC", "D", "EF", "GH"]
}
//-----------------------------------------------------------------------------------------------------------------------------------------------
TEST(strEdit, lstrip){
std::string str_in = " \t abcd \t ";
std::string str_ans = "abcd \t ";
ASSERT_TRUE(sstd::lstrip(str_in.c_str()) == str_ans);
ASSERT_TRUE(sstd::lstrip(str_in ) == str_ans);
}
TEST(strEdit, lstrip_ow){
std::string str_in = " \t abcd \t ";
std::string str_ans = "abcd \t ";
sstd::lstrip_ow(str_in);
ASSERT_TRUE(str_in == str_ans);
}
TEST(strEdit, rstrip){
std::string str_in = " \t abcd \t ";
std::string str_ans = " \t abcd";
ASSERT_TRUE(sstd::rstrip(str_in.c_str()) == str_ans);
ASSERT_TRUE(sstd::rstrip(str_in ) == str_ans);
}
TEST(strEdit, rstrip_ow){
std::string str_in = " \t abcd \t ";
std::string str_ans = " \t abcd";
sstd::rstrip_ow(str_in);
ASSERT_TRUE(str_in == str_ans);
}
TEST(strEdit, strip){
std::string str_in = " \t abcd \t ";
std::string str_ans = "abcd";
ASSERT_TRUE(sstd::strip(str_in.c_str()) == str_ans);
ASSERT_TRUE(sstd::strip(str_in ) == str_ans);
}
TEST(strEdit, strip_ow){
std::string str_in = " \t abcd \t ";
std::string str_ans = "abcd";
sstd::strip_ow(str_in);
ASSERT_TRUE(str_in == str_ans);
}
TEST(strEdit, strip_vec){
std::vector<std::string> vecStr_in = {" \t abcd01 \t ", " \t abcd02 \t ", " \t abcd03 \t "};
std::vector<std::string> vecStr_ans = {"abcd01", "abcd02", "abcd03"};
ASSERT_TRUE(sstd::strip(vecStr_in) == vecStr_ans);
}
//-----------------------------------------------------------------------------------------------------------------------------------------------
/*
// 実装完了 (処理時間短縮のため,コメントアウト)
TEST(strEdit, strIn){
{
std::string lhs = "";
std::string rhs = "";
bool ret=sstd::strIn(lhs, rhs); ASSERT_TRUE(ret);
}
{
std::string lhs = "ABCD";
std::string rhs = "ABCDEFG";
bool ret=sstd::strIn(lhs, rhs); ASSERT_TRUE(ret);
}
{
std::string lhs = "BCD";
std::string rhs = "ABCDEFG";
bool ret=sstd::strIn(lhs, rhs); ASSERT_TRUE(ret);
}
{
std::string lhs = "DEFG";
std::string rhs = "ABCDEFG";
bool ret=sstd::strIn(lhs, rhs); ASSERT_TRUE(ret);
}
{
std::string lhs = "ABCDEFG";
std::string rhs = "ABCDEFG";
bool ret=sstd::strIn(lhs, rhs); ASSERT_TRUE(ret);
}
{
std::string lhs = "AXCDEFG";
std::string rhs = "ABCDEFG";
bool ret=sstd::strIn(lhs, rhs); ASSERT_TRUE(!ret);
}
}
//*/
//-----------------------------------------------------------------------------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/* Copyright (c) 2008-2021 the MRtrix3 contributors.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Covered Software is provided under this License on an "as is"
* basis, without warranty of any kind, either expressed, implied, or
* statutory, including, without limitation, warranties that the
* Covered Software is free of defects, merchantable, fit for a
* particular purpose or non-infringing.
* See the Mozilla Public License v. 2.0 for more details.
*
* For more details, see http://www.mrtrix.org/.
*/
#include "command.h"
#include "progressbar.h"
#include "math/rng.h"
#include "math/SH.h"
#include "dwi/gradient.h"
#include "dwi/directions/file.h"
#include <random>
#include <functional>
using namespace MR;
using namespace App;
void usage ()
{
AUTHOR = "J-Donald Tournier (jdtournier@gmail.com)";
SYNOPSIS = "Reorder a set of directions to ensure near-uniformity upon truncation";
DESCRIPTION
+ "The intent of this command is to reorder a set of gradient directions such that "
"if a scan is terminated prematurely, at any point, the acquired directions will "
"still be close to optimally distributed on the half-sphere.";
ARGUMENTS
+ Argument ("input", "the input directions file").type_file_in()
+ Argument ("output", "the output directions file").type_file_out();
OPTIONS
+ Option ("cartesian", "Output the directions in Cartesian coordinates [x y z] instead of [az el].");
}
using value_type = double;
vector<size_t> optimise (const Eigen::MatrixXd& directions, const size_t first_volume)
{
vector<size_t> indices (1, first_volume);
vector<size_t> remaining;
for (size_t n = 0; n < size_t(directions.rows()); ++n)
if (n != indices[0])
remaining.push_back (n);
while (remaining.size()) {
ssize_t best = 0;
value_type best_E = std::numeric_limits<value_type>::max();
for (size_t n = 0; n < remaining.size(); ++n) {
value_type E = 0.0;
ssize_t a = remaining[n];
for (size_t i = 0; i < indices.size(); ++i) {
ssize_t b = indices[i];
E += 1.0 / (directions.row(a) - directions.row(b)).norm();
E += 1.0 / (directions.row(a) + directions.row(b)).norm();
}
if (E < best_E) {
best_E = E;
best = n;
}
}
indices.push_back (remaining[best]);
remaining.erase (remaining.begin()+best);
}
return indices;
}
value_type calc_cost (const Eigen::MatrixXd& directions, const vector<size_t>& order)
{
const size_t start = Math::SH::NforL (2);
if (directions.rows() <= start)
return value_type(0);
Eigen::MatrixXd subset (start, 3);
for (size_t i = 0; i != start; ++i)
subset.row(i) = directions.row(order[i]);
value_type cost = value_type(0);
for (size_t N = start+1; N < size_t(directions.rows()); ++N) {
// Don't include condition numbers where precisely the number of coefficients
// for that spherical harmonic degree are included, as these tend to
// be outliers
const size_t lmax = Math::SH::LforN (N-1);
subset.conservativeResize (N, 3);
subset.row(N-1) = directions.row(order[N-1]);
const value_type cond = DWI::condition_number_for_lmax (subset, lmax);
cost += cond;
}
return cost;
}
void run ()
{
auto directions = DWI::Directions::load_cartesian (argument[0]);
size_t last_candidate_first_volume = directions.rows();
if (directions.rows() <= Math::SH::NforL (2)) {
WARN ("Very few directions in input ("
+ str(directions.rows())
+ "); selection of first direction cannot be optimised"
+ " (first direction in input will be first direction in output)");
last_candidate_first_volume = 1;
}
value_type min_cost = std::numeric_limits<value_type>::infinity();
vector<size_t> best_order;
ProgressBar progress ("Determining best reordering", directions.rows());
for (size_t first_volume = 0; first_volume != last_candidate_first_volume; ++first_volume) {
const vector<size_t> order = optimise (directions, first_volume);
const value_type cost = calc_cost (directions, order);
if (cost < min_cost) {
min_cost = cost;
best_order = order;
}
++progress;
}
decltype(directions) output (directions.rows(), 3);
for (ssize_t n = 0; n < directions.rows(); ++n)
output.row(n) = directions.row (best_order[n]);
DWI::Directions::save (output, argument[1], get_options("cartesian").size());
}
<commit_msg>diroder: Fix compiler warning<commit_after>/* Copyright (c) 2008-2021 the MRtrix3 contributors.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Covered Software is provided under this License on an "as is"
* basis, without warranty of any kind, either expressed, implied, or
* statutory, including, without limitation, warranties that the
* Covered Software is free of defects, merchantable, fit for a
* particular purpose or non-infringing.
* See the Mozilla Public License v. 2.0 for more details.
*
* For more details, see http://www.mrtrix.org/.
*/
#include "command.h"
#include "progressbar.h"
#include "math/rng.h"
#include "math/SH.h"
#include "dwi/gradient.h"
#include "dwi/directions/file.h"
#include <random>
#include <functional>
using namespace MR;
using namespace App;
void usage ()
{
AUTHOR = "J-Donald Tournier (jdtournier@gmail.com)";
SYNOPSIS = "Reorder a set of directions to ensure near-uniformity upon truncation";
DESCRIPTION
+ "The intent of this command is to reorder a set of gradient directions such that "
"if a scan is terminated prematurely, at any point, the acquired directions will "
"still be close to optimally distributed on the half-sphere.";
ARGUMENTS
+ Argument ("input", "the input directions file").type_file_in()
+ Argument ("output", "the output directions file").type_file_out();
OPTIONS
+ Option ("cartesian", "Output the directions in Cartesian coordinates [x y z] instead of [az el].");
}
using value_type = double;
vector<size_t> optimise (const Eigen::MatrixXd& directions, const size_t first_volume)
{
vector<size_t> indices (1, first_volume);
vector<size_t> remaining;
for (size_t n = 0; n < size_t(directions.rows()); ++n)
if (n != indices[0])
remaining.push_back (n);
while (remaining.size()) {
ssize_t best = 0;
value_type best_E = std::numeric_limits<value_type>::max();
for (size_t n = 0; n < remaining.size(); ++n) {
value_type E = 0.0;
ssize_t a = remaining[n];
for (size_t i = 0; i < indices.size(); ++i) {
ssize_t b = indices[i];
E += 1.0 / (directions.row(a) - directions.row(b)).norm();
E += 1.0 / (directions.row(a) + directions.row(b)).norm();
}
if (E < best_E) {
best_E = E;
best = n;
}
}
indices.push_back (remaining[best]);
remaining.erase (remaining.begin()+best);
}
return indices;
}
value_type calc_cost (const Eigen::MatrixXd& directions, const vector<size_t>& order)
{
const size_t start = Math::SH::NforL (2);
if (size_t(directions.rows()) <= start)
return value_type(0);
Eigen::MatrixXd subset (start, 3);
for (size_t i = 0; i != start; ++i)
subset.row(i) = directions.row(order[i]);
value_type cost = value_type(0);
for (size_t N = start+1; N < size_t(directions.rows()); ++N) {
// Don't include condition numbers where precisely the number of coefficients
// for that spherical harmonic degree are included, as these tend to
// be outliers
const size_t lmax = Math::SH::LforN (N-1);
subset.conservativeResize (N, 3);
subset.row(N-1) = directions.row(order[N-1]);
const value_type cond = DWI::condition_number_for_lmax (subset, lmax);
cost += cond;
}
return cost;
}
void run ()
{
auto directions = DWI::Directions::load_cartesian (argument[0]);
size_t last_candidate_first_volume = directions.rows();
if (size_t(directions.rows()) <= Math::SH::NforL (2)) {
WARN ("Very few directions in input ("
+ str(directions.rows())
+ "); selection of first direction cannot be optimised"
+ " (first direction in input will be first direction in output)");
last_candidate_first_volume = 1;
}
value_type min_cost = std::numeric_limits<value_type>::infinity();
vector<size_t> best_order;
ProgressBar progress ("Determining best reordering", directions.rows());
for (size_t first_volume = 0; first_volume != last_candidate_first_volume; ++first_volume) {
const vector<size_t> order = optimise (directions, first_volume);
const value_type cost = calc_cost (directions, order);
if (cost < min_cost) {
min_cost = cost;
best_order = order;
}
++progress;
}
decltype(directions) output (directions.rows(), 3);
for (ssize_t n = 0; n < directions.rows(); ++n)
output.row(n) = directions.row (best_order[n]);
DWI::Directions::save (output, argument[1], get_options("cartesian").size());
}
<|endoftext|>
|
<commit_before>// ======================================================================== //
// Copyright 2009-2017 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. //
// ======================================================================== //
// own
#include "Importer.h"
// ospcommon
#include "ospcommon/FileName.h"
// tinyxml
#include "TinyXML2.h"
// std
#include <stdexcept>
namespace ospray {
namespace importer {
void importVolumeRAW(const FileName &fileName, Volume *volume);
void importVolumeRM(const FileName &fileName, Volume *volume);
void importVolume(const FileName &fileName, Volume *volume)
{
const std::string ext = fileName.ext();
if (ext == "raw" || ext == "gz") {
importVolumeRAW(fileName, volume);
} else if (ext == "bob") {
importVolumeRM(fileName, volume);
} else {
throw std::runtime_error("unknown volume format '"+ext+"'");
}
// post-checks
assert(volume->handle != nullptr);
assert(!volume->bounds.empty());
}
vec2i parseInt2(const tinyxml2::XMLNode *node)
{
vec2i v;
int rc = sscanf(node->ToElement()->GetText(),"%i %i",&v.x,&v.y);
(void)rc;
assert(rc == 2);
return v;
}
vec3i parseInt3(const tinyxml2::XMLNode *node)
{
vec3i v;
int rc = sscanf(node->ToElement()->GetText(),"%i %i %i",&v.x,&v.y,&v.z);
(void)rc;
assert(rc == 3);
return v;
}
float parseFloat1(const tinyxml2::XMLNode *node)
{
float v;
int rc = sscanf(node->ToElement()->GetText(),"%f",&v);
(void)rc;
assert(rc == 1);
return v;
}
vec2f parseFloat2(const tinyxml2::XMLNode *node)
{
vec2f v;
int rc = sscanf(node->ToElement()->GetText(),"%f %f",&v.x,&v.y);
(void)rc;
assert(rc == 2);
return v;
}
vec3f parseFloat3(const tinyxml2::XMLNode *node)
{
vec3f v;
int rc = sscanf(node->ToElement()->GetText(),"%f %f %f",&v.x,&v.y,&v.z);
(void)rc;
assert(rc == 3);
return v;
}
void importVolume(const FileName &orgFileName,
Group *group,
const tinyxml2::XMLNode *root)
{
auto dpFromEnv = getEnvVar<std::string>("OSPRAY_DATA_PARALLEL");
Volume *volume = new Volume;
if (dpFromEnv.first) {
// Create the OSPRay object.
osp::vec3i blockDims;
int rc = sscanf(dpFromEnv.second.c_str(), "%dx%dx%d",
&blockDims.x, &blockDims.y, &blockDims.z);
if (rc != 3) {
throw std::runtime_error("could not parse OSPRAY_DATA_PARALLEL "
"env-var. Must be of format <X>x<Y>x<>Z "
"(e.g., '4x4x4'");
}
volume->handle = ospNewVolume("data_distributed_volume");
if (volume->handle == nullptr) {
throw std::runtime_error("#loaders.ospObjectFile: could not create "
"volume ...");
}
ospSetVec3i(volume->handle, "num_dp_blocks", blockDims);
} else {
// Create the OSPRay object.
std::string volumeType = "block_bricked_volume";
auto volTypeFromEnv = getEnvVar<std::string>("OSPRAY_USE_VOLUME_TYPE");
if (volTypeFromEnv.first)
volumeType = volTypeFromEnv.second;
volume->handle = ospNewVolume(volumeType.c_str());
}
if (volume->handle == nullptr) {
throw std::runtime_error("#loaders.ospObjectFile: could not create "
"volume ...");
}
// Temporary storage for the file name attribute if specified.
const char *volumeFilename = nullptr;
// Iterate over object attributes.
for (const tinyxml2::XMLNode *node = root->FirstChild();
node;
node = node->NextSibling()) {
// Volume size in voxels per dimension.
if (!strcmp(node->ToElement()->Name(), "dimensions")) {
volume->dimensions = parseInt3(node);
continue;
}
// File containing a volume specification and / or voxel data.
if (!strcmp(node->ToElement()->Name(), "filename")) {
volumeFilename = node->ToElement()->GetText();
continue;
}
// Grid origin in world coordinates.
if (!strcmp(node->ToElement()->Name(), "gridOrigin")) {
volume->gridOrigin = parseFloat3(node);
ospSetVec3f(volume->handle, "gridOrigin", (osp::vec3f&)volume->gridOrigin);
continue;
}
// Grid spacing in each dimension in world coordinates.
if (!strcmp(node->ToElement()->Name(), "gridSpacing")) {
volume->gridSpacing = parseFloat3(node);
ospSetVec3f(volume->handle, "gridSpacing", (osp::vec3f&)volume->gridSpacing);
continue;
}
// Sampling rate for ray casting based renderers.
if (!strcmp(node->ToElement()->Name(), "samplingRate")) {
volume->samplingRate = parseFloat1(node);
ospSet1f(volume->handle, "samplingRate", volume->samplingRate);
continue;
}
// Volume scale factor.
if (!strcmp(node->ToElement()->Name(), "scaleFactor")) {
volume->scaleFactor = parseFloat3(node);
std::cout << "Got scaleFactor = " << volume->scaleFactor << std::endl;
ospSetVec3f(volume->handle, "scaleFactor", (osp::vec3f&)volume->scaleFactor);
continue;
}
// Subvolume offset from origin within the full volume.
if (!strcmp(node->ToElement()->Name(), "subvolumeOffsets")) {
volume->subVolumeOffsets = parseInt3(node);
continue;
}
// Subvolume dimensions within the full volume.
if (!strcmp(node->ToElement()->Name(), "subvolumeDimensions")) {
volume->subVolumeDimensions = parseInt3(node);
continue;
}
// Subvolume steps in each dimension; can be used to subsample.
if (!strcmp(node->ToElement()->Name(), "subvolumeSteps")) {
volume->subVolumeSteps = parseInt3(node);
continue;
}
// Voxel value range.
if (!strcmp(node->ToElement()->Name(), "voxelRange")) {
volume->voxelRange = parseFloat2(node);
continue;
}
// Voxel type string.
if (!strcmp(node->ToElement()->Name(), "voxelType")) {
volume->voxelType = node->ToElement()->GetText();
continue;
}
// Error check.
exitOnCondition(true, "unrecognized XML element type '" +
std::string(node->ToElement()->Name()) + "'");
}
// Load the contents of the volume file if specified.
if (volumeFilename != nullptr) {
// The volume file path is absolute.
if (volumeFilename[0] == '/')
importVolume(volumeFilename, volume);
else {
importVolume((orgFileName.path().str()
+ "/" + volumeFilename).c_str(), volume);
}
}
group->volume.push_back(volume);
}
void importTriangleMesh(Group *group, const tinyxml2::XMLNode *node)
{
throw std::runtime_error("importTriangleMesh: not yet implemented");
}
void importLight(Group *group, const tinyxml2::XMLNode *node)
{
throw std::runtime_error("importLight: not yet implemented");
}
void importObject(const FileName &orgFileName,
Group *group,
const tinyxml2::XMLNode *node)
{
// OSPRay light object.
if (!strcmp(node->ToElement()->Name(), "light"))
importLight(group,node);
// OSPRay triangle mesh object.
else if (!strcmp(node->ToElement()->Name(), "triangleMesh"))
importTriangleMesh(group,node);
// OSPRay volume object.
else if (!strcmp(node->ToElement()->Name(), "volume"))
importVolume(orgFileName,group,node);
// No other object types are currently supported.
else
exitOnCondition(true, "unrecognized XML element type '"
+ std::string(node->ToElement()->Name()) + "'");
}
void importOSP(const FileName &fileName, Group *existingGroupToAddTo)
{
// The XML document container.
tinyxml2::XMLDocument xml(true, tinyxml2::COLLAPSE_WHITESPACE);
// Read the XML object file.
exitOnCondition(xml.LoadFile(fileName.str().c_str()) != tinyxml2::XML_SUCCESS,
"unable to read object file '" + fileName.str() + "'");
Group *group = existingGroupToAddTo ? existingGroupToAddTo : new Group;
// Iterate over the object entries, skip the XML declaration and comments.
for (const tinyxml2::XMLNode *node = xml.FirstChild();
node;
node = node->NextSibling()) {
if (node->ToElement())
importObject(fileName,group,node);
}
// post-checks:
for (size_t i = 0; i < group->volume.size(); i++) {
assert(group->volume[i]->handle != nullptr);
assert(!group->volume[i]->bounds.empty());
}
}
}
}
<commit_msg>Works on mac<commit_after>// ======================================================================== //
// Copyright 2009-2017 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. //
// ======================================================================== //
// own
#include "Importer.h"
// ospcommon
#include "ospcommon/FileName.h"
// tinyxml
#include "TinyXML2.h"
// std
#include <stdexcept>
namespace ospray {
namespace importer {
void importVolumeRAW(const FileName &fileName, Volume *volume);
void importVolumeRM(const FileName &fileName, Volume *volume);
void importVolume(const FileName &fileName, Volume *volume)
{
const std::string ext = fileName.ext();
if (ext == "raw" || ext == "gz") {
importVolumeRAW(fileName, volume);
} else if (ext == "bob") {
importVolumeRM(fileName, volume);
} else {
throw std::runtime_error("unknown volume format '"+ext+"'");
}
// post-checks
assert(volume->handle != nullptr);
assert(!volume->bounds.empty());
}
vec2i parseInt2(const tinyxml2::XMLNode *node)
{
vec2i v;
int rc = sscanf(node->ToElement()->GetText(),"%i %i",&v.x,&v.y);
(void)rc;
assert(rc == 2);
return v;
}
vec3i parseInt3(const tinyxml2::XMLNode *node)
{
vec3i v;
int rc = sscanf(node->ToElement()->GetText(),"%i %i %i",&v.x,&v.y,&v.z);
(void)rc;
assert(rc == 3);
return v;
}
float parseFloat1(const tinyxml2::XMLNode *node)
{
float v;
int rc = sscanf(node->ToElement()->GetText(),"%f",&v);
(void)rc;
assert(rc == 1);
return v;
}
vec2f parseFloat2(const tinyxml2::XMLNode *node)
{
vec2f v;
int rc = sscanf(node->ToElement()->GetText(),"%f %f",&v.x,&v.y);
(void)rc;
assert(rc == 2);
return v;
}
vec3f parseFloat3(const tinyxml2::XMLNode *node)
{
vec3f v;
int rc = sscanf(node->ToElement()->GetText(),"%f %f %f",&v.x,&v.y,&v.z);
(void)rc;
assert(rc == 3);
return v;
}
void importVolume(const FileName &orgFileName,
Group *group,
const tinyxml2::XMLNode *root)
{
auto dpFromEnv = std::make_pair(false, std::string());//getEnvVar<std::string>("OSPRAY_DATA_PARALLEL");
Volume *volume = new Volume;
if (dpFromEnv.first) {
// Create the OSPRay object.
osp::vec3i blockDims;
int rc = sscanf(dpFromEnv.second.c_str(), "%dx%dx%d",
&blockDims.x, &blockDims.y, &blockDims.z);
if (rc != 3) {
throw std::runtime_error("could not parse OSPRAY_DATA_PARALLEL "
"env-var. Must be of format <X>x<Y>x<>Z "
"(e.g., '4x4x4'");
}
volume->handle = ospNewVolume("data_distributed_volume");
if (volume->handle == nullptr) {
throw std::runtime_error("#loaders.ospObjectFile: could not create "
"volume ...");
}
ospSetVec3i(volume->handle, "num_dp_blocks", blockDims);
} else {
// Create the OSPRay object.
std::string volumeType = "block_bricked_volume";
auto volTypeFromEnv = std::make_pair(false, std::string());//getEnvVar<std::string>("OSPRAY_USE_VOLUME_TYPE");
if (volTypeFromEnv.first)
volumeType = volTypeFromEnv.second;
volume->handle = ospNewVolume(volumeType.c_str());
}
if (volume->handle == nullptr) {
throw std::runtime_error("#loaders.ospObjectFile: could not create "
"volume ...");
}
// Temporary storage for the file name attribute if specified.
const char *volumeFilename = nullptr;
// Iterate over object attributes.
for (const tinyxml2::XMLNode *node = root->FirstChild();
node;
node = node->NextSibling()) {
// Volume size in voxels per dimension.
if (!strcmp(node->ToElement()->Name(), "dimensions")) {
volume->dimensions = parseInt3(node);
continue;
}
// File containing a volume specification and / or voxel data.
if (!strcmp(node->ToElement()->Name(), "filename")) {
volumeFilename = node->ToElement()->GetText();
continue;
}
// Grid origin in world coordinates.
if (!strcmp(node->ToElement()->Name(), "gridOrigin")) {
volume->gridOrigin = parseFloat3(node);
ospSetVec3f(volume->handle, "gridOrigin", (osp::vec3f&)volume->gridOrigin);
continue;
}
// Grid spacing in each dimension in world coordinates.
if (!strcmp(node->ToElement()->Name(), "gridSpacing")) {
volume->gridSpacing = parseFloat3(node);
ospSetVec3f(volume->handle, "gridSpacing", (osp::vec3f&)volume->gridSpacing);
continue;
}
// Sampling rate for ray casting based renderers.
if (!strcmp(node->ToElement()->Name(), "samplingRate")) {
volume->samplingRate = parseFloat1(node);
ospSet1f(volume->handle, "samplingRate", volume->samplingRate);
continue;
}
// Volume scale factor.
if (!strcmp(node->ToElement()->Name(), "scaleFactor")) {
volume->scaleFactor = parseFloat3(node);
std::cout << "Got scaleFactor = " << volume->scaleFactor << std::endl;
ospSetVec3f(volume->handle, "scaleFactor", (osp::vec3f&)volume->scaleFactor);
continue;
}
// Subvolume offset from origin within the full volume.
if (!strcmp(node->ToElement()->Name(), "subvolumeOffsets")) {
volume->subVolumeOffsets = parseInt3(node);
continue;
}
// Subvolume dimensions within the full volume.
if (!strcmp(node->ToElement()->Name(), "subvolumeDimensions")) {
volume->subVolumeDimensions = parseInt3(node);
continue;
}
// Subvolume steps in each dimension; can be used to subsample.
if (!strcmp(node->ToElement()->Name(), "subvolumeSteps")) {
volume->subVolumeSteps = parseInt3(node);
continue;
}
// Voxel value range.
if (!strcmp(node->ToElement()->Name(), "voxelRange")) {
volume->voxelRange = parseFloat2(node);
continue;
}
// Voxel type string.
if (!strcmp(node->ToElement()->Name(), "voxelType")) {
volume->voxelType = node->ToElement()->GetText();
continue;
}
// Error check.
exitOnCondition(true, "unrecognized XML element type '" +
std::string(node->ToElement()->Name()) + "'");
}
// Load the contents of the volume file if specified.
if (volumeFilename != nullptr) {
// The volume file path is absolute.
if (volumeFilename[0] == '/')
importVolume(volumeFilename, volume);
else {
importVolume((orgFileName.path()
+ "/" + volumeFilename).c_str(), volume);
}
}
group->volume.push_back(volume);
}
void importTriangleMesh(Group *group, const tinyxml2::XMLNode *node)
{
throw std::runtime_error("importTriangleMesh: not yet implemented");
}
void importLight(Group *group, const tinyxml2::XMLNode *node)
{
throw std::runtime_error("importLight: not yet implemented");
}
void importObject(const FileName &orgFileName,
Group *group,
const tinyxml2::XMLNode *node)
{
// OSPRay light object.
if (!strcmp(node->ToElement()->Name(), "light"))
importLight(group,node);
// OSPRay triangle mesh object.
else if (!strcmp(node->ToElement()->Name(), "triangleMesh"))
importTriangleMesh(group,node);
// OSPRay volume object.
else if (!strcmp(node->ToElement()->Name(), "volume"))
importVolume(orgFileName,group,node);
// No other object types are currently supported.
else
exitOnCondition(true, "unrecognized XML element type '"
+ std::string(node->ToElement()->Name()) + "'");
}
void importOSP(const FileName &fileName, Group *existingGroupToAddTo)
{
// The XML document container.
tinyxml2::XMLDocument xml(true, tinyxml2::COLLAPSE_WHITESPACE);
// Read the XML object file.
exitOnCondition(xml.LoadFile(fileName.str().c_str()) != tinyxml2::XML_SUCCESS,
"unable to read object file '" + fileName.str() + "'");
Group *group = existingGroupToAddTo ? existingGroupToAddTo : new Group;
// Iterate over the object entries, skip the XML declaration and comments.
for (const tinyxml2::XMLNode *node = xml.FirstChild();
node;
node = node->NextSibling()) {
if (node->ToElement())
importObject(fileName,group,node);
}
// post-checks:
for (size_t i = 0; i < group->volume.size(); i++) {
assert(group->volume[i]->handle != nullptr);
assert(!group->volume[i]->bounds.empty());
}
}
}
}
<|endoftext|>
|
<commit_before>#include <cassert>
#include <random>
#include "synthetic.hpp"
#include "network.hpp"
#include "tclap/ValueArg.h"
WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(InternalEvent)
WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(ExternalEvent)
inline std::string Node::lpName(const unsigned int lp_index) {
return std::string("Node_") + std::to_string(lp_index);
}
std::vector<std::shared_ptr<warped::Event> > Node::initializeLP() {
std::vector<std::shared_ptr<warped::Event> > events;
/* Register random number generator */
registerRNG<std::default_random_engine>(rng_);
for (unsigned int i = 0; i < num_nodes_; i++) {
unsigned int time = send_distribution_->nextTimeDelta(*rng_);
events.emplace_back(new InternalEvent {time});
}
return events;
}
std::vector<std::shared_ptr<warped::Event> > Node::receiveEvent(const warped::Event& event) {
std::vector<std::shared_ptr<warped::Event> > response_events;
assert (event.sender_name_ == event.receiverName());
#if 0
std::exponential_distribution<double> time_expo(1.0/mean_time_);
std::uniform_int_distribution<int> ext_node(0, adjacency_list_.size()-1);
/* Check if event received is a self/internal timer event */
if (event.sender_name_ == event.receiverName()) {
/* Restart the timer/internal event */
unsigned int time = (unsigned int)std::ceil(time_expo(*rng_));
response_events.emplace_back(new InternalEvent {time});
/* Send an external event to one of the nodes in its adjacency list */
auto id = (unsigned int) ext_node(*rng_);
response_events.emplace_back(
new ExternalEvent { adjacency_list_[id],
1,
time });
} else { /* Event received from other LPs/nodes */
}
#endif
return response_events;
}
int main(int argc, const char** argv) {
unsigned int num_nodes = 100000;
std::string network = "Watts-Strogatz,30,0.1";
std::string node_selection = "exponential,3.5";
std::string event_processing_time = "1000,1000";
std::string state_size = "100,100";
std::string event_send = "geometric,0.5,10";
TCLAP::ValueArg<unsigned int> num_nodes_arg("n", "num-nodes",
"Number of nodes", false, num_nodes, "unsigned int");
TCLAP::ValueArg<std::string> network_arg("t", "network-params",
"Network details - <type,param1,param2,...>", false, network, "string");
TCLAP::ValueArg<std::string> node_selection_arg("o", "node-selection-params",
"Node selection details - <distribution-type,<distribution-params>>",
false, node_selection, "string");
TCLAP::ValueArg<std::string> event_processing_time_arg("e", "event-processing-time-range",
"Event processing time (as floating-point calculation count) range - <min,max>",
false, event_processing_time, "string");
TCLAP::ValueArg<std::string> state_size_arg("s", "state-size-range",
"Size range (in bytes) for the LP state - <min,max>",
false, state_size, "string");
TCLAP::ValueArg<std::string> event_send_arg("p", "send-params",
"Event send details - <distribution-type,<distribution-params>,ceiling-value>",
"false", event_send, "string");
std::vector<TCLAP::Arg*> args = { &num_nodes_arg,
&network_arg,
&node_selection_arg,
&event_processing_time_arg,
&state_size_arg,
&event_send_arg
};
warped::Simulation synthetic_sim {"Synthetic Simulation", argc, argv, args};
num_nodes = num_nodes_arg.getValue();
network = network_arg.getValue();
node_selection = node_selection_arg.getValue();
event_processing_time = event_processing_time_arg.getValue();
state_size = state_size_arg.getValue();
event_send = event_send_arg.getValue();
std::vector<Node> lps;
std::vector<std::string> lp_names;
/* Create uniform distribution for event processing time */
std::string delimiter = ",";
size_t pos = event_processing_time.find(delimiter);
unsigned int min_processing_time =
(unsigned int) std::stoul(event_processing_time.substr(0, pos));
unsigned int max_processing_time =
(unsigned int) std::stoul(event_processing_time.substr(pos+1));
std::uniform_int_distribution<unsigned int>
event_processing_time_dist( min_processing_time, max_processing_time );
/* Create uniform distribution for the state size */
pos = state_size.find(delimiter);
unsigned int min_state_size = (unsigned int) std::stoul(state_size.substr(0, pos));
unsigned int max_state_size = (unsigned int) std::stoul(state_size.substr(pos+1));
std::uniform_int_distribution<unsigned int>
state_size_dist( min_state_size, max_state_size );
/* Create the LPs */
std::default_random_engine generator (num_nodes);
for (unsigned int i = 0; i < num_nodes; i++) {
auto name = Node::lpName(i);
lp_names.push_back(name);
lps.emplace_back( name,
num_nodes,
event_processing_time_dist(generator),
state_size_dist(generator),
i
);
}
std::vector<warped::LogicalProcess*> lp_pointers;
for (auto& lp : lps) {
lp_pointers.push_back(&lp);
}
/* Create the Network */
Network *ntwrk = nullptr;
pos = network.find(delimiter);
std::string type = network.substr(0, pos);
network.erase(0, pos + delimiter.length());
if (type == "Watts-Strogatz") { // If the choice is Watts-Strogatz
pos = network.find(delimiter);
std::string token = network.substr(0, pos);
unsigned int k = (unsigned int) std::stoul(token);
network.erase(0, pos + delimiter.length());
double beta = std::stod(network);
ntwrk = new WattsStrogatz(lp_names, k, beta);
} else if (type == "Barabasi-Albert") { // If the choice is Barabasi-Albert
pos = network.find(delimiter);
std::string token = network.substr(0, pos);
unsigned int m = (unsigned int) std::stoul(token);
network.erase(0, pos + delimiter.length());
double a = std::stod(network);
ntwrk = new BarabasiAlbert(lp_names, m, a);
} else { // Invalid choice
std::cerr << "Invalid choice of network." << std::endl;
abort();
}
/* Parse the event send distribution type and parameters */
pos = event_send.find(delimiter);
std::string distribution_type = event_send.substr(0, pos);
event_send.erase(0, pos + delimiter.length());
for (auto& lp : lps) {
/* Create the send time distributions */
if (distribution_type == "geometric") {
lp.send_distribution_ = new Geometric(event_send);
} else if (distribution_type == "exponential") {
lp.send_distribution_ = new Exponential(event_send);
} else if (distribution_type == "binomial") {
lp.send_distribution_ = new Binomial(event_send);
} else {
std::cerr << "Invalid choice of event send distribution." << std::endl;
abort();
}
/* Fetch the adjacency list for each node */
lp.adjacency_list_ = ntwrk->adjacencyList(lp.name_);
assert(lp.adjacency_list_.size());
}
delete ntwrk;
/* Parse the node selection distribution type and parameters */
pos = node_selection.find(delimiter);
distribution_type = node_selection.substr(0, pos);
node_selection.erase(0, pos + delimiter.length());
for (auto& lp : lps) {
node_selection += "," + lp.adjacency_list_.size();
/* Create the node selection distributions */
if (distribution_type == "geometric") {
lp.node_sel_distribution_ = new Geometric(node_selection);
} else if (distribution_type == "exponential") {
lp.node_sel_distribution_ = new Exponential(node_selection);
} else if (distribution_type == "binomial") {
lp.node_sel_distribution_ = new Binomial(node_selection);
} else {
std::cerr << "Invalid choice of node select distribution." << std::endl;
abort();
}
}
/* Simulate the synthetic model */
synthetic_sim.simulate(lp_pointers);
return 0;
}
<commit_msg>completed receiveEvent()<commit_after>#include <cassert>
#include <random>
#include "synthetic.hpp"
#include "network.hpp"
#include "tclap/ValueArg.h"
WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(InternalEvent)
WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(ExternalEvent)
inline std::string Node::lpName(const unsigned int lp_index) {
return std::string("Node_") + std::to_string(lp_index);
}
std::vector<std::shared_ptr<warped::Event> > Node::initializeLP() {
std::vector<std::shared_ptr<warped::Event> > events;
/* Register random number generator */
registerRNG<std::default_random_engine>(rng_);
for (unsigned int i = 0; i < num_nodes_; i++) {
unsigned int time = send_distribution_->nextTimeDelta(*rng_);
events.emplace_back(new InternalEvent {time});
}
return events;
}
std::vector<std::shared_ptr<warped::Event> > Node::receiveEvent(const warped::Event& event) {
std::vector<std::shared_ptr<warped::Event> > response_events;
/* Register random number generator */
registerRNG<std::default_random_engine>(rng_);
/* Check if event received is a self/internal timer event */
if (event.sender_name_ == event.receiverName()) {
/* Restart the processing_timer/internal event */
unsigned int processing_time = send_distribution_->nextTimeDelta(*rng_);
response_events.emplace_back(new InternalEvent {processing_time});
/* Send an external event to one of the nodes in its adjacency list */
/* selecting node using distribution */
auto id = (unsigned int) node_sel_distribution_->nextTimeDelta(*rng_);
/* Restart the timer/external event */
unsigned int ts = send_distribution_->nextTimeDelta(*rng_);
response_events.emplace_back(
new ExternalEvent { adjacency_list_[id],
processing_time,
ts });
} else { /* Event received from other LPs/nodes */
}
return response_events;
}
int main(int argc, const char** argv) {
unsigned int num_nodes = 100000;
std::string network = "Watts-Strogatz,30,0.1";
std::string node_selection = "exponential,3.5";
std::string event_processing_time = "1000,1000";
std::string state_size = "100,100";
std::string event_send = "geometric,0.5,10";
TCLAP::ValueArg<unsigned int> num_nodes_arg("n", "num-nodes",
"Number of nodes", false, num_nodes, "unsigned int");
TCLAP::ValueArg<std::string> network_arg("t", "network-params",
"Network details - <type,param1,param2,...>", false, network, "string");
TCLAP::ValueArg<std::string> node_selection_arg("o", "node-selection-params",
"Node selection details - <distribution-type,<distribution-params>>",
false, node_selection, "string");
TCLAP::ValueArg<std::string> event_processing_time_arg("e", "event-processing-time-range",
"Event processing time (as floating-point calculation count) range - <min,max>",
false, event_processing_time, "string");
TCLAP::ValueArg<std::string> state_size_arg("s", "state-size-range",
"Size range (in bytes) for the LP state - <min,max>",
false, state_size, "string");
TCLAP::ValueArg<std::string> event_send_arg("p", "send-params",
"Event send details - <distribution-type,<distribution-params>,ceiling-value>",
"false", event_send, "string");
std::vector<TCLAP::Arg*> args = { &num_nodes_arg,
&network_arg,
&node_selection_arg,
&event_processing_time_arg,
&state_size_arg,
&event_send_arg
};
warped::Simulation synthetic_sim {"Synthetic Simulation", argc, argv, args};
num_nodes = num_nodes_arg.getValue();
network = network_arg.getValue();
node_selection = node_selection_arg.getValue();
event_processing_time = event_processing_time_arg.getValue();
state_size = state_size_arg.getValue();
event_send = event_send_arg.getValue();
std::vector<Node> lps;
std::vector<std::string> lp_names;
/* Create uniform distribution for event processing time */
std::string delimiter = ",";
size_t pos = event_processing_time.find(delimiter);
unsigned int min_processing_time =
(unsigned int) std::stoul(event_processing_time.substr(0, pos));
unsigned int max_processing_time =
(unsigned int) std::stoul(event_processing_time.substr(pos+1));
std::uniform_int_distribution<unsigned int>
event_processing_time_dist( min_processing_time, max_processing_time );
/* Create uniform distribution for the state size */
pos = state_size.find(delimiter);
unsigned int min_state_size = (unsigned int) std::stoul(state_size.substr(0, pos));
unsigned int max_state_size = (unsigned int) std::stoul(state_size.substr(pos+1));
std::uniform_int_distribution<unsigned int>
state_size_dist( min_state_size, max_state_size );
/* Create the LPs */
std::default_random_engine generator (num_nodes);
for (unsigned int i = 0; i < num_nodes; i++) {
auto name = Node::lpName(i);
lp_names.push_back(name);
lps.emplace_back( name,
num_nodes,
event_processing_time_dist(generator),
state_size_dist(generator),
i
);
}
std::vector<warped::LogicalProcess*> lp_pointers;
for (auto& lp : lps) {
lp_pointers.push_back(&lp);
}
/* Create the Network */
Network *ntwrk = nullptr;
pos = network.find(delimiter);
std::string type = network.substr(0, pos);
network.erase(0, pos + delimiter.length());
if (type == "Watts-Strogatz") { // If the choice is Watts-Strogatz
pos = network.find(delimiter);
std::string token = network.substr(0, pos);
unsigned int k = (unsigned int) std::stoul(token);
network.erase(0, pos + delimiter.length());
double beta = std::stod(network);
ntwrk = new WattsStrogatz(lp_names, k, beta);
} else if (type == "Barabasi-Albert") { // If the choice is Barabasi-Albert
pos = network.find(delimiter);
std::string token = network.substr(0, pos);
unsigned int m = (unsigned int) std::stoul(token);
network.erase(0, pos + delimiter.length());
double a = std::stod(network);
ntwrk = new BarabasiAlbert(lp_names, m, a);
} else { // Invalid choice
std::cerr << "Invalid choice of network." << std::endl;
abort();
}
/* Parse the event send distribution type and parameters */
pos = event_send.find(delimiter);
std::string distribution_type = event_send.substr(0, pos);
event_send.erase(0, pos + delimiter.length());
for (auto& lp : lps) {
/* Create the send time distributions */
if (distribution_type == "geometric") {
lp.send_distribution_ = new Geometric(event_send);
} else if (distribution_type == "exponential") {
lp.send_distribution_ = new Exponential(event_send);
} else if (distribution_type == "binomial") {
lp.send_distribution_ = new Binomial(event_send);
} else {
std::cerr << "Invalid choice of event send distribution." << std::endl;
abort();
}
/* Fetch the adjacency list for each node */
lp.adjacency_list_ = ntwrk->adjacencyList(lp.name_);
assert(lp.adjacency_list_.size());
}
delete ntwrk;
/* Parse the node selection distribution type and parameters */
pos = node_selection.find(delimiter);
distribution_type = node_selection.substr(0, pos);
node_selection.erase(0, pos + delimiter.length());
for (auto& lp : lps) {
node_selection += "," + lp.adjacency_list_.size();
/* Create the node selection distributions */
if (distribution_type == "geometric") {
lp.node_sel_distribution_ = new Geometric(node_selection);
} else if (distribution_type == "exponential") {
lp.node_sel_distribution_ = new Exponential(node_selection);
} else if (distribution_type == "binomial") {
lp.node_sel_distribution_ = new Binomial(node_selection);
} else {
std::cerr << "Invalid choice of node select distribution." << std::endl;
abort();
}
}
/* Simulate the synthetic model */
synthetic_sim.simulate(lp_pointers);
return 0;
}
<|endoftext|>
|
<commit_before>#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <vector>
#include <stdexcept>
#include <cassert>
#include <ctime>
#include <omp.h>
void readpgm( const std::string &fn,
unsigned char* &data,
int &width,
int &height ) {
FILE* stream = 0;
stream = fopen(fn.c_str(),"r");
if ( !stream ) {
std::cerr << " Failed to read pgm." << std::endl;
exit(-1);
}
int bsize;
int read = fscanf(stream,"P5\n%d %d\n%d%*[\n]",&width,&height,&bsize);
if ( read < 3 ) {
std::cerr << " Failed to read pgm header." << std::endl;
exit(-1);
}
data = new unsigned char[width*height];
read = fread(data,1,width*height,stream);
if ( read != width*height ) {
std::cerr << " Failed to read pgm data." << std::endl;
std::cerr << " Read " << read << " expected " << width*height
<< "." << std::endl;
exit(-1);
}
fclose(stream);
}
void writepgm( const std::string &fn,
unsigned char* &data,
int &width,
int &height ) {
FILE* stream = 0;
stream = fopen(fn.c_str(),"w");
if ( !stream ) {
std::cerr << " Failed to write pgm." << std::endl;
exit(-1);
}
int wrote = fprintf(stream,"P5\n%d %d\n%d\n",width,height,255);
if ( wrote < 3 ) {
std::cerr << " Failed to write pgm header." << std::endl;
exit(-1);
}
wrote = fwrite(data,1,width*height,stream);
if ( wrote != width*height ) {
std::cerr << " Failed to write pgm data." << std::endl;
std::cerr << " Wrote " << wrote << " expected " << width*height
<< "." << std::endl;
exit(-1);
}
fclose(stream);
}
typedef struct _im {
unsigned char *data;
int width, height;
} im_t;
inline double smoothing_term( int *displut, unsigned char *disp, int width, int
height, int y, int x, int thisdisp, double p1, double p2 ) {
if ( y < 0 || y >= height || x < 0 || x >= width ) {
return 0; /* TODO: Is this the correct behaviour? */
}
double smoothterm = 0;
int absdisp = std::abs(displut[disp[y*width+x]] - thisdisp);
if ( absdisp == 0 ) {
smoothterm = 0;
} else if ( absdisp == 1 ) {
smoothterm = p1;
} else {
smoothterm = p2;
}
return smoothterm;
}
inline int sample_distribution( int n, double *prob, double norm ) {
double unirand = (double) std::rand() / (double) RAND_MAX;
double cumsum = 0;
double invnorm = 1/norm;
int reti = -1;
for ( int i = 0; i < n; ++i ) {
cumsum += prob[i] * invnorm;
if ( unirand <= cumsum ) { /* This must eventually be true of any prob.
dist. */
reti = i;
break;
}
}
assert( reti >= 0 );
return reti;
}
double calculate_energy( int ndisp,
int mindisp,
double p1,
double p2,
double temperature,
int width, /* Image width */
int height, /* Image width */
unsigned char *ref,
unsigned char *match,
unsigned char *disp /* Disparity */) {
int* displut = new int[ndisp];
for ( int idisp = 0; idisp < ndisp; ++idisp ) {
displut[idisp] = idisp + mindisp;
}
const double invtemperature = 1/temperature;
double energy = 0;
for ( int irow = 0; irow < height; ++irow ) {
for ( int icol = 0; icol < width; ++icol ) {
int refidx = irow * width + icol;
int thisdisp = disp[irow*width + icol];
int matchx = icol + thisdisp;
if ( matchx < 0 || matchx >= width ) {
continue;
}
int matchidx = irow*width + matchx;
double dataterm = std::abs((int)(ref[refidx]) - (int)(match[matchidx])) * invtemperature ;
double smoothterm = 0;
smoothterm += smoothing_term(displut,disp,width,height,irow+1,icol,thisdisp,p1,p2);
smoothterm += smoothing_term(displut,disp,width,height,irow,icol+1,thisdisp,p1,p2);
energy += dataterm + smoothterm;
}
}
delete[] displut;
return energy;
}
void block_gibbs_iter( bool smooth,
int partition, /* 0 or 1 */
int ndisp,
int mindisp,
double p1,
double p2,
double temperature,
int width, /* Image width */
int height, /* Image width */
unsigned char *ref,
unsigned char *match,
unsigned char *disp /* Disparity */) {
int* displut = new int[ndisp];
for ( int idisp = 0; idisp < ndisp; ++idisp ) {
displut[idisp] = idisp + mindisp;
}
const double invtemperature = 1/temperature;
int nthread = 1;
#pragma omp parallel
{
nthread = omp_get_num_threads();
}
double **probs = new double*[nthread];
for ( int i = 0; i < nthread; ++i ){
probs[i] = new double[ndisp];
}
#pragma omp parallel for
for ( int irow = 0; irow < height; ++irow ) {
int omptid = omp_get_thread_num();
double* prob = probs[omptid];
int shift = (partition + irow) % 2; /* 0 or 1 aternating between rows */
for ( int icol = shift; icol < width; icol += 2 ) {
int refidx = irow * width + icol; /* Every second element */
//Need to compute the energy for every possible disparity:
for ( int idisp = 0; idisp < ndisp; ++idisp ) {
int thisdisp = displut[idisp];
int matchx = icol + thisdisp;
if ( matchx < 0 || matchx >= width ) {
prob[idisp] = -1;
continue;
}
int matchidx = irow*width + matchx;
double dataterm = std::abs((int)(ref[refidx]) - (int)(match[matchidx])) * invtemperature;
//Smoothing term of the four neighbours.
double smoothterm = 0;
if ( smooth ) {
smoothterm += smoothing_term(displut,disp,width,height,irow+1,icol,thisdisp,p1,p2);
smoothterm += smoothing_term(displut,disp,width,height,irow-1,icol,thisdisp,p1,p2);
smoothterm += smoothing_term(displut,disp,width,height,irow,icol+1,thisdisp,p1,p2);
smoothterm += smoothing_term(displut,disp,width,height,irow,icol-1,thisdisp,p1,p2);
}
prob[idisp] = dataterm + smoothterm;
}
double partitionfunc = 0;
for ( int idisp = 0; idisp < ndisp; ++idisp ) {
if ( prob[idisp] >= 0 ) {
prob[idisp] = std::exp( - (prob[idisp]) );
partitionfunc += prob[idisp];
} else {
prob[idisp] = 0;
}
}
assert ( partitionfunc > 0 ); /* There must be some disparity with non-zero prob.*/
disp[ refidx ] = sample_distribution(ndisp,prob,partitionfunc);
}
}
delete[] displut;
for ( int i = 0; i < nthread; ++i ) {
delete[] probs[i];
}
delete[] probs;
}
void block_gibbs( int niter,
int ndisp,
int mindisp,
double _p1,
double _p2,
double temperature,
im_t &im1,
im_t &im2,
im_t &disp) {
if ( !(im1.width == im2.width && im1.height == im2.height ) ) {
std::cerr << " Images are not same dimensions." << std::endl;
exit(-1);
}
int width = im1.width;
int height = im1.height;
double p1,p2;
p1 = _p1 / temperature;
p2 = _p2 / temperature;
unsigned char *ref = im1.data;
unsigned char *match = im2.data;
unsigned char *out = disp.data;
for ( int iter = 0; iter < niter;
++iter ) {
for ( int k = 0; k < 2; ++k ) {
int partition = k;
block_gibbs_iter( true, partition, ndisp, mindisp, p1, p2, temperature, width,
height, ref, match, out);
}
double energy = calculate_energy( ndisp, mindisp, p1, p2, temperature, width,
height, ref, match, out );
writepgm("disp_inprogress.pgm",
disp.data,
disp.width,
disp.height);
std::cout << " done block gibbs iter " << iter+1 << " of " <<
niter << " energy: " << energy << std::endl;
}
}
int main( int argc, char *argv[] ) {
std::srand(time(NULL));
im_t im1, im2, disp;
std::cout << " Reading im1 " << std::endl;
readpgm("cones_left.pgm",
im1.data,
im1.width,
im1.height);
std::cout << " Reading im2 " << std::endl;
readpgm("cones_right.pgm",
im2.data,
im2.width,
im2.height);
disp.width = im1.width;
disp.height = im1.height;
disp.data = new unsigned char[disp.width*disp.height];
std::fill(disp.data,disp.data+disp.width*disp.height,0);
int niter1 = 0;
int ndisp = 128;
int mindisp = -(ndisp-1);
double temperature = 10.; /* Temperature is unfortunately critical to
methods based on block gibbs sampling. Higher
temperature induces more variability and
possibly non convergence, lower temperatures
cause numeric instabilities as well as poor
solutions that refuse to shift from their
locally optimal solution. */
std::cout << " ndisp: " << ndisp << std::endl;
std::cout << " mindisp: " << mindisp << std::endl;
std::cout << " temperature: " << temperature << std::endl;
double p1, p2; /* The model that is minimized uses the same p1, p2
penalties as SGM and countless other stereo algorithms.
*/
int niter;
std::cout << " calculating prior: " << std::endl;
p1 = 0;
p2 = 0;
niter = 10;
block_gibbs(niter,ndisp,mindisp,p1,p2,temperature,im1,im2,disp);
std::cout << " done calculating prior " << std::endl;
std::cout << " calculating posterior: " << std::endl;
p1 = 5.;
p2 = 50.;
niter = 10000;
block_gibbs(niter,ndisp,mindisp,p1,p2,temperature,im1,im2,disp);
std::cout << " done calculating posterior " << std::endl;
writepgm("disp.pgm",
disp.data,
disp.width,
disp.height);
delete[] im1.data;
delete[] im2.data;
delete[] disp.data;
return 0;
}
<commit_msg>Gibbs stereo working, but can be tweaked a lot more.<commit_after>#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <vector>
#include <stdexcept>
#include <cassert>
#include <ctime>
#include <omp.h>
#include <limits>
void readpgm( const std::string &fn,
unsigned char* &data,
int &width,
int &height ) {
FILE* stream = 0;
stream = fopen(fn.c_str(),"r");
if ( !stream ) {
std::cerr << " Failed to read pgm." << std::endl;
exit(-1);
}
int bsize;
int read = fscanf(stream,"P5\n%d %d\n%d%*[\n]",&width,&height,&bsize);
if ( read < 3 ) {
std::cerr << " Failed to read pgm header." << std::endl;
exit(-1);
}
data = new unsigned char[width*height];
read = fread(data,1,width*height,stream);
if ( read != width*height ) {
std::cerr << " Failed to read pgm data." << std::endl;
std::cerr << " Read " << read << " expected " << width*height
<< "." << std::endl;
exit(-1);
}
fclose(stream);
}
void writepgm( const std::string &fn,
unsigned char* &data,
int &width,
int &height ) {
FILE* stream = 0;
stream = fopen(fn.c_str(),"w");
if ( !stream ) {
std::cerr << " Failed to write pgm." << std::endl;
exit(-1);
}
int wrote = fprintf(stream,"P5\n%d %d\n%d\n",width,height,255);
if ( wrote < 3 ) {
std::cerr << " Failed to write pgm header." << std::endl;
exit(-1);
}
wrote = fwrite(data,1,width*height,stream);
if ( wrote != width*height ) {
std::cerr << " Failed to write pgm data." << std::endl;
std::cerr << " Wrote " << wrote << " expected " << width*height
<< "." << std::endl;
exit(-1);
}
fclose(stream);
}
typedef struct _im {
unsigned char *data;
int width, height;
} im_t;
inline double smoothing_term( int *displut, unsigned char *disp, int width, int
height, int y, int x, int thisdisp, double p1, double p2 ) {
if ( y < 0 || y >= height || x < 0 || x >= width ) {
return 0; /* TODO: Is this the correct behaviour? */
}
double smoothterm = 0;
int absdisp = std::abs(displut[disp[y*width+x]] - thisdisp);
if ( absdisp == 0 ) {
smoothterm = 0;
} else if ( absdisp == 1 ) {
smoothterm = p1;
} else {
smoothterm = p2;
}
return smoothterm;
}
inline int sample_distribution( int n, double *prob, double norm ) {
double unirand = (double) std::rand() / (double) RAND_MAX;
double cumsum = 0;
double invnorm = 1/norm;
int reti = -1;
for ( int i = 0; i < n; ++i ) {
cumsum += prob[i] * invnorm;
if ( unirand <= cumsum ) { /* This must eventually be true of any prob.
dist. */
reti = i;
break;
}
}
if ( reti < 0 ){ /* This seems to happen only in the case when the
comparison above fails which is extremely unlikely. */
printf(" ****warning corner case in sampling detected:\n"
" cumsum=%g\n unirand=%g\n", cumsum, unirand);
reti = n-1; /* It almost always seems to be the case that unirand == 1
&& cumsum == 1 but it is a precision error that fails
the comparison above. */
}
assert( reti >= 0 );
return reti;
}
double calculate_energy( int ndisp,
int mindisp,
double p1,
double p2,
double temperature,
int width, /* Image width */
int height, /* Image width */
unsigned char *dataterms,
unsigned char *ref,
unsigned char *match,
unsigned char *disp /* Disparity */) {
int* displut = new int[ndisp];
for ( int idisp = 0; idisp < ndisp; ++idisp ) {
displut[idisp] = idisp + mindisp;
}
const double invtemperature = 1/temperature;
double energy = 0;
for ( int irow = 0; irow < height; ++irow ) {
for ( int icol = 0; icol < width; ++icol ) {
int refidx = irow * width + icol;
int idisp = disp[irow*width + icol];
int thisdisp = displut[idisp];
int matchx = icol + thisdisp;
if ( matchx < 0 || matchx >= width ) {
continue;
}
int matchidx = irow*width + matchx;
double dataterm = dataterms[(irow*width+icol)*ndisp + idisp] * invtemperature;
double smoothterm = 0;
smoothterm += smoothing_term(displut,disp,width,height,irow+1,icol,thisdisp,p1,p2);
smoothterm += smoothing_term(displut,disp,width,height,irow,icol+1,thisdisp,p1,p2);
energy += dataterm + smoothterm;
}
}
delete[] displut;
return energy;
}
void block_gibbs_iter( bool smooth,
int partition, /* 0 or 1 */
int ndisp,
int mindisp,
double p1,
double p2,
double temperature,
int width, /* Image width */
int height, /* Image width */
unsigned char *dataterms,
unsigned char *ref,
unsigned char *match,
unsigned char *disp /* Disparity */) {
int* displut = new int[ndisp];
for ( int idisp = 0; idisp < ndisp; ++idisp ) {
displut[idisp] = idisp + mindisp;
}
const double invtemperature = 1/temperature;
int nthread = 1;
#pragma omp parallel
{
nthread = omp_get_num_threads();
}
double **probs = new double*[nthread];
for ( int i = 0; i < nthread; ++i ){
probs[i] = new double[ndisp];
}
#pragma omp parallel for
for ( int irow = 0; irow < height; ++irow ) {
int omptid = omp_get_thread_num();
double* prob = probs[omptid];
int shift = (partition + irow) % 2; /* 0 or 1 aternating between rows */
for ( int icol = shift; icol < width; icol += 2 ) {
int refidx = irow * width + icol; /* Every second element */
//Need to compute the energy for every possible disparity:
for ( int idisp = 0; idisp < ndisp; ++idisp ) {
int thisdisp = displut[idisp];
int matchx = icol + thisdisp;
if ( matchx < 0 || matchx >= width ) {
prob[idisp] = -1;
continue;
}
int matchidx = irow*width + matchx;
double dataterm = dataterms[(irow*width+icol)*ndisp + idisp] * invtemperature;
//Smoothing term of the four neighbours.
double smoothterm = 0;
if ( smooth ) {
smoothterm += smoothing_term(displut,disp,width,height,irow+1,icol,thisdisp,p1,p2);
smoothterm += smoothing_term(displut,disp,width,height,irow-1,icol,thisdisp,p1,p2);
smoothterm += smoothing_term(displut,disp,width,height,irow,icol+1,thisdisp,p1,p2);
smoothterm += smoothing_term(displut,disp,width,height,irow,icol-1,thisdisp,p1,p2);
}
prob[idisp] = dataterm + smoothterm;
}
double partitionfunc = 0;
for ( int idisp = 0; idisp < ndisp; ++idisp ) {
if ( prob[idisp] >= 0 ) {
prob[idisp] = std::exp( - (prob[idisp]) );
partitionfunc += prob[idisp];
} else {
prob[idisp] = 0;
}
}
assert ( partitionfunc > 0 ); /* There must be some disparity with non-zero prob.*/
disp[ refidx ] = sample_distribution(ndisp,prob,partitionfunc);
}
}
delete[] displut;
for ( int i = 0; i < nthread; ++i ) {
delete[] probs[i];
}
delete[] probs;
}
void block_gibbs( int niter,
int ndisp,
int mindisp,
double _p1,
double _p2,
double temperature,
unsigned char *dataterms,
im_t &im1,
im_t &im2,
im_t &disp) {
if ( !(im1.width == im2.width && im1.height == im2.height ) ) {
std::cerr << " Images are not same dimensions." << std::endl;
exit(-1);
}
int width = im1.width;
int height = im1.height;
double p1,p2;
p1 = _p1 / temperature;
p2 = _p2 / temperature;
unsigned char *ref = im1.data;
unsigned char *match = im2.data;
unsigned char *out = disp.data;
for ( int iter = 0; iter < niter;
++iter ) {
for ( int k = 0; k < 2; ++k ) {
int partition = k;
block_gibbs_iter( true, partition, ndisp, mindisp, p1, p2, temperature, width,
height, dataterms, ref, match, out);
}
double energy = calculate_energy( ndisp, mindisp, p1, p2, temperature, width,
height, dataterms, ref, match, out );
if ( iter % 2 == 0 ) {
writepgm("disp_inprogress.pgm",
disp.data,
disp.width,
disp.height);
}
std::cout << " done block gibbs iter " << iter+1 << " of " <<
niter << " energy: " << energy << std::endl;
}
}
void calculate_dataterms( int ndisp,
int mindisp,
int rady,
int radx,
im_t &im1,
im_t &im2,
unsigned char *dataterms ) {
if ( !(im1.width == im2.width && im1.height == im2.height ) ) {
std::cerr << " Images are not same dimensions." << std::endl;
exit(-1);
}
int width = im1.width;
int height = im1.height;
unsigned char *ref = im1.data;
unsigned char *match = im2.data;
int* displut = new int[ndisp];
for ( int idisp = 0; idisp < ndisp; ++idisp ) {
displut[idisp] = idisp + mindisp;
}
#pragma omp parallel for
for ( int irow = 0; irow < height; ++irow ) {
int rsizey = 2*rady+1;
int rsizex = 2*radx+1;
double *refpx = new double[rsizey*rsizex];
double *matchpx = new double[rsizey*rsizex];
for ( int icol = 0; icol < width; ++icol ) {
int refidx = irow * width + icol;
for ( int idisp = 0; idisp < ndisp; ++idisp ) {
int thisdisp = displut[idisp];
int matchx = icol + thisdisp;
if ( matchx < 0 || matchx >= width ) {
continue;
}
int matchidx = irow*width + matchx;
refpx[0] = ref[refidx];
matchpx[0] = match[matchidx];
double refaggrterm = refpx[0];
double matchaggrterm = matchpx[0];
int countfound = 1;
for ( int dy = -rady; dy <= rady; ++dy ) {
for ( int dx = -radx; dx <= radx; ++dx ) {
if ( dx == 0 && dy == 0 ) {
continue;
}
int x0, y0, x1, y1;
y0 = irow + dy;
x0 = matchx + dx;
y1 = y0;
x1 = icol + dx;
if ( x0 < 0 || x0 >= width || x1 < 0 || x1 >= width ||
y0 < 0 || y0 >= height ) {
continue;
}
refpx[countfound] = ref[y1*width+x1];
matchpx[countfound] = match[y0*width+x0];
refaggrterm += refpx[countfound];
matchaggrterm += matchpx[countfound];
countfound++;
}
}
//Compute means & std
double refmean = refaggrterm / countfound;
double matchmean = matchaggrterm / countfound;
double refstd = 0;
double matchstd = 0;
for ( int ipx = 0; ipx < countfound; ++ipx ) {
double t;
t = (refpx[ipx] - refmean );
refstd += t*t;
t = (matchpx[ipx] - matchmean );
matchstd += t*t;
}
refstd = std::sqrt(refstd);
matchstd = std::sqrt(matchstd);
int stdthresh = 0;
double norm = 1. / refstd / matchstd;
double ncc = 0;
for ( int ipx = 0; ipx < countfound; ++ipx ) {
ncc += (refpx[ipx] - refmean) * (matchpx[ipx] - matchmean ) * norm;
}
if ( matchstd > stdthresh && refstd > stdthresh ) {
if ( !( ncc <= 1+1e-6 && ncc >= -1-1e-6) ) {
std::cout << " countfound: " << countfound << std::endl;
std::cout << " ncc: " << ncc << std::endl;
printf("nccp: %lf\n",ncc);
std::cout << " refstd: " << refstd << std::endl;
std::cout << " matchstd: " << matchstd << std::endl;
std::cout << " refmean: " << refmean << std::endl;
std::cout << " matchmean: " << matchmean << std::endl;
std::cout << " refpx: ";
for ( int ipx = 0; ipx < countfound; ++ipx ) {
std::cout << refpx[ipx] << ", ";
}
std::cout << std::endl;
std::cout << " matchpx: ";
for ( int ipx = 0; ipx < countfound; ++ipx ) {
std::cout << matchpx[ipx] << ", ";
}
std::cout << std::endl;
}
assert( ncc <= 1.+1e-6 && ncc >= -1.-1e-6);
double output = (1-ncc) * 128;
output = output < 0 ? 0 : output > 255 ? 255 : output;
dataterms[ (irow*width + icol)*ndisp + idisp ] = output;
} else {
dataterms[ (irow*width + icol)*ndisp + idisp ] = 255;
}
}
}
delete[] refpx;
delete[] matchpx;
}
delete[] displut;
}
int main( int argc, char *argv[] ) {
std::srand(time(NULL));
im_t im1, im2, disp;
std::cout << " Reading im1 " << std::endl;
readpgm("cones_left.pgm",
im1.data,
im1.width,
im1.height);
std::cout << " Reading im2 " << std::endl;
readpgm("cones_right.pgm",
im2.data,
im2.width,
im2.height);
disp.width = im1.width;
disp.height = im1.height;
disp.data = new unsigned char[disp.width*disp.height];
bool usecheckpoint = false;
std::string checkpointfile = "";
if ( usecheckpoint ) {
readpgm(checkpointfile,
disp.data,
disp.width,
disp.height);
} else {
std::fill(disp.data,disp.data+disp.width*disp.height,0);
}
int ndisp = 128;
int mindisp = -(ndisp-1);
double temperature; /* Temperature is unfortunately critical to
methods based on block gibbs sampling. Higher
temperature induces more variability and
possibly non convergence, lower temperatures
cause numeric instabilities as well as poor
solutions that refuse to shift from their
locally optimal solution. */
std::cout << " ndisp: " << ndisp << std::endl;
std::cout << " mindisp: " << mindisp << std::endl;
double p1, p2; /* The model that is minimized uses the same p1, p2
penalties as SGM and countless other stereo algorithms.
*/
/* Precompute the dataterms based on radius size */
int drady = 1;
int dradx = 1;
unsigned char *dataterms = new unsigned char[im1.width*im1.height*ndisp];
std::cout << " precomputing dataterms ... " << std::endl;
calculate_dataterms(ndisp,mindisp,drady,dradx,im1,im2,dataterms);
std::cout << " done precomputing dataterms " << std::endl;
int niter;
if ( !usecheckpoint ) {
std::cout << " calculating prior ... " << std::endl;
p1 = 0;
p2 = 0;
niter = 1;
temperature = 1.;
block_gibbs(niter,ndisp,mindisp,p1,p2,temperature,dataterms,im1,im2,disp);
std::cout << " done calculating prior " << std::endl;
}
/* A very reasonable set of settings is:
*
* p1 = 10; p2 = 215; temperature = 80;
*
*/
std::cout << " calculating posterior ... " << std::endl;
p1 = 10;
p2 = 215;
niter = 2000;
temperature = 20.;
block_gibbs(niter,ndisp,mindisp,p1,p2,temperature,dataterms,im1,im2,disp);
writepgm("disp.pgm",
disp.data,
disp.width,
disp.height);
delete[] im1.data;
delete[] im2.data;
delete[] disp.data;
delete[] dataterms;
return 0;
}
<|endoftext|>
|
<commit_before>//-------------------------------------------------------------------------------
///
/// \file scene.cpp
/// \author Cem Yuksel (www.cemyuksel.com)
/// \version 1.0
/// \date August 26, 2013
///
/// \brief Example source for CS 6620 - University of Utah.
///
//-------------------------------------------------------------------------------
#ifndef _SCENE_CPP_INCLUDED_
#define _SCENE_CPP_INCLUDED_
//-------------------------------------------------------------------------------
#include <vector>
#include "library/cyPoint.h"
typedef cyPoint3f Point3;
#include "library/cyMatrix3.h"
typedef cyMatrix3f Matrix3;
//-------------------------------------------------------------------------------
#ifndef min
# define min(a,b) ((a)<(b)?(a):(b))
#endif
#ifndef max
# define max(a,b) ((a)>(b)?(a):(b))
#endif
#define BIGFLOAT 1.0e30f
namespace scene{
//-------------------------------------------------------------------------------
class Ray
{
public:
Point3 p, dir;
Ray() {}
Ray(const Point3 &_p, const Point3 &_dir) : p(_p), dir(_dir) {}
void Normalize() { dir.Normalize(); }
};
//-------------------------------------------------------------------------------
class Node;
#define HIT_NONE 0
#define HIT_FRONT 1
#define HIT_BACK 2
#define HIT_FRONT_AND_BACK (HIT_FRONT|HIT_BACK)
struct HitInfo
{
float z; // the distance from the ray center to the hit point
const Node *node; // the object node that was hit
bool front; // true if the ray hits the front side, false if the ray hits the back side
HitInfo() { Init(); }
void Init() { z=BIGFLOAT; node=NULL; front=true; }
};
//-------------------------------------------------------------------------------
class ItemBase
{
private:
char *name; // The name of the item
public:
ItemBase() : name(NULL) {}
virtual ~ItemBase() { if ( name ) delete [] name; }
const char* GetName() const { return name ? name : ""; }
void SetName(const char *newName)
{
if ( name ) delete [] name;
if ( newName ) {
int n = strlen(newName);
name = new char[n+1];
for ( int i=0; i<n; i++ ) name[i] = newName[i];
name[n] = '\0';
} else { name = NULL; }
}
};
template <class T> class ItemList : public std::vector<T*>
{
public:
virtual ~ItemList() { DeleteAll(); }
void DeleteAll() { int n=this->size(); for ( int i=0; i<n; i++ ) if ( this->at(i) ) delete this->at(i); }
};
template <class T> class ItemFileList
{
public:
void Clear() { list.DeleteAll(); }
void Append( T* item, const char *name ) { list.push_back( new FileInfo(item,name) ); }
T* Find( const char *name ) const { int n=list.size(); for ( int i=0; i<n; i++ ) if ( list[i] && strcmp(name,list[i]->GetName())==0 ) return list[i]->GetObj(); return NULL; }
private:
class FileInfo : public ItemBase
{
private:
T *item;
public:
FileInfo() : item(NULL) {}
FileInfo(T *_item, const char *name) : item(_item) { SetName(name); }
~FileInfo() { Delete(); }
void Delete() { if (item) delete item; item=NULL; }
void SetObj(T *_item) { Delete(); item=_item; }
T* GetObj() { return item; }
};
ItemList<FileInfo> list;
};
//-------------------------------------------------------------------------------
class Transformation
{
private:
Matrix3 tm; // Transformation matrix to the local space
Point3 pos; // Translation part of the transformation matrix
mutable Matrix3 itm; // Inverse of the transformation matrix (cached)
public:
Transformation() : pos(0,0,0) { tm.SetIdentity(); itm.SetIdentity(); }
const Matrix3& GetTransform() const { return tm; }
const Point3& GetPosition() const { return pos; }
const Matrix3& GetInverseTransform() const { return itm; }
Point3 TransformTo( const Point3 &p ) const { return itm * (p - pos); } // Transform to the local coordinate system
Point3 TransformFrom( const Point3 &p ) const { return tm*p + pos; } // Transform from the local coordinate system
// Transforms a vector to the local coordinate system (same as multiplication with the inverse transpose of the transformation)
Point3 VectorTransformTo( const Point3 &dir ) const { return TransposeMult(tm,dir); }
// Transforms a vector from the local coordinate system (same as multiplication with the inverse transpose of the transformation)
Point3 VectorTransformFrom( const Point3 &dir ) const { return TransposeMult(itm,dir); }
void Translate(Point3 p) { pos+=p; }
void Rotate(Point3 axis, float degree) { Matrix3 m; m.SetRotation(axis,degree*(float)M_PI/180.0f); Transform(m); }
void Scale(float sx, float sy, float sz) { Matrix3 m; m.Zero(); m[0]=sx; m[4]=sy; m[8]=sz; Transform(m); }
void Transform(const Matrix3 &m) { tm*=m; pos=m*pos; tm.GetInverse(itm); }
void InitTransform() { pos.Zero(); tm.SetIdentity(); itm.SetIdentity(); }
private:
// Multiplies the given vector with the transpose of the given matrix
static Point3 TransposeMult( const Matrix3 &m, const Point3 &dir )
{
Point3 d;
d.x = m.GetColumn(0) % dir;
d.y = m.GetColumn(1) % dir;
d.z = m.GetColumn(2) % dir;
return d;
}
};
//-------------------------------------------------------------------------------
// Base class for all object types
class Object
{
public:
virtual ~Object()=0;
virtual bool IntersectRay( const Ray &ray, HitInfo &hit, int face=HIT_FRONT ) const=0;
//void ViewportDisplay() const {} // used for OpenGL display
};
Object::~Object(){}
typedef ItemFileList<Object> ObjFileList;
//-------------------------------------------------------------------------------
class Node : public ItemBase, public Transformation
{
private:
Node **child; // Child nodes
int numChild; // The number of child nodes
Object *obj; // Object reference (merely points to the object, but does not own the object, so it doesn't get deleted automatically)
public:
Node() : child(NULL), numChild(0), obj(NULL) {}
void Init() { DeleteAllChildNodes(); obj=NULL; SetName(NULL); InitTransform(); } // Initialize the node deleting all child nodes
// Hierarchy management
int GetNumChild() const { return numChild; }
void SetNumChild(int n, int keepOld=false)
{
if ( n < 0 ) n=0; // just to be sure
Node **nc = NULL; // new child pointer
if ( n > 0 ) nc = new Node*[n];
for ( int i=0; i<n; i++ ) nc[i] = NULL;
if ( keepOld ) {
int sn = min(n,numChild);
for ( int i=0; i<sn; i++ ) nc[i] = child[i];
}
if ( child ) delete [] child;
child = nc;
numChild = n;
}
const Node* GetChild(int i) const { return child[i]; }
Node* GetChild(int i) { return child[i]; }
void SetChild(int i, Node *node) { child[i]=node; }
void AppendChild(Node *node) { SetNumChild(numChild+1,true); SetChild(numChild-1,node); }
void RemoveChild(int i) { for ( int j=i; j<numChild-1; j++) child[j]=child[j-1]; SetNumChild(numChild-1); }
void DeleteAllChildNodes() { for ( int i=0; i<numChild; i++ ) { child[i]->DeleteAllChildNodes(); delete child[i]; } SetNumChild(0); }
// Object management
const Object* GetObject() const { return obj; }
Object* GetObject() { return obj; }
void SetObject(Object *object) { obj=object; }
// Transformations
Ray ToNodeCoords( const Ray &ray ) const
{
Ray r;
r.p = TransformTo(ray.p);
r.dir = TransformTo(ray.p + ray.dir) - r.p;
return r;
}
};
//-------------------------------------------------------------------------------
class Camera
{
public:
Point3 pos, dir, up;
float fov;
int imgWidth, imgHeight;
void Init()
{
pos.Set(0,0,0);
dir.Set(0,0,-1);
up.Set(0,1,0);
fov = 40;
imgWidth = 200;
imgHeight = 150;
}
};
//-------------------------------------------------------------------------------
typedef unsigned char uchar;
struct Color24
{
uchar r, g, b;
};
//-------------------------------------------------------------------------------
class RenderImage
{
private:
Color24 *img;
float *zbuffer;
uchar *zbuffer8;
int width, height;
int numRenderedPixels;
public:
RenderImage() : img(NULL), zbuffer(NULL), zbuffer8(NULL), width(0), height(0), numRenderedPixels(0) {}
void Init(int w, int h)
{
width=w;
height=h;
if (img) delete [] img;
img = new Color24[width*height];
if (zbuffer) delete [] zbuffer;
zbuffer = new float[width*height];
for(int i = 0; i < width * height; i++)
zbuffer[i] = BIGFLOAT;
if (zbuffer8) delete [] zbuffer8;
zbuffer8 = NULL;
ResetNumRenderedPixels();
}
void setBackground(Color24 c){
for(int i = 0; i < width * height; i++)
img[i] = c;
}
int GetWidth() const { return width; }
int GetHeight() const { return height; }
Color24* GetPixels() { return img; }
float* GetZBuffer() { return zbuffer; }
uchar* GetZBufferImage() { return zbuffer8; }
void ResetNumRenderedPixels() { numRenderedPixels=0; }
int GetNumRenderedPixels() const { return numRenderedPixels; }
void IncrementNumRenderPixel() { numRenderedPixels++; }
void IncrementNumRenderPixel(int n) { numRenderedPixels+=n; } // not thread-safe
bool IsRenderDone() const { return numRenderedPixels >= width*height; }
void ComputeZBufferImage()
{
int size = width * height;
if (zbuffer8) delete [] zbuffer8;
zbuffer8 = new unsigned char[size];
float zmin=BIGFLOAT, zmax=0;
for ( int i=0; i<size; i++ ) {
if ( zbuffer[i] == BIGFLOAT ) continue;
if ( zmin > zbuffer[i] ) zmin = zbuffer[i];
if ( zmax < zbuffer[i] ) zmax = zbuffer[i];
}
for ( int i=0; i<size; i++ ) {
if ( zbuffer[i] == BIGFLOAT ) zbuffer8[i] = 33;
else {
float f = (zmax-zbuffer[i])/(zmax-zmin);
int c = int(f * 200);
if ( c < 0 ) f = 0;
if ( c > 200 ) f = 200;
zbuffer8[i] = c + 47;
}
}
}
bool SaveImage(const char *filename) const { return SavePPM(filename,&img[0].r,3); }
bool SaveZImage(const char *filename) const { return SavePPM(filename,zbuffer8,1); }
private:
bool SavePPM(const char *filename, uchar *data, int compCount) const
{
FILE *fp = fopen(filename,"wb");
if ( !fp ) return false;
fprintf(fp,"P6\n%d %d\n255\n", width, height);
switch( compCount ) {
case 1:
for ( int i=0; i<width*height; i++ ) {
uchar d[3] = { data[i], data[i], data[i] };
fwrite(d,1,3,fp);
}
break;
case 3:
fwrite(data,width*height,3,fp);
break;
}
fclose(fp);
return true;
}
};
//-------------------------------------------------------------------------------
}
#endif
<commit_msg>major rewrite of scene class, need to clean up and refactor majorly next<commit_after>// Copyright 2013 Sean McKenna
//
// 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.
//
// scene class (nodes, objects, transformation, camera, rendering, etc.)
// originally adapted from code provided by Cem Yuksel
// libraries, namespace
#ifndef _SCENE_CPP_INCLUDED_
#define _SCENE_CPP_INCLUDED_
#include <vector>
#include "library/cyPoint.h"
typedef cyPoint3f Point3;
#include "library/cyMatrix3.h"
typedef cyMatrix3f Matrix3;
using namespace std;
// custom functions
#ifndef min
# define min(a, b) ((a) < (b) ? (a):(b))
#endif
#ifndef max
# define max(a, b) ((a) > (b) ? (a):(b))
#endif
#define BIGFLOAT 1.0e30f
// declare namespace
namespace scene{
// Ray definition (point & direction)
class Ray{
public:
Point3 p, dir;
Ray(){}
Ray(const Point3 &_p, const Point3 &_dir): p(_p), dir(_dir) {}
void Normalize(){
dir.Normalize();
}
};
// Node definition
class Node;
// Hit Info definition (for each node)
#define HIT_NONE 0
#define HIT_FRONT 1
#define HIT_BACK 2
#define HIT_FRONT_AND_BACK (HIT_FRONT | HIT_BACK)
struct HitInfo{
// distance from ray to the hit point
float z;
// object node that is hit
const Node *node;
// returns true if the object is hit on a front face, false if back face
bool front;
// initialization
HitInfo(){
Init();
}
void Init(){
z = BIGFLOAT;
node = NULL;
front = true;
}
};
// Item Base definition
class ItemBase{
private:
// name of the item
char *name;
public:
ItemBase(): name(NULL) {}
virtual ~ItemBase(){
if(name)
delete [] name;
}
const char* GetName() const{
return name ? name: "";
}
void SetName(const char *newName){
if(name)
delete [] name;
if(newName){
int n = strlen(newName);
name = new char[n + 1];
for(int i = 0; i < n; i++)
name[i] = newName[i];
name[n] = '\0';
}else{
name = NULL;
}
}
};
// ItemList template definition
template <class T> class ItemList: public vector <T*>{
public:
virtual ~ItemList(){
DeleteAll();
}
void DeleteAll(){
int n = this->size();
for(int i = 0; i < n; i++)
if(this->at(i))
delete this->at(i);
}
};
// ItemFileList template definition
template <class T> class ItemFileList{
public:
void Clear(){
list.DeleteAll();
}
void Append(T* item, const char *name){
list.push_back(new FileInfo(item, name));
}
T* Find(const char *name) const{
int n = list.size();
for(int i = 0; i < n; i++)
if(list[i] && strcmp(name, list[i]->GetName()) == 0)
return list[i]->GetObj();
return NULL;
}
private:
class FileInfo: public ItemBase{
private:
T *item;
public:
FileInfo(): item(NULL) {}
FileInfo(T *_item, const char *name): item(_item){
SetName(name);
}
~FileInfo(){
Delete();
}
void Delete(){
if(item)
delete item;
item = NULL;
}
void SetObj(T *_item){
Delete();
item = _item;
}
T* GetObj(){
return item;
}
};
ItemList<FileInfo> list;
};
// Transformation definition
class Transformation{
private:
// transformation matrix (to local space)
Matrix3 tm;
// translation part of transformation
Point3 pos;
// inverse of transformation matrix (cached)
mutable Matrix3 itm;
public:
Transformation(): pos(0, 0, 0){
tm.SetIdentity();
itm.SetIdentity();
}
const Matrix3& GetTransform() const{
return tm;
}
const Point3& GetPosition() const{
return pos;
}
const Matrix3& GetInverseTransform() const{
return itm;
}
// transform into local space
Point3 TransformTo(const Point3 &p) const{
return itm * (p - pos);
}
// transform from local space
Point3 TransformFrom(const Point3 &p) const{
return tm * p + pos;
}
// transform vector to local space
Point3 VectorTransformTo(const Point3 &dir) const{
return TransposeMult(tm, dir);
}
// transform vector from local space
Point3 VectorTransformFrom(const Point3 &dir) const{
return TransposeMult(itm, dir);
}
void Translate(Point3 p){
pos += p;
}
void Rotate(Point3 axis, float degree){
Matrix3 m;
m.SetRotation(axis, degree * (float) M_PI / 180.0);
Transform(m);
}
void Scale(float sx, float sy, float sz){
Matrix3 m;
m.Zero();
m[0] = sx;
m[4] = sy;
m[8] = sz;
Transform(m);
}
void Transform(const Matrix3 &m){
tm *= m;
pos = m * pos;
tm.GetInverse(itm);
}
void InitTransform(){
pos.Zero();
tm.SetIdentity();
itm.SetIdentity();
}
private:
// multiples given vector with transpose of the matrix
static Point3 TransposeMult(const Matrix3 &m, const Point3 &dir){
Point3 d;
d.x = m.GetColumn(0) % dir;
d.y = m.GetColumn(1) % dir;
d.z = m.GetColumn(2) % dir;
return d;
}
};
// Object definition (extended for all kinds of objects attached to a node)
class Object{
public:
virtual ~Object() = 0;
virtual bool IntersectRay(const Ray &ray, HitInfo &hit, int face = HIT_FRONT) const = 0;
};
Object::~Object(){}
// ObjectFileList definition
typedef ItemFileList<Object> ObjFileList;
// Node definition (stores objects)
class Node: public ItemBase, public Transformation{
private:
// child nodes
Node **child;
// number of child nodes
int numChild;
// object reference
Object *obj;
public:
Node(): child(NULL), numChild(0), obj(NULL) {}
// initialize the node, by deleting all its children
void Init(){
DeleteAllChildNodes();
obj = NULL;
SetName(NULL);
InitTransform();
}
// managing hierarchy of nodes
int GetNumChild() const{
return numChild;
}
void SetNumChild(int n, int keepOld = false){
if(n < 0)
n = 0;
// create a new child pointer
Node **nc = NULL;
if(n > 0)
nc = new Node*[n];
for(int i = 0; i < n; i++)
nc[i] = NULL;
if(keepOld){
int sn = min(n, numChild);
for(int i = 0; i < sn; i++)
nc[i] = child[i];
}
if(child)
delete [] child;
child = nc;
numChild = n;
}
const Node* GetChild(int i) const{
return child[i];
}
Node* GetChild(int i){
return child[i];
}
void SetChild(int i, Node *node){
child[i] = node;
}
void AppendChild(Node *node){
SetNumChild(numChild + 1, true);
SetChild(numChild - 1, node);
}
void RemoveChild(int i){
for(int j = i; j < numChild - 1; j++)
child[j] = child[j - 1];
SetNumChild(numChild - 1);
}
void DeleteAllChildNodes(){
for(int i = 0; i < numChild; i++){
child[i]->DeleteAllChildNodes();
delete child[i];
}
SetNumChild(0);
}
// managing node objects
const Object* GetObject() const{
return obj;
}
Object* GetObject(){
return obj;
}
void SetObject(Object *object){
obj = object;
}
// transformations
Ray ToNodeCoords(const Ray &ray) const{
Ray r;
r.p = TransformTo(ray.p);
r.dir = TransformTo(ray.p + ray.dir) - r.p;
return r;
}
};
// Camera definition
class Camera{
public:
Point3 pos, dir, up;
float fov;
int imgWidth, imgHeight;
void Init(){
pos.Set(0, 0, 0);
dir.Set(0, 0, -1);
up.Set(0, 1, 0);
fov = 40;
imgWidth = 200;
imgHeight = 150;
}
};
// Color definition
typedef unsigned char uchar;
struct Color24{
uchar r, g, b;
};
// RenderImage definition
class RenderImage{
private:
Color24 *img;
float *zbuffer;
uchar *zbuffer8;
int width, height;
int numRenderedPixels;
public:
RenderImage(): img(NULL), zbuffer(NULL), zbuffer8(NULL), width(0), height(0), numRenderedPixels(0) {}
void Init(int w, int h){
width = w;
height = h;
if(img)
delete [] img;
img = new Color24[width * height];
if(zbuffer)
delete [] zbuffer;
zbuffer = new float[width * height];
for(int i = 0; i < width * height; i++)
zbuffer[i] = BIGFLOAT;
if(zbuffer8)
delete [] zbuffer8;
zbuffer8 = NULL;
ResetNumRenderedPixels();
}
void setBackground(Color24 c){
for(int i = 0; i < width * height; i++)
img[i] = c;
}
int GetWidth() const{
return width;
}
int GetHeight() const{
return height;
}
Color24* GetPixels(){
return img;
}
float* GetZBuffer(){
return zbuffer;
}
uchar* GetZBufferImage(){
return zbuffer8;
}
void ResetNumRenderedPixels(){
numRenderedPixels = 0;
}
int GetNumRenderedPixels() const{
return numRenderedPixels;
}
void IncrementNumRenderPixel(){
numRenderedPixels++;
}
void IncrementNumRenderPixel(int n){
numRenderedPixels += n;
}
bool IsRenderDone() const{
return numRenderedPixels >= width * height;
}
void ComputeZBufferImage(){
int size = width * height;
if(zbuffer8)
delete [] zbuffer8;
zbuffer8 = new unsigned char[size];
float zmin = BIGFLOAT, zmax = 0;
for(int i = 0; i < size; i++){
if(zbuffer[i] == BIGFLOAT)
continue;
if(zmin > zbuffer[i])
zmin = zbuffer[i];
if(zmax < zbuffer[i])
zmax = zbuffer[i];
}
for(int i = 0; i < size; i++){
if(zbuffer[i] == BIGFLOAT)
zbuffer8[i] = 33;
else{
float f = (zmax - zbuffer[i]) / (zmax - zmin);
int c = int(f * 200);
if(c < 0)
f = 0;
if(c > 200)
f = 200;
zbuffer8[i] = c + 47;
}
}
}
bool SaveImage(const char *filename) const{
return SavePPM(filename, &img[0].r, 3);
}
bool SaveZImage(const char *filename) const{
return SavePPM(filename, zbuffer8, 1);
}
private:
bool SavePPM(const char *filename, uchar *data, int compCount) const{
FILE *fp = fopen(filename, "wb");
if(!fp)
return false;
fprintf(fp, "P6\n%d %d\n255\n", width, height);
switch(compCount){
case 1:
for(int i = 0; i < width * height; i++){
uchar d[3] = {data[i], data[i], data[i]};
fwrite(d, 1, 3, fp);
}
break;
case 3:
fwrite(data, width * height, 3, fp);
break;
}
fclose(fp);
return true;
}
};
}
#endif
<|endoftext|>
|
<commit_before>#include "process.h"
// POSIX
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>
// POSIX++
#include <cerrno>
#include <cstdlib>
#include <climits>
#include <cstring>
// PDTK
#include <specialized/procstat.h>
#include <specialized/eventbackend.h>
#include <cxxutils/error_helpers.h>
#include <cxxutils/colors.h>
enum class command : uint8_t
{
invoke = 0,
executable,
arguments,
environment,
environmentvar,
workingdir,
priority,
uid,
gid,
euid,
egid,
resource
};
static inline vfifo& operator << (vfifo& vq, command cmd) noexcept
{ return vq << static_cast<uint8_t>(cmd); }
static std::unordered_map<pid_t, Process*> process_map; // do not try to own Process memory
void Process::init_once(void) noexcept
{
static bool ok = true;
if(ok)
{
ok = false;
struct sigaction actions;
actions.sa_handler = &reaper;
::sigemptyset(&actions.sa_mask);
actions.sa_flags = SA_RESTART | SA_NOCLDSTOP;
flaw(::sigaction(SIGCHLD, &actions, nullptr) == posix::error_response, posix::critical, , std::exit(1),
"An 'impossible' situation has occurred.")
}
}
void Process::reaper(int sig) noexcept
{
flaw(sig != SIGCHLD, posix::warning, posix::error(std::errc::invalid_argument),,
"Process::reaper() has been called improperly")
pid_t pid = posix::error_response; // set value just in case
int status = 0;
while((pid = ::waitpid(pid_t(-1), &status, WNOHANG)) != posix::error_response) // get the next dead process (if there is one)... while the currently reaped process was valid
{
auto process_map_iter = process_map.find(pid); // find dead process
if(process_map_iter != process_map.end()) // if the dead process exists...
{
Process* p = process_map_iter->second;
#ifndef ENABLE_PROCESS_EVENT_TRACKING
Object::enqueue_copy(p->finished, posix::invalid_descriptor, EventData_t(EventFlags::ExitEvent, p->processId(), p->processId(), status, sig));
#endif
EventBackend::remove(p->getStdOut());
EventBackend::remove(p->getStdErr());
posix::close(p->getStdOut());
posix::close(p->getStdErr());
posix::close(p->getStdIn());
p->m_state = Process::State::Finished;
process_map.erase(process_map_iter); // remove finished process from the process map
}
}
}
Process::Process(void) noexcept
: m_state(State::Initializing)
{
init_once();
process_map.emplace(processId(), this); // add self to process map
#ifdef ENABLE_PROCESS_EVENT_TRACKING
Object::connect(processId(), EventFlags::ExecEvent, started);
Object::connect(processId(), EventFlags::ExitEvent, finished);
#endif
}
Process::~Process(void) noexcept
{
if(m_state == State::Running)
sendSignal(posix::signal::Kill);
Object::disconnect(getStdOut(), EventFlags::Readable);
Object::disconnect(getStdErr(), EventFlags::Readable);
Object::disconnect(processId(), EventFlags::ExecEvent);
Object::disconnect(processId(), EventFlags::ExitEvent);
m_state = State::Invalid;
}
bool Process::write_then_read(void) noexcept
{
if(m_iobuf.empty() || // ensure there is data to write
!writeStdIn(m_iobuf) || // write data to pipe
!waitReadStdOut(1000) || // wait to read pipe
!readStdOut(m_iobuf) || // read data from pipe
(m_iobuf >> errno).hadError()) // read return value
return false;
return errno == posix::success_response;
}
bool Process::setArguments(const std::vector<std::string>& arguments) noexcept
{
m_iobuf.reset();
m_iobuf << command::arguments;
for(const std::string& arg : arguments)
m_iobuf << arg;
return write_then_read();
}
bool Process::setEnvironment(const std::unordered_map<std::string, std::string>& environment) noexcept
{
m_iobuf.reset();
m_iobuf << command::environment;
for(const std::pair<std::string, std::string>& p : environment)
m_iobuf << p.first << p.second;
return write_then_read();
}
bool Process::setEnvironmentVariable(const std::string& name, const std::string& value) noexcept
{
m_iobuf.reset();
m_iobuf << command::environment << name << value;
return write_then_read();
}
bool Process::setResourceLimit(Process::Resource which, rlim_t limit) noexcept
{
m_iobuf.reset();
m_iobuf << command::resource
<< static_cast<int>(which)
<< static_cast<rlim_t>(RLIM_SAVED_CUR)
<< limit;
return write_then_read();
}
bool Process::setWorkingDirectory(const std::string& dir) noexcept
{
m_iobuf.reset();
m_iobuf << command::workingdir << dir;
return write_then_read();
}
bool Process::setExecutable(const std::string& executable) noexcept
{
m_iobuf.reset();
m_iobuf << command::executable << executable;
return write_then_read();
}
bool Process::setUserID(uid_t id) noexcept
{
if(posix::getpwuid(id) == nullptr)
return false;
m_iobuf.reset();
m_iobuf << command::uid << id;
return write_then_read();
}
bool Process::setGroupID(gid_t id) noexcept
{
if(posix::getgrgid(id) == nullptr)
return false;
m_iobuf.reset();
m_iobuf << command::gid << id;
return write_then_read();
}
bool Process::setEffectiveUserID(uid_t id) noexcept
{
if(posix::getpwuid(id) == nullptr)
return false;
m_iobuf.reset();
m_iobuf << command::euid << id;
return write_then_read();
}
bool Process::setEffectiveGroupID(gid_t id) noexcept
{
if(posix::getgrgid(id) == nullptr)
return false;
m_iobuf.reset();
m_iobuf << command::egid << id;
return write_then_read();
}
bool Process::setPriority(int nval) noexcept
{
#if defined(PRIO_MIN) && defined(PRIO_MAX)
if(nval < PRIO_MIN || nval > PRIO_MAX)
return false;
#else
#warning PRIO_MIN or PRIO_MAX is not defined. The safegaurd in Process::setPriority() is disabled.
#endif
m_iobuf.reset();
m_iobuf << command::priority << nval;
return write_then_read();
}
#ifdef _XOPEN_SOURCE_EXTENDED
bool Process::sendSignal(posix::signal::EId id, int value) const noexcept
{
return posix::signal::send(processId(), id, value);
}
#endif
bool Process::invoke(void) noexcept
{
flaw(m_state != State::Initializing, posix::severe, posix::error(std::errc::device_or_resource_busy), false,
"Called Process::invoke() on an active process!")
m_iobuf.reset();
m_iobuf << command::invoke;
if(!writeStdIn(m_iobuf))
return false;
m_state = State::Invalid;
state();
#ifndef ENABLE_PROCESS_EVENT_TRACKING
Object::enqueue_copy(started, posix::invalid_descriptor, EventData_t(EventFlags::ExecEvent, processId(), processId()));
#endif
Object::connect(getStdOut(), EventFlags::Readable, stdoutMessage);
Object::connect(getStdErr(), EventFlags::Readable, stderrMessage);
m_state = State::Running;
return errno == posix::success_response;
}
Process::State Process::state(void) noexcept
{
switch(m_state)
{
case State::Finished:
case State::Initializing:
break;
default:
process_state_t data;
flaw(::procstat(processId(), &data) == posix::error_response, posix::severe, m_state = State::Invalid, m_state,
"Process %i does not exist.", processId()); // process _must_ exist
switch (data.state)
{
case WaitingInterruptable:
case WaitingUninterruptable:
m_state = State::Waiting; break;
case Zombie : m_state = State::Zombie ; break;
case Stopped: m_state = State::Stopped; break;
case Running: m_state = State::Running; break;
}
}
return m_state;
}
<commit_msg>portability fixes<commit_after>#include "process.h"
// POSIX
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>
// POSIX++
#include <cerrno>
#include <cstdlib>
#include <climits>
#include <cstring>
// PDTK
#include <specialized/procstat.h>
#include <specialized/eventbackend.h>
#include <cxxutils/error_helpers.h>
#include <cxxutils/colors.h>
enum class command : uint8_t
{
invoke = 0,
executable,
arguments,
environment,
environmentvar,
workingdir,
priority,
uid,
gid,
euid,
egid,
resource
};
static inline vfifo& operator << (vfifo& vq, command cmd) noexcept
{ return vq << static_cast<uint8_t>(cmd); }
static std::unordered_map<pid_t, Process*> process_map; // do not try to own Process memory
void Process::init_once(void) noexcept
{
static bool ok = true;
if(ok)
{
ok = false;
struct sigaction actions;
actions.sa_handler = &reaper;
::sigemptyset((&actions.sa_mask));
actions.sa_flags = SA_RESTART | SA_NOCLDSTOP;
flaw(::sigaction(SIGCHLD, &actions, nullptr) == posix::error_response, posix::critical, , std::exit(1),
"An 'impossible' situation has occurred.")
}
}
void Process::reaper(int sig) noexcept
{
flaw(sig != SIGCHLD, posix::warning, posix::error(std::errc::invalid_argument),,
"Process::reaper() has been called improperly")
pid_t pid = posix::error_response; // set value just in case
int status = 0;
while((pid = ::waitpid(pid_t(-1), &status, WNOHANG)) != posix::error_response) // get the next dead process (if there is one)... while the currently reaped process was valid
{
auto process_map_iter = process_map.find(pid); // find dead process
if(process_map_iter != process_map.end()) // if the dead process exists...
{
Process* p = process_map_iter->second;
#ifndef ENABLE_PROCESS_EVENT_TRACKING
Object::enqueue_copy(p->finished, posix::invalid_descriptor, EventData_t(EventFlags::ExitEvent, p->processId(), p->processId(), status, sig));
#endif
EventBackend::remove(p->getStdOut());
EventBackend::remove(p->getStdErr());
posix::close(p->getStdOut());
posix::close(p->getStdErr());
posix::close(p->getStdIn());
p->m_state = Process::State::Finished;
process_map.erase(process_map_iter); // remove finished process from the process map
}
}
}
Process::Process(void) noexcept
: m_state(State::Initializing)
{
init_once();
process_map.emplace(processId(), this); // add self to process map
#ifdef ENABLE_PROCESS_EVENT_TRACKING
Object::connect(processId(), EventFlags::ExecEvent, started);
Object::connect(processId(), EventFlags::ExitEvent, finished);
#endif
}
Process::~Process(void) noexcept
{
#ifdef _XOPEN_SOURCE_EXTENDED
if(m_state == State::Running)
sendSignal(posix::signal::Kill);
#endif
Object::disconnect(getStdOut(), EventFlags::Readable);
Object::disconnect(getStdErr(), EventFlags::Readable);
Object::disconnect(processId(), EventFlags::ExecEvent);
Object::disconnect(processId(), EventFlags::ExitEvent);
m_state = State::Invalid;
}
bool Process::write_then_read(void) noexcept
{
if(m_iobuf.empty() || // ensure there is data to write
!writeStdIn(m_iobuf) || // write data to pipe
!waitReadStdOut(1000) || // wait to read pipe
!readStdOut(m_iobuf) || // read data from pipe
(m_iobuf >> errno).hadError()) // read return value
return false;
return errno == posix::success_response;
}
bool Process::setArguments(const std::vector<std::string>& arguments) noexcept
{
m_iobuf.reset();
m_iobuf << command::arguments;
for(const std::string& arg : arguments)
m_iobuf << arg;
return write_then_read();
}
bool Process::setEnvironment(const std::unordered_map<std::string, std::string>& environment) noexcept
{
m_iobuf.reset();
m_iobuf << command::environment;
for(const std::pair<std::string, std::string>& p : environment)
m_iobuf << p.first << p.second;
return write_then_read();
}
bool Process::setEnvironmentVariable(const std::string& name, const std::string& value) noexcept
{
m_iobuf.reset();
m_iobuf << command::environment << name << value;
return write_then_read();
}
bool Process::setResourceLimit(Process::Resource which, rlim_t limit) noexcept
{
m_iobuf.reset();
m_iobuf << command::resource
<< static_cast<int>(which)
<< static_cast<rlim_t>(RLIM_SAVED_CUR)
<< limit;
return write_then_read();
}
bool Process::setWorkingDirectory(const std::string& dir) noexcept
{
m_iobuf.reset();
m_iobuf << command::workingdir << dir;
return write_then_read();
}
bool Process::setExecutable(const std::string& executable) noexcept
{
m_iobuf.reset();
m_iobuf << command::executable << executable;
return write_then_read();
}
bool Process::setUserID(uid_t id) noexcept
{
if(posix::getpwuid(id) == nullptr)
return false;
m_iobuf.reset();
m_iobuf << command::uid << id;
return write_then_read();
}
bool Process::setGroupID(gid_t id) noexcept
{
if(posix::getgrgid(id) == nullptr)
return false;
m_iobuf.reset();
m_iobuf << command::gid << id;
return write_then_read();
}
bool Process::setEffectiveUserID(uid_t id) noexcept
{
if(posix::getpwuid(id) == nullptr)
return false;
m_iobuf.reset();
m_iobuf << command::euid << id;
return write_then_read();
}
bool Process::setEffectiveGroupID(gid_t id) noexcept
{
if(posix::getgrgid(id) == nullptr)
return false;
m_iobuf.reset();
m_iobuf << command::egid << id;
return write_then_read();
}
bool Process::setPriority(int nval) noexcept
{
#if defined(PRIO_MIN) && defined(PRIO_MAX)
if(nval < PRIO_MIN || nval > PRIO_MAX)
return false;
#else
#warning PRIO_MIN or PRIO_MAX is not defined. The safegaurd in Process::setPriority() is disabled.
#endif
m_iobuf.reset();
m_iobuf << command::priority << nval;
return write_then_read();
}
#ifdef _XOPEN_SOURCE_EXTENDED
bool Process::sendSignal(posix::signal::EId id, int value) const noexcept
{
return posix::signal::send(processId(), id, value);
}
#endif
bool Process::invoke(void) noexcept
{
flaw(m_state != State::Initializing, posix::severe, posix::error(std::errc::device_or_resource_busy), false,
"Called Process::invoke() on an active process!")
m_iobuf.reset();
m_iobuf << command::invoke;
if(!writeStdIn(m_iobuf))
return false;
m_state = State::Invalid;
state();
#ifndef ENABLE_PROCESS_EVENT_TRACKING
Object::enqueue_copy(started, posix::invalid_descriptor, EventData_t(EventFlags::ExecEvent, processId(), processId()));
#endif
Object::connect(getStdOut(), EventFlags::Readable, stdoutMessage);
Object::connect(getStdErr(), EventFlags::Readable, stderrMessage);
m_state = State::Running;
return errno == posix::success_response;
}
Process::State Process::state(void) noexcept
{
switch(m_state)
{
case State::Finished:
case State::Initializing:
break;
default:
process_state_t data;
flaw(::procstat(processId(), &data) == posix::error_response, posix::severe, m_state = State::Invalid, m_state,
"Process %i does not exist.", processId()); // process _must_ exist
switch (data.state)
{
case WaitingInterruptable:
case WaitingUninterruptable:
m_state = State::Waiting; break;
case Zombie : m_state = State::Zombie ; break;
case Stopped: m_state = State::Stopped; break;
case Running: m_state = State::Running; break;
}
}
return m_state;
}
<|endoftext|>
|
<commit_before>/*
Copyright 2003-2009 John Plevyak, All Rights Reserved
*/
#define EXTERN
#include <signal.h>
#include <sys/resource.h>
#include "defs.h"
int do_unit_tests = 0;
static char pyc_ifa_log[256];
static void
help(ArgumentState *arg_state, char *arg_unused) {
char ver[30];
get_version(ver);
fprintf(stderr, "PYC Version %s ", ver);
fprintf(stderr,
#include "COPYRIGHT.i"
);
usage(arg_state, arg_unused);
}
static void
version(ArgumentState *arg_state, char *arg_unused) {
char ver[30];
get_version(ver);
fprintf(stderr, "PYC Version %s ", ver);
fprintf(stderr,
#include "COPYRIGHT.i"
);
exit(0);
}
static void
license(ArgumentState *arg_state, char *arg_unused) {
fprintf(stderr,
#include "LICENSE.i"
);
exit(0);
}
static ArgumentDescription arg_desc[] = {
{"debug_info", 'g', "Produce Debugging Information", "F", &codegen_debug, "PYC_DEBUG_INFO", NULL},
{"optimize", 'O', "Optimize", "F", &codegen_optimize, "PYC_OPTIMIZE", NULL},
#ifdef DEBUG
{"test", 't', "Unit Test", "F", &do_unit_tests, "PYC_TEST", NULL},
{"test_scoping", ' ', "Test Scoping", "F", &test_scoping, "PYC_TEST_SCOPING", NULL},
#endif
{"html", ' ', "Output as HTML", "F", &fdump_html, "PYC_HTML", NULL},
{"ifalog", 'l', "IFA Log", "S256", pyc_ifa_log, "PYC_IFA_LOG", log_flags_arg},
{"system_directory", 'D', "System Directory", "S511", system_dir, "PYC_SYSTEM_DIRECTORY", NULL},
{"verbose", 'v', "Verbosity Level", "+", &verbose_level, "PYC_VERBOSE", NULL},
{"debug", 'd', "Debugging Level", "+", &debug_level, "PYC_DEBUG", NULL},
{"license", ' ', "Show License", NULL, NULL, NULL, license},
{"version", ' ', "Version", NULL, NULL, NULL, version},
{"help", 'h', "Help", NULL, NULL, NULL, help},
{0}
};
static ArgumentState arg_state("pyc", arg_desc);
static void init_system() {
struct rlimit nfiles;
assert(!getrlimit(RLIMIT_NOFILE, &nfiles));
nfiles.rlim_cur = nfiles.rlim_max;
assert(!setrlimit(RLIMIT_NOFILE, &nfiles));
assert(!getrlimit(RLIMIT_NOFILE, &nfiles));
}
void compile(cchar *fn) {
if (ifa_analyze(fn) < 0)
fail("program does not type");
if (ifa_optimize() < 0)
fail("unable to optimize program");
if (fgraph)
ifa_graph(fn);
if (fdump_html) {
char mktree_dir[512];
strcpy(mktree_dir, system_dir);
ifa_html(fn, mktree_dir);
}
if (fcg) {
c_codegen_write_c(pdb->fa, if1->top->fun, fn);
c_codegen_compile(fn);
}
return;
}
cchar *mod_name_from_filename(cchar *n) {
cchar *start = strrchr(n, '/');
if (!start) start = n; else start++;
cchar *end = strrchr(n, '.');
assert(end);
return dupstr(start,end);
}
int main(int argc, char *argv[]) {
MEM_INIT();
INIT_RAND64(0x1234567);
process_args(&arg_state, argc, argv);
ifa_verbose = verbose_level;
ifa_debug = debug_level;
if (arg_state.nfile_arguments < 1)
usage(&arg_state, 0);
init_system();
init_config();
if (pyc_ifa_log[0])
init_logs();
Service::start_all();
if (do_unit_tests) {
int r = UnitTest::run_all();
Service::stop_all();
_exit(r);
}
Py_Initialize();
PyEval_InitThreads();
PyArena *arena = PyArena_New();
cchar *first_filename = 0;
Vec<PycModule *> mods;
for (int i = -1; i < arg_state.nfile_arguments; i++) {
cchar *filename = 0;
if (i < 0) {
char fn[256];
strcpy(fn, system_dir);
strcat(fn, "/__pyc__.py");
filename = dupstr(fn);
} else
filename = arg_state.file_argument[i];
if (!i)
first_filename = filename;
mod_ty mod = file_to_mod(filename, arena);
if (mod)
mods.add(new PycModule(mod, filename, i < 0));
}
if (mods.n > 1) {
ast_to_if1(mods, arena);
compile(first_filename);
}
PyArena_Free(arena);
Py_Finalize();
Service::stop_all();
exit(0);
return 0;
}
<commit_msg>return error code from c_compile as exit() value<commit_after>/*
Copyright 2003-2009 John Plevyak, All Rights Reserved
*/
#define EXTERN
#include <signal.h>
#include <sys/resource.h>
#include "defs.h"
int do_unit_tests = 0;
static char pyc_ifa_log[256];
static void
help(ArgumentState *arg_state, char *arg_unused) {
char ver[30];
get_version(ver);
fprintf(stderr, "PYC Version %s ", ver);
fprintf(stderr,
#include "COPYRIGHT.i"
);
usage(arg_state, arg_unused);
}
static void
version(ArgumentState *arg_state, char *arg_unused) {
char ver[30];
get_version(ver);
fprintf(stderr, "PYC Version %s ", ver);
fprintf(stderr,
#include "COPYRIGHT.i"
);
exit(0);
}
static void
license(ArgumentState *arg_state, char *arg_unused) {
fprintf(stderr,
#include "LICENSE.i"
);
exit(0);
}
static ArgumentDescription arg_desc[] = {
{"debug_info", 'g', "Produce Debugging Information", "F", &codegen_debug, "PYC_DEBUG_INFO", NULL},
{"optimize", 'O', "Optimize", "F", &codegen_optimize, "PYC_OPTIMIZE", NULL},
#ifdef DEBUG
{"test", 't', "Unit Test", "F", &do_unit_tests, "PYC_TEST", NULL},
{"test_scoping", ' ', "Test Scoping", "F", &test_scoping, "PYC_TEST_SCOPING", NULL},
#endif
{"html", ' ', "Output as HTML", "F", &fdump_html, "PYC_HTML", NULL},
{"ifalog", 'l', "IFA Log", "S256", pyc_ifa_log, "PYC_IFA_LOG", log_flags_arg},
{"system_directory", 'D', "System Directory", "S511", system_dir, "PYC_SYSTEM_DIRECTORY", NULL},
{"verbose", 'v', "Verbosity Level", "+", &verbose_level, "PYC_VERBOSE", NULL},
{"debug", 'd', "Debugging Level", "+", &debug_level, "PYC_DEBUG", NULL},
{"license", ' ', "Show License", NULL, NULL, NULL, license},
{"version", ' ', "Version", NULL, NULL, NULL, version},
{"help", 'h', "Help", NULL, NULL, NULL, help},
{0}
};
static ArgumentState arg_state("pyc", arg_desc);
static void init_system() {
struct rlimit nfiles;
assert(!getrlimit(RLIMIT_NOFILE, &nfiles));
nfiles.rlim_cur = nfiles.rlim_max;
assert(!setrlimit(RLIMIT_NOFILE, &nfiles));
assert(!getrlimit(RLIMIT_NOFILE, &nfiles));
}
void compile(cchar *fn) {
if (ifa_analyze(fn) < 0)
fail("program does not type");
if (ifa_optimize() < 0)
fail("unable to optimize program");
if (fgraph)
ifa_graph(fn);
if (fdump_html) {
char mktree_dir[512];
strcpy(mktree_dir, system_dir);
ifa_html(fn, mktree_dir);
}
if (fcg) {
c_codegen_write_c(pdb->fa, if1->top->fun, fn);
if (c_codegen_compile(fn))
fail("compilation failure");
}
return;
}
cchar *mod_name_from_filename(cchar *n) {
cchar *start = strrchr(n, '/');
if (!start) start = n; else start++;
cchar *end = strrchr(n, '.');
assert(end);
return dupstr(start,end);
}
int main(int argc, char *argv[]) {
MEM_INIT();
INIT_RAND64(0x1234567);
process_args(&arg_state, argc, argv);
ifa_verbose = verbose_level;
ifa_debug = debug_level;
if (arg_state.nfile_arguments < 1)
usage(&arg_state, 0);
init_system();
init_config();
if (pyc_ifa_log[0])
init_logs();
Service::start_all();
if (do_unit_tests) {
int r = UnitTest::run_all();
Service::stop_all();
_exit(r);
}
Py_Initialize();
PyEval_InitThreads();
PyArena *arena = PyArena_New();
cchar *first_filename = 0;
Vec<PycModule *> mods;
for (int i = -1; i < arg_state.nfile_arguments; i++) {
cchar *filename = 0;
if (i < 0) {
char fn[256];
strcpy(fn, system_dir);
strcat(fn, "/__pyc__.py");
filename = dupstr(fn);
} else
filename = arg_state.file_argument[i];
if (!i)
first_filename = filename;
mod_ty mod = file_to_mod(filename, arena);
if (mod)
mods.add(new PycModule(mod, filename, i < 0));
}
if (mods.n > 1) {
ast_to_if1(mods, arena);
compile(first_filename);
}
PyArena_Free(arena);
Py_Finalize();
Service::stop_all();
exit(0);
return 0;
}
<|endoftext|>
|
<commit_before>// [WriteFile Name=LineOfSightGeoElement, Category=Analysis]
// [Legal]
// Copyright 2019 Esri.
// 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.
// [Legal]
#include "LineOfSightGeoElement.h"
#include "ArcGISSceneLayer.h"
#include "ArcGISTiledElevationSource.h"
#include "GeoElementLineOfSight.h"
#include "GeometryEngine.h"
#include "GraphicsOverlay.h"
#include "ModelSceneSymbol.h"
#include "PointBuilder.h"
#include "Scene.h"
#include "SceneQuickView.h"
#include "SimpleMarkerSymbol.h"
#include "SimpleRenderer.h"
#include <QStandardPaths>
#include <QDir>
using namespace Esri::ArcGISRuntime;
namespace
{
// Initial fixed point to observe taxi.
const Point observationPoint(-73.9853, 40.7484, 200, SpatialReference::wgs84());
// Waypoints around the block for taxi to drive.
const std::array<Point, 4> waypoints = {{
{ -73.984513, 40.748469, 2, SpatialReference::wgs84() },
{ -73.985068, 40.747786, 2, SpatialReference::wgs84() },
{ -73.983452, 40.747091, 2, SpatialReference::wgs84() },
{ -73.982961, 40.747762, 2, SpatialReference::wgs84() }
}};
// Path of Taxi 3D CAD model.
QString dolmusPath()
{
auto homepath = QStandardPaths::standardLocations(QStandardPaths::HomeLocation).last();
return QDir(homepath).filePath("ArcGIS/Runtime/Data/3D/dolmus_3ds/dolmus.3ds");
}
}
LineOfSightGeoElement::LineOfSightGeoElement(QObject* parent /* = nullptr */):
QObject(parent),
m_scene(new Scene(Basemap::imagery(this), this))
{
// create a new elevation source from Terrain3D rest service
ArcGISTiledElevationSource* elevationSource = new ArcGISTiledElevationSource(
QUrl("https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer"), this);
// add the elevation source to the scene to display elevation
m_scene->baseSurface()->elevationSources()->append(elevationSource);
// Load up the buildings that will block the line of sight.
ArcGISSceneLayer* buildings = new ArcGISSceneLayer(
QUrl("https://tiles.arcgis.com/tiles/z2tnIkrLQ2BRzr6P/arcgis/rest/services/New_York_LoD2_3D_Buildings/SceneServer/layers/0"));
m_scene->operationalLayers()->append(buildings);
// Trigger animation of taxi every 100ms.
m_animation.setInterval(100);
m_animation.callOnTimeout(this, &LineOfSightGeoElement::animate);
}
LineOfSightGeoElement::~LineOfSightGeoElement() = default;
void LineOfSightGeoElement::init()
{
// Register classes for QML
qmlRegisterType<SceneQuickView>("Esri.Samples", 1, 0, "SceneView");
qmlRegisterType<LineOfSightGeoElement>("Esri.Samples", 1, 0, "LineOfSightGeoElementSample");
}
double LineOfSightGeoElement::heightZ() const
{
if (m_observer)
{
const Point p = geometry_cast<Point>(m_observer->geometry());
return p.isValid() ? p.z() : 0.0;
}
else
{
return 0.0;
}
}
void LineOfSightGeoElement::setHeightZ(double z)
{
if (!m_observer)
return;
const Point p = geometry_cast<Point>(m_observer->geometry());
if (p.isValid())
{
PointBuilder builder(p);
builder.setZ(z);
m_observer->setGeometry(builder.toGeometry());
emit heightZChanged();
}
}
SceneQuickView* LineOfSightGeoElement::sceneView() const
{
return m_sceneView;
}
// Set the view (created in QML)
void LineOfSightGeoElement::setSceneView(SceneQuickView* sceneView)
{
if (!sceneView || sceneView == m_sceneView)
{
return;
}
m_sceneView = sceneView;
m_sceneView->setArcGISScene(m_scene);
emit sceneViewChanged();
// Setup the graphics overlay - ensure that all z-position are relative to the height of the surface.
GraphicsOverlay* graphicsOverlay = new GraphicsOverlay(this);
{
LayerSceneProperties properties = graphicsOverlay->sceneProperties();
properties.setSurfacePlacement(SurfacePlacement::Relative);
graphicsOverlay->setSceneProperties(properties);
}
m_sceneView->graphicsOverlays()->append(graphicsOverlay);
// Set up the renderer so that we can orient the taxi using the `HEADING` attribute.
SimpleRenderer* renderer3D = new SimpleRenderer(this);
{
RendererSceneProperties properties = renderer3D->sceneProperties();
properties.setHeadingExpression("[HEADING]");
renderer3D->setSceneProperties(properties);
}
graphicsOverlay->setRenderer(renderer3D);
// Create our observation point as a red sphere.
m_observer = new Graphic(observationPoint, new SimpleMarkerSymbol(SimpleMarkerSymbolStyle::Circle, Qt::red, 5.f), this);
emit heightZChanged(); // We now have a point to extract the Z-height from.
graphicsOverlay->graphics()->append(m_observer);
// Get our Taxi model. We will attempt to load it and continue our setup after it has loaded.
ModelSceneSymbol* taxiSymbol = new ModelSceneSymbol(dolmusPath(), 1.0, this);
taxiSymbol->setAnchorPosition(SceneSymbolAnchorPosition::Bottom);
connect(taxiSymbol, &ModelSceneSymbol::doneLoading, this,
[this, graphicsOverlay, taxiSymbol](Error error)
{
if (!error.isEmpty())
{
return;
}
// Create taxi from loaded taxi symbol, with an initial "HEADING" attribute for orientation.
m_taxi = new Graphic(waypoints.front(), taxiSymbol, this);
m_taxi->attributes()->insertAttribute("HEADING", 0.0);
graphicsOverlay->graphics()->append(m_taxi);
// Set up our line of sight analysis.
AnalysisOverlay* analysisOverlay = new AnalysisOverlay(this);
m_sceneView->analysisOverlays()->append(analysisOverlay);
GeoElementLineOfSight* lineOfSight = new GeoElementLineOfSight(m_observer, m_taxi, this);
analysisOverlay->analyses()->append(lineOfSight);
connect(lineOfSight, &GeoElementLineOfSight::targetVisibilityChanged, this,
[this](LineOfSightTargetVisibility targetVisibility)
{
// Select taxi whenever there is a clear line of sight from observer position.
m_taxi->setSelected(targetVisibility == LineOfSightTargetVisibility::Visible);
});
Camera camera(observationPoint, 700, -30, 45, 0);
m_sceneView->setViewpointCamera(camera, 0);
m_animation.start();
});
taxiSymbol->load();
}
void LineOfSightGeoElement::animate()
{
// Goal point to travel to
Point waypoint = waypoints.at(m_waypointIndex);
// Calculate azimuth between current location and goal location for taxi.
Point location = geometry_cast<Point>(m_taxi->geometry());
if (!location.isValid())
return;
GeodeticDistanceResult distance = GeometryEngine::distanceGeodetic(
location, waypoint, LinearUnit::meters(), AngularUnit::degrees(), GeodeticCurveType::Geodesic);
// Move taxi one metre along the line between its current position and the goal location.
QList<Point> newPoints = GeometryEngine::moveGeodetic(
{ location }, 1.0, LinearUnit::meters(), distance.azimuth1(), AngularUnit::degrees(), GeodeticCurveType::Geodesic);
if (newPoints.size() > 0)
{
location = newPoints.last();
}
// Update taxi position and orientation.
m_taxi->setGeometry(geometry_cast<Geometry>(location));
m_taxi->attributes()->replaceAttribute("HEADING", distance.azimuth1());
// When taxi is close enough to the waypoint then increment the index for a new goal next animation step.
// Index is cyclic and an element of [0, 3].
if (distance.distance() <= 2) {
m_waypointIndex = (m_waypointIndex + 1) % waypoints.size();
}
}
<commit_msg>Included missing import for mac.<commit_after>// [WriteFile Name=LineOfSightGeoElement, Category=Analysis]
// [Legal]
// Copyright 2019 Esri.
// 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.
// [Legal]
#include "LineOfSightGeoElement.h"
#include "ArcGISSceneLayer.h"
#include "ArcGISTiledElevationSource.h"
#include "GeoElementLineOfSight.h"
#include "GeometryEngine.h"
#include "GraphicsOverlay.h"
#include "ModelSceneSymbol.h"
#include "PointBuilder.h"
#include "Scene.h"
#include "SceneQuickView.h"
#include "SimpleMarkerSymbol.h"
#include "SimpleRenderer.h"
#include <array>
#include <QStandardPaths>
#include <QDir>
using namespace Esri::ArcGISRuntime;
namespace
{
// Initial fixed point to observe taxi.
const Point observationPoint(-73.9853, 40.7484, 200, SpatialReference::wgs84());
// Waypoints around the block for taxi to drive.
const std::array<Point, 4> waypoints = {{
{ -73.984513, 40.748469, 2, SpatialReference::wgs84() },
{ -73.985068, 40.747786, 2, SpatialReference::wgs84() },
{ -73.983452, 40.747091, 2, SpatialReference::wgs84() },
{ -73.982961, 40.747762, 2, SpatialReference::wgs84() }
}};
// Path of Taxi 3D CAD model.
QString dolmusPath()
{
auto homepath = QStandardPaths::standardLocations(QStandardPaths::HomeLocation).last();
return QDir(homepath).filePath("ArcGIS/Runtime/Data/3D/dolmus_3ds/dolmus.3ds");
}
}
LineOfSightGeoElement::LineOfSightGeoElement(QObject* parent /* = nullptr */):
QObject(parent),
m_scene(new Scene(Basemap::imagery(this), this))
{
// create a new elevation source from Terrain3D rest service
ArcGISTiledElevationSource* elevationSource = new ArcGISTiledElevationSource(
QUrl("https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer"), this);
// add the elevation source to the scene to display elevation
m_scene->baseSurface()->elevationSources()->append(elevationSource);
// Load up the buildings that will block the line of sight.
ArcGISSceneLayer* buildings = new ArcGISSceneLayer(
QUrl("https://tiles.arcgis.com/tiles/z2tnIkrLQ2BRzr6P/arcgis/rest/services/New_York_LoD2_3D_Buildings/SceneServer/layers/0"));
m_scene->operationalLayers()->append(buildings);
// Trigger animation of taxi every 100ms.
m_animation.setInterval(100);
m_animation.callOnTimeout(this, &LineOfSightGeoElement::animate);
}
LineOfSightGeoElement::~LineOfSightGeoElement() = default;
void LineOfSightGeoElement::init()
{
// Register classes for QML
qmlRegisterType<SceneQuickView>("Esri.Samples", 1, 0, "SceneView");
qmlRegisterType<LineOfSightGeoElement>("Esri.Samples", 1, 0, "LineOfSightGeoElementSample");
}
double LineOfSightGeoElement::heightZ() const
{
if (m_observer)
{
const Point p = geometry_cast<Point>(m_observer->geometry());
return p.isValid() ? p.z() : 0.0;
}
else
{
return 0.0;
}
}
void LineOfSightGeoElement::setHeightZ(double z)
{
if (!m_observer)
return;
const Point p = geometry_cast<Point>(m_observer->geometry());
if (p.isValid())
{
PointBuilder builder(p);
builder.setZ(z);
m_observer->setGeometry(builder.toGeometry());
emit heightZChanged();
}
}
SceneQuickView* LineOfSightGeoElement::sceneView() const
{
return m_sceneView;
}
// Set the view (created in QML)
void LineOfSightGeoElement::setSceneView(SceneQuickView* sceneView)
{
if (!sceneView || sceneView == m_sceneView)
{
return;
}
m_sceneView = sceneView;
m_sceneView->setArcGISScene(m_scene);
emit sceneViewChanged();
// Setup the graphics overlay - ensure that all z-position are relative to the height of the surface.
GraphicsOverlay* graphicsOverlay = new GraphicsOverlay(this);
{
LayerSceneProperties properties = graphicsOverlay->sceneProperties();
properties.setSurfacePlacement(SurfacePlacement::Relative);
graphicsOverlay->setSceneProperties(properties);
}
m_sceneView->graphicsOverlays()->append(graphicsOverlay);
// Set up the renderer so that we can orient the taxi using the `HEADING` attribute.
SimpleRenderer* renderer3D = new SimpleRenderer(this);
{
RendererSceneProperties properties = renderer3D->sceneProperties();
properties.setHeadingExpression("[HEADING]");
renderer3D->setSceneProperties(properties);
}
graphicsOverlay->setRenderer(renderer3D);
// Create our observation point as a red sphere.
m_observer = new Graphic(observationPoint, new SimpleMarkerSymbol(SimpleMarkerSymbolStyle::Circle, Qt::red, 5.f), this);
emit heightZChanged(); // We now have a point to extract the Z-height from.
graphicsOverlay->graphics()->append(m_observer);
// Get our Taxi model. We will attempt to load it and continue our setup after it has loaded.
ModelSceneSymbol* taxiSymbol = new ModelSceneSymbol(dolmusPath(), 1.0, this);
taxiSymbol->setAnchorPosition(SceneSymbolAnchorPosition::Bottom);
connect(taxiSymbol, &ModelSceneSymbol::doneLoading, this,
[this, graphicsOverlay, taxiSymbol](Error error)
{
if (!error.isEmpty())
{
return;
}
// Create taxi from loaded taxi symbol, with an initial "HEADING" attribute for orientation.
m_taxi = new Graphic(waypoints.front(), taxiSymbol, this);
m_taxi->attributes()->insertAttribute("HEADING", 0.0);
graphicsOverlay->graphics()->append(m_taxi);
// Set up our line of sight analysis.
AnalysisOverlay* analysisOverlay = new AnalysisOverlay(this);
m_sceneView->analysisOverlays()->append(analysisOverlay);
GeoElementLineOfSight* lineOfSight = new GeoElementLineOfSight(m_observer, m_taxi, this);
analysisOverlay->analyses()->append(lineOfSight);
connect(lineOfSight, &GeoElementLineOfSight::targetVisibilityChanged, this,
[this](LineOfSightTargetVisibility targetVisibility)
{
// Select taxi whenever there is a clear line of sight from observer position.
m_taxi->setSelected(targetVisibility == LineOfSightTargetVisibility::Visible);
});
Camera camera(observationPoint, 700, -30, 45, 0);
m_sceneView->setViewpointCamera(camera, 0);
m_animation.start();
});
taxiSymbol->load();
}
void LineOfSightGeoElement::animate()
{
// Goal point to travel to
Point waypoint = waypoints.at(m_waypointIndex);
// Calculate azimuth between current location and goal location for taxi.
Point location = geometry_cast<Point>(m_taxi->geometry());
if (!location.isValid())
return;
GeodeticDistanceResult distance = GeometryEngine::distanceGeodetic(
location, waypoint, LinearUnit::meters(), AngularUnit::degrees(), GeodeticCurveType::Geodesic);
// Move taxi one metre along the line between its current position and the goal location.
QList<Point> newPoints = GeometryEngine::moveGeodetic(
{ location }, 1.0, LinearUnit::meters(), distance.azimuth1(), AngularUnit::degrees(), GeodeticCurveType::Geodesic);
if (newPoints.size() > 0)
{
location = newPoints.last();
}
// Update taxi position and orientation.
m_taxi->setGeometry(geometry_cast<Geometry>(location));
m_taxi->attributes()->replaceAttribute("HEADING", distance.azimuth1());
// When taxi is close enough to the waypoint then increment the index for a new goal next animation step.
// Index is cyclic and an element of [0, 3].
if (distance.distance() <= 2) {
m_waypointIndex = (m_waypointIndex + 1) % waypoints.size();
}
}
<|endoftext|>
|
<commit_before>// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2014 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //
#include <limits>
#include <stdint.h>
#include <vector>
#include <gtest/gtest.h>
#include "AssertHelpers.hpp"
#include "pixel.hpp"
#include "color_conversion.hpp"
using namespace std;
using namespace DO;
// ========================================================================== //
// Define the set of integral channel types, which we will test.
typedef testing::Types<float, double> FloatingPointChannelTypes;
// ========================================================================== //
// Define the parameterized test case.
template <typename ChannelType>
class TestConvertColorConversion : public testing::Test {};
TYPED_TEST_CASE_P(TestConvertColorConversion);
// ========================================================================== //
// RGB <-> RGBA.
TEST(TestConvertColorConversionBetweenRGB, test_rgb_to_rgba)
{
Pixel<double, Rgb> rgb(1,1,1);
Pixel<double, Rgba> rgba;
convert_color(rgb, rgba);
EXPECT_EQ(Vector4d(1,1,1,1), rgba);
}
TEST(TestConvertColorConversionBetweenRGB, test_rgb_to_rgba)
{
Pixel<double, Rgba> rgba(1,1,1,1);
Pixel<double, Rgb> rgb;
convert_color(rgba, rgb);
EXPECT_EQ(Vector3d(1,1,1), rgb);
}
// ========================================================================== //
// RGB <-> grayscale.
TYPED_TEST_P(TestConvertColorConversion, test_rgb_to_gray)
{
typedef TypeParam T;
// Using the explicit function.
{
Matrix<T, 3, 1> rgb(1,1,1);
T gray;
rgb_to_gray(rgb, gray);
EXPECT_NEAR(gray, 1, T(1e-3));
}
// Using the unified API.
{
Pixel<T, Rgb> rgb(1,1,1);
T gray;
convert_color(rgb, gray);
EXPECT_NEAR(gray, 1, T(1e-3));
}
}
TYPED_TEST_P(TestConvertColorConversion, test_gray_to_rgb)
{
// Using the explicit function.
typedef TypeParam T;
{
const T src_gray = T(0.5);
const Matrix<T, 3, 1> expected_rgb(src_gray, src_gray, src_gray);
Matrix<T, 3, 1> actual_rgb;
gray_to_rgb(src_gray, actual_rgb);
EXPECT_EQ(expected_rgb, actual_rgb);
}
// Using the unified API.
{
const T src_gray = T(0.5);
const Pixel<T, Rgb> expected_rgb(src_gray, src_gray, src_gray);
Pixel<T, Rgb> actual_rgb;
convert_color(src_gray, actual_rgb);
EXPECT_EQ(expected_rgb, actual_rgb);
}
}
// ========================================================================== //
// RGB <-> YUV.
TYPED_TEST_P(TestConvertColorConversion, test_rgb_to_yuv)
{
typedef TypeParam T;
typedef Matrix<T, 3, 1> Vec3;
const Vec3 rgb[] = {
Vec3(1, 0, 0),
Vec3(0, 1, 0),
Vec3(0, 0, 1)
};
const Vec3 expected_yuv[] = {
Vec3(0.299, 0.492*(0-0.299), 0.877*(1-0.299)),
Vec3(0.587, 0.492*(0-0.587), 0.877*(0-0.587)),
Vec3(0.114, 0.492*(1-0.114), 0.877*(0-0.114))
};
// Using the explicit function.
for (int i = 0; i < 3; ++i)
{
Vec3 actual_yuv;
rgb_to_yuv(rgb[i], actual_yuv);
EXPECT_MATRIX_NEAR(expected_yuv[i], actual_yuv, T(1e-3));
}
// Using the unified API.
for (int i = 0; i < 3; ++i)
{
const Pixel<T, Rgb> rgb_pixel(rgb[i]);
const Pixel<T, Yuv> expected_yuv_pixel(expected_yuv[i]);
Pixel<T, Yuv> actual_yuv_pixel;
convert_color(rgb_pixel, actual_yuv_pixel);
EXPECT_MATRIX_NEAR(expected_yuv_pixel, actual_yuv_pixel, T(1e-3));
}
}
TYPED_TEST_P(TestConvertColorConversion, test_yuv_to_rgb)
{
typedef TypeParam T;
typedef Matrix<T, 3, 1> Vec3;
const Vec3 yuv[] = {
Vec3(1, 0 , 0 ),
Vec3(0, 0.436, 0 ),
Vec3(0, 0 , 0.615)
};
const Vec3 expected_rgb[] = {
Vec3(1 , 1 , 1 ),
Vec3(0 , -0.39465*0.436, 2.03211*0.436),
Vec3(1.13983*0.615, -0.58060*0.615, 0 )
};
// Using the explicit function.
for (int i = 0; i < 3; ++i)
{
Vec3 actual_rgb;
yuv_to_rgb(yuv[i], actual_rgb);
EXPECT_MATRIX_NEAR(expected_rgb[i], actual_rgb, T(1e-3));
}
// Using the unified API.
for (int i = 0; i < 3; ++i)
{
const Pixel<T, Yuv> yuv_pixel(yuv[i]);
const Pixel<T, Yuv> expected_rgb_pixel(expected_rgb[i]);
Pixel<T, Rgb> actual_rgb_pixel;
convert_color(yuv_pixel, actual_rgb_pixel);
EXPECT_MATRIX_NEAR(expected_rgb_pixel, actual_rgb_pixel, T(1e-3));
}
}
// ========================================================================== //
// YUV <-> Gray
TYPED_TEST_P(TestConvertColorConversion, test_yuv_to_gray)
{
typedef TypeParam T;
typedef Matrix<T, 3, 1> Vec3;
const Vec3 yuv(1, 0, 0);
{
T gray;
yuv_to_gray(yuv, gray);
EXPECT_EQ(1, gray);
}
{
Pixel<T, Yuv> yuv_pixel(yuv);
T gray;
convert_color<T, Yuv>(yuv, gray);
EXPECT_EQ(1, gray);
}
}
TYPED_TEST_P(TestConvertColorConversion, test_gray_to_yuv)
{
typedef TypeParam T;
typedef Matrix<T, 3, 1> Vec3;
T gray = T(0.5);
{
Vec3 yuv;
const Vec3 expected_yuv(0.5, 0, 0);
gray_to_yuv(gray, yuv);
EXPECT_EQ(expected_yuv, yuv);
}
{
Pixel<T, Yuv> yuv;
const Pixel<T, Yuv> expected_yuv(0.5, 0, 0);
convert_color(gray, yuv);
EXPECT_EQ(expected_yuv, yuv);
}
}
// ========================================================================== //
// Register all typed tests and instantiate them.
REGISTER_TYPED_TEST_CASE_P(TestConvertColorConversion,
test_rgb_to_gray,
test_gray_to_rgb,
test_rgb_to_yuv,
test_yuv_to_rgb,
test_yuv_to_gray,
test_gray_to_yuv);
INSTANTIATE_TYPED_TEST_CASE_P(Core_Pixel_ColorConversion,
TestConvertColorConversion,
FloatingPointChannelTypes);
// ========================================================================== //
// Run the tests.
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}<commit_msg>Fix test names.<commit_after>// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2014 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //
#include <limits>
#include <stdint.h>
#include <vector>
#include <gtest/gtest.h>
#include "AssertHelpers.hpp"
#include "pixel.hpp"
#include "color_conversion.hpp"
using namespace std;
using namespace DO;
// ========================================================================== //
// Define the set of integral channel types, which we will test.
typedef testing::Types<float, double> FloatingPointChannelTypes;
// ========================================================================== //
// Define the parameterized test case.
template <typename ChannelType>
class TestConvertColorConversion : public testing::Test {};
TYPED_TEST_CASE_P(TestConvertColorConversion);
// ========================================================================== //
// RGB <-> RGBA.
TEST(TestConvertColorConversion, test_rgb_to_rgba)
{
Pixel<double, Rgb> rgb(1,1,1);
Pixel<double, Rgba> rgba;
convert_color(rgb, rgba);
EXPECT_EQ(Vector4d(1,1,1,1), rgba);
}
TEST(TestConvertColorConversion, test_rgba_to_rgb)
{
Pixel<double, Rgba> rgba(1,1,1,1);
Pixel<double, Rgb> rgb;
convert_color(rgba, rgb);
EXPECT_EQ(Vector3d(1,1,1), rgb);
}
// ========================================================================== //
// RGB <-> grayscale.
TYPED_TEST_P(TestConvertColorConversion, test_rgb_to_gray)
{
typedef TypeParam T;
// Using the explicit function.
{
Matrix<T, 3, 1> rgb(1,1,1);
T gray;
rgb_to_gray(rgb, gray);
EXPECT_NEAR(gray, 1, T(1e-3));
}
// Using the unified API.
{
Pixel<T, Rgb> rgb(1,1,1);
T gray;
convert_color(rgb, gray);
EXPECT_NEAR(gray, 1, T(1e-3));
}
}
TYPED_TEST_P(TestConvertColorConversion, test_gray_to_rgb)
{
// Using the explicit function.
typedef TypeParam T;
{
const T src_gray = T(0.5);
const Matrix<T, 3, 1> expected_rgb(src_gray, src_gray, src_gray);
Matrix<T, 3, 1> actual_rgb;
gray_to_rgb(src_gray, actual_rgb);
EXPECT_EQ(expected_rgb, actual_rgb);
}
// Using the unified API.
{
const T src_gray = T(0.5);
const Pixel<T, Rgb> expected_rgb(src_gray, src_gray, src_gray);
Pixel<T, Rgb> actual_rgb;
convert_color(src_gray, actual_rgb);
EXPECT_EQ(expected_rgb, actual_rgb);
}
}
// ========================================================================== //
// RGB <-> YUV.
TYPED_TEST_P(TestConvertColorConversion, test_rgb_to_yuv)
{
typedef TypeParam T;
typedef Matrix<T, 3, 1> Vec3;
const Vec3 rgb[] = {
Vec3(1, 0, 0),
Vec3(0, 1, 0),
Vec3(0, 0, 1)
};
const Vec3 expected_yuv[] = {
Vec3(0.299, 0.492*(0-0.299), 0.877*(1-0.299)),
Vec3(0.587, 0.492*(0-0.587), 0.877*(0-0.587)),
Vec3(0.114, 0.492*(1-0.114), 0.877*(0-0.114))
};
// Using the explicit function.
for (int i = 0; i < 3; ++i)
{
Vec3 actual_yuv;
rgb_to_yuv(rgb[i], actual_yuv);
EXPECT_MATRIX_NEAR(expected_yuv[i], actual_yuv, T(1e-3));
}
// Using the unified API.
for (int i = 0; i < 3; ++i)
{
const Pixel<T, Rgb> rgb_pixel(rgb[i]);
const Pixel<T, Yuv> expected_yuv_pixel(expected_yuv[i]);
Pixel<T, Yuv> actual_yuv_pixel;
convert_color(rgb_pixel, actual_yuv_pixel);
EXPECT_MATRIX_NEAR(expected_yuv_pixel, actual_yuv_pixel, T(1e-3));
}
}
TYPED_TEST_P(TestConvertColorConversion, test_yuv_to_rgb)
{
typedef TypeParam T;
typedef Matrix<T, 3, 1> Vec3;
const Vec3 yuv[] = {
Vec3(1, 0 , 0 ),
Vec3(0, 0.436, 0 ),
Vec3(0, 0 , 0.615)
};
const Vec3 expected_rgb[] = {
Vec3(1 , 1 , 1 ),
Vec3(0 , -0.39465*0.436, 2.03211*0.436),
Vec3(1.13983*0.615, -0.58060*0.615, 0 )
};
// Using the explicit function.
for (int i = 0; i < 3; ++i)
{
Vec3 actual_rgb;
yuv_to_rgb(yuv[i], actual_rgb);
EXPECT_MATRIX_NEAR(expected_rgb[i], actual_rgb, T(1e-3));
}
// Using the unified API.
for (int i = 0; i < 3; ++i)
{
const Pixel<T, Yuv> yuv_pixel(yuv[i]);
const Pixel<T, Yuv> expected_rgb_pixel(expected_rgb[i]);
Pixel<T, Rgb> actual_rgb_pixel;
convert_color(yuv_pixel, actual_rgb_pixel);
EXPECT_MATRIX_NEAR(expected_rgb_pixel, actual_rgb_pixel, T(1e-3));
}
}
// ========================================================================== //
// YUV <-> Gray
TYPED_TEST_P(TestConvertColorConversion, test_yuv_to_gray)
{
typedef TypeParam T;
typedef Matrix<T, 3, 1> Vec3;
const Vec3 yuv(1, 0, 0);
{
T gray;
yuv_to_gray(yuv, gray);
EXPECT_EQ(1, gray);
}
{
Pixel<T, Yuv> yuv_pixel(yuv);
T gray;
convert_color<T, Yuv>(yuv, gray);
EXPECT_EQ(1, gray);
}
}
TYPED_TEST_P(TestConvertColorConversion, test_gray_to_yuv)
{
typedef TypeParam T;
typedef Matrix<T, 3, 1> Vec3;
T gray = T(0.5);
{
Vec3 yuv;
const Vec3 expected_yuv(0.5, 0, 0);
gray_to_yuv(gray, yuv);
EXPECT_EQ(expected_yuv, yuv);
}
{
Pixel<T, Yuv> yuv;
const Pixel<T, Yuv> expected_yuv(0.5, 0, 0);
convert_color(gray, yuv);
EXPECT_EQ(expected_yuv, yuv);
}
}
// ========================================================================== //
// Register all typed tests and instantiate them.
REGISTER_TYPED_TEST_CASE_P(TestConvertColorConversion,
test_rgb_to_gray,
test_gray_to_rgb,
test_rgb_to_yuv,
test_yuv_to_rgb,
test_yuv_to_gray,
test_gray_to_yuv);
INSTANTIATE_TYPED_TEST_CASE_P(Core_Pixel_ColorConversion,
TestConvertColorConversion,
FloatingPointChannelTypes);
// ========================================================================== //
// Run the tests.
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Popup) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionTest("popup_api")) << message_;
}
<commit_msg>Disable flaky (crashing) ExtensionApiTest.Popup<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
// This test has been disabled because it was crashing
// browsertests. crbug.com/26599
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Popup) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionTest("popup_api")) << message_;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: cacheoptions.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: ka $ $Date: 2001-04-19 12:15:57 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
//_________________________________________________________________________________________________________________
// includes
//_________________________________________________________________________________________________________________
#include "cacheoptions.hxx"
#ifndef _UTL_CONFIGMGR_HXX_
#include <unotools/configmgr.hxx>
#endif
#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
//_________________________________________________________________________________________________________________
// namespaces
//_________________________________________________________________________________________________________________
using namespace ::utl;
using namespace ::rtl;
using namespace ::osl;
using namespace ::com::sun::star::uno;
//_________________________________________________________________________________________________________________
// const
//_________________________________________________________________________________________________________________
#define ROOTNODE_START OUString(RTL_CONSTASCII_USTRINGPARAM("Office.Common/Cache" ))
#define DEFAULT_WRITEROLE 20
#define DEFAULT_DRAWINGOLE 20
#define DEFAULT_GRFMGR_TOTALSIZE 10000000
#define DEFAULT_GRFMGR_OBJECTSIZE 2400000
#define PROPERTYNAME_WRITEROLE OUString(RTL_CONSTASCII_USTRINGPARAM("Writer/OLE_Objects"))
#define PROPERTYNAME_DRAWINGOLE OUString(RTL_CONSTASCII_USTRINGPARAM("DrawingEngine/OLE_Objects"))
#define PROPERTYNAME_GRFMGR_TOTALSIZE OUString(RTL_CONSTASCII_USTRINGPARAM("GraphicManager/TotalCacheSize"))
#define PROPERTYNAME_GRFMGR_OBJECTSIZE OUString(RTL_CONSTASCII_USTRINGPARAM("GraphicManager/ObjectCacheSize"))
#define PROPERTYHANDLE_WRITEROLE 0
#define PROPERTYHANDLE_DRAWINGOLE 1
#define PROPERTYHANDLE_GRFMGR_TOTALSIZE 2
#define PROPERTYHANDLE_GRFMGR_OBJECTSIZE 3
#define PROPERTYCOUNT 4
class SvtCacheOptions_Impl : public ConfigItem
{
public:
//---------------------------------------------------------------------------------------------------------
// constructor / destructor
//---------------------------------------------------------------------------------------------------------
SvtCacheOptions_Impl();
~SvtCacheOptions_Impl();
//---------------------------------------------------------------------------------------------------------
// overloaded methods of baseclass
//---------------------------------------------------------------------------------------------------------
virtual void Commit();
//---------------------------------------------------------------------------------------------------------
// public interface
//---------------------------------------------------------------------------------------------------------
sal_Int32 GetWriterOLE_Objects() const;
sal_Int32 GetDrawingEngineOLE_Objects() const;
sal_Int32 GetGraphicManagerTotalCacheSize() const;
sal_Int32 GetGraphicManagerObjectCacheSize() const;
void SetWriterOLE_Objects( sal_Int32 nObjects );
void SetDrawingEngineOLE_Objects( sal_Int32 nObjects );
void SetGraphicManagerTotalCacheSize( sal_Int32 nTotalCacheSize );
void SetGraphicManagerObjectCacheSize( sal_Int32 nObjectCacheSize );
//-------------------------------------------------------------------------------------------------------------
// private methods
//-------------------------------------------------------------------------------------------------------------
private:
static Sequence< OUString > impl_GetPropertyNames();
//-------------------------------------------------------------------------------------------------------------
// private member
//-------------------------------------------------------------------------------------------------------------
private:
sal_Int32 mnWriterOLE;
sal_Int32 mnDrawingOLE;
sal_Int32 mnGrfMgrTotalSize;
sal_Int32 mnGrfMgrObjectSize;
};
//_________________________________________________________________________________________________________________
// definitions
//_________________________________________________________________________________________________________________
//*****************************************************************************************************************
// constructor
//*****************************************************************************************************************
SvtCacheOptions_Impl::SvtCacheOptions_Impl() :
ConfigItem( ROOTNODE_START ),
mnWriterOLE( DEFAULT_WRITEROLE ),
mnDrawingOLE( DEFAULT_DRAWINGOLE ),
mnGrfMgrTotalSize( DEFAULT_GRFMGR_TOTALSIZE ),
mnGrfMgrObjectSize( DEFAULT_GRFMGR_OBJECTSIZE )
{
Sequence< OUString > seqNames( impl_GetPropertyNames() );
Sequence< Any > seqValues = GetProperties( seqNames ) ;
DBG_ASSERT( !(seqNames.getLength()!=seqValues.getLength()), "SvtCacheOptions_Impl::SvtCacheOptions_Impl()\nI miss some values of configuration keys!\n" );
// Copy values from list in right order to ouer internal member.
sal_Int32 nPropertyCount = seqValues.getLength();
sal_Int32 nProperty = 0;
for( nProperty=0; nProperty<nPropertyCount; ++nProperty )
{
DBG_ASSERT( !(seqValues[nProperty].hasValue()==sal_False), "SvtCacheOptions_Impl::SvtCacheOptions_Impl()\nInvalid property value for property detected!\n" );
switch( nProperty )
{
case PROPERTYHANDLE_WRITEROLE:
{
if( seqValues[ nProperty ].getValueTypeClass() == TypeClass_LONG )
seqValues[nProperty] >>= mnWriterOLE;
}
break;
case PROPERTYHANDLE_DRAWINGOLE:
{
if( seqValues[ nProperty ].getValueTypeClass() == TypeClass_LONG )
seqValues[nProperty] >>= mnDrawingOLE;
}
break;
case PROPERTYHANDLE_GRFMGR_TOTALSIZE:
{
if( seqValues[ nProperty ].getValueTypeClass() == TypeClass_LONG )
seqValues[nProperty] >>= mnGrfMgrTotalSize;
}
break;
case PROPERTYHANDLE_GRFMGR_OBJECTSIZE:
{
if( seqValues[ nProperty ].getValueTypeClass() == TypeClass_LONG )
seqValues[nProperty] >>= mnGrfMgrObjectSize;
}
break;
}
}
}
//*****************************************************************************************************************
// destructor
//*****************************************************************************************************************
SvtCacheOptions_Impl::~SvtCacheOptions_Impl()
{
if( IsModified() )
Commit();
}
//*****************************************************************************************************************
// Commit
//*****************************************************************************************************************
void SvtCacheOptions_Impl::Commit()
{
Sequence< OUString > aSeqNames( impl_GetPropertyNames() );
Sequence< Any > aSeqValues( aSeqNames.getLength() );
for( sal_Int32 nProperty = 0, nCount = aSeqNames.getLength(); nProperty < nCount; ++nProperty )
{
switch( nProperty )
{
case PROPERTYHANDLE_WRITEROLE:
aSeqValues[nProperty] <<= mnWriterOLE;
break;
case PROPERTYHANDLE_DRAWINGOLE:
aSeqValues[nProperty] <<= mnDrawingOLE;
break;
case PROPERTYHANDLE_GRFMGR_TOTALSIZE:
aSeqValues[nProperty] <<= mnGrfMgrTotalSize;
break;
case PROPERTYHANDLE_GRFMGR_OBJECTSIZE:
aSeqValues[nProperty] <<= mnGrfMgrObjectSize;
break;
}
}
PutProperties( aSeqNames, aSeqValues );
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
sal_Int32 SvtCacheOptions_Impl::GetWriterOLE_Objects() const
{
return mnWriterOLE;
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
sal_Int32 SvtCacheOptions_Impl::GetDrawingEngineOLE_Objects() const
{
return mnDrawingOLE;
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
sal_Int32 SvtCacheOptions_Impl::GetGraphicManagerTotalCacheSize() const
{
return mnGrfMgrTotalSize;
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
sal_Int32 SvtCacheOptions_Impl::GetGraphicManagerObjectCacheSize() const
{
return mnGrfMgrObjectSize;
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtCacheOptions_Impl::SetWriterOLE_Objects( sal_Int32 nWriterOLE )
{
mnWriterOLE = nWriterOLE;
SetModified();
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtCacheOptions_Impl::SetDrawingEngineOLE_Objects( sal_Int32 nDrawingOLE )
{
mnDrawingOLE = nDrawingOLE;
SetModified();
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtCacheOptions_Impl::SetGraphicManagerTotalCacheSize( sal_Int32 nGrfMgrTotalSize )
{
mnGrfMgrTotalSize = nGrfMgrTotalSize;
SetModified();
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtCacheOptions_Impl::SetGraphicManagerObjectCacheSize( sal_Int32 nGrfMgrObjectSize )
{
mnGrfMgrObjectSize = nGrfMgrObjectSize;
SetModified();
}
//*****************************************************************************************************************
// private method
//*****************************************************************************************************************
Sequence< OUString > SvtCacheOptions_Impl::impl_GetPropertyNames()
{
// Build static list of configuration key names.
static const OUString pProperties[] =
{
PROPERTYNAME_WRITEROLE,
PROPERTYNAME_DRAWINGOLE,
PROPERTYNAME_GRFMGR_TOTALSIZE,
PROPERTYNAME_GRFMGR_OBJECTSIZE
};
// Initialize return sequence with these list ...
static const Sequence< OUString > seqPropertyNames( pProperties, PROPERTYCOUNT );
// ... and return it.
return seqPropertyNames;
}
//*****************************************************************************************************************
// initialize static member
// DON'T DO IT IN YOUR HEADER!
// see definition for further informations
//*****************************************************************************************************************
SvtCacheOptions_Impl* SvtCacheOptions::m_pDataContainer = NULL;
sal_Int32 SvtCacheOptions::m_nRefCount = 0;
//*****************************************************************************************************************
// constructor
//*****************************************************************************************************************
SvtCacheOptions::SvtCacheOptions()
{
// Global access, must be guarded (multithreading!).
MutexGuard aGuard( GetOwnStaticMutex() );
// Increase ouer refcount ...
++m_nRefCount;
// ... and initialize ouer data container only if it not already!
if( m_pDataContainer == NULL )
{
m_pDataContainer = new SvtCacheOptions_Impl();
}
}
//*****************************************************************************************************************
// destructor
//*****************************************************************************************************************
SvtCacheOptions::~SvtCacheOptions()
{
// Global access, must be guarded (multithreading!)
MutexGuard aGuard( GetOwnStaticMutex() );
// Decrease ouer refcount.
--m_nRefCount;
// If last instance was deleted ...
// we must destroy ouer static data container!
if( m_nRefCount <= 0 )
{
delete m_pDataContainer;
m_pDataContainer = NULL;
}
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
sal_Int32 SvtCacheOptions::GetWriterOLE_Objects() const
{
MutexGuard aGuard( GetOwnStaticMutex() );
return m_pDataContainer->GetWriterOLE_Objects();
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
sal_Int32 SvtCacheOptions::GetDrawingEngineOLE_Objects() const
{
MutexGuard aGuard( GetOwnStaticMutex() );
return m_pDataContainer->GetDrawingEngineOLE_Objects();
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
sal_Int32 SvtCacheOptions::GetGraphicManagerTotalCacheSize() const
{
MutexGuard aGuard( GetOwnStaticMutex() );
return m_pDataContainer->GetGraphicManagerTotalCacheSize();
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
sal_Int32 SvtCacheOptions::GetGraphicManagerObjectCacheSize() const
{
MutexGuard aGuard( GetOwnStaticMutex() );
return m_pDataContainer->GetGraphicManagerObjectCacheSize();
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtCacheOptions::SetWriterOLE_Objects( sal_Int32 nWriterOLE )
{
MutexGuard aGuard( GetOwnStaticMutex() );
m_pDataContainer->SetWriterOLE_Objects( nWriterOLE );
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtCacheOptions::SetDrawingEngineOLE_Objects( sal_Int32 nDrawingOLE )
{
MutexGuard aGuard( GetOwnStaticMutex() );
m_pDataContainer->SetDrawingEngineOLE_Objects( nDrawingOLE );
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtCacheOptions::SetGraphicManagerTotalCacheSize( sal_Int32 nGrfMgrTotalSize )
{
MutexGuard aGuard( GetOwnStaticMutex() );
m_pDataContainer->SetGraphicManagerTotalCacheSize( nGrfMgrTotalSize );
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtCacheOptions::SetGraphicManagerObjectCacheSize( sal_Int32 nGrfMgrObjectSize )
{
MutexGuard aGuard( GetOwnStaticMutex() );
m_pDataContainer->SetGraphicManagerObjectCacheSize( nGrfMgrObjectSize );
}
//*****************************************************************************************************************
// private method
//*****************************************************************************************************************
Mutex& SvtCacheOptions::GetOwnStaticMutex()
{
// Initialize static mutex only for one time!
static Mutex* pMutex = NULL;
// If these method first called (Mutex not already exist!) ...
if( pMutex == NULL )
{
// ... we must create a new one. Protect follow code with the global mutex -
// It must be - we create a static variable!
MutexGuard aGuard( Mutex::getGlobalMutex() );
// We must check our pointer again - because it can be that another instance of ouer class will be fastr then these!
if( pMutex == NULL )
{
// Create the new mutex and set it for return on static variable.
static Mutex aMutex;
pMutex = &aMutex;
}
}
// Return new created or already existing mutex object.
return *pMutex;
}
<commit_msg>#86165#: assertions removed<commit_after>/*************************************************************************
*
* $RCSfile: cacheoptions.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: ka $ $Date: 2001-04-19 12:24:50 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
//_________________________________________________________________________________________________________________
// includes
//_________________________________________________________________________________________________________________
#include "cacheoptions.hxx"
#ifndef _UTL_CONFIGMGR_HXX_
#include <unotools/configmgr.hxx>
#endif
#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
//_________________________________________________________________________________________________________________
// namespaces
//_________________________________________________________________________________________________________________
using namespace ::utl;
using namespace ::rtl;
using namespace ::osl;
using namespace ::com::sun::star::uno;
//_________________________________________________________________________________________________________________
// const
//_________________________________________________________________________________________________________________
#define ROOTNODE_START OUString(RTL_CONSTASCII_USTRINGPARAM("Office.Common/Cache" ))
#define DEFAULT_WRITEROLE 20
#define DEFAULT_DRAWINGOLE 20
#define DEFAULT_GRFMGR_TOTALSIZE 10000000
#define DEFAULT_GRFMGR_OBJECTSIZE 2400000
#define PROPERTYNAME_WRITEROLE OUString(RTL_CONSTASCII_USTRINGPARAM("Writer/OLE_Objects"))
#define PROPERTYNAME_DRAWINGOLE OUString(RTL_CONSTASCII_USTRINGPARAM("DrawingEngine/OLE_Objects"))
#define PROPERTYNAME_GRFMGR_TOTALSIZE OUString(RTL_CONSTASCII_USTRINGPARAM("GraphicManager/TotalCacheSize"))
#define PROPERTYNAME_GRFMGR_OBJECTSIZE OUString(RTL_CONSTASCII_USTRINGPARAM("GraphicManager/ObjectCacheSize"))
#define PROPERTYHANDLE_WRITEROLE 0
#define PROPERTYHANDLE_DRAWINGOLE 1
#define PROPERTYHANDLE_GRFMGR_TOTALSIZE 2
#define PROPERTYHANDLE_GRFMGR_OBJECTSIZE 3
#define PROPERTYCOUNT 4
class SvtCacheOptions_Impl : public ConfigItem
{
public:
//---------------------------------------------------------------------------------------------------------
// constructor / destructor
//---------------------------------------------------------------------------------------------------------
SvtCacheOptions_Impl();
~SvtCacheOptions_Impl();
//---------------------------------------------------------------------------------------------------------
// overloaded methods of baseclass
//---------------------------------------------------------------------------------------------------------
virtual void Commit();
//---------------------------------------------------------------------------------------------------------
// public interface
//---------------------------------------------------------------------------------------------------------
sal_Int32 GetWriterOLE_Objects() const;
sal_Int32 GetDrawingEngineOLE_Objects() const;
sal_Int32 GetGraphicManagerTotalCacheSize() const;
sal_Int32 GetGraphicManagerObjectCacheSize() const;
void SetWriterOLE_Objects( sal_Int32 nObjects );
void SetDrawingEngineOLE_Objects( sal_Int32 nObjects );
void SetGraphicManagerTotalCacheSize( sal_Int32 nTotalCacheSize );
void SetGraphicManagerObjectCacheSize( sal_Int32 nObjectCacheSize );
//-------------------------------------------------------------------------------------------------------------
// private methods
//-------------------------------------------------------------------------------------------------------------
private:
static Sequence< OUString > impl_GetPropertyNames();
//-------------------------------------------------------------------------------------------------------------
// private member
//-------------------------------------------------------------------------------------------------------------
private:
sal_Int32 mnWriterOLE;
sal_Int32 mnDrawingOLE;
sal_Int32 mnGrfMgrTotalSize;
sal_Int32 mnGrfMgrObjectSize;
};
//_________________________________________________________________________________________________________________
// definitions
//_________________________________________________________________________________________________________________
//*****************************************************************************************************************
// constructor
//*****************************************************************************************************************
SvtCacheOptions_Impl::SvtCacheOptions_Impl() :
ConfigItem( ROOTNODE_START ),
mnWriterOLE( DEFAULT_WRITEROLE ),
mnDrawingOLE( DEFAULT_DRAWINGOLE ),
mnGrfMgrTotalSize( DEFAULT_GRFMGR_TOTALSIZE ),
mnGrfMgrObjectSize( DEFAULT_GRFMGR_OBJECTSIZE )
{
Sequence< OUString > seqNames( impl_GetPropertyNames() );
Sequence< Any > seqValues = GetProperties( seqNames ) ;
DBG_ASSERT( !(seqNames.getLength()!=seqValues.getLength()), "SvtCacheOptions_Impl::SvtCacheOptions_Impl()\nI miss some values of configuration keys!\n" );
// Copy values from list in right order to ouer internal member.
sal_Int32 nPropertyCount = seqValues.getLength();
sal_Int32 nProperty = 0;
for( nProperty=0; nProperty<nPropertyCount; ++nProperty )
{
if( seqValues[ nProperty ].hasValue() )
{
switch( nProperty )
{
case PROPERTYHANDLE_WRITEROLE:
{
if( seqValues[ nProperty ].getValueTypeClass() == TypeClass_LONG )
seqValues[nProperty] >>= mnWriterOLE;
}
break;
case PROPERTYHANDLE_DRAWINGOLE:
{
if( seqValues[ nProperty ].getValueTypeClass() == TypeClass_LONG )
seqValues[nProperty] >>= mnDrawingOLE;
}
break;
case PROPERTYHANDLE_GRFMGR_TOTALSIZE:
{
if( seqValues[ nProperty ].getValueTypeClass() == TypeClass_LONG )
seqValues[nProperty] >>= mnGrfMgrTotalSize;
}
break;
case PROPERTYHANDLE_GRFMGR_OBJECTSIZE:
{
if( seqValues[ nProperty ].getValueTypeClass() == TypeClass_LONG )
seqValues[nProperty] >>= mnGrfMgrObjectSize;
}
break;
}
}
}
}
//*****************************************************************************************************************
// destructor
//*****************************************************************************************************************
SvtCacheOptions_Impl::~SvtCacheOptions_Impl()
{
if( IsModified() )
Commit();
}
//*****************************************************************************************************************
// Commit
//*****************************************************************************************************************
void SvtCacheOptions_Impl::Commit()
{
Sequence< OUString > aSeqNames( impl_GetPropertyNames() );
Sequence< Any > aSeqValues( aSeqNames.getLength() );
for( sal_Int32 nProperty = 0, nCount = aSeqNames.getLength(); nProperty < nCount; ++nProperty )
{
switch( nProperty )
{
case PROPERTYHANDLE_WRITEROLE:
aSeqValues[nProperty] <<= mnWriterOLE;
break;
case PROPERTYHANDLE_DRAWINGOLE:
aSeqValues[nProperty] <<= mnDrawingOLE;
break;
case PROPERTYHANDLE_GRFMGR_TOTALSIZE:
aSeqValues[nProperty] <<= mnGrfMgrTotalSize;
break;
case PROPERTYHANDLE_GRFMGR_OBJECTSIZE:
aSeqValues[nProperty] <<= mnGrfMgrObjectSize;
break;
}
}
PutProperties( aSeqNames, aSeqValues );
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
sal_Int32 SvtCacheOptions_Impl::GetWriterOLE_Objects() const
{
return mnWriterOLE;
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
sal_Int32 SvtCacheOptions_Impl::GetDrawingEngineOLE_Objects() const
{
return mnDrawingOLE;
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
sal_Int32 SvtCacheOptions_Impl::GetGraphicManagerTotalCacheSize() const
{
return mnGrfMgrTotalSize;
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
sal_Int32 SvtCacheOptions_Impl::GetGraphicManagerObjectCacheSize() const
{
return mnGrfMgrObjectSize;
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtCacheOptions_Impl::SetWriterOLE_Objects( sal_Int32 nWriterOLE )
{
mnWriterOLE = nWriterOLE;
SetModified();
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtCacheOptions_Impl::SetDrawingEngineOLE_Objects( sal_Int32 nDrawingOLE )
{
mnDrawingOLE = nDrawingOLE;
SetModified();
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtCacheOptions_Impl::SetGraphicManagerTotalCacheSize( sal_Int32 nGrfMgrTotalSize )
{
mnGrfMgrTotalSize = nGrfMgrTotalSize;
SetModified();
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtCacheOptions_Impl::SetGraphicManagerObjectCacheSize( sal_Int32 nGrfMgrObjectSize )
{
mnGrfMgrObjectSize = nGrfMgrObjectSize;
SetModified();
}
//*****************************************************************************************************************
// private method
//*****************************************************************************************************************
Sequence< OUString > SvtCacheOptions_Impl::impl_GetPropertyNames()
{
// Build static list of configuration key names.
static const OUString pProperties[] =
{
PROPERTYNAME_WRITEROLE,
PROPERTYNAME_DRAWINGOLE,
PROPERTYNAME_GRFMGR_TOTALSIZE,
PROPERTYNAME_GRFMGR_OBJECTSIZE
};
// Initialize return sequence with these list ...
static const Sequence< OUString > seqPropertyNames( pProperties, PROPERTYCOUNT );
// ... and return it.
return seqPropertyNames;
}
//*****************************************************************************************************************
// initialize static member
// DON'T DO IT IN YOUR HEADER!
// see definition for further informations
//*****************************************************************************************************************
SvtCacheOptions_Impl* SvtCacheOptions::m_pDataContainer = NULL;
sal_Int32 SvtCacheOptions::m_nRefCount = 0;
//*****************************************************************************************************************
// constructor
//*****************************************************************************************************************
SvtCacheOptions::SvtCacheOptions()
{
// Global access, must be guarded (multithreading!).
MutexGuard aGuard( GetOwnStaticMutex() );
// Increase ouer refcount ...
++m_nRefCount;
// ... and initialize ouer data container only if it not already!
if( m_pDataContainer == NULL )
{
m_pDataContainer = new SvtCacheOptions_Impl();
}
}
//*****************************************************************************************************************
// destructor
//*****************************************************************************************************************
SvtCacheOptions::~SvtCacheOptions()
{
// Global access, must be guarded (multithreading!)
MutexGuard aGuard( GetOwnStaticMutex() );
// Decrease ouer refcount.
--m_nRefCount;
// If last instance was deleted ...
// we must destroy ouer static data container!
if( m_nRefCount <= 0 )
{
delete m_pDataContainer;
m_pDataContainer = NULL;
}
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
sal_Int32 SvtCacheOptions::GetWriterOLE_Objects() const
{
MutexGuard aGuard( GetOwnStaticMutex() );
return m_pDataContainer->GetWriterOLE_Objects();
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
sal_Int32 SvtCacheOptions::GetDrawingEngineOLE_Objects() const
{
MutexGuard aGuard( GetOwnStaticMutex() );
return m_pDataContainer->GetDrawingEngineOLE_Objects();
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
sal_Int32 SvtCacheOptions::GetGraphicManagerTotalCacheSize() const
{
MutexGuard aGuard( GetOwnStaticMutex() );
return m_pDataContainer->GetGraphicManagerTotalCacheSize();
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
sal_Int32 SvtCacheOptions::GetGraphicManagerObjectCacheSize() const
{
MutexGuard aGuard( GetOwnStaticMutex() );
return m_pDataContainer->GetGraphicManagerObjectCacheSize();
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtCacheOptions::SetWriterOLE_Objects( sal_Int32 nWriterOLE )
{
MutexGuard aGuard( GetOwnStaticMutex() );
m_pDataContainer->SetWriterOLE_Objects( nWriterOLE );
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtCacheOptions::SetDrawingEngineOLE_Objects( sal_Int32 nDrawingOLE )
{
MutexGuard aGuard( GetOwnStaticMutex() );
m_pDataContainer->SetDrawingEngineOLE_Objects( nDrawingOLE );
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtCacheOptions::SetGraphicManagerTotalCacheSize( sal_Int32 nGrfMgrTotalSize )
{
MutexGuard aGuard( GetOwnStaticMutex() );
m_pDataContainer->SetGraphicManagerTotalCacheSize( nGrfMgrTotalSize );
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtCacheOptions::SetGraphicManagerObjectCacheSize( sal_Int32 nGrfMgrObjectSize )
{
MutexGuard aGuard( GetOwnStaticMutex() );
m_pDataContainer->SetGraphicManagerObjectCacheSize( nGrfMgrObjectSize );
}
//*****************************************************************************************************************
// private method
//*****************************************************************************************************************
Mutex& SvtCacheOptions::GetOwnStaticMutex()
{
// Initialize static mutex only for one time!
static Mutex* pMutex = NULL;
// If these method first called (Mutex not already exist!) ...
if( pMutex == NULL )
{
// ... we must create a new one. Protect follow code with the global mutex -
// It must be - we create a static variable!
MutexGuard aGuard( Mutex::getGlobalMutex() );
// We must check our pointer again - because it can be that another instance of ouer class will be fastr then these!
if( pMutex == NULL )
{
// Create the new mutex and set it for return on static variable.
static Mutex aMutex;
pMutex = &aMutex;
}
}
// Return new created or already existing mutex object.
return *pMutex;
}
<|endoftext|>
|
<commit_before>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* 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/yosys.h"
#include "kernel/sigtools.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct MemoryDffWorker
{
Module *module;
SigMap sigmap;
vector<Cell*> dff_cells;
dict<SigBit, SigBit> invbits;
dict<SigBit, int> sigbit_users_count;
dict<SigSpec, Cell*> mux_cells_a, mux_cells_b;
pool<Cell*> forward_merged_dffs, candidate_dffs;
pool<SigBit> init_bits;
MemoryDffWorker(Module *module) : module(module), sigmap(module)
{
for (auto wire : module->wires()) {
if (wire->attributes.count("\\init") == 0)
continue;
SigSpec sig = sigmap(wire);
Const initval = wire->attributes.count("\\init");
for (int i = 0; i < GetSize(sig) && i < GetSize(initval); i++)
if (initval[i] == State::S0 || initval[i] == State::S1)
init_bits.insert(sig[i]);
}
}
bool find_sig_before_dff(RTLIL::SigSpec &sig, RTLIL::SigSpec &clk, bool &clk_polarity, bool after = false)
{
sigmap.apply(sig);
for (auto &bit : sig)
{
if (bit.wire == NULL)
continue;
if (!after && init_bits.count(sigmap(bit)))
return false;
for (auto cell : dff_cells)
{
if (after && forward_merged_dffs.count(cell))
continue;
SigSpec this_clk = cell->getPort("\\CLK");
bool this_clk_polarity = cell->parameters["\\CLK_POLARITY"].as_bool();
if (invbits.count(this_clk)) {
this_clk = invbits.at(this_clk);
this_clk_polarity = !this_clk_polarity;
}
if (clk != RTLIL::SigSpec(RTLIL::State::Sx)) {
if (this_clk != clk)
continue;
if (this_clk_polarity != clk_polarity)
continue;
}
RTLIL::SigSpec q_norm = cell->getPort(after ? "\\D" : "\\Q");
sigmap.apply(q_norm);
RTLIL::SigSpec d = q_norm.extract(bit, &cell->getPort(after ? "\\Q" : "\\D"));
if (d.size() != 1)
continue;
if (after && init_bits.count(d))
return false;
bit = d;
clk = this_clk;
clk_polarity = this_clk_polarity;
candidate_dffs.insert(cell);
goto replaced_this_bit;
}
return false;
replaced_this_bit:;
}
return true;
}
void handle_wr_cell(RTLIL::Cell *cell)
{
log("Checking cell `%s' in module `%s': ", cell->name.c_str(), module->name.c_str());
RTLIL::SigSpec clk = RTLIL::SigSpec(RTLIL::State::Sx);
bool clk_polarity = 0;
candidate_dffs.clear();
RTLIL::SigSpec sig_addr = cell->getPort("\\ADDR");
if (!find_sig_before_dff(sig_addr, clk, clk_polarity)) {
log("no (compatible) $dff for address input found.\n");
return;
}
RTLIL::SigSpec sig_data = cell->getPort("\\DATA");
if (!find_sig_before_dff(sig_data, clk, clk_polarity)) {
log("no (compatible) $dff for data input found.\n");
return;
}
RTLIL::SigSpec sig_en = cell->getPort("\\EN");
if (!find_sig_before_dff(sig_en, clk, clk_polarity)) {
log("no (compatible) $dff for enable input found.\n");
return;
}
if (clk != RTLIL::SigSpec(RTLIL::State::Sx))
{
for (auto cell : candidate_dffs)
forward_merged_dffs.insert(cell);
cell->setPort("\\CLK", clk);
cell->setPort("\\ADDR", sig_addr);
cell->setPort("\\DATA", sig_data);
cell->setPort("\\EN", sig_en);
cell->parameters["\\CLK_ENABLE"] = RTLIL::Const(1);
cell->parameters["\\CLK_POLARITY"] = RTLIL::Const(clk_polarity);
log("merged $dff to cell.\n");
return;
}
log("no (compatible) $dff found.\n");
}
void disconnect_dff(RTLIL::SigSpec sig)
{
sigmap.apply(sig);
sig.sort_and_unify();
std::stringstream sstr;
sstr << "$memory_dff_disconnected$" << (autoidx++);
RTLIL::SigSpec new_sig = module->addWire(sstr.str(), sig.size());
for (auto cell : module->cells())
if (cell->type == "$dff") {
RTLIL::SigSpec new_q = cell->getPort("\\Q");
new_q.replace(sig, new_sig);
cell->setPort("\\Q", new_q);
}
}
void handle_rd_cell(RTLIL::Cell *cell)
{
log("Checking cell `%s' in module `%s': ", cell->name.c_str(), module->name.c_str());
bool clk_polarity = 0;
RTLIL::SigSpec clk_data = RTLIL::SigSpec(RTLIL::State::Sx);
RTLIL::SigSpec sig_data = cell->getPort("\\DATA");
for (auto bit : sigmap(sig_data))
if (sigbit_users_count[bit] > 1)
goto skip_ff_after_read_merging;
if (mux_cells_a.count(sig_data) || mux_cells_b.count(sig_data))
{
bool enable_invert = mux_cells_a.count(sig_data) != 0;
Cell *mux = enable_invert ? mux_cells_a.at(sig_data) : mux_cells_b.at(sig_data);
SigSpec check_q = sigmap(mux->getPort(enable_invert ? "\\B" : "\\A"));
sig_data = sigmap(mux->getPort("\\Y"));
for (auto bit : sig_data)
if (sigbit_users_count[bit] > 1)
goto skip_ff_after_read_merging;
if (find_sig_before_dff(sig_data, clk_data, clk_polarity, true) && clk_data != RTLIL::SigSpec(RTLIL::State::Sx) && sig_data == check_q)
{
disconnect_dff(sig_data);
cell->setPort("\\CLK", clk_data);
cell->setPort("\\EN", enable_invert ? module->LogicNot(NEW_ID, mux->getPort("\\S")) : mux->getPort("\\S"));
cell->setPort("\\DATA", sig_data);
cell->parameters["\\CLK_ENABLE"] = RTLIL::Const(1);
cell->parameters["\\CLK_POLARITY"] = RTLIL::Const(clk_polarity);
cell->parameters["\\TRANSPARENT"] = RTLIL::Const(0);
log("merged data $dff with rd enable to cell.\n");
return;
}
}
else
{
if (find_sig_before_dff(sig_data, clk_data, clk_polarity, true) && clk_data != RTLIL::SigSpec(RTLIL::State::Sx))
{
disconnect_dff(sig_data);
cell->setPort("\\CLK", clk_data);
cell->setPort("\\EN", State::S1);
cell->setPort("\\DATA", sig_data);
cell->parameters["\\CLK_ENABLE"] = RTLIL::Const(1);
cell->parameters["\\CLK_POLARITY"] = RTLIL::Const(clk_polarity);
cell->parameters["\\TRANSPARENT"] = RTLIL::Const(0);
log("merged data $dff to cell.\n");
return;
}
}
skip_ff_after_read_merging:;
RTLIL::SigSpec clk_addr = RTLIL::SigSpec(RTLIL::State::Sx);
RTLIL::SigSpec sig_addr = cell->getPort("\\ADDR");
if (find_sig_before_dff(sig_addr, clk_addr, clk_polarity) &&
clk_addr != RTLIL::SigSpec(RTLIL::State::Sx))
{
cell->setPort("\\CLK", clk_addr);
cell->setPort("\\EN", State::S1);
cell->setPort("\\ADDR", sig_addr);
cell->parameters["\\CLK_ENABLE"] = RTLIL::Const(1);
cell->parameters["\\CLK_POLARITY"] = RTLIL::Const(clk_polarity);
cell->parameters["\\TRANSPARENT"] = RTLIL::Const(1);
log("merged address $dff to cell.\n");
return;
}
log("no (compatible) $dff found.\n");
}
void run(bool flag_wr_only)
{
for (auto wire : module->wires()) {
if (wire->port_output)
for (auto bit : sigmap(wire))
sigbit_users_count[bit]++;
}
for (auto cell : module->cells()) {
if (cell->type == "$dff")
dff_cells.push_back(cell);
if (cell->type == "$mux") {
mux_cells_a[sigmap(cell->getPort("\\A"))] = cell;
mux_cells_b[sigmap(cell->getPort("\\B"))] = cell;
}
if (cell->type == "$not" || cell->type == "$_NOT_" || (cell->type == "$logic_not" && GetSize(cell->getPort("\\A")) == 1)) {
SigSpec sig_a = cell->getPort("\\A");
SigSpec sig_y = cell->getPort("\\Y");
if (cell->type == "$not")
sig_a.extend_u0(GetSize(sig_y), cell->getParam("\\A_SIGNED").as_bool());
if (cell->type == "$logic_not")
sig_y.extend_u0(1);
for (int i = 0; i < GetSize(sig_y); i++)
invbits[sig_y[i]] = sig_a[i];
}
for (auto &conn : cell->connections())
if (!cell->known() || cell->input(conn.first))
for (auto bit : sigmap(conn.second))
sigbit_users_count[bit]++;
}
for (auto cell : module->selected_cells())
if (cell->type == "$memwr" && !cell->parameters["\\CLK_ENABLE"].as_bool())
handle_wr_cell(cell);
if (!flag_wr_only)
for (auto cell : module->selected_cells())
if (cell->type == "$memrd" && !cell->parameters["\\CLK_ENABLE"].as_bool())
handle_rd_cell(cell);
}
};
struct MemoryDffPass : public Pass {
MemoryDffPass() : Pass("memory_dff", "merge input/output DFFs into memories") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" memory_dff [options] [selection]\n");
log("\n");
log("This pass detects DFFs at memory ports and merges them into the memory port.\n");
log("I.e. it consumes an asynchronous memory port and the flip-flops at its\n");
log("interface and yields a synchronous memory port.\n");
log("\n");
log(" -nordfff\n");
log(" do not merge registers on read ports\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
bool flag_wr_only = false;
log_header(design, "Executing MEMORY_DFF pass (merging $dff cells to $memrd and $memwr).\n");
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-nordff" || args[argidx] == "-wr_only") {
flag_wr_only = true;
continue;
}
break;
}
extra_args(args, argidx, design);
for (auto mod : design->selected_modules()) {
MemoryDffWorker worker(mod);
worker.run(flag_wr_only);
}
}
} MemoryDffPass;
PRIVATE_NAMESPACE_END
<commit_msg>memory_dff: Fix typo when checking init value<commit_after>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* 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/yosys.h"
#include "kernel/sigtools.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct MemoryDffWorker
{
Module *module;
SigMap sigmap;
vector<Cell*> dff_cells;
dict<SigBit, SigBit> invbits;
dict<SigBit, int> sigbit_users_count;
dict<SigSpec, Cell*> mux_cells_a, mux_cells_b;
pool<Cell*> forward_merged_dffs, candidate_dffs;
pool<SigBit> init_bits;
MemoryDffWorker(Module *module) : module(module), sigmap(module)
{
for (auto wire : module->wires()) {
if (wire->attributes.count("\\init") == 0)
continue;
SigSpec sig = sigmap(wire);
Const initval = wire->attributes.at("\\init");
for (int i = 0; i < GetSize(sig) && i < GetSize(initval); i++)
if (initval[i] == State::S0 || initval[i] == State::S1)
init_bits.insert(sig[i]);
}
}
bool find_sig_before_dff(RTLIL::SigSpec &sig, RTLIL::SigSpec &clk, bool &clk_polarity, bool after = false)
{
sigmap.apply(sig);
for (auto &bit : sig)
{
if (bit.wire == NULL)
continue;
if (!after && init_bits.count(sigmap(bit)))
return false;
for (auto cell : dff_cells)
{
if (after && forward_merged_dffs.count(cell))
continue;
SigSpec this_clk = cell->getPort("\\CLK");
bool this_clk_polarity = cell->parameters["\\CLK_POLARITY"].as_bool();
if (invbits.count(this_clk)) {
this_clk = invbits.at(this_clk);
this_clk_polarity = !this_clk_polarity;
}
if (clk != RTLIL::SigSpec(RTLIL::State::Sx)) {
if (this_clk != clk)
continue;
if (this_clk_polarity != clk_polarity)
continue;
}
RTLIL::SigSpec q_norm = cell->getPort(after ? "\\D" : "\\Q");
sigmap.apply(q_norm);
RTLIL::SigSpec d = q_norm.extract(bit, &cell->getPort(after ? "\\Q" : "\\D"));
if (d.size() != 1)
continue;
if (after && init_bits.count(d))
return false;
bit = d;
clk = this_clk;
clk_polarity = this_clk_polarity;
candidate_dffs.insert(cell);
goto replaced_this_bit;
}
return false;
replaced_this_bit:;
}
return true;
}
void handle_wr_cell(RTLIL::Cell *cell)
{
log("Checking cell `%s' in module `%s': ", cell->name.c_str(), module->name.c_str());
RTLIL::SigSpec clk = RTLIL::SigSpec(RTLIL::State::Sx);
bool clk_polarity = 0;
candidate_dffs.clear();
RTLIL::SigSpec sig_addr = cell->getPort("\\ADDR");
if (!find_sig_before_dff(sig_addr, clk, clk_polarity)) {
log("no (compatible) $dff for address input found.\n");
return;
}
RTLIL::SigSpec sig_data = cell->getPort("\\DATA");
if (!find_sig_before_dff(sig_data, clk, clk_polarity)) {
log("no (compatible) $dff for data input found.\n");
return;
}
RTLIL::SigSpec sig_en = cell->getPort("\\EN");
if (!find_sig_before_dff(sig_en, clk, clk_polarity)) {
log("no (compatible) $dff for enable input found.\n");
return;
}
if (clk != RTLIL::SigSpec(RTLIL::State::Sx))
{
for (auto cell : candidate_dffs)
forward_merged_dffs.insert(cell);
cell->setPort("\\CLK", clk);
cell->setPort("\\ADDR", sig_addr);
cell->setPort("\\DATA", sig_data);
cell->setPort("\\EN", sig_en);
cell->parameters["\\CLK_ENABLE"] = RTLIL::Const(1);
cell->parameters["\\CLK_POLARITY"] = RTLIL::Const(clk_polarity);
log("merged $dff to cell.\n");
return;
}
log("no (compatible) $dff found.\n");
}
void disconnect_dff(RTLIL::SigSpec sig)
{
sigmap.apply(sig);
sig.sort_and_unify();
std::stringstream sstr;
sstr << "$memory_dff_disconnected$" << (autoidx++);
RTLIL::SigSpec new_sig = module->addWire(sstr.str(), sig.size());
for (auto cell : module->cells())
if (cell->type == "$dff") {
RTLIL::SigSpec new_q = cell->getPort("\\Q");
new_q.replace(sig, new_sig);
cell->setPort("\\Q", new_q);
}
}
void handle_rd_cell(RTLIL::Cell *cell)
{
log("Checking cell `%s' in module `%s': ", cell->name.c_str(), module->name.c_str());
bool clk_polarity = 0;
RTLIL::SigSpec clk_data = RTLIL::SigSpec(RTLIL::State::Sx);
RTLIL::SigSpec sig_data = cell->getPort("\\DATA");
for (auto bit : sigmap(sig_data))
if (sigbit_users_count[bit] > 1)
goto skip_ff_after_read_merging;
if (mux_cells_a.count(sig_data) || mux_cells_b.count(sig_data))
{
bool enable_invert = mux_cells_a.count(sig_data) != 0;
Cell *mux = enable_invert ? mux_cells_a.at(sig_data) : mux_cells_b.at(sig_data);
SigSpec check_q = sigmap(mux->getPort(enable_invert ? "\\B" : "\\A"));
sig_data = sigmap(mux->getPort("\\Y"));
for (auto bit : sig_data)
if (sigbit_users_count[bit] > 1)
goto skip_ff_after_read_merging;
if (find_sig_before_dff(sig_data, clk_data, clk_polarity, true) && clk_data != RTLIL::SigSpec(RTLIL::State::Sx) && sig_data == check_q)
{
disconnect_dff(sig_data);
cell->setPort("\\CLK", clk_data);
cell->setPort("\\EN", enable_invert ? module->LogicNot(NEW_ID, mux->getPort("\\S")) : mux->getPort("\\S"));
cell->setPort("\\DATA", sig_data);
cell->parameters["\\CLK_ENABLE"] = RTLIL::Const(1);
cell->parameters["\\CLK_POLARITY"] = RTLIL::Const(clk_polarity);
cell->parameters["\\TRANSPARENT"] = RTLIL::Const(0);
log("merged data $dff with rd enable to cell.\n");
return;
}
}
else
{
if (find_sig_before_dff(sig_data, clk_data, clk_polarity, true) && clk_data != RTLIL::SigSpec(RTLIL::State::Sx))
{
disconnect_dff(sig_data);
cell->setPort("\\CLK", clk_data);
cell->setPort("\\EN", State::S1);
cell->setPort("\\DATA", sig_data);
cell->parameters["\\CLK_ENABLE"] = RTLIL::Const(1);
cell->parameters["\\CLK_POLARITY"] = RTLIL::Const(clk_polarity);
cell->parameters["\\TRANSPARENT"] = RTLIL::Const(0);
log("merged data $dff to cell.\n");
return;
}
}
skip_ff_after_read_merging:;
RTLIL::SigSpec clk_addr = RTLIL::SigSpec(RTLIL::State::Sx);
RTLIL::SigSpec sig_addr = cell->getPort("\\ADDR");
if (find_sig_before_dff(sig_addr, clk_addr, clk_polarity) &&
clk_addr != RTLIL::SigSpec(RTLIL::State::Sx))
{
cell->setPort("\\CLK", clk_addr);
cell->setPort("\\EN", State::S1);
cell->setPort("\\ADDR", sig_addr);
cell->parameters["\\CLK_ENABLE"] = RTLIL::Const(1);
cell->parameters["\\CLK_POLARITY"] = RTLIL::Const(clk_polarity);
cell->parameters["\\TRANSPARENT"] = RTLIL::Const(1);
log("merged address $dff to cell.\n");
return;
}
log("no (compatible) $dff found.\n");
}
void run(bool flag_wr_only)
{
for (auto wire : module->wires()) {
if (wire->port_output)
for (auto bit : sigmap(wire))
sigbit_users_count[bit]++;
}
for (auto cell : module->cells()) {
if (cell->type == "$dff")
dff_cells.push_back(cell);
if (cell->type == "$mux") {
mux_cells_a[sigmap(cell->getPort("\\A"))] = cell;
mux_cells_b[sigmap(cell->getPort("\\B"))] = cell;
}
if (cell->type == "$not" || cell->type == "$_NOT_" || (cell->type == "$logic_not" && GetSize(cell->getPort("\\A")) == 1)) {
SigSpec sig_a = cell->getPort("\\A");
SigSpec sig_y = cell->getPort("\\Y");
if (cell->type == "$not")
sig_a.extend_u0(GetSize(sig_y), cell->getParam("\\A_SIGNED").as_bool());
if (cell->type == "$logic_not")
sig_y.extend_u0(1);
for (int i = 0; i < GetSize(sig_y); i++)
invbits[sig_y[i]] = sig_a[i];
}
for (auto &conn : cell->connections())
if (!cell->known() || cell->input(conn.first))
for (auto bit : sigmap(conn.second))
sigbit_users_count[bit]++;
}
for (auto cell : module->selected_cells())
if (cell->type == "$memwr" && !cell->parameters["\\CLK_ENABLE"].as_bool())
handle_wr_cell(cell);
if (!flag_wr_only)
for (auto cell : module->selected_cells())
if (cell->type == "$memrd" && !cell->parameters["\\CLK_ENABLE"].as_bool())
handle_rd_cell(cell);
}
};
struct MemoryDffPass : public Pass {
MemoryDffPass() : Pass("memory_dff", "merge input/output DFFs into memories") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" memory_dff [options] [selection]\n");
log("\n");
log("This pass detects DFFs at memory ports and merges them into the memory port.\n");
log("I.e. it consumes an asynchronous memory port and the flip-flops at its\n");
log("interface and yields a synchronous memory port.\n");
log("\n");
log(" -nordfff\n");
log(" do not merge registers on read ports\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
bool flag_wr_only = false;
log_header(design, "Executing MEMORY_DFF pass (merging $dff cells to $memrd and $memwr).\n");
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-nordff" || args[argidx] == "-wr_only") {
flag_wr_only = true;
continue;
}
break;
}
extra_args(args, argidx, design);
for (auto mod : design->selected_modules()) {
MemoryDffWorker worker(mod);
worker.run(flag_wr_only);
}
}
} MemoryDffPass;
PRIVATE_NAMESPACE_END
<|endoftext|>
|
<commit_before>AliAnalysisTaskQASym * AddTaskQAsym(Int_t runNumber)
{
// Creates a QA task exploiting simple symmetries phi, eta +/-, charge ...
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskQAsym", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler()) {
::Error("AddTasQAsym", "This task requires an input event handler");
return NULL;
}
TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
// Configure analysis
//===========================================================================
//Task for global tracks
AliAnalysisTaskQASym *task0 = new AliAnalysisTaskQASym("AliAnalysisTaskQASym_Global");
task0->SetTrackType(0);
task0->SelectCollisionCandidates(); // default setting: kMB = min bias trigger
task0->SetNChargedRange(30,50); // comparison of different trigger settings
//Task for global tracks (high multiplicity)
AliAnalysisTaskQASym *task0HM = new AliAnalysisTaskQASym("AliAnalysisTaskQASym_Global_HighMult");
task0HM->SetTrackType(0);
task0HM->SelectCollisionCandidates(AliVEvent::kHighMult);
task0HM->SetNChargedRange(30,50);
//Task for ITS tracks
AliAnalysisTaskQASym *task1 = new AliAnalysisTaskQASym("AliAnalysisTaskQASym_ITS");
task1->SetTrackType(1);
task1->SetStandAloneTrack(kFALSE);
task1->SelectCollisionCandidates();
task1->SetNChargedRange(30,50);
//Task for ITS tracks SA
AliAnalysisTaskQASym *task1sa = new AliAnalysisTaskQASym("AliAnalysisTaskQASym_ITS_SA");
task1sa->SetTrackType(1);
task1sa->SetStandAloneTrack(kTRUE);
task1sa->SelectCollisionCandidates();
task1sa->SetNChargedRange(30,50);
//Task for TPC tracks
AliAnalysisTaskQASym *task2 = new AliAnalysisTaskQASym("AliAnalysisTaskQASym_TPC");
task2->SetTrackType(2);
task2->SelectCollisionCandidates();
task2->SetNChargedRange(30,50);
//cuts for global tracks
AliESDtrackCuts* esdTrackCutsL0 = new AliESDtrackCuts("AliESDtrackCuts0","Global");
esdTrackCutsL0->SetMinNClustersTPC(70);
esdTrackCutsL0->SetRequireTPCRefit(kTRUE);
esdTrackCutsL0->SetRequireITSRefit(kTRUE);
esdTrackCutsL0->SetMaxDCAToVertexXY(3.);
esdTrackCutsL0->SetMaxDCAToVertexZ(3.);
esdTrackCutsL0->SetAcceptKinkDaughters(kFALSE);
//cuts for ITS tracks
AliESDtrackCuts* esdTrackCutsL1 = new AliESDtrackCuts("AliESDtrackCuts1","ITS");
esdTrackCutsL1->SetMaxDCAToVertexXY(3.);
esdTrackCutsL1->SetMaxDCAToVertexZ(3.);
esdTrackCutsL1->SetAcceptKinkDaughters(kFALSE);
esdTrackCutsL1->SetRequireITSRefit(kTRUE);
esdTrackCutsL1->SetRequireITSStandAlone(kTRUE);
//cuts for ITS tracks SA
AliESDtrackCuts* esdTrackCutsL1sa = new AliESDtrackCuts("AliESDtrackCuts1","ITS_SA");
esdTrackCutsL1sa->SetMaxDCAToVertexXY(3.);
esdTrackCutsL1sa->SetMaxDCAToVertexZ(3.);
esdTrackCutsL1sa->SetAcceptKinkDaughters(kFALSE);
esdTrackCutsL1sa->SetRequireITSRefit(kTRUE);
esdTrackCutsL1sa->SetRequireITSPureStandAlone(kTRUE);
//cuts for TPC tracks
AliESDtrackCuts* esdTrackCutsL2 = new AliESDtrackCuts("AliESDtrackCuts2","TPC");
esdTrackCutsL2->SetRequireTPCRefit(kFALSE);
esdTrackCutsL2->SetAcceptKinkDaughters(kFALSE);
//jacek's cuts:
esdTrackCutsL2->SetMinNClustersTPC(70);
// cut on max ncl=160 in Task
esdTrackCutsL2->SetMaxDCAToVertexXY(3.);
esdTrackCutsL2->SetMaxDCAToVertexZ(3.);
esdTrackCutsL2->SetMaxChi2PerClusterTPC(3.999);
//cut minChi=0 in task
//esdTrackCutsL2->SetPRange(0.15,16); // not needed for QA
//esdTrackCutsL2->SetEtaRange(-0.8, 0.7999); // not needed for QA
task0->SetCuts(esdTrackCutsL0);
task0HM->SetCuts(esdTrackCutsL0);
task1->SetCuts(esdTrackCutsL1);
task1sa->SetCuts(esdTrackCutsL1sa);
task2->SetCuts(esdTrackCutsL2);
mgr->AddTask(task0);
mgr->AddTask(task0HM);
mgr->AddTask(task1);
mgr->AddTask(task1sa);
mgr->AddTask(task2);
AliAnalysisDataContainer *cout0 = 0;
AliAnalysisDataContainer *cout0HM = 0;
AliAnalysisDataContainer *cout1 = 0;
AliAnalysisDataContainer *cout1sa = 0;
AliAnalysisDataContainer *cout2 = 0;
if(runNumber>0){
cout0 = mgr->CreateContainer("QAsymHists_Global",TList::Class(),
AliAnalysisManager::kOutputContainer, Form("run%d.root",runNumber));
cout0HM = mgr->CreateContainer("QAsymHists_Global_HighMult",TList::Class(),
AliAnalysisManager::kOutputContainer, Form("run%d.root",runNumber));
cout1 = mgr->CreateContainer("QAsymHists_ITS",TList::Class(),
AliAnalysisManager::kOutputContainer, Form("run%d.root",runNumber));
cout1sa = mgr->CreateContainer("QAsymHists_ITS_SA",TList::Class(),
AliAnalysisManager::kOutputContainer, Form("run%d.root",runNumber));
cout2 = mgr->CreateContainer("QAsymHists_TPC",TList::Class(),
AliAnalysisManager::kOutputContainer, Form("run%d.root",runNumber));
}
else{
cout0 = mgr->CreateContainer("QAsymHists_Global",TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:PWG1_QAsymHists",AliAnalysisManager::GetCommonFileName()));
cout0HM = mgr->CreateContainer("QAsymHists_Global_HighMult",TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:PWG1_QAsymHists",AliAnalysisManager::GetCommonFileName()));
cout1 = mgr->CreateContainer("QAsymHists_ITS",TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:PWG1_QAsymHists",AliAnalysisManager::GetCommonFileName()));
cout1sa = mgr->CreateContainer("QAsymHists_ITS_SA",TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:PWG1_QAsymHists",AliAnalysisManager::GetCommonFileName()));
cout2 = mgr->CreateContainer("QAsymHists_TPC",TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:PWG1_QAsymHists",AliAnalysisManager::GetCommonFileName()));
}
mgr->ConnectInput (task0, 0, mgr->GetCommonInputContainer());
mgr->ConnectInput (task0HM, 0, mgr->GetCommonInputContainer());
mgr->ConnectInput (task1, 0, mgr->GetCommonInputContainer());
mgr->ConnectInput (task1sa, 0, mgr->GetCommonInputContainer());
mgr->ConnectInput (task2, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput (task0, 1, cout0);
mgr->ConnectOutput (task0HM, 1, cout0HM);
mgr->ConnectOutput (task1, 1, cout1);
mgr->ConnectOutput (task1sa, 1, cout1sa);
mgr->ConnectOutput (task2, 1, cout2);
return task0;
}
<commit_msg>Allow to pass trigger mask value as parameter to AddTaskQAsym<commit_after>AliAnalysisTaskQASym * AddTaskQAsym(Int_t runNumber, UInt_t maskMB, UInt_t maskHM)
{
// Creates a QA task exploiting simple symmetries phi, eta +/-, charge ...
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskQAsym", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler()) {
::Error("AddTasQAsym", "This task requires an input event handler");
return NULL;
}
TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
// Configure analysis
//===========================================================================
//Task for global tracks
AliAnalysisTaskQASym *task0 = new AliAnalysisTaskQASym("AliAnalysisTaskQASym_Global");
task0->SetTrackType(0);
task0->SelectCollisionCandidates(maskMB); // default setting: kMB = min bias trigger
task0->SetNChargedRange(30,50); // comparison of different trigger settings
//Task for global tracks (high multiplicity)
AliAnalysisTaskQASym *task0HM = new AliAnalysisTaskQASym("AliAnalysisTaskQASym_Global_HighMult");
task0HM->SetTrackType(0);
task0HM->SelectCollisionCandidates(maskHM);
task0HM->SetNChargedRange(30,50);
//Task for ITS tracks
AliAnalysisTaskQASym *task1 = new AliAnalysisTaskQASym("AliAnalysisTaskQASym_ITS");
task1->SetTrackType(1);
task1->SetStandAloneTrack(kFALSE);
task1->SelectCollisionCandidates(maskMB);
task1->SetNChargedRange(30,50);
//Task for ITS tracks SA
AliAnalysisTaskQASym *task1sa = new AliAnalysisTaskQASym("AliAnalysisTaskQASym_ITS_SA");
task1sa->SetTrackType(1);
task1sa->SetStandAloneTrack(kTRUE);
task1sa->SelectCollisionCandidates(maskMB);
task1sa->SetNChargedRange(30,50);
//Task for TPC tracks
AliAnalysisTaskQASym *task2 = new AliAnalysisTaskQASym("AliAnalysisTaskQASym_TPC");
task2->SetTrackType(2);
task2->SelectCollisionCandidates(maskMB);
task2->SetNChargedRange(30,50);
//cuts for global tracks
AliESDtrackCuts* esdTrackCutsL0 = new AliESDtrackCuts("AliESDtrackCuts0","Global");
esdTrackCutsL0->SetMinNClustersTPC(70);
esdTrackCutsL0->SetRequireTPCRefit(kTRUE);
esdTrackCutsL0->SetRequireITSRefit(kTRUE);
esdTrackCutsL0->SetMaxDCAToVertexXY(3.);
esdTrackCutsL0->SetMaxDCAToVertexZ(3.);
esdTrackCutsL0->SetAcceptKinkDaughters(kFALSE);
//cuts for ITS tracks
AliESDtrackCuts* esdTrackCutsL1 = new AliESDtrackCuts("AliESDtrackCuts1","ITS");
esdTrackCutsL1->SetMaxDCAToVertexXY(3.);
esdTrackCutsL1->SetMaxDCAToVertexZ(3.);
esdTrackCutsL1->SetAcceptKinkDaughters(kFALSE);
esdTrackCutsL1->SetRequireITSRefit(kTRUE);
esdTrackCutsL1->SetRequireITSStandAlone(kTRUE);
//cuts for ITS tracks SA
AliESDtrackCuts* esdTrackCutsL1sa = new AliESDtrackCuts("AliESDtrackCuts1sa","ITS_SA");
esdTrackCutsL1sa->SetMaxDCAToVertexXY(3.);
esdTrackCutsL1sa->SetMaxDCAToVertexZ(3.);
esdTrackCutsL1sa->SetAcceptKinkDaughters(kFALSE);
esdTrackCutsL1sa->SetRequireITSRefit(kTRUE);
esdTrackCutsL1sa->SetRequireITSPureStandAlone(kTRUE);
//cuts for TPC tracks
AliESDtrackCuts* esdTrackCutsL2 = new AliESDtrackCuts("AliESDtrackCuts2","TPC");
esdTrackCutsL2->SetRequireTPCRefit(kFALSE);
esdTrackCutsL2->SetAcceptKinkDaughters(kFALSE);
//jacek's cuts:
esdTrackCutsL2->SetMinNClustersTPC(70);
// cut on max ncl=160 in Task
esdTrackCutsL2->SetMaxDCAToVertexXY(3.);
esdTrackCutsL2->SetMaxDCAToVertexZ(3.);
esdTrackCutsL2->SetMaxChi2PerClusterTPC(3.999);
//cut minChi=0 in task
//esdTrackCutsL2->SetPRange(0.15,16); // not needed for QA
//esdTrackCutsL2->SetEtaRange(-0.8, 0.7999); // not needed for QA
task0->SetCuts(esdTrackCutsL0);
task0HM->SetCuts(esdTrackCutsL0);
task1->SetCuts(esdTrackCutsL1);
task1sa->SetCuts(esdTrackCutsL1sa);
task2->SetCuts(esdTrackCutsL2);
mgr->AddTask(task0);
mgr->AddTask(task0HM);
mgr->AddTask(task1);
mgr->AddTask(task1sa);
mgr->AddTask(task2);
AliAnalysisDataContainer *cout0 = 0;
AliAnalysisDataContainer *cout0HM = 0;
AliAnalysisDataContainer *cout1 = 0;
AliAnalysisDataContainer *cout1sa = 0;
AliAnalysisDataContainer *cout2 = 0;
if(runNumber>0){
cout0 = mgr->CreateContainer("QAsymHists_Global",TList::Class(),
AliAnalysisManager::kOutputContainer, Form("run%d.root",runNumber));
cout0HM = mgr->CreateContainer("QAsymHists_Global_HighMult",TList::Class(),
AliAnalysisManager::kOutputContainer, Form("run%d.root",runNumber));
cout1 = mgr->CreateContainer("QAsymHists_ITS",TList::Class(),
AliAnalysisManager::kOutputContainer, Form("run%d.root",runNumber));
cout1sa = mgr->CreateContainer("QAsymHists_ITS_SA",TList::Class(),
AliAnalysisManager::kOutputContainer, Form("run%d.root",runNumber));
cout2 = mgr->CreateContainer("QAsymHists_TPC",TList::Class(),
AliAnalysisManager::kOutputContainer, Form("run%d.root",runNumber));
}
else{
cout0 = mgr->CreateContainer("QAsymHists_Global",TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:PWG1_QAsymHists",AliAnalysisManager::GetCommonFileName()));
cout0HM = mgr->CreateContainer("QAsymHists_Global_HighMult",TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:PWG1_QAsymHists",AliAnalysisManager::GetCommonFileName()));
cout1 = mgr->CreateContainer("QAsymHists_ITS",TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:PWG1_QAsymHists",AliAnalysisManager::GetCommonFileName()));
cout1sa = mgr->CreateContainer("QAsymHists_ITS_SA",TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:PWG1_QAsymHists",AliAnalysisManager::GetCommonFileName()));
cout2 = mgr->CreateContainer("QAsymHists_TPC",TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:PWG1_QAsymHists",AliAnalysisManager::GetCommonFileName()));
}
mgr->ConnectInput (task0, 0, mgr->GetCommonInputContainer());
mgr->ConnectInput (task0HM, 0, mgr->GetCommonInputContainer());
mgr->ConnectInput (task1, 0, mgr->GetCommonInputContainer());
mgr->ConnectInput (task1sa, 0, mgr->GetCommonInputContainer());
mgr->ConnectInput (task2, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput (task0, 1, cout0);
mgr->ConnectOutput (task0HM, 1, cout0HM);
mgr->ConnectOutput (task1, 1, cout1);
mgr->ConnectOutput (task1sa, 1, cout1sa);
mgr->ConnectOutput (task2, 1, cout2);
return task0;
}
<|endoftext|>
|
<commit_before>/** @file
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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.
*/
////////////////////////////////////////////////////////////////////////////////
// collapsed_forwarding::
//
// ATS plugin to allow collapsed forwarding of concurrent requests for the same
// object. This plugin is based on open_write_fail_action feature, which detects
// cache open write failure on a cache miss and returns a 502 error along with a
// special @-header indicating the reason for 502 error. The plugin acts on the
// error by using an internal redirect follow back to itself, essentially blocking
// the request until a response arrives, at which point, relies on read-while-writer
// feature to start downloading the object to all waiting clients. The following
// config parameters are assumed to be set for this plugin to work:
////////////////////////////////////////////////////////////////////////////////////
// proxy.config.http.cache.open_write_fail_action 1 /////////////////////////
// proxy.config.cache.enable_read_while_writer 1 /////////////////////////
// proxy.config.http.redirection_enabled 1 /////////////////////////
// proxy.config.http.number_of_redirections 10 /////////////////////////
// proxy.config.http.redirect_use_orig_cache_key 1 /////////////////////////
// proxy.config.http.background_fill_active_timeout 0 /////////////////////////
// proxy.config.http.background_fill_completed_threshold 0 /////////////////////////
////////////////////////////////////////////////////////////////////////////////////
// Additionally, given that collapsed forwarding works based on cache write
// lock failure detection, the plugin requires cache to be enabled and ready.
// On a restart, Traffic Server typically takes a few seconds to initialize
// the cache depending on the cache size and number of dirents. While the
// cache is not ready yet, collapsed forwarding can not detect the write lock
// contention and so can not work. The setting proxy.config.http.wait_for_cache
// may be enabled which allows blocking incoming connections from being
// accepted until cache is ready.
////////////////////////////////////////////////////////////////////////////////////
// This plugin currently supports only per-remap mode activation.
////////////////////////////////////////////////////////////////////////////////////
#include <sys/time.h>
#include <ts/ts.h>
#include <ts/remap.h>
#include <set>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <stdarg.h>
#include <getopt.h>
#include <netdb.h>
#include <map>
static const char *DEBUG_TAG = (char *)"collapsed_forwarding";
static const char *LOCATION_HEADER = "Location";
static const char *REDIRECT_REASON = "See Other";
static const char *ATS_INTERNAL_MESSAGE = "@Ats-Internal";
static int OPEN_WRITE_FAIL_MAX_REQ_DELAY_RETRIES = 5;
static int OPEN_WRITE_FAIL_REQ_DELAY_TIMEOUT = 500;
typedef struct _RequestData {
TSHttpTxn txnp;
int wl_retry; // write lock failure retry count
std::string req_url;
} RequestData;
static int
add_redirect_header(TSMBuffer &bufp, TSMLoc &hdr_loc, const std::string &location)
{
// This is needed in case the response already contains a Location header
TSMLoc field_loc = TSMimeHdrFieldFind(bufp, hdr_loc, LOCATION_HEADER, strlen(LOCATION_HEADER));
if (field_loc == TS_NULL_MLOC) {
TSMimeHdrFieldCreateNamed(bufp, hdr_loc, LOCATION_HEADER, strlen(LOCATION_HEADER), &field_loc);
}
if (TS_SUCCESS == TSMimeHdrFieldValueStringSet(bufp, hdr_loc, field_loc, -1, location.c_str(), location.size())) {
TSDebug(DEBUG_TAG, "Adding Location header %s", LOCATION_HEADER);
TSMimeHdrFieldAppend(bufp, hdr_loc, field_loc);
}
TSHandleMLocRelease(bufp, hdr_loc, field_loc);
TSHttpHdrStatusSet(bufp, hdr_loc, TS_HTTP_STATUS_SEE_OTHER);
TSHttpHdrReasonSet(bufp, hdr_loc, REDIRECT_REASON, strlen(REDIRECT_REASON));
return TS_SUCCESS;
}
static bool
check_internal_message_hdr(TSHttpTxn &txnp)
{
TSMBuffer bufp;
TSMLoc hdr_loc;
bool found = false;
if (TSHttpTxnClientRespGet(txnp, &bufp, &hdr_loc) != TS_SUCCESS) {
TSError("check_internal_message_hdr: couldn't retrieve client response header");
return false;
}
TSMLoc header_loc = TSMimeHdrFieldFind(bufp, hdr_loc, ATS_INTERNAL_MESSAGE, strlen(ATS_INTERNAL_MESSAGE));
if (header_loc) {
found = true;
// found the header, remove it now..
TSMimeHdrFieldDestroy(bufp, hdr_loc, header_loc);
TSHandleMLocRelease(bufp, hdr_loc, header_loc);
}
TSHandleMLocRelease(bufp, TS_NULL_MLOC, hdr_loc);
return found;
}
static int
on_OS_DNS(const RequestData *req, TSHttpTxn &txnp)
{
if (req->wl_retry > 0) {
TSDebug(DEBUG_TAG, "OS_DNS request delayed %d times, block origin req for url: %s", req->wl_retry, req->req_url.c_str());
TSHttpTxnReenable(txnp, TS_EVENT_HTTP_ERROR);
return TS_SUCCESS;
}
TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);
return TS_SUCCESS;
}
static int
on_send_request_header(const RequestData *req, TSHttpTxn &txnp)
{
if (req->wl_retry > 0) {
TSDebug(DEBUG_TAG, "Send_Req request delayed %d times, block origin req for url: %s", req->wl_retry, req->req_url.c_str());
TSHttpTxnReenable(txnp, TS_EVENT_HTTP_ERROR);
return TS_SUCCESS;
}
TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);
return TS_SUCCESS;
}
static int
on_read_response_header(TSHttpTxn &txnp)
{
TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);
return TS_SUCCESS;
}
static int
on_immediate(RequestData *req, TSCont &contp)
{
if (!req) {
TSError("%s: invalid req_data", DEBUG_TAG);
return TS_SUCCESS;
}
TSDebug(DEBUG_TAG, "continuation delayed, scheduling now..for url: %s", req->req_url.c_str());
// add retry_done header to prevent looping
std::string value;
TSMBuffer bufp;
TSMLoc hdr_loc;
if (TSHttpTxnClientRespGet(req->txnp, &bufp, &hdr_loc) != TS_SUCCESS) {
TSError("plugin=%s, level=error, error_code=could_not_retrieve_client_response_header for url %s", DEBUG_TAG,
req->req_url.c_str());
TSHttpTxnReenable(req->txnp, TS_EVENT_HTTP_ERROR);
return TS_SUCCESS;
}
add_redirect_header(bufp, hdr_loc, req->req_url);
TSHandleMLocRelease(bufp, TS_NULL_MLOC, hdr_loc);
TSHttpTxnReenable(req->txnp, TS_EVENT_HTTP_CONTINUE);
return TS_SUCCESS;
}
static int
on_send_response_header(RequestData *req, TSHttpTxn &txnp, TSCont &contp)
{
TSMBuffer bufp;
TSMLoc hdr_loc;
if (TSHttpTxnClientRespGet(txnp, &bufp, &hdr_loc) != TS_SUCCESS) {
TSError("plugin=%s, level=error, error_code=could_not_retrieve_client_response_header", DEBUG_TAG);
return TS_SUCCESS;
}
TSHttpStatus status = TSHttpHdrStatusGet(bufp, hdr_loc);
TSDebug(DEBUG_TAG, "Response code: %d", status);
if ((status == TS_HTTP_STATUS_BAD_GATEWAY) || (status == TS_HTTP_STATUS_SEE_OTHER) ||
status == TS_HTTP_STATUS_INTERNAL_SERVER_ERROR) {
bool is_internal_message_hdr = check_internal_message_hdr(txnp);
bool delay_request =
is_internal_message_hdr || ((req->wl_retry > 0) && (req->wl_retry < OPEN_WRITE_FAIL_MAX_REQ_DELAY_RETRIES));
if (delay_request) {
req->wl_retry++;
TSDebug(DEBUG_TAG, "delaying request, url@%p: {{%s}} on retry: %d time", txnp, req->req_url.c_str(), req->wl_retry);
TSContSchedule(contp, OPEN_WRITE_FAIL_REQ_DELAY_TIMEOUT, TS_THREAD_POOL_TASK);
TSHandleMLocRelease(bufp, TS_NULL_MLOC, hdr_loc);
return TS_SUCCESS;
}
}
if (req->wl_retry > 0) {
TSDebug(DEBUG_TAG, "request delayed, but unsuccessful, url@%p: {{%s}} on retry: %d time", txnp, req->req_url.c_str(),
req->wl_retry);
req->wl_retry = 0;
}
// done..cleanup
delete req;
TSContDestroy(contp);
TSHandleMLocRelease(bufp, TS_NULL_MLOC, hdr_loc);
TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);
return TS_SUCCESS;
}
static int
collapsed_cont(TSCont contp, TSEvent event, void *edata)
{
TSHttpTxn txnp = static_cast<TSHttpTxn>(edata);
RequestData *my_req = static_cast<RequestData *>(TSContDataGet(contp));
switch (event) {
case TS_EVENT_HTTP_OS_DNS: {
return on_OS_DNS(my_req, txnp);
}
case TS_EVENT_HTTP_SEND_REQUEST_HDR: {
return on_send_request_header(my_req, txnp);
}
case TS_EVENT_HTTP_READ_RESPONSE_HDR: {
return on_read_response_header(txnp);
}
case TS_EVENT_IMMEDIATE:
case TS_EVENT_TIMEOUT: {
return on_immediate(my_req, contp);
}
case TS_EVENT_HTTP_SEND_RESPONSE_HDR: {
return on_send_response_header(my_req, txnp, contp);
}
default: {
TSDebug(DEBUG_TAG, "Unexpected event: %d", event);
break;
}
}
TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);
return TS_SUCCESS;
}
TSReturnCode
TSRemapInit(TSRemapInterface * /* api_info */, char * /* errbuf */, int /* errbuf_size */)
{
TSDebug(DEBUG_TAG, "plugin is succesfully initialized");
return TS_SUCCESS;
}
TSReturnCode
TSRemapNewInstance(int argc, char *argv[], void ** /* ih */, char * /* errbuf */, int /* errbuf_size */)
{
// basic argv processing..
for (int i = 2; i < argc; ++i) {
if (strncmp(argv[i], "--delay=", 8) == 0) {
OPEN_WRITE_FAIL_REQ_DELAY_TIMEOUT = atoi((char *)(argv[i] + 8));
} else if (strncmp(argv[i], "--retries=", 10) == 0) {
OPEN_WRITE_FAIL_MAX_REQ_DELAY_RETRIES = atoi((char *)(argv[i] + 10));
}
}
return TS_SUCCESS;
}
TSRemapStatus
TSRemapDoRemap(void *ih, TSHttpTxn rh, TSRemapRequestInfo *rri)
{
TSCont cont = TSContCreate(collapsed_cont, TSMutexCreate());
RequestData *req_data = new RequestData();
req_data->txnp = rh;
req_data->wl_retry = 0;
int url_len = 0;
char *url = TSHttpTxnEffectiveUrlStringGet(rh, &url_len);
req_data->req_url.assign(url, url_len);
TSfree(url);
TSContDataSet(cont, req_data);
TSHttpTxnHookAdd(rh, TS_HTTP_SEND_REQUEST_HDR_HOOK, cont);
TSHttpTxnHookAdd(rh, TS_HTTP_SEND_RESPONSE_HDR_HOOK, cont);
TSHttpTxnHookAdd(rh, TS_HTTP_READ_RESPONSE_HDR_HOOK, cont);
TSHttpTxnHookAdd(rh, TS_HTTP_OS_DNS_HOOK, cont);
return TSREMAP_DID_REMAP;
}
<commit_msg>TS-4888: Modified collapsed_forwarding plugin to return TSREMAP_NO_REMAP.<commit_after>/** @file
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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.
*/
////////////////////////////////////////////////////////////////////////////////
// collapsed_forwarding::
//
// ATS plugin to allow collapsed forwarding of concurrent requests for the same
// object. This plugin is based on open_write_fail_action feature, which detects
// cache open write failure on a cache miss and returns a 502 error along with a
// special @-header indicating the reason for 502 error. The plugin acts on the
// error by using an internal redirect follow back to itself, essentially blocking
// the request until a response arrives, at which point, relies on read-while-writer
// feature to start downloading the object to all waiting clients. The following
// config parameters are assumed to be set for this plugin to work:
////////////////////////////////////////////////////////////////////////////////////
// proxy.config.http.cache.open_write_fail_action 1 /////////////////////////
// proxy.config.cache.enable_read_while_writer 1 /////////////////////////
// proxy.config.http.redirection_enabled 1 /////////////////////////
// proxy.config.http.number_of_redirections 10 /////////////////////////
// proxy.config.http.redirect_use_orig_cache_key 1 /////////////////////////
// proxy.config.http.background_fill_active_timeout 0 /////////////////////////
// proxy.config.http.background_fill_completed_threshold 0 /////////////////////////
////////////////////////////////////////////////////////////////////////////////////
// Additionally, given that collapsed forwarding works based on cache write
// lock failure detection, the plugin requires cache to be enabled and ready.
// On a restart, Traffic Server typically takes a few seconds to initialize
// the cache depending on the cache size and number of dirents. While the
// cache is not ready yet, collapsed forwarding can not detect the write lock
// contention and so can not work. The setting proxy.config.http.wait_for_cache
// may be enabled which allows blocking incoming connections from being
// accepted until cache is ready.
////////////////////////////////////////////////////////////////////////////////////
// This plugin currently supports only per-remap mode activation.
////////////////////////////////////////////////////////////////////////////////////
#include <sys/time.h>
#include <ts/ts.h>
#include <ts/remap.h>
#include <set>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <stdarg.h>
#include <getopt.h>
#include <netdb.h>
#include <map>
static const char *DEBUG_TAG = (char *)"collapsed_forwarding";
static const char *LOCATION_HEADER = "Location";
static const char *REDIRECT_REASON = "See Other";
static const char *ATS_INTERNAL_MESSAGE = "@Ats-Internal";
static int OPEN_WRITE_FAIL_MAX_REQ_DELAY_RETRIES = 5;
static int OPEN_WRITE_FAIL_REQ_DELAY_TIMEOUT = 500;
typedef struct _RequestData {
TSHttpTxn txnp;
int wl_retry; // write lock failure retry count
std::string req_url;
} RequestData;
static int
add_redirect_header(TSMBuffer &bufp, TSMLoc &hdr_loc, const std::string &location)
{
// This is needed in case the response already contains a Location header
TSMLoc field_loc = TSMimeHdrFieldFind(bufp, hdr_loc, LOCATION_HEADER, strlen(LOCATION_HEADER));
if (field_loc == TS_NULL_MLOC) {
TSMimeHdrFieldCreateNamed(bufp, hdr_loc, LOCATION_HEADER, strlen(LOCATION_HEADER), &field_loc);
}
if (TS_SUCCESS == TSMimeHdrFieldValueStringSet(bufp, hdr_loc, field_loc, -1, location.c_str(), location.size())) {
TSDebug(DEBUG_TAG, "Adding Location header %s", LOCATION_HEADER);
TSMimeHdrFieldAppend(bufp, hdr_loc, field_loc);
}
TSHandleMLocRelease(bufp, hdr_loc, field_loc);
TSHttpHdrStatusSet(bufp, hdr_loc, TS_HTTP_STATUS_SEE_OTHER);
TSHttpHdrReasonSet(bufp, hdr_loc, REDIRECT_REASON, strlen(REDIRECT_REASON));
return TS_SUCCESS;
}
static bool
check_internal_message_hdr(TSHttpTxn &txnp)
{
TSMBuffer bufp;
TSMLoc hdr_loc;
bool found = false;
if (TSHttpTxnClientRespGet(txnp, &bufp, &hdr_loc) != TS_SUCCESS) {
TSError("check_internal_message_hdr: couldn't retrieve client response header");
return false;
}
TSMLoc header_loc = TSMimeHdrFieldFind(bufp, hdr_loc, ATS_INTERNAL_MESSAGE, strlen(ATS_INTERNAL_MESSAGE));
if (header_loc) {
found = true;
// found the header, remove it now..
TSMimeHdrFieldDestroy(bufp, hdr_loc, header_loc);
TSHandleMLocRelease(bufp, hdr_loc, header_loc);
}
TSHandleMLocRelease(bufp, TS_NULL_MLOC, hdr_loc);
return found;
}
static int
on_OS_DNS(const RequestData *req, TSHttpTxn &txnp)
{
if (req->wl_retry > 0) {
TSDebug(DEBUG_TAG, "OS_DNS request delayed %d times, block origin req for url: %s", req->wl_retry, req->req_url.c_str());
TSHttpTxnReenable(txnp, TS_EVENT_HTTP_ERROR);
return TS_SUCCESS;
}
TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);
return TS_SUCCESS;
}
static int
on_send_request_header(const RequestData *req, TSHttpTxn &txnp)
{
if (req->wl_retry > 0) {
TSDebug(DEBUG_TAG, "Send_Req request delayed %d times, block origin req for url: %s", req->wl_retry, req->req_url.c_str());
TSHttpTxnReenable(txnp, TS_EVENT_HTTP_ERROR);
return TS_SUCCESS;
}
TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);
return TS_SUCCESS;
}
static int
on_read_response_header(TSHttpTxn &txnp)
{
TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);
return TS_SUCCESS;
}
static int
on_immediate(RequestData *req, TSCont &contp)
{
if (!req) {
TSError("%s: invalid req_data", DEBUG_TAG);
return TS_SUCCESS;
}
TSDebug(DEBUG_TAG, "continuation delayed, scheduling now..for url: %s", req->req_url.c_str());
// add retry_done header to prevent looping
std::string value;
TSMBuffer bufp;
TSMLoc hdr_loc;
if (TSHttpTxnClientRespGet(req->txnp, &bufp, &hdr_loc) != TS_SUCCESS) {
TSError("plugin=%s, level=error, error_code=could_not_retrieve_client_response_header for url %s", DEBUG_TAG,
req->req_url.c_str());
TSHttpTxnReenable(req->txnp, TS_EVENT_HTTP_ERROR);
return TS_SUCCESS;
}
add_redirect_header(bufp, hdr_loc, req->req_url);
TSHandleMLocRelease(bufp, TS_NULL_MLOC, hdr_loc);
TSHttpTxnReenable(req->txnp, TS_EVENT_HTTP_CONTINUE);
return TS_SUCCESS;
}
static int
on_send_response_header(RequestData *req, TSHttpTxn &txnp, TSCont &contp)
{
TSMBuffer bufp;
TSMLoc hdr_loc;
if (TSHttpTxnClientRespGet(txnp, &bufp, &hdr_loc) != TS_SUCCESS) {
TSError("plugin=%s, level=error, error_code=could_not_retrieve_client_response_header", DEBUG_TAG);
return TS_SUCCESS;
}
TSHttpStatus status = TSHttpHdrStatusGet(bufp, hdr_loc);
TSDebug(DEBUG_TAG, "Response code: %d", status);
if ((status == TS_HTTP_STATUS_BAD_GATEWAY) || (status == TS_HTTP_STATUS_SEE_OTHER) ||
status == TS_HTTP_STATUS_INTERNAL_SERVER_ERROR) {
bool is_internal_message_hdr = check_internal_message_hdr(txnp);
bool delay_request =
is_internal_message_hdr || ((req->wl_retry > 0) && (req->wl_retry < OPEN_WRITE_FAIL_MAX_REQ_DELAY_RETRIES));
if (delay_request) {
req->wl_retry++;
TSDebug(DEBUG_TAG, "delaying request, url@%p: {{%s}} on retry: %d time", txnp, req->req_url.c_str(), req->wl_retry);
TSContSchedule(contp, OPEN_WRITE_FAIL_REQ_DELAY_TIMEOUT, TS_THREAD_POOL_TASK);
TSHandleMLocRelease(bufp, TS_NULL_MLOC, hdr_loc);
return TS_SUCCESS;
}
}
if (req->wl_retry > 0) {
TSDebug(DEBUG_TAG, "request delayed, but unsuccessful, url@%p: {{%s}} on retry: %d time", txnp, req->req_url.c_str(),
req->wl_retry);
req->wl_retry = 0;
}
// done..cleanup
delete req;
TSContDestroy(contp);
TSHandleMLocRelease(bufp, TS_NULL_MLOC, hdr_loc);
TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);
return TS_SUCCESS;
}
static int
collapsed_cont(TSCont contp, TSEvent event, void *edata)
{
TSHttpTxn txnp = static_cast<TSHttpTxn>(edata);
RequestData *my_req = static_cast<RequestData *>(TSContDataGet(contp));
switch (event) {
case TS_EVENT_HTTP_OS_DNS: {
return on_OS_DNS(my_req, txnp);
}
case TS_EVENT_HTTP_SEND_REQUEST_HDR: {
return on_send_request_header(my_req, txnp);
}
case TS_EVENT_HTTP_READ_RESPONSE_HDR: {
return on_read_response_header(txnp);
}
case TS_EVENT_IMMEDIATE:
case TS_EVENT_TIMEOUT: {
return on_immediate(my_req, contp);
}
case TS_EVENT_HTTP_SEND_RESPONSE_HDR: {
return on_send_response_header(my_req, txnp, contp);
}
default: {
TSDebug(DEBUG_TAG, "Unexpected event: %d", event);
break;
}
}
TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);
return TS_SUCCESS;
}
TSReturnCode
TSRemapInit(TSRemapInterface * /* api_info */, char * /* errbuf */, int /* errbuf_size */)
{
TSDebug(DEBUG_TAG, "plugin is succesfully initialized");
return TS_SUCCESS;
}
TSReturnCode
TSRemapNewInstance(int argc, char *argv[], void ** /* ih */, char * /* errbuf */, int /* errbuf_size */)
{
// basic argv processing..
for (int i = 2; i < argc; ++i) {
if (strncmp(argv[i], "--delay=", 8) == 0) {
OPEN_WRITE_FAIL_REQ_DELAY_TIMEOUT = atoi((char *)(argv[i] + 8));
} else if (strncmp(argv[i], "--retries=", 10) == 0) {
OPEN_WRITE_FAIL_MAX_REQ_DELAY_RETRIES = atoi((char *)(argv[i] + 10));
}
}
return TS_SUCCESS;
}
TSRemapStatus
TSRemapDoRemap(void *ih, TSHttpTxn rh, TSRemapRequestInfo *rri)
{
TSCont cont = TSContCreate(collapsed_cont, TSMutexCreate());
RequestData *req_data = new RequestData();
req_data->txnp = rh;
req_data->wl_retry = 0;
int url_len = 0;
char *url = TSHttpTxnEffectiveUrlStringGet(rh, &url_len);
req_data->req_url.assign(url, url_len);
TSfree(url);
TSContDataSet(cont, req_data);
TSHttpTxnHookAdd(rh, TS_HTTP_SEND_REQUEST_HDR_HOOK, cont);
TSHttpTxnHookAdd(rh, TS_HTTP_SEND_RESPONSE_HDR_HOOK, cont);
TSHttpTxnHookAdd(rh, TS_HTTP_READ_RESPONSE_HDR_HOOK, cont);
TSHttpTxnHookAdd(rh, TS_HTTP_OS_DNS_HOOK, cont);
return TSREMAP_NO_REMAP;
}
void
TSRemapDeleteInstance(void *ih)
{
// To resolve run time error
}
<|endoftext|>
|
<commit_before>enum libModes {mLocal,mLocalSource};
//mLocal: Analyze data on your computer using aliroot
//mLocalSource: Analyze data on your computer using root + source files
void mergeOutput(const Int_t nRuns=-1, TString type="",Int_t mode=mLocal)
{
// load needed libraries:
LoadSpreadLibraries(mode);
// file mergers for the output file of each method separately:
// MCEP:
TFileMerger *mcepFileMerger = new TFileMerger();
TString mergedFileNameMCEP("outputMCEPanalysis.root");
mcepFileMerger->OutputFile(mergedFileNameMCEP);
// SP:
TFileMerger *spFileMerger = new TFileMerger();
TString mergedFileNameSP("outputSPanalysis.root");
spFileMerger->OutputFile(mergedFileNameSP);
// GFC:
TFileMerger *gfcFileMerger = new TFileMerger();
TString mergedFileNameGFC("outputGFCanalysis.root");
gfcFileMerger->OutputFile(mergedFileNameGFC);
// QC:
TFileMerger *qcFileMerger = new TFileMerger();
TString mergedFileNameQC("outputQCanalysis.root");
qcFileMerger->OutputFile(mergedFileNameQC);
// FQD:
TFileMerger *fqdFileMerger = new TFileMerger();
TString mergedFileNameFQD("outputFQDanalysis.root");
fqdFileMerger->OutputFile(mergedFileNameFQD);
// LYZ1:
TFileMerger *lyz1FileMerger = new TFileMerger();
TString mergedFileNameLYZ1("outputLYZ1analysis.root");
lyz1FileMerger->OutputFile(mergedFileNameLYZ1);
// LYZ2:
TFileMerger *lyz2FileMerger = new TFileMerger();
TString mergedFileNameLYZ2("outputLYZ2analysis.root");
lyz2FileMerger->OutputFile(mergedFileNameLYZ2);
// LYZEP:
TFileMerger *lyzepFileMerger = new TFileMerger();
TString mergedFileNameLYZEP("outputLYZEPanalysis.root");
lyzepFileMerger->OutputFile(mergedFileNameLYZEP);
// standard magic:
TString execDir(gSystem->pwd());
TSystemDirectory* baseDir = new TSystemDirectory(".",execDir.Data());
TList* dirList = baseDir->GetListOfFiles();
Int_t nDirs = dirList->GetEntries();
gSystem->cd(execDir);
Int_t counter = 0;
for(Int_t iDir=0;iDir<nDirs;++iDir)
{
TSystemFile* presentDir = (TSystemFile*)dirList->At(iDir);
if(!presentDir || !presentDir->IsDirectory() || strcmp(presentDir->GetName(), ".") == 0 ||
strcmp(presentDir->GetName(), "..") == 0) continue;
if(nRuns != -1)
{
if (counter >= nRuns) break;
}
TString presentDirName(gSystem->pwd());
presentDirName += "/";
presentDirName += presentDir->GetName();
presentDirName += "/";
// accessing the output .root files from independent analysis for each method:
// MCEP:
TString fileNameMCEP = presentDirName;
fileNameMCEP+="outputMCEPanalysis.root";
mcepFileMerger->AddFile(fileNameMCEP.Data());
// SP:
TString fileNameSP = presentDirName;
fileNameSP+="outputSPanalysis.root";
spFileMerger->AddFile(fileNameSP.Data());
// GFC:
TString fileNameGFC = presentDirName;
fileNameGFC+="outputGFCanalysis.root";
gfcFileMerger->AddFile(fileNameGFC.Data());
// QC:
TString fileNameQC = presentDirName;
fileNameQC+="outputQCanalysis.root";
qcFileMerger->AddFile(fileNameQC.Data());
// FQD:
TString fileNameFQD = presentDirName;
fileNameFQD+="outputFQDanalysis.root";
fqdFileMerger->AddFile(fileNameFQD.Data());
// LYZ1:
TString fileNameLYZ1 = presentDirName;
fileNameLYZ1+="outputLYZ1analysis.root";
lyz1FileMerger->AddFile(fileNameLYZ1.Data());
// LYZ2:
TString fileNameLYZ2 = presentDirName;
fileNameLYZ2+="outputLYZ2analysis.root";
lyz2FileMerger->AddFile(fileNameLYZ2.Data());
// LYZEP:
TString fileNameLYZEP = presentDirName;
fileNameLYZEP+="outputLYZEPanalysis.root";
lyzepFileMerger->AddFile(fileNameLYZEP.Data());
counter++;
} // end of for(Int_t iDir=0;iDir<nDirs;++iDir)
// merge everything:
mcepFileMerger->Merge();
spFileMerger->Merge();
gfcFileMerger->Merge();
qcFileMerger->Merge();
fqdFileMerger->Merge();
lyz1FileMerger->Merge();
lyz2FileMerger->Merge();
lyzepFileMerger->Merge();
}
void LoadSpreadLibraries(const libModes mode) {
//--------------------------------------
// Load the needed libraries most of them already loaded by aliroot
//--------------------------------------
gSystem->Load("libTree.so");
gSystem->Load("libGeom.so");
gSystem->Load("libVMC.so");
gSystem->Load("libXMLIO.so");
gSystem->Load("libPhysics.so");
//----------------------------------------------------------
// >>>>>>>>>>> Local mode <<<<<<<<<<<<<<
//----------------------------------------------------------
if (mode==mLocal) {
//--------------------------------------------------------
// If you want to use already compiled libraries
// in the aliroot distribution
//--------------------------------------------------------
//==================================================================================
//load needed libraries:
gSystem->AddIncludePath("-I$ROOTSYS/include");
gSystem->Load("libTree.so");
// for AliRoot
gSystem->AddIncludePath("-I$ALICE_ROOT/include");
gSystem->Load("libANALYSIS.so");
gSystem->Load("libPWG2flowCommon.so");
cerr<<"libPWG2flowCommon.so loaded ..."<<endl;
}
else if (mode==mLocalSource) {
// In root inline compile
// Constants
gROOT->LoadMacro("AliFlowCommon/AliFlowCommonConstants.cxx+");
gROOT->LoadMacro("AliFlowCommon/AliFlowLYZConstants.cxx+");
gROOT->LoadMacro("AliFlowCommon/AliFlowCumuConstants.cxx+");
// Flow event
gROOT->LoadMacro("AliFlowCommon/AliFlowVector.cxx+");
gROOT->LoadMacro("AliFlowCommon/AliFlowTrackSimple.cxx+");
gROOT->LoadMacro("AliFlowCommon/AliFlowEventSimple.cxx+");
// Cuts
gROOT->LoadMacro("AliFlowCommon/AliFlowTrackSimpleCuts.cxx+");
// Output histosgrams
gROOT->LoadMacro("AliFlowCommon/AliFlowCommonHist.cxx+");
gROOT->LoadMacro("AliFlowCommon/AliFlowCommonHistResults.cxx+");
gROOT->LoadMacro("AliFlowCommon/AliFlowLYZHist1.cxx+");
gROOT->LoadMacro("AliFlowCommon/AliFlowLYZHist2.cxx+");
cout << "finished loading macros!" << endl;
}
}
<commit_msg>Added some protection<commit_after>enum libModes {mLocal,mLocalSource};
//mLocal: Analyze data on your computer using aliroot
//mLocalSource: Analyze data on your computer using root + source files
void mergeOutput(const Int_t nRuns=-1, TString type="",Int_t mode=mLocal)
{
// load needed libraries:
LoadSpreadLibraries(mode);
TString pwd(gSystem->pwd());
// file mergers for the output file of each method separately:
// MCEP:
TFileMerger *mcepFileMerger = new TFileMerger();
TString mergedFileNameMCEP("outputMCEPanalysis.root");
if(!(gSystem->AccessPathName(((pwd+="/")+=mergedFileNameMCEP).Data(),kFileExists)))
{
cout<<"WARNING: You already have a merged output for MCEP !!!!"<<endl;
break;
}
mcepFileMerger->OutputFile(mergedFileNameMCEP);
// SP:
TFileMerger *spFileMerger = new TFileMerger();
TString mergedFileNameSP("outputSPanalysis.root");
pwd=gSystem->pwd();
if(!(gSystem->AccessPathName(((pwd+="/")+=mergedFileNameSP).Data(),kFileExists)))
{
cout<<"WARNING: You already have a merged output for SP !!!!"<<endl;
break;
}
spFileMerger->OutputFile(mergedFileNameSP);
// GFC:
TFileMerger *gfcFileMerger = new TFileMerger();
TString mergedFileNameGFC("outputGFCanalysis.root");
pwd=gSystem->pwd();
if(!(gSystem->AccessPathName(((pwd+="/")+=mergedFileNameGFC).Data(),kFileExists)))
{
cout<<"WARNING: You already have a merged output for GFC !!!!"<<endl;
break;
}
gfcFileMerger->OutputFile(mergedFileNameGFC);
// QC:
TFileMerger *qcFileMerger = new TFileMerger();
TString mergedFileNameQC("outputQCanalysis.root");
pwd=gSystem->pwd();
if(!(gSystem->AccessPathName(((pwd+="/")+=mergedFileNameQC).Data(),kFileExists)))
{
cout<<"WARNING: You already have a merged output for QC !!!!"<<endl;
break;
}
qcFileMerger->OutputFile(mergedFileNameQC);
// FQD:
TFileMerger *fqdFileMerger = new TFileMerger();
TString mergedFileNameFQD("outputFQDanalysis.root");
pwd=gSystem->pwd();
if(!(gSystem->AccessPathName(((pwd+="/")+=mergedFileNameFQD).Data(),kFileExists)))
{
cout<<"WARNING: You already have a merged output for FQD !!!!"<<endl;
break;
}
fqdFileMerger->OutputFile(mergedFileNameFQD);
// LYZ1:
TFileMerger *lyz1FileMerger = new TFileMerger();
TString mergedFileNameLYZ1("outputLYZ1analysis.root");
pwd=gSystem->pwd();
if(!(gSystem->AccessPathName(((pwd+="/")+=mergedFileNameLYZ1).Data(),kFileExists)))
{
cout<<"WARNING: You already have a merged output for LYZ1 !!!!"<<endl;
break;
}
lyz1FileMerger->OutputFile(mergedFileNameLYZ1);
// LYZ2:
TFileMerger *lyz2FileMerger = new TFileMerger();
TString mergedFileNameLYZ2("outputLYZ2analysis.root");
pwd=gSystem->pwd();
if(!(gSystem->AccessPathName(((pwd+="/")+=mergedFileNameLYZ2).Data(),kFileExists)))
{
cout<<"WARNING: You already have a merged output for LYZ2 !!!!"<<endl;
break;
}
lyz2FileMerger->OutputFile(mergedFileNameLYZ2);
// LYZEP:
TFileMerger *lyzepFileMerger = new TFileMerger();
TString mergedFileNameLYZEP("outputLYZEPanalysis.root");
pwd=gSystem->pwd();
if(!(gSystem->AccessPathName(((pwd+="/")+=mergedFileNameLYZEP).Data(),kFileExists)))
{
cout<<"WARNING: You already have a merged output for LYZEP !!!!"<<endl;
break;
}
lyzepFileMerger->OutputFile(mergedFileNameLYZEP);
// standard magic:
TString execDir(gSystem->pwd());
TSystemDirectory* baseDir = new TSystemDirectory(".",execDir.Data());
TList* dirList = baseDir->GetListOfFiles();
Int_t nDirs = dirList->GetEntries();
gSystem->cd(execDir);
Int_t counter = 0;
for(Int_t iDir=0;iDir<nDirs;++iDir)
{
TSystemFile* presentDir = (TSystemFile*)dirList->At(iDir);
if(!presentDir || !presentDir->IsDirectory() || strcmp(presentDir->GetName(), ".") == 0 ||
strcmp(presentDir->GetName(), "..") == 0) continue;
if(nRuns != -1)
{
if (counter >= nRuns) break;
}
TString presentDirName(gSystem->pwd());
presentDirName += "/";
presentDirName += presentDir->GetName();
presentDirName += "/";
// accessing the output .root files from independent analysis for each method:
// MCEP:
TString fileNameMCEP = presentDirName;
fileNameMCEP+="outputMCEPanalysis.root";
if(!(gSystem->AccessPathName(fileNameMCEP.Data(),kFileExists)))
{
mcepFileMerger->AddFile(fileNameMCEP.Data());
}
// SP:
TString fileNameSP = presentDirName;
fileNameSP+="outputSPanalysis.root";
if(!(gSystem->AccessPathName(fileNameSP.Data(),kFileExists)))
{
spFileMerger->AddFile(fileNameSP.Data());
}
// GFC:
TString fileNameGFC = presentDirName;
fileNameGFC+="outputGFCanalysis.root";
if(!(gSystem->AccessPathName(fileNameGFC.Data(),kFileExists)))
{
gfcFileMerger->AddFile(fileNameGFC.Data());
}
// QC:
TString fileNameQC = presentDirName;
fileNameQC+="outputQCanalysis.root";
if(!(gSystem->AccessPathName(fileNameQC.Data(),kFileExists)))
{
qcFileMerger->AddFile(fileNameQC.Data());
}
// FQD:
TString fileNameFQD = presentDirName;
fileNameFQD+="outputFQDanalysis.root";
if(!(gSystem->AccessPathName(fileNameFQD.Data(),kFileExists)))
{
fqdFileMerger->AddFile(fileNameFQD.Data());
}
// LYZ1:
TString fileNameLYZ1 = presentDirName;
fileNameLYZ1+="outputLYZ1analysis.root";
if(!(gSystem->AccessPathName(fileNameLYZ1.Data(),kFileExists)))
{
lyz1FileMerger->AddFile(fileNameLYZ1.Data());
}
// LYZ2:
TString fileNameLYZ2 = presentDirName;
fileNameLYZ2+="outputLYZ2analysis.root";
if(!(gSystem->AccessPathName(fileNameLYZ2.Data(),kFileExists)))
{
lyz2FileMerger->AddFile(fileNameLYZ2.Data());
}
// LYZEP:
TString fileNameLYZEP = presentDirName;
fileNameLYZEP+="outputLYZEPanalysis.root";
if(!(gSystem->AccessPathName(fileNameLYZEP.Data(),kFileExists)))
{
lyzepFileMerger->AddFile(fileNameLYZEP.Data());
}
counter++;
} // end of for(Int_t iDir=0;iDir<nDirs;++iDir)
// merge everything:
mcepFileMerger->Merge();
spFileMerger->Merge();
gfcFileMerger->Merge();
qcFileMerger->Merge();
fqdFileMerger->Merge();
lyz1FileMerger->Merge();
lyz2FileMerger->Merge();
lyzepFileMerger->Merge();
}
void LoadSpreadLibraries(const libModes mode) {
//--------------------------------------
// Load the needed libraries most of them already loaded by aliroot
//--------------------------------------
gSystem->Load("libTree.so");
gSystem->Load("libGeom.so");
gSystem->Load("libVMC.so");
gSystem->Load("libXMLIO.so");
gSystem->Load("libPhysics.so");
//----------------------------------------------------------
// >>>>>>>>>>> Local mode <<<<<<<<<<<<<<
//----------------------------------------------------------
if (mode==mLocal) {
//--------------------------------------------------------
// If you want to use already compiled libraries
// in the aliroot distribution
//--------------------------------------------------------
//==================================================================================
//load needed libraries:
gSystem->AddIncludePath("-I$ROOTSYS/include");
gSystem->Load("libTree.so");
// for AliRoot
gSystem->AddIncludePath("-I$ALICE_ROOT/include");
gSystem->Load("libANALYSIS.so");
gSystem->Load("libPWG2flowCommon.so");
cerr<<"libPWG2flowCommon.so loaded ..."<<endl;
}
else if (mode==mLocalSource) {
// In root inline compile
// Constants
gROOT->LoadMacro("AliFlowCommon/AliFlowCommonConstants.cxx+");
gROOT->LoadMacro("AliFlowCommon/AliFlowLYZConstants.cxx+");
gROOT->LoadMacro("AliFlowCommon/AliFlowCumuConstants.cxx+");
// Flow event
gROOT->LoadMacro("AliFlowCommon/AliFlowVector.cxx+");
gROOT->LoadMacro("AliFlowCommon/AliFlowTrackSimple.cxx+");
gROOT->LoadMacro("AliFlowCommon/AliFlowEventSimple.cxx+");
// Cuts
gROOT->LoadMacro("AliFlowCommon/AliFlowTrackSimpleCuts.cxx+");
// Output histosgrams
gROOT->LoadMacro("AliFlowCommon/AliFlowCommonHist.cxx+");
gROOT->LoadMacro("AliFlowCommon/AliFlowCommonHistResults.cxx+");
gROOT->LoadMacro("AliFlowCommon/AliFlowLYZHist1.cxx+");
gROOT->LoadMacro("AliFlowCommon/AliFlowLYZHist2.cxx+");
cout << "finished loading macros!" << endl;
}
}
<|endoftext|>
|
<commit_before>// Copyright 2016-2020 Google LLC
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
#include "field.h"
#include <map>
#include <cstdint>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/stubs/strutil.h>
#include "proto2-descriptor-extensions.pb.h"
#include "literals.h"
#include "names.h"
namespace google {
namespace protobuf {
namespace cl_protobufs {
namespace {
const std::string FieldLispType(const FieldDescriptor* field) {
std::string type;
if (field->options().HasExtension(lisp_type)) {
type = field->options().GetExtension(lisp_type);
} else {
switch (field->type()) {
case FieldDescriptor::TYPE_DOUBLE:
type = "cl:double-float";
break;
case FieldDescriptor::TYPE_FLOAT:
type = "cl:float";
break;
case FieldDescriptor::TYPE_INT64:
type = "proto:int64";
break;
case FieldDescriptor::TYPE_UINT64:
type = "proto:uint64";
break;
case FieldDescriptor::TYPE_INT32:
type = "proto:int32";
break;
case FieldDescriptor::TYPE_FIXED64:
type = "proto:fixed64";
break;
case FieldDescriptor::TYPE_FIXED32:
type = "proto:fixed32";
break;
case FieldDescriptor::TYPE_BOOL:
type = "cl:boolean";
break;
case FieldDescriptor::TYPE_STRING:
type = "cl:string";
break;
case FieldDescriptor::TYPE_MESSAGE:
type = QualifiedMessageLispName(field->message_type(), field->file());
break;
case FieldDescriptor::TYPE_BYTES:
type = "proto:byte-vector";
break;
case FieldDescriptor::TYPE_UINT32:
type = "proto:uint32";
break;
case FieldDescriptor::TYPE_ENUM:
type = QualifiedEnumLispName(field->enum_type(), field->file());
break;
case FieldDescriptor::TYPE_SFIXED32:
type = "proto:sfixed32";
break;
case FieldDescriptor::TYPE_SFIXED64:
type = "proto:sfixed64";
break;
case FieldDescriptor::TYPE_SINT32:
type = "proto:sint32";
break;
case FieldDescriptor::TYPE_SINT64:
type = "proto:sint64";
break;
default:
GOOGLE_LOG(FATAL) << "Unsupported FileDescriptorType: "
<< field->DebugString();
break;
}
}
if (field->type() == FieldDescriptor::TYPE_MESSAGE && !field->is_repeated())
return StrCat("(cl:or cl:null ", type, ")");
if (field->is_required() || field->is_optional()) return type;
if (field->is_repeated()) {
if (field->options().HasExtension(lisp_container)) {
switch (field->options().GetExtension(lisp_container)) {
case LIST:
return StrCat("(proto:list-of ", type, ")");
case VECTOR:
return StrCat("(proto:vector-of ", type, ")");
}
} else {
return StrCat("(proto:list-of ", type, ")");
}
}
GOOGLE_LOG(FATAL) << "Error determining field type: " << field->DebugString();
return ":error";
}
// Return the "arity" of the field, i.e. whether it's required, optional, or
// repeated, and if repeated the type of repeated.
const std::string FieldLispLabel(const FieldDescriptor* field) {
switch (field->label()) {
case FieldDescriptor::Label::LABEL_REQUIRED:
return "(:required)";
case FieldDescriptor::Label::LABEL_OPTIONAL:
return "(:optional)";
case FieldDescriptor::Label::LABEL_REPEATED:
if (field->options().HasExtension(lisp_container)) {
switch (field->options().GetExtension(lisp_container)) {
case LIST:
return "(:repeated :list)";
case VECTOR:
return "(:repeated :vector)";
}
} else {
return "(:repeated :list)";
}
}
GOOGLE_LOG(FATAL) << "Error determining field arity: " << field->DebugString();
return "(:error)";
}
const std::string FieldLispDefault(const FieldDescriptor* field) {
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_DOUBLE:
return LispSimpleDtoa(field->default_value_double());
case FieldDescriptor::CPPTYPE_FLOAT:
return LispSimpleFtoa(field->default_value_float());
case FieldDescriptor::CPPTYPE_BOOL:
return LispBool(field->default_value_bool());
case FieldDescriptor::CPPTYPE_ENUM: {
const EnumValueDescriptor* value = field->default_value_enum();
return StrCat(":", ToLispName(value->name()));
}
case FieldDescriptor::CPPTYPE_INT32:
return StrCat(field->default_value_int32());
case FieldDescriptor::CPPTYPE_UINT32:
return StrCat(field->default_value_uint32());
case FieldDescriptor::CPPTYPE_INT64:
return StrCat(field->default_value_int64());
case FieldDescriptor::CPPTYPE_UINT64:
return StrCat(field->default_value_uint64());
case FieldDescriptor::CPPTYPE_STRING: {
switch (field->type()) {
case FieldDescriptor::TYPE_BYTES:
return StrCat(
"#.(cl:make-array ", field->default_value_string().size(),
" :element-type '(cl:unsigned-byte 8)", " :initial-contents '(",
StringOctets(field->default_value_string()), "))");
case FieldDescriptor::TYPE_STRING:
return LispEscapeString(field->default_value_string());
default: break;
}
break;
}
default: break;
}
// Unsupported by cl_protobufs.
// case FieldDescriptor::CPPTYPE_MESSAGE:
// Report errors as early as possible.
GOOGLE_LOG(FATAL) << "Unsupported FileDescriptorType: " << field->DebugString();
return "";
}
const std::string FieldTypeName(const FieldDescriptor* field) {
switch (field->type()) {
case FieldDescriptor::TYPE_ENUM:
return (field->enum_type()->file() == field->file() &&
(field->enum_type()->containing_type() ==
field->containing_type() ||
field->enum_type()->containing_type() ==
field->containing_type()->containing_type())) ?
field->enum_type()->name():
field->enum_type()->full_name();
case FieldDescriptor::TYPE_MESSAGE:
return (field->message_type()->file() == field->file() &&
(field->message_type()->containing_type() ==
field->containing_type() ||
field->message_type()->containing_type() ==
field->containing_type()->containing_type())) ?
field->message_type()->name():
field->message_type()->full_name();
default:
return field->type_name();
}
}
} // namespace
const std::string FieldLispName(const FieldDescriptor* field) {
if (field->options().HasExtension(lisp_slot)) {
return field->options().GetExtension(lisp_slot);
} else {
return ToLispName(field->name());
}
}
void GenerateField(io::Printer* printer, const FieldDescriptor* field) {
std::map<std::string, std::string> vars;
vars["name"] = FieldLispName(field);
vars["tag"] = StrCat(field->number());
vars["type"] = FieldLispType(field);
vars["label"] = FieldLispLabel(field);
vars["typename"] = FieldTypeName(field);
vars["packed"] = field->options().packed() ? " :packed cl:t" : "";
vars["lazy"] = field->options().lazy() ? " :lazy cl:t" : "";
vars["default"] = field->has_default_value()
? StrCat(" :default ", FieldLispDefault(field))
: "";
printer->Print(vars,
"\n($name$ "
" :index $tag$ "
" :type $type$"
" :label $label$"
" :typename \"$typename$\""
"$default$"
"$packed$"
"$lazy$)");
printer->Annotate("name", field);
}
void GenerateExtension(io::Printer* printer,
const FieldDescriptor* extension,
const FileDescriptor* file) {
printer->Print(
"\n(proto:define-extend $name$ ()",
"name", QualifiedMessageLispName(extension->containing_type(), file));
printer->Indent();
GenerateField(printer, extension);
printer->Print(")");
printer->Outdent();
}
} // namespace cl_protobufs
} // namespace protobuf
} // namespace google
<commit_msg>Add protoc handling of map fields<commit_after>// Copyright 2016-2020 Google LLC
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
#include "field.h"
#include <map>
#include <cstdint>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/stubs/strutil.h>
#include "proto2-descriptor-extensions.pb.h"
#include "literals.h"
#include "names.h"
namespace google {
namespace protobuf {
namespace cl_protobufs {
namespace {
const std::string FieldLispType(const FieldDescriptor* field) {
std::string type;
if (field->options().HasExtension(lisp_type)) {
type = field->options().GetExtension(lisp_type);
} else {
switch (field->type()) {
case FieldDescriptor::TYPE_DOUBLE:
type = "cl:double-float";
break;
case FieldDescriptor::TYPE_FLOAT:
type = "cl:float";
break;
case FieldDescriptor::TYPE_INT64:
type = "proto:int64";
break;
case FieldDescriptor::TYPE_UINT64:
type = "proto:uint64";
break;
case FieldDescriptor::TYPE_INT32:
type = "proto:int32";
break;
case FieldDescriptor::TYPE_FIXED64:
type = "proto:fixed64";
break;
case FieldDescriptor::TYPE_FIXED32:
type = "proto:fixed32";
break;
case FieldDescriptor::TYPE_BOOL:
type = "cl:boolean";
break;
case FieldDescriptor::TYPE_STRING:
type = "cl:string";
break;
case FieldDescriptor::TYPE_MESSAGE:
type = QualifiedMessageLispName(field->message_type(), field->file());
break;
case FieldDescriptor::TYPE_BYTES:
type = "proto:byte-vector";
break;
case FieldDescriptor::TYPE_UINT32:
type = "proto:uint32";
break;
case FieldDescriptor::TYPE_ENUM:
type = QualifiedEnumLispName(field->enum_type(), field->file());
break;
case FieldDescriptor::TYPE_SFIXED32:
type = "proto:sfixed32";
break;
case FieldDescriptor::TYPE_SFIXED64:
type = "proto:sfixed64";
break;
case FieldDescriptor::TYPE_SINT32:
type = "proto:sint32";
break;
case FieldDescriptor::TYPE_SINT64:
type = "proto:sint64";
break;
default:
GOOGLE_LOG(FATAL) << "Unsupported FileDescriptorType: "
<< field->DebugString();
break;
}
}
if (field->type() == FieldDescriptor::TYPE_MESSAGE && !field->is_repeated())
return StrCat("(cl:or cl:null ", type, ")");
if (field->is_required() || field->is_optional()) return type;
if (field->is_repeated()) {
if (field->options().HasExtension(lisp_container)) {
switch (field->options().GetExtension(lisp_container)) {
case LIST:
return StrCat("(proto:list-of ", type, ")");
case VECTOR:
return StrCat("(proto:vector-of ", type, ")");
}
} else {
return StrCat("(proto:list-of ", type, ")");
}
}
GOOGLE_LOG(FATAL) << "Error determining field type: " << field->DebugString();
return ":error";
}
// Return the "arity" of the field, i.e. whether it's required, optional, or
// repeated, and if repeated the type of repeated.
const std::string FieldLispLabel(const FieldDescriptor* field) {
switch (field->label()) {
case FieldDescriptor::Label::LABEL_REQUIRED:
return "(:required)";
case FieldDescriptor::Label::LABEL_OPTIONAL:
return "(:optional)";
case FieldDescriptor::Label::LABEL_REPEATED:
if (field->options().HasExtension(lisp_container)) {
switch (field->options().GetExtension(lisp_container)) {
case LIST:
return "(:repeated :list)";
case VECTOR:
return "(:repeated :vector)";
}
} else {
return "(:repeated :list)";
}
}
GOOGLE_LOG(FATAL) << "Error determining field arity: " << field->DebugString();
return "(:error)";
}
const std::string FieldLispDefault(const FieldDescriptor* field) {
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_DOUBLE:
return LispSimpleDtoa(field->default_value_double());
case FieldDescriptor::CPPTYPE_FLOAT:
return LispSimpleFtoa(field->default_value_float());
case FieldDescriptor::CPPTYPE_BOOL:
return LispBool(field->default_value_bool());
case FieldDescriptor::CPPTYPE_ENUM: {
const EnumValueDescriptor* value = field->default_value_enum();
return StrCat(":", ToLispName(value->name()));
}
case FieldDescriptor::CPPTYPE_INT32:
return StrCat(field->default_value_int32());
case FieldDescriptor::CPPTYPE_UINT32:
return StrCat(field->default_value_uint32());
case FieldDescriptor::CPPTYPE_INT64:
return StrCat(field->default_value_int64());
case FieldDescriptor::CPPTYPE_UINT64:
return StrCat(field->default_value_uint64());
case FieldDescriptor::CPPTYPE_STRING: {
switch (field->type()) {
case FieldDescriptor::TYPE_BYTES:
return StrCat(
"#.(cl:make-array ", field->default_value_string().size(),
" :element-type '(cl:unsigned-byte 8)", " :initial-contents '(",
StringOctets(field->default_value_string()), "))");
case FieldDescriptor::TYPE_STRING:
return LispEscapeString(field->default_value_string());
default: break;
}
break;
}
default: break;
}
// Unsupported by cl_protobufs.
// case FieldDescriptor::CPPTYPE_MESSAGE:
// Report errors as early as possible.
GOOGLE_LOG(FATAL) << "Unsupported FileDescriptorType: " << field->DebugString();
return "";
}
const std::string FieldTypeName(const FieldDescriptor* field) {
switch (field->type()) {
case FieldDescriptor::TYPE_ENUM:
return (field->enum_type()->file() == field->file() &&
(field->enum_type()->containing_type() ==
field->containing_type() ||
field->enum_type()->containing_type() ==
field->containing_type()->containing_type())) ?
field->enum_type()->name():
field->enum_type()->full_name();
case FieldDescriptor::TYPE_MESSAGE:
return (field->message_type()->file() == field->file() &&
(field->message_type()->containing_type() ==
field->containing_type() ||
field->message_type()->containing_type() ==
field->containing_type()->containing_type())) ?
field->message_type()->name():
field->message_type()->full_name();
default:
return field->type_name();
}
}
} // namespace
const std::string FieldLispName(const FieldDescriptor* field) {
if (field->options().HasExtension(lisp_slot)) {
return field->options().GetExtension(lisp_slot);
} else {
return ToLispName(field->name());
}
}
void GenerateField(io::Printer* printer, const FieldDescriptor* field) {
std::map<std::string, std::string> vars;
vars["name"] = FieldLispName(field);
vars["tag"] = StrCat(field->number());
if(field->is_map()) {
vars["type"] = QualifiedMessageLispName(field->message_type(), field->file());
printer->Print(vars,
"\n(proto:define-map $name$\n"
" (:map-desc $type$\n"
" :index $tag$))");
} else {
vars["type"] = FieldLispType(field);
vars["label"] = FieldLispLabel(field);
vars["typename"] = FieldTypeName(field);
vars["packed"] = field->options().packed() ? " :packed cl:t" : "";
vars["lazy"] = field->options().lazy() ? " :lazy cl:t" : "";
vars["default"] = field->has_default_value()
? StrCat(" :default ", FieldLispDefault(field))
: "";
printer->Print(vars,
"\n($name$ "
" :index $tag$ "
" :type $type$"
" :label $label$"
" :typename \"$typename$\""
"$default$"
"$packed$"
"$lazy$)");
}
printer->Annotate("name", field);
}
void GenerateExtension(io::Printer* printer,
const FieldDescriptor* extension,
const FileDescriptor* file) {
printer->Print(
"\n(proto:define-extend $name$ ()",
"name", QualifiedMessageLispName(extension->containing_type(), file));
printer->Indent();
GenerateField(printer, extension);
printer->Print(")");
printer->Outdent();
}
} // namespace cl_protobufs
} // namespace protobuf
} // namespace google
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: mmoutputtypepage.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: kz $ $Date: 2007-09-06 14:06:48 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif
#ifndef _MAILMERGEOUTPUTTYPEPAGE_HXX
#include <mmoutputtypepage.hxx>
#endif
#ifndef _MAILMERGEWIZARD_HXX
#include <mailmergewizard.hxx>
#endif
#ifndef _MMCONFIGITEM_HXX
#include <mmconfigitem.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _DBUI_HRC
#include <dbui.hrc>
#endif
#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#include <mmoutputtypepage.hrc>
#include <dbui.hrc>
/*-- 02.04.2004 11:06:55---------------------------------------------------
-----------------------------------------------------------------------*/
SwMailMergeOutputTypePage::SwMailMergeOutputTypePage( SwMailMergeWizard* _pParent) :
svt::OWizardPage( _pParent, SW_RES(DLG_MM_OUTPUTTYPE_PAGE)),
#ifdef _MSC_VER
#pragma warning (disable : 4355)
#endif
m_aHeaderFI( this, SW_RES( FI_HEADER )),
m_aTypeFT( this, SW_RES( FT_TYPE )),
m_aLetterRB( this, SW_RES( RB_LETTER )),
m_aMailRB( this, SW_RES( RB_MAIL )),
m_aHintHeaderFI(this, SW_RES( FI_HINTHEADER)),
m_aHintFI( this, SW_RES( FI_HINT)),
m_aNoMailHintFI(this, SW_RES( FT_NOMAILHINT)),
#ifdef _MSC_VER
#pragma warning (default : 4355)
#endif
m_pWizard(_pParent),
m_sLetterHintHeader( SW_RES( ST_LETTERHINTHEADER)),
m_sMailHintHeader( SW_RES( ST_MAILHINTHEADER)),
m_sLetterHint( SW_RES( ST_LETTERHINT)),
m_sMailHint( SW_RES( ST_MAILHINT))
{
FreeResource();
Link aLink = LINK(this, SwMailMergeOutputTypePage, TypeHdl_Impl);
m_aLetterRB.SetClickHdl(aLink);
m_aMailRB.SetClickHdl(aLink);
SwMailMergeConfigItem& rConfigItem = m_pWizard->GetConfigItem();
m_pWizard->EnterWait();
bool bMailAvailable = rConfigItem.IsMailAvailable();
m_pWizard->LeaveWait();
if(rConfigItem.IsOutputToLetter())
m_aLetterRB.Check();
else
m_aMailRB.Check();
if(!bMailAvailable)
{
m_aNoMailHintFI.Show();
m_aMailRB.Enable(sal_False);
m_aLetterRB.Check();
}
TypeHdl_Impl(&m_aLetterRB);
}
/*-- 02.04.2004 11:06:55---------------------------------------------------
-----------------------------------------------------------------------*/
SwMailMergeOutputTypePage::~SwMailMergeOutputTypePage()
{
}
/*-- 14.04.2004 14:44:07---------------------------------------------------
-----------------------------------------------------------------------*/
IMPL_LINK( SwMailMergeOutputTypePage, TypeHdl_Impl, RadioButton*, EMPTYARG )
{
bool bLetter = m_aLetterRB.IsChecked();
m_aHintHeaderFI.SetText(bLetter ? m_sLetterHintHeader : m_sMailHintHeader);
m_aHintFI.SetText(bLetter ? m_sLetterHint : m_sMailHint);
m_pWizard->GetConfigItem().SetOutputToLetter(bLetter);
m_pWizard->updateRoadmapItemLabel( MM_ADDRESSBLOCKPAGE );
m_pWizard->UpdateRoadmap();
return 0;
}
<commit_msg>INTEGRATION: CWS swwarnings (1.6.222); FILE MERGED 2007/05/29 12:19:23 os 1.6.222.2: RESYNC: (1.6-1.7); FILE MERGED 2007/02/26 15:59:13 os 1.6.222.1: #i69287# warnings removed<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: mmoutputtypepage.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: hr $ $Date: 2007-09-27 11:35:12 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif
#ifndef _MAILMERGEOUTPUTTYPEPAGE_HXX
#include <mmoutputtypepage.hxx>
#endif
#ifndef _MAILMERGEWIZARD_HXX
#include <mailmergewizard.hxx>
#endif
#ifndef _MMCONFIGITEM_HXX
#include <mmconfigitem.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _DBUI_HRC
#include <dbui.hrc>
#endif
#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#include <mmoutputtypepage.hrc>
#include <dbui.hrc>
/*-- 02.04.2004 11:06:55---------------------------------------------------
-----------------------------------------------------------------------*/
SwMailMergeOutputTypePage::SwMailMergeOutputTypePage( SwMailMergeWizard* _pParent) :
svt::OWizardPage( _pParent, SW_RES(DLG_MM_OUTPUTTYPE_PAGE)),
#ifdef MSC
#pragma warning (disable : 4355)
#endif
m_aHeaderFI( this, SW_RES( FI_HEADER )),
m_aTypeFT( this, SW_RES( FT_TYPE )),
m_aLetterRB( this, SW_RES( RB_LETTER )),
m_aMailRB( this, SW_RES( RB_MAIL )),
m_aHintHeaderFI(this, SW_RES( FI_HINTHEADER)),
m_aHintFI( this, SW_RES( FI_HINT)),
m_aNoMailHintFI(this, SW_RES( FT_NOMAILHINT)),
#ifdef MSC
#pragma warning (default : 4355)
#endif
m_sLetterHintHeader( SW_RES( ST_LETTERHINTHEADER)),
m_sMailHintHeader( SW_RES( ST_MAILHINTHEADER)),
m_sLetterHint( SW_RES( ST_LETTERHINT)),
m_sMailHint( SW_RES( ST_MAILHINT)),
m_pWizard(_pParent)
{
FreeResource();
Link aLink = LINK(this, SwMailMergeOutputTypePage, TypeHdl_Impl);
m_aLetterRB.SetClickHdl(aLink);
m_aMailRB.SetClickHdl(aLink);
SwMailMergeConfigItem& rConfigItem = m_pWizard->GetConfigItem();
m_pWizard->EnterWait();
bool bMailAvailable = rConfigItem.IsMailAvailable();
m_pWizard->LeaveWait();
if(rConfigItem.IsOutputToLetter())
m_aLetterRB.Check();
else
m_aMailRB.Check();
if(!bMailAvailable)
{
m_aNoMailHintFI.Show();
m_aMailRB.Enable(sal_False);
m_aLetterRB.Check();
}
TypeHdl_Impl(&m_aLetterRB);
}
/*-- 02.04.2004 11:06:55---------------------------------------------------
-----------------------------------------------------------------------*/
SwMailMergeOutputTypePage::~SwMailMergeOutputTypePage()
{
}
/*-- 14.04.2004 14:44:07---------------------------------------------------
-----------------------------------------------------------------------*/
IMPL_LINK( SwMailMergeOutputTypePage, TypeHdl_Impl, RadioButton*, EMPTYARG )
{
bool bLetter = m_aLetterRB.IsChecked();
m_aHintHeaderFI.SetText(bLetter ? m_sLetterHintHeader : m_sMailHintHeader);
m_aHintFI.SetText(bLetter ? m_sLetterHint : m_sMailHint);
m_pWizard->GetConfigItem().SetOutputToLetter(bLetter);
m_pWizard->updateRoadmapItemLabel( MM_ADDRESSBLOCKPAGE );
m_pWizard->UpdateRoadmap();
return 0;
}
<|endoftext|>
|
<commit_before>#include <QtGui/QCursor>
#include <QtWidgets/QStyleOptionGraphicsItem>
#include <qmath.h>
#include "rotater.h"
using namespace qReal::interpreters::robots;
using namespace details::d2Model;
using namespace graphicsUtils;
Rotater::Rotater() : AbstractItem()
{
setFlags(ItemIsSelectable | ItemIsMovable);
setAcceptHoverEvents(true);
setAcceptDrops(true);
setCursor(QCursor(Qt::PointingHandCursor));
setZValue(2);
mPen.setColor(Qt::blue);
mPen.setWidth(3);
mBrush.setStyle(Qt::NoBrush);
}
void Rotater::setMasterItem(RotateItem *masterItem)
{
mMaster = masterItem;
mLength = 30; //mMaster->horizontalRadius();//asd
mDrift = drift > mMaster->horizontalRadius() ? drift / 2 : drift;
mResizeDrift = drift > mMaster->horizontalRadius() ? resizeDrift / 2 : resizeDrift;
QRectF const rect = mMaster->rect();
mMaster->setFlag(ItemClipsToShape, false);
setParentItem(mMaster);
// TODO: Dispose of hardcoding
mX1 = rect.right();
// Placing rotater into the center of item`s rigth side
mY1 = rect.y() + rect.height() / 2;
mX2 = mX1 + mLength;
mY2 = mY1;
}
void Rotater::drawItem(QPainter *painter, const QStyleOptionGraphicsItem *style, QWidget *widget)
{
Q_UNUSED(style)
Q_UNUSED(widget)
painter->setOpacity(0.5);
const int addLength = mLength / 3;
qreal const angle = addAngle;
// Must be equal to mLength
qreal const checkLength = sqrt((mX2 - mX1) * (mX2 - mX1) + (mY2 - mY1) * (mY2 - mY1));
qreal const x0 = ((checkLength - addLength) * mX2 + addLength * mX1) / checkLength;
qreal const y0 = ((checkLength - addLength) * mY2 + addLength * mY1) / checkLength;
QPointF const first = QTransform().translate(mX2 - x0, mY2 - y0).rotate(- angle).translate(- mX2 + x0, - mY2 + y0).rotate(angle).map(QPointF(x0, y0));
QPointF const second = QTransform().translate(mX2 - x0, mY2 - y0).rotate(angle).translate(- mX2 + x0, - mY2 + y0).rotate(- angle).map(QPointF(x0, y0));
mLineImpl.drawItem(painter, mX1, mY1, mX2, mY2);
mLineImpl.drawItem(painter, mX2, mY2, first.x(), first.y());
mLineImpl.drawItem(painter, mX2, mY2, second.x(), second.y());
}
void Rotater::setPenBrushForExtraxtion(QPainter* painter, const QStyleOptionGraphicsItem* option)
{
Q_UNUSED(option)
QPen pen(Qt::red);
pen.setWidth(2);
painter->setPen(pen);
}
void Rotater::drawExtractionForItem(QPainter* painter)
{
mLineImpl.drawExtractionForItem(painter, mX1, mY1, mX2, mY2, mDrift);
drawFieldForResizeItem(painter);
}
void Rotater::drawFieldForResizeItem(QPainter* painter)
{
painter->drawEllipse(QPointF(mX2, mY2), mResizeDrift, mResizeDrift);
}
QRectF Rotater::boundingRect() const
{
return mLineImpl.boundingRect(mX1, mY1, mX2, mY2, mPen.width(), drift);
}
//qreal Rotater::distance(qreal x1, qreal y1, qreal x2, qreal y2) const
//{
// return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
//}
//qreal Rotater::distance(QPointF const &p1, QPointF const &p2) const
//{
// return distance(p1.x(), p1.y(), p2.x(), p2.y());
//}
void Rotater::calcResizeItem(QGraphicsSceneMouseEvent *event)
{
// Cosine theorem
qreal const x1 = event->pos().x() - mX1 / 2;
qreal const y1 = event->pos().y() - mY1 / 2;
qreal const x2 = event->lastPos().x() - mX1 / 2;
qreal const y2 = event->lastPos().y() - mY1 / 2;
qreal const len = sqrt((x1 * x1 + y1 * y1) * (x2 * x2 + y2 * y2));
// Rotation sign is the sign of the vector product
qreal const vectorProduct = x1 * y2 - x2 * y1;
int const sign = vectorProduct < 0 ? -1 : 1;
qreal const eps = 10e-8;
qreal const dalpha = len < eps ? 0 : acos((x1 * x2 + y1 * y2) / len);
mMaster->rotate(mMaster->rotation() - sign * dalpha * 180 / M_PI);
}
void Rotater::resizeItem(QGraphicsSceneMouseEvent *event)
{
if (mDragState == BottomRight) {
setFlag(ItemIsMovable, false);
AbstractItem::resizeItem(event);
}
}
void Rotater::mousePressEvent(QGraphicsSceneMouseEvent * event)
{
AbstractItem::mousePressEvent(event);
mMaster->setSelected(true);
}
void Rotater::mouseMoveEvent(QGraphicsSceneMouseEvent * event)
{
AbstractItem::mouseMoveEvent(event);
mMaster->setSelected(true);
}
void Rotater::mouseReleaseEvent(QGraphicsSceneMouseEvent * event)
{
AbstractItem::mouseReleaseEvent(event);
}
<commit_msg>Now rotaters are ok<commit_after>#include <QtGui/QCursor>
#include <QtWidgets/QStyleOptionGraphicsItem>
#include <qmath.h>
#include "rotater.h"
using namespace qReal::interpreters::robots;
using namespace details::d2Model;
using namespace graphicsUtils;
Rotater::Rotater() : AbstractItem()
{
setFlags(ItemIsSelectable | ItemIsMovable);
setAcceptHoverEvents(true);
setAcceptDrops(true);
setCursor(QCursor(Qt::PointingHandCursor));
setZValue(2);
mPen.setColor(Qt::blue);
mPen.setWidth(3);
mBrush.setStyle(Qt::NoBrush);
}
void Rotater::setMasterItem(RotateItem *masterItem)
{
mMaster = masterItem;
mLength = 30; //mMaster->horizontalRadius();//asd
mDrift = drift > mMaster->horizontalRadius() ? drift / 2 : drift;
mResizeDrift = drift > mMaster->horizontalRadius() ? resizeDrift / 2 : resizeDrift;
QRectF const rect = mMaster->rect();
mMaster->setFlag(ItemClipsToShape, false);
setParentItem(mMaster);
// TODO: Dispose of hardcoding
mX1 = rect.right();
// Placing rotater into the center of item`s rigth side
mY1 = rect.y() + rect.height() / 2;
mX2 = mX1 + mLength;
mY2 = mY1;
}
void Rotater::drawItem(QPainter *painter, const QStyleOptionGraphicsItem *style, QWidget *widget)
{
Q_UNUSED(style)
Q_UNUSED(widget)
painter->setOpacity(0.5);
const int addLength = mLength / 3;
qreal const angle = addAngle;
// Must be equal to mLength
qreal const checkLength = sqrt((mX2 - mX1) * (mX2 - mX1) + (mY2 - mY1) * (mY2 - mY1));
qreal const x0 = ((checkLength - addLength) * mX2 + addLength * mX1) / checkLength;
qreal const y0 = ((checkLength - addLength) * mY2 + addLength * mY1) / checkLength;
QPointF const first = QTransform().translate(mX2 - x0, mY2 - y0).rotate(- angle).translate(- mX2 + x0, - mY2 + y0).rotate(angle).map(QPointF(x0, y0));
QPointF const second = QTransform().translate(mX2 - x0, mY2 - y0).rotate(angle).translate(- mX2 + x0, - mY2 + y0).rotate(- angle).map(QPointF(x0, y0));
mLineImpl.drawItem(painter, mX1, mY1, mX2, mY2);
mLineImpl.drawItem(painter, mX2, mY2, first.x(), first.y());
mLineImpl.drawItem(painter, mX2, mY2, second.x(), second.y());
}
void Rotater::setPenBrushForExtraxtion(QPainter* painter, const QStyleOptionGraphicsItem* option)
{
Q_UNUSED(option)
QPen pen(Qt::red);
pen.setWidth(2);
painter->setPen(pen);
}
void Rotater::drawExtractionForItem(QPainter* painter)
{
mLineImpl.drawExtractionForItem(painter, mX1, mY1, mX2, mY2, mDrift);
drawFieldForResizeItem(painter);
}
void Rotater::drawFieldForResizeItem(QPainter* painter)
{
painter->drawEllipse(QPointF(mX2, mY2), mResizeDrift, mResizeDrift);
}
QRectF Rotater::boundingRect() const
{
return mLineImpl.boundingRect(mX1, mY1, mX2, mY2, mPen.width(), drift);
}
void Rotater::calcResizeItem(QGraphicsSceneMouseEvent *event)
{
qreal const eps = 0.000000001;
QPointF const masterCenter(mMaster->mapToScene(mMaster->rect().center()));
QPointF const zeroRotationVector(mLength, 0);
qreal const mouseX = event->scenePos().x() - masterCenter.x();
qreal const mouseY = event->scenePos().y() - masterCenter.y();
// Master rotation is signed angle between initial and mouse vector.
// Calculating it from theese vectors product and cosine theorem
qreal const vectorProduct = zeroRotationVector.x() * mouseY
- zeroRotationVector.y() * mouseX;
qreal const mouseVectorLength = sqrt(mouseX * mouseX + mouseY * mouseY);
if (mouseVectorLength < eps) {
return;
}
qreal const translationX = mouseX - zeroRotationVector.x();
qreal const translationY = mouseY - zeroRotationVector.y();
qreal const translation = translationX * translationX + translationY * translationY;
qreal const sin = vectorProduct / (mouseVectorLength * mLength);
bool const cosIsNegative = mouseVectorLength * mouseVectorLength + mLength * mLength < translation;
qreal const angleInWrongQuarter = asin(sin);
qreal const angle = cosIsNegative ? M_PI - angleInWrongQuarter : angleInWrongQuarter;
mMaster->rotate(angle * 180 / M_PI);
}
void Rotater::resizeItem(QGraphicsSceneMouseEvent *event)
{
if (mDragState == BottomRight) {
setFlag(ItemIsMovable, false);
AbstractItem::resizeItem(event);
}
}
void Rotater::mousePressEvent(QGraphicsSceneMouseEvent * event)
{
AbstractItem::mousePressEvent(event);
mMaster->setSelected(true);
}
void Rotater::mouseMoveEvent(QGraphicsSceneMouseEvent * event)
{
AbstractItem::mouseMoveEvent(event);
mMaster->setSelected(true);
}
void Rotater::mouseReleaseEvent(QGraphicsSceneMouseEvent * event)
{
AbstractItem::mouseReleaseEvent(event);
}
<|endoftext|>
|
<commit_before><commit_msg>Fix Typo<commit_after><|endoftext|>
|
<commit_before>#include "physics/transforms.hpp"
#include <limits>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "physics/degrees_of_freedom.hpp"
#include "physics/frame.hpp"
#include "physics/massive_body.hpp"
#include "physics/massless_body.hpp"
#include "quantities/named_quantities.hpp"
#include "quantities/quantities.hpp"
#include "testing_utilities/almost_equals.hpp"
#include "testing_utilities/numerics.hpp"
using principia::quantities::Length;
using principia::quantities::Mass;
using principia::quantities::SIUnit;
using principia::quantities::Speed;
using principia::quantities::Time;
using principia::testing_utilities::AbsoluteError;
using principia::testing_utilities::AlmostEquals;
using testing::Eq;
using testing::Lt;
namespace principia {
namespace physics {
namespace {
const int kNumberOfPoints = 20;
} // namespace
class TransformsTest : public testing::Test {
protected:
enum class Tag {
kFrom,
kThrough,
kTo,
};
using From = Frame<Tag, Tag::kFrom, true>;
using Through = Frame<Tag, Tag::kThrough, false>;
using To = Frame<Tag, Tag::kTo, true>;
void SetUp() override {
body1_ = std::make_unique<MassiveBody>(1 * SIUnit<Mass>());
body2_ = std::make_unique<MassiveBody>(3 * SIUnit<Mass>());
satellite_from_ = std::make_unique<Trajectory<From>>(satellite_);
body1_from_ = std::make_unique<Trajectory<From>>(*body1_);
body2_from_ = std::make_unique<Trajectory<From>>(*body2_);
body1_to_ = std::make_unique<Trajectory<To>>(*body1_);
body2_to_ = std::make_unique<Trajectory<To>>(*body2_);
// The various bodies move have both a position and a velocity that
// increases linearly with time. This is not a situation that's physically
// possible, but we don't care, all we want is to make sure that the
// transforms are properly performed: |Transforms| doesn't know anything
// about physics. Also, the trajectories were chosen so that we are not in
// any "special case" with respect to the positions or the velocities.
for (int i = 1; i <= kNumberOfPoints; ++i) {
body1_from_->Append(
Instant(i * SIUnit<Time>()),
DegreesOfFreedom<From>(
Position<From>(
Displacement<From>({1 * i * SIUnit<Length>(),
2 * i * SIUnit<Length>(),
3 * i * SIUnit<Length>()})),
Velocity<From>({4 * i * SIUnit<Speed>(),
8 * i * SIUnit<Speed>(),
16 * i * SIUnit<Speed>()})));
body2_from_->Append(
Instant(i * SIUnit<Time>()),
DegreesOfFreedom<From>(
Position<From>(
Displacement<From>({-1 * i * SIUnit<Length>(),
-2 * i * SIUnit<Length>(),
3 * i * SIUnit<Length>()})),
Velocity<From>({-4 * i * SIUnit<Speed>(),
8 * i * SIUnit<Speed>(),
-16 * i * SIUnit<Speed>()})));
satellite_from_->Append(
Instant(i * SIUnit<Time>()),
DegreesOfFreedom<From>(
Position<From>(
Displacement<From>({10 * i * SIUnit<Length>(),
-20 * i * SIUnit<Length>(),
30 * i * SIUnit<Length>()})),
Velocity<From>({40 * i * SIUnit<Speed>(),
-80 * i * SIUnit<Speed>(),
160 * i * SIUnit<Speed>()})));
}
}
std::unique_ptr<MassiveBody> body1_;
std::unique_ptr<MassiveBody> body2_;
MasslessBody satellite_;
std::unique_ptr<Trajectory<From>> body1_from_;
std::unique_ptr<Trajectory<From>> body2_from_;
std::unique_ptr<Trajectory<To>> body1_to_;
std::unique_ptr<Trajectory<To>> body2_to_;
std::unique_ptr<Trajectory<From>> satellite_from_;
std::unique_ptr<Transforms<From, Through, To>> transforms_;
};
// This transform is simple enough that we can compute its effect by hand. This
// test verifies that we get the expected result both in |Through| and in |To|.
TEST_F(TransformsTest, BodyCentredNonRotating) {
transforms_ = Transforms<From, Through, To>::BodyCentredNonRotating(
*body1_from_, *body1_to_);
Trajectory<Through> body1_through(*body1_);
int i = 1;
for (auto it = transforms_->first(satellite_from_.get());
!it.at_end();
++it, ++i) {
DegreesOfFreedom<Through> const degrees_of_freedom =
it.degrees_of_freedom();
EXPECT_THAT(degrees_of_freedom.position - Position<Through>(),
Eq(Displacement<Through>({9 * i * SIUnit<Length>(),
-22 * i * SIUnit<Length>(),
27 * i * SIUnit<Length>()}))) << i;
EXPECT_THAT(degrees_of_freedom.velocity,
Eq(Velocity<Through>({36 * i * SIUnit<Speed>(),
-88 * i * SIUnit<Speed>(),
144 * i * SIUnit<Speed>()}))) << i;
body1_through.Append(Instant(i * SIUnit<Time>()), degrees_of_freedom);
}
i = 1;
for (auto it = transforms_->second(&body1_through);
!it.at_end();
++it, ++i) {
body1_to_->Append(
Instant(i * SIUnit<Time>()),
DegreesOfFreedom<To>(
Position<To>(
Displacement<To>({3 * i * SIUnit<Length>(),
1 * i * SIUnit<Length>(),
2 * i * SIUnit<Length>()})),
Velocity<To>({16 * i * SIUnit<Speed>(),
4 * i * SIUnit<Speed>(),
8 * i * SIUnit<Speed>()})));
DegreesOfFreedom<To> const degrees_of_freedom =
it.degrees_of_freedom();
EXPECT_THAT(degrees_of_freedom.position - Position<To>(),
Eq(Displacement<To>({12 * i * SIUnit<Length>(),
-21 * i * SIUnit<Length>(),
29 * i * SIUnit<Length>()}))) << i;
EXPECT_THAT(degrees_of_freedom.velocity,
Eq(Velocity<To>({36 * i * SIUnit<Speed>(),
-88 * i * SIUnit<Speed>(),
144 * i * SIUnit<Speed>()}))) << i;
}
}
// Check that the computations we do match those done using Mathematica.
TEST_F(TransformsTest, SatelliteBarycentricRotating) {
transforms_ = Transforms<From, Through, To>::BarycentricRotating(
*body1_from_, *body1_to_,
*body2_from_, *body2_to_);
Trajectory<Through> satellite_through(satellite_);
int i = 1;
for (auto it = transforms_->first(satellite_from_.get());
!it.at_end();
++it, ++i) {
DegreesOfFreedom<Through> const degrees_of_freedom =
it.degrees_of_freedom();
EXPECT_THAT(degrees_of_freedom.position - Position<Through>(),
AlmostEquals(Displacement<Through>(
{-5.5 * sqrt(5.0) * i * SIUnit<Length>(),
62.0 * sqrt(5.0 / 21.0) * i * SIUnit<Length>(),
53.0 / sqrt(21.0) * i * SIUnit<Length>()}))) << i;
EXPECT_THAT(degrees_of_freedom.velocity,
AlmostEquals(Velocity<Through>(
{-134.0 / sqrt(5.0) * i * SIUnit<Speed>(),
1852.0 / sqrt(105.0) * i * SIUnit<Speed>(),
176.0 / sqrt(21.0) * i * SIUnit<Speed>()}))) << i;
satellite_through.Append(Instant(i * SIUnit<Time>()), degrees_of_freedom);
}
i = 1;
for (auto it = transforms_->second(&satellite_through);
!it.at_end();
++it, ++i) {
body1_to_->Append(
Instant(i * SIUnit<Time>()),
DegreesOfFreedom<To>(
Position<To>(
Displacement<To>({3 * i * SIUnit<Length>(),
1 * i * SIUnit<Length>(),
2 * i * SIUnit<Length>()})),
Velocity<To>({16 * i * SIUnit<Speed>(),
4 * i * SIUnit<Speed>(),
8 * i * SIUnit<Speed>()})));
body2_to_->Append(
Instant(i * SIUnit<Time>()),
DegreesOfFreedom<To>(
Position<To>(
Displacement<To>({3 * i * SIUnit<Length>(),
-1 * i * SIUnit<Length>(),
-2 * i * SIUnit<Length>()})),
Velocity<To>({-16 * i * SIUnit<Speed>(),
4 * i * SIUnit<Speed>(),
8 * i * SIUnit<Speed>()})));
DegreesOfFreedom<To> const degrees_of_freedom =
it.degrees_of_freedom();
EXPECT_THAT(degrees_of_freedom.position - Position<To>(),
AlmostEquals(Displacement<To>(
{(3.0 + 62.0 * sqrt(5.0 / 21.0)) * i * SIUnit<Length>(),
(-6.0 + 106.0 / sqrt(105.0)) * i * SIUnit<Length>(),
(-12.0 - 53.0 / sqrt(105.0)) * i * SIUnit<Length>()})))
<< i;
EXPECT_THAT(degrees_of_freedom.velocity,
AlmostEquals(Velocity<To>(
{1852.0 / sqrt(105.0) * i * SIUnit<Speed>(),
(-26.8 + 352.0 / sqrt(105.0)) * i * SIUnit<Speed>(),
(-53.6 - 176.0 / sqrt(105.0)) * i * SIUnit<Speed>()}),
12)) << i;
}
}
// Check that the bodies remain on the invariant line and at the right distance
// from each other and from the barycentre, and that the barycentre is the
// centre of the coordinates.
TEST_F(TransformsTest, BodiesBarycentricRotating) {
transforms_ = Transforms<From, Through, To>::BarycentricRotating(
*body1_from_, *body1_to_,
*body2_from_, *body2_to_);
Trajectory<Through> body1_through(*body1_);
Trajectory<Through> body2_through(*body2_);
int i = 1;
for (auto it1 = transforms_->first(body1_from_.get()),
it2 = transforms_->first(body2_from_.get());
!it1.at_end() && !it2.at_end();
++it1, ++it2, ++i) {
DegreesOfFreedom<Through> const degrees_of_freedom1 =
it1.degrees_of_freedom();
DegreesOfFreedom<Through> const degrees_of_freedom2 =
it2.degrees_of_freedom();
EXPECT_THAT(
AbsoluteError(degrees_of_freedom1.position - Position<Through>(),
Displacement<Through>(
{1.5 * sqrt(5.0) * i * SIUnit<Length>(),
0 * SIUnit<Length>(),
0 * SIUnit<Length>()})),
Lt(40 * std::numeric_limits<double>::epsilon() * SIUnit<Length>()));
EXPECT_THAT(
AbsoluteError(degrees_of_freedom2.position - Position<Through>(),
Displacement<Through>(
{-0.5 * sqrt(5.0) * i * SIUnit<Length>(),
0 * SIUnit<Length>(),
0 * SIUnit<Length>()})),
Lt(50 * std::numeric_limits<double>::epsilon() * SIUnit<Length>()));
// TODO(phl): Add a test that the velocities are along X once we have fixed
// them.
DegreesOfFreedom<Through> const barycentre_degrees_of_freedom =
Barycentre<Through, Mass>({degrees_of_freedom1, degrees_of_freedom2},
{body1_->mass(), body2_->mass()});
EXPECT_THAT(AbsoluteError(barycentre_degrees_of_freedom.position -
Position<Through>(),
Displacement<Through>()),
Lt(40 * std::numeric_limits<double>::epsilon() *
SIUnit<Length>())) << i;
EXPECT_THAT(AbsoluteError(barycentre_degrees_of_freedom.velocity,
Velocity<Through>()),
Lt(140 * std::numeric_limits<double>::epsilon() *
SIUnit<Speed>())) << i;
Length const length = (degrees_of_freedom1.position -
degrees_of_freedom2.position).Norm();
EXPECT_THAT(length, AlmostEquals(2.0 * sqrt(5.0) * i * SIUnit<Length>()));
}
}
} // namespace physics
} // namespace principia
<commit_msg>Failing test.<commit_after>#include "physics/transforms.hpp"
#include <limits>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "physics/degrees_of_freedom.hpp"
#include "physics/frame.hpp"
#include "physics/massive_body.hpp"
#include "physics/massless_body.hpp"
#include "quantities/named_quantities.hpp"
#include "quantities/quantities.hpp"
#include "testing_utilities/almost_equals.hpp"
#include "testing_utilities/numerics.hpp"
using principia::quantities::Length;
using principia::quantities::Mass;
using principia::quantities::SIUnit;
using principia::quantities::Speed;
using principia::quantities::Time;
using principia::testing_utilities::AbsoluteError;
using principia::testing_utilities::AlmostEquals;
using testing::Eq;
using testing::Lt;
namespace principia {
namespace physics {
namespace {
const int kNumberOfPoints = 20;
} // namespace
class TransformsTest : public testing::Test {
protected:
enum class Tag {
kFrom,
kThrough,
kTo,
};
using From = Frame<Tag, Tag::kFrom, true>;
using Through = Frame<Tag, Tag::kThrough, false>;
using To = Frame<Tag, Tag::kTo, true>;
void SetUp() override {
body1_ = std::make_unique<MassiveBody>(1 * SIUnit<Mass>());
body2_ = std::make_unique<MassiveBody>(3 * SIUnit<Mass>());
satellite_from_ = std::make_unique<Trajectory<From>>(satellite_);
body1_from_ = std::make_unique<Trajectory<From>>(*body1_);
body2_from_ = std::make_unique<Trajectory<From>>(*body2_);
body1_to_ = std::make_unique<Trajectory<To>>(*body1_);
body2_to_ = std::make_unique<Trajectory<To>>(*body2_);
// The various bodies move have both a position and a velocity that
// increases linearly with time. This is not a situation that's physically
// possible, but we don't care, all we want is to make sure that the
// transforms are properly performed: |Transforms| doesn't know anything
// about physics. Also, the trajectories were chosen so that we are not in
// any "special case" with respect to the positions or the velocities.
for (int i = 1; i <= kNumberOfPoints; ++i) {
body1_from_->Append(
Instant(i * SIUnit<Time>()),
DegreesOfFreedom<From>(
Position<From>(
Displacement<From>({1 * i * SIUnit<Length>(),
2 * i * SIUnit<Length>(),
3 * i * SIUnit<Length>()})),
Velocity<From>({4 * i * SIUnit<Speed>(),
8 * i * SIUnit<Speed>(),
16 * i * SIUnit<Speed>()})));
body2_from_->Append(
Instant(i * SIUnit<Time>()),
DegreesOfFreedom<From>(
Position<From>(
Displacement<From>({-1 * i * SIUnit<Length>(),
-2 * i * SIUnit<Length>(),
3 * i * SIUnit<Length>()})),
Velocity<From>({-4 * i * SIUnit<Speed>(),
8 * i * SIUnit<Speed>(),
-16 * i * SIUnit<Speed>()})));
satellite_from_->Append(
Instant(i * SIUnit<Time>()),
DegreesOfFreedom<From>(
Position<From>(
Displacement<From>({10 * i * SIUnit<Length>(),
-20 * i * SIUnit<Length>(),
30 * i * SIUnit<Length>()})),
Velocity<From>({40 * i * SIUnit<Speed>(),
-80 * i * SIUnit<Speed>(),
160 * i * SIUnit<Speed>()})));
}
}
std::unique_ptr<MassiveBody> body1_;
std::unique_ptr<MassiveBody> body2_;
MasslessBody satellite_;
std::unique_ptr<Trajectory<From>> body1_from_;
std::unique_ptr<Trajectory<From>> body2_from_;
std::unique_ptr<Trajectory<To>> body1_to_;
std::unique_ptr<Trajectory<To>> body2_to_;
std::unique_ptr<Trajectory<From>> satellite_from_;
std::unique_ptr<Transforms<From, Through, To>> transforms_;
};
// This transform is simple enough that we can compute its effect by hand. This
// test verifies that we get the expected result both in |Through| and in |To|.
TEST_F(TransformsTest, BodyCentredNonRotating) {
transforms_ = Transforms<From, Through, To>::BodyCentredNonRotating(
*body1_from_, *body1_to_);
Trajectory<Through> body1_through(*body1_);
int i = 1;
for (auto it = transforms_->first(satellite_from_.get());
!it.at_end();
++it, ++i) {
DegreesOfFreedom<Through> const degrees_of_freedom =
it.degrees_of_freedom();
EXPECT_THAT(degrees_of_freedom.position - Position<Through>(),
Eq(Displacement<Through>({9 * i * SIUnit<Length>(),
-22 * i * SIUnit<Length>(),
27 * i * SIUnit<Length>()}))) << i;
EXPECT_THAT(degrees_of_freedom.velocity,
Eq(Velocity<Through>({36 * i * SIUnit<Speed>(),
-88 * i * SIUnit<Speed>(),
144 * i * SIUnit<Speed>()}))) << i;
body1_through.Append(Instant(i * SIUnit<Time>()), degrees_of_freedom);
}
i = 1;
for (auto it = transforms_->second(&body1_through);
!it.at_end();
++it, ++i) {
body1_to_->Append(
Instant(i * SIUnit<Time>()),
DegreesOfFreedom<To>(
Position<To>(
Displacement<To>({3 * i * SIUnit<Length>(),
1 * i * SIUnit<Length>(),
2 * i * SIUnit<Length>()})),
Velocity<To>({16 * i * SIUnit<Speed>(),
4 * i * SIUnit<Speed>(),
8 * i * SIUnit<Speed>()})));
DegreesOfFreedom<To> const degrees_of_freedom =
it.degrees_of_freedom();
EXPECT_THAT(degrees_of_freedom.position - Position<To>(),
Eq(Displacement<To>({12 * i * SIUnit<Length>(),
-21 * i * SIUnit<Length>(),
29 * i * SIUnit<Length>()}))) << i;
EXPECT_THAT(degrees_of_freedom.velocity,
Eq(Velocity<To>({36 * i * SIUnit<Speed>(),
-88 * i * SIUnit<Speed>(),
144 * i * SIUnit<Speed>()}))) << i;
}
}
// Check that the computations we do match those done using Mathematica.
TEST_F(TransformsTest, SatelliteBarycentricRotating) {
transforms_ = Transforms<From, Through, To>::BarycentricRotating(
*body1_from_, *body1_to_,
*body2_from_, *body2_to_);
Trajectory<Through> satellite_through(satellite_);
int i = 1;
for (auto it = transforms_->first(satellite_from_.get());
!it.at_end();
++it, ++i) {
DegreesOfFreedom<Through> const degrees_of_freedom =
it.degrees_of_freedom();
EXPECT_THAT(degrees_of_freedom.position - Position<Through>(),
AlmostEquals(Displacement<Through>(
{-5.5 * sqrt(5.0) * i * SIUnit<Length>(),
62.0 * sqrt(5.0 / 21.0) * i * SIUnit<Length>(),
53.0 / sqrt(21.0) * i * SIUnit<Length>()}))) << i;
EXPECT_THAT(degrees_of_freedom.velocity,
AlmostEquals(Velocity<Through>(
{-134.0 / sqrt(5.0) * i * SIUnit<Speed>(),
1852.0 / sqrt(105.0) * i * SIUnit<Speed>(),
176.0 / sqrt(21.0) * i * SIUnit<Speed>()}))) << i;
satellite_through.Append(Instant(i * SIUnit<Time>()), degrees_of_freedom);
}
i = 1;
for (auto it = transforms_->second(&satellite_through);
!it.at_end();
++it, ++i) {
body1_to_->Append(
Instant(i * SIUnit<Time>()),
DegreesOfFreedom<To>(
Position<To>(
Displacement<To>({3 * i * SIUnit<Length>(),
1 * i * SIUnit<Length>(),
2 * i * SIUnit<Length>()})),
Velocity<To>({16 * i * SIUnit<Speed>(),
4 * i * SIUnit<Speed>(),
8 * i * SIUnit<Speed>()})));
body2_to_->Append(
Instant(i * SIUnit<Time>()),
DegreesOfFreedom<To>(
Position<To>(
Displacement<To>({3 * i * SIUnit<Length>(),
-1 * i * SIUnit<Length>(),
-2 * i * SIUnit<Length>()})),
Velocity<To>({-16 * i * SIUnit<Speed>(),
4 * i * SIUnit<Speed>(),
8 * i * SIUnit<Speed>()})));
DegreesOfFreedom<To> const degrees_of_freedom =
it.degrees_of_freedom();
EXPECT_THAT(degrees_of_freedom.position - Position<To>(),
AlmostEquals(Displacement<To>(
{(3.0 + 62.0 * sqrt(5.0 / 21.0)) * i * SIUnit<Length>(),
(-6.0 + 106.0 / sqrt(105.0)) * i * SIUnit<Length>(),
(-12.0 - 53.0 / sqrt(105.0)) * i * SIUnit<Length>()})))
<< i;
EXPECT_THAT(degrees_of_freedom.velocity,
AlmostEquals(Velocity<To>(
{1852.0 / sqrt(105.0) * i * SIUnit<Speed>(),
(-26.8 + 352.0 / sqrt(105.0)) * i * SIUnit<Speed>(),
(-53.6 - 176.0 / sqrt(105.0)) * i * SIUnit<Speed>()}),
12)) << i;
}
}
// Check that the bodies remain on the invariant line and at the right distance
// from each other and from the barycentre, and that the barycentre is the
// centre of the coordinates.
TEST_F(TransformsTest, BodiesBarycentricRotating) {
transforms_ = Transforms<From, Through, To>::BarycentricRotating(
*body1_from_, *body1_to_,
*body2_from_, *body2_to_);
Trajectory<Through> body1_through(*body1_);
Trajectory<Through> body2_through(*body2_);
int i = 1;
for (auto it1 = transforms_->first(body1_from_.get()),
it2 = transforms_->first(body2_from_.get());
!it1.at_end() && !it2.at_end();
++it1, ++it2, ++i) {
DegreesOfFreedom<Through> const degrees_of_freedom1 =
it1.degrees_of_freedom();
DegreesOfFreedom<Through> const degrees_of_freedom2 =
it2.degrees_of_freedom();
EXPECT_THAT(
AbsoluteError(degrees_of_freedom1.position - Position<Through>(),
Displacement<Through>(
{1.5 * sqrt(5.0) * i * SIUnit<Length>(),
0 * SIUnit<Length>(),
0 * SIUnit<Length>()})),
Lt(40 * std::numeric_limits<double>::epsilon() * SIUnit<Length>()));
EXPECT_THAT(
AbsoluteError(degrees_of_freedom2.position - Position<Through>(),
Displacement<Through>(
{-0.5 * sqrt(5.0) * i * SIUnit<Length>(),
0 * SIUnit<Length>(),
0 * SIUnit<Length>()})),
Lt(50 * std::numeric_limits<double>::epsilon() * SIUnit<Length>()));
EXPECT_THAT(
AbsoluteError(degrees_of_freedom1.velocity,
Velocity<Through>(
{1.5 * sqrt(5.0) * i * SIUnit<Speed>(),
0 * SIUnit<Speed>(),
0 * SIUnit<Speed>()})),
Lt(1 * std::numeric_limits<double>::epsilon() * SIUnit<Speed>()));
EXPECT_THAT(
AbsoluteError(degrees_of_freedom2.velocity,
Velocity<Through>(
{-0.5 * sqrt(5.0) * i * SIUnit<Speed>(),
0 * SIUnit<Speed>(),
0 * SIUnit<Speed>()})),
Lt(1 * std::numeric_limits<double>::epsilon() * SIUnit<Speed>()));
DegreesOfFreedom<Through> const barycentre_degrees_of_freedom =
Barycentre<Through, Mass>({degrees_of_freedom1, degrees_of_freedom2},
{body1_->mass(), body2_->mass()});
EXPECT_THAT(AbsoluteError(barycentre_degrees_of_freedom.position -
Position<Through>(),
Displacement<Through>()),
Lt(40 * std::numeric_limits<double>::epsilon() *
SIUnit<Length>())) << i;
EXPECT_THAT(AbsoluteError(barycentre_degrees_of_freedom.velocity,
Velocity<Through>()),
Lt(140 * std::numeric_limits<double>::epsilon() *
SIUnit<Speed>())) << i;
Length const length = (degrees_of_freedom1.position -
degrees_of_freedom2.position).Norm();
EXPECT_THAT(length, AlmostEquals(2.0 * sqrt(5.0) * i * SIUnit<Length>()));
}
}
} // namespace physics
} // namespace principia
<|endoftext|>
|
<commit_before>#pragma once
#include "elog_entry.hpp"
#include "xyz/openbmc_project/Collection/DeleteAll/server.hpp"
#include "xyz/openbmc_project/Logging/Create/server.hpp"
#include "xyz/openbmc_project/Logging/Entry/server.hpp"
#include "xyz/openbmc_project/Logging/Internal/Manager/server.hpp"
#include <list>
#include <phosphor-logging/log.hpp>
#include <sdbusplus/bus.hpp>
namespace phosphor
{
namespace logging
{
extern const std::map<std::string, std::vector<std::string>> g_errMetaMap;
extern const std::map<std::string, level> g_errLevelMap;
using CreateIface = sdbusplus::xyz::openbmc_project::Logging::server::Create;
using DeleteAllIface =
sdbusplus::xyz::openbmc_project::Collection::server::DeleteAll;
namespace details
{
template <typename... T>
using ServerObject = typename sdbusplus::server::object::object<T...>;
using ManagerIface =
sdbusplus::xyz::openbmc_project::Logging::Internal::server::Manager;
} // namespace details
namespace internal
{
/** @class Manager
* @brief OpenBMC logging manager implementation.
* @details A concrete implementation for the
* xyz.openbmc_project.Logging.Internal.Manager DBus API.
*/
class Manager : public details::ServerObject<details::ManagerIface>
{
public:
Manager() = delete;
Manager(const Manager&) = delete;
Manager& operator=(const Manager&) = delete;
Manager(Manager&&) = delete;
Manager& operator=(Manager&&) = delete;
virtual ~Manager() = default;
/** @brief Constructor to put object onto bus at a dbus path.
* @param[in] bus - Bus to attach to.
* @param[in] path - Path to attach at.
*/
Manager(sdbusplus::bus::bus& bus, const char* objPath) :
details::ServerObject<details::ManagerIface>(bus, objPath), busLog(bus),
entryId(0), fwVersion(readFWVersion()){};
/*
* @fn commit()
* @brief sd_bus Commit method implementation callback.
* @details Create an error/event log based on transaction id and
* error message.
* @param[in] transactionId - Unique identifier of the journal entries
* to be committed.
* @param[in] errMsg - The error exception message associated with the
* error log to be committed.
*/
void commit(uint64_t transactionId, std::string errMsg) override;
/*
* @fn commit()
* @brief sd_bus CommitWithLvl method implementation callback.
* @details Create an error/event log based on transaction id and
* error message.
* @param[in] transactionId - Unique identifier of the journal entries
* to be committed.
* @param[in] errMsg - The error exception message associated with the
* error log to be committed.
* @param[in] errLvl - level of the error
*/
void commitWithLvl(uint64_t transactionId, std::string errMsg,
uint32_t errLvl) override;
/** @brief Erase specified entry d-bus object
*
* @param[in] entryId - unique identifier of the entry
*/
void erase(uint32_t entryId);
/** @brief Construct error d-bus objects from their persisted
* representations.
*/
void restore();
/** @brief Erase all error log entries
*
*/
void eraseAll()
{
auto iter = entries.begin();
while (iter != entries.end())
{
auto e = iter->first;
++iter;
erase(e);
}
}
/** @brief Returns the count of high severity errors
*
* @return int - count of real errors
*/
int getRealErrSize();
/** @brief Returns the count of Info errors
*
* @return int - count of info errors
*/
int getInfoErrSize();
sdbusplus::bus::bus& getBus()
{
return busLog;
}
/** @brief Creates an event log
*
* This is an alternative to the _commit() API. It doesn't use
* the journal to look up event log metadata like _commit does.
*
* @param[in] errMsg - The error exception message associated with the
* error log to be committed.
* @param[in] severity - level of the error
* @param[in] additionalData - The AdditionalData property for the error
*/
void create(
const std::string& message,
sdbusplus::xyz::openbmc_project::Logging::server::Entry::Level severity,
const std::map<std::string, std::string>& additionalData);
private:
/*
* @fn _commit()
* @brief commit() helper
* @param[in] transactionId - Unique identifier of the journal entries
* to be committed.
* @param[in] errMsg - The error exception message associated with the
* error log to be committed.
* @param[in] errLvl - level of the error
*/
void _commit(uint64_t transactionId, std::string&& errMsg,
Entry::Level errLvl);
/** @brief Call metadata handler(s), if any. Handlers may create
* associations.
* @param[in] errorName - name of the error
* @param[in] additionalData - list of metadata (in key=value format)
* @param[out] objects - list of error's association objects
*/
void processMetadata(const std::string& errorName,
const std::vector<std::string>& additionalData,
AssociationList& objects) const;
/** @brief Synchronize unwritten journal messages to disk.
* @details This is the same implementation as the systemd command
* "journalctl --sync".
*/
void journalSync();
/** @brief Reads the BMC code level
*
* @return std::string - the version string
*/
static std::string readFWVersion();
/** @brief Call any create() functions provided by any extensions.
* This is called right after an event log is created to allow
* extensions to create their own log based on this one.
*
* @param[in] entry - the new event log entry
*/
void doExtensionLogCreate(const Entry& entry);
/** @brief Common wrapper for creating an Entry object
*
* @param[in] errMsg - The error exception message associated with the
* error log to be committed.
* @param[in] errLvl - level of the error
* @param[in] additionalData - The AdditionalData property for the error
*/
void createEntry(std::string errMsg, Entry::Level errLvl,
std::vector<std::string> additionalData);
/** @brief Persistent sdbusplus DBus bus connection. */
sdbusplus::bus::bus& busLog;
/** @brief Persistent map of Entry dbus objects and their ID */
std::map<uint32_t, std::unique_ptr<Entry>> entries;
/** @brief List of error ids for high severity errors */
std::list<uint32_t> realErrors;
/** @brief List of error ids for Info(and below) severity */
std::list<uint32_t> infoErrors;
/** @brief Id of last error log entry */
uint32_t entryId;
/** @brief The BMC firmware version */
const std::string fwVersion;
};
} // namespace internal
/** @class Manager
* @brief Implementation for deleting all error log entries and
* creating new logs.
* @details A concrete implementation for the
* xyz.openbmc_project.Collection.DeleteAll and
* xyz.openbmc_project.Logging.Create interfaces.
*/
class Manager : public details::ServerObject<DeleteAllIface, CreateIface>
{
public:
Manager() = delete;
Manager(const Manager&) = delete;
Manager& operator=(const Manager&) = delete;
Manager(Manager&&) = delete;
Manager& operator=(Manager&&) = delete;
virtual ~Manager() = default;
/** @brief Constructor to put object onto bus at a dbus path.
* Defer signal registration (pass true for deferSignal to the
* base class) until after the properties are set.
* @param[in] bus - Bus to attach to.
* @param[in] path - Path to attach at.
* @param[in] manager - Reference to internal manager object.
*/
Manager(sdbusplus::bus::bus& bus, const std::string& path,
internal::Manager& manager) :
details::ServerObject<DeleteAllIface, CreateIface>(bus, path.c_str(),
true),
manager(manager){};
/** @brief Delete all d-bus objects.
*/
void deleteAll()
{
manager.eraseAll();
}
/** @brief D-Bus method call implementation to create an event log.
*
* @param[in] errMsg - The error exception message associated with the
* error log to be committed.
* @param[in] severity - Level of the error
* @param[in] additionalData - The AdditionalData property for the error
*/
void create(
std::string message,
sdbusplus::xyz::openbmc_project::Logging::server::Entry::Level severity,
std::map<std::string, std::string> additionalData) override
{
manager.create(message, severity, additionalData);
}
void createWithFFDCFiles(
std::string message,
sdbusplus::xyz::openbmc_project::Logging::server::Entry::Level severity,
std::map<std::string, std::string> additionalData,
std::vector<std::tuple<CreateIface::FFDCFormat, uint8_t, uint8_t,
sdbusplus::message::unix_fd>>
ffdc) override
{
}
private:
/** @brief This is a reference to manager object */
internal::Manager& manager;
};
} // namespace logging
} // namespace phosphor
<commit_msg>Format fix<commit_after>#pragma once
#include "elog_entry.hpp"
#include "xyz/openbmc_project/Collection/DeleteAll/server.hpp"
#include "xyz/openbmc_project/Logging/Create/server.hpp"
#include "xyz/openbmc_project/Logging/Entry/server.hpp"
#include "xyz/openbmc_project/Logging/Internal/Manager/server.hpp"
#include <list>
#include <phosphor-logging/log.hpp>
#include <sdbusplus/bus.hpp>
namespace phosphor
{
namespace logging
{
extern const std::map<std::string, std::vector<std::string>> g_errMetaMap;
extern const std::map<std::string, level> g_errLevelMap;
using CreateIface = sdbusplus::xyz::openbmc_project::Logging::server::Create;
using DeleteAllIface =
sdbusplus::xyz::openbmc_project::Collection::server::DeleteAll;
namespace details
{
template <typename... T>
using ServerObject = typename sdbusplus::server::object::object<T...>;
using ManagerIface =
sdbusplus::xyz::openbmc_project::Logging::Internal::server::Manager;
} // namespace details
namespace internal
{
/** @class Manager
* @brief OpenBMC logging manager implementation.
* @details A concrete implementation for the
* xyz.openbmc_project.Logging.Internal.Manager DBus API.
*/
class Manager : public details::ServerObject<details::ManagerIface>
{
public:
Manager() = delete;
Manager(const Manager&) = delete;
Manager& operator=(const Manager&) = delete;
Manager(Manager&&) = delete;
Manager& operator=(Manager&&) = delete;
virtual ~Manager() = default;
/** @brief Constructor to put object onto bus at a dbus path.
* @param[in] bus - Bus to attach to.
* @param[in] path - Path to attach at.
*/
Manager(sdbusplus::bus::bus& bus, const char* objPath) :
details::ServerObject<details::ManagerIface>(bus, objPath), busLog(bus),
entryId(0), fwVersion(readFWVersion()){};
/*
* @fn commit()
* @brief sd_bus Commit method implementation callback.
* @details Create an error/event log based on transaction id and
* error message.
* @param[in] transactionId - Unique identifier of the journal entries
* to be committed.
* @param[in] errMsg - The error exception message associated with the
* error log to be committed.
*/
void commit(uint64_t transactionId, std::string errMsg) override;
/*
* @fn commit()
* @brief sd_bus CommitWithLvl method implementation callback.
* @details Create an error/event log based on transaction id and
* error message.
* @param[in] transactionId - Unique identifier of the journal entries
* to be committed.
* @param[in] errMsg - The error exception message associated with the
* error log to be committed.
* @param[in] errLvl - level of the error
*/
void commitWithLvl(uint64_t transactionId, std::string errMsg,
uint32_t errLvl) override;
/** @brief Erase specified entry d-bus object
*
* @param[in] entryId - unique identifier of the entry
*/
void erase(uint32_t entryId);
/** @brief Construct error d-bus objects from their persisted
* representations.
*/
void restore();
/** @brief Erase all error log entries
*
*/
void eraseAll()
{
auto iter = entries.begin();
while (iter != entries.end())
{
auto e = iter->first;
++iter;
erase(e);
}
}
/** @brief Returns the count of high severity errors
*
* @return int - count of real errors
*/
int getRealErrSize();
/** @brief Returns the count of Info errors
*
* @return int - count of info errors
*/
int getInfoErrSize();
sdbusplus::bus::bus& getBus()
{
return busLog;
}
/** @brief Creates an event log
*
* This is an alternative to the _commit() API. It doesn't use
* the journal to look up event log metadata like _commit does.
*
* @param[in] errMsg - The error exception message associated with the
* error log to be committed.
* @param[in] severity - level of the error
* @param[in] additionalData - The AdditionalData property for the error
*/
void create(
const std::string& message,
sdbusplus::xyz::openbmc_project::Logging::server::Entry::Level severity,
const std::map<std::string, std::string>& additionalData);
private:
/*
* @fn _commit()
* @brief commit() helper
* @param[in] transactionId - Unique identifier of the journal entries
* to be committed.
* @param[in] errMsg - The error exception message associated with the
* error log to be committed.
* @param[in] errLvl - level of the error
*/
void _commit(uint64_t transactionId, std::string&& errMsg,
Entry::Level errLvl);
/** @brief Call metadata handler(s), if any. Handlers may create
* associations.
* @param[in] errorName - name of the error
* @param[in] additionalData - list of metadata (in key=value format)
* @param[out] objects - list of error's association objects
*/
void processMetadata(const std::string& errorName,
const std::vector<std::string>& additionalData,
AssociationList& objects) const;
/** @brief Synchronize unwritten journal messages to disk.
* @details This is the same implementation as the systemd command
* "journalctl --sync".
*/
void journalSync();
/** @brief Reads the BMC code level
*
* @return std::string - the version string
*/
static std::string readFWVersion();
/** @brief Call any create() functions provided by any extensions.
* This is called right after an event log is created to allow
* extensions to create their own log based on this one.
*
* @param[in] entry - the new event log entry
*/
void doExtensionLogCreate(const Entry& entry);
/** @brief Common wrapper for creating an Entry object
*
* @param[in] errMsg - The error exception message associated with the
* error log to be committed.
* @param[in] errLvl - level of the error
* @param[in] additionalData - The AdditionalData property for the error
*/
void createEntry(std::string errMsg, Entry::Level errLvl,
std::vector<std::string> additionalData);
/** @brief Persistent sdbusplus DBus bus connection. */
sdbusplus::bus::bus& busLog;
/** @brief Persistent map of Entry dbus objects and their ID */
std::map<uint32_t, std::unique_ptr<Entry>> entries;
/** @brief List of error ids for high severity errors */
std::list<uint32_t> realErrors;
/** @brief List of error ids for Info(and below) severity */
std::list<uint32_t> infoErrors;
/** @brief Id of last error log entry */
uint32_t entryId;
/** @brief The BMC firmware version */
const std::string fwVersion;
};
} // namespace internal
/** @class Manager
* @brief Implementation for deleting all error log entries and
* creating new logs.
* @details A concrete implementation for the
* xyz.openbmc_project.Collection.DeleteAll and
* xyz.openbmc_project.Logging.Create interfaces.
*/
class Manager : public details::ServerObject<DeleteAllIface, CreateIface>
{
public:
Manager() = delete;
Manager(const Manager&) = delete;
Manager& operator=(const Manager&) = delete;
Manager(Manager&&) = delete;
Manager& operator=(Manager&&) = delete;
virtual ~Manager() = default;
/** @brief Constructor to put object onto bus at a dbus path.
* Defer signal registration (pass true for deferSignal to the
* base class) until after the properties are set.
* @param[in] bus - Bus to attach to.
* @param[in] path - Path to attach at.
* @param[in] manager - Reference to internal manager object.
*/
Manager(sdbusplus::bus::bus& bus, const std::string& path,
internal::Manager& manager) :
details::ServerObject<DeleteAllIface, CreateIface>(bus, path.c_str(),
true),
manager(manager){};
/** @brief Delete all d-bus objects.
*/
void deleteAll()
{
manager.eraseAll();
}
/** @brief D-Bus method call implementation to create an event log.
*
* @param[in] errMsg - The error exception message associated with the
* error log to be committed.
* @param[in] severity - Level of the error
* @param[in] additionalData - The AdditionalData property for the error
*/
void create(
std::string message,
sdbusplus::xyz::openbmc_project::Logging::server::Entry::Level severity,
std::map<std::string, std::string> additionalData) override
{
manager.create(message, severity, additionalData);
}
void createWithFFDCFiles(
std::string message,
sdbusplus::xyz::openbmc_project::Logging::server::Entry::Level severity,
std::map<std::string, std::string> additionalData,
std::vector<std::tuple<CreateIface::FFDCFormat, uint8_t, uint8_t,
sdbusplus::message::unix_fd>>
ffdc) override
{
}
private:
/** @brief This is a reference to manager object */
internal::Manager& manager;
};
} // namespace logging
} // namespace phosphor
<|endoftext|>
|
<commit_before>class dataRecord
{
public :
void addField(std::string value);
friend bool isMatch(dataRecord rec1, dataRecord rec2);
private :
int numFields;
std::vector<std::string> fields;
std::vector<int> id;
}
class dataRecordSet
{
public :
void readFile(std::string fname);
void writeFile(std::string fname);
void addColumn(dataRecordSet recSet, int col);
private :
int numRecords;
std::vector<dataRecord> records;
}
<commit_msg>Added initial read record routine.<commit_after>class dataRecord
{
public :
void addField(std::string value);
friend bool isMatch(dataRecord rec1, dataRecord rec2);
private :
int numFields;
std::vector<std::string> fields;
std::vector<int> syncFieldNum;
}
class dataRecordSet
{
public :
void readFile(std::string fname);
void writeFile(std::string fname);
void addColumn(dataRecordSet recSet, int col);
private :
char recSeparator=",";
int numRecords;
std::vector<std::string> columnLabels;
std::vector<dataRecord> records;
std::string readRecord(std::stringstream input);
}
void dataRecord::addField(std::string value)
{
fields.push_back(value);
numFields=fields.size();
}
std::string dataRecordSet::readRecord(std::stringstream input)
{
std::string rec;
rec.resize(input.size());
auto c=rec.begin();
*c=input.getc();
while (*c!=",") *(c++)=input.getc();
rec.resize(c-rec.begin());
}
<|endoftext|>
|
<commit_before>/*BEGIN_LEGAL
Intel Open Source License
Copyright (c) 2002-2013 Intel Corporation. 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 Intel Corporation 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 INTEL OR
ITS 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.
END_LEGAL */
#include "pin.H"
#include <iostream>
#include <cstdio>
#include <cstring>
#include <set>
#include "memlist.h"
#include "memoryalloc.h"
#include "stats.h"
using namespace std;
// Prototypes ; TODO: Move to Seperate Header file?
void HookFree(IMG img);
void HookMalloc(IMG img);
void HookCalloc(IMG img);
void HookRealloc(IMG img);
typedef VOID* (*FP_MALLOC)(size_t);
typedef void (*FP_FREE)(void*);
typedef void* (*FP_CALLOC)(size_t, size_t);
typedef void* (*FP_REALLOC)(void*, size_t);
bool hasEnding (std::string const &fullString, std::string const &ending);
bool inMain = false;
FILE * trace;
MemList ml;
Stats stats;
// Print a memory read record
VOID RecordHeapMemRead(VOID * ip, VOID * addr) {
int rtn = ml.containsAddress(addr);
if(rtn == ERR_IN_FENCE) {
fprintf(trace,"##########BAD WRITE: %p \n", addr);
cout << "BAD READ" << endl;
stats.incInvalidReadCount();
}
//printf("heap read: %p\n", addr);
}
// Print a memory write record
VOID RecordHeapMemWrite(VOID * ip, VOID * addr) {
int rtn = ml.containsAddress(addr);
if(rtn == ERR_IN_FENCE) {
fprintf(trace,"##########BAD WRITE: %p \n", addr);
cout << "BAD WRITE" << endl;
stats.incInvalidWriteCount();
}
//printf("heap write: %p\n", addr);
}
bool hasEnding (std::string const &fullString, std::string const &ending) {
if (fullString.length() >= ending.length()) {
return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending));
} else {
return false;
}
}
VOID RecordStackMemRead(VOID * ip, VOID * addr) {
//printf("stack read: %p\n", addr);
}
// Print a memory write record
VOID RecordStackMemWrite(VOID * ip, VOID * addr) {
//printf("stack write: %p\n", addr);
}
// Set global inMain = true
VOID SetInMain(void){
inMain = true;
cout << "Main execution started" << endl;
}
// Is called for every instruction and instruments reads and writes
VOID Instruction(INS ins, VOID *v) {
if(!inMain)
return;
// Instruments memory accesses using a predicated call, i.e.
// the instrumentation is called iff the instruction will actually be executed.
//
// On the IA-32 and Intel(R) 64 architectures conditional moves and REP
// prefixed instructions appear as predicated instructions in Pin.
UINT32 memOperands = INS_MemoryOperandCount(ins);
// Iterate over each memory operand of the instruction.
for (UINT32 memOp = 0; memOp < memOperands; memOp++) {
//if (INS_MemoryOperandIsRead(ins, memOp)) {
if (INS_MemoryOperandIsRead(ins, memOp) && !INS_IsStackRead(ins)) {
INS_InsertPredicatedCall(
ins, IPOINT_BEFORE, (AFUNPTR)RecordHeapMemRead,
IARG_INST_PTR,
IARG_MEMORYOP_EA, memOp,
IARG_END);
} else if (INS_MemoryOperandIsRead(ins, memOp)) {
INS_InsertPredicatedCall(
ins, IPOINT_BEFORE, (AFUNPTR)RecordStackMemRead,
IARG_INST_PTR,
IARG_MEMORYOP_EA, memOp,
IARG_END);
}
// Note that in some architectures a single memory operand can be
// both read and written (for instance incl (%eax) on IA-32)
// In that case we instrument it once for read and once for write.
//if (INS_MemoryOperandIsWritten(ins, memOp)) {
if (INS_MemoryOperandIsWritten(ins, memOp) && !INS_IsStackWrite(ins)) {
INS_InsertPredicatedCall(
ins, IPOINT_BEFORE, (AFUNPTR)RecordHeapMemWrite,
IARG_INST_PTR,
IARG_MEMORYOP_EA, memOp,
IARG_END);
} else if (INS_MemoryOperandIsWritten(ins, memOp)) {
INS_InsertPredicatedCall(
ins, IPOINT_BEFORE, (AFUNPTR)RecordStackMemWrite,
IARG_INST_PTR,
IARG_MEMORYOP_EA, memOp,
IARG_END);
}
}
}
VOID Fini(INT32 code, VOID *v) {
fprintf(trace, "#eof \n");
// Display the stats
stats.displayResults(ml, trace);
fclose(trace);
}
// This is the replacement routine.
VOID* NewMalloc(FP_MALLOC orgFuncptr, UINT32 arg0, ADDRINT returnIp) {
// Call the relocated entry point of the original (replaced) routine.
void* v = orgFuncptr(arg0 + (2 * DEFAULT_FENCE_SIZE));
stats.incMallocCount();
MemoryAlloc ma = ml.add(v, arg0, DEFAULT_FENCE_SIZE);
fprintf(trace, "ADDED: %p %d \n", v, DEFAULT_FENCE_SIZE);
return ma.getAddress();
}
void* NewCalloc(FP_CALLOC libc_calloc, UINT32 arg0, UINT32 arg1, ADDRINT returnIp) {
// Calculate the size in bytes
size_t bytes = (arg0 * arg1);
size_t totalSize = bytes + (2 + DEFAULT_FENCE_SIZE);
// Figure out the correct amount of chunks
size_t nmemb = totalSize / arg1;
size_t nmembe = totalSize % arg1;
nmembe = (nmembe > 0) ? 1 : 0;
// Sum up the chunks
nmemb += nmembe;
// Allocate space using malloc
void *ptr = libc_calloc(nmemb, arg1);
// Create a new MemoryAlloc
MemoryAlloc ma = ml.add(ptr, bytes, DEFAULT_FENCE_SIZE);
// Add the information to the trace file
fprintf(trace, "ADDED: %p %d \n", ptr, DEFAULT_FENCE_SIZE);
stats.incMallocCount();
return ma.getAddress();
}
void* NewRealloc(FP_REALLOC orgFuncptr, void* arg0, UINT32 arg1, ADDRINT returnIp) {
printf("New Realloc was called\n");
return arg0;
}
void NewFree(FP_FREE orgFuncptr, void* ptr, ADDRINT returnIp) {
if(ptr != NULL) {
// Check the MemList
int index = ml.containsAddress(ptr);
if(index >= 0) {
MemoryAlloc alloc = ml.get(index);
// Remove the space
orgFuncptr(alloc.getUnderflowFence());
fprintf(trace, "Freed the memory @ address %p successfully.\n", alloc.getUnderflowFence());
// Remove the element from the list
ml.removeMatching(alloc);
stats.incFreeCount();
} else if(index == ERR_NOT_FOUND) {
// This currently gets hit since a blacklist is being used
fprintf(trace, "Address = %p not found. Bad address or stack address used.\n", ptr);
stats.incInvalidFreeCount();
/*
// Dump all memory currently stored
char buffer[1024];
for(int i = 0; i < ml.size(); i++) {
fprintf(trace, "%s\n", ml.get(i).toString(buffer, 1024));
}
*/
} else if(index == ERR_MID_CHUNK) {
fprintf(trace, "Mid-chunk memory deallocation @ %p\n", ptr);
stats.incMidFreeChunkCount();
} else if(index == ERR_IN_FENCE) {
fprintf(trace, "Memory Fence Hit @ %p\n", ptr);
stats.incFenceHitCount();
} else {
// This should Never happen...
fprintf(trace, "index = %d : Unable to deallocate the memory @ %p\n", index, ptr);
}
} else {
fprintf(trace, "Attempted to free NULL\n");
stats.incFreeNullCount();
}
}
// Pin calls this function every time a new img is loaded.
// It is best to do probe replacement when the image is loaded,
// because only one thread knows about the image at this time.
VOID ImageLoad(IMG img, VOID *v) {
if(IMG_IsMainExecutable(img)) {
RTN rtn = RTN_FindByName(img, "main");
RTN_Open(rtn);//Must open RTN API before examining instructions
INS ins = RTN_InsHead(rtn);
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)SetInMain, IARG_END);
RTN_Close(rtn);
}
if(!hasEnding(IMG_Name(img), "libc.so.6")) {
return;
}
if(!inMain) {
inMain = IMG_IsMainExecutable(img);
}
// Hook Functions
HookMalloc(img);
HookFree(img);
HookCalloc(img);
HookRealloc(img);
}
void HookFree(IMG img) {
RTN rtn = RTN_FindByName(img, "free");
if(RTN_Valid(rtn)) {
cout << "Replacing free in " << IMG_Name(img) << endl;
// Return type, cstype, function name, arguments...
PROTO proto = PROTO_Allocate(PIN_PARG(void), CALLINGSTD_DEFAULT, "free", PIN_PARG(void*), PIN_PARG_END());
// Replace free
RTN_ReplaceSignature(rtn, AFUNPTR(NewFree),
IARG_PROTOTYPE,
proto,
IARG_ORIG_FUNCPTR,
IARG_FUNCARG_ENTRYPOINT_VALUE,
0,
IARG_RETURN_IP,
IARG_END);
// Free the function prototype
PROTO_Free(proto);
}
}
void HookMalloc(IMG img) {
// See if malloc() is present in the image. If so, replace it.
RTN rtnMalloc = RTN_FindByName(img, "malloc");
if(RTN_Valid(rtnMalloc)) {
cout << "Replacing malloc in " << IMG_Name(img) << endl;
PROTO proto_malloc = PROTO_Allocate(PIN_PARG(void *), CALLINGSTD_DEFAULT,
"malloc", PIN_PARG(int), PIN_PARG_END());
RTN_ReplaceSignature(rtnMalloc, AFUNPTR(NewMalloc),
IARG_PROTOTYPE, proto_malloc,
IARG_ORIG_FUNCPTR,
IARG_FUNCARG_ENTRYPOINT_VALUE, 0,
IARG_RETURN_IP,
IARG_END);
// Free the function prototype.
PROTO_Free(proto_malloc);
}
}
void HookCalloc(IMG img) {
// See if calloc() is present in the image. If so, replace it.
RTN rtn = RTN_FindByName(img, "calloc");
if(RTN_Valid(rtn)) {
cout << "Replacing calloc in " << IMG_Name(img) << endl;
PROTO proto = PROTO_Allocate(PIN_PARG(void *), CALLINGSTD_DEFAULT,
"calloc", PIN_PARG(size_t), PIN_PARG(size_t), PIN_PARG_END());
RTN_ReplaceSignature(rtn, AFUNPTR(NewCalloc),
IARG_PROTOTYPE, proto,
IARG_ORIG_FUNCPTR,
IARG_FUNCARG_ENTRYPOINT_VALUE, 0,
IARG_RETURN_IP,
IARG_END);
// Free the function prototype.
PROTO_Free(proto);
}
}
void HookRealloc(IMG img) {
// See if calloc() is present in the image. If so, replace it.
RTN rtn = RTN_FindByName(img, "realloc");
if(RTN_Valid(rtn)) {
cout << "Replacing realloc in " << IMG_Name(img) << endl;
PROTO proto = PROTO_Allocate(PIN_PARG(void *), CALLINGSTD_DEFAULT,
"realloc", PIN_PARG(void*), PIN_PARG(size_t), PIN_PARG_END());
RTN_ReplaceSignature(rtn, AFUNPTR(NewRealloc),
IARG_PROTOTYPE, proto,
IARG_ORIG_FUNCPTR,
IARG_FUNCARG_ENTRYPOINT_VALUE, 0,
IARG_RETURN_IP,
IARG_END);
// Free the function prototype.
PROTO_Free(proto);
}
}
/* ===================================================================== */
/* Print Help Message */
/* ===================================================================== */
INT32 Usage() {
cerr << "This tool demonstrates how to replace an original" << endl;
cerr << " function with a custom function defined in the tool " << endl;
cerr << " using probes. The replacement function has a different " << endl;
cerr << " signature from that of the original replaced function." << endl;
cerr << endl << KNOB_BASE::StringKnobSummary() << endl;
return -1;
}
/* ===================================================================== */
/* Main: Initialize and start Pin in Probe mode. */
/* ===================================================================== */
int main(INT32 argc, CHAR *argv[]) {
// Initialize symbol processing
PIN_InitSymbols();
// Initialize pin
if (PIN_Init(argc, argv))
return Usage();
// Open up the trace file
trace = fopen("zzz.out", "w");
// Register ImageLoad to be called when an image is loaded
IMG_AddInstrumentFunction(ImageLoad, 0);
INS_AddInstrumentFunction(Instruction, 0);
PIN_AddFiniFunction(Fini, 0);
PIN_StartProgram();
return 0;
}
<commit_msg>Removed print statements from stdout.<commit_after>/*BEGIN_LEGAL
Intel Open Source License
Copyright (c) 2002-2013 Intel Corporation. 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 Intel Corporation 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 INTEL OR
ITS 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.
END_LEGAL */
#include "pin.H"
#include <iostream>
#include <cstdio>
#include <cstring>
#include <set>
#include "memlist.h"
#include "memoryalloc.h"
#include "stats.h"
using namespace std;
// Prototypes ; TODO: Move to Seperate Header file?
void HookFree(IMG img);
void HookMalloc(IMG img);
void HookCalloc(IMG img);
void HookRealloc(IMG img);
typedef VOID* (*FP_MALLOC)(size_t);
typedef void (*FP_FREE)(void*);
typedef void* (*FP_CALLOC)(size_t, size_t);
typedef void* (*FP_REALLOC)(void*, size_t);
bool hasEnding (std::string const &fullString, std::string const &ending);
bool inMain = false;
FILE * trace;
MemList ml;
Stats stats;
// Print a memory read record
VOID RecordHeapMemRead(VOID * ip, VOID * addr) {
int rtn = ml.containsAddress(addr);
if(rtn == ERR_IN_FENCE) {
fprintf(trace,"##########BAD WRITE: %p \n", addr);
stats.incInvalidReadCount();
}
//printf("heap read: %p\n", addr);
}
// Print a memory write record
VOID RecordHeapMemWrite(VOID * ip, VOID * addr) {
int rtn = ml.containsAddress(addr);
if(rtn == ERR_IN_FENCE) {
fprintf(trace,"##########BAD WRITE: %p \n", addr);
stats.incInvalidWriteCount();
}
//printf("heap write: %p\n", addr);
}
bool hasEnding (std::string const &fullString, std::string const &ending) {
if (fullString.length() >= ending.length()) {
return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending));
} else {
return false;
}
}
VOID RecordStackMemRead(VOID * ip, VOID * addr) {
//printf("stack read: %p\n", addr);
}
// Print a memory write record
VOID RecordStackMemWrite(VOID * ip, VOID * addr) {
//printf("stack write: %p\n", addr);
}
// Set global inMain = true
VOID SetInMain(void){
inMain = true;
fprintf(trace, "Main execution started\n");
}
// Is called for every instruction and instruments reads and writes
VOID Instruction(INS ins, VOID *v) {
if(!inMain)
return;
// Instruments memory accesses using a predicated call, i.e.
// the instrumentation is called iff the instruction will actually be executed.
//
// On the IA-32 and Intel(R) 64 architectures conditional moves and REP
// prefixed instructions appear as predicated instructions in Pin.
UINT32 memOperands = INS_MemoryOperandCount(ins);
// Iterate over each memory operand of the instruction.
for (UINT32 memOp = 0; memOp < memOperands; memOp++) {
//if (INS_MemoryOperandIsRead(ins, memOp)) {
if (INS_MemoryOperandIsRead(ins, memOp) && !INS_IsStackRead(ins)) {
INS_InsertPredicatedCall(
ins, IPOINT_BEFORE, (AFUNPTR)RecordHeapMemRead,
IARG_INST_PTR,
IARG_MEMORYOP_EA, memOp,
IARG_END);
} else if (INS_MemoryOperandIsRead(ins, memOp)) {
INS_InsertPredicatedCall(
ins, IPOINT_BEFORE, (AFUNPTR)RecordStackMemRead,
IARG_INST_PTR,
IARG_MEMORYOP_EA, memOp,
IARG_END);
}
// Note that in some architectures a single memory operand can be
// both read and written (for instance incl (%eax) on IA-32)
// In that case we instrument it once for read and once for write.
//if (INS_MemoryOperandIsWritten(ins, memOp)) {
if (INS_MemoryOperandIsWritten(ins, memOp) && !INS_IsStackWrite(ins)) {
INS_InsertPredicatedCall(
ins, IPOINT_BEFORE, (AFUNPTR)RecordHeapMemWrite,
IARG_INST_PTR,
IARG_MEMORYOP_EA, memOp,
IARG_END);
} else if (INS_MemoryOperandIsWritten(ins, memOp)) {
INS_InsertPredicatedCall(
ins, IPOINT_BEFORE, (AFUNPTR)RecordStackMemWrite,
IARG_INST_PTR,
IARG_MEMORYOP_EA, memOp,
IARG_END);
}
}
}
VOID Fini(INT32 code, VOID *v) {
fprintf(trace, "#eof \n");
// Display the stats
stats.displayResults(ml, trace);
fclose(trace);
}
// This is the replacement routine.
VOID* NewMalloc(FP_MALLOC orgFuncptr, UINT32 arg0, ADDRINT returnIp) {
// Call the relocated entry point of the original (replaced) routine.
void* v = orgFuncptr(arg0 + (2 * DEFAULT_FENCE_SIZE));
stats.incMallocCount();
MemoryAlloc ma = ml.add(v, arg0, DEFAULT_FENCE_SIZE);
fprintf(trace, "ADDED: %p %d \n", v, DEFAULT_FENCE_SIZE);
return ma.getAddress();
}
void* NewCalloc(FP_CALLOC libc_calloc, UINT32 arg0, UINT32 arg1, ADDRINT returnIp) {
// Calculate the size in bytes
size_t bytes = (arg0 * arg1);
size_t totalSize = bytes + (2 + DEFAULT_FENCE_SIZE);
// Figure out the correct amount of chunks
size_t nmemb = totalSize / arg1;
size_t nmembe = totalSize % arg1;
nmembe = (nmembe > 0) ? 1 : 0;
// Sum up the chunks
nmemb += nmembe;
// Allocate space using malloc
void *ptr = libc_calloc(nmemb, arg1);
// Create a new MemoryAlloc
MemoryAlloc ma = ml.add(ptr, bytes, DEFAULT_FENCE_SIZE);
// Add the information to the trace file
fprintf(trace, "ADDED: %p %d \n", ptr, DEFAULT_FENCE_SIZE);
stats.incMallocCount();
return ma.getAddress();
}
void* NewRealloc(FP_REALLOC orgFuncptr, void* arg0, UINT32 arg1, ADDRINT returnIp) {
printf("New Realloc was called\n");
return arg0;
}
void NewFree(FP_FREE orgFuncptr, void* ptr, ADDRINT returnIp) {
if(ptr != NULL) {
// Check the MemList
int index = ml.containsAddress(ptr);
if(index >= 0) {
MemoryAlloc alloc = ml.get(index);
// Remove the space
orgFuncptr(alloc.getUnderflowFence());
fprintf(trace, "Freed the memory @ address %p successfully.\n", alloc.getUnderflowFence());
// Remove the element from the list
ml.removeMatching(alloc);
stats.incFreeCount();
} else if(index == ERR_NOT_FOUND) {
// This currently gets hit since a blacklist is being used
fprintf(trace, "Address = %p not found. Bad address or stack address used.\n", ptr);
stats.incInvalidFreeCount();
/*
// Dump all memory currently stored
char buffer[1024];
for(int i = 0; i < ml.size(); i++) {
fprintf(trace, "%s\n", ml.get(i).toString(buffer, 1024));
}
*/
} else if(index == ERR_MID_CHUNK) {
fprintf(trace, "Mid-chunk memory deallocation @ %p\n", ptr);
stats.incMidFreeChunkCount();
} else if(index == ERR_IN_FENCE) {
fprintf(trace, "Memory Fence Hit @ %p\n", ptr);
stats.incFenceHitCount();
} else {
// This should Never happen...
fprintf(trace, "index = %d : Unable to deallocate the memory @ %p\n", index, ptr);
}
} else {
fprintf(trace, "Attempted to free NULL\n");
stats.incFreeNullCount();
}
}
// Pin calls this function every time a new img is loaded.
// It is best to do probe replacement when the image is loaded,
// because only one thread knows about the image at this time.
VOID ImageLoad(IMG img, VOID *v) {
if(IMG_IsMainExecutable(img)) {
RTN rtn = RTN_FindByName(img, "main");
RTN_Open(rtn);//Must open RTN API before examining instructions
INS ins = RTN_InsHead(rtn);
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)SetInMain, IARG_END);
RTN_Close(rtn);
}
if(!hasEnding(IMG_Name(img), "libc.so.6")) {
return;
}
if(!inMain) {
inMain = IMG_IsMainExecutable(img);
}
// Hook Functions
HookMalloc(img);
HookFree(img);
HookCalloc(img);
HookRealloc(img);
}
void HookFree(IMG img) {
RTN rtn = RTN_FindByName(img, "free");
if(RTN_Valid(rtn)) {
fprintf(trace, "Replacing free in %s\n", IMG_Name(img).c_str());
// Return type, cstype, function name, arguments...
PROTO proto = PROTO_Allocate(PIN_PARG(void), CALLINGSTD_DEFAULT, "free", PIN_PARG(void*), PIN_PARG_END());
// Replace free
RTN_ReplaceSignature(rtn, AFUNPTR(NewFree),
IARG_PROTOTYPE,
proto,
IARG_ORIG_FUNCPTR,
IARG_FUNCARG_ENTRYPOINT_VALUE,
0,
IARG_RETURN_IP,
IARG_END);
// Free the function prototype
PROTO_Free(proto);
}
}
void HookMalloc(IMG img) {
// See if malloc() is present in the image. If so, replace it.
RTN rtnMalloc = RTN_FindByName(img, "malloc");
if(RTN_Valid(rtnMalloc)) {
fprintf(trace, "Replacing malloc in %s\n", IMG_Name(img).c_str());
PROTO proto_malloc = PROTO_Allocate(PIN_PARG(void *), CALLINGSTD_DEFAULT,
"malloc", PIN_PARG(int), PIN_PARG_END());
RTN_ReplaceSignature(rtnMalloc, AFUNPTR(NewMalloc),
IARG_PROTOTYPE, proto_malloc,
IARG_ORIG_FUNCPTR,
IARG_FUNCARG_ENTRYPOINT_VALUE, 0,
IARG_RETURN_IP,
IARG_END);
// Free the function prototype.
PROTO_Free(proto_malloc);
}
}
void HookCalloc(IMG img) {
// See if calloc() is present in the image. If so, replace it.
RTN rtn = RTN_FindByName(img, "calloc");
if(RTN_Valid(rtn)) {
fprintf(trace, "Replacing calloc in %s\n", IMG_Name(img).c_str());
PROTO proto = PROTO_Allocate(PIN_PARG(void *), CALLINGSTD_DEFAULT,
"calloc", PIN_PARG(size_t), PIN_PARG(size_t), PIN_PARG_END());
RTN_ReplaceSignature(rtn, AFUNPTR(NewCalloc),
IARG_PROTOTYPE, proto,
IARG_ORIG_FUNCPTR,
IARG_FUNCARG_ENTRYPOINT_VALUE, 0,
IARG_RETURN_IP,
IARG_END);
// Free the function prototype.
PROTO_Free(proto);
}
}
void HookRealloc(IMG img) {
// See if calloc() is present in the image. If so, replace it.
RTN rtn = RTN_FindByName(img, "realloc");
if(RTN_Valid(rtn)) {
fprintf(trace, "Replacing realloc in %s\n", IMG_Name(img).c_str());
PROTO proto = PROTO_Allocate(PIN_PARG(void *), CALLINGSTD_DEFAULT,
"realloc", PIN_PARG(void*), PIN_PARG(size_t), PIN_PARG_END());
RTN_ReplaceSignature(rtn, AFUNPTR(NewRealloc),
IARG_PROTOTYPE, proto,
IARG_ORIG_FUNCPTR,
IARG_FUNCARG_ENTRYPOINT_VALUE, 0,
IARG_RETURN_IP,
IARG_END);
// Free the function prototype.
PROTO_Free(proto);
}
}
/* ===================================================================== */
/* Print Help Message */
/* ===================================================================== */
INT32 Usage() {
cerr << "This tool demonstrates how to replace an original" << endl;
cerr << " function with a custom function defined in the tool " << endl;
cerr << " using probes. The replacement function has a different " << endl;
cerr << " signature from that of the original replaced function." << endl;
cerr << endl << KNOB_BASE::StringKnobSummary() << endl;
return -1;
}
/* ===================================================================== */
/* Main: Initialize and start Pin in Probe mode. */
/* ===================================================================== */
int main(INT32 argc, CHAR *argv[]) {
// Initialize symbol processing
PIN_InitSymbols();
// Initialize pin
if (PIN_Init(argc, argv))
return Usage();
// Open up the trace file
trace = fopen("zzz.out", "w");
// Register ImageLoad to be called when an image is loaded
IMG_AddInstrumentFunction(ImageLoad, 0);
INS_AddInstrumentFunction(Instruction, 0);
PIN_AddFiniFunction(Fini, 0);
PIN_StartProgram();
return 0;
}
<|endoftext|>
|
<commit_before>#include "stats.h"
Stats::Stats() {
this->reset();
}
void Stats::reset() {
/* Allocation Stats */
this->allocCount = 0;
this->mallocCount = 0;
this->callocCount = 0;
this->reallocCount = 0;
/* Deallocation Stats */
this->freeCount = 0;
/* Invalid Free Stats*/
this->invalidFreeCount = 0;
this->midFreeChunkCount = 0;
this->freeNullCount = 0;
/* Invalid Read Stats */
this->invalidReadCount = 0;
this->readFenceOverflow = 0;
this->readFenceUnderflow = 0;
/* Invalid Write Stats */
this->invalidWriteCount = 0;
this->writeFenceOverflow = 0;
this->writeFenceUnderflow = 0;
/* Stack Smashing Stats */
this->invalidReturnCount = 0;
}
/* Getters */
unsigned int Stats::getAllocCount() {
return this->allocCount;
}
unsigned int Stats::getMallocCount() {
return this->mallocCount;
}
unsigned int Stats::getCallocCount() {
return this->callocCount;
}
unsigned int Stats::getReallocCount() {
return this->reallocCount;
}
unsigned int Stats::getFreeCount() {
return this->freeCount;
}
unsigned int Stats::getInvalidReadCount() {
return this->invalidReadCount;
}
unsigned int Stats::getReadFenceOverflow() {
return this->readFenceOverflow;
}
unsigned int Stats::getReadFenceUnderflow() {
return this->readFenceUnderflow;
}
unsigned int Stats::getInvalidWriteCount() {
return this->invalidWriteCount;
}
unsigned int Stats::getWriteFenceOverflow() {
return this->writeFenceOverflow;
}
unsigned int Stats::getWriteFenceUnderflow() {
return this->writeFenceUnderflow;
}
unsigned int Stats::getInvalidFreeCount() {
return this->invalidFreeCount;
}
unsigned int Stats::getMidFreeChunkCount() {
return this->midFreeChunkCount;
}
unsigned int Stats::getFreeNullCount() {
return this->freeNullCount;
}
unsigned int Stats::getFreeNotFoundCount() {
return this->freeNotFoundCount;
}
unsigned int Stats::getInvalidReturnCount() {
return this->invalidReturnCount;
}
/* Setters */
void Stats::setAllocCount(unsigned int count) {
this->allocCount = count;
}
void Stats::setMallocCount(unsigned int count) {
this->allocCount = count;
}
void Stats::setCallocCount(unsigned int count) {
this->allocCount = count;
}
void Stats::setReallocCount(unsigned int count) {
this->allocCount = count;
}
void Stats::setFreeCount(unsigned int count) {
this->freeCount = count;
}
void Stats::setInvalidReadCount(unsigned int count) {
this->invalidReadCount = count;
}
void Stats::setReadFenceOverflow(unsigned int count) {
this->readFenceOverflow = count;
}
void Stats::setReadFenceUnderflow(unsigned int count) {
this->readFenceUnderflow = count;
}
void Stats::setInvalidWriteCount(unsigned int count) {
this->invalidWriteCount = count;
}
void Stats::setWriteFenceOverflow(unsigned int count) {
this->writeFenceOverflow = count;
}
void Stats::setWriteFenceUnderflow(unsigned int count) {
this->writeFenceUnderflow = count;
}
void Stats::setInvalidFreeCount(unsigned int count) {
this->invalidFreeCount = count;
}
void Stats::setMidFreeChunkCount(unsigned int count) {
this->midFreeChunkCount = count;
}
void Stats::setFreeNullCount(unsigned int count) {
this->freeNullCount = count;
}
void Stats::setInvalidReturnCount(unsigned int count) {
this->invalidReturnCount = count;
}
void Stats::setFreeNotFoundCount(unsigned int count) {
this->freeNotFoundCount = count;
}
/* Increment Count Functions */
void Stats::incAllocCount() {
this->allocCount++;
}
void Stats::incMallocCount() {
this->mallocCount++;
}
void Stats::incCallocCount() {
this->callocCount++;
}
void Stats::incReallocCount() {
this->reallocCount++;
}
void Stats::incFreeCount() {
this->freeCount++;
}
void Stats::incInvalidReadCount() {
this->invalidReadCount++;
}
void Stats::incReadFenceOverflow() {
this->readFenceOverflow++;
}
void Stats::incReadFenceUnderflow() {
this->readFenceUnderflow++;
}
void Stats::incInvalidWriteCount() {
this->invalidWriteCount++;
}
void Stats::incWriteFenceOverflow() {
this->writeFenceOverflow++;
}
void Stats::incWriteFenceUnderflow() {
this->writeFenceUnderflow++;
}
void Stats::incInvalidFreeCount() {
this->invalidFreeCount++;
}
void Stats::incMidFreeChunkCount() {
this->midFreeChunkCount++;
}
void Stats::incFreeNullCount() {
this->freeNullCount++;
}
void Stats::incFreeNotFoundCount() {
this->freeNotFoundCount++;
}
void Stats::incInvalidReturnCount() {
this->invalidReturnCount++;
}
/**
* Display All information tracked by the pintool.
*/
void Stats::displayResults(MemList memlist, FILE *fp) {
if(fp == NULL) {
fp = stdin;
}
// Print out the initial object
fprintf(fp, "==================================\n");
fprintf(fp, "%-20s %s\n", "ACTIONS ", "COUNT");
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "allocations: ", this->allocCount);
fprintf(fp, "%-20s %d\n", " malloc", this->mallocCount);
fprintf(fp, "%-20s %d\n", " calloc", this->callocCount);
fprintf(fp, "%-20s %d\n", " realloc", this->reallocCount);
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "deallocations: ", this->freeCount);
fprintf(fp, "%-20s %d\n", " free ", this->freeCount);
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "invalid reads: ", this->invalidReadCount);
fprintf(fp, "%-20s %d\n", " underflow", this->readFenceUnderflow);
fprintf(fp, "%-20s %d\n", " overflow", this->readFenceOverflow);
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "invalid writes: ", this->invalidWriteCount);
fprintf(fp, "%-20s %d\n", " underflow", this->writeFenceUnderflow);
fprintf(fp, "%-20s %d\n", " overflow", this->writeFenceOverflow);
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "invalid frees: ", this->invalidFreeCount);
fprintf(fp, "%-20s %d\n", " not found", this->freeNotFoundCount);
fprintf(fp, "%-20s %d\n", " null free", this->freeNullCount);
fprintf(fp, "%-20s %d\n", " midchunk free", this->midFreeChunkCount);
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "invalid returns: ", this->invalidReturnCount);
fprintf(fp, "==================================\n");
// Print out the contents of memlist if it was provided.
fprintf(fp, "%-20s\n", "MEMLIST CONTENTS");
char buffer[2048];
int lostMemory = 0;
for(int i = 0; i < memlist.size(); i++) {
MemoryAlloc alloc = memlist.get(i);
fprintf(fp, "%s\n", alloc.toString(buffer, 2048));
lostMemory += alloc.getTotalSize();
}
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "list size: ", memlist.size());
fprintf(fp, "%-20s %d %s\n", "total loss: ", lostMemory, "bytes");
fprintf(fp, "==================================\n");
}
<commit_msg>Changed total size to reflect the user requested size instead of the size including the memoryfence.<commit_after>#include "stats.h"
Stats::Stats() {
this->reset();
}
void Stats::reset() {
/* Allocation Stats */
this->allocCount = 0;
this->mallocCount = 0;
this->callocCount = 0;
this->reallocCount = 0;
/* Deallocation Stats */
this->freeCount = 0;
/* Invalid Free Stats*/
this->invalidFreeCount = 0;
this->midFreeChunkCount = 0;
this->freeNullCount = 0;
/* Invalid Read Stats */
this->invalidReadCount = 0;
this->readFenceOverflow = 0;
this->readFenceUnderflow = 0;
/* Invalid Write Stats */
this->invalidWriteCount = 0;
this->writeFenceOverflow = 0;
this->writeFenceUnderflow = 0;
/* Stack Smashing Stats */
this->invalidReturnCount = 0;
}
/* Getters */
unsigned int Stats::getAllocCount() {
return this->allocCount;
}
unsigned int Stats::getMallocCount() {
return this->mallocCount;
}
unsigned int Stats::getCallocCount() {
return this->callocCount;
}
unsigned int Stats::getReallocCount() {
return this->reallocCount;
}
unsigned int Stats::getFreeCount() {
return this->freeCount;
}
unsigned int Stats::getInvalidReadCount() {
return this->invalidReadCount;
}
unsigned int Stats::getReadFenceOverflow() {
return this->readFenceOverflow;
}
unsigned int Stats::getReadFenceUnderflow() {
return this->readFenceUnderflow;
}
unsigned int Stats::getInvalidWriteCount() {
return this->invalidWriteCount;
}
unsigned int Stats::getWriteFenceOverflow() {
return this->writeFenceOverflow;
}
unsigned int Stats::getWriteFenceUnderflow() {
return this->writeFenceUnderflow;
}
unsigned int Stats::getInvalidFreeCount() {
return this->invalidFreeCount;
}
unsigned int Stats::getMidFreeChunkCount() {
return this->midFreeChunkCount;
}
unsigned int Stats::getFreeNullCount() {
return this->freeNullCount;
}
unsigned int Stats::getFreeNotFoundCount() {
return this->freeNotFoundCount;
}
unsigned int Stats::getInvalidReturnCount() {
return this->invalidReturnCount;
}
/* Setters */
void Stats::setAllocCount(unsigned int count) {
this->allocCount = count;
}
void Stats::setMallocCount(unsigned int count) {
this->allocCount = count;
}
void Stats::setCallocCount(unsigned int count) {
this->allocCount = count;
}
void Stats::setReallocCount(unsigned int count) {
this->allocCount = count;
}
void Stats::setFreeCount(unsigned int count) {
this->freeCount = count;
}
void Stats::setInvalidReadCount(unsigned int count) {
this->invalidReadCount = count;
}
void Stats::setReadFenceOverflow(unsigned int count) {
this->readFenceOverflow = count;
}
void Stats::setReadFenceUnderflow(unsigned int count) {
this->readFenceUnderflow = count;
}
void Stats::setInvalidWriteCount(unsigned int count) {
this->invalidWriteCount = count;
}
void Stats::setWriteFenceOverflow(unsigned int count) {
this->writeFenceOverflow = count;
}
void Stats::setWriteFenceUnderflow(unsigned int count) {
this->writeFenceUnderflow = count;
}
void Stats::setInvalidFreeCount(unsigned int count) {
this->invalidFreeCount = count;
}
void Stats::setMidFreeChunkCount(unsigned int count) {
this->midFreeChunkCount = count;
}
void Stats::setFreeNullCount(unsigned int count) {
this->freeNullCount = count;
}
void Stats::setInvalidReturnCount(unsigned int count) {
this->invalidReturnCount = count;
}
void Stats::setFreeNotFoundCount(unsigned int count) {
this->freeNotFoundCount = count;
}
/* Increment Count Functions */
void Stats::incAllocCount() {
this->allocCount++;
}
void Stats::incMallocCount() {
this->mallocCount++;
}
void Stats::incCallocCount() {
this->callocCount++;
}
void Stats::incReallocCount() {
this->reallocCount++;
}
void Stats::incFreeCount() {
this->freeCount++;
}
void Stats::incInvalidReadCount() {
this->invalidReadCount++;
}
void Stats::incReadFenceOverflow() {
this->readFenceOverflow++;
}
void Stats::incReadFenceUnderflow() {
this->readFenceUnderflow++;
}
void Stats::incInvalidWriteCount() {
this->invalidWriteCount++;
}
void Stats::incWriteFenceOverflow() {
this->writeFenceOverflow++;
}
void Stats::incWriteFenceUnderflow() {
this->writeFenceUnderflow++;
}
void Stats::incInvalidFreeCount() {
this->invalidFreeCount++;
}
void Stats::incMidFreeChunkCount() {
this->midFreeChunkCount++;
}
void Stats::incFreeNullCount() {
this->freeNullCount++;
}
void Stats::incFreeNotFoundCount() {
this->freeNotFoundCount++;
}
void Stats::incInvalidReturnCount() {
this->invalidReturnCount++;
}
/**
* Display All information tracked by the pintool.
*/
void Stats::displayResults(MemList memlist, FILE *fp) {
if(fp == NULL) {
fp = stdin;
}
// Print out the initial object
fprintf(fp, "==================================\n");
fprintf(fp, "%-20s %s\n", "ACTIONS ", "COUNT");
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "allocations: ", this->allocCount);
fprintf(fp, "%-20s %d\n", " malloc", this->mallocCount);
fprintf(fp, "%-20s %d\n", " calloc", this->callocCount);
fprintf(fp, "%-20s %d\n", " realloc", this->reallocCount);
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "deallocations: ", this->freeCount);
fprintf(fp, "%-20s %d\n", " free ", this->freeCount);
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "invalid reads: ", this->invalidReadCount);
fprintf(fp, "%-20s %d\n", " underflow", this->readFenceUnderflow);
fprintf(fp, "%-20s %d\n", " overflow", this->readFenceOverflow);
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "invalid writes: ", this->invalidWriteCount);
fprintf(fp, "%-20s %d\n", " underflow", this->writeFenceUnderflow);
fprintf(fp, "%-20s %d\n", " overflow", this->writeFenceOverflow);
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "invalid frees: ", this->invalidFreeCount);
fprintf(fp, "%-20s %d\n", " not found", this->freeNotFoundCount);
fprintf(fp, "%-20s %d\n", " null free", this->freeNullCount);
fprintf(fp, "%-20s %d\n", " midchunk free", this->midFreeChunkCount);
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "invalid returns: ", this->invalidReturnCount);
fprintf(fp, "==================================\n");
// Print out the contents of memlist if it was provided.
fprintf(fp, "%-20s\n", "MEMLIST CONTENTS");
char buffer[2048];
int lostMemory = 0;
for(int i = 0; i < memlist.size(); i++) {
MemoryAlloc alloc = memlist.get(i);
fprintf(fp, "%s\n", alloc.toString(buffer, 2048));
lostMemory += alloc.getUserSize();
}
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "list size: ", memlist.size());
fprintf(fp, "%-20s %d %s\n", "total loss: ", lostMemory, "bytes");
fprintf(fp, "==================================\n");
}
<|endoftext|>
|
<commit_before>//
// A* with strict expanded list
//
#pragma once
#include <functional>
#include <unordered_set>
#include "priority_queue.hpp"
#include "func.hpp"
#include "node.hpp"
#include "timing.hpp"
using std::size_t;
using std::string;
using std::move;
using std::max;
using std::any_of;
using std::unordered_set;
namespace search
{
//
// Hfunc : heuristic function, (Node) -> h value
// ValidateFunc : unary predicate, check if a node is valid, (Node) -> bool
// Cfunc : cost function, (Node) -> c value
//
template<typename Hfunc, typename ValidateFunc, typename Cfunc = Cost<Node>>
class AStarSEL
{
public:
using Q = PriorityQueue<Node, Less<Node, Hfunc>>;
using Expansions = unordered_set<State>;
struct Get
{
Q q;
size_t const& max_q_size;
Expansions const& expansions;
string const& final_path;
long long const& run_time;
bool const& is_found;
} const last_run;
AStarSEL()
: last_run{ _q, _max_q_size, _expansions, _final_path, _run_time, _is_found }
{
reset();
}
auto operator()(State start, State goal, ValidateFunc validate) -> void
{
reset();
Timing timing{ _run_time };
search(start, goal, validate);
}
private:
//
// Data members
//
Q _q;
size_t _max_q_size;
Expansions _expansions;
string _final_path;
long long _run_time;
bool _is_found;
//
// reset all data members
//
auto reset() -> void
{
_q.reset();
_max_q_size = 0;
_expansions.clear();
_final_path.clear();
_run_time = 0;
_is_found = false;
}
//
// Core part
//
auto search(State start, State goal, ValidateFunc validate) -> void
{
for (_q.push({ "", start, goal }); !_q.empty() && _q.top().state() != goal; update_max_q_size())
{
auto curr = _q.pop();
if (!has_expanded_into_state_of(curr))
{
expand_into(curr.state());
for (auto const& child : curr.children(validate))
if (!has_expanded_into_state_of(child))
if (!_q.any(SameStateAs{ child.state() }))
_q.push(child);
else
_q.update_with_if(child, SameStateAs{ child.state() });
}
}
if (_q.empty())
{
_final_path = "";
_is_found = false;
}
else
{
_final_path = _q.top().path();
_is_found = true;
}
}
//
// helper for method search
//
auto update_max_q_size() -> void
{
_max_q_size = max(_max_q_size, _q.size());
}
//
// helper for method search
//
struct SameStateAs
{
State state_to_compare;
auto operator()(Node const& n) const -> bool
{
return n.state() == state_to_compare;
}
};
//
// helper for method search
//
auto has_expanded_into_state_of(Node const& n) const -> bool
{
auto const& e = _expansions;
return any_of(e.cbegin(), e.cend(), [&](State s) {return s == n.state(); });
}
//
// helper for method search
//
auto expand_into(State s) -> void
{
_expansions.insert(s);
}
};
}<commit_msg>changed parameters for method search, not tested<commit_after>//
// A* with strict expanded list
//
#pragma once
#include <functional>
#include <unordered_set>
#include "priority_queue.hpp"
#include "func.hpp"
#include "node.hpp"
#include "timing.hpp"
using std::size_t;
using std::string;
using std::move;
using std::max;
using std::any_of;
using std::unordered_set;
namespace search
{
//
// Hfunc : heuristic function, (Node) -> h value
// ValidateFunc : unary predicate, check if a node is valid, (Node) -> bool
// Cfunc : cost function, (Node) -> c value
//
template<typename Hfunc, typename ValidateFunc, typename Cfunc = Cost<Node>>
class AStarSEL
{
public:
using Q = PriorityQueue<Node, Less<Node, Hfunc>>;
using Expansions = unordered_set<State>;
struct Get
{
Q q;
size_t const& max_q_size;
Expansions const& expansions;
string const& final_path;
long long const& run_time;
bool const& is_found;
} const last_run;
AStarSEL()
: last_run{ _q, _max_q_size, _expansions, _final_path, _run_time, _is_found }
{
reset();
}
auto operator()(State start, State goal, ValidateFunc validate) -> void
{
reset();
Timing timing{ _run_time };
search(start, goal, validate);
}
private:
//
// Data members
//
Q _q;
size_t _max_q_size;
Expansions _expansions;
string _final_path;
long long _run_time;
bool _is_found;
//
// reset all data members
//
auto reset() -> void
{
_q.reset();
_max_q_size = 0;
_expansions.clear();
_final_path.clear();
_run_time = 0;
_is_found = false;
}
//
// Core part
//
auto search(Node from, ValidateFunc validate) -> void
{
for (_q.push(from.state()); !_q.empty() && _q.top().state() != goal; update_max_q_size())
{
auto curr = _q.pop();
if (!has_expanded_into_state_of(curr))
{
expand_into(curr.state());
for (auto const& child : curr.children(validate))
if (!has_expanded_into_state_of(child))
if (!_q.any(SameStateAs{ child.state() }))
_q.push(child);
else
_q.update_with_if(child, SameStateAs{ child.state() });
}
}
if (_q.empty())
{
_final_path = "";
_is_found = false;
}
else
{
_final_path = _q.top().path();
_is_found = true;
}
}
//
// helper for method search
//
auto update_max_q_size() -> void
{
_max_q_size = max(_max_q_size, _q.size());
}
//
// helper for method search
//
struct SameStateAs
{
State state_to_compare;
auto operator()(Node const& n) const -> bool
{
return n.state() == state_to_compare;
}
};
//
// helper for method search
//
auto has_expanded_into_state_of(Node const& n) const -> bool
{
auto const& e = _expansions;
return any_of(e.cbegin(), e.cend(), [&](State s) {return s == n.state(); });
}
//
// helper for method search
//
auto expand_into(State s) -> void
{
_expansions.insert(s);
}
};
}
<|endoftext|>
|
<commit_before>/* Copyright 2007-2015 QReal Research Group
*
* 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 "styledButton.h"
#include <QtWidgets/QLabel>
#include <QtWidgets/QStyle>
#include "brandManager/brandManager.h"
#include "circleWidget.h"
using namespace qReal;
StyledButton::StyledButton(const QString &text, const QString &icon
, QBoxLayout::Direction direction, QWidget *parent)
: QPushButton(parent)
{
setMouseTracking(true);
QBoxLayout * const layout = new QBoxLayout(direction);
layout->setMargin(2);
if (!icon.isEmpty()) {
QWidget * const circleWidget = new CircleWidget(QSize(70, 70), icon);
layout->addWidget(circleWidget);
bindHighlightedOnHover(circleWidget);
}
QLabel * const textLabel = new QLabel(text);
textLabel->setWordWrap(true);
textLabel->setAttribute(Qt::WA_Hover);
layout->addWidget(textLabel);
bindHighlightedOnHover(textLabel);
setFlat(true);
setStyleSheet(BrandManager::styles()->startTabButtonStyle());
setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
setLayout(layout);
}
void StyledButton::bindHighlightedOnHover(QWidget * const widget)
{
widget->setProperty("enabled", false);
mChildren << widget;
}
void StyledButton::enterEvent(QEvent *event)
{
QPushButton::enterEvent(event);
highlight(true);
}
void StyledButton::leaveEvent(QEvent *event)
{
QPushButton::leaveEvent(event);
highlight(false);
}
void StyledButton::highlight(bool on)
{
for (QWidget * const child : mChildren) {
child->setProperty("enabled", on);
child->style()->unpolish(child);
child->style()->polish(child);
}
}
<commit_msg>A dirty fix for styled button size, now 'Open interpreted diagram' on a start screen is not being cut.<commit_after>/* Copyright 2007-2015 QReal Research Group
*
* 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 "styledButton.h"
#include <QtWidgets/QLabel>
#include <QtWidgets/QStyle>
#include "brandManager/brandManager.h"
#include "circleWidget.h"
using namespace qReal;
StyledButton::StyledButton(const QString &text, const QString &icon
, QBoxLayout::Direction direction, QWidget *parent)
: QPushButton(parent)
{
setMouseTracking(true);
QBoxLayout * const layout = new QBoxLayout(direction);
layout->setMargin(2);
if (!icon.isEmpty()) {
QWidget * const circleWidget = new CircleWidget(QSize(70, 70), icon);
layout->addWidget(circleWidget);
bindHighlightedOnHover(circleWidget);
}
QLabel * const textLabel = new QLabel(text);
textLabel->setWordWrap(true);
textLabel->setAttribute(Qt::WA_Hover);
// Beginning from some version of Qt >= 5.5 QLabel does not take into account word wrap when calculating size hint,
// so second line becomes clipped off. We use two lines for some buttons, so we manually set minimum height of a
// label to fit two lines with our default font. Somebody who has internet connection shall provide more adequate
// solution.
textLabel->setMinimumHeight(55);
layout->addWidget(textLabel);
bindHighlightedOnHover(textLabel);
setFlat(true);
setStyleSheet(BrandManager::styles()->startTabButtonStyle());
setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
setLayout(layout);
}
void StyledButton::bindHighlightedOnHover(QWidget * const widget)
{
widget->setProperty("enabled", false);
mChildren << widget;
}
void StyledButton::enterEvent(QEvent *event)
{
QPushButton::enterEvent(event);
highlight(true);
}
void StyledButton::leaveEvent(QEvent *event)
{
QPushButton::leaveEvent(event);
highlight(false);
}
void StyledButton::highlight(bool on)
{
for (QWidget * const child : mChildren) {
child->setProperty("enabled", on);
child->style()->unpolish(child);
child->style()->polish(child);
}
}
<|endoftext|>
|
<commit_before>#include "THMMesh.h"
#include "libmesh/node.h"
#include "libmesh/edge_edge2.h"
#include "libmesh/edge_edge3.h"
#include "libmesh/face_quad4.h"
#include "libmesh/face_quad9.h"
registerMooseObject("THMApp", THMMesh);
const BoundaryName THMMesh::INVALID_BOUNDARY_ID = "invalid_boundary_id";
template <>
InputParameters
validParams<THMMesh>()
{
InputParameters params = validParams<MooseMesh>();
// we do not allow renumbering, becuase we generate our meshes
params.set<bool>("allow_renumbering") = false;
return params;
}
THMMesh::THMMesh(const InputParameters & parameters)
: MooseMesh(parameters),
_dim(getParam<MooseEnum>("dim")),
_next_node_id(0),
_next_element_id(0),
_next_subdomain_id(0),
_next_boundary_id(0)
{
}
THMMesh::THMMesh(const THMMesh & other_mesh)
: MooseMesh(other_mesh),
_dim(other_mesh._dim),
_next_node_id(other_mesh._next_node_id),
_next_element_id(other_mesh._next_element_id),
_next_subdomain_id(other_mesh._next_subdomain_id),
_next_boundary_id(other_mesh._next_boundary_id)
{
}
unsigned int
THMMesh::dimension() const
{
return _dim;
}
unsigned int
THMMesh::effectiveSpatialDimension() const
{
return _dim;
}
MooseMesh &
THMMesh::clone() const
{
mooseError("CRITICAL ERROR: calling clone() is not allowed and should not happen.");
}
std::unique_ptr<MooseMesh>
THMMesh::safeClone() const
{
return libmesh_make_unique<THMMesh>(*this);
}
void
THMMesh::buildMesh()
{
getMesh().set_spatial_dimension(_dim);
}
void
THMMesh::prep()
{
prepare(true);
}
dof_id_type
THMMesh::getNextNodeId()
{
unsigned int id = _next_node_id++;
return id;
}
dof_id_type
THMMesh::getNextElementId()
{
unsigned int id = _next_element_id++;
return id;
}
Node *
THMMesh::addNode(const Point & pt)
{
dof_id_type id = getNextNodeId();
Node * node = _mesh->add_point(pt, id);
node->set_unique_id() = id;
return node;
}
Elem *
THMMesh::addElementEdge2(dof_id_type node0, dof_id_type node1)
{
const auto pid = _mesh->comm().rank();
dof_id_type elem_id = getNextElementId();
Elem * elem = new Edge2;
elem->set_id(elem_id);
elem->processor_id() = pid;
elem->set_unique_id() = elem_id;
_mesh->add_elem(elem);
elem->set_node(0) = _mesh->node_ptr(node0);
elem->set_node(1) = _mesh->node_ptr(node1);
return elem;
}
Elem *
THMMesh::addElementEdge3(dof_id_type node0, dof_id_type node1, dof_id_type node2)
{
const auto pid = _mesh->comm().rank();
dof_id_type elem_id = getNextElementId();
Elem * elem = new Edge3;
elem->set_id(elem_id);
elem->processor_id() = pid;
elem->set_unique_id() = elem_id;
_mesh->add_elem(elem);
elem->set_node(0) = _mesh->node_ptr(node0);
elem->set_node(1) = _mesh->node_ptr(node1);
elem->set_node(2) = _mesh->node_ptr(node2);
return elem;
}
Elem *
THMMesh::addElementQuad4(dof_id_type node0, dof_id_type node1, dof_id_type node2, dof_id_type node3)
{
const auto pid = _mesh->comm().rank();
dof_id_type elem_id = getNextElementId();
Elem * elem = new Quad4;
elem->set_id(elem_id);
elem->processor_id() = pid;
elem->set_unique_id() = elem_id;
_mesh->add_elem(elem);
elem->set_node(0) = _mesh->node_ptr(node0);
elem->set_node(1) = _mesh->node_ptr(node1);
elem->set_node(2) = _mesh->node_ptr(node2);
elem->set_node(3) = _mesh->node_ptr(node3);
return elem;
}
Elem *
THMMesh::addElementQuad9(dof_id_type node0,
dof_id_type node1,
dof_id_type node2,
dof_id_type node3,
dof_id_type node4,
dof_id_type node5,
dof_id_type node6,
dof_id_type node7,
dof_id_type node8)
{
const auto pid = _mesh->comm().rank();
dof_id_type elem_id = getNextElementId();
Elem * elem = new Quad9;
elem->set_id(elem_id);
elem->processor_id() = pid;
elem->set_unique_id() = elem_id;
_mesh->add_elem(elem);
// vertices
elem->set_node(0) = _mesh->node_ptr(node0);
elem->set_node(1) = _mesh->node_ptr(node1);
elem->set_node(2) = _mesh->node_ptr(node2);
elem->set_node(3) = _mesh->node_ptr(node3);
// mid-edges
elem->set_node(4) = _mesh->node_ptr(node4);
elem->set_node(5) = _mesh->node_ptr(node5);
elem->set_node(6) = _mesh->node_ptr(node6);
elem->set_node(7) = _mesh->node_ptr(node7);
// center
elem->set_node(8) = _mesh->node_ptr(node8);
return elem;
}
SubdomainID
THMMesh::getNextSubdomainId()
{
SubdomainID id = _next_subdomain_id++;
return id;
}
BoundaryID
THMMesh::getNextBoundaryId()
{
BoundaryID id = _next_boundary_id++;
return id;
}
<commit_msg>Fixing incorrect type<commit_after>#include "THMMesh.h"
#include "libmesh/node.h"
#include "libmesh/edge_edge2.h"
#include "libmesh/edge_edge3.h"
#include "libmesh/face_quad4.h"
#include "libmesh/face_quad9.h"
registerMooseObject("THMApp", THMMesh);
const BoundaryName THMMesh::INVALID_BOUNDARY_ID = "invalid_boundary_id";
template <>
InputParameters
validParams<THMMesh>()
{
InputParameters params = validParams<MooseMesh>();
// we do not allow renumbering, becuase we generate our meshes
params.set<bool>("allow_renumbering") = false;
return params;
}
THMMesh::THMMesh(const InputParameters & parameters)
: MooseMesh(parameters),
_dim(getParam<MooseEnum>("dim")),
_next_node_id(0),
_next_element_id(0),
_next_subdomain_id(0),
_next_boundary_id(0)
{
}
THMMesh::THMMesh(const THMMesh & other_mesh)
: MooseMesh(other_mesh),
_dim(other_mesh._dim),
_next_node_id(other_mesh._next_node_id),
_next_element_id(other_mesh._next_element_id),
_next_subdomain_id(other_mesh._next_subdomain_id),
_next_boundary_id(other_mesh._next_boundary_id)
{
}
unsigned int
THMMesh::dimension() const
{
return _dim;
}
unsigned int
THMMesh::effectiveSpatialDimension() const
{
return _dim;
}
MooseMesh &
THMMesh::clone() const
{
mooseError("CRITICAL ERROR: calling clone() is not allowed and should not happen.");
}
std::unique_ptr<MooseMesh>
THMMesh::safeClone() const
{
return libmesh_make_unique<THMMesh>(*this);
}
void
THMMesh::buildMesh()
{
getMesh().set_spatial_dimension(_dim);
}
void
THMMesh::prep()
{
prepare(true);
}
dof_id_type
THMMesh::getNextNodeId()
{
dof_id_type id = _next_node_id++;
return id;
}
dof_id_type
THMMesh::getNextElementId()
{
dof_id_type id = _next_element_id++;
return id;
}
Node *
THMMesh::addNode(const Point & pt)
{
dof_id_type id = getNextNodeId();
Node * node = _mesh->add_point(pt, id);
node->set_unique_id() = id;
return node;
}
Elem *
THMMesh::addElementEdge2(dof_id_type node0, dof_id_type node1)
{
const auto pid = _mesh->comm().rank();
dof_id_type elem_id = getNextElementId();
Elem * elem = new Edge2;
elem->set_id(elem_id);
elem->processor_id() = pid;
elem->set_unique_id() = elem_id;
_mesh->add_elem(elem);
elem->set_node(0) = _mesh->node_ptr(node0);
elem->set_node(1) = _mesh->node_ptr(node1);
return elem;
}
Elem *
THMMesh::addElementEdge3(dof_id_type node0, dof_id_type node1, dof_id_type node2)
{
const auto pid = _mesh->comm().rank();
dof_id_type elem_id = getNextElementId();
Elem * elem = new Edge3;
elem->set_id(elem_id);
elem->processor_id() = pid;
elem->set_unique_id() = elem_id;
_mesh->add_elem(elem);
elem->set_node(0) = _mesh->node_ptr(node0);
elem->set_node(1) = _mesh->node_ptr(node1);
elem->set_node(2) = _mesh->node_ptr(node2);
return elem;
}
Elem *
THMMesh::addElementQuad4(dof_id_type node0, dof_id_type node1, dof_id_type node2, dof_id_type node3)
{
const auto pid = _mesh->comm().rank();
dof_id_type elem_id = getNextElementId();
Elem * elem = new Quad4;
elem->set_id(elem_id);
elem->processor_id() = pid;
elem->set_unique_id() = elem_id;
_mesh->add_elem(elem);
elem->set_node(0) = _mesh->node_ptr(node0);
elem->set_node(1) = _mesh->node_ptr(node1);
elem->set_node(2) = _mesh->node_ptr(node2);
elem->set_node(3) = _mesh->node_ptr(node3);
return elem;
}
Elem *
THMMesh::addElementQuad9(dof_id_type node0,
dof_id_type node1,
dof_id_type node2,
dof_id_type node3,
dof_id_type node4,
dof_id_type node5,
dof_id_type node6,
dof_id_type node7,
dof_id_type node8)
{
const auto pid = _mesh->comm().rank();
dof_id_type elem_id = getNextElementId();
Elem * elem = new Quad9;
elem->set_id(elem_id);
elem->processor_id() = pid;
elem->set_unique_id() = elem_id;
_mesh->add_elem(elem);
// vertices
elem->set_node(0) = _mesh->node_ptr(node0);
elem->set_node(1) = _mesh->node_ptr(node1);
elem->set_node(2) = _mesh->node_ptr(node2);
elem->set_node(3) = _mesh->node_ptr(node3);
// mid-edges
elem->set_node(4) = _mesh->node_ptr(node4);
elem->set_node(5) = _mesh->node_ptr(node5);
elem->set_node(6) = _mesh->node_ptr(node6);
elem->set_node(7) = _mesh->node_ptr(node7);
// center
elem->set_node(8) = _mesh->node_ptr(node8);
return elem;
}
SubdomainID
THMMesh::getNextSubdomainId()
{
SubdomainID id = _next_subdomain_id++;
return id;
}
BoundaryID
THMMesh::getNextBoundaryId()
{
BoundaryID id = _next_boundary_id++;
return id;
}
<|endoftext|>
|
<commit_before>#include <THtml.h>
#include <TROOT.h>
#include <TSystem.h>
void mkhtml (char *macro=0, Int_t force=0) {
// to run this macro, you must have the correct .rootrc file
// in your galice directory.
// The gAlice classes summary documentation go to directory html
// The gAlice classes source documentation go to directory html/src
// The example macros documentation go to directory html/examples
// gROOT->LoadMacro("loadlibs.C");
// loadlibs();
THtml html;
html.SetProductName("AliRoot");
if(macro) {
gROOT->LoadMacro(macro);
html.Convert(macro,"Example Macro");
} else {
gSystem->Load("liblhapdf.so"); // Parton density functions
gSystem->Load("libEGPythia6.so"); // TGenerator interface
gSystem->Load("libpythia6.so"); // Pythia
gSystem->Load("libAliPythia6.so"); // ALICE specific implementations
gSystem->Load("libANALYSIS.so");
gSystem->Load("libANALYSISalice.so");
gSystem->Load("libANALYSIScalib.so");
gSystem->Load("libEventMixing.so");
gSystem->Load("libPWG0base.so");
gSystem->Load("libPWG0dep.so");
gSystem->Load("libPWG0selectors.so");
gSystem->Load("libTENDER.so");
gSystem->Load("libPWGPP.so");
gSystem->Load("libCORRFW.so");
gSystem->Load("libPWG2AOD.so");
gSystem->Load("libPWG2ebye.so");
gSystem->Load("libPWG2evchar.so");
gSystem->Load("libPWG2femtoscopy.so");
gSystem->Load("libPWG2femtoscopyUser.so");
gSystem->Load("libPWG2flowCommon.so");
gSystem->Load("libPWG2flowTasks.so");
gSystem->Load("libPWG2forward.so");
gSystem->Load("libPWG2kink.so");
gSystem->Load("libPWG2resonances.so");
gSystem->Load("libPWG2spectra.so");
gSystem->Load("libPWG2unicor.so");
gSystem->Load("libPWGHFbase.so");
gSystem->Load("libPWGHFhfe.so");
gSystem->Load("libPWGmuondep.so");
gSystem->Load("libPWGmuon.so");
gSystem->Load("libPWGHFvertexingHF.so");
gSystem->Load("libJETAN.so");
gSystem->Load("libPWG4CaloCalib.so");
gSystem->Load("libPWG4GammaConv.so");
gSystem->Load("libPWG4JetTasks.so");
gSystem->Load("libPWG4omega3pi.so");
gSystem->Load("libPWG4PartCorrBase.so");
gSystem->Load("libPWG4PartCorrDep.so");
// EVE
gSystem->Load("libEve.so");
gSystem->Load("libEveBase.so");
gSystem->Load("libEveDet.so");
gSystem->Load("libEveHLT.so");
html.MakeAll(force,"[A-Z]*");
}
}
<commit_msg>Updated list of libraries<commit_after>#include <THtml.h>
#include <TROOT.h>
#include <TSystem.h>
void mkhtml (char *macro=0, Int_t force=0) {
// to run this macro, you must have the correct .rootrc file
// in your galice directory.
// The gAlice classes summary documentation go to directory html
// The gAlice classes source documentation go to directory html/src
// The example macros documentation go to directory html/examples
// gROOT->LoadMacro("loadlibs.C");
// loadlibs();
THtml html;
html.SetProductName("AliRoot");
if(macro) {
gROOT->LoadMacro(macro);
html.Convert(macro,"Example Macro");
} else {
gSystem->Load("liblhapdf.so"); // Parton density functions
gSystem->Load("libEGPythia6.so"); // TGenerator interface
gSystem->Load("libpythia6.so"); // Pythia
gSystem->Load("libAliPythia6.so"); // ALICE specific implementations
// ANALYSIS
gSystem->Load("libANALYSIS.so");
gSystem->Load("libANALYSISalice.so");
gSystem->Load("libANALYSIScalib.so");
gSystem->Load("libEventMixing.so");
gSystem->Load("libTENDER.so");
gSystem->Load("libTENDERSupplies.so");
// CORRFW
gSystem->Load("libCORRFW.so"); //
// PWG
gSystem->Load("libPWGTools.so");
gSystem->Load("libPWGGlauber.so");
gSystem->Load("libPWGflowBase.so");
gSystem->Load("libPWGflowTasks.so");
gSystem->Load("libPWGmuon.so");
gSystem->Load("libPWGmuondep.so");
gSystem->Load("libPWGEMCAL.so");
gSystem->Load("libPWGCaloTrackCorrBase.so");
// PWGCF
gSystem->Load("libPWGCFCorrelationsBase.so");
gSystem->Load("libPWGCFCorrelationsDPhi.so");
gSystem->Load("libPWGCFCorrelationsJCORRAN.so");
gSystem->Load("libPWGCFChaoticity.so");
gSystem->Load("libPWGCFFEMTOSCOPYAOD.so");
gSystem->Load("libPWGCFfemtoscopy.so");
gSystem->Load("libPWGCFfemtoscopyUser.so");
gSystem->Load("libPWGCFunicor.so");
gSystem->Load("libPWGCFebye.so");
//PH gSystem->Load("libPWGCFK0Analysis.so");
// PWGDQ
gSystem->Load("libPWGDQbase.so");
gSystem->Load("libPWGDQdielectron.so");
// PWGGA
gSystem->Load("libPWGGACaloTasks.so");
gSystem->Load("libPWGGACaloTrackCorrelations.so");
gSystem->Load("libPWGGAEMCALTasks.so");
gSystem->Load("libPWGGAGammaConv.so");
gSystem->Load("libPWGGAPHOSTasks.so");
// PWGHF
gSystem->Load("libPWGHFbase.so");
gSystem->Load("libPWGHFhfe.so");
gSystem->Load("libPWGHFcorrelationHF.so");
gSystem->Load("libPWGHFvertexingHF.so");
// PWGJE
gSystem->Load("libJETAN.so");
// gSystem->Load("libPWGJE.so");
// gSystem->Load("libPWGJEEMCALJetTasks.so");
// PWGLF
gSystem->Load("libPWGLFSTRANGENESS.so");
gSystem->Load("libPWGLFforward.so");
gSystem->Load("libPWGLFforward2.so");
gSystem->Load("libPWGLFresonances.so");
gSystem->Load("libPWGLFrsnextra.so");
gSystem->Load("libPWGLFspectra.so");
// gSystem->Load("libPWGLFtotEt.so")
// PWGPP
gSystem->Load("libPWGPP.so");
gSystem->Load("libPWGPPMUONdep.so");
gSystem->Load("libPWGPPMUONlite.so");
gSystem->Load("libPWGPPevchar.so");
// PWGUD
gSystem->Load("libPWGUDbase.so");
gSystem->Load("libPWGUDFP.so");
gSystem->Load("libPWGUDdiffractive.so");
gSystem->Load("libPWGUDselectors.so");
// EVE
gSystem->Load("libEve.so");
gSystem->Load("libEveBase.so");
gSystem->Load("libEveDet.so");
gSystem->Load("libEveHLT.so");
html.MakeAll(force,"[A-Z]*");
}
}
<|endoftext|>
|
<commit_before>// 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
//
// 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 <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <vector>
#include <ImfArray.h>
#include <ImfInputPart.h>
#include <ImfMultiPartInputFile.h>
#include <ImfChannelList.h>
#include <ImfRgbaFile.h>
#include <ImfStdIO.h>
using namespace OPENEXR_IMF_INTERNAL_NAMESPACE;
using IMATH_NAMESPACE::Box2i;
using std::vector;
using std::max;
namespace {
static void readSingle(IStream& is) {
try {
RgbaInputFile in(is);
const Box2i &dw = in.dataWindow();
int w = dw.max.x - dw.min.x + 1;
int dx = dw.min.x;
if (w > (1 << 24)) return;
Array<Rgba> pixels(w);
in.setFrameBuffer(&pixels[-dx], 1, 0);
// read up to 10,000 scanlines from file
int step = max( 1 , (dw.max.y - dw.min.y + 1) / 10000);
for (int y = dw.min.y; y <= dw.max.y; y+=step) in.readPixels(y);
} catch (...) {
}
}
static void readMulti(IStream& is) {
MultiPartInputFile *file;
try {
file = new MultiPartInputFile(is);
} catch (...) {
return;
}
for (int p = 0; p < file->parts(); p++) {
InputPart *in;
try {
in = new InputPart(*file, p);
} catch (...) {
continue;
}
try {
const Box2i &dw = in->header().dataWindow();
int w = dw.max.x - dw.min.x + 1;
int dx = dw.min.x;
if (w > (1 << 24))
{
throw std::logic_error("ignoring - very wide datawindow\n");
}
FrameBuffer i;
//
// read all channels present (later channels will overwrite earlier ones)
vector<half> otherChannels(w);
const ChannelList& channelList = in->header().channels();
for (ChannelList::ConstIterator c = channelList.begin() ; c != channelList.end() ; ++c )
{
i.insert(c.name(),Slice(HALF, (char*)&otherChannels[0] , sizeof(half) , 0 ));
}
// always try to read RGBA even if not present in file
Array<Rgba> pixels(w);
i.insert("R", Slice(HALF, (char *)&(pixels[-dx].r), sizeof(Rgba), 0));
i.insert("G", Slice(HALF, (char *)&(pixels[-dx].g), sizeof(Rgba), 0));
i.insert("B", Slice(HALF, (char *)&(pixels[-dx].b), sizeof(Rgba), 0));
i.insert("A", Slice(HALF, (char *)&(pixels[-dx].a), sizeof(Rgba), 0));
in->setFrameBuffer(i);
// read up to 10,000 scanlines from file
int step = max( 1 , (dw.max.y - dw.min.y + 1) / 10000);
for (int y = dw.min.y; y <= dw.max.y; y+=step) in->readPixels(y);
} catch (...) {
}
delete in;
}
delete file;
}
} // namespace
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
const std::string s(reinterpret_cast<const char*>(data), size);
{
StdISStream is;
is.str(s);
readSingle(is);
}
{
StdISStream is;
is.str(s);
readMulti(is);
}
return 0;
}
<commit_msg>[openexr] fix reading extra EXR channels in readMulti (#4461)<commit_after>// 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
//
// 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 <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <vector>
#include <ImfArray.h>
#include <ImfInputPart.h>
#include <ImfMultiPartInputFile.h>
#include <ImfChannelList.h>
#include <ImfRgbaFile.h>
#include <ImfStdIO.h>
using namespace OPENEXR_IMF_INTERNAL_NAMESPACE;
using IMATH_NAMESPACE::Box2i;
using std::vector;
using std::max;
namespace {
static void readSingle(IStream& is) {
try {
RgbaInputFile in(is);
const Box2i &dw = in.dataWindow();
int w = dw.max.x - dw.min.x + 1;
int dx = dw.min.x;
if (w > (1 << 24)) return;
Array<Rgba> pixels(w);
in.setFrameBuffer(&pixels[-dx], 1, 0);
// read up to 10,000 scanlines from file
int step = max( 1 , (dw.max.y - dw.min.y + 1) / 10000);
for (int y = dw.min.y; y <= dw.max.y; y+=step) in.readPixels(y);
} catch (...) {
}
}
static void readMulti(IStream& is) {
MultiPartInputFile *file;
try {
file = new MultiPartInputFile(is);
} catch (...) {
return;
}
for (int p = 0; p < file->parts(); p++) {
InputPart *in;
try {
in = new InputPart(*file, p);
} catch (...) {
continue;
}
try {
const Box2i &dw = in->header().dataWindow();
int w = dw.max.x - dw.min.x + 1;
int dx = dw.min.x;
if (w > (1 << 24))
{
throw std::logic_error("ignoring - very wide datawindow\n");
}
FrameBuffer i;
//
// read all channels present (later channels will overwrite earlier ones)
vector<half> otherChannels(w);
const ChannelList& channelList = in->header().channels();
for (ChannelList::ConstIterator c = channelList.begin() ; c != channelList.end() ; ++c )
{
i.insert(c.name(),Slice(HALF, (char*)&otherChannels[-dx] , sizeof(half) , 0 ));
}
// always try to read RGBA even if not present in file
Array<Rgba> pixels(w);
i.insert("R", Slice(HALF, (char *)&(pixels[-dx].r), sizeof(Rgba), 0));
i.insert("G", Slice(HALF, (char *)&(pixels[-dx].g), sizeof(Rgba), 0));
i.insert("B", Slice(HALF, (char *)&(pixels[-dx].b), sizeof(Rgba), 0));
i.insert("A", Slice(HALF, (char *)&(pixels[-dx].a), sizeof(Rgba), 0));
in->setFrameBuffer(i);
// read up to 10,000 scanlines from file
int step = max( 1 , (dw.max.y - dw.min.y + 1) / 10000);
for (int y = dw.min.y; y <= dw.max.y; y+=step) in->readPixels(y);
} catch (...) {
}
delete in;
}
delete file;
}
} // namespace
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
const std::string s(reinterpret_cast<const char*>(data), size);
{
StdISStream is;
is.str(s);
readSingle(is);
}
{
StdISStream is;
is.str(s);
readMulti(is);
}
return 0;
}
<|endoftext|>
|
<commit_before>/* -*- 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 _OWNLIST_HXX
#define _OWNLIST_HXX
#include "svl/svldllapi.h"
#include <tools/stream.hxx>
#include <com/sun/star/uno/Sequence.hxx>
#include <vector>
namespace com { namespace sun { namespace star {
namespace beans {
struct PropertyValue;
}
}}}
//=========================================================================
class SvCommand
/* [Beschreibung]
Enth"alt einen String, welcher das Kommando angibt und eine weiteren
String, der das Argument des Kommandos bildet. W"urde solch ein
Kommando "uber die Kommandozeile angegeben werden, s"ahe es wie folgt
aus: Kommando = Argument.
*/
{
String aCommand;
String aArgument;
public:
SvCommand() {}
SvCommand( const String & rCommand, const String & rArg )
{
aCommand = rCommand;
aArgument = rArg;
}
const String & GetCommand() const { return aCommand; }
const String & GetArgument() const { return aArgument; }
friend SvStream& operator >> ( SvStream& rStm, SvCommand & rThis )
{
rStm.ReadByteString( rThis.aCommand, gsl_getSystemTextEncoding() );
rStm.ReadByteString( rThis.aArgument, gsl_getSystemTextEncoding() );
return rStm;
}
friend SvStream& operator << ( SvStream& rStm, const SvCommand & rThis )
{
rStm.WriteByteString( rThis.aCommand, gsl_getSystemTextEncoding() );
rStm.WriteByteString( rThis.aArgument, gsl_getSystemTextEncoding() );
return rStm;
}
};
typedef ::std::vector< SvCommand > SvCommandList_impl;
//=========================================================================
class SVL_DLLPUBLIC SvCommandList
/* [Beschreibung]
Die Liste enth"alt Objekte vom Typ SvCommand. Wird ein Objekt
eingef"ugt, dann wird es kopiert und das neue Objekt wird
in die Liste gestellt.
*/
{
private:
SvCommandList_impl aCommandList;
public:
SvCommand& Append( const String & rCommand, const String & rArg );
sal_Bool AppendCommands( const String & rCmd, sal_uInt16 * pEaten );
String GetCommands() const;
sal_Bool FillFromSequence( const com::sun::star::uno::Sequence < com::sun::star::beans::PropertyValue >& );
void FillSequence( com::sun::star::uno::Sequence < com::sun::star::beans::PropertyValue >& );
size_t size() const { return aCommandList.size(); }
SvCommand operator[]( size_t i) {
return aCommandList[ i ];
}
void clear() {
aCommandList.clear();
}
};
#endif // _OWNLIST_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>ditch other unused stream operators<commit_after>/* -*- 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 _OWNLIST_HXX
#define _OWNLIST_HXX
#include "svl/svldllapi.h"
#include <tools/stream.hxx>
#include <com/sun/star/uno/Sequence.hxx>
#include <vector>
namespace com { namespace sun { namespace star {
namespace beans {
struct PropertyValue;
}
}}}
//=========================================================================
class SvCommand
/* [Beschreibung]
Enth"alt einen String, welcher das Kommando angibt und eine weiteren
String, der das Argument des Kommandos bildet. W"urde solch ein
Kommando "uber die Kommandozeile angegeben werden, s"ahe es wie folgt
aus: Kommando = Argument.
*/
{
String aCommand;
String aArgument;
public:
SvCommand() {}
SvCommand( const String & rCommand, const String & rArg )
{
aCommand = rCommand;
aArgument = rArg;
}
const String & GetCommand() const { return aCommand; }
const String & GetArgument() const { return aArgument; }
};
typedef ::std::vector< SvCommand > SvCommandList_impl;
//=========================================================================
class SVL_DLLPUBLIC SvCommandList
/* [Beschreibung]
Die Liste enth"alt Objekte vom Typ SvCommand. Wird ein Objekt
eingef"ugt, dann wird es kopiert und das neue Objekt wird
in die Liste gestellt.
*/
{
private:
SvCommandList_impl aCommandList;
public:
SvCommand& Append( const String & rCommand, const String & rArg );
sal_Bool AppendCommands( const String & rCmd, sal_uInt16 * pEaten );
String GetCommands() const;
sal_Bool FillFromSequence( const com::sun::star::uno::Sequence < com::sun::star::beans::PropertyValue >& );
void FillSequence( com::sun::star::uno::Sequence < com::sun::star::beans::PropertyValue >& );
size_t size() const { return aCommandList.size(); }
SvCommand operator[]( size_t i) {
return aCommandList[ i ];
}
void clear() {
aCommandList.clear();
}
};
#endif // _OWNLIST_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>#include "threadPoolAsync.h"
#include "shared/defer.tcc"
#include <thread>
#include "../simpleServer/mt.h"
#include "exceptions.h"
namespace simpleServer {
using ondra_shared::defer;
ThreadPoolAsyncImpl::~ThreadPoolAsyncImpl() {
stop();
}
void ThreadPoolAsyncImpl::cancel(const AsyncResource& resource) {
Sync _(lock);
auto sz = cQueue.size();
while (sz) {
PStreamEventDispatcher d = cQueue.front();
cQueue.pop();
d->cancel(resource);
cQueue.push(d);
--sz;
}
}
void ThreadPoolAsyncImpl::checkThreadCount() {
while (static_cast<unsigned int>(threadCount.getCounter()) < reqThreadCount) {
RefCntPtr<ThreadPoolAsyncImpl> me(this);
runThread([me] {
me->worker();
});
threadCount.inc();
}
}
class ThreadPoolAsyncImpl::InvokeNetworkDispatcher {
public:
InvokeNetworkDispatcher(ThreadPoolAsyncImpl &owner, const PStreamEventDispatcher &sed)
:owner(owner)
,sed(sed) {}
void operator()() const {
/* auto t = sed->wait();
if (t == nullptr) {
disp.quit();
} else {
disp.dispatch(*this);
}
t();*/
owner.waitForTask(sed);
}
protected:
ThreadPoolAsyncImpl &owner;
PStreamEventDispatcher sed;
};
void ThreadPoolAsyncImpl::onExitDispatcher(const PStreamEventDispatcher &sed) noexcept {
Sync _(lock);
auto ccnt = cQueue.size();
for (decltype(ccnt) i = 0; i < ccnt; i++) {
const PStreamEventDispatcher &x = cQueue.front();
if (x == sed) {
cQueue.pop();
if (cQueue.empty()) {
dQueue.quit();
}
break;
} else {
cQueue.push(x);
cQueue.pop();
}
}
}
void ThreadPoolAsyncImpl::waitForTask(const PStreamEventDispatcher &sed) noexcept {
auto t = sed->wait();
if (t == nullptr) {
onExitDispatcher(sed);
return;
} else {
dQueue.dispatch(InvokeNetworkDispatcher(*this, sed));
}
t();
}
PStreamEventDispatcher ThreadPoolAsyncImpl::getListener() {
Sync _(lock);
PStreamEventDispatcher lst,lst2;
while (cQueue.size() < reqDispatcherCount) {
lst = AbstractStreamEventDispatcher::create();
cQueue.push(lst);
dQueue.dispatch(InvokeNetworkDispatcher(*this, lst));
}
while (cQueue.size() > reqDispatcherCount) {
//pop extra dispatcher
//they are still in queue, but eventually disappear because they no longer receive a work
cQueue.pop();
}
checkThreadCount();
lst = cQueue.front();
cQueue.pop();
cQueue.push(lst);
return lst;
}
void ThreadPoolAsyncImpl::runAsync(const AsyncResource& resource, int timeout, const CompletionFn &fn) {
if (exitFlag) {
defer >> std::bind(fn, asyncCancel);
return;
}
unsigned int tries = 0;
auto retry = [&] {
Sync _(lock);
++tries;
if (tries >= cQueue.size()) {
reqDispatcherCount++;
if (reqDispatcherCount>reqThreadCount) reqThreadCount++;
}
};
do {
try {
auto lst = getListener();
if (lst->getPendingCount()>=taskLimit) {
retry();
} else {
lst->runAsync(resource,timeout, fn);
return;
}
} catch (OutOfSpaceException) {
retry();
}
}while(true);
}
void ThreadPoolAsyncImpl::setCountOfDispatchers(unsigned int count) {
Sync _(lock);
reqDispatcherCount = count;
}
void ThreadPoolAsyncImpl::setCountOfThreads(unsigned int count) {
Sync _(lock);
reqThreadCount = count;
}
void ThreadPoolAsyncImpl::stop() {
{
Sync _(lock);
exitFlag = true;
auto sz = cQueue.size();
while (sz) {
PStreamEventDispatcher d = cQueue.front();
cQueue.pop();
cQueue.push(d);
d->stop();
--sz;
}
}
threadCount.wait();
}
void ThreadPoolAsyncImpl::setTasksPerDispLimit(unsigned int count) {
Sync _(lock);
taskLimit = count;
}
void ThreadPoolAsyncImpl::worker() noexcept {
using namespace ondra_shared;
DeferContext defer(ondra_shared::defer_root);
for(;;) {
if (!dQueue.pump()) {
dQueue.quit();
defer_yield();
threadCount.dec();
return;
}
defer_yield();
/* PStreamEventDispatcher lst = tQueue.pop();
if (lst == nullptr) {
tQueue.push(nullptr);
threadCount.dec();
return;
}
auto t = lst->wait();
tQueue.push(lst);
if (t == nullptr) {
threadCount.dec();
return;
}
t();
*/
if (static_cast<unsigned int>(threadCount.getCounter()) > reqThreadCount) {
Sync _(lock);
if (static_cast<unsigned int>(threadCount.getCounter()) > reqThreadCount) {
threadCount.dec();
return;
}
}
}
}
AsyncProvider ThreadPoolAsync::create(unsigned int numThreads, unsigned int numListeners, unsigned int tasksPerDispLimit) {
ThreadPoolAsync provider (new ThreadPoolAsyncImpl);
provider.setCountOfDispatchers(numListeners);
provider.setCountOfThreads(numThreads);
provider.setTasksPerDispLimit(tasksPerDispLimit);
return provider;
}
void ThreadPoolAsync::setCountOfDispatchers(unsigned int count) {
ptr->setCountOfDispatchers(count);
}
void ThreadPoolAsync::setCountOfThreads(unsigned int count) {
ptr->setCountOfThreads(count);
}
void ThreadPoolAsync::stop() {
ptr->stop();
}
ThreadPoolAsync::~ThreadPoolAsync() {
if (!ptr->isShared()) {
ptr->stop();
}
}
void ThreadPoolAsyncImpl::runAsync(const CustomFn& completion) {
if (exitFlag) {
defer >> completion;
return;
}
if (reqThreadCount > reqDispatcherCount) {
checkThreadCount();
dQueue.dispatch(completion);
} else {
auto lst = getListener();
lst->runAsync(completion);
}
}
void ThreadPoolAsync::setTasksPerDispLimit(unsigned int count) {
ptr->setTasksPerDispLimit(count);
}
ThreadPoolAsync::operator AsyncProvider() const {
return AsyncProvider(ptr);
}
}
<commit_msg>fix warning error: catching polymorphic type ‘class simpleServer::OutOfSpaceException’ by value<commit_after>#include "threadPoolAsync.h"
#include "shared/defer.tcc"
#include <thread>
#include "../simpleServer/mt.h"
#include "exceptions.h"
namespace simpleServer {
using ondra_shared::defer;
ThreadPoolAsyncImpl::~ThreadPoolAsyncImpl() {
stop();
}
void ThreadPoolAsyncImpl::cancel(const AsyncResource& resource) {
Sync _(lock);
auto sz = cQueue.size();
while (sz) {
PStreamEventDispatcher d = cQueue.front();
cQueue.pop();
d->cancel(resource);
cQueue.push(d);
--sz;
}
}
void ThreadPoolAsyncImpl::checkThreadCount() {
while (static_cast<unsigned int>(threadCount.getCounter()) < reqThreadCount) {
RefCntPtr<ThreadPoolAsyncImpl> me(this);
runThread([me] {
me->worker();
});
threadCount.inc();
}
}
class ThreadPoolAsyncImpl::InvokeNetworkDispatcher {
public:
InvokeNetworkDispatcher(ThreadPoolAsyncImpl &owner, const PStreamEventDispatcher &sed)
:owner(owner)
,sed(sed) {}
void operator()() const {
/* auto t = sed->wait();
if (t == nullptr) {
disp.quit();
} else {
disp.dispatch(*this);
}
t();*/
owner.waitForTask(sed);
}
protected:
ThreadPoolAsyncImpl &owner;
PStreamEventDispatcher sed;
};
void ThreadPoolAsyncImpl::onExitDispatcher(const PStreamEventDispatcher &sed) noexcept {
Sync _(lock);
auto ccnt = cQueue.size();
for (decltype(ccnt) i = 0; i < ccnt; i++) {
const PStreamEventDispatcher &x = cQueue.front();
if (x == sed) {
cQueue.pop();
if (cQueue.empty()) {
dQueue.quit();
}
break;
} else {
cQueue.push(x);
cQueue.pop();
}
}
}
void ThreadPoolAsyncImpl::waitForTask(const PStreamEventDispatcher &sed) noexcept {
auto t = sed->wait();
if (t == nullptr) {
onExitDispatcher(sed);
return;
} else {
dQueue.dispatch(InvokeNetworkDispatcher(*this, sed));
}
t();
}
PStreamEventDispatcher ThreadPoolAsyncImpl::getListener() {
Sync _(lock);
PStreamEventDispatcher lst,lst2;
while (cQueue.size() < reqDispatcherCount) {
lst = AbstractStreamEventDispatcher::create();
cQueue.push(lst);
dQueue.dispatch(InvokeNetworkDispatcher(*this, lst));
}
while (cQueue.size() > reqDispatcherCount) {
//pop extra dispatcher
//they are still in queue, but eventually disappear because they no longer receive a work
cQueue.pop();
}
checkThreadCount();
lst = cQueue.front();
cQueue.pop();
cQueue.push(lst);
return lst;
}
void ThreadPoolAsyncImpl::runAsync(const AsyncResource& resource, int timeout, const CompletionFn &fn) {
if (exitFlag) {
defer >> std::bind(fn, asyncCancel);
return;
}
unsigned int tries = 0;
auto retry = [&] {
Sync _(lock);
++tries;
if (tries >= cQueue.size()) {
reqDispatcherCount++;
if (reqDispatcherCount>reqThreadCount) reqThreadCount++;
}
};
do {
try {
auto lst = getListener();
if (lst->getPendingCount()>=taskLimit) {
retry();
} else {
lst->runAsync(resource,timeout, fn);
return;
}
} catch (OutOfSpaceException &) {
retry();
}
}while(true);
}
void ThreadPoolAsyncImpl::setCountOfDispatchers(unsigned int count) {
Sync _(lock);
reqDispatcherCount = count;
}
void ThreadPoolAsyncImpl::setCountOfThreads(unsigned int count) {
Sync _(lock);
reqThreadCount = count;
}
void ThreadPoolAsyncImpl::stop() {
{
Sync _(lock);
exitFlag = true;
auto sz = cQueue.size();
while (sz) {
PStreamEventDispatcher d = cQueue.front();
cQueue.pop();
cQueue.push(d);
d->stop();
--sz;
}
}
threadCount.wait();
}
void ThreadPoolAsyncImpl::setTasksPerDispLimit(unsigned int count) {
Sync _(lock);
taskLimit = count;
}
void ThreadPoolAsyncImpl::worker() noexcept {
using namespace ondra_shared;
DeferContext defer(ondra_shared::defer_root);
for(;;) {
if (!dQueue.pump()) {
dQueue.quit();
defer_yield();
threadCount.dec();
return;
}
defer_yield();
/* PStreamEventDispatcher lst = tQueue.pop();
if (lst == nullptr) {
tQueue.push(nullptr);
threadCount.dec();
return;
}
auto t = lst->wait();
tQueue.push(lst);
if (t == nullptr) {
threadCount.dec();
return;
}
t();
*/
if (static_cast<unsigned int>(threadCount.getCounter()) > reqThreadCount) {
Sync _(lock);
if (static_cast<unsigned int>(threadCount.getCounter()) > reqThreadCount) {
threadCount.dec();
return;
}
}
}
}
AsyncProvider ThreadPoolAsync::create(unsigned int numThreads, unsigned int numListeners, unsigned int tasksPerDispLimit) {
ThreadPoolAsync provider (new ThreadPoolAsyncImpl);
provider.setCountOfDispatchers(numListeners);
provider.setCountOfThreads(numThreads);
provider.setTasksPerDispLimit(tasksPerDispLimit);
return provider;
}
void ThreadPoolAsync::setCountOfDispatchers(unsigned int count) {
ptr->setCountOfDispatchers(count);
}
void ThreadPoolAsync::setCountOfThreads(unsigned int count) {
ptr->setCountOfThreads(count);
}
void ThreadPoolAsync::stop() {
ptr->stop();
}
ThreadPoolAsync::~ThreadPoolAsync() {
if (!ptr->isShared()) {
ptr->stop();
}
}
void ThreadPoolAsyncImpl::runAsync(const CustomFn& completion) {
if (exitFlag) {
defer >> completion;
return;
}
if (reqThreadCount > reqDispatcherCount) {
checkThreadCount();
dQueue.dispatch(completion);
} else {
auto lst = getListener();
lst->runAsync(completion);
}
}
void ThreadPoolAsync::setTasksPerDispLimit(unsigned int count) {
ptr->setTasksPerDispLimit(count);
}
ThreadPoolAsync::operator AsyncProvider() const {
return AsyncProvider(ptr);
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012, 2013 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "openMVG/exif_IO/exif_IO_EasyExif.hpp"
#include "openMVG_Samples/sensorWidthDatabase/ParseDatabase.hpp"
#include "openMVG/image/image.hpp"
#include "third_party/cmdLine/cmdLine.h"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include <iostream>
#include <fstream>
#include <memory>
#include <string>
#include <vector>
int main(int argc, char **argv)
{
CmdLine cmd;
std::string sImageDir;
std::string sfileDatabase = "";
std::string sOutputDir = "";
double focalPixPermm = -1.0;
cmd.add( make_option('i', sImageDir, "imageDirectory") );
cmd.add( make_option('d', sfileDatabase, "sensorWidthDatabase") );
cmd.add( make_option('o', sOutputDir, "outputDirectory") );
cmd.add( make_option('f', focalPixPermm, "focal") );
try {
if (argc == 1) throw std::string("Invalid command line parameter.");
cmd.process(argc, argv);
} catch(const std::string& s) {
std::cerr << "Usage: " << argv[0] << '\n'
<< "[-i|--imageDirectory]\n"
<< "[-d|--sensorWidthDatabase]\n"
<< "[-o|--outputDirectory]\n"
<< "[-f|--focal] (pixels)\n"
<< std::endl;
std::cerr << s << std::endl;
return EXIT_FAILURE;
}
std::cout << " You called : " <<std::endl
<< argv[0] << std::endl
<< "--imageDirectory " << sImageDir << std::endl
<< "--sensorWidthDatabase " << sfileDatabase << std::endl
<< "--outputDirectory " << sOutputDir << std::endl
<< "--focal " << focalPixPermm << std::endl;
if ( !stlplus::folder_exists( sImageDir ) )
{
std::cerr << "\nThe input directory doesn't exist" << std::endl;
return EXIT_FAILURE;
}
if (sOutputDir.empty())
{
std::cerr << "\nInvalid output directory" << std::endl;
return EXIT_FAILURE;
}
if ( !stlplus::folder_exists( sOutputDir ) )
{
if ( !stlplus::folder_create( sOutputDir ))
{
std::cerr << "\nCannot create output directory" << std::endl;
return EXIT_FAILURE;
}
}
std::vector<std::string> vec_image = stlplus::folder_files( sImageDir );
// Write the new file
std::ofstream listTXT( stlplus::create_filespec( sOutputDir,
"lists.txt" ).c_str() );
if ( listTXT )
{
std::sort(vec_image.begin(), vec_image.end());
for ( std::vector<std::string>::const_iterator iter_image = vec_image.begin();
iter_image != vec_image.end();
iter_image++ )
{
// Read meta data to fill width height and focalPixPermm
std::string sImageFilename = stlplus::create_filespec( sImageDir, *iter_image );
size_t width = -1;
size_t height = -1;
std::auto_ptr<Exif_IO> exifReader (new Exif_IO_EasyExif() );
exifReader->open( sImageFilename );
// Consider the case where focal is provided
std::ostringstream os;
//If image do not contains meta data
if ( !exifReader->doesHaveExifInfo() || focalPixPermm != -1)
{
Image<unsigned char> image;
if (openMVG::ReadImage( sImageFilename.c_str(), &image)) {
width = image.Width();
height = image.Height();
}
else
{
Image<RGBColor> imageRGB;
if (openMVG::ReadImage( sImageFilename.c_str(), &imageRGB)) {
width = imageRGB.Width();
height = imageRGB.Height();
}
else
{
Image<RGBAColor> imageRGBA;
if (openMVG::ReadImage( sImageFilename.c_str(), &imageRGBA)) {
width = imageRGBA.Width();
height = imageRGBA.Height();
}
else
continue; // image is not considered, cannot be read
}
}
if ( focalPixPermm == -1)
os << *iter_image << ";" << width << ";" << height << std::endl;
else
os << *iter_image << ";" << width << ";" << height << ";"
<< focalPixPermm << ";" << 0 << ";" << width/2.0 << ";"
<< 0 << ";" << focalPixPermm << ";" << height/2.0 << ";"
<< 0 << ";" << 0 << ";" << 1 << std::endl;
}
else // If image contains meta data
{
double focal = focalPixPermm;
width = exifReader->getWidth();
height = exifReader->getHeight();
std::string sCamName = exifReader->getBrand();
std::string sCamModel = exifReader->getModel();
std::vector<Datasheet> vec_database;
Datasheet datasheet;
if ( parseDatabase( sfileDatabase, vec_database ) )
{
if ( getInfo( sCamName, sCamModel, vec_database, datasheet ) )
{
// The camera model was found in the database so we can compute it's approximated focal length
double ccdw = datasheet._sensorSize;
focal = std::max ( width, height ) * exifReader->getFocal() / ccdw;
os << *iter_image << ";" << width << ";" << height << ";" << focal << ";" << sCamName << ";" << sCamModel << std::endl;
}
else
{
std::cout << "Camera \"" << sCamName << "\" model \"" << sCamModel << "\" doesn't exist in the database" << std::endl;
os << *iter_image << ";" << width << ";" << height << ";" << sCamName << ";" << sCamModel << std::endl;
}
}
else
{
std::cout << "Sensor width database \"" << sfileDatabase << "\" doesn't exist." << std::endl;
std::cout << "Please consider add your camera model in the database." << std::endl;
os << *iter_image << ";" << width << ";" << height << ";" << sCamName << ";" << sCamModel << std::endl;
}
}
std::cout << os.str();
listTXT << os.str();
}
}
listTXT.close();
return EXIT_SUCCESS;
}
<commit_msg>Add a -k option to set a known camera intrinsic matrix. #162<commit_after>// Copyright (c) 2012, 2013 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "openMVG/exif_IO/exif_IO_EasyExif.hpp"
#include "openMVG_Samples/sensorWidthDatabase/ParseDatabase.hpp"
#include "openMVG/image/image.hpp"
#include "openMVG/split/split.hpp"
#include "third_party/cmdLine/cmdLine.h"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include <iostream>
#include <fstream>
#include <sstream>
#include <memory>
#include <string>
#include <vector>
/// Check that Kmatrix is a string like "f;0;ppx;0;f;ppy;0;0;1"
/// With f,ppx,ppy as valid numerical value
bool checkIntrinsicStringValidity(const std::string & Kmatrix)
{
std::vector<std::string> vec_str;
split( Kmatrix, ";", vec_str );
if (vec_str.size() != 9) {
std::cerr << "\n Missing ';' character" << std::endl;
return false;
}
// Check that all K matrix value are valid numbers
for (size_t i = 0; i < vec_str.size(); ++i) {
double readvalue = 0.0;
std::stringstream ss;
ss.str(vec_str[i]);
if (! (ss >> readvalue) ) {
std::cerr << "\n Used an invalid not a number character" << std::endl;
return false;
}
}
return true;
}
int main(int argc, char **argv)
{
CmdLine cmd;
std::string sImageDir,
sfileDatabase = "",
sOutputDir = "",
sKmatrix;
double focalPixPermm = -1.0;
cmd.add( make_option('i', sImageDir, "imageDirectory") );
cmd.add( make_option('d', sfileDatabase, "sensorWidthDatabase") );
cmd.add( make_option('o', sOutputDir, "outputDirectory") );
cmd.add( make_option('f', focalPixPermm, "focal") );
cmd.add( make_option('k', sKmatrix, "intrinsics") );
try {
if (argc == 1) throw std::string("Invalid command line parameter.");
cmd.process(argc, argv);
} catch(const std::string& s) {
std::cerr << "Usage: " << argv[0] << '\n'
<< "[-i|--imageDirectory]\n"
<< "[-d|--sensorWidthDatabase]\n"
<< "[-o|--outputDirectory]\n"
<< "[-f|--focal] (pixels)\n"
<< "[-k|--intrinsics] Kmatrix: \"f;0;ppx;0;f;ppy;0;0;1\""
<< std::endl;
std::cerr << s << std::endl;
return EXIT_FAILURE;
}
std::cout << " You called : " <<std::endl
<< argv[0] << std::endl
<< "--imageDirectory " << sImageDir << std::endl
<< "--sensorWidthDatabase " << sfileDatabase << std::endl
<< "--outputDirectory " << sOutputDir << std::endl
<< "--focal " << focalPixPermm << std::endl
<< "--intrinsics " << sKmatrix << std::endl;
if ( !stlplus::folder_exists( sImageDir ) )
{
std::cerr << "\nThe input directory doesn't exist" << std::endl;
return EXIT_FAILURE;
}
if (sOutputDir.empty())
{
std::cerr << "\nInvalid output directory" << std::endl;
return EXIT_FAILURE;
}
if ( !stlplus::folder_exists( sOutputDir ) )
{
if ( !stlplus::folder_create( sOutputDir ))
{
std::cerr << "\nCannot create output directory" << std::endl;
return EXIT_FAILURE;
}
}
if (sKmatrix.size() > 0 && !checkIntrinsicStringValidity(sKmatrix) )
{
std::cerr << "\nInvalid K matrix input" << std::endl;
return EXIT_FAILURE;
}
if (sKmatrix.size() > 0 && focalPixPermm != -1.0)
{
std::cerr << "\nCannot combine -f and -k options" << std::endl;
return EXIT_FAILURE;
}
std::vector<std::string> vec_image = stlplus::folder_files( sImageDir );
// Write the new file
std::ofstream listTXT( stlplus::create_filespec( sOutputDir,
"lists.txt" ).c_str() );
if ( listTXT )
{
std::sort(vec_image.begin(), vec_image.end());
for ( std::vector<std::string>::const_iterator iter_image = vec_image.begin();
iter_image != vec_image.end();
iter_image++ )
{
// Read meta data to fill width height and focalPixPermm
std::string sImageFilename = stlplus::create_filespec( sImageDir, *iter_image );
size_t width = -1;
size_t height = -1;
std::auto_ptr<Exif_IO> exifReader (new Exif_IO_EasyExif() );
exifReader->open( sImageFilename );
// Consider the case where focal is provided
std::ostringstream os;
//If image do not contains meta data
if ( !exifReader->doesHaveExifInfo() || focalPixPermm != -1)
{
Image<unsigned char> image;
if (openMVG::ReadImage( sImageFilename.c_str(), &image)) {
width = image.Width();
height = image.Height();
}
else
{
Image<RGBColor> imageRGB;
if (openMVG::ReadImage( sImageFilename.c_str(), &imageRGB)) {
width = imageRGB.Width();
height = imageRGB.Height();
}
else
{
Image<RGBAColor> imageRGBA;
if (openMVG::ReadImage( sImageFilename.c_str(), &imageRGBA)) {
width = imageRGBA.Width();
height = imageRGBA.Height();
}
else
continue; // image is not considered, cannot be read
}
}
os << *iter_image << ";" << width << ";" << height;
if ( focalPixPermm == -1 && sKmatrix.size() == 0)
os << std::endl;
else
{
if (sKmatrix.size() > 0) // Known intrinsic matrix
{
os << ";" << sKmatrix << std::endl;
}
else
os << ";"
<< focalPixPermm << ";" << 0 << ";" << width/2.0 << ";"
<< 0 << ";" << focalPixPermm << ";" << height/2.0 << ";"
<< 0 << ";" << 0 << ";" << 1 << std::endl;
}
}
else // If image contains meta data
{
double focal = focalPixPermm;
width = exifReader->getWidth();
height = exifReader->getHeight();
std::string sCamName = exifReader->getBrand();
std::string sCamModel = exifReader->getModel();
std::vector<Datasheet> vec_database;
Datasheet datasheet;
if ( parseDatabase( sfileDatabase, vec_database ) )
{
if ( getInfo( sCamName, sCamModel, vec_database, datasheet ) )
{
// The camera model was found in the database so we can compute it's approximated focal length
double ccdw = datasheet._sensorSize;
focal = std::max ( width, height ) * exifReader->getFocal() / ccdw;
os << *iter_image << ";" << width << ";" << height << ";" << focal << ";" << sCamName << ";" << sCamModel << std::endl;
}
else
{
std::cout << "Camera \"" << sCamName << "\" model \"" << sCamModel << "\" doesn't exist in the database" << std::endl;
os << *iter_image << ";" << width << ";" << height << ";" << sCamName << ";" << sCamModel << std::endl;
}
}
else
{
std::cout << "Sensor width database \"" << sfileDatabase << "\" doesn't exist." << std::endl;
std::cout << "Please consider add your camera model in the database." << std::endl;
os << *iter_image << ";" << width << ";" << height << ";" << sCamName << ";" << sCamModel << std::endl;
}
}
std::cout << os.str();
listTXT << os.str();
}
}
listTXT.close();
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>// Copyright (C) 2015 Elviss Strazdins
// This file is part of the Ouzel engine.
#include <algorithm>
#include "Engine.h"
#include "Layer.h"
#include "Node.h"
#include "Camera.h"
#include "Renderer.h"
#include "Scene.h"
#include "Matrix4.h"
namespace ouzel
{
Layer::Layer()
{
_camera = std::make_shared<Camera>();
}
Layer::~Layer()
{
}
void Layer::update(float delta)
{
lock();
for (const NodePtr& child : _children)
{
child->update(delta);
}
unlock();
}
void Layer::draw()
{
_drawQueue.clear();
// render only if there is an active camera
if (_camera)
{
lock();
for (const NodePtr child : _children)
{
child->visit();
child->calculateTransformRecursive();
}
std::stable_sort(_drawQueue.begin(), _drawQueue.end(), [](const NodePtr& a, const NodePtr& b) {
return a->getZ() > b->getZ();
});
for (const NodePtr& node : _drawQueue)
{
node->process();
}
unlock();
}
}
bool Layer::addChild(const NodePtr& node)
{
if (NodeContainer::addChild(node))
{
node->addToLayer(std::static_pointer_cast<Layer>(shared_from_this()));
node->updateTransform(Matrix4::identity());
return true;
}
else
{
return false;
}
}
void Layer::addToDrawQueue(const NodePtr& node)
{
_drawQueue.push_back(node);
}
void Layer::setCamera(const CameraPtr& camera)
{
_camera = camera;
}
Vector2 Layer::screenToWorldLocation(const Vector2& position)
{
if (_camera)
{
Matrix4 projViewMatrix = _projection * _camera->getTransform();
Matrix4 inverseViewMatrix = projViewMatrix;
inverseViewMatrix.invert();
Vector3 result = Vector3(position.x, position.y, 0.0f);
inverseViewMatrix.transformPoint(&result);
return Vector2(result.x, result.y);
}
else
{
return Vector2();
}
}
Vector2 Layer::worldToScreenLocation(const Vector2& position)
{
if (_camera)
{
Matrix4 projViewMatrix = _projection * _camera->getTransform();
Vector3 result = Vector3(position.x, position.y, 0.0f);
projViewMatrix.transformPoint(&result);
return Vector2(result.x, result.y);
}
else
{
return Vector2();
}
}
NodePtr Layer::pickNode(const Vector2& position)
{
for (std::vector<NodePtr>::const_reverse_iterator i = _drawQueue.rbegin(); i != _drawQueue.rend(); ++i)
{
NodePtr node = *i;
if (node->isPickable() && node->pointOn(position))
{
return node;
}
}
return nullptr;
}
std::set<NodePtr> Layer::pickNodes(const Rectangle& rectangle)
{
std::set<NodePtr> result;
for (std::vector<NodePtr>::const_reverse_iterator i = _drawQueue.rbegin(); i != _drawQueue.rend(); ++i)
{
NodePtr node = *i;
if (node->isPickable() && node->rectangleOverlaps(rectangle))
{
result.insert(node);
}
}
return result;
}
void Layer::setScaleMode(ScaleMode scaleMode)
{
_scaleMode = scaleMode;
recalculateProjection();
}
void Layer::setDesignSize(const Size2& designSize)
{
_designSize = designSize;
recalculateProjection();
}
void Layer::recalculateProjection()
{
Size2 size = Engine::getInstance()->getRenderer()->getSize();
Vector2 scale(1.0f, 1.0f);
if (_designSize.width != 0.0f && _designSize.height != 0.0f &&
size.width != 0.0f && size.height != 0.0f)
{
float aspectRatio = size.width / size.height;
switch (_scaleMode)
{
case ScaleMode::None:
{
// Do nothing
break;
}
case ScaleMode::ExactFit:
{
scale.x = _designSize.width / size.width;
scale.y = _designSize.height / size.height;
break;
}
case ScaleMode::NoBorder:
{
if (size.width / size.height > _designSize.width / _designSize.height)
{
scale.x = _designSize.width / size.width;
scale.y = (_designSize.width / size.height) / aspectRatio;
}
else
{
scale.x = (_designSize.height / size.width) * aspectRatio;
scale.y = _designSize.height / size.height;
}
break;
}
case ScaleMode::ShowAll:
{
if (size.width / size.height < _designSize.width / _designSize.height)
{
scale.x = _designSize.width / size.width;
scale.y = (_designSize.width / size.height) / aspectRatio;
}
else
{
scale.x = (_designSize.height / size.width) * aspectRatio;
scale.y = _designSize.height / size.height;
}
break;
}
}
}
Matrix4::createOrthographic(size.width * scale.x, size.height * scale.y, -1.0f, 1.0f, &_projection);
_inverseProjection = _projection;
_inverseProjection.invert();
}
void Layer::setOrder(int32_t order)
{
_order = order;
if (ScenePtr scene = _scene.lock())
{
scene->reorderLayers();
}
}
void Layer::addToScene(const ScenePtr& scene)
{
_scene = scene;
}
void Layer::removeFromScene()
{
_scene.reset();
}
}
<commit_msg>Don' t use scale for calculation projection matrix<commit_after>// Copyright (C) 2015 Elviss Strazdins
// This file is part of the Ouzel engine.
#include <algorithm>
#include "Engine.h"
#include "Layer.h"
#include "Node.h"
#include "Camera.h"
#include "Renderer.h"
#include "Scene.h"
#include "Matrix4.h"
namespace ouzel
{
Layer::Layer()
{
_camera = std::make_shared<Camera>();
}
Layer::~Layer()
{
}
void Layer::update(float delta)
{
lock();
for (const NodePtr& child : _children)
{
child->update(delta);
}
unlock();
}
void Layer::draw()
{
_drawQueue.clear();
// render only if there is an active camera
if (_camera)
{
lock();
for (const NodePtr child : _children)
{
child->visit();
child->calculateTransformRecursive();
}
std::stable_sort(_drawQueue.begin(), _drawQueue.end(), [](const NodePtr& a, const NodePtr& b) {
return a->getZ() > b->getZ();
});
for (const NodePtr& node : _drawQueue)
{
node->process();
}
unlock();
}
}
bool Layer::addChild(const NodePtr& node)
{
if (NodeContainer::addChild(node))
{
node->addToLayer(std::static_pointer_cast<Layer>(shared_from_this()));
node->updateTransform(Matrix4::identity());
return true;
}
else
{
return false;
}
}
void Layer::addToDrawQueue(const NodePtr& node)
{
_drawQueue.push_back(node);
}
void Layer::setCamera(const CameraPtr& camera)
{
_camera = camera;
}
Vector2 Layer::screenToWorldLocation(const Vector2& position)
{
if (_camera)
{
Matrix4 projViewMatrix = _projection * _camera->getTransform();
Matrix4 inverseViewMatrix = projViewMatrix;
inverseViewMatrix.invert();
Vector3 result = Vector3(position.x, position.y, 0.0f);
inverseViewMatrix.transformPoint(&result);
return Vector2(result.x, result.y);
}
else
{
return Vector2();
}
}
Vector2 Layer::worldToScreenLocation(const Vector2& position)
{
if (_camera)
{
Matrix4 projViewMatrix = _projection * _camera->getTransform();
Vector3 result = Vector3(position.x, position.y, 0.0f);
projViewMatrix.transformPoint(&result);
return Vector2(result.x, result.y);
}
else
{
return Vector2();
}
}
NodePtr Layer::pickNode(const Vector2& position)
{
for (std::vector<NodePtr>::const_reverse_iterator i = _drawQueue.rbegin(); i != _drawQueue.rend(); ++i)
{
NodePtr node = *i;
if (node->isPickable() && node->pointOn(position))
{
return node;
}
}
return nullptr;
}
std::set<NodePtr> Layer::pickNodes(const Rectangle& rectangle)
{
std::set<NodePtr> result;
for (std::vector<NodePtr>::const_reverse_iterator i = _drawQueue.rbegin(); i != _drawQueue.rend(); ++i)
{
NodePtr node = *i;
if (node->isPickable() && node->rectangleOverlaps(rectangle))
{
result.insert(node);
}
}
return result;
}
void Layer::setScaleMode(ScaleMode scaleMode)
{
_scaleMode = scaleMode;
recalculateProjection();
}
void Layer::setDesignSize(const Size2& designSize)
{
_designSize = designSize;
recalculateProjection();
}
void Layer::recalculateProjection()
{
Size2 size = Engine::getInstance()->getRenderer()->getSize();
if (_designSize.width != 0.0f && _designSize.height != 0.0f &&
size.width != 0.0f && size.height != 0.0f)
{
float aspectRatio = size.width / size.height;
switch (_scaleMode)
{
case ScaleMode::None:
{
// Do nothing
break;
}
case ScaleMode::ExactFit:
{
size.width = _designSize.width;
size.height = _designSize.height;
break;
}
case ScaleMode::NoBorder:
{
if (size.width / size.height > _designSize.width / _designSize.height)
{
size.width = _designSize.width;
size.height = _designSize.width / aspectRatio;
}
else
{
size.width = _designSize.height * aspectRatio;
size.height = _designSize.height;
}
break;
}
case ScaleMode::ShowAll:
{
if (size.width / size.height < _designSize.width / _designSize.height)
{
size.width = _designSize.width;
size.height = _designSize.width / aspectRatio;
}
else
{
size.width = _designSize.height * aspectRatio;
size.height = _designSize.height;
}
break;
}
}
}
Matrix4::createOrthographic(size.width, size.height, -1.0f, 1.0f, &_projection);
_inverseProjection = _projection;
_inverseProjection.invert();
}
void Layer::setOrder(int32_t order)
{
_order = order;
if (ScenePtr scene = _scene.lock())
{
scene->reorderLayers();
}
}
void Layer::addToScene(const ScenePtr& scene)
{
_scene = scene;
}
void Layer::removeFromScene()
{
_scene.reset();
}
}
<|endoftext|>
|
<commit_before><commit_msg>coverity#708646 Uninitialized scalar field<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: scrwnd.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2006-06-19 19:39:49 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <math.h>
#include <limits.h>
#ifndef _TOOLS_TIME_HXX
#include <tools/time.hxx>
#endif
#include <tools/debug.hxx>
#ifndef _SV_SVIDS_HRC
#include <svids.hrc>
#endif
#ifndef _SV_SVDATA_HXX
#include <svdata.hxx>
#endif
#ifndef _VCL_TIMER_HXX
#include <timer.hxx>
#endif
#ifndef _VCL_EVENT_HXX
#include <event.hxx>
#endif
#ifndef _VCL_SCRWND_HXX
#include <scrwnd.hxx>
#endif
// -----------
// - Defines -
// -----------
#define WHEEL_WIDTH 25
#define WHEEL_RADIUS ((WHEEL_WIDTH) >> 1 )
#define MAX_TIME 300
#define MIN_TIME 20
#define DEF_TIMEOUT 50
// -------------------
// - ImplWheelWindow -
// -------------------
ImplWheelWindow::ImplWheelWindow( Window* pParent ) :
FloatingWindow ( pParent, 0 ),
mnRepaintTime ( 1UL ),
mnTimeout ( DEF_TIMEOUT ),
mnWheelMode ( WHEELMODE_NONE ),
mnActDist ( 0UL ),
mnActDeltaX ( 0L ),
mnActDeltaY ( 0L )
{
// we need a parent
DBG_ASSERT( pParent, "ImplWheelWindow::ImplWheelWindow(): Parent not set!" );
const Size aSize( pParent->GetOutputSizePixel() );
const USHORT nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags;
const BOOL bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0;
const BOOL bVert = ( nFlags & AUTOSCROLL_VERT ) != 0;
// calculate maximum speed distance
mnMaxWidth = (ULONG) ( 0.4 * hypot( (double) aSize.Width(), aSize.Height() ) );
// create wheel window
SetTitleType( FLOATWIN_TITLE_NONE );
ImplCreateImageList();
ResMgr* pResMgr = ImplGetResMgr();
Bitmap aBmp;
if( pResMgr )
aBmp = Bitmap( ResId( SV_RESID_BITMAP_SCROLLMSK, ImplGetResMgr() ) );
ImplSetRegion( aBmp );
// set wheel mode
if( bHorz && bVert )
ImplSetWheelMode( WHEELMODE_VH );
else if( bHorz )
ImplSetWheelMode( WHEELMODE_H );
else
ImplSetWheelMode( WHEELMODE_V );
// init timer
mpTimer = new Timer;
mpTimer->SetTimeoutHdl( LINK( this, ImplWheelWindow, ImplScrollHdl ) );
mpTimer->SetTimeout( mnTimeout );
mpTimer->Start();
CaptureMouse();
}
// ------------------------------------------------------------------------
ImplWheelWindow::~ImplWheelWindow()
{
ReleaseMouse();
mpTimer->Stop();
delete mpTimer;
}
// ------------------------------------------------------------------------
void ImplWheelWindow::ImplSetRegion( const Bitmap& rRegionBmp )
{
Point aPos( GetPointerPosPixel() );
const Size aSize( rRegionBmp.GetSizePixel() );
Point aPoint;
const Rectangle aRect( aPoint, aSize );
maCenter = maLastMousePos = aPos;
aPos.X() -= aSize.Width() >> 1;
aPos.Y() -= aSize.Height() >> 1;
SetPosSizePixel( aPos, aSize );
SetWindowRegionPixel( rRegionBmp.CreateRegion( COL_BLACK, aRect ) );
}
// ------------------------------------------------------------------------
void ImplWheelWindow::ImplCreateImageList()
{
Bitmap aImgBmp;
ResMgr* pResMgr = ImplGetResMgr();
if( pResMgr )
aImgBmp = Bitmap( ResId( SV_RESID_BITMAP_SCROLLBMP, pResMgr ) );
maImgList = ImageList( aImgBmp, 6 );
}
// ------------------------------------------------------------------------
void ImplWheelWindow::ImplSetWheelMode( ULONG nWheelMode )
{
if( nWheelMode != mnWheelMode )
{
mnWheelMode = nWheelMode;
if( WHEELMODE_NONE == mnWheelMode )
{
if( IsVisible() )
Hide();
}
else
{
if( !IsVisible() )
Show();
ImplDrawWheel();
}
}
}
// ------------------------------------------------------------------------
void ImplWheelWindow::ImplDrawWheel()
{
USHORT nId;
switch( mnWheelMode )
{
case( WHEELMODE_VH ): nId = 1; break;
case( WHEELMODE_V ): nId = 2; break;
case( WHEELMODE_H ): nId = 3; break;
case( WHEELMODE_SCROLL_VH ):nId = 4; break;
case( WHEELMODE_SCROLL_V ): nId = 5; break;
case( WHEELMODE_SCROLL_H ): nId = 6; break;
default: nId = 0; break;
}
if( nId )
DrawImage( Point(), maImgList.GetImage( nId ) );
}
// ------------------------------------------------------------------------
void ImplWheelWindow::ImplRecalcScrollValues()
{
if( mnActDist < WHEEL_RADIUS )
{
mnActDeltaX = mnActDeltaY = 0L;
mnTimeout = DEF_TIMEOUT;
}
else
{
ULONG nCurTime;
// calc current time
if( mnMaxWidth )
{
const double fExp = ( (double) mnActDist / mnMaxWidth ) * log10( (double) MAX_TIME / MIN_TIME );
nCurTime = (ULONG) ( MAX_TIME / pow( 10., fExp ) );
}
else
nCurTime = MAX_TIME;
if( !nCurTime )
nCurTime = 1UL;
if( mnRepaintTime <= nCurTime )
mnTimeout = nCurTime - mnRepaintTime;
else
{
long nMult = mnRepaintTime / nCurTime;
if( !( mnRepaintTime % nCurTime ) )
mnTimeout = 0UL;
else
mnTimeout = ++nMult * nCurTime - mnRepaintTime;
double fValX = (double) mnActDeltaX * nMult;
double fValY = (double) mnActDeltaY * nMult;
if( fValX > LONG_MAX )
mnActDeltaX = LONG_MAX;
else if( fValX < LONG_MIN )
mnActDeltaX = LONG_MIN;
else
mnActDeltaX = (long) fValX;
if( fValY > LONG_MAX )
mnActDeltaY = LONG_MAX;
else if( fValY < LONG_MIN )
mnActDeltaY = LONG_MIN;
else
mnActDeltaY = (long) fValY;
}
}
}
// ------------------------------------------------------------------------
PointerStyle ImplWheelWindow::ImplGetMousePointer( long nDistX, long nDistY )
{
PointerStyle eStyle;
const USHORT nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags;
const BOOL bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0;
const BOOL bVert = ( nFlags & AUTOSCROLL_VERT ) != 0;
if( bHorz || bVert )
{
if( mnActDist < WHEEL_RADIUS )
{
if( bHorz && bVert )
eStyle = POINTER_AUTOSCROLL_NSWE;
else if( bHorz )
eStyle = POINTER_AUTOSCROLL_WE;
else
eStyle = POINTER_AUTOSCROLL_NS;
}
else
{
double fAngle = atan2( (double) -nDistY, nDistX ) / F_PI180;
if( fAngle < 0.0 )
fAngle += 360.;
if( bHorz && bVert )
{
if( fAngle >= 22.5 && fAngle <= 67.5 )
eStyle = POINTER_AUTOSCROLL_NE;
else if( fAngle >= 67.5 && fAngle <= 112.5 )
eStyle = POINTER_AUTOSCROLL_N;
else if( fAngle >= 112.5 && fAngle <= 157.5 )
eStyle = POINTER_AUTOSCROLL_NW;
else if( fAngle >= 157.5 && fAngle <= 202.5 )
eStyle = POINTER_AUTOSCROLL_W;
else if( fAngle >= 202.5 && fAngle <= 247.5 )
eStyle = POINTER_AUTOSCROLL_SW;
else if( fAngle >= 247.5 && fAngle <= 292.5 )
eStyle = POINTER_AUTOSCROLL_S;
else if( fAngle >= 292.5 && fAngle <= 337.5 )
eStyle = POINTER_AUTOSCROLL_SE;
else
eStyle = POINTER_AUTOSCROLL_E;
}
else if( bHorz )
{
if( fAngle >= 270. || fAngle <= 90. )
eStyle = POINTER_AUTOSCROLL_E;
else
eStyle = POINTER_AUTOSCROLL_W;
}
else
{
if( fAngle >= 0. && fAngle <= 180. )
eStyle = POINTER_AUTOSCROLL_N;
else
eStyle = POINTER_AUTOSCROLL_S;
}
}
}
else
eStyle = POINTER_ARROW;
return eStyle;
}
// ------------------------------------------------------------------------
void ImplWheelWindow::Paint( const Rectangle& )
{
ImplDrawWheel();
}
// ------------------------------------------------------------------------
void ImplWheelWindow::MouseMove( const MouseEvent& rMEvt )
{
FloatingWindow::MouseMove( rMEvt );
const Point aMousePos( OutputToScreenPixel( rMEvt.GetPosPixel() ) );
const long nDistX = aMousePos.X() - maCenter.X();
const long nDistY = aMousePos.Y() - maCenter.Y();
mnActDist = (ULONG) hypot( (double) nDistX, nDistY );
const PointerStyle eActStyle = ImplGetMousePointer( nDistX, nDistY );
const USHORT nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags;
const BOOL bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0;
const BOOL bVert = ( nFlags & AUTOSCROLL_VERT ) != 0;
const BOOL bOuter = mnActDist > WHEEL_RADIUS;
if( bOuter && ( maLastMousePos != aMousePos ) )
{
switch( eActStyle )
{
case( POINTER_AUTOSCROLL_N ): mnActDeltaX = +0L, mnActDeltaY = +1L; break;
case( POINTER_AUTOSCROLL_S ): mnActDeltaX = +0L, mnActDeltaY = -1L; break;
case( POINTER_AUTOSCROLL_W ): mnActDeltaX = +1L, mnActDeltaY = +0L; break;
case( POINTER_AUTOSCROLL_E ): mnActDeltaX = -1L, mnActDeltaY = +0L; break;
case( POINTER_AUTOSCROLL_NW ): mnActDeltaX = +1L, mnActDeltaY = +1L; break;
case( POINTER_AUTOSCROLL_NE ): mnActDeltaX = -1L, mnActDeltaY = +1L; break;
case( POINTER_AUTOSCROLL_SW ): mnActDeltaX = +1L, mnActDeltaY = -1L; break;
case( POINTER_AUTOSCROLL_SE ): mnActDeltaX = -1L, mnActDeltaY = -1L; break;
default:
break;
}
}
ImplRecalcScrollValues();
maLastMousePos = aMousePos;
SetPointer( eActStyle );
if( bHorz && bVert )
ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_VH : WHEELMODE_VH );
else if( bHorz )
ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_H : WHEELMODE_H );
else
ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_V : WHEELMODE_V );
}
// ------------------------------------------------------------------------
void ImplWheelWindow::MouseButtonUp( const MouseEvent& rMEvt )
{
if( mnActDist > WHEEL_RADIUS )
GetParent()->EndAutoScroll();
else
FloatingWindow::MouseButtonUp( rMEvt );
}
// ------------------------------------------------------------------------
IMPL_LINK( ImplWheelWindow, ImplScrollHdl, Timer*, EMPTYARG )
{
if ( mnActDeltaX || mnActDeltaY )
{
Window* pWindow = GetParent();
const Point aMousePos( pWindow->OutputToScreenPixel( pWindow->GetPointerPosPixel() ) );
Point aCmdMousePos( pWindow->ImplFrameToOutput( aMousePos ) );
CommandScrollData aScrollData( mnActDeltaX, mnActDeltaY );
CommandEvent aCEvt( aCmdMousePos, COMMAND_AUTOSCROLL, TRUE, &aScrollData );
NotifyEvent aNCmdEvt( EVENT_COMMAND, pWindow, &aCEvt );
if ( !ImplCallPreNotify( aNCmdEvt ) )
{
const ULONG nTime = Time::GetSystemTicks();
pWindow->Command( aCEvt );
mnRepaintTime = Max( Time::GetSystemTicks() - nTime, 1UL );
ImplRecalcScrollValues();
}
}
if ( mnTimeout != mpTimer->GetTimeout() )
mpTimer->SetTimeout( mnTimeout );
mpTimer->Start();
return 0L;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.7.112); FILE MERGED 2006/09/01 17:57:55 kaib 1.7.112.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: scrwnd.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2006-09-17 12:20:32 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#include <math.h>
#include <limits.h>
#ifndef _TOOLS_TIME_HXX
#include <tools/time.hxx>
#endif
#include <tools/debug.hxx>
#ifndef _SV_SVIDS_HRC
#include <svids.hrc>
#endif
#ifndef _SV_SVDATA_HXX
#include <svdata.hxx>
#endif
#ifndef _VCL_TIMER_HXX
#include <timer.hxx>
#endif
#ifndef _VCL_EVENT_HXX
#include <event.hxx>
#endif
#ifndef _VCL_SCRWND_HXX
#include <scrwnd.hxx>
#endif
// -----------
// - Defines -
// -----------
#define WHEEL_WIDTH 25
#define WHEEL_RADIUS ((WHEEL_WIDTH) >> 1 )
#define MAX_TIME 300
#define MIN_TIME 20
#define DEF_TIMEOUT 50
// -------------------
// - ImplWheelWindow -
// -------------------
ImplWheelWindow::ImplWheelWindow( Window* pParent ) :
FloatingWindow ( pParent, 0 ),
mnRepaintTime ( 1UL ),
mnTimeout ( DEF_TIMEOUT ),
mnWheelMode ( WHEELMODE_NONE ),
mnActDist ( 0UL ),
mnActDeltaX ( 0L ),
mnActDeltaY ( 0L )
{
// we need a parent
DBG_ASSERT( pParent, "ImplWheelWindow::ImplWheelWindow(): Parent not set!" );
const Size aSize( pParent->GetOutputSizePixel() );
const USHORT nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags;
const BOOL bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0;
const BOOL bVert = ( nFlags & AUTOSCROLL_VERT ) != 0;
// calculate maximum speed distance
mnMaxWidth = (ULONG) ( 0.4 * hypot( (double) aSize.Width(), aSize.Height() ) );
// create wheel window
SetTitleType( FLOATWIN_TITLE_NONE );
ImplCreateImageList();
ResMgr* pResMgr = ImplGetResMgr();
Bitmap aBmp;
if( pResMgr )
aBmp = Bitmap( ResId( SV_RESID_BITMAP_SCROLLMSK, ImplGetResMgr() ) );
ImplSetRegion( aBmp );
// set wheel mode
if( bHorz && bVert )
ImplSetWheelMode( WHEELMODE_VH );
else if( bHorz )
ImplSetWheelMode( WHEELMODE_H );
else
ImplSetWheelMode( WHEELMODE_V );
// init timer
mpTimer = new Timer;
mpTimer->SetTimeoutHdl( LINK( this, ImplWheelWindow, ImplScrollHdl ) );
mpTimer->SetTimeout( mnTimeout );
mpTimer->Start();
CaptureMouse();
}
// ------------------------------------------------------------------------
ImplWheelWindow::~ImplWheelWindow()
{
ReleaseMouse();
mpTimer->Stop();
delete mpTimer;
}
// ------------------------------------------------------------------------
void ImplWheelWindow::ImplSetRegion( const Bitmap& rRegionBmp )
{
Point aPos( GetPointerPosPixel() );
const Size aSize( rRegionBmp.GetSizePixel() );
Point aPoint;
const Rectangle aRect( aPoint, aSize );
maCenter = maLastMousePos = aPos;
aPos.X() -= aSize.Width() >> 1;
aPos.Y() -= aSize.Height() >> 1;
SetPosSizePixel( aPos, aSize );
SetWindowRegionPixel( rRegionBmp.CreateRegion( COL_BLACK, aRect ) );
}
// ------------------------------------------------------------------------
void ImplWheelWindow::ImplCreateImageList()
{
Bitmap aImgBmp;
ResMgr* pResMgr = ImplGetResMgr();
if( pResMgr )
aImgBmp = Bitmap( ResId( SV_RESID_BITMAP_SCROLLBMP, pResMgr ) );
maImgList = ImageList( aImgBmp, 6 );
}
// ------------------------------------------------------------------------
void ImplWheelWindow::ImplSetWheelMode( ULONG nWheelMode )
{
if( nWheelMode != mnWheelMode )
{
mnWheelMode = nWheelMode;
if( WHEELMODE_NONE == mnWheelMode )
{
if( IsVisible() )
Hide();
}
else
{
if( !IsVisible() )
Show();
ImplDrawWheel();
}
}
}
// ------------------------------------------------------------------------
void ImplWheelWindow::ImplDrawWheel()
{
USHORT nId;
switch( mnWheelMode )
{
case( WHEELMODE_VH ): nId = 1; break;
case( WHEELMODE_V ): nId = 2; break;
case( WHEELMODE_H ): nId = 3; break;
case( WHEELMODE_SCROLL_VH ):nId = 4; break;
case( WHEELMODE_SCROLL_V ): nId = 5; break;
case( WHEELMODE_SCROLL_H ): nId = 6; break;
default: nId = 0; break;
}
if( nId )
DrawImage( Point(), maImgList.GetImage( nId ) );
}
// ------------------------------------------------------------------------
void ImplWheelWindow::ImplRecalcScrollValues()
{
if( mnActDist < WHEEL_RADIUS )
{
mnActDeltaX = mnActDeltaY = 0L;
mnTimeout = DEF_TIMEOUT;
}
else
{
ULONG nCurTime;
// calc current time
if( mnMaxWidth )
{
const double fExp = ( (double) mnActDist / mnMaxWidth ) * log10( (double) MAX_TIME / MIN_TIME );
nCurTime = (ULONG) ( MAX_TIME / pow( 10., fExp ) );
}
else
nCurTime = MAX_TIME;
if( !nCurTime )
nCurTime = 1UL;
if( mnRepaintTime <= nCurTime )
mnTimeout = nCurTime - mnRepaintTime;
else
{
long nMult = mnRepaintTime / nCurTime;
if( !( mnRepaintTime % nCurTime ) )
mnTimeout = 0UL;
else
mnTimeout = ++nMult * nCurTime - mnRepaintTime;
double fValX = (double) mnActDeltaX * nMult;
double fValY = (double) mnActDeltaY * nMult;
if( fValX > LONG_MAX )
mnActDeltaX = LONG_MAX;
else if( fValX < LONG_MIN )
mnActDeltaX = LONG_MIN;
else
mnActDeltaX = (long) fValX;
if( fValY > LONG_MAX )
mnActDeltaY = LONG_MAX;
else if( fValY < LONG_MIN )
mnActDeltaY = LONG_MIN;
else
mnActDeltaY = (long) fValY;
}
}
}
// ------------------------------------------------------------------------
PointerStyle ImplWheelWindow::ImplGetMousePointer( long nDistX, long nDistY )
{
PointerStyle eStyle;
const USHORT nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags;
const BOOL bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0;
const BOOL bVert = ( nFlags & AUTOSCROLL_VERT ) != 0;
if( bHorz || bVert )
{
if( mnActDist < WHEEL_RADIUS )
{
if( bHorz && bVert )
eStyle = POINTER_AUTOSCROLL_NSWE;
else if( bHorz )
eStyle = POINTER_AUTOSCROLL_WE;
else
eStyle = POINTER_AUTOSCROLL_NS;
}
else
{
double fAngle = atan2( (double) -nDistY, nDistX ) / F_PI180;
if( fAngle < 0.0 )
fAngle += 360.;
if( bHorz && bVert )
{
if( fAngle >= 22.5 && fAngle <= 67.5 )
eStyle = POINTER_AUTOSCROLL_NE;
else if( fAngle >= 67.5 && fAngle <= 112.5 )
eStyle = POINTER_AUTOSCROLL_N;
else if( fAngle >= 112.5 && fAngle <= 157.5 )
eStyle = POINTER_AUTOSCROLL_NW;
else if( fAngle >= 157.5 && fAngle <= 202.5 )
eStyle = POINTER_AUTOSCROLL_W;
else if( fAngle >= 202.5 && fAngle <= 247.5 )
eStyle = POINTER_AUTOSCROLL_SW;
else if( fAngle >= 247.5 && fAngle <= 292.5 )
eStyle = POINTER_AUTOSCROLL_S;
else if( fAngle >= 292.5 && fAngle <= 337.5 )
eStyle = POINTER_AUTOSCROLL_SE;
else
eStyle = POINTER_AUTOSCROLL_E;
}
else if( bHorz )
{
if( fAngle >= 270. || fAngle <= 90. )
eStyle = POINTER_AUTOSCROLL_E;
else
eStyle = POINTER_AUTOSCROLL_W;
}
else
{
if( fAngle >= 0. && fAngle <= 180. )
eStyle = POINTER_AUTOSCROLL_N;
else
eStyle = POINTER_AUTOSCROLL_S;
}
}
}
else
eStyle = POINTER_ARROW;
return eStyle;
}
// ------------------------------------------------------------------------
void ImplWheelWindow::Paint( const Rectangle& )
{
ImplDrawWheel();
}
// ------------------------------------------------------------------------
void ImplWheelWindow::MouseMove( const MouseEvent& rMEvt )
{
FloatingWindow::MouseMove( rMEvt );
const Point aMousePos( OutputToScreenPixel( rMEvt.GetPosPixel() ) );
const long nDistX = aMousePos.X() - maCenter.X();
const long nDistY = aMousePos.Y() - maCenter.Y();
mnActDist = (ULONG) hypot( (double) nDistX, nDistY );
const PointerStyle eActStyle = ImplGetMousePointer( nDistX, nDistY );
const USHORT nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags;
const BOOL bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0;
const BOOL bVert = ( nFlags & AUTOSCROLL_VERT ) != 0;
const BOOL bOuter = mnActDist > WHEEL_RADIUS;
if( bOuter && ( maLastMousePos != aMousePos ) )
{
switch( eActStyle )
{
case( POINTER_AUTOSCROLL_N ): mnActDeltaX = +0L, mnActDeltaY = +1L; break;
case( POINTER_AUTOSCROLL_S ): mnActDeltaX = +0L, mnActDeltaY = -1L; break;
case( POINTER_AUTOSCROLL_W ): mnActDeltaX = +1L, mnActDeltaY = +0L; break;
case( POINTER_AUTOSCROLL_E ): mnActDeltaX = -1L, mnActDeltaY = +0L; break;
case( POINTER_AUTOSCROLL_NW ): mnActDeltaX = +1L, mnActDeltaY = +1L; break;
case( POINTER_AUTOSCROLL_NE ): mnActDeltaX = -1L, mnActDeltaY = +1L; break;
case( POINTER_AUTOSCROLL_SW ): mnActDeltaX = +1L, mnActDeltaY = -1L; break;
case( POINTER_AUTOSCROLL_SE ): mnActDeltaX = -1L, mnActDeltaY = -1L; break;
default:
break;
}
}
ImplRecalcScrollValues();
maLastMousePos = aMousePos;
SetPointer( eActStyle );
if( bHorz && bVert )
ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_VH : WHEELMODE_VH );
else if( bHorz )
ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_H : WHEELMODE_H );
else
ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_V : WHEELMODE_V );
}
// ------------------------------------------------------------------------
void ImplWheelWindow::MouseButtonUp( const MouseEvent& rMEvt )
{
if( mnActDist > WHEEL_RADIUS )
GetParent()->EndAutoScroll();
else
FloatingWindow::MouseButtonUp( rMEvt );
}
// ------------------------------------------------------------------------
IMPL_LINK( ImplWheelWindow, ImplScrollHdl, Timer*, EMPTYARG )
{
if ( mnActDeltaX || mnActDeltaY )
{
Window* pWindow = GetParent();
const Point aMousePos( pWindow->OutputToScreenPixel( pWindow->GetPointerPosPixel() ) );
Point aCmdMousePos( pWindow->ImplFrameToOutput( aMousePos ) );
CommandScrollData aScrollData( mnActDeltaX, mnActDeltaY );
CommandEvent aCEvt( aCmdMousePos, COMMAND_AUTOSCROLL, TRUE, &aScrollData );
NotifyEvent aNCmdEvt( EVENT_COMMAND, pWindow, &aCEvt );
if ( !ImplCallPreNotify( aNCmdEvt ) )
{
const ULONG nTime = Time::GetSystemTicks();
pWindow->Command( aCEvt );
mnRepaintTime = Max( Time::GetSystemTicks() - nTime, 1UL );
ImplRecalcScrollValues();
}
}
if ( mnTimeout != mpTimer->GetTimeout() )
mpTimer->SetTimeout( mnTimeout );
mpTimer->Start();
return 0L;
}
<|endoftext|>
|
<commit_before><commit_msg>vcl: tabify WindowImpl<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2013, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "db/dbformat.h"
#include <stdio.h>
#include "port/port.h"
#include "util/coding.h"
#include "util/perf_context_imp.h"
namespace rocksdb {
uint64_t PackSequenceAndType(uint64_t seq, ValueType t) {
assert(seq <= kMaxSequenceNumber);
assert(t <= kValueTypeForSeek);
return (seq << 8) | t;
}
void UnPackSequenceAndType(uint64_t packed, uint64_t* seq, ValueType* t) {
*seq = packed >> 8;
*t = static_cast<ValueType>(packed & 0xff);
assert(*seq <= kMaxSequenceNumber);
assert(*t <= kValueTypeForSeek);
}
void AppendInternalKey(std::string* result, const ParsedInternalKey& key) {
result->append(key.user_key.data(), key.user_key.size());
PutFixed64(result, PackSequenceAndType(key.sequence, key.type));
}
std::string ParsedInternalKey::DebugString(bool hex) const {
char buf[50];
snprintf(buf, sizeof(buf), "' @ %llu : %d",
(unsigned long long) sequence,
int(type));
std::string result = "'";
result += user_key.ToString(hex);
result += buf;
return result;
}
std::string InternalKey::DebugString(bool hex) const {
std::string result;
ParsedInternalKey parsed;
if (ParseInternalKey(rep_, &parsed)) {
result = parsed.DebugString(hex);
} else {
result = "(bad)";
result.append(EscapeString(rep_));
}
return result;
}
const char* InternalKeyComparator::Name() const {
return name_.c_str();
}
int InternalKeyComparator::Compare(const Slice& akey, const Slice& bkey) const {
// Order by:
// increasing user key (according to user-supplied comparator)
// decreasing sequence number
// decreasing type (though sequence# should be enough to disambiguate)
int r = user_comparator_->Compare(ExtractUserKey(akey), ExtractUserKey(bkey));
PERF_COUNTER_ADD(user_key_comparison_count, 1);
if (r == 0) {
const uint64_t anum = DecodeFixed64(akey.data() + akey.size() - 8);
const uint64_t bnum = DecodeFixed64(bkey.data() + bkey.size() - 8);
if (anum > bnum) {
r = -1;
} else if (anum < bnum) {
r = +1;
}
}
return r;
}
int InternalKeyComparator::Compare(const ParsedInternalKey& a,
const ParsedInternalKey& b) const {
// Order by:
// increasing user key (according to user-supplied comparator)
// decreasing sequence number
// decreasing type (though sequence# should be enough to disambiguate)
int r = user_comparator_->Compare(a.user_key, b.user_key);
PERF_COUNTER_ADD(user_key_comparison_count, 1);
if (r == 0) {
if (a.sequence > b.sequence) {
r = -1;
} else if (a.sequence < b.sequence) {
r = +1;
} else if (a.type > b.type) {
r = -1;
} else if (a.type < b.type) {
r = +1;
}
}
return r;
}
void InternalKeyComparator::FindShortestSeparator(
std::string* start,
const Slice& limit) const {
// Attempt to shorten the user portion of the key
Slice user_start = ExtractUserKey(*start);
Slice user_limit = ExtractUserKey(limit);
std::string tmp(user_start.data(), user_start.size());
user_comparator_->FindShortestSeparator(&tmp, user_limit);
if (tmp.size() < user_start.size() &&
user_comparator_->Compare(user_start, tmp) < 0) {
// User key has become shorter physically, but larger logically.
// Tack on the earliest possible number to the shortened user key.
PutFixed64(&tmp, PackSequenceAndType(kMaxSequenceNumber,kValueTypeForSeek));
assert(this->Compare(*start, tmp) < 0);
assert(this->Compare(tmp, limit) < 0);
start->swap(tmp);
}
}
void InternalKeyComparator::FindShortSuccessor(std::string* key) const {
Slice user_key = ExtractUserKey(*key);
std::string tmp(user_key.data(), user_key.size());
user_comparator_->FindShortSuccessor(&tmp);
if (tmp.size() < user_key.size() &&
user_comparator_->Compare(user_key, tmp) < 0) {
// User key has become shorter physically, but larger logically.
// Tack on the earliest possible number to the shortened user key.
PutFixed64(&tmp, PackSequenceAndType(kMaxSequenceNumber,kValueTypeForSeek));
assert(this->Compare(*key, tmp) < 0);
key->swap(tmp);
}
}
LookupKey::LookupKey(const Slice& _user_key, SequenceNumber s) {
size_t usize = _user_key.size();
size_t needed = usize + 13; // A conservative estimate
char* dst;
if (needed <= sizeof(space_)) {
dst = space_;
} else {
dst = new char[needed];
}
start_ = dst;
// NOTE: We don't support users keys of more than 2GB :)
dst = EncodeVarint32(dst, static_cast<uint32_t>(usize + 8));
kstart_ = dst;
memcpy(dst, _user_key.data(), usize);
dst += usize;
EncodeFixed64(dst, PackSequenceAndType(s, kValueTypeForSeek));
dst += 8;
end_ = dst;
}
} // namespace rocksdb
<commit_msg>Replace %llu with format macros in ParsedInternalKey::DebugString())<commit_after>// Copyright (c) 2013, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "db/dbformat.h"
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include <inttypes.h>
#include <stdio.h>
#include "port/port.h"
#include "util/coding.h"
#include "util/perf_context_imp.h"
namespace rocksdb {
uint64_t PackSequenceAndType(uint64_t seq, ValueType t) {
assert(seq <= kMaxSequenceNumber);
assert(t <= kValueTypeForSeek);
return (seq << 8) | t;
}
void UnPackSequenceAndType(uint64_t packed, uint64_t* seq, ValueType* t) {
*seq = packed >> 8;
*t = static_cast<ValueType>(packed & 0xff);
assert(*seq <= kMaxSequenceNumber);
assert(*t <= kValueTypeForSeek);
}
void AppendInternalKey(std::string* result, const ParsedInternalKey& key) {
result->append(key.user_key.data(), key.user_key.size());
PutFixed64(result, PackSequenceAndType(key.sequence, key.type));
}
std::string ParsedInternalKey::DebugString(bool hex) const {
char buf[50];
snprintf(buf, sizeof(buf), "' @ %" PRIu64 ": %d", sequence,
static_cast<int>(type));
std::string result = "'";
result += user_key.ToString(hex);
result += buf;
return result;
}
std::string InternalKey::DebugString(bool hex) const {
std::string result;
ParsedInternalKey parsed;
if (ParseInternalKey(rep_, &parsed)) {
result = parsed.DebugString(hex);
} else {
result = "(bad)";
result.append(EscapeString(rep_));
}
return result;
}
const char* InternalKeyComparator::Name() const {
return name_.c_str();
}
int InternalKeyComparator::Compare(const Slice& akey, const Slice& bkey) const {
// Order by:
// increasing user key (according to user-supplied comparator)
// decreasing sequence number
// decreasing type (though sequence# should be enough to disambiguate)
int r = user_comparator_->Compare(ExtractUserKey(akey), ExtractUserKey(bkey));
PERF_COUNTER_ADD(user_key_comparison_count, 1);
if (r == 0) {
const uint64_t anum = DecodeFixed64(akey.data() + akey.size() - 8);
const uint64_t bnum = DecodeFixed64(bkey.data() + bkey.size() - 8);
if (anum > bnum) {
r = -1;
} else if (anum < bnum) {
r = +1;
}
}
return r;
}
int InternalKeyComparator::Compare(const ParsedInternalKey& a,
const ParsedInternalKey& b) const {
// Order by:
// increasing user key (according to user-supplied comparator)
// decreasing sequence number
// decreasing type (though sequence# should be enough to disambiguate)
int r = user_comparator_->Compare(a.user_key, b.user_key);
PERF_COUNTER_ADD(user_key_comparison_count, 1);
if (r == 0) {
if (a.sequence > b.sequence) {
r = -1;
} else if (a.sequence < b.sequence) {
r = +1;
} else if (a.type > b.type) {
r = -1;
} else if (a.type < b.type) {
r = +1;
}
}
return r;
}
void InternalKeyComparator::FindShortestSeparator(
std::string* start,
const Slice& limit) const {
// Attempt to shorten the user portion of the key
Slice user_start = ExtractUserKey(*start);
Slice user_limit = ExtractUserKey(limit);
std::string tmp(user_start.data(), user_start.size());
user_comparator_->FindShortestSeparator(&tmp, user_limit);
if (tmp.size() < user_start.size() &&
user_comparator_->Compare(user_start, tmp) < 0) {
// User key has become shorter physically, but larger logically.
// Tack on the earliest possible number to the shortened user key.
PutFixed64(&tmp, PackSequenceAndType(kMaxSequenceNumber,kValueTypeForSeek));
assert(this->Compare(*start, tmp) < 0);
assert(this->Compare(tmp, limit) < 0);
start->swap(tmp);
}
}
void InternalKeyComparator::FindShortSuccessor(std::string* key) const {
Slice user_key = ExtractUserKey(*key);
std::string tmp(user_key.data(), user_key.size());
user_comparator_->FindShortSuccessor(&tmp);
if (tmp.size() < user_key.size() &&
user_comparator_->Compare(user_key, tmp) < 0) {
// User key has become shorter physically, but larger logically.
// Tack on the earliest possible number to the shortened user key.
PutFixed64(&tmp, PackSequenceAndType(kMaxSequenceNumber,kValueTypeForSeek));
assert(this->Compare(*key, tmp) < 0);
key->swap(tmp);
}
}
LookupKey::LookupKey(const Slice& _user_key, SequenceNumber s) {
size_t usize = _user_key.size();
size_t needed = usize + 13; // A conservative estimate
char* dst;
if (needed <= sizeof(space_)) {
dst = space_;
} else {
dst = new char[needed];
}
start_ = dst;
// NOTE: We don't support users keys of more than 2GB :)
dst = EncodeVarint32(dst, static_cast<uint32_t>(usize + 8));
kstart_ = dst;
memcpy(dst, _user_key.data(), usize);
dst += usize;
EncodeFixed64(dst, PackSequenceAndType(s, kValueTypeForSeek));
dst += 8;
end_ = dst;
}
} // namespace rocksdb
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkTestingObjectFactory.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyrgight notice for more information.
=========================================================================*/
#ifndef __vtkTestingObjectFactory_h
#define __vtkTestingObjectFactory_h
// .NAME vtkTestingObjectFactory - Object overrides used during testing
// .SECTION Description
// Some vtk examples and tests need to perform differently when they
// are run as tests versus when they are run as individual
// programs. Many tests/examples are interactive and eventually call
// vtkRenderWindowInteration::Start() to initialie the
// interaction. But, when run as tests, these programs should
// exit. This factory overrides vtkRenderWindowInteractor so that the
// Start() method just returns.
// To use this factory:
// \code
// #include "vtkTestingObjectFactory.h"
// vtkTestingObjectFactory* factory = vtkTestingObjectFactory::New();
// vtkObjectFactory::RegisterFactory(factory);
// \endcode
#include "vtkVersion.h"
#include "vtkObjectFactory.h"
#include "vtkTesting.h" // Required for testing framework
#include "vtkTestDriver.h" // Required for testing framework
#include "vtkTestingInteractor.h" // Required for testing framework
#include "vtkSmartPointer.h" // Required for testing framework
#include "vtkObjectFactoryCollection.h" // Required for testing framework
#if VTK_MAJOR_VERSION <= 5
class VTK_RENDERING_EXPORT vtkTestingObjectFactory : public vtkObjectFactory
#else
#include "vtkTestingRenderingModule.h" // For export macro
class VTKTESTINGRENDERING_EXPORT vtkTestingObjectFactory : public vtkObjectFactory
#endif
{
public:
#ifndef VTK_OVERRIDE
#define VTK_OVERRIDE
#endif
static vtkTestingObjectFactory* New();
vtkTypeMacro(vtkTestingObjectFactory,vtkObjectFactory);
virtual const char* GetVTKSourceVersion() VTK_OVERRIDE;
const char* GetDescription() VTK_OVERRIDE { return "Factory for overrides during testing"; }
void PrintSelf(ostream& os, vtkIndent indent) VTK_OVERRIDE;
protected:
// Description:
// Register objects that override vtk objects whem they are run as tests.
vtkTestingObjectFactory();
private:
vtkTestingObjectFactory(const vtkTestingObjectFactory&); // Not implemented
void operator=(const vtkTestingObjectFactory&); // Not implemented
};
#endif
<commit_msg>STYLE: vtkTestingObjectFactory: Fix typo in comment<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkTestingObjectFactory.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyrgight notice for more information.
=========================================================================*/
#ifndef __vtkTestingObjectFactory_h
#define __vtkTestingObjectFactory_h
// .NAME vtkTestingObjectFactory - Object overrides used during testing
// .SECTION Description
// Some vtk examples and tests need to perform differently when they
// are run as tests versus when they are run as individual
// programs. Many tests/examples are interactive and eventually call
// vtkRenderWindowInteration::Start() to initialize the
// interaction. But, when run as tests, these programs should
// exit. This factory overrides vtkRenderWindowInteractor so that the
// Start() method just returns.
// To use this factory:
// \code
// #include "vtkTestingObjectFactory.h"
// vtkTestingObjectFactory* factory = vtkTestingObjectFactory::New();
// vtkObjectFactory::RegisterFactory(factory);
// \endcode
#include "vtkVersion.h"
#include "vtkObjectFactory.h"
#include "vtkTesting.h" // Required for testing framework
#include "vtkTestDriver.h" // Required for testing framework
#include "vtkTestingInteractor.h" // Required for testing framework
#include "vtkSmartPointer.h" // Required for testing framework
#include "vtkObjectFactoryCollection.h" // Required for testing framework
#if VTK_MAJOR_VERSION <= 5
class VTK_RENDERING_EXPORT vtkTestingObjectFactory : public vtkObjectFactory
#else
#include "vtkTestingRenderingModule.h" // For export macro
class VTKTESTINGRENDERING_EXPORT vtkTestingObjectFactory : public vtkObjectFactory
#endif
{
public:
#ifndef VTK_OVERRIDE
#define VTK_OVERRIDE
#endif
static vtkTestingObjectFactory* New();
vtkTypeMacro(vtkTestingObjectFactory,vtkObjectFactory);
virtual const char* GetVTKSourceVersion() VTK_OVERRIDE;
const char* GetDescription() VTK_OVERRIDE { return "Factory for overrides during testing"; }
void PrintSelf(ostream& os, vtkIndent indent) VTK_OVERRIDE;
protected:
// Description:
// Register objects that override vtk objects whem they are run as tests.
vtkTestingObjectFactory();
private:
vtkTestingObjectFactory(const vtkTestingObjectFactory&); // Not implemented
void operator=(const vtkTestingObjectFactory&); // Not implemented
};
#endif
<|endoftext|>
|
<commit_before>// $Id$
//
// Task to setup emcal related global objects.
//
// Author: C.Loizides
#include "AliEmcalSetupTask.h"
#include <TClonesArray.h>
#include <TGeoGlobalMagField.h>
#include <TGeoManager.h>
#include "AliAODEvent.h"
#include "AliAnalysisManager.h"
#include "AliCDBManager.h"
#include "AliEMCALGeometry.h"
#include "AliESDEvent.h"
#include "AliGeomManager.h"
#include "AliMagF.h"
#include "AliOADBContainer.h"
ClassImp(AliEmcalSetupTask)
//________________________________________________________________________
AliEmcalSetupTask::AliEmcalSetupTask() :
AliAnalysisTaskSE(),
fOcdbPath(),
fOadbPath("$ALICE_ROOT/OADB/EMCAL"),
fGeoPath("."),
fIsInit(kFALSE)
{
// Constructor.
}
//________________________________________________________________________
AliEmcalSetupTask::AliEmcalSetupTask(const char *name) :
AliAnalysisTaskSE(name),
fOcdbPath(),
fOadbPath("$ALICE_ROOT/OADB/EMCAL"),
fGeoPath("$ALICE_ROOT/OADB/EMCAL"),
fIsInit(kFALSE)
{
// Constructor.
fBranchNames = "ESD:AliESDHeader.,AliESDRun.";
}
//________________________________________________________________________
AliEmcalSetupTask::~AliEmcalSetupTask()
{
// Destructor.
}
//________________________________________________________________________
void AliEmcalSetupTask::UserExec(Option_t *)
{
// Main loop, called for each event.
if (fIsInit)
return;
AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();
if (!am) {
AliError("Manager zero, returning");
return;
}
am->LoadBranch("AliESDRun.");
am->LoadBranch("AliESDHeader.");
Int_t runno = InputEvent()->GetRunNumber();
TString geoname("EMCAL_COMPLETE12SMV1");
Int_t year = 2013;
if (runno<=139517) {
year = 2010;
geoname = "EMCAL_FIRSTYEARV1";
} else if ((runno>139517) && (runno<=170593)) {
year = 2011;
geoname = "EMCAL_COMPLETEV1";
} else if ((runno>170593) && (runno<=193766)) {
year = 2012;
}
AliEMCALGeometry *geom = AliEMCALGeometry::GetInstance(geoname);
if (!geom) {
AliFatal(Form("Can not create geometry: %s",geoname.Data()));
return;
}
AliCDBManager *man = 0;
if (fOcdbPath.Length()>0) {
AliInfo(Form("Setting up OCDB"));
man = AliCDBManager::Instance();
man->SetDefaultStorage(fOcdbPath);
man->SetRun(runno);
}
TGeoManager *geo = AliGeomManager::GetGeometry();
if (!geo) {
TString fname(gSystem->ExpandPathName(Form("%s/geometry_%d.root", fGeoPath.Data(), year)));
if (gSystem->AccessPathName(fname)==0) {
AliInfo(Form("Loading geometry from %s", fname.Data()));
AliGeomManager::LoadGeometry(fname);
} else if (man) {
AliInfo(Form("Loading geometry from OCDB"));
AliGeomManager::LoadGeometry();
}
}
if (geo) {
AliGeomManager::ApplyAlignObjsFromCDB("EMCAL");
AliInfo(Form("Locking geometry"));
geo->LockGeometry();
}
if (!TGeoGlobalMagField::Instance()->GetField()) { // construct field map
InputEvent()->InitMagneticField();
}
if (fOadbPath.Length()>0) {
AliOADBContainer emcalgeoCont(Form("emcal"));
emcalgeoCont.InitFromFile(Form("%s/EMCALlocal2master.root",fOadbPath.Data()),
Form("AliEMCALgeo"));
TObjArray *mobj=dynamic_cast<TObjArray*>(emcalgeoCont.GetObject(runno,"EmcalMatrices"));
if (mobj) {
for(Int_t mod=0; mod < (geom->GetEMCGeometry())->GetNumberOfSuperModules(); mod++){
//AliInfo(Form("Misalignment matrix %d", mod));
geom->SetMisalMatrix((TGeoHMatrix*) mobj->At(mod),mod);
}
}
}
fIsInit = kTRUE;
}
<commit_msg>Apply alignment consistently<commit_after>// $Id$
//
// Task to setup emcal related global objects.
//
// Author: C.Loizides
#include "AliEmcalSetupTask.h"
#include <TClonesArray.h>
#include <TGeoGlobalMagField.h>
#include <TGeoManager.h>
#include "AliAODEvent.h"
#include "AliAnalysisManager.h"
#include "AliCDBManager.h"
#include "AliEMCALGeometry.h"
#include "AliESDEvent.h"
#include "AliGeomManager.h"
#include "AliMagF.h"
#include "AliOADBContainer.h"
ClassImp(AliEmcalSetupTask)
//________________________________________________________________________
AliEmcalSetupTask::AliEmcalSetupTask() :
AliAnalysisTaskSE(),
fOcdbPath(),
fOadbPath("$ALICE_ROOT/OADB/EMCAL"),
fGeoPath("."),
fIsInit(kFALSE)
{
// Constructor.
}
//________________________________________________________________________
AliEmcalSetupTask::AliEmcalSetupTask(const char *name) :
AliAnalysisTaskSE(name),
fOcdbPath(),
fOadbPath("$ALICE_ROOT/OADB/EMCAL"),
fGeoPath("$ALICE_ROOT/OADB/EMCAL"),
fIsInit(kFALSE)
{
// Constructor.
fBranchNames = "ESD:AliESDHeader.,AliESDRun.";
}
//________________________________________________________________________
AliEmcalSetupTask::~AliEmcalSetupTask()
{
// Destructor.
}
//________________________________________________________________________
void AliEmcalSetupTask::UserExec(Option_t *)
{
// Main loop, called for each event.
if (fIsInit)
return;
AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();
if (!am) {
AliError("Manager zero, returning");
return;
}
am->LoadBranch("AliESDRun.");
am->LoadBranch("AliESDHeader.");
Int_t runno = InputEvent()->GetRunNumber();
TString geoname("EMCAL_COMPLETE12SMV1");
Int_t year = 2013;
if (runno<=139517) {
year = 2010;
geoname = "EMCAL_FIRSTYEARV1";
} else if ((runno>139517) && (runno<=170593)) {
year = 2011;
geoname = "EMCAL_COMPLETEV1";
} else if ((runno>170593) && (runno<=193766)) {
year = 2012;
}
AliEMCALGeometry *geom = AliEMCALGeometry::GetInstance(geoname);
if (!geom) {
AliFatal(Form("Can not create geometry: %s",geoname.Data()));
return;
}
AliCDBManager *man = 0;
if (fOcdbPath.Length()>0) {
AliInfo(Form("Setting up OCDB"));
man = AliCDBManager::Instance();
if (!man->IsDefaultStorageSet())
man->SetDefaultStorage(fOcdbPath);
if (man->GetRun()!=runno)
man->SetRun(runno);
}
TGeoManager *geo = AliGeomManager::GetGeometry();
if (!geo) {
TString fname(gSystem->ExpandPathName(Form("%s/geometry_%d.root", fGeoPath.Data(), year)));
if (gSystem->AccessPathName(fname)==0) {
AliInfo(Form("Loading geometry from %s", fname.Data()));
AliGeomManager::LoadGeometry(fname);
} else if (man) {
AliInfo(Form("Loading geometry from OCDB"));
AliGeomManager::LoadGeometry();
}
geo = AliGeomManager::GetGeometry();
}
if (geo) {
AliGeomManager::ApplyAlignObjsFromCDB("EMCAL");
AliInfo(Form("Locking geometry"));
geo->LockGeometry();
}
if (!TGeoGlobalMagField::Instance()->GetField()) { // construct field map
InputEvent()->InitMagneticField();
}
if (fOadbPath.Length()>0) {
AliOADBContainer emcalgeoCont(Form("emcal"));
emcalgeoCont.InitFromFile(Form("%s/EMCALlocal2master.root",fOadbPath.Data()),
Form("AliEMCALgeo"));
TObjArray *mobj=dynamic_cast<TObjArray*>(emcalgeoCont.GetObject(runno,"EmcalMatrices"));
if (mobj) {
for(Int_t mod=0; mod < (geom->GetEMCGeometry())->GetNumberOfSuperModules(); mod++){
//AliInfo(Form("Misalignment matrix %d", mod));
geom->SetMisalMatrix((TGeoHMatrix*) mobj->At(mod),mod);
}
}
}
fIsInit = kTRUE;
}
<|endoftext|>
|
<commit_before>#if ! defined (__CINT__) || defined (__MAKECINT__)
#include "AliLog.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"
#include "PWG1/TRD/AliTRDinfoGen.h"
#include "PWG1/TRD/AliTRDpwg1Helper.h"
#include "PWG1/TRD/info/AliTRDeventInfo.h"
#endif
void AddTRDinfoGen(AliAnalysisManager *mgr, Int_t /*map*/, AliAnalysisDataContainer **/*ci*/, AliAnalysisDataContainer **co)
{
Bool_t mc=mgr->GetMCtruthEventHandler();
//AliLog::SetClassDebugLevel("AliTRDinfoGen", 2);
AliTRDinfoGen *info(NULL);
mgr->AddTask(info = new AliTRDinfoGen((char*)"TRDinfoGen"));
info->SetDebugLevel(0);
info->SetMCdata(mc);
info->SetLocalTrkSelection();
info->SetOCDB("alien://folder=/alice/data/2010/OCDB");
// settings for collisions
info->SetCollision(/*kFALSE*/);
if(info->IsCollision()){
if(!mc) info->SetTrigger(
"CINT1B-ABCE-NOPF-ALL"
" CINT5-B-NOPF-ALL"
" CINT1WU-B-NOPF-ALL"
" CINT5WU-B-NOPF-ALL"
" CSCO1-ABCE-NOPF-CENT" // cosmic SPD trigger
);
info->SetLocalEvSelection();
}
// Connect IO slots
mgr->ConnectInput (info, 0, mgr->GetCommonInputContainer());
co[AliTRDpwg1Helper::kEventInfo] = mgr->CreateContainer("eventInfo", AliTRDeventInfo::Class(), AliAnalysisManager::kExchangeContainer);
co[AliTRDpwg1Helper::kTracksBarrel] = mgr->CreateContainer("tracksBarrel", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
co[AliTRDpwg1Helper::kTracksSA] = mgr->CreateContainer("tracksSA", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
co[AliTRDpwg1Helper::kTracksKink] = mgr->CreateContainer("tracksKink", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
co[AliTRDpwg1Helper::kV0List] = mgr->CreateContainer("v0List", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
for(Int_t ios(1);ios<AliTRDpwg1Helper::kNOutSlots-1;ios++) mgr->ConnectOutput(info, ios, co[ios]);
// add last monitor container
AliAnalysisDataContainer *mon=mgr->CreateContainer(info->GetName(), TObjArray::Class(), AliAnalysisManager::kOutputContainer, Form("%s:TRD_Performance",mgr->GetCommonFileName()));
mgr->ConnectOutput(info, AliTRDpwg1Helper::kNOutSlots-1, mon);
}
<commit_msg>switch off triggers (Markus Fasel)<commit_after>#if ! defined (__CINT__) || defined (__MAKECINT__)
#include "AliLog.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"
#include "PWG1/TRD/AliTRDinfoGen.h"
#include "PWG1/TRD/AliTRDpwg1Helper.h"
#include "PWG1/TRD/info/AliTRDeventInfo.h"
#endif
void AddTRDinfoGen(AliAnalysisManager *mgr, Int_t /*map*/, AliAnalysisDataContainer **/*ci*/, AliAnalysisDataContainer **co)
{
Bool_t mc=mgr->GetMCtruthEventHandler();
//AliLog::SetClassDebugLevel("AliTRDinfoGen", 2);
AliTRDinfoGen *info(NULL);
mgr->AddTask(info = new AliTRDinfoGen((char*)"TRDinfoGen"));
info->SetDebugLevel(0);
info->SetMCdata(mc);
info->SetLocalTrkSelection();
info->SetOCDB("alien://folder=/alice/data/2010/OCDB");
// settings for collisions
info->SetCollision(/*kFALSE*/);
if(info->IsCollision()){
/*
if(!mc) info->SetTrigger(
"CINT1B-ABCE-NOPF-ALL"
" CINT5-B-NOPF-ALL"
" CINT1WU-B-NOPF-ALL"
" CINT5WU-B-NOPF-ALL"
" CSCO1-ABCE-NOPF-CENT" // cosmic SPD trigger
);
*/
info->SetLocalEvSelection();
}
// Connect IO slots
mgr->ConnectInput (info, 0, mgr->GetCommonInputContainer());
co[AliTRDpwg1Helper::kEventInfo] = mgr->CreateContainer("eventInfo", AliTRDeventInfo::Class(), AliAnalysisManager::kExchangeContainer);
co[AliTRDpwg1Helper::kTracksBarrel] = mgr->CreateContainer("tracksBarrel", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
co[AliTRDpwg1Helper::kTracksSA] = mgr->CreateContainer("tracksSA", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
co[AliTRDpwg1Helper::kTracksKink] = mgr->CreateContainer("tracksKink", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
co[AliTRDpwg1Helper::kV0List] = mgr->CreateContainer("v0List", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
for(Int_t ios(1);ios<AliTRDpwg1Helper::kNOutSlots-1;ios++) mgr->ConnectOutput(info, ios, co[ios]);
// add last monitor container
AliAnalysisDataContainer *mon=mgr->CreateContainer(info->GetName(), TObjArray::Class(), AliAnalysisManager::kOutputContainer, Form("%s:TRD_Performance",mgr->GetCommonFileName()));
mgr->ConnectOutput(info, AliTRDpwg1Helper::kNOutSlots-1, mon);
}
<|endoftext|>
|
<commit_before>#ifndef NKLIB_MAKE_UNIQUE_HPP__
#define NKLIB_MAKE_UNIQUE_HPP__
// STL's implementation from N3656. Part of C++14.
#include <memory>
#include <type_traits>
#include <utility>
namespace nk {
template <typename T, typename... Args>
std::unique_ptr<T> make_unique_helper(std::false_type, Args&&... args)
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
template <typename T, typename... Args>
std::unique_ptr<T> make_unique_helper(std::true_type, Args&&... args)
{
static_assert(std::extent<T>::value == 0,
"make_unique<T[N]>() is forbidden, please use make_unique<T[]>().");
typedef typename std::remove_extent<T>::type U;
return std::unique_ptr<T>(new U[sizeof...(Args)]{std::forward<Args>(args)...});
}
template <typename T, typename... Args> std::unique_ptr<T>
make_unique(Args&&... args)
{
return make_unique_helper<T>(std::is_array<T>(), std::forward<Args>(args)...);
}
}
#endif /* NKLIB_MAKE_UNIQUE_HPP__ */
<commit_msg>Remove make_unique.hpp; it's integrated in C++14 stdlib.<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright 2014 Milian Wolff <mail@milianw.de>
*
* This program 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 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.
*/
#include <cstdio>
#include <cassert>
#include <cstring>
#include <cstdlib>
#include <atomic>
#include <mutex>
#include <unordered_map>
#include <string>
#include <vector>
#include <algorithm>
#include <tuple>
#include <boost/functional/hash.hpp>
#include <dlfcn.h>
#include <unistd.h>
#include <link.h>
#define UNW_LOCAL_ONLY
#include <libunwind.h>
using namespace std;
using Trace = vector<unw_word_t>;
namespace std {
template<>
struct hash<Trace>
{
size_t operator() (const Trace& trace) const
{
size_t seed = 0;
for (auto ip : trace) {
boost::hash_combine(seed, ip);
}
boost::hash_combine(seed, trace.size());
return seed;
}
};
}
namespace {
using malloc_t = void* (*) (size_t);
using free_t = void (*) (void*);
using realloc_t = void* (*) (void*, size_t);
using calloc_t = void* (*) (size_t, size_t);
using posix_memalign_t = int (*) (void **, size_t, size_t);
using valloc_t = void* (*) (size_t);
using aligned_alloc_t = void* (*) (size_t, size_t);
using dlopen_t = void* (*) (const char*, int);
malloc_t real_malloc = nullptr;
free_t real_free = nullptr;
realloc_t real_realloc = nullptr;
calloc_t real_calloc = nullptr;
posix_memalign_t real_posix_memalign = nullptr;
valloc_t real_valloc = nullptr;
aligned_alloc_t real_aligned_alloc = nullptr;
dlopen_t real_dlopen = nullptr;
// threadsafe stuff
atomic<bool> moduleCacheDirty(true);
thread_local Trace traceBuffer;
void trace(const int skip = 2)
{
traceBuffer.clear();
const size_t MAX_TRACE_SIZE = 64;
traceBuffer.reserve(MAX_TRACE_SIZE);
unw_context_t uc;
unw_getcontext (&uc);
unw_cursor_t cursor;
unw_init_local (&cursor, &uc);
// skip functions we are not interested in
for (int i = 0; i < skip; ++i) {
if (unw_step(&cursor) <= 0) {
return;
}
}
while (unw_step(&cursor) > 0 && traceBuffer.size() < MAX_TRACE_SIZE) {
unw_word_t ip;
unw_get_reg(&cursor, UNW_REG_IP, &ip);
if (!ip) {
// this seems to happen regularly at the end of every trace and is useless to us
// not also useless, its also quite slow to continue here into libunwind
// I'll report this upstream.
break;
}
traceBuffer.push_back(ip);
}
}
struct HandleGuard
{
HandleGuard()
: wasLocked(inHandler)
{
inHandler = true;
}
~HandleGuard()
{
inHandler = wasLocked;
}
const bool wasLocked;
static thread_local bool inHandler;
};
thread_local bool HandleGuard::inHandler = false;
string env(const char* variable)
{
const char* value = getenv(variable);
return value ? string(value) : string();
}
struct Module
{
string fileName;
uintptr_t baseAddress;
uint32_t size;
unsigned int id;
bool isExe;
bool operator<(const Module& module) const
{
return make_tuple(baseAddress, size, fileName) < make_tuple(module.baseAddress, module.size, module.fileName);
}
bool operator!=(const Module& module) const
{
return make_tuple(baseAddress, size, fileName) != make_tuple(module.baseAddress, module.size, module.fileName);
}
};
struct Data
{
Data()
{
modules.reserve(32);
ipCache.reserve(65536);
traceCache.reserve(16384);
allocationInfo.reserve(16384);
string outputFileName = env("DUMP_MALLOC_TRACE_OUTPUT") + to_string(getpid());
out = fopen(outputFileName.c_str(), "wa");
if (!out) {
fprintf(stderr, "Failed to open output file: %s\n", outputFileName.c_str());
exit(1);
}
unsetenv("DUMP_MALLOC_TRACE_OUTPUT");
unsetenv("LD_PRELOAD");
}
~Data()
{
HandleGuard::inHandler = true;
fclose(out);
}
void updateModuleCache()
{
// check list of loaded modules for unknown ones
dl_iterate_phdr(dlopen_notify_callback, this);
moduleCacheDirty = false;
}
/**
* Mostly copied from vogl's src/libbacktrace/btrace.cpp
*/
static int dlopen_notify_callback(struct dl_phdr_info *info, size_t /*size*/, void *_data)
{
auto data = reinterpret_cast<Data*>(_data);
auto& modules = data->modules;
bool isExe = false;
const char *fileName = info->dlpi_name;
const int BUF_SIZE = 1024;
char buf[BUF_SIZE];
// If we don't have a filename and we haven't added our main exe yet, do it now.
if (!fileName || !fileName[0]) {
if (modules.empty()) {
isExe = true;
ssize_t ret = readlink("/proc/self/exe", buf, sizeof(buf));
if ((ret > 0) && (ret < (ssize_t)sizeof(buf))) {
buf[ret] = 0;
fileName = buf;
}
}
if (!fileName || !fileName[0]) {
return 0;
}
}
uintptr_t addressStart = 0;
uintptr_t addressEnd = 0;
for (int i = 0; i < info->dlpi_phnum; i++) {
if (info->dlpi_phdr[i].p_type == PT_LOAD) {
if (addressEnd == 0) {
addressStart = info->dlpi_addr + info->dlpi_phdr[i].p_vaddr;
addressEnd = addressStart + info->dlpi_phdr[i].p_memsz;
} else {
uintptr_t addr = info->dlpi_addr + info->dlpi_phdr[i].p_vaddr + info->dlpi_phdr[i].p_memsz;
if (addr > addressEnd) {
addressEnd = addr;
}
}
}
}
Module module{fileName, addressStart, static_cast<uint32_t>(addressEnd - addressStart), 0, isExe};
auto it = lower_bound(modules.begin(), modules.end(), module);
if (it == modules.end() || *it != module) {
module.id = data->next_module_id++;
fprintf(data->out, "m %u %s %lx %d\n", module.id, module.fileName.c_str(), module.baseAddress, module.isExe);
modules.insert(it, module);
}
return 0;
}
void handleMalloc(void* ptr, size_t size)
{
trace();
lock_guard<mutex> lock(m_mutex);
if (moduleCacheDirty) {
updateModuleCache();
}
auto it = traceCache.find(traceBuffer);
if (it == traceCache.end()) {
// cache before converting
auto traceId = next_trace_id++;
it = traceCache.insert(it, {traceBuffer, traceId});
// ensure ip cache is up2date
for (auto& ip : traceBuffer) {
auto ipIt = ipCache.find(ip);
if (ipIt == ipCache.end()) {
// find module and offset from cache
auto module = lower_bound(modules.begin(), modules.end(), ip,
[] (const Module& module, const unw_word_t addr) -> bool {
return module.baseAddress + module.size < addr;
});
if (module == modules.end()) {
ip = numeric_limits<unsigned int>::max();
continue;
}
auto ipId = next_ipCache_id++;
fprintf(out, "i %u %u %lx\n", ipId, module->id, ip - module->baseAddress);
ipIt = ipCache.insert(ipIt, {ip, ipId});
}
ip = ipIt->second;
}
// print trace
fprintf(out, "t %u ", traceId);
for (auto ipId : traceBuffer) {
if (ipId == numeric_limits<unsigned int>::max()) {
continue;
}
fprintf(out, "%lu ", ipId);
}
fputc('\n', out);
}
allocationInfo[ptr] = {size, it->second};
fprintf(out, "+ %lu %u\n", size, it->second);
}
void handleFree(void* ptr)
{
lock_guard<mutex> lock(m_mutex);
auto it = allocationInfo.find(ptr);
if (it == allocationInfo.end()) {
return;
}
fprintf(out, "- %lu %u\n", it->second.size, it->second.traceId);
allocationInfo.erase(it);
}
mutex m_mutex;
unsigned int next_module_id = 0;
unsigned int next_thread_id = 0;
unsigned int next_ipCache_id = 0;
unsigned int next_trace_id = 0;
vector<Module> modules;
unordered_map<unw_word_t, unw_word_t> ipCache;
unordered_map<vector<unw_word_t>, unsigned int> traceCache;
struct AllocationInfo
{
size_t size;
unsigned int traceId;
};
unordered_map<void*, AllocationInfo> allocationInfo;
FILE* out = nullptr;
};
unique_ptr<Data> data;
template<typename T>
T findReal(const char* name)
{
auto ret = dlsym(RTLD_NEXT, name);
if (!ret) {
fprintf(stderr, "Could not find original function %s\n", name);
abort();
}
return reinterpret_cast<T>(ret);
}
/**
* Dummy implementation, since the call to dlsym from findReal triggers a call to calloc.
*
* This is only called at startup and will eventually be replaced by the "proper" calloc implementation.
*/
void* dummy_calloc(size_t num, size_t size)
{
const size_t MAX_SIZE = 1024;
static char* buf[MAX_SIZE];
static size_t offset = 0;
if (!offset) {
memset(buf, 0, MAX_SIZE);
}
size_t oldOffset = offset;
offset += num * size;
if (offset >= MAX_SIZE) {
fprintf(stderr, "failed to initialize, dummy calloc buf size exhausted: %lu requested, %lu available\n", offset, MAX_SIZE);
abort();
}
return buf + oldOffset;
}
void init()
{
if (data || HandleGuard::inHandler) {
fprintf(stderr, "initialization recursion detected\n");
abort();
}
HandleGuard guard;
real_calloc = &dummy_calloc;
real_calloc = findReal<calloc_t>("calloc");
real_dlopen = findReal<dlopen_t>("dlopen");
real_malloc = findReal<malloc_t>("malloc");
real_free = findReal<free_t>("free");
real_realloc = findReal<realloc_t>("realloc");
real_posix_memalign = findReal<posix_memalign_t>("posix_memalign");
real_valloc = findReal<valloc_t>("valloc");
real_aligned_alloc = findReal<aligned_alloc_t>("aligned_alloc");
data.reset(new Data);
}
}
extern "C" {
/// TODO: memalign, pvalloc, ...?
void* malloc(size_t size)
{
if (!real_malloc) {
init();
}
void* ret = real_malloc(size);
if (ret && !HandleGuard::inHandler) {
HandleGuard guard;
data->handleMalloc(ret, size);
}
return ret;
}
void free(void* ptr)
{
if (!real_free) {
init();
}
real_free(ptr);
if (ptr && !HandleGuard::inHandler) {
HandleGuard guard;
data->handleFree(ptr);
}
}
void* realloc(void* ptr, size_t size)
{
if (!real_realloc) {
init();
}
void* ret = real_realloc(ptr, size);
if (ret && !HandleGuard::inHandler) {
HandleGuard guard;
data->handleFree(ptr);
data->handleMalloc(ret, size);
}
return ret;
}
void* calloc(size_t num, size_t size)
{
if (!real_calloc) {
init();
}
void* ret = real_calloc(num, size);
if (ret && !HandleGuard::inHandler) {
HandleGuard guard;
data->handleMalloc(ret, num*size);
}
return ret;
}
int posix_memalign(void **memptr, size_t alignment, size_t size)
{
if (!real_posix_memalign) {
init();
}
int ret = real_posix_memalign(memptr, alignment, size);
if (ret && !HandleGuard::inHandler) {
HandleGuard guard;
data->handleMalloc(*memptr, size);
}
return ret;
}
void* aligned_alloc(size_t alignment, size_t size)
{
if (!real_aligned_alloc) {
init();
}
void* ret = real_aligned_alloc(alignment, size);
if (ret && !HandleGuard::inHandler) {
HandleGuard guard;
data->handleMalloc(ret, size);
}
return ret;
}
void* valloc(size_t size)
{
if (!real_valloc) {
init();
}
void* ret = real_valloc(size);
if (ret && !HandleGuard::inHandler) {
HandleGuard guard;
data->handleMalloc(ret, size);
}
return ret;
}
void *dlopen(const char *filename, int flag)
{
if (!real_dlopen) {
init();
}
void* ret = real_dlopen(filename, flag);
if (ret) {
moduleCacheDirty = true;
}
return ret;
}
}
<commit_msg>Use stack-allocated trace buffer.<commit_after>/*
* Copyright 2014 Milian Wolff <mail@milianw.de>
*
* This program 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 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.
*/
#include <cstdio>
#include <cassert>
#include <cstring>
#include <cstdlib>
#include <atomic>
#include <mutex>
#include <unordered_map>
#include <string>
#include <vector>
#include <algorithm>
#include <tuple>
#include <boost/functional/hash.hpp>
#include <dlfcn.h>
#include <unistd.h>
#include <link.h>
#define UNW_LOCAL_ONLY
#include <libunwind.h>
using namespace std;
const size_t MAX_TRACE_SIZE = 64;
struct Trace
{
void clear()
{
m_size = 0;
}
void push_back(unw_word_t ip)
{
m_data[m_size++] = ip;
}
const unw_word_t* begin() const
{
return m_data;
}
unw_word_t* begin()
{
return m_data;
}
const unw_word_t* end() const
{
return m_data + m_size;
}
unw_word_t* end()
{
return m_data + m_size;
}
size_t size() const
{
return m_size;
}
bool operator==(const Trace& o) const
{
return m_size == o.m_size && !memcmp(m_data, o.m_data, m_size * sizeof(unw_word_t));
}
private:
size_t m_size = 0;
unw_word_t m_data[MAX_TRACE_SIZE];
};
namespace std {
template<>
struct hash<Trace>
{
size_t operator() (const Trace& trace) const
{
size_t seed = 0;
for (auto ip : trace) {
boost::hash_combine(seed, ip);
}
boost::hash_combine(seed, trace.size());
return seed;
}
};
}
namespace {
using malloc_t = void* (*) (size_t);
using free_t = void (*) (void*);
using realloc_t = void* (*) (void*, size_t);
using calloc_t = void* (*) (size_t, size_t);
using posix_memalign_t = int (*) (void **, size_t, size_t);
using valloc_t = void* (*) (size_t);
using aligned_alloc_t = void* (*) (size_t, size_t);
using dlopen_t = void* (*) (const char*, int);
malloc_t real_malloc = nullptr;
free_t real_free = nullptr;
realloc_t real_realloc = nullptr;
calloc_t real_calloc = nullptr;
posix_memalign_t real_posix_memalign = nullptr;
valloc_t real_valloc = nullptr;
aligned_alloc_t real_aligned_alloc = nullptr;
dlopen_t real_dlopen = nullptr;
// threadsafe stuff
atomic<bool> moduleCacheDirty(true);
void trace(Trace& trace, const int skip = 2)
{
trace.clear();
unw_context_t uc;
unw_getcontext (&uc);
unw_cursor_t cursor;
unw_init_local (&cursor, &uc);
// skip functions we are not interested in
for (int i = 0; i < skip; ++i) {
if (unw_step(&cursor) <= 0) {
return;
}
}
while (unw_step(&cursor) > 0 && trace.size() < MAX_TRACE_SIZE) {
unw_word_t ip;
unw_get_reg(&cursor, UNW_REG_IP, &ip);
if (!ip) {
// this seems to happen regularly at the end of every trace and is useless to us
// not also useless, its also quite slow to continue here into libunwind
// I'll report this upstream.
break;
}
trace.push_back(ip);
}
}
struct HandleGuard
{
HandleGuard()
: wasLocked(inHandler)
{
inHandler = true;
}
~HandleGuard()
{
inHandler = wasLocked;
}
const bool wasLocked;
static thread_local bool inHandler;
};
thread_local bool HandleGuard::inHandler = false;
string env(const char* variable)
{
const char* value = getenv(variable);
return value ? string(value) : string();
}
struct Module
{
string fileName;
uintptr_t baseAddress;
uint32_t size;
unsigned int id;
bool isExe;
bool operator<(const Module& module) const
{
return make_tuple(baseAddress, size, fileName) < make_tuple(module.baseAddress, module.size, module.fileName);
}
bool operator!=(const Module& module) const
{
return make_tuple(baseAddress, size, fileName) != make_tuple(module.baseAddress, module.size, module.fileName);
}
};
struct Data
{
Data()
{
modules.reserve(32);
ipCache.reserve(65536);
traceCache.reserve(16384);
allocationInfo.reserve(16384);
string outputFileName = env("DUMP_MALLOC_TRACE_OUTPUT") + to_string(getpid());
out = fopen(outputFileName.c_str(), "wa");
if (!out) {
fprintf(stderr, "Failed to open output file: %s\n", outputFileName.c_str());
exit(1);
}
unsetenv("DUMP_MALLOC_TRACE_OUTPUT");
unsetenv("LD_PRELOAD");
}
~Data()
{
HandleGuard::inHandler = true;
fclose(out);
}
void updateModuleCache()
{
// check list of loaded modules for unknown ones
dl_iterate_phdr(dlopen_notify_callback, this);
moduleCacheDirty = false;
}
/**
* Mostly copied from vogl's src/libbacktrace/btrace.cpp
*/
static int dlopen_notify_callback(struct dl_phdr_info *info, size_t /*size*/, void *_data)
{
auto data = reinterpret_cast<Data*>(_data);
auto& modules = data->modules;
bool isExe = false;
const char *fileName = info->dlpi_name;
const int BUF_SIZE = 1024;
char buf[BUF_SIZE];
// If we don't have a filename and we haven't added our main exe yet, do it now.
if (!fileName || !fileName[0]) {
if (modules.empty()) {
isExe = true;
ssize_t ret = readlink("/proc/self/exe", buf, sizeof(buf));
if ((ret > 0) && (ret < (ssize_t)sizeof(buf))) {
buf[ret] = 0;
fileName = buf;
}
}
if (!fileName || !fileName[0]) {
return 0;
}
}
uintptr_t addressStart = 0;
uintptr_t addressEnd = 0;
for (int i = 0; i < info->dlpi_phnum; i++) {
if (info->dlpi_phdr[i].p_type == PT_LOAD) {
if (addressEnd == 0) {
addressStart = info->dlpi_addr + info->dlpi_phdr[i].p_vaddr;
addressEnd = addressStart + info->dlpi_phdr[i].p_memsz;
} else {
uintptr_t addr = info->dlpi_addr + info->dlpi_phdr[i].p_vaddr + info->dlpi_phdr[i].p_memsz;
if (addr > addressEnd) {
addressEnd = addr;
}
}
}
}
Module module{fileName, addressStart, static_cast<uint32_t>(addressEnd - addressStart), 0, isExe};
auto it = lower_bound(modules.begin(), modules.end(), module);
if (it == modules.end() || *it != module) {
module.id = data->next_module_id++;
fprintf(data->out, "m %u %s %lx %d\n", module.id, module.fileName.c_str(), module.baseAddress, module.isExe);
modules.insert(it, module);
}
return 0;
}
void handleMalloc(void* ptr, size_t size)
{
Trace traceBuffer;
trace(traceBuffer);
lock_guard<mutex> lock(m_mutex);
if (moduleCacheDirty) {
updateModuleCache();
}
auto it = traceCache.find(traceBuffer);
if (it == traceCache.end()) {
// cache before converting
auto traceId = next_trace_id++;
it = traceCache.insert(it, {traceBuffer, traceId});
// ensure ip cache is up2date
for (auto& ip : traceBuffer) {
auto ipIt = ipCache.find(ip);
if (ipIt == ipCache.end()) {
// find module and offset from cache
auto module = lower_bound(modules.begin(), modules.end(), ip,
[] (const Module& module, const unw_word_t addr) -> bool {
return module.baseAddress + module.size < addr;
});
if (module == modules.end()) {
ip = numeric_limits<unsigned int>::max();
continue;
}
auto ipId = next_ipCache_id++;
fprintf(out, "i %u %u %lx\n", ipId, module->id, ip - module->baseAddress);
ipIt = ipCache.insert(ipIt, {ip, ipId});
}
ip = ipIt->second;
}
// print trace
fprintf(out, "t %u ", traceId);
for (auto ipId : traceBuffer) {
if (ipId == numeric_limits<unsigned int>::max()) {
continue;
}
fprintf(out, "%lu ", ipId);
}
fputc('\n', out);
}
allocationInfo[ptr] = {size, it->second};
fprintf(out, "+ %lu %u\n", size, it->second);
}
void handleFree(void* ptr)
{
lock_guard<mutex> lock(m_mutex);
auto it = allocationInfo.find(ptr);
if (it == allocationInfo.end()) {
return;
}
fprintf(out, "- %lu %u\n", it->second.size, it->second.traceId);
allocationInfo.erase(it);
}
mutex m_mutex;
unsigned int next_module_id = 0;
unsigned int next_thread_id = 0;
unsigned int next_ipCache_id = 0;
unsigned int next_trace_id = 0;
vector<Module> modules;
unordered_map<unw_word_t, unw_word_t> ipCache;
unordered_map<Trace, unsigned int> traceCache;
struct AllocationInfo
{
size_t size;
unsigned int traceId;
};
unordered_map<void*, AllocationInfo> allocationInfo;
FILE* out = nullptr;
};
unique_ptr<Data> data;
template<typename T>
T findReal(const char* name)
{
auto ret = dlsym(RTLD_NEXT, name);
if (!ret) {
fprintf(stderr, "Could not find original function %s\n", name);
abort();
}
return reinterpret_cast<T>(ret);
}
/**
* Dummy implementation, since the call to dlsym from findReal triggers a call to calloc.
*
* This is only called at startup and will eventually be replaced by the "proper" calloc implementation.
*/
void* dummy_calloc(size_t num, size_t size)
{
const size_t MAX_SIZE = 1024;
static char* buf[MAX_SIZE];
static size_t offset = 0;
if (!offset) {
memset(buf, 0, MAX_SIZE);
}
size_t oldOffset = offset;
offset += num * size;
if (offset >= MAX_SIZE) {
fprintf(stderr, "failed to initialize, dummy calloc buf size exhausted: %lu requested, %lu available\n", offset, MAX_SIZE);
abort();
}
return buf + oldOffset;
}
void init()
{
if (data || HandleGuard::inHandler) {
fprintf(stderr, "initialization recursion detected\n");
abort();
}
HandleGuard guard;
real_calloc = &dummy_calloc;
real_calloc = findReal<calloc_t>("calloc");
real_dlopen = findReal<dlopen_t>("dlopen");
real_malloc = findReal<malloc_t>("malloc");
real_free = findReal<free_t>("free");
real_realloc = findReal<realloc_t>("realloc");
real_posix_memalign = findReal<posix_memalign_t>("posix_memalign");
real_valloc = findReal<valloc_t>("valloc");
real_aligned_alloc = findReal<aligned_alloc_t>("aligned_alloc");
data.reset(new Data);
}
}
extern "C" {
/// TODO: memalign, pvalloc, ...?
void* malloc(size_t size)
{
if (!real_malloc) {
init();
}
void* ret = real_malloc(size);
if (ret && !HandleGuard::inHandler) {
HandleGuard guard;
data->handleMalloc(ret, size);
}
return ret;
}
void free(void* ptr)
{
if (!real_free) {
init();
}
real_free(ptr);
if (ptr && !HandleGuard::inHandler) {
HandleGuard guard;
data->handleFree(ptr);
}
}
void* realloc(void* ptr, size_t size)
{
if (!real_realloc) {
init();
}
void* ret = real_realloc(ptr, size);
if (ret && !HandleGuard::inHandler) {
HandleGuard guard;
data->handleFree(ptr);
data->handleMalloc(ret, size);
}
return ret;
}
void* calloc(size_t num, size_t size)
{
if (!real_calloc) {
init();
}
void* ret = real_calloc(num, size);
if (ret && !HandleGuard::inHandler) {
HandleGuard guard;
data->handleMalloc(ret, num*size);
}
return ret;
}
int posix_memalign(void **memptr, size_t alignment, size_t size)
{
if (!real_posix_memalign) {
init();
}
int ret = real_posix_memalign(memptr, alignment, size);
if (ret && !HandleGuard::inHandler) {
HandleGuard guard;
data->handleMalloc(*memptr, size);
}
return ret;
}
void* aligned_alloc(size_t alignment, size_t size)
{
if (!real_aligned_alloc) {
init();
}
void* ret = real_aligned_alloc(alignment, size);
if (ret && !HandleGuard::inHandler) {
HandleGuard guard;
data->handleMalloc(ret, size);
}
return ret;
}
void* valloc(size_t size)
{
if (!real_valloc) {
init();
}
void* ret = real_valloc(size);
if (ret && !HandleGuard::inHandler) {
HandleGuard guard;
data->handleMalloc(ret, size);
}
return ret;
}
void *dlopen(const char *filename, int flag)
{
if (!real_dlopen) {
init();
}
void* ret = real_dlopen(filename, flag);
if (ret) {
moduleCacheDirty = true;
}
return ret;
}
}
<|endoftext|>
|
<commit_before>#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <d2d1.h>
#pragma comment(lib, "d2d1")
#include "../../../Nova/nova_geometry.h"
#include "../../../Nova/nova_render.h"
LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
// Direct 2D vars.
ID2D1Factory *pFactory = NULL;
ID2D1HwndRenderTarget *pRenderTarget = NULL;
ID2D1Bitmap *bm = NULL;
ID2D1SolidColorBrush *pBrush = NULL;
HRESULT CreateD2D(HWND hWnd);
void DestroyD2D();
// My vars.
Mesh *mesh;
Matrix pos, persp;
void draw_line_D2D(float x0, float y0, float x1, float y1)
{
D2D1_POINT_2F p0 = { x0, y0 };
D2D1_POINT_2F p1 = { x1, y1 };
pRenderTarget->DrawLine(p0, p1, pBrush);
}
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, LPWSTR pCmdLine, int nCmdShow)
{
// Register the window class.
WNDCLASS wc = { 0 };
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = L"Nova Window";
RegisterClass(&wc);
// Create the window.
HWND hWnd = CreateWindowEx(0, wc.lpszClassName, L"Nova", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 600, 600, NULL, NULL, hInstance, NULL);
if (hWnd == NULL)
return -1;
ShowWindow(hWnd, nCmdShow);
if (FAILED(D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &pFactory)))
return -1;
// Set up my stuff.
mesh = CreateMeshFromFile("../../../models/bunny-5000.obj");
if (!mesh)
MessageBox(NULL, L"ERROR", L"Unable to load mesh file!", MB_OK);
draw_line = draw_line_D2D;
MatSetTranslate(&pos, 0.0f, -0.1f, -0.3f);
// Run the message loop.
MSG msg = { 0 };
DWORD start = GetTickCount();
DWORD now;
int frame = 0;
wchar_t d[20];
while (msg.message != WM_QUIT)
{
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
InvalidateRect(hWnd, NULL, FALSE);
frame++;
now = GetTickCount();
if (now - start > 2000)
{
start = now;
_itow_s(frame / 2, d, 20, 10);
SetWindowText(hWnd, d);
frame = 0;
}
}
if (pFactory)
{
pFactory->Release();
pFactory = NULL;
}
DestroyD2D();
DestroyMesh(mesh);
return 0;
}
HRESULT CreateD2D(HWND hWnd)
{
HRESULT hr = S_OK;
if (pRenderTarget == NULL)
{
RECT rc;
GetClientRect(hWnd, &rc);
D2D1_SIZE_U size = D2D1::SizeU(rc.right, rc.bottom);
hr = pFactory->CreateHwndRenderTarget(D2D1::RenderTargetProperties(), D2D1::HwndRenderTargetProperties(hWnd, size, D2D1_PRESENT_OPTIONS_IMMEDIATELY), &pRenderTarget);
if (SUCCEEDED(hr))
{
const D2D1_COLOR_F color = D2D1::ColorF(0.0f, 0.0f, 0.0f);
hr = pRenderTarget->CreateSolidColorBrush(color, &pBrush);
}
}
return hr;
}
void DestroyD2D()
{
if (pRenderTarget)
{
pRenderTarget->Release();
pRenderTarget = NULL;
}
if (pBrush)
{
pBrush->Release();
pBrush = NULL;
}
}
LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_CREATE:
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_PAINT:
{
if (pRenderTarget == NULL)
{
CreateD2D(hWnd);
D2D1_PIXEL_FORMAT pf = pRenderTarget->GetPixelFormat();
float dpix, dpiy;
pRenderTarget->GetDpi(&dpix, &dpiy);
D2D1_BITMAP_PROPERTIES bmp = D2D1::BitmapProperties(pf, dpix, dpiy);
RECT rc;
GetClientRect(hWnd, &rc);
pRenderTarget->CreateBitmap(D2D1::SizeU(rc.right, rc.bottom), bmp, &bm);
}
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
pRenderTarget->BeginDraw();
clear_pixel_buffer();
clear_depth_buffer();
if (mesh != NULL)
RenderMesh(mesh, &pos);
RECT rc;
GetClientRect(hWnd, &rc);
D2D1_RECT_U rect = D2D1::RectU(0, 0, rc.right, rc.bottom);
uint32_t *src = get_pixel_buffer();
HRESULT hr = bm->CopyFromMemory(NULL, src, rc.right * sizeof(uint32_t));
pRenderTarget->DrawBitmap(bm);
hr = pRenderTarget->EndDraw();
if (FAILED(hr) || hr == D2DERR_RECREATE_TARGET)
DestroyD2D();
EndPaint(hWnd, &ps);
}
return 0;
case WM_SIZE:
RECT rc;
GetClientRect(hWnd, &rc);
if (pRenderTarget)
{
D2D1_SIZE_U size = D2D1::SizeU(rc.right, rc.bottom);
pRenderTarget->Resize(size);
InvalidateRect(hWnd, NULL, FALSE);
}
set_screen_size(rc.right, rc.bottom);
set_fov(60.0f);
return 0;
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
<commit_msg>Refactored support for Win32 window resizing<commit_after>#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <d2d1.h>
#pragma comment(lib, "d2d1")
#include "../../../Nova/nova_geometry.h"
#include "../../../Nova/nova_render.h"
LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
// Direct 2D vars.
ID2D1Factory *pFactory = NULL;
ID2D1HwndRenderTarget *pRenderTarget = NULL;
ID2D1Bitmap *bm = NULL;
HRESULT CreateD2D(HWND hWnd);
void DestroyD2D();
// My vars.
Mesh *mesh;
Matrix pos, persp;
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, LPWSTR pCmdLine, int nCmdShow)
{
// Register the window class.
WNDCLASS wc = { 0 };
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = L"Nova Window";
RegisterClass(&wc);
// Create the window.
HWND hWnd = CreateWindowEx(0, wc.lpszClassName, L"Nova", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 600, 600, NULL, NULL, hInstance, NULL);
if (hWnd == NULL)
return -1;
ShowWindow(hWnd, nCmdShow);
if (FAILED(D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &pFactory)))
return -1;
// Set up my stuff.
mesh = CreateMeshFromFile("../../../models/bunny-1500.obj");
if (!mesh)
MessageBox(NULL, L"ERROR", L"Unable to load mesh file!", MB_OK);
MatSetTranslate(&pos, 0.0f, -0.1f, -0.3f);
// Run the message loop.
MSG msg = { 0 };
DWORD start = GetTickCount();
DWORD now;
int frame = 0;
wchar_t d[20];
while (msg.message != WM_QUIT)
{
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
InvalidateRect(hWnd, NULL, FALSE);
frame++;
now = GetTickCount();
if (now - start > 2000)
{
start = now;
_itow_s(frame / 2, d, 20, 10);
SetWindowText(hWnd, d);
frame = 0;
}
}
if (pFactory)
{
pFactory->Release();
pFactory = NULL;
}
DestroyD2D();
DestroyMesh(mesh);
return 0;
}
HRESULT CreateD2D(HWND hWnd)
{
HRESULT hr = S_OK;
if (pRenderTarget == NULL)
{
RECT rc;
GetClientRect(hWnd, &rc);
D2D1_SIZE_U size = D2D1::SizeU(rc.right, rc.bottom);
hr = pFactory->CreateHwndRenderTarget(D2D1::RenderTargetProperties(), D2D1::HwndRenderTargetProperties(hWnd, size, D2D1_PRESENT_OPTIONS_IMMEDIATELY), &pRenderTarget);
if (SUCCEEDED(hr))
{
D2D1_PIXEL_FORMAT pf = pRenderTarget->GetPixelFormat();
D2D1_BITMAP_PROPERTIES bmp = D2D1::BitmapProperties(pf);
hr = pRenderTarget->CreateBitmap(pRenderTarget->GetPixelSize(), bmp, &bm);
}
}
return hr;
}
void DestroyD2D()
{
if (pRenderTarget != NULL)
{
pRenderTarget->Release();
pRenderTarget = NULL;
}
if (bm != NULL)
{
bm->Release();
bm = NULL;
}
}
LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_CREATE:
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_PAINT:
{
if (pRenderTarget == NULL)
{
CreateD2D(hWnd);
D2D1_PIXEL_FORMAT pf = pRenderTarget->GetPixelFormat();
float dpix, dpiy;
pRenderTarget->GetDpi(&dpix, &dpiy);
D2D1_BITMAP_PROPERTIES bmp = D2D1::BitmapProperties(pf, dpix, dpiy);
RECT rc;
GetClientRect(hWnd, &rc);
pRenderTarget->CreateBitmap(D2D1::SizeU(rc.right, rc.bottom), bmp, &bm);
}
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
pRenderTarget->BeginDraw();
clear_pixel_buffer();
clear_depth_buffer();
if (mesh != NULL)
RenderMesh(mesh, &pos);
RECT rc;
GetClientRect(hWnd, &rc);
D2D1_RECT_U rect = D2D1::RectU(0, 0, rc.right, rc.bottom);
uint32_t *src = get_pixel_buffer();
HRESULT hr = bm->CopyFromMemory(NULL, src, rc.right * sizeof(uint32_t));
pRenderTarget->DrawBitmap(bm);
hr = pRenderTarget->EndDraw();
if (hr == D2DERR_RECREATE_TARGET)
DestroyD2D();
EndPaint(hWnd, &ps);
}
return 0;
case WM_SIZE:
RECT rc;
GetClientRect(hWnd, &rc);
DestroyD2D();
set_screen_size(rc.right, rc.bottom);
set_fov(60.0f);
return 0;
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
<|endoftext|>
|
<commit_before>#include "include/vkalloc.h"<commit_msg>Define vka namespace<commit_after>#include "include/vkalloc.h"
#include <vector>
#include <unordered_map>
namespace vka {
struct Page {
VkDeviceMemory deviceMemory;
Node* head = nullptr;
};
struct Node {
Node* next = nullptr;
uint64_t offset;
uint64_t size;
};
VkPhysicalDevice physicalDevice;
VkDevice device;
VkPhysicalDeviceMemoryProperties properties;
std::unordered_map<VkDeviceMemory, int32_t> pageMap;
std::vector<Page> heaps[32]; //32 possible heaps
}
void vkaInit(VkPhysicalDevice physicalDevice, VkDevice device){
}
using namespace vka;
void vkaTerminate(){
}
VkAllocation vkAlloc(VkMemoryRequirements requirements){
}
void vkFree(VkAllocation allocation){
}
VkAllocation vkHostAlloc(VkMemoryRequirements requirements){
}
void vkHostFree(VkAllocation allocation){
}<|endoftext|>
|
<commit_before>
#include <string.h>
int main()
{
printf("Hello World!");
printf("Patrick");
printf("Simon")
return NULL;
}
<commit_msg>test provoke conflict<commit_after>
#include <string.h>
int main()
{
printf("Hello World!");
printf("Patrick");
printf("RIOT");
printf("Simon");
return NULL;
}
<|endoftext|>
|
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Alexander V. Astapchuk
* @version $Revision: $
*/
/**
* @file
* @brief Main decoding (disassembling) routines implementation.
*/
#include "dec_base.h"
#include "open/common.h"
bool DecoderBase::is_prefix(const unsigned char * bytes)
{
unsigned char b0 = *bytes;
unsigned char b1 = *(bytes+1);
if (b0 == 0xF0) { // LOCK
return true;
}
if (b0==0xF2 || b0==0xF3) { // REPNZ/REPZ prefixes
if (b1 == 0x0F) { // .... but may be a part of SIMD opcode
return false;
}
return true;
}
if (b0 == 0x2E || b0 == 0x36 || b0==0x3E || b0==0x26 || b0==0x64 || b0==0x3E) {
// branch hints, segment prefixes
return true;
}
if (b0==0x66) { // operand-size prefix
if (b1 == 0x0F) { // .... but may be a part of SIMD opcode
return false;
}
return false; //XXX - currently considered as part of opcode//true;
}
if (b0==0x67) { // address size prefix
return true;
}
return false;
}
unsigned DecoderBase::decode(const void * addr, Inst * pinst)
{
Inst tmp;
//assert( *(unsigned char*)addr != 0x66);
const unsigned char * bytes = (unsigned char*)addr;
// Check prefix first
for (unsigned i=0; i<4; i++) {
if (!is_prefix(bytes)) {
break;
}
++bytes;
}
if (is_prefix(bytes)) {
// More than 4 prefixes together ?
// assert(false);
return 0;
}
// Load up to 4 prefixes
// for each Mnemonic
// for each opcodedesc
// if (raw_len == 0) memcmp(, raw_len)
// else check the mixed state which is one of the following:
// /digit /i /rw /rd /rb
bool found = false;
const unsigned char * saveBytes = bytes;
for (unsigned mn=1; mn<Mnemonic_Count; mn++) {
bytes = saveBytes;
found=try_mn((Mnemonic)mn, &bytes, &tmp);
if (found) {
tmp.mn = (Mnemonic)mn;
break;
}
}
if (!found) {
// assert(false);
return 0;
}
tmp.size = (unsigned)(bytes-(const unsigned char*)addr);
if (pinst) {
*pinst = tmp;
}
return tmp.size;
}
#ifdef _EM64T_
#define EXTEND_REG(reg, flag) \
((NULL == rex || 0 == rex->flag) ? reg : (reg + 8))
#else
#define EXTEND_REG(reg, flag) (reg)
#endif
bool DecoderBase::decode_aux(const EncoderBase::OpcodeDesc& odesc, unsigned aux,
const unsigned char ** pbuf, Inst * pinst, const Rex UNREF *rex)
{
OpcodeByteKind kind = (OpcodeByteKind)(aux & OpcodeByteKind_KindMask);
unsigned byte = (aux & OpcodeByteKind_OpcodeMask);
unsigned data_byte = **pbuf;
EncoderBase::Operand& opnd = pinst->operands[pinst->argc];
const EncoderBase::OpndDesc& opndDesc = odesc.opnds[pinst->argc];
switch (kind) {
case OpcodeByteKind_SlashR:
//decodeModRM(odesc, pbuf, pinst);
{
const ModRM& modrm = *(ModRM*)*pbuf;
unsigned regIndex = odesc.opnds[0].kind == OpndKind_GPReg ? 0 : 1;
RegName reg = getRegName(OpndKind_GPReg, opndDesc.size, EXTEND_REG(modrm.reg, r));
EncoderBase::Operand& regOpnd = pinst->operands[regIndex];
if (regIndex == 0) {
regOpnd = EncoderBase::Operand(reg);
++pinst->argc;
decodeModRM(odesc, pbuf, pinst, rex);
}
else {
decodeModRM(odesc, pbuf, pinst, rex);
++pinst->argc;
regOpnd = EncoderBase::Operand(reg);
}
++pinst->argc;
}
return true;
case OpcodeByteKind_rb:
case OpcodeByteKind_rw:
case OpcodeByteKind_rd:
{
// Gregory -
// Here we don't parse register because for current needs
// disassembler doesn't require to parse all operands
unsigned regid = data_byte - byte;
if (regid>7) {
return false;
}
++*pbuf;
return true;
}
case OpcodeByteKind_cb:
{
char offset = *(char*)*pbuf;
*pbuf += 1;
opnd = EncoderBase::Operand(offset);
++pinst->argc;
//pinst->direct_addr = (void*)(pinst->offset + *pbuf);
}
return true;
case OpcodeByteKind_cw:
// assert(false); // not an error, but not expected in current env
break;
case OpcodeByteKind_cd:
{
int offset = *(int*)*pbuf;
*pbuf += 4;
opnd = EncoderBase::Operand(offset);
++pinst->argc;
}
return true;
case OpcodeByteKind_SlashNum:
{
const ModRM& modrm = *(ModRM*)*pbuf;
if (modrm.reg != byte) {
return false;
}
decodeModRM(odesc, pbuf, pinst, rex);
++pinst->argc;
}
return true;
case OpcodeByteKind_ib:
{
char ival = *(char*)*pbuf;
opnd = EncoderBase::Operand(ival);
++pinst->argc;
*pbuf += 1;
}
return true;
case OpcodeByteKind_iw:
{
short ival = *(short*)*pbuf;
opnd = EncoderBase::Operand(ival);
++pinst->argc;
*pbuf += 2;
}
return true;
case OpcodeByteKind_id:
{
int ival = *(int*)*pbuf;
opnd = EncoderBase::Operand(ival);
++pinst->argc;
*pbuf += 4;
}
return true;
#ifdef _EM64T_
case OpcodeByteKind_io:
{
long long int ival = *(long long int*)*pbuf;
opnd = EncoderBase::Operand(OpndSize_64, ival);
++pinst->argc;
*pbuf += 8;
}
return true;
#endif
case OpcodeByteKind_plus_i:
{
unsigned regid = data_byte - byte;
if (regid>7) {
return false;
}
++*pbuf;
return true;
}
case OpcodeByteKind_ZeroOpcodeByte: // cant be here
// assert(false);
break;
default:
// unknown kind ? how comes ?
// assert(false);
break;
}
return false;
}
bool DecoderBase::try_mn(Mnemonic mn, const unsigned char ** pbuf, Inst * pinst) {
const unsigned char * save_pbuf = *pbuf;
EncoderBase::OpcodeDesc * opcodes = EncoderBase::opcodes[mn];
for (unsigned i=0; !opcodes[i].last; i++) {
const EncoderBase::OpcodeDesc& odesc = opcodes[i];
char *opcode_ptr = const_cast<char *>(odesc.opcode);
int opcode_len = odesc.opcode_len;
Rex *prex = NULL;
#ifdef _EM64T_
Rex rex;
#endif
*pbuf = save_pbuf;
#ifdef _EM64T_
// Match REX prefixes
unsigned char rex_byte = (*pbuf)[0];
if ((rex_byte & 0xf0) == 0x40)
{
if ((rex_byte & 0x08) != 0)
{
// Have REX.W
if (opcode_len > 0 && opcode_ptr[0] == 0x48)
{
// Have REX.W in opcode. All mnemonics that allow
// REX.W have to have specified it in opcode,
// otherwise it is not allowed
rex = *(Rex *)*pbuf;
prex = &rex;
(*pbuf)++;
opcode_ptr++;
opcode_len--;
}
}
else
{
// No REX.W, so it doesn't have to be in opcode. We
// have REX.B, REX.X, REX.R or their combination, but
// not in opcode, they may extend any part of the
// instruction
rex = *(Rex *)*pbuf;
prex = &rex;
(*pbuf)++;
}
}
#endif
if (opcode_len != 0) {
if (memcmp(*pbuf, opcode_ptr, opcode_len)) {
continue;
}
*pbuf += opcode_len;
}
if (odesc.aux0 != 0) {
if (!decode_aux(odesc, odesc.aux0, pbuf, pinst, prex)) {
continue;
}
if (odesc.aux1 != 0) {
if (!decode_aux(odesc, odesc.aux1, pbuf, pinst, prex)) {
continue;
}
}
pinst->odesc = &opcodes[i];
return true;
}
else {
// Can't have empty opcode
assert(opcode_len != 0);
pinst->odesc = &opcodes[i];
return true;
}
}
return false;
}
bool DecoderBase::decodeModRM(const EncoderBase::OpcodeDesc& odesc,
const unsigned char ** pbuf, Inst * pinst, const Rex *rex)
{
EncoderBase::Operand& opnd = pinst->operands[pinst->argc];
const EncoderBase::OpndDesc& opndDesc = odesc.opnds[pinst->argc];
//XXX debug ///assert(0x66 != *(*pbuf-2));
const ModRM& modrm = *(ModRM*)*pbuf;
*pbuf += 1;
RegName base = RegName_Null;
RegName index = RegName_Null;
int disp = 0;
unsigned scale = 0;
OpndSize reg_size = OpndSize_32;
#ifdef _EM64T_
if (NULL != rex && 0 != rex->w)
reg_size = OpndSize_64;
#endif
if (modrm.mod == 3) {
// we have only modrm. no sib, no disp.
RegName reg = getRegName(OpndKind_GPReg, opndDesc.size, EXTEND_REG(modrm.rm, b));
opnd = EncoderBase::Operand(reg);
return true;
}
const SIB& sib = *(SIB*)*pbuf;
// check whether we have a sib
if (modrm.rm == 4) {
// yes, we have SIB
*pbuf += 1;
scale = sib.scale == 0 ? 0 : (1<<sib.scale);
if (sib.index != 4) {
index = getRegName(OpndKind_GPReg, reg_size, EXTEND_REG(sib.index, x));
} else {
// (sib.index == 4) => no index
}
if (sib.base != 5 && modrm.mod != 0) {
base = getRegName(OpndKind_GPReg, reg_size, EXTEND_REG(sib.base, b));
} else {
// (sib.base == 5 && modrm.mod == 0) => no base
}
}
else {
if (modrm.mod != 0 || modrm.rm != 5) {
base = getRegName(OpndKind_GPReg, reg_size, EXTEND_REG(modrm.rm, b));
}
else {
// mod=0 && rm == 5 => only disp32
}
}
if (modrm.mod == 2) {
// have disp32
disp = *(int*)*pbuf;
*pbuf += 4;
}
else if (modrm.mod == 1) {
// have disp8
disp = *(char*)*pbuf;
*pbuf += 1;
}
else {
assert(modrm.mod == 0);
if (modrm.rm == 5) {
// have disp32 w/o sib
disp = *(int*)*pbuf;
*pbuf += 4;
}
else if (modrm.rm == 4 && sib.base == 5) {
// have disp32 with SI in sib
disp = *(int*)*pbuf;
*pbuf += 4;
}
}
opnd = EncoderBase::Operand(opndDesc.size, base, index, scale, disp);
return true;
}
<commit_msg>Applied patch from HARMONY-5510 [drlvm][jvmti] VTS test for SingleStep event fails on x86_64<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Alexander V. Astapchuk
* @version $Revision: $
*/
/**
* @file
* @brief Main decoding (disassembling) routines implementation.
*/
#include "dec_base.h"
#include "open/common.h"
bool DecoderBase::is_prefix(const unsigned char * bytes)
{
unsigned char b0 = *bytes;
unsigned char b1 = *(bytes+1);
if (b0 == 0xF0) { // LOCK
return true;
}
if (b0==0xF2 || b0==0xF3) { // REPNZ/REPZ prefixes
if (b1 == 0x0F) { // .... but may be a part of SIMD opcode
return false;
}
return true;
}
if (b0 == 0x2E || b0 == 0x36 || b0==0x3E || b0==0x26 || b0==0x64 || b0==0x3E) {
// branch hints, segment prefixes
return true;
}
if (b0==0x66) { // operand-size prefix
if (b1 == 0x0F) { // .... but may be a part of SIMD opcode
return false;
}
return false; //XXX - currently considered as part of opcode//true;
}
if (b0==0x67) { // address size prefix
return true;
}
return false;
}
unsigned DecoderBase::decode(const void * addr, Inst * pinst)
{
Inst tmp;
//assert( *(unsigned char*)addr != 0x66);
const unsigned char * bytes = (unsigned char*)addr;
// Check prefix first
for (unsigned i=0; i<4; i++) {
if (!is_prefix(bytes)) {
break;
}
++bytes;
}
if (is_prefix(bytes)) {
// More than 4 prefixes together ?
// assert(false);
return 0;
}
// Load up to 4 prefixes
// for each Mnemonic
// for each opcodedesc
// if (raw_len == 0) memcmp(, raw_len)
// else check the mixed state which is one of the following:
// /digit /i /rw /rd /rb
bool found = false;
const unsigned char * saveBytes = bytes;
for (unsigned mn=1; mn<Mnemonic_Count; mn++) {
bytes = saveBytes;
found=try_mn((Mnemonic)mn, &bytes, &tmp);
if (found) {
tmp.mn = (Mnemonic)mn;
break;
}
}
if (!found) {
// assert(false);
return 0;
}
tmp.size = (unsigned)(bytes-(const unsigned char*)addr);
if (pinst) {
*pinst = tmp;
}
return tmp.size;
}
#ifdef _EM64T_
#define EXTEND_REG(reg, flag) \
((NULL == rex || 0 == rex->flag) ? reg : (reg + 8))
#else
#define EXTEND_REG(reg, flag) (reg)
#endif
bool DecoderBase::decode_aux(const EncoderBase::OpcodeDesc& odesc, unsigned aux,
const unsigned char ** pbuf, Inst * pinst, const Rex UNREF *rex)
{
OpcodeByteKind kind = (OpcodeByteKind)(aux & OpcodeByteKind_KindMask);
unsigned byte = (aux & OpcodeByteKind_OpcodeMask);
unsigned data_byte = **pbuf;
EncoderBase::Operand& opnd = pinst->operands[pinst->argc];
const EncoderBase::OpndDesc& opndDesc = odesc.opnds[pinst->argc];
switch (kind) {
case OpcodeByteKind_SlashR:
//decodeModRM(odesc, pbuf, pinst);
{
const ModRM& modrm = *(ModRM*)*pbuf;
unsigned regIndex = odesc.opnds[0].kind == OpndKind_GPReg ? 0 : 1;
RegName reg = getRegName(OpndKind_GPReg, opndDesc.size, EXTEND_REG(modrm.reg, r));
EncoderBase::Operand& regOpnd = pinst->operands[regIndex];
if (regIndex == 0) {
regOpnd = EncoderBase::Operand(reg);
++pinst->argc;
decodeModRM(odesc, pbuf, pinst, rex);
}
else {
decodeModRM(odesc, pbuf, pinst, rex);
++pinst->argc;
regOpnd = EncoderBase::Operand(reg);
}
++pinst->argc;
}
return true;
case OpcodeByteKind_rb:
case OpcodeByteKind_rw:
case OpcodeByteKind_rd:
{
// Gregory -
// Here we don't parse register because for current needs
// disassembler doesn't require to parse all operands
unsigned regid = data_byte - byte;
if (regid>7) {
return false;
}
++*pbuf;
return true;
}
case OpcodeByteKind_cb:
{
char offset = *(char*)*pbuf;
*pbuf += 1;
opnd = EncoderBase::Operand(offset);
++pinst->argc;
//pinst->direct_addr = (void*)(pinst->offset + *pbuf);
}
return true;
case OpcodeByteKind_cw:
// assert(false); // not an error, but not expected in current env
break;
case OpcodeByteKind_cd:
{
int offset = *(int*)*pbuf;
*pbuf += 4;
opnd = EncoderBase::Operand(offset);
++pinst->argc;
}
return true;
case OpcodeByteKind_SlashNum:
{
const ModRM& modrm = *(ModRM*)*pbuf;
if (modrm.reg != byte) {
return false;
}
decodeModRM(odesc, pbuf, pinst, rex);
++pinst->argc;
}
return true;
case OpcodeByteKind_ib:
{
char ival = *(char*)*pbuf;
opnd = EncoderBase::Operand(ival);
++pinst->argc;
*pbuf += 1;
}
return true;
case OpcodeByteKind_iw:
{
short ival = *(short*)*pbuf;
opnd = EncoderBase::Operand(ival);
++pinst->argc;
*pbuf += 2;
}
return true;
case OpcodeByteKind_id:
{
int ival = *(int*)*pbuf;
opnd = EncoderBase::Operand(ival);
++pinst->argc;
*pbuf += 4;
}
return true;
#ifdef _EM64T_
case OpcodeByteKind_io:
{
long long int ival = *(long long int*)*pbuf;
opnd = EncoderBase::Operand(OpndSize_64, ival);
++pinst->argc;
*pbuf += 8;
}
return true;
#endif
case OpcodeByteKind_plus_i:
{
unsigned regid = data_byte - byte;
if (regid>7) {
return false;
}
++*pbuf;
return true;
}
case OpcodeByteKind_ZeroOpcodeByte: // cant be here
// assert(false);
break;
default:
// unknown kind ? how comes ?
// assert(false);
break;
}
return false;
}
bool DecoderBase::try_mn(Mnemonic mn, const unsigned char ** pbuf, Inst * pinst) {
const unsigned char * save_pbuf = *pbuf;
EncoderBase::OpcodeDesc * opcodes = EncoderBase::opcodes[mn];
for (unsigned i=0; !opcodes[i].last; i++) {
const EncoderBase::OpcodeDesc& odesc = opcodes[i];
char *opcode_ptr = const_cast<char *>(odesc.opcode);
int opcode_len = odesc.opcode_len;
Rex *prex = NULL;
#ifdef _EM64T_
Rex rex;
#endif
*pbuf = save_pbuf;
#ifdef _EM64T_
// Match REX prefixes
unsigned char rex_byte = (*pbuf)[0];
if ((rex_byte & 0xf0) == 0x40)
{
if ((rex_byte & 0x08) != 0)
{
// Have REX.W
if (opcode_len > 0 && opcode_ptr[0] == 0x48)
{
// Have REX.W in opcode. All mnemonics that allow
// REX.W have to have specified it in opcode,
// otherwise it is not allowed
rex = *(Rex *)*pbuf;
prex = &rex;
(*pbuf)++;
opcode_ptr++;
opcode_len--;
}
}
else
{
// No REX.W, so it doesn't have to be in opcode. We
// have REX.B, REX.X, REX.R or their combination, but
// not in opcode, they may extend any part of the
// instruction
rex = *(Rex *)*pbuf;
prex = &rex;
(*pbuf)++;
}
}
#endif
if (opcode_len != 0) {
if (memcmp(*pbuf, opcode_ptr, opcode_len)) {
continue;
}
*pbuf += opcode_len;
}
if (odesc.aux0 != 0) {
if (!decode_aux(odesc, odesc.aux0, pbuf, pinst, prex)) {
continue;
}
if (odesc.aux1 != 0) {
if (!decode_aux(odesc, odesc.aux1, pbuf, pinst, prex)) {
continue;
}
}
pinst->odesc = &opcodes[i];
return true;
}
else {
// Can't have empty opcode
assert(opcode_len != 0);
pinst->odesc = &opcodes[i];
return true;
}
}
return false;
}
bool DecoderBase::decodeModRM(const EncoderBase::OpcodeDesc& odesc,
const unsigned char ** pbuf, Inst * pinst, const Rex *rex)
{
EncoderBase::Operand& opnd = pinst->operands[pinst->argc];
const EncoderBase::OpndDesc& opndDesc = odesc.opnds[pinst->argc];
//XXX debug ///assert(0x66 != *(*pbuf-2));
const ModRM& modrm = *(ModRM*)*pbuf;
*pbuf += 1;
RegName base = RegName_Null;
RegName index = RegName_Null;
int disp = 0;
unsigned scale = 0;
// On x86_64 all mnemonics that allow REX.W have REX.W in opcode.
// Therefore REX.W is simply ignored, and opndDesc.size is used
if (modrm.mod == 3) {
// we have only modrm. no sib, no disp.
RegName reg = getRegName(OpndKind_GPReg, opndDesc.size, EXTEND_REG(modrm.rm, b));
opnd = EncoderBase::Operand(reg);
return true;
}
const SIB& sib = *(SIB*)*pbuf;
// check whether we have a sib
if (modrm.rm == 4) {
// yes, we have SIB
*pbuf += 1;
scale = sib.scale == 0 ? 0 : (1<<sib.scale);
if (sib.index != 4) {
index = getRegName(OpndKind_GPReg, opndDesc.size, EXTEND_REG(sib.index, x));
} else {
// (sib.index == 4) => no index
}
if (sib.base != 5 && modrm.mod != 0) {
base = getRegName(OpndKind_GPReg, opndDesc.size, EXTEND_REG(sib.base, b));
} else {
// (sib.base == 5 && modrm.mod == 0) => no base
}
}
else {
if (modrm.mod != 0 || modrm.rm != 5) {
base = getRegName(OpndKind_GPReg, opndDesc.size, EXTEND_REG(modrm.rm, b));
}
else {
// mod=0 && rm == 5 => only disp32
}
}
if (modrm.mod == 2) {
// have disp32
disp = *(int*)*pbuf;
*pbuf += 4;
}
else if (modrm.mod == 1) {
// have disp8
disp = *(char*)*pbuf;
*pbuf += 1;
}
else {
assert(modrm.mod == 0);
if (modrm.rm == 5) {
// have disp32 w/o sib
disp = *(int*)*pbuf;
*pbuf += 4;
}
else if (modrm.rm == 4 && sib.base == 5) {
// have disp32 with SI in sib
disp = *(int*)*pbuf;
*pbuf += 4;
}
}
opnd = EncoderBase::Operand(opndDesc.size, base, index, scale, disp);
return true;
}
<|endoftext|>
|
<commit_before>#ifndef VIENNAGRID_META_TYPELIST_HPP
#define VIENNAGRID_META_TYPELIST_HPP
#include "utils.hpp"
namespace viennagrid
{
namespace meta
{
template <class head_, class tail_>
struct typelist_t
{
typedef head_ head;
typedef tail_ tail;
};
// C++11 version
// template<typename ... types>
// struct make_typelist;
//
// template<>
// struct make_typelist<>
// {
// typedef viennagrid::meta::null_type type;
// };
//
// template<typename head, typename ... tail>
// struct make_typelist<head, tail...>
// {
// typedef viennagrid::meta::typelist_t<head, typename make_typelist<tail...>::type> type;
// };
template< typename T01 = viennagrid::meta::null_type, typename T02 = viennagrid::meta::null_type, typename T03 = viennagrid::meta::null_type, typename T04 = viennagrid::meta::null_type,
typename T05 = viennagrid::meta::null_type, typename T06 = viennagrid::meta::null_type, typename T07 = viennagrid::meta::null_type, typename T08 = viennagrid::meta::null_type,
typename T09 = viennagrid::meta::null_type, typename T10 = viennagrid::meta::null_type, typename T11 = viennagrid::meta::null_type, typename T12 = viennagrid::meta::null_type,
typename T13 = viennagrid::meta::null_type, typename T14 = viennagrid::meta::null_type, typename T15 = viennagrid::meta::null_type, typename T16 = viennagrid::meta::null_type,
typename T17 = viennagrid::meta::null_type, typename T18 = viennagrid::meta::null_type, typename T19 = viennagrid::meta::null_type, typename T20 = viennagrid::meta::null_type >
struct make_typelist
{
typedef
typelist_t<
T01,
typename make_typelist<T02, T03, T04, T05, T06, T07, T08, T09, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20>::type
> type;
};
template<>
struct make_typelist<
viennagrid::meta::null_type, viennagrid::meta::null_type, viennagrid::meta::null_type, viennagrid::meta::null_type,
viennagrid::meta::null_type, viennagrid::meta::null_type, viennagrid::meta::null_type, viennagrid::meta::null_type,
viennagrid::meta::null_type, viennagrid::meta::null_type, viennagrid::meta::null_type, viennagrid::meta::null_type,
viennagrid::meta::null_type, viennagrid::meta::null_type, viennagrid::meta::null_type, viennagrid::meta::null_type,
viennagrid::meta::null_type, viennagrid::meta::null_type, viennagrid::meta::null_type, viennagrid::meta::null_type>
{
typedef viennagrid::meta::null_type type;
};
namespace typelist
{
namespace result_of
{
// size of a typelist
template <typename typelist> struct size;
template <> struct size<null_type>
{
enum { value = 0 };
};
template <typename head, typename tail>
struct size< typelist_t<head, tail> >
{
enum { value = 1 + size<tail>::value };
};
// index access
template <typename typelist, unsigned int index> struct at
{
typedef out_of_range type;
};
template <typename head, typename tail>
struct at<typelist_t<head, tail>, 0>
{
typedef head type;
};
template <typename head, typename tail, unsigned int i>
struct at<typelist_t<head, tail>, i>
{
typedef typename at<tail, i - 1>::type type;
};
// returns the index of the first type in the typelist
template <typename typelist, typename to_find> struct index_of;
template <typename to_find>
struct index_of<null_type, to_find>
{
enum { value = -1 };
};
template <typename to_find, typename tail>
struct index_of<typelist_t<to_find, tail>, to_find>
{
enum { value = 0 };
};
template <typename head, typename tail, typename to_find>
struct index_of<typelist_t<head, tail>, to_find>
{
private:
enum { temp = index_of<tail, to_find>::value };
public:
enum { value = (temp == -1 ? -1 : 1 + temp) };
};
// push back a single type
template <typename typelist, typename to_add> struct push_back;
template <>
struct push_back<null_type, null_type>
{
typedef null_type type;
};
template <typename to_add>
struct push_back<null_type, to_add>
{
typedef typelist_t<to_add, null_type> type;
};
template <typename head, typename tail, typename to_add>
struct push_back<typelist_t<head, tail>, to_add>
{
typedef typelist_t<head, typename push_back<tail, to_add>::type> type;
};
// push back list
template <typename typelist, typename typelist_to_add> struct push_back_list;
template <>
struct push_back_list<null_type, null_type>
{
typedef null_type type;
};
template <typename head, typename tail>
struct push_back_list<null_type, typelist_t<head, tail> >
{
typedef typelist_t<head, tail> type;
};
template <typename head, typename tail>
struct push_back_list<typelist_t<head, tail>, null_type >
{
typedef typelist_t<head, tail> type;
};
template <typename head1, typename tail1, typename head2, typename tail2>
struct push_back_list<typelist_t<head1, tail1>, typelist_t<head2, tail2> >
{
typedef typename push_back_list< typename push_back< typelist_t<head1, tail1>, head2>::type, tail2 >::type type;
};
// erase_at the type at index
template <typename typelist, unsigned int index_to_erase> struct erase_at;
template <unsigned int index_to_erase>
struct erase_at<null_type, index_to_erase>
{
typedef null_type type;
};
template <typename head, typename tail>
struct erase_at< typelist_t<head, tail>, 0>
{
typedef tail type;
};
template <typename head, typename tail, unsigned int index_to_erase>
struct erase_at< typelist_t<head, tail>, index_to_erase>
{
typedef typelist_t<head, typename erase_at<tail, index_to_erase-1>::type> type;
};
// erase the first type
template <typename typelist, typename to_erase> struct erase;
template <typename to_erase>
struct erase<null_type, to_erase>
{
typedef null_type type;
};
template <typename to_erase, typename tail>
struct erase< typelist_t<to_erase, tail>, to_erase>
{
typedef tail type;
};
template <typename head, typename tail, typename to_erase>
struct erase< typelist_t<head, tail>, to_erase>
{
typedef typelist_t<head, typename erase<tail, to_erase>::type> type;
};
// erase all types
template <typename typelist, typename to_erase>
struct erase_all;
template <typename to_erase>
struct erase_all<null_type, to_erase>
{
typedef null_type type;
};
template <typename to_erase, typename tail>
struct erase_all< typelist_t<to_erase, tail>, to_erase>
{
// Go all the way down the list removing the type
typedef typename erase_all<tail, to_erase>::type type;
};
template <typename head, typename tail, typename to_erase>
struct erase_all< typelist_t<head, tail>, to_erase>
{
// Go all the way down the list removing the type
typedef typelist_t<head, typename erase_all<tail, to_erase>::type> type;
};
// reverse
template <typename typelist> struct reverse;
template <> struct
reverse<null_type>
{
typedef null_type type;
};
template <typename head, typename tail>
struct reverse< typelist_t<head, tail> >
{
public:
typedef typelist_t<head, tail> typelist;
typedef typelist_t<
typename at<
typelist,
size<typelist>::value-1
>::type,
typename erase_at<
typelist,
size<typelist>::value-1
>::type
> type;
};
// no duplicate types
template <typename typelist> struct no_duplicates;
template <> struct
no_duplicates<null_type>
{
typedef null_type type;
};
template <typename head, typename tail>
struct no_duplicates< typelist_t<head, tail> >
{
private:
typedef typename no_duplicates<tail>::type L1;
typedef typename erase<L1, head>::type L2;
public:
typedef typelist_t<head, L2> type;
};
// replace the type at index by another type
template <typename typelist, unsigned int index_to_replace, typename replaced> struct replace_at;
template <unsigned int index_to_replace, typename replaced>
struct replace_at<null_type, index_to_replace, replaced>
{
typedef null_type type;
};
template <typename head, typename tail, typename replaced>
struct replace_at<typelist_t<head, tail>, 0, replaced>
{
typedef typelist_t<replaced, tail> type;
};
template <typename head, typename tail, unsigned int index_to_replace, typename replaced>
struct replace_at<typelist_t<head, tail>, index_to_replace, replaced>
{
typedef typelist_t<head, typename replace_at<tail, index_to_replace-1, replaced>::type> type;
};
// replace the first type by another type
template <typename typelist, typename to_replace, typename replaced> struct replace;
template <typename to_replace, typename replaced>
struct replace<null_type, to_replace, replaced>
{
typedef null_type type;
};
template <typename to_replace, typename tail, typename replaced>
struct replace<typelist_t<to_replace, tail>, to_replace, replaced>
{
typedef typelist_t<replaced, tail> type;
};
template <typename head, typename tail, typename to_replace, typename replaced>
struct replace<typelist_t<head, tail>, to_replace, replaced>
{
typedef typelist_t<head, typename replace<tail, to_replace, replaced>::type> type;
};
// replace all types by another type
template <typename typelist, typename to_replace, typename replaced> struct replace_all;
template <typename to_replace, typename replaced>
struct replace_all<null_type, to_replace, replaced>
{
typedef null_type type;
};
template <typename to_replace, typename tail, typename replaced>
struct replace_all<typelist_t<to_replace, tail>, to_replace, replaced>
{
typedef typelist_t<replaced, typename replace_all<tail, to_replace, replaced>::type> type;
};
template <typename head, typename tail, typename to_replace, typename replaced>
struct replace_all<typelist_t<head, tail>, to_replace, replaced>
{
typedef typelist_t<head, typename replace_all<tail, to_replace, replaced>::type> type;
};
// returns only those types which are in both typelists
template<typename typelist1, typename typelist2>
struct intersection {};
template<>
struct intersection<null_type, null_type>
{
typedef null_type type;
};
template<typename head1, typename tail1>
struct intersection<typelist_t<head1, tail1>, null_type>
{
typedef null_type type;
};
template<typename head2, typename tail2>
struct intersection<null_type, typelist_t<head2, tail2> >
{
typedef null_type type;
};
template<typename head1, typename tail1, typename head2, typename tail2>
struct intersection< typelist_t<head1, tail1>, typelist_t<head2, tail2> >
{
typedef typelist_t<head1, tail1> typelist1;
typedef typelist_t<head2, tail2> typelist2;
enum { search_result = index_of< typelist2, head1 >::value };
typedef typename IF<
(search_result >= 0),
typename erase_at<typelist2, search_result>::type,
typelist2
>::type new_typelist2;
typedef typename IF<
(search_result >= 0),
typelist_t<head1, typename intersection<tail1, new_typelist2>::type >,
typename intersection<tail1, new_typelist2>::type
>::type type;
};
}
}
} // namespace meta
} // namespace viennagrid
#endif // end file guardian
<commit_msg>fixed bug in reverse meta function<commit_after>#ifndef VIENNAGRID_META_TYPELIST_HPP
#define VIENNAGRID_META_TYPELIST_HPP
#include "utils.hpp"
namespace viennagrid
{
namespace meta
{
template <class head_, class tail_>
struct typelist_t
{
typedef head_ head;
typedef tail_ tail;
};
// C++11 version
// template<typename ... types>
// struct make_typelist;
//
// template<>
// struct make_typelist<>
// {
// typedef viennagrid::meta::null_type type;
// };
//
// template<typename head, typename ... tail>
// struct make_typelist<head, tail...>
// {
// typedef viennagrid::meta::typelist_t<head, typename make_typelist<tail...>::type> type;
// };
template< typename T01 = viennagrid::meta::null_type, typename T02 = viennagrid::meta::null_type, typename T03 = viennagrid::meta::null_type, typename T04 = viennagrid::meta::null_type,
typename T05 = viennagrid::meta::null_type, typename T06 = viennagrid::meta::null_type, typename T07 = viennagrid::meta::null_type, typename T08 = viennagrid::meta::null_type,
typename T09 = viennagrid::meta::null_type, typename T10 = viennagrid::meta::null_type, typename T11 = viennagrid::meta::null_type, typename T12 = viennagrid::meta::null_type,
typename T13 = viennagrid::meta::null_type, typename T14 = viennagrid::meta::null_type, typename T15 = viennagrid::meta::null_type, typename T16 = viennagrid::meta::null_type,
typename T17 = viennagrid::meta::null_type, typename T18 = viennagrid::meta::null_type, typename T19 = viennagrid::meta::null_type, typename T20 = viennagrid::meta::null_type >
struct make_typelist
{
typedef
typelist_t<
T01,
typename make_typelist<T02, T03, T04, T05, T06, T07, T08, T09, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20>::type
> type;
};
template<>
struct make_typelist<
viennagrid::meta::null_type, viennagrid::meta::null_type, viennagrid::meta::null_type, viennagrid::meta::null_type,
viennagrid::meta::null_type, viennagrid::meta::null_type, viennagrid::meta::null_type, viennagrid::meta::null_type,
viennagrid::meta::null_type, viennagrid::meta::null_type, viennagrid::meta::null_type, viennagrid::meta::null_type,
viennagrid::meta::null_type, viennagrid::meta::null_type, viennagrid::meta::null_type, viennagrid::meta::null_type,
viennagrid::meta::null_type, viennagrid::meta::null_type, viennagrid::meta::null_type, viennagrid::meta::null_type>
{
typedef viennagrid::meta::null_type type;
};
namespace typelist
{
namespace result_of
{
// size of a typelist
template <typename typelist> struct size;
template <> struct size<null_type>
{
enum { value = 0 };
};
template <typename head, typename tail>
struct size< typelist_t<head, tail> >
{
enum { value = 1 + size<tail>::value };
};
// index access
template <typename typelist, unsigned int index> struct at
{
typedef out_of_range type;
};
template <typename head, typename tail>
struct at<typelist_t<head, tail>, 0>
{
typedef head type;
};
template <typename head, typename tail, unsigned int i>
struct at<typelist_t<head, tail>, i>
{
typedef typename at<tail, i - 1>::type type;
};
// returns the index of the first type in the typelist
template <typename typelist, typename to_find> struct index_of;
template <typename to_find>
struct index_of<null_type, to_find>
{
enum { value = -1 };
};
template <typename to_find, typename tail>
struct index_of<typelist_t<to_find, tail>, to_find>
{
enum { value = 0 };
};
template <typename head, typename tail, typename to_find>
struct index_of<typelist_t<head, tail>, to_find>
{
private:
enum { temp = index_of<tail, to_find>::value };
public:
enum { value = (temp == -1 ? -1 : 1 + temp) };
};
// push back a single type
template <typename typelist, typename to_add> struct push_back;
template <>
struct push_back<null_type, null_type>
{
typedef null_type type;
};
template <typename to_add>
struct push_back<null_type, to_add>
{
typedef typelist_t<to_add, null_type> type;
};
template <typename head, typename tail, typename to_add>
struct push_back<typelist_t<head, tail>, to_add>
{
typedef typelist_t<head, typename push_back<tail, to_add>::type> type;
};
// push back list
template <typename typelist, typename typelist_to_add> struct push_back_list;
template <>
struct push_back_list<null_type, null_type>
{
typedef null_type type;
};
template <typename head, typename tail>
struct push_back_list<null_type, typelist_t<head, tail> >
{
typedef typelist_t<head, tail> type;
};
template <typename head, typename tail>
struct push_back_list<typelist_t<head, tail>, null_type >
{
typedef typelist_t<head, tail> type;
};
template <typename head1, typename tail1, typename head2, typename tail2>
struct push_back_list<typelist_t<head1, tail1>, typelist_t<head2, tail2> >
{
typedef typename push_back_list< typename push_back< typelist_t<head1, tail1>, head2>::type, tail2 >::type type;
};
// erase_at the type at index
template <typename typelist, unsigned int index_to_erase> struct erase_at;
template <unsigned int index_to_erase>
struct erase_at<null_type, index_to_erase>
{
typedef null_type type;
};
template <typename head, typename tail>
struct erase_at< typelist_t<head, tail>, 0>
{
typedef tail type;
};
template <typename head, typename tail, unsigned int index_to_erase>
struct erase_at< typelist_t<head, tail>, index_to_erase>
{
typedef typelist_t<head, typename erase_at<tail, index_to_erase-1>::type> type;
};
// erase the first type
template <typename typelist, typename to_erase> struct erase;
template <typename to_erase>
struct erase<null_type, to_erase>
{
typedef null_type type;
};
template <typename to_erase, typename tail>
struct erase< typelist_t<to_erase, tail>, to_erase>
{
typedef tail type;
};
template <typename head, typename tail, typename to_erase>
struct erase< typelist_t<head, tail>, to_erase>
{
typedef typelist_t<head, typename erase<tail, to_erase>::type> type;
};
// erase all types
template <typename typelist, typename to_erase>
struct erase_all;
template <typename to_erase>
struct erase_all<null_type, to_erase>
{
typedef null_type type;
};
template <typename to_erase, typename tail>
struct erase_all< typelist_t<to_erase, tail>, to_erase>
{
// Go all the way down the list removing the type
typedef typename erase_all<tail, to_erase>::type type;
};
template <typename head, typename tail, typename to_erase>
struct erase_all< typelist_t<head, tail>, to_erase>
{
// Go all the way down the list removing the type
typedef typelist_t<head, typename erase_all<tail, to_erase>::type> type;
};
// reverse
template <typename typelist> struct reverse;
template <> struct
reverse<null_type>
{
typedef null_type type;
};
template <typename head, typename tail>
struct reverse< typelist_t<head, tail> >
{
public:
typedef typelist_t<head, tail> typelist;
typedef typelist_t<
typename at<
typelist,
size<typelist>::value-1
>::type,
typename reverse<
typename erase_at<
typelist,
size<typelist>::value-1
>::type
>::type
> type;
};
// no duplicate types
template <typename typelist> struct no_duplicates;
template <> struct
no_duplicates<null_type>
{
typedef null_type type;
};
template <typename head, typename tail>
struct no_duplicates< typelist_t<head, tail> >
{
private:
typedef typename no_duplicates<tail>::type L1;
typedef typename erase<L1, head>::type L2;
public:
typedef typelist_t<head, L2> type;
};
// replace the type at index by another type
template <typename typelist, unsigned int index_to_replace, typename replaced> struct replace_at;
template <unsigned int index_to_replace, typename replaced>
struct replace_at<null_type, index_to_replace, replaced>
{
typedef null_type type;
};
template <typename head, typename tail, typename replaced>
struct replace_at<typelist_t<head, tail>, 0, replaced>
{
typedef typelist_t<replaced, tail> type;
};
template <typename head, typename tail, unsigned int index_to_replace, typename replaced>
struct replace_at<typelist_t<head, tail>, index_to_replace, replaced>
{
typedef typelist_t<head, typename replace_at<tail, index_to_replace-1, replaced>::type> type;
};
// replace the first type by another type
template <typename typelist, typename to_replace, typename replaced> struct replace;
template <typename to_replace, typename replaced>
struct replace<null_type, to_replace, replaced>
{
typedef null_type type;
};
template <typename to_replace, typename tail, typename replaced>
struct replace<typelist_t<to_replace, tail>, to_replace, replaced>
{
typedef typelist_t<replaced, tail> type;
};
template <typename head, typename tail, typename to_replace, typename replaced>
struct replace<typelist_t<head, tail>, to_replace, replaced>
{
typedef typelist_t<head, typename replace<tail, to_replace, replaced>::type> type;
};
// replace all types by another type
template <typename typelist, typename to_replace, typename replaced> struct replace_all;
template <typename to_replace, typename replaced>
struct replace_all<null_type, to_replace, replaced>
{
typedef null_type type;
};
template <typename to_replace, typename tail, typename replaced>
struct replace_all<typelist_t<to_replace, tail>, to_replace, replaced>
{
typedef typelist_t<replaced, typename replace_all<tail, to_replace, replaced>::type> type;
};
template <typename head, typename tail, typename to_replace, typename replaced>
struct replace_all<typelist_t<head, tail>, to_replace, replaced>
{
typedef typelist_t<head, typename replace_all<tail, to_replace, replaced>::type> type;
};
// returns only those types which are in both typelists
template<typename typelist1, typename typelist2>
struct intersection {};
template<>
struct intersection<null_type, null_type>
{
typedef null_type type;
};
template<typename head1, typename tail1>
struct intersection<typelist_t<head1, tail1>, null_type>
{
typedef null_type type;
};
template<typename head2, typename tail2>
struct intersection<null_type, typelist_t<head2, tail2> >
{
typedef null_type type;
};
template<typename head1, typename tail1, typename head2, typename tail2>
struct intersection< typelist_t<head1, tail1>, typelist_t<head2, tail2> >
{
typedef typelist_t<head1, tail1> typelist1;
typedef typelist_t<head2, tail2> typelist2;
enum { search_result = index_of< typelist2, head1 >::value };
typedef typename IF<
(search_result >= 0),
typename erase_at<typelist2, search_result>::type,
typelist2
>::type new_typelist2;
typedef typename IF<
(search_result >= 0),
typelist_t<head1, typename intersection<tail1, new_typelist2>::type >,
typename intersection<tail1, new_typelist2>::type
>::type type;
};
}
}
} // namespace meta
} // namespace viennagrid
#endif // end file guardian
<|endoftext|>
|
<commit_before>
//--------------------------------------------------
// file: RPN+UnitTests.cpp
//-------------------------------------------------
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "RPNCalc.h"
#include "RPNTestHelper.h"
using namespace P4_RPNCALC;
TEST_CASE("Operation Methods")
{
RPNTestHelper test;
SECTION("Sanity Tests") {
for (int n = 0; n < 100; n++) {
REQUIRE(test.expectedStackOutput(to_string(n), to_string(n)));
}
}
SECTION("Method: clearAll()")
{
REQUIRE(test.expectedStackOutput("50", "50"));
REQUIRE(test.expectedOutput("c", ""));
REQUIRE(test.expectedStackOutput("50 100 +", "150"));
REQUIRE(test.expectedOutput("c", ""));
REQUIRE(test.expectedStackOutput("50 100 + 200", "200"));
REQUIRE(test.expectedOutput("c", ""));
REQUIRE(test.expectedStackOutput("50", "50"));
REQUIRE(test.expectedOutput("C", ""));
REQUIRE(test.expectedStackOutput("50 100 +", "150"));
REQUIRE(test.expectedOutput("C", ""));
REQUIRE(test.expectedStackOutput("50 100 + 200", "200"));
REQUIRE(test.expectedOutput("C", ""));
}
SECTION("Method: clearEntry()")
{
REQUIRE(test.expectedStackOutput("50", "50"));
REQUIRE(test.expectedOutput("ce", ""));
REQUIRE(test.expectedStackOutput("50 100 +", "150"));
REQUIRE(test.expectedOutput("ce", ""));
REQUIRE(test.expectedStackOutput("50 100 + 200", "200"));
REQUIRE(test.expectedStackOutput("ce", "150"));
REQUIRE(test.expectedOutput("ce", ""));
REQUIRE(test.expectedStackOutput("50", "50"));
REQUIRE(test.expectedOutput("CE", ""));
REQUIRE(test.expectedStackOutput("50 100 +", "150"));
REQUIRE(test.expectedOutput("CE", ""));
REQUIRE(test.expectedStackOutput("50 100 + 200", "200"));
REQUIRE(test.expectedStackOutput("CE", "150"));
REQUIRE(test.expectedOutput("CE", ""));
}
SECTION("Method: add()")
{
REQUIRE(test.expectedStackOutput("3 5+", "8"));
REQUIRE(test.expectedStackOutput("2 4 3 +", "7"));
REQUIRE(test.expectedOutput("c", ""));
REQUIRE(test.expectedStackOutput("3 4 + 6", "6"));
REQUIRE(test.expectedStackOutput("4 +", "10"));
REQUIRE(test.expectedStackOutput("-12 +", "-2"));
REQUIRE(test.expectedStackOutput("5 +", "3"));
REQUIRE(test.expectedStackOutput("3 +", "6"));
REQUIRE(test.getStackOutput("10 100 +") == "110");
REQUIRE(test.getStackOutput("10 100+") == "110");
}
SECTION("Method: combinations of add() & subtract()")
{
REQUIRE(test.getStackOutput("4.4 5.5 + 60 -") == "-50.1");
REQUIRE(test.expectedStackOutput("4.4 5.5 - 60 +", "58.9"));
REQUIRE(test.expectedStackOutput("40 50 + 60 -", "30"));
REQUIRE(test.expectedStackOutput("40 50 - 60 +", "50"));
REQUIRE(test.expectedStackOutput("40 50 60 + -", "-70"));
REQUIRE(test.expectedStackOutput("40 50 60 - +", "30"));
REQUIRE(test.expectedStackOutput("-40 -50 + 60 -", "-150"));
REQUIRE(test.expectedStackOutput("-40 -50 + -60 -", "-30"));
REQUIRE(test.expectedStackOutput("-40 -50 - 60 +", "70"));
REQUIRE(test.expectedStackOutput("-40 -50 - -60 +", "-50"));
}
SECTION("Method: subtract()")
{
REQUIRE(test.expectedStackOutput("5 6 -", "-1"));
REQUIRE(test.expectedStackOutput("3 9 4 -", "5"));
REQUIRE(test.expectedStackOutput("-", "-2"));
REQUIRE(test.expectedOutput("c", ""));
REQUIRE(test.expectedStackOutput("-1 5 -", "-6"));
REQUIRE(test.expectedStackOutput("10 100 -", "-90"));
REQUIRE(test.expectedStackOutput("10 100-", "-90"));
REQUIRE(test.expectedStackOutput("-", "0"));
}
SECTION("Method: multiply()")
{
REQUIRE(test.expectedStackOutput("3 9 7 2 4 *", "8"));
REQUIRE(test.expectedStackOutput("*", "56"));
REQUIRE(test.expectedStackOutput("*", "504"));
REQUIRE(test.expectedStackOutput("*", "1512"));
REQUIRE(test.expectError("*"));
REQUIRE(test.getOutput("c") == "");
REQUIRE(test.expectedStackOutput("-4 -6 *", "24"));
REQUIRE(test.expectedStackOutput("-2 *", "-48"));
REQUIRE(test.expectedStackOutput("10 100 *", "1000"));
REQUIRE(test.expectedStackOutput("10 100*", "1000"));
REQUIRE(test.expectedStackOutput("5.5 2.2*", "12.1"));
}
SECTION("Method: divide()")
{
REQUIRE(test.expectedStackOutput("16 4 2 /", "2"));
REQUIRE(test.expectedStackOutput("/", "8"));
REQUIRE(test.expectedOutput("c", ""));
REQUIRE(test.expectedStackOutput("2 5 /", "0.4"));
REQUIRE(test.expectedStackOutput("9 3 7 /", "0.428571"));
REQUIRE(test.expectedStackOutput("-1 /", "-0.428571"));
REQUIRE(test.expectedStackOutput("-1 / ", "0.428571"));
REQUIRE(test.expectedStackOutput("100 10 /", "10"));
REQUIRE(test.expectedStackOutput("100 10/", "10"));
REQUIRE(test.expectedStackOutput("/", "1"));
REQUIRE(test.expectedStackOutput("/", "0.428571"));
REQUIRE(test.expectedStackOutput("/", "21"));
REQUIRE(test.expectedStackOutput("/", "0.0190476"));
REQUIRE(test.expectedStackOutput("/", "0.0190476"));
REQUIRE(test.expectError("/"));
}
SECTION("Method: mod()")
{
REQUIRE(test.expectedStackOutput("16 8 6 %", "2"));
REQUIRE(test.expectedStackOutput("%", "0"));
REQUIRE(test.expectedOutput("c", ""));
REQUIRE(test.expectError("%"));
REQUIRE(test.expectedStackOutput("10 1 %", "0"));
REQUIRE(test.expectedStackOutput("10 2 %", "0"));
REQUIRE(test.expectedStackOutput("10 3 %", "1"));
REQUIRE(test.expectedStackOutput("10 4 %", "2"));
REQUIRE(test.expectedStackOutput("10 5 %", "0"));
REQUIRE(test.expectedStackOutput("10 6 %", "4"));
REQUIRE(test.expectedStackOutput("10 7 %", "3"));
REQUIRE(test.expectedStackOutput("10 8 %", "2"));
REQUIRE(test.expectedStackOutput("10 9 %", "1"));
REQUIRE(test.expectedStackOutput("10 10 %", "0"));
REQUIRE(test.expectedStackOutput("100 70 %", "30"));
REQUIRE(test.expectedStackOutput("100 70%", "30"));
}
SECTION("Method: exp()")
{
REQUIRE(test.expectedStackOutput("10 2 ^", "100"));
REQUIRE(test.expectedStackOutput("10 2 2 ^", "4"));
REQUIRE(test.expectedStackOutput("^", "10000"));
REQUIRE(test.expectedStackOutput("-10 2 ^", "100"));
REQUIRE(test.expectedStackOutput("-10 3 ^", "-1000"));
REQUIRE(test.expectedStackOutput("-10 3^", "-1000"));
REQUIRE(test.expectedStackOutput("0^", "1"));
REQUIRE(test.expectedStackOutput("^", "-1000"));
REQUIRE(test.expectedStackOutput("^", "0"));
REQUIRE(test.expectedStackOutput("^", "1"));
REQUIRE(test.expectedStackOutput("^", "100"));
REQUIRE(test.expectError("^"));
REQUIRE(test.expectedOutput("c", ""));
REQUIRE(test.expectError("^"));
REQUIRE(test.expectedStackOutput("100 100^", "1e+200"));
}
SECTION("Method: neg()")
{
REQUIRE(test.expectedStackOutput("-1000", "-1000"));
REQUIRE(test.expectedStackOutput("M", "1000"));
REQUIRE(test.getStackOutput("-1000 -1*") == "1000");
REQUIRE(test.expectedStackOutput("M", "-1000"));
REQUIRE(test.expectedStackOutput("-4/", "250"));
REQUIRE(test.expectedStackOutput("m", "-250"));
REQUIRE(test.expectedStackOutput("-2*", "500"));
REQUIRE(test.expectedStackOutput("m", "-500"));
REQUIRE(test.expectedOutput("c", ""));
REQUIRE(test.expectError("m"));
REQUIRE(test.expectError("M"));
}
/*
SECTION("Method: rotateDown()")
{
REQUIRE(test.expectedInputOutput("100 200", "200"));
REQUIRE(test.expectedInputOutput("D", "100"));
REQUIRE(test.expectedInputOutput("D", "200"));
REQUIRE(test.expectedInputOutput("d", "100"));
REQUIRE(test.expectedInputOutput("d", "200"));
REQUIRE(test.expectedInputOutput("c", ""));
REQUIRE(test.expectedInputOutput("D", "<<error>>"));
REQUIRE(test.expectedInputOutput("c", ""));
REQUIRE(test.expectedInputOutput("d", "<<error>>"));
}
SECTION("Method: rotateUp()")
{
REQUIRE(test.expectedInputOutput("300 500", "500"));
REQUIRE(test.expectedInputOutput("U", "300"));
REQUIRE(test.expectedInputOutput("U", "500"));
REQUIRE(test.expectedInputOutput("u", "300"));
REQUIRE(test.expectedInputOutput("u", "500"));
REQUIRE(test.expectedInputOutput("c", ""));
REQUIRE(test.expectedInputOutput("U", "<<error>>"));
REQUIRE(test.expectedInputOutput("c", ""));
REQUIRE(test.expectedInputOutput("u", "<<error>>"));
}
SECTION("Methods: saveToFile(), loadProgram(), recordProgram(), runProgram()")
{
REQUIRE(test.expectedInputOutput("R", "<<error>>"));
REQUIRE(test.expectedInputOutput("F", "<<error>>"));
REQUIRE(test.expectedInputOutput("p", "0>"));
REQUIRE(test.expectedInputOutput("5 10 +", "1>"));
REQUIRE(test.expectedInputOutput("20 30 -", "2>"));
//REQUIRE(test.expectedInputOutput("P", ""));
//REQUIRE(test.expectedInputOutput("f", "Enter a filename:"));
REQUIRE(test.expectedInputOutput("test1", ""));
//REQUIRE(test.expectedInputOutput("l", "Enter a filename:"));
REQUIRE(test.expectedInputOutput("test", "error"));
//REQUIRE(test.expectedInputOutput("L", "Enter a filename:"));
REQUIRE(test.expectedInputOutput("test1", ""));
REQUIRE(test.expectedInputOutput("r", "-10"));
REQUIRE(test.expectedInputOutput("c", ""));
}
SECTION("Methods: getReg(), setReg()")
{
REQUIRE(test.expectedInputOutput("s0", "<<error>>"));
REQUIRE(test.expectedInputOutput("S1", "<<error>>"));
REQUIRE(test.expectedInputOutput("s5", "<<error>>"));
REQUIRE(test.expectedInputOutput("G0", "0"));
REQUIRE(test.expectedInputOutput("g1", "0"));
REQUIRE(test.expectedInputOutput("G5", "0"));
REQUIRE(test.expectedInputOutput("1000", "1000"));
REQUIRE(test.expectedInputOutput("s5", "1000"));
REQUIRE(test.expectedInputOutput("2.5", "2.5"));
REQUIRE(test.expectedInputOutput("S0", "2.5"));
REQUIRE(test.expectedInputOutput("G5", "1000"));
REQUIRE(test.expectedInputOutput("g0", "2.5"));
}
// */
}
//*/<commit_msg>uncomment rotate down tests<commit_after>
//--------------------------------------------------
// file: RPN+UnitTests.cpp
//-------------------------------------------------
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "RPNCalc.h"
#include "RPNTestHelper.h"
using namespace P4_RPNCALC;
TEST_CASE("Operation Methods")
{
RPNTestHelper test;
SECTION("Sanity Tests") {
for (int n = 0; n < 100; n++) {
REQUIRE(test.expectedStackOutput(to_string(n), to_string(n)));
}
}
SECTION("Method: clearAll()")
{
REQUIRE(test.expectedStackOutput("50", "50"));
REQUIRE(test.expectedOutput("c", ""));
REQUIRE(test.expectedStackOutput("50 100 +", "150"));
REQUIRE(test.expectedOutput("c", ""));
REQUIRE(test.expectedStackOutput("50 100 + 200", "200"));
REQUIRE(test.expectedOutput("c", ""));
REQUIRE(test.expectedStackOutput("50", "50"));
REQUIRE(test.expectedOutput("C", ""));
REQUIRE(test.expectedStackOutput("50 100 +", "150"));
REQUIRE(test.expectedOutput("C", ""));
REQUIRE(test.expectedStackOutput("50 100 + 200", "200"));
REQUIRE(test.expectedOutput("C", ""));
}
SECTION("Method: clearEntry()")
{
REQUIRE(test.expectedStackOutput("50", "50"));
REQUIRE(test.expectedOutput("ce", ""));
REQUIRE(test.expectedStackOutput("50 100 +", "150"));
REQUIRE(test.expectedOutput("ce", ""));
REQUIRE(test.expectedStackOutput("50 100 + 200", "200"));
REQUIRE(test.expectedStackOutput("ce", "150"));
REQUIRE(test.expectedOutput("ce", ""));
REQUIRE(test.expectedStackOutput("50", "50"));
REQUIRE(test.expectedOutput("CE", ""));
REQUIRE(test.expectedStackOutput("50 100 +", "150"));
REQUIRE(test.expectedOutput("CE", ""));
REQUIRE(test.expectedStackOutput("50 100 + 200", "200"));
REQUIRE(test.expectedStackOutput("CE", "150"));
REQUIRE(test.expectedOutput("CE", ""));
}
SECTION("Method: add()")
{
REQUIRE(test.expectedStackOutput("3 5+", "8"));
REQUIRE(test.expectedStackOutput("2 4 3 +", "7"));
REQUIRE(test.expectedOutput("c", ""));
REQUIRE(test.expectedStackOutput("3 4 + 6", "6"));
REQUIRE(test.expectedStackOutput("4 +", "10"));
REQUIRE(test.expectedStackOutput("-12 +", "-2"));
REQUIRE(test.expectedStackOutput("5 +", "3"));
REQUIRE(test.expectedStackOutput("3 +", "6"));
REQUIRE(test.getStackOutput("10 100 +") == "110");
REQUIRE(test.getStackOutput("10 100+") == "110");
}
SECTION("Method: combinations of add() & subtract()")
{
REQUIRE(test.getStackOutput("4.4 5.5 + 60 -") == "-50.1");
REQUIRE(test.expectedStackOutput("4.4 5.5 - 60 +", "58.9"));
REQUIRE(test.expectedStackOutput("40 50 + 60 -", "30"));
REQUIRE(test.expectedStackOutput("40 50 - 60 +", "50"));
REQUIRE(test.expectedStackOutput("40 50 60 + -", "-70"));
REQUIRE(test.expectedStackOutput("40 50 60 - +", "30"));
REQUIRE(test.expectedStackOutput("-40 -50 + 60 -", "-150"));
REQUIRE(test.expectedStackOutput("-40 -50 + -60 -", "-30"));
REQUIRE(test.expectedStackOutput("-40 -50 - 60 +", "70"));
REQUIRE(test.expectedStackOutput("-40 -50 - -60 +", "-50"));
}
SECTION("Method: subtract()")
{
REQUIRE(test.expectedStackOutput("5 6 -", "-1"));
REQUIRE(test.expectedStackOutput("3 9 4 -", "5"));
REQUIRE(test.expectedStackOutput("-", "-2"));
REQUIRE(test.expectedOutput("c", ""));
REQUIRE(test.expectedStackOutput("-1 5 -", "-6"));
REQUIRE(test.expectedStackOutput("10 100 -", "-90"));
REQUIRE(test.expectedStackOutput("10 100-", "-90"));
REQUIRE(test.expectedStackOutput("-", "0"));
}
SECTION("Method: multiply()")
{
REQUIRE(test.expectedStackOutput("3 9 7 2 4 *", "8"));
REQUIRE(test.expectedStackOutput("*", "56"));
REQUIRE(test.expectedStackOutput("*", "504"));
REQUIRE(test.expectedStackOutput("*", "1512"));
REQUIRE(test.expectError("*"));
REQUIRE(test.getOutput("c") == "");
REQUIRE(test.expectedStackOutput("-4 -6 *", "24"));
REQUIRE(test.expectedStackOutput("-2 *", "-48"));
REQUIRE(test.expectedStackOutput("10 100 *", "1000"));
REQUIRE(test.expectedStackOutput("10 100*", "1000"));
REQUIRE(test.expectedStackOutput("5.5 2.2*", "12.1"));
}
SECTION("Method: divide()")
{
REQUIRE(test.expectedStackOutput("16 4 2 /", "2"));
REQUIRE(test.expectedStackOutput("/", "8"));
REQUIRE(test.expectedOutput("c", ""));
REQUIRE(test.expectedStackOutput("2 5 /", "0.4"));
REQUIRE(test.expectedStackOutput("9 3 7 /", "0.428571"));
REQUIRE(test.expectedStackOutput("-1 /", "-0.428571"));
REQUIRE(test.expectedStackOutput("-1 / ", "0.428571"));
REQUIRE(test.expectedStackOutput("100 10 /", "10"));
REQUIRE(test.expectedStackOutput("100 10/", "10"));
REQUIRE(test.expectedStackOutput("/", "1"));
REQUIRE(test.expectedStackOutput("/", "0.428571"));
REQUIRE(test.expectedStackOutput("/", "21"));
REQUIRE(test.expectedStackOutput("/", "0.0190476"));
REQUIRE(test.expectedStackOutput("/", "0.0190476"));
REQUIRE(test.expectError("/"));
}
SECTION("Method: mod()")
{
REQUIRE(test.expectedStackOutput("16 8 6 %", "2"));
REQUIRE(test.expectedStackOutput("%", "0"));
REQUIRE(test.expectedOutput("c", ""));
REQUIRE(test.expectError("%"));
REQUIRE(test.expectedStackOutput("10 1 %", "0"));
REQUIRE(test.expectedStackOutput("10 2 %", "0"));
REQUIRE(test.expectedStackOutput("10 3 %", "1"));
REQUIRE(test.expectedStackOutput("10 4 %", "2"));
REQUIRE(test.expectedStackOutput("10 5 %", "0"));
REQUIRE(test.expectedStackOutput("10 6 %", "4"));
REQUIRE(test.expectedStackOutput("10 7 %", "3"));
REQUIRE(test.expectedStackOutput("10 8 %", "2"));
REQUIRE(test.expectedStackOutput("10 9 %", "1"));
REQUIRE(test.expectedStackOutput("10 10 %", "0"));
REQUIRE(test.expectedStackOutput("100 70 %", "30"));
REQUIRE(test.expectedStackOutput("100 70%", "30"));
}
SECTION("Method: exp()")
{
REQUIRE(test.expectedStackOutput("10 2 ^", "100"));
REQUIRE(test.expectedStackOutput("10 2 2 ^", "4"));
REQUIRE(test.expectedStackOutput("^", "10000"));
REQUIRE(test.expectedStackOutput("-10 2 ^", "100"));
REQUIRE(test.expectedStackOutput("-10 3 ^", "-1000"));
REQUIRE(test.expectedStackOutput("-10 3^", "-1000"));
REQUIRE(test.expectedStackOutput("0^", "1"));
REQUIRE(test.expectedStackOutput("^", "-1000"));
REQUIRE(test.expectedStackOutput("^", "0"));
REQUIRE(test.expectedStackOutput("^", "1"));
REQUIRE(test.expectedStackOutput("^", "100"));
REQUIRE(test.expectError("^"));
REQUIRE(test.expectedOutput("c", ""));
REQUIRE(test.expectError("^"));
REQUIRE(test.expectedStackOutput("100 100^", "1e+200"));
}
SECTION("Method: neg()")
{
REQUIRE(test.expectedStackOutput("-1000", "-1000"));
REQUIRE(test.expectedStackOutput("M", "1000"));
REQUIRE(test.getStackOutput("-1000 -1*") == "1000");
REQUIRE(test.expectedStackOutput("M", "-1000"));
REQUIRE(test.expectedStackOutput("-4/", "250"));
REQUIRE(test.expectedStackOutput("m", "-250"));
REQUIRE(test.expectedStackOutput("-2*", "500"));
REQUIRE(test.expectedStackOutput("m", "-500"));
REQUIRE(test.expectedOutput("c", ""));
REQUIRE(test.expectError("m"));
REQUIRE(test.expectError("M"));
}
SECTION("Method: rotateDown()")
{
REQUIRE(test.expectedStackOutput("100 200", "200"));
REQUIRE(test.expectedStackOutput("D", "100"));
REQUIRE(test.expectedStackOutput("D", "200"));
REQUIRE(test.expectedStackOutput("d", "100"));
REQUIRE(test.expectedStackOutput("d", "200"));
REQUIRE(test.expectedOutput("c", ""));
REQUIRE(test.expectError("D"));
REQUIRE(test.expectError("d"));
}
/*
SECTION("Method: rotateUp()")
{
REQUIRE(test.expectedInputOutput("300 500", "500"));
REQUIRE(test.expectedInputOutput("U", "300"));
REQUIRE(test.expectedInputOutput("U", "500"));
REQUIRE(test.expectedInputOutput("u", "300"));
REQUIRE(test.expectedInputOutput("u", "500"));
REQUIRE(test.expectedInputOutput("c", ""));
REQUIRE(test.expectedInputOutput("U", "<<error>>"));
REQUIRE(test.expectedInputOutput("c", ""));
REQUIRE(test.expectedInputOutput("u", "<<error>>"));
}
SECTION("Methods: saveToFile(), loadProgram(), recordProgram(), runProgram()")
{
REQUIRE(test.expectedInputOutput("R", "<<error>>"));
REQUIRE(test.expectedInputOutput("F", "<<error>>"));
REQUIRE(test.expectedInputOutput("p", "0>"));
REQUIRE(test.expectedInputOutput("5 10 +", "1>"));
REQUIRE(test.expectedInputOutput("20 30 -", "2>"));
//REQUIRE(test.expectedInputOutput("P", ""));
//REQUIRE(test.expectedInputOutput("f", "Enter a filename:"));
REQUIRE(test.expectedInputOutput("test1", ""));
//REQUIRE(test.expectedInputOutput("l", "Enter a filename:"));
REQUIRE(test.expectedInputOutput("test", "error"));
//REQUIRE(test.expectedInputOutput("L", "Enter a filename:"));
REQUIRE(test.expectedInputOutput("test1", ""));
REQUIRE(test.expectedInputOutput("r", "-10"));
REQUIRE(test.expectedInputOutput("c", ""));
}
SECTION("Methods: getReg(), setReg()")
{
REQUIRE(test.expectedInputOutput("s0", "<<error>>"));
REQUIRE(test.expectedInputOutput("S1", "<<error>>"));
REQUIRE(test.expectedInputOutput("s5", "<<error>>"));
REQUIRE(test.expectedInputOutput("G0", "0"));
REQUIRE(test.expectedInputOutput("g1", "0"));
REQUIRE(test.expectedInputOutput("G5", "0"));
REQUIRE(test.expectedInputOutput("1000", "1000"));
REQUIRE(test.expectedInputOutput("s5", "1000"));
REQUIRE(test.expectedInputOutput("2.5", "2.5"));
REQUIRE(test.expectedInputOutput("S0", "2.5"));
REQUIRE(test.expectedInputOutput("G5", "1000"));
REQUIRE(test.expectedInputOutput("g0", "2.5"));
}
// */
}
//*/<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////
//
// General package
//
// ---------------------------------------------------------
//
// AUTHOR: Miguel Ramos Pernas
// e-mail: miguel.ramos.pernas@cern.ch
//
// Last update: 19/10/2017
//
// ---------------------------------------------------------
//
// Description:
//
// Definition of the main class to print information into
// a terminal/file. It can be formatted so one can put
// colors and change the style of the words being
// displayed.
//
// ---------------------------------------------------------
////////////////////////////////////////////////////////////
#ifndef EXCEPTIONS_HPP
#define EXCEPTIONS_HPP
#include "Messenger.hpp"
#include <exception>
#include <string>
#include <sstream>
//_______________________________________________________________________________
namespace isis {
//_______________________________________________________________________________
// Base class to represent an exception
class BaseException : public std::exception {
public:
// Constructor given the string to be printed and the message code
BaseException( const std::string &info, const MsgCode &st = MsgCode::Error ) {
std::stringstream ss;
Messenger msg(st, &ss);
msg << info << IEndMsg;
fWhat = ss.str();
}
// Destructor. The output is not printed if the "fIgnore" flag is true.
virtual ~BaseException() { if ( !fIgnore ) std::cout << this->what(); }
// Ignore the output of this exception
void ignore() { fIgnore = true; }
const char* msg() {
this->ignore();
return this->what();
}
protected:
// Redefinition of the method from "std::exception"
const char* what() const throw() { return fWhat.c_str(); }
// Store what is going to be printed
std::string fWhat;
// Flag to ignore the output of this exception
bool fIgnore = false;
};
//_______________________________________________________________________________
// Represent an exception to be thrown when an input argument is invalid
class InvalidArgument : public BaseException {
public:
// Constructor given the invalid argument and the message code
InvalidArgument( const std::string &arg, const MsgCode &st = MsgCode::Error ) :
BaseException(std::string{"Invalid argument \""} + arg + std::string{"\""}, st) { }
};
//_______________________________________________________________________________
// Represent an exception to be thrown when an object could not be found
class NotFound : public BaseException {
public:
// Constructor given the object name, the argument and the message code
NotFound( const std::string &objname, const std::string &arg, const MsgCode &st = MsgCode::Error ) :
BaseException(std::string{"Unable to find "} + objname +
std::string{"\""} + arg + std::string{"\""}, st) { }
};
}
#endif
<commit_msg>Fix issue with one print from the exceptions<commit_after>////////////////////////////////////////////////////////////
//
// General package
//
// ---------------------------------------------------------
//
// AUTHOR: Miguel Ramos Pernas
// e-mail: miguel.ramos.pernas@cern.ch
//
// Last update: 19/10/2017
//
// ---------------------------------------------------------
//
// Description:
//
// Definition of the main class to print information into
// a terminal/file. It can be formatted so one can put
// colors and change the style of the words being
// displayed.
//
// ---------------------------------------------------------
////////////////////////////////////////////////////////////
#ifndef EXCEPTIONS_HPP
#define EXCEPTIONS_HPP
#include "Messenger.hpp"
#include <exception>
#include <string>
#include <sstream>
//_______________________________________________________________________________
namespace isis {
//_______________________________________________________________________________
// Base class to represent an exception
class BaseException : public std::exception {
public:
// Constructor given the string to be printed and the message code
BaseException( const std::string &info, const MsgCode &st = MsgCode::Error ) {
std::stringstream ss;
Messenger msg(st, &ss);
msg << info << IEndMsg;
fWhat = ss.str();
}
// Destructor. The output is not printed if the "fIgnore" flag is true.
virtual ~BaseException() { if ( !fIgnore ) std::cout << this->what(); }
// Ignore the output of this exception
void ignore() { fIgnore = true; }
const char* msg() {
this->ignore();
return this->what();
}
protected:
// Redefinition of the method from "std::exception"
const char* what() const throw() { return fWhat.c_str(); }
// Store what is going to be printed
std::string fWhat;
// Flag to ignore the output of this exception
bool fIgnore = false;
};
//_______________________________________________________________________________
// Represent an exception to be thrown when an input argument is invalid
class InvalidArgument : public BaseException {
public:
// Constructor given the invalid argument and the message code
InvalidArgument( const std::string &arg, const MsgCode &st = MsgCode::Error ) :
BaseException(std::string{"Invalid argument \""} + arg + std::string{"\""}, st) { }
};
//_______________________________________________________________________________
// Represent an exception to be thrown when an object could not be found
class NotFound : public BaseException {
public:
// Constructor given the object name, the argument and the message code
NotFound( const std::string &objname, const std::string &arg, const MsgCode &st = MsgCode::Error ) :
BaseException(std::string{"Unable to find "} + objname +
std::string{" \""} + arg + std::string{"\""}, st) { }
};
}
#endif
<|endoftext|>
|
<commit_before>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2014 Paul Asmuth, Google Inc.
*
* 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 <functional>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <thread>
#include <unistd.h>
#include "fnord-base/exception.h"
#include "fnord-base/inspect.h"
#include "fnord-base/thread/eventloop.h"
namespace fnord {
namespace thread {
EventLoop::EventLoop() :
max_fd_(1),
running_(true),
threadid_(std::this_thread::get_id()),
callbacks_(FD_SETSIZE + 1, nullptr) {
FD_ZERO(&op_read_);
FD_ZERO(&op_write_);
FD_ZERO(&op_error_);
setupRunQWakeupPipe();
}
EventLoop::~EventLoop() {
close(runq_wakeup_pipe_[0]);
close(runq_wakeup_pipe_[1]);
}
void EventLoop::setupRunQWakeupPipe() {
if (pipe(runq_wakeup_pipe_) < 0) {
RAISE_ERRNO(kIOError, "pipe() failed");
}
int flags = fcntl(runq_wakeup_pipe_[0], F_GETFL, 0);
flags |= O_NONBLOCK;
if (fcntl(runq_wakeup_pipe_[0], F_SETFL, flags) != 0) {
RAISE_ERRNO(kIOError, "fnctl(%i) failed", runq_wakeup_pipe_[0]);
}
FD_SET(runq_wakeup_pipe_[0], &op_read_);
if (runq_wakeup_pipe_[0] > max_fd_) {
max_fd_ = runq_wakeup_pipe_[0];
}
callbacks_[runq_wakeup_pipe_[0]] = std::bind(&EventLoop::onRunQWakeup, this);
}
void EventLoop::run(std::function<void()> task) {
if (std::this_thread::get_id() == threadid_) {
task();
} else {
appendToRunQ(task);
}
}
void EventLoop::appendToRunQ(std::function<void()> task) {
std::unique_lock<std::mutex> lk(runq_mutex_);
runq_.emplace_back(task);
lk.unlock();
wakeup();
}
void EventLoop::runOnReadable(std::function<void()> task, int fd) {
if (std::this_thread::get_id() != threadid_) {
appendToRunQ([this, task, fd] {
runOnReadable(task, fd);
});
return;
}
if (fd > FD_SETSIZE) {
RAISEF(kIOError, "fd is too large: $0, max is $1", fd, FD_SETSIZE);
}
if (fd > max_fd_) {
max_fd_ = fd;
}
FD_SET(fd, &op_read_);
FD_SET(fd, &op_error_);
callbacks_[fd] = task;
}
void EventLoop::runOnWritable(std::function<void()> task, int fd) {
if (std::this_thread::get_id() != threadid_) {
appendToRunQ([this, task, fd] {
runOnWritable(task, fd);
});
return;
}
if (fd > FD_SETSIZE) {
RAISEF(kIOError, "fd is too large: $0, max is $1", fd, FD_SETSIZE);
}
if (fd > max_fd_) {
max_fd_ = fd;
}
FD_SET(fd, &op_write_);
FD_SET(fd, &op_error_);
callbacks_[fd] = task;
}
void EventLoop::poll() {
fd_set op_read, op_write, op_error;
memcpy(&op_read, &op_read_, sizeof(fd_set));
memcpy(&op_write, &op_write_, sizeof(fd_set));
memcpy(&op_error, &op_error_, sizeof(fd_set));
int res = select(max_fd_ + 1, &op_read, &op_write, &op_error, NULL);
if (res == 0) {
return;
}
if (res == -1) {
if (errno == EINTR) {
return;
}
RAISE_ERRNO(kIOError, "select() failed");
}
for (int fd = 0; fd <= max_fd_; fd++) {
if (FD_ISSET(fd, &op_read)) {
FD_CLR(fd, &op_read_);
FD_CLR(fd, &op_error_);
callbacks_[fd]();
}
else if (FD_ISSET(fd, &op_write)) {
FD_CLR(fd, &op_write_);
FD_CLR(fd, &op_error_);
callbacks_[fd]();
}
}
}
void EventLoop::wakeup() {
write(runq_wakeup_pipe_[1], "\x0", 1);
}
void EventLoop::runOnWakeup(
std::function<void()> task,
Wakeup* wakeup,
long wakeup_generation) {
wakeup->onWakeup(wakeup_generation, [this, task] {
this->run(task);
});
}
void EventLoop::onRunQWakeup() {
FD_SET(runq_wakeup_pipe_[0], &op_read_);
static char devnull[512];
while (read(runq_wakeup_pipe_[0], devnull, sizeof(devnull)) > 0);
std::list<std::function<void()>> tasks;
std::unique_lock<std::mutex> lk(runq_mutex_);
tasks.splice(tasks.begin(), runq_);
lk.unlock();
for (const auto& task : tasks) {
task();
}
}
void EventLoop::run() {
threadid_ = std::this_thread::get_id();
while (running_.load()) {
poll();
}
}
void EventLoop::shutdown() {
running_ = false;
wakeup();
}
}
}
<commit_msg>ugly ugly hack<commit_after>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2014 Paul Asmuth, Google Inc.
*
* 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 <functional>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <thread>
#include <unistd.h>
#include "fnord-base/exception.h"
#include "fnord-base/inspect.h"
#include "fnord-base/thread/eventloop.h"
namespace fnord {
namespace thread {
EventLoop::EventLoop() :
max_fd_(1),
running_(true),
threadid_(std::this_thread::get_id()),
callbacks_(FD_SETSIZE + 1, nullptr) {
FD_ZERO(&op_read_);
FD_ZERO(&op_write_);
FD_ZERO(&op_error_);
setupRunQWakeupPipe();
}
EventLoop::~EventLoop() {
close(runq_wakeup_pipe_[0]);
close(runq_wakeup_pipe_[1]);
}
void EventLoop::setupRunQWakeupPipe() {
if (pipe(runq_wakeup_pipe_) < 0) {
RAISE_ERRNO(kIOError, "pipe() failed");
}
int flags = fcntl(runq_wakeup_pipe_[0], F_GETFL, 0);
flags |= O_NONBLOCK;
if (fcntl(runq_wakeup_pipe_[0], F_SETFL, flags) != 0) {
RAISE_ERRNO(kIOError, "fnctl(%i) failed", runq_wakeup_pipe_[0]);
}
FD_SET(runq_wakeup_pipe_[0], &op_read_);
if (runq_wakeup_pipe_[0] > max_fd_) {
max_fd_ = runq_wakeup_pipe_[0];
}
callbacks_[runq_wakeup_pipe_[0]] = std::bind(&EventLoop::onRunQWakeup, this);
}
void EventLoop::run(std::function<void()> task) {
if (std::this_thread::get_id() == threadid_) {
task();
} else {
appendToRunQ(task);
}
}
void EventLoop::appendToRunQ(std::function<void()> task) {
std::unique_lock<std::mutex> lk(runq_mutex_);
runq_.emplace_back(task);
lk.unlock();
wakeup();
}
void EventLoop::runOnReadable(std::function<void()> task, int fd) {
if (std::this_thread::get_id() != threadid_) {
appendToRunQ([this, task, fd] {
runOnReadable(task, fd);
});
return;
}
if (fd > FD_SETSIZE) {
RAISEF(kIOError, "fd is too large: $0, max is $1", fd, FD_SETSIZE);
}
if (fd > max_fd_) {
max_fd_ = fd;
}
FD_SET(fd, &op_read_);
FD_SET(fd, &op_error_);
callbacks_[fd] = task;
}
void EventLoop::runOnWritable(std::function<void()> task, int fd) {
if (std::this_thread::get_id() != threadid_) {
appendToRunQ([this, task, fd] {
runOnWritable(task, fd);
});
return;
}
if (fd > FD_SETSIZE) {
RAISEF(kIOError, "fd is too large: $0, max is $1", fd, FD_SETSIZE);
}
if (fd > max_fd_) {
max_fd_ = fd;
}
FD_SET(fd, &op_write_);
FD_SET(fd, &op_error_);
callbacks_[fd] = task;
}
void EventLoop::poll() {
fd_set op_read, op_write, op_error;
memcpy(&op_read, &op_read_, sizeof(fd_set));
memcpy(&op_write, &op_write_, sizeof(fd_set));
memcpy(&op_error, &op_error_, sizeof(fd_set));
int res = select(max_fd_ + 1, &op_read, &op_write, &op_error, NULL);
if (res == 0) {
return;
}
if (res == -1) {
if (errno == EINTR) {
return;
}
RAISE_ERRNO(kIOError, "select() failed");
}
for (int fd = 0; fd <= max_fd_; fd++) {
if (FD_ISSET(fd, &op_read)) {
FD_CLR(fd, &op_read_);
FD_CLR(fd, &op_error_);
callbacks_[fd]();
}
else if (FD_ISSET(fd, &op_write)) {
FD_CLR(fd, &op_write_);
FD_CLR(fd, &op_error_);
callbacks_[fd]();
}
}
}
void EventLoop::wakeup() {
write(runq_wakeup_pipe_[1], "\x0", 1);
}
void EventLoop::runOnWakeup(
std::function<void()> task,
Wakeup* wakeup,
long wakeup_generation) {
wakeup->onWakeup(wakeup_generation, [this, task] {
this->run(task);
});
}
void EventLoop::onRunQWakeup() {
FD_SET(runq_wakeup_pipe_[0], &op_read_);
static char devnull[512];
while (read(runq_wakeup_pipe_[0], devnull, sizeof(devnull)) > 0);
std::list<std::function<void()>> tasks;
std::unique_lock<std::mutex> lk(runq_mutex_);
tasks.splice(tasks.begin(), runq_);
lk.unlock();
for (const auto& task : tasks) {
task();
}
}
void EventLoop::run() {
threadid_ = std::this_thread::get_id();
while (running_.load()) {
poll();
}
}
void EventLoop::shutdown() {
usleep(10000); // FIXPAUL hack!!!!
running_ = false;
wakeup();
}
}
}
<|endoftext|>
|
<commit_before>/*
* EMULAB-COPYRIGHT
* Copyright (c) 2006 University of Utah and the Flux Group.
* All rights reserved.
*/
#include "UdpMaxDelaySensor.h"
#include "CommandOutput.h"
using namespace std;
UdpMaxDelaySensor::UdpMaxDelaySensor(UdpPacketSensor const *udpPacketSensorVal, UdpMinDelaySensor const *minDelaySensorVal, UdpLossSensor const *lossSensorVal)
: maxDelay(0),sentDelay(0),
packetHistory(udpPacketSensorVal),
minDelaySensor(minDelaySensorVal),
lossSensor(lossSensorVal)
{
}
UdpMaxDelaySensor::~UdpMaxDelaySensor()
{
}
void UdpMaxDelaySensor::localSend(PacketInfo *packet)
{
}
void UdpMaxDelaySensor::localAck(PacketInfo *packet)
{
// This is a re-ordered ACK or a corrupted packet - don't do anything
// with it - just return.
// If this packet is ACKing a packet that we lost due to libpcap send loss,
// dont use this packet timestamp for RTT calculations.
if( packetHistory->isAckValid() == false || packetHistory->isAckFake() == true)
return;
unsigned short int seqNum = *(unsigned short int *)(packet->payload + 1);
unsigned long long oneWayQueueDelay;
vector<UdpPacketInfo>::iterator vecIterator;
vector<UdpPacketInfo> ackedPackets = packetHistory->getAckedPackets();
vecIterator = find_if(ackedPackets.begin(), ackedPackets.end(), bind2nd(equalSeqNum(), seqNum));
if(vecIterator == ackedPackets.end())
{
logWrite(ERROR,"UdpMaxDelay: Cannot find seqNum=%d in AckedPacketList", seqNum);
return;
}
unsigned long long timeStamp = packet->packetTime.toMicroseconds();
// Find the one way RTT for this packet.
oneWayQueueDelay = (timeStamp - (*vecIterator).timeStamp)/2;
// Scale the value of one way RTT, so that it is correct for a transmission
// size of 1518 bytes.
// We lost this packet size details due to loss in libpcap, use the
// size echoed in the ACK packet - this does not included the header
// overhead for the packet - we assume that the packet on the reverse path
// has the same overhead length as the original packet.
oneWayQueueDelay = ( oneWayQueueDelay )*1518 / ((*vecIterator).packetSize);
if(oneWayQueueDelay < minDelaySensor->getMinDelay())
{
logWrite(ERROR,"Incorrect oneWayQueueDelay value = %llu, minDelay = %llu, seqNum=%d, SENDTS=%llu,RECVTS=%llu", oneWayQueueDelay, minDelaySensor->getMinDelay(),seqNum, (*vecIterator).timeStamp, timeStamp);
return;
}
// Find the queuing delay for this packet, by subtracting the
// one way minimum delay from the above value.
oneWayQueueDelay = oneWayQueueDelay - minDelaySensor->getMinDelay();
if(oneWayQueueDelay > 90000000)
{
logWrite(ERROR,"Incorrect oneWayQueueDelay value = %llu, minDelay = %llu, seqNum=%d, SENDTS=%llu,RECVTS=%llu", oneWayQueueDelay, minDelaySensor->getMinDelay(),seqNum, (*vecIterator).timeStamp, timeStamp);
return;
}
// Set this as the new maximum one way queuing delay.
if(oneWayQueueDelay > maxDelay)
maxDelay = oneWayQueueDelay;
// Send an event message to the monitor to change the value of maximum one way delay.
if(lossSensor->getPacketLoss() > 0)
{
// Report the maximum delay
ostringstream messageBuffer;
if(maxDelay > sentDelay)
{
messageBuffer<<"MAXINQ="<<(maxDelay+minDelaySensor->getMinDelay())/1000;
global::output->eventMessage(messageBuffer.str(), packet->elab);
sentDelay = maxDelay;
}
logWrite(SENSOR,"VALUE::New Max Delay = %llu",maxDelay);
}
logWrite(SENSOR,"MAXD:TIME=%llu,MAXD=%llu",timeStamp,maxDelay);
logWrite(SENSOR,"ACTUAL_MAXD:TIME=%llu,ACTUAL_MAXD=%llu",timeStamp,oneWayQueueDelay);
}
<commit_msg>A little tweak for the better - removed scaling of max delay values (which used to depend on packet size).<commit_after>/*
* EMULAB-COPYRIGHT
* Copyright (c) 2006 University of Utah and the Flux Group.
* All rights reserved.
*/
#include "UdpMaxDelaySensor.h"
#include "CommandOutput.h"
using namespace std;
UdpMaxDelaySensor::UdpMaxDelaySensor(UdpPacketSensor const *udpPacketSensorVal, UdpMinDelaySensor const *minDelaySensorVal, UdpLossSensor const *lossSensorVal)
: maxDelay(0),sentDelay(0),
packetHistory(udpPacketSensorVal),
minDelaySensor(minDelaySensorVal),
lossSensor(lossSensorVal)
{
}
UdpMaxDelaySensor::~UdpMaxDelaySensor()
{
}
void UdpMaxDelaySensor::localSend(PacketInfo *packet)
{
}
void UdpMaxDelaySensor::localAck(PacketInfo *packet)
{
// This is a re-ordered ACK or a corrupted packet - don't do anything
// with it - just return.
// If this packet is ACKing a packet that we lost due to libpcap send loss,
// dont use this packet timestamp for RTT calculations.
if( packetHistory->isAckValid() == false || packetHistory->isAckFake() == true)
return;
unsigned short int seqNum = *(unsigned short int *)(packet->payload + 1);
unsigned long long oneWayQueueDelay;
vector<UdpPacketInfo>::iterator vecIterator;
vector<UdpPacketInfo> ackedPackets = packetHistory->getAckedPackets();
vecIterator = find_if(ackedPackets.begin(), ackedPackets.end(), bind2nd(equalSeqNum(), seqNum));
if(vecIterator == ackedPackets.end())
{
logWrite(ERROR,"UdpMaxDelay: Cannot find seqNum=%d in AckedPacketList", seqNum);
return;
}
unsigned long long timeStamp = packet->packetTime.toMicroseconds();
// Find the one way RTT for this packet.
oneWayQueueDelay = (timeStamp - (*vecIterator).timeStamp)/2;
// Scale the value of one way RTT, so that it is correct for a transmission
// size of 1518 bytes.
// We lost this packet size details due to loss in libpcap, use the
// size echoed in the ACK packet - this does not included the header
// overhead for the packet - we assume that the packet on the reverse path
// has the same overhead length as the original packet.
//oneWayQueueDelay = ( oneWayQueueDelay )*1518 / ((*vecIterator).packetSize);
// NOTE: Do not scale the queuing delay - the results are bad for small
// packet transmissions.
//if(oneWayQueueDelay < minDelaySensor->getMinDelay())
//{
// logWrite(ERROR,"Incorrect oneWayQueueDelay value = %llu, minDelay = %llu, seqNum=%d, SENDTS=%llu,RECVTS=%llu", oneWayQueueDelay, minDelaySensor->getMinDelay(),seqNum, (*vecIterator).timeStamp, timeStamp);
// return;
//}
// Find the queuing delay for this packet, by subtracting the
// one way minimum delay from the above value.
if(oneWayQueueDelay > minDelaySensor->getMinDelay())
oneWayQueueDelay = oneWayQueueDelay - minDelaySensor->getMinDelay();
else
oneWayQueueDelay = 0;
if(oneWayQueueDelay > 90000000)
{
logWrite(ERROR,"Incorrect oneWayQueueDelay value = %llu, minDelay = %llu, seqNum=%d, SENDTS=%llu,RECVTS=%llu", oneWayQueueDelay, minDelaySensor->getMinDelay(),seqNum, (*vecIterator).timeStamp, timeStamp);
return;
}
// Set this as the new maximum one way queuing delay.
if(oneWayQueueDelay > maxDelay)
maxDelay = oneWayQueueDelay;
// Send an event message to the monitor to change the value of maximum one way delay.
if(lossSensor->getPacketLoss() > 0)
{
// Report the maximum delay
ostringstream messageBuffer;
if(maxDelay > sentDelay)
{
messageBuffer<<"MAXINQ="<<(maxDelay+minDelaySensor->getMinDelay())/1000;
global::output->eventMessage(messageBuffer.str(), packet->elab);
sentDelay = maxDelay;
}
logWrite(SENSOR,"VALUE::New Max Delay = %llu",maxDelay);
}
logWrite(SENSOR,"MAXD:TIME=%llu,MAXD=%llu",timeStamp,maxDelay);
logWrite(SENSOR,"ACTUAL_MAXD:TIME=%llu,ACTUAL_MAXD=%llu",timeStamp,oneWayQueueDelay);
}
<|endoftext|>
|
<commit_before>/** Copyright (C) 2016, 2017 European Spallation Source ERIC */
#include <cassert>
#include <common/Detector.h>
#include <common/EFUArgs.h>
#include <common/Trace.h>
#include <efu/Launcher.h>
#include <iostream>
#include <thread>
#include <map>
void Launcher::launchThreads(std::shared_ptr<Detector> &detector) {
auto startThreadsWithoutAffinity = [&detector]() {
XTRACE(MAIN, ALW, "Launching threads without core affinity.\n");
for (auto &ThreadInfo : detector->GetThreadInfo()) {
XTRACE(MAIN, ALW, "Creating new thread (id: %s)\n", ThreadInfo.name.c_str());
ThreadInfo.thread = std::thread(ThreadInfo.func);
}
};
auto setThreadCoreAffinity = [](std::thread &thread, std::uint16_t core) {
#ifdef __linux__
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(core, &cpuset);
XTRACE(MAIN, ALW, "Setting thread affinity to core %d\n", core);
GLOG_INF("Setting thread affinity to core " + std::to_string(core));
int __attribute__((unused))s = pthread_setaffinity_np(thread.native_handle(), sizeof(cpu_set_t), &cpuset);
assert(s == 0);
}
#else
#pragma message("setaffinity only implemented for Linux")
GLOG_WAR("setaffinity only implemented for Linux");
#endif
};
std::map<std::string,std::uint16_t> AffinityMap;
for (auto &Affinity : ThreadCoreAffinity) {
AffinityMap[Affinity.Name] = Affinity.Core;
}
if (0 == ThreadCoreAffinity.size()) {
startThreadsWithoutAffinity();
} else if (1 == ThreadCoreAffinity.size() and ThreadCoreAffinity[0].Name == "implicit_affinity") {
XTRACE(MAIN, ALW, "Launching threads with implicit core affinity.\n");
int CoreCounter = ThreadCoreAffinity[0].Core;
for (auto &ThreadInfo : detector->GetThreadInfo()) {
XTRACE(MAIN, ALW, "Creating new thread (id: %s)\n", ThreadInfo.name.c_str());
ThreadInfo.thread = std::thread(ThreadInfo.func);
setThreadCoreAffinity(ThreadInfo.thread, CoreCounter++);
}
} else {
XTRACE(MAIN, ALW, "Launching threads with explicit core affinity.\n");
for (auto &ThreadInfo : detector->GetThreadInfo()) {
XTRACE(MAIN, ALW, "Creating new thread (id: %s)\n", ThreadInfo.name.c_str());
ThreadInfo.thread = std::thread(ThreadInfo.func);
if (1 == AffinityMap.count(ThreadInfo.name)) {
setThreadCoreAffinity(ThreadInfo.thread, AffinityMap[ThreadInfo.name]);
}
}
}
}
<commit_msg>Improved the error messages.<commit_after>/** Copyright (C) 2016, 2017 European Spallation Source ERIC */
#include <cassert>
#include <common/Detector.h>
#include <common/EFUArgs.h>
#include <common/Trace.h>
#include <efu/Launcher.h>
#include <iostream>
#include <thread>
#include <map>
void Launcher::launchThreads(std::shared_ptr<Detector> &detector) {
auto startThreadsWithoutAffinity = [&detector]() {
XTRACE(MAIN, ALW, "Launching threads without core affinity.\n");
for (auto &ThreadInfo : detector->GetThreadInfo()) {
XTRACE(MAIN, ALW, "Creating new thread (id: %s)\n", ThreadInfo.name.c_str());
ThreadInfo.thread = std::thread(ThreadInfo.func);
}
};
auto setThreadCoreAffinity = [](std::thread &thread, std::uint16_t core) {
#ifdef __linux__
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(core, &cpuset);
XTRACE(MAIN, ALW, "Setting thread affinity to core %d\n", core);
GLOG_INF("Setting thread affinity to core " + std::to_string(core));
int __attribute__((unused))s = pthread_setaffinity_np(thread.native_handle(), sizeof(cpu_set_t), &cpuset);
assert(s == 0);
}
#else
#pragma message("setaffinity only implemented for Linux")
GLOG_WAR("setaffinity only implemented for Linux");
#endif
};
std::map<std::string,std::uint16_t> AffinityMap;
for (auto &Affinity : ThreadCoreAffinity) {
AffinityMap[Affinity.Name] = Affinity.Core;
}
if (0 == ThreadCoreAffinity.size()) {
startThreadsWithoutAffinity();
} else if (1 == ThreadCoreAffinity.size() and ThreadCoreAffinity[0].Name == "implicit_affinity") {
XTRACE(MAIN, ALW, "Launching threads with implicit core affinity.\n");
int CoreCounter = ThreadCoreAffinity[0].Core;
for (auto &ThreadInfo : detector->GetThreadInfo()) {
XTRACE(MAIN, ALW, "Creating new thread (id: %s)\n", ThreadInfo.name.c_str());
ThreadInfo.thread = std::thread(ThreadInfo.func);
setThreadCoreAffinity(ThreadInfo.thread, CoreCounter++);
}
} else {
XTRACE(MAIN, ALW, "Launching threads with explicit core affinity.\n");
for (auto &ThreadInfo : detector->GetThreadInfo()) {
XTRACE(MAIN, ALW, "Creating new thread (id: %s)\n", ThreadInfo.name.c_str());
ThreadInfo.thread = std::thread(ThreadInfo.func);
if (1 == AffinityMap.count(ThreadInfo.name)) {
setThreadCoreAffinity(ThreadInfo.thread, AffinityMap[ThreadInfo.name]);
} else {
XTRACE(MAIN, ALW, "No thread core affinity information available for thread with id: %s\n", ThreadInfo.name.c_str());
}
}
}
}
<|endoftext|>
|
<commit_before><commit_msg>Localization: Unsigned value cannot be negative.<commit_after><|endoftext|>
|
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkTestingMacros.h"
#include <mitkTestingConfig.h>
#include <mitkTestFixture.h>
#include <mitkIOUtil.h>
#include <mitkInteractionTestHelper.h>
#include <mitkPointSet.h>
#include <mitkPointSetDataInteractor.h>
class mitkPointSetDataInteractorTestSuite : public mitk::TestFixture
{
CPPUNIT_TEST_SUITE(mitkPointSetDataInteractorTestSuite);
MITK_TEST(AddPointInteraction);
MITK_TEST(DeletePointInteraction);
CPPUNIT_TEST_SUITE_END();
private:
mitk::DataNode::Pointer m_TestPointSetNode;
mitk::PointSetDataInteractor::Pointer m_DataInteractor;
mitk::PointSet::Pointer m_TestPointSet;
public:
void setUp()
{
//Create DataNode as a container for our PointSet to be tested
m_TestPointSetNode = mitk::DataNode::New();
// Create PointSetData Interactor
m_DataInteractor = mitk::PointSetDataInteractor::New();
// Load the according state machine for regular point set interaction
m_DataInteractor->LoadStateMachine("PointSet.xml");
// Set the configuration file that defines the triggers for the transitions
m_DataInteractor->SetEventConfig("PointSetConfig.xml");
//Create new PointSet which will receive the interaction input
m_TestPointSet = mitk::PointSet::New();
m_TestPointSetNode->SetData(m_TestPointSet);
// set the DataNode (which already is added to the DataStorage)
m_DataInteractor->SetDataNode(m_TestPointSetNode);
}
void tearDown()
{
//destroy all objects
m_TestPointSetNode = NULL;
m_TestPointSet = NULL;
m_DataInteractor = NULL;
}
void AddPointInteraction()
{
//Path to the reference PointSet
std::string referencePointSetPath = GetTestDataFilePath("InteractionTestData/ReferenceData/PointSetDataInteractor_add_points_in_2D_ref.mps");
//Path to the interaction xml file
std::string interactionXmlPath = GetTestDataFilePath("InteractionTestData/Interactions/PointSetDataInteractor_add_points_in_2D.xml");
//Create test helper to initialize all necessary objects for interaction
mitk::InteractionTestHelper interactionTestHelper(interactionXmlPath);
//Add our test node to the DataStorage of our test helper
interactionTestHelper.AddNodeToStorage(m_TestPointSetNode);
//Start Interaction
interactionTestHelper.PlaybackInteraction();
//Load the reference PointSet
mitk::PointSet::Pointer referencePointSet = mitk::IOUtil::LoadPointSet(referencePointSetPath);
//Compare reference with the result of the interaction
MITK_ASSERT_EQUAL(m_TestPointSet, referencePointSet, "");
}
void PlayInteraction( std::string &xmlFile, mitk::DataNode* node )
{
mitk::InteractionTestHelper interactionTestHelper( xmlFile );
interactionTestHelper.AddNodeToStorage( node );
interactionTestHelper.PlaybackInteraction();
}
void EvaluateState( std::string &refPsFile, mitk::PointSet::Pointer ps, int selected )
{
mitk::PointSet::Pointer refPs = mitk::IOUtil::LoadPointSet( refPsFile );
MITK_ASSERT_EQUAL(ps, refPs, "");
MITK_TEST_CONDITION_REQUIRED(ps->GetNumberOfSelected() == 1, "One selected point." );
MITK_TEST_CONDITION_REQUIRED(ps->GetSelectInfo( selected ) , "Testing if point is selected." );
}
void SetupInteractor( mitk::PointSetDataInteractor* dataInteractor, mitk::DataNode* node )
{
dataInteractor->LoadStateMachine("PointSet.xml");
dataInteractor->SetEventConfig("PointSetConfig.xml");
dataInteractor->SetDataNode( node );
}
void DeletePointInteraction()
{
mitk::PointSetDataInteractor::Pointer dataInteractor = mitk::PointSetDataInteractor::New();
mitk::DataNode::Pointer pointSetNode = mitk::DataNode::New();
//Path to the reference PointSet
std::string referencePointSetPath = GetTestDataFilePath("InteractionTestData/InitPointSet.mps");
mitk::PointSet::Pointer ps = mitk::IOUtil::LoadPointSet( referencePointSetPath );
pointSetNode->SetData( ps );
this->SetupInteractor( dataInteractor, pointSetNode );
std::string interactionXmlPath = GetTestDataFilePath("InteractionTestData/Interactions/testInteractionDel-0_1.xml");
referencePointSetPath = GetTestDataFilePath("InteractionTestData/PointSet-0.mps");
PlayInteraction( interactionXmlPath, pointSetNode );
EvaluateState( referencePointSetPath, ps, 1 );
interactionXmlPath = GetTestDataFilePath("InteractionTestData/Interactions/testInteractionDel-1_3.xml");
referencePointSetPath = GetTestDataFilePath("InteractionTestData/PointSet-1.mps");
PlayInteraction( interactionXmlPath, pointSetNode );
EvaluateState( referencePointSetPath, ps, 1 );
interactionXmlPath = GetTestDataFilePath("InteractionTestData/Interactions/testInteractionDel-2_4.xml");
referencePointSetPath = GetTestDataFilePath("InteractionTestData/PointSet-2.mps");
PlayInteraction( interactionXmlPath, pointSetNode );
EvaluateState( referencePointSetPath, ps, 1 );
interactionXmlPath = GetTestDataFilePath("InteractionTestData/Interactions/testInteractionDel-3_8.xml");
referencePointSetPath = GetTestDataFilePath("InteractionTestData/PointSet-3.mps");
PlayInteraction( interactionXmlPath, pointSetNode );
EvaluateState( referencePointSetPath, ps, 1 );
interactionXmlPath = GetTestDataFilePath("InteractionTestData/Interactions/testInteractionDel-4_2.xml");
referencePointSetPath = GetTestDataFilePath("InteractionTestData/PointSet-4.mps");
PlayInteraction( interactionXmlPath, pointSetNode );
EvaluateState( referencePointSetPath, ps, 4 );
interactionXmlPath = GetTestDataFilePath("InteractionTestData/Interactions/testInteractionDel-5_6.xml");
referencePointSetPath = GetTestDataFilePath("InteractionTestData/PointSet-5.mps");
PlayInteraction( interactionXmlPath, pointSetNode );
EvaluateState( referencePointSetPath, ps, 4 );
interactionXmlPath = GetTestDataFilePath("InteractionTestData/Interactions/testInteractionDel-6_7.xml");
referencePointSetPath = GetTestDataFilePath("InteractionTestData/PointSet-6.mps");
PlayInteraction( interactionXmlPath, pointSetNode );
EvaluateState( referencePointSetPath, ps, 4 );
interactionXmlPath = GetTestDataFilePath("InteractionTestData/Interactions/testInteractionDel-7_5.xml");
referencePointSetPath = GetTestDataFilePath("InteractionTestData/PointSet1.mps");
PlayInteraction( interactionXmlPath, pointSetNode );
MITK_TEST_CONDITION_REQUIRED(ps->GetPointSet()->GetNumberOfPoints() == 0, "Empty point set check.");
MITK_TEST_CONDITION_REQUIRED(ps->GetNumberOfSelected() == 0, "No selected points." );
}
};
MITK_TEST_SUITE_REGISTRATION(mitkPointSetDataInteractor)
<commit_msg>Geometries for TestPointSet and ReferencePointSet have to be updated before comparison.<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkTestingMacros.h"
#include <mitkTestingConfig.h>
#include <mitkTestFixture.h>
#include <mitkIOUtil.h>
#include <mitkInteractionTestHelper.h>
#include <mitkPointSet.h>
#include <mitkPointSetDataInteractor.h>
class mitkPointSetDataInteractorTestSuite : public mitk::TestFixture
{
CPPUNIT_TEST_SUITE(mitkPointSetDataInteractorTestSuite);
MITK_TEST(AddPointInteraction);
MITK_TEST(DeletePointInteraction);
CPPUNIT_TEST_SUITE_END();
private:
mitk::DataNode::Pointer m_TestPointSetNode;
mitk::PointSetDataInteractor::Pointer m_DataInteractor;
mitk::PointSet::Pointer m_TestPointSet;
public:
void setUp()
{
//Create DataNode as a container for our PointSet to be tested
m_TestPointSetNode = mitk::DataNode::New();
// Create PointSetData Interactor
m_DataInteractor = mitk::PointSetDataInteractor::New();
// Load the according state machine for regular point set interaction
m_DataInteractor->LoadStateMachine("PointSet.xml");
// Set the configuration file that defines the triggers for the transitions
m_DataInteractor->SetEventConfig("PointSetConfig.xml");
//Create new PointSet which will receive the interaction input
m_TestPointSet = mitk::PointSet::New();
m_TestPointSetNode->SetData(m_TestPointSet);
// set the DataNode (which already is added to the DataStorage)
m_DataInteractor->SetDataNode(m_TestPointSetNode);
}
void tearDown()
{
//destroy all objects
m_TestPointSetNode = NULL;
m_TestPointSet = NULL;
m_DataInteractor = NULL;
}
void AddPointInteraction()
{
//Path to the reference PointSet
std::string referencePointSetPath = GetTestDataFilePath("InteractionTestData/ReferenceData/PointSetDataInteractor_add_points_in_2D_ref.mps");
//Path to the interaction xml file
std::string interactionXmlPath = GetTestDataFilePath("InteractionTestData/Interactions/PointSetDataInteractor_add_points_in_2D.xml");
//Create test helper to initialize all necessary objects for interaction
mitk::InteractionTestHelper interactionTestHelper(interactionXmlPath);
//Add our test node to the DataStorage of our test helper
interactionTestHelper.AddNodeToStorage(m_TestPointSetNode);
//Start Interaction
interactionTestHelper.PlaybackInteraction();
//Load the reference PointSet
mitk::PointSet::Pointer referencePointSet = mitk::IOUtil::LoadPointSet(referencePointSetPath);
//Compare reference with the result of the interaction
MITK_ASSERT_EQUAL(m_TestPointSet, referencePointSet, "");
}
void PlayInteraction( std::string &xmlFile, mitk::DataNode* node )
{
mitk::InteractionTestHelper interactionTestHelper( xmlFile );
interactionTestHelper.AddNodeToStorage( node );
interactionTestHelper.PlaybackInteraction();
}
void EvaluateState( std::string &refPsFile, mitk::PointSet::Pointer ps, int selected )
{
mitk::PointSet::Pointer refPs = mitk::IOUtil::LoadPointSet( refPsFile );
refPs->UpdateOutputInformation();
ps->UpdateOutputInformation();
MITK_ASSERT_EQUAL(ps, refPs, "");
MITK_TEST_CONDITION_REQUIRED(true, "Test against reference point set." );
MITK_TEST_CONDITION_REQUIRED(ps->GetNumberOfSelected() == 1, "One selected point." );
MITK_TEST_CONDITION_REQUIRED(ps->GetSelectInfo( selected ) , "Testing if proper point is selected." );
}
void SetupInteractor( mitk::PointSetDataInteractor* dataInteractor, mitk::DataNode* node )
{
dataInteractor->LoadStateMachine("PointSet.xml");
dataInteractor->SetEventConfig("PointSetConfig.xml");
dataInteractor->SetDataNode( node );
}
void DeletePointInteraction()
{
mitk::PointSetDataInteractor::Pointer dataInteractor = mitk::PointSetDataInteractor::New();
mitk::DataNode::Pointer pointSetNode = mitk::DataNode::New();
//Path to the reference PointSet
std::string referencePointSetPath = GetTestDataFilePath("InteractionTestData/InitPointSet.mps");
mitk::PointSet::Pointer ps = mitk::IOUtil::LoadPointSet( referencePointSetPath );
pointSetNode->SetData( ps );
this->SetupInteractor( dataInteractor, pointSetNode );
std::string interactionXmlPath = GetTestDataFilePath("InteractionTestData/Interactions/testInteractionDel-0_1.xml");
referencePointSetPath = GetTestDataFilePath("InteractionTestData/refPointSet-0.mps");
PlayInteraction( interactionXmlPath, pointSetNode );
EvaluateState( referencePointSetPath, ps, 1 );
interactionXmlPath = GetTestDataFilePath("InteractionTestData/Interactions/testInteractionDel-1_3.xml");
referencePointSetPath = GetTestDataFilePath("InteractionTestData/refPointSet-1.mps");
PlayInteraction( interactionXmlPath, pointSetNode );
EvaluateState( referencePointSetPath, ps, 1 );
interactionXmlPath = GetTestDataFilePath("InteractionTestData/Interactions/testInteractionDel-2_4.xml");
referencePointSetPath = GetTestDataFilePath("InteractionTestData/refPointSet-2.mps");
PlayInteraction( interactionXmlPath, pointSetNode );
EvaluateState( referencePointSetPath, ps, 1 );
interactionXmlPath = GetTestDataFilePath("InteractionTestData/Interactions/testInteractionDel-3_8.xml");
referencePointSetPath = GetTestDataFilePath("InteractionTestData/refPointSet-3.mps");
PlayInteraction( interactionXmlPath, pointSetNode );
EvaluateState( referencePointSetPath, ps, 1 );
interactionXmlPath = GetTestDataFilePath("InteractionTestData/Interactions/testInteractionDel-4_2.xml");
referencePointSetPath = GetTestDataFilePath("InteractionTestData/refPointSet-4.mps");
PlayInteraction( interactionXmlPath, pointSetNode );
EvaluateState( referencePointSetPath, ps, 4 );
interactionXmlPath = GetTestDataFilePath("InteractionTestData/Interactions/testInteractionDel-5_6.xml");
referencePointSetPath = GetTestDataFilePath("InteractionTestData/refPointSet-5.mps");
PlayInteraction( interactionXmlPath, pointSetNode );
EvaluateState( referencePointSetPath, ps, 4 );
interactionXmlPath = GetTestDataFilePath("InteractionTestData/Interactions/testInteractionDel-6_7.xml");
referencePointSetPath = GetTestDataFilePath("InteractionTestData/refPointSet-6.mps");
PlayInteraction( interactionXmlPath, pointSetNode );
EvaluateState( referencePointSetPath, ps, 4 );
interactionXmlPath = GetTestDataFilePath("InteractionTestData/Interactions/testInteractionDel-7_5.xml");
//referencePointSetPath = GetTestDataFilePath("InteractionTestData/PointSet1.mps");
PlayInteraction( interactionXmlPath, pointSetNode );
MITK_TEST_CONDITION_REQUIRED(ps->GetPointSet()->GetNumberOfPoints() == 0, "Empty point set check.");
MITK_TEST_CONDITION_REQUIRED(ps->GetNumberOfSelected() == 0, "No selected points." );
}
};
MITK_TEST_SUITE_REGISTRATION(mitkPointSetDataInteractor)
<|endoftext|>
|
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.
*
*=========================================================================*/
// Software Guide : BeginLatex
//
// This example introduces the use of the
// \doxygen{CannyEdgeDetectionImageFilter}. This filter is widely used for
// edge detection since it is the optimal solution satisfying the constraints
// of good sensitivity, localization and noise robustness.
//
// \index{itk::CannyEdgeDetectionImageFilter|textbf}
//
// Software Guide : EndLatex
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkCastImageFilter.h"
#include "itkRescaleIntensityImageFilter.h"
// Software Guide : BeginLatex
//
// The first step required for using this filter is to include its header file.
//
// \index{itk::CannyEdgeDetectionImageFilter!header}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkCannyEdgeDetectionImageFilter.h"
// Software Guide : EndCodeSnippet
int main(int argc, char* argv[])
{
if( argc < 3 )
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " inputImage outputImage [variance upperThreshold lowerThreshold]" << std::endl;
return EXIT_FAILURE;
}
const char * inputFilename = argv[1];
const char * outputFilename = argv[2];
float variance = 2.0;
float upperThreshold = 0.0;
float lowerThreshold = 0.0;
if( argc > 3 )
{
variance = atof( argv[3] );
}
if( argc > 4 )
{
upperThreshold = atof( argv[4] );
}
if( argc > 5 )
{
lowerThreshold = atof( argv[5] );
}
std::cout << "Variance = " << variance << std::endl;
std::cout << "UpperThreshold = " << upperThreshold << std::endl;
std::cout << "LowerThreshold = " << lowerThreshold << std::endl;
typedef unsigned char CharPixelType; // IO
typedef double RealPixelType; // Operations
const unsigned int Dimension = 2;
typedef itk::Image<CharPixelType, Dimension> CharImageType;
typedef itk::Image<RealPixelType, Dimension> RealImageType;
typedef itk::ImageFileReader< CharImageType > ReaderType;
typedef itk::ImageFileWriter< CharImageType > WriterType;
// Software Guide : BeginLatex
//
// This filter operates on images of pixel type \code{float}. It is then
// necessary to cast the type of the input images which are usually of
// integer type. The \doxygen{CastImageFilter} is used here for this purpose.
// Its image template parameters are defined for casting from the input type
// to the \code{float} type used for processing.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::CastImageFilter< CharImageType, RealImageType>
CastToRealFilterType;
// Software Guide : EndCodeSnippet
typedef itk::RescaleIntensityImageFilter<RealImageType, CharImageType > RescaleFilter;
// Software Guide : BeginLatex
//
// The \doxygen{CannyEdgeDetectionImageFilter} is instantiated using the
// \code{float} image type.
//
// \index{itk::CannyEdgeDetectionImageFilter|textbf}
//
// Software Guide : EndLatex
typedef itk::CannyEdgeDetectionImageFilter<RealImageType, RealImageType> CannyFilter;
//Setting the IO
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
CastToRealFilterType::Pointer toReal = CastToRealFilterType::New();
RescaleFilter::Pointer rescale = RescaleFilter::New();
//Setting the ITK pipeline filter
CannyFilter::Pointer cannyFilter = CannyFilter::New();
reader->SetFileName( inputFilename );
writer->SetFileName( outputFilename );
//The output of an edge filter is 0 or 1
rescale->SetOutputMinimum( 0 );
rescale->SetOutputMaximum( 255 );
toReal->SetInput( reader->GetOutput() );
cannyFilter->SetInput( toReal->GetOutput() );
cannyFilter->SetVariance( variance );
cannyFilter->SetUpperThreshold( upperThreshold );
cannyFilter->SetLowerThreshold( lowerThreshold );
rescale->SetInput( cannyFilter->GetOutput() );
writer->SetInput( rescale->GetOutput() );
try
{
writer->Update();
}
catch( itk::ExceptionObject & err )
{
std::cout << "ExceptionObject caught !" << std::endl;
std::cout << err << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>DOC: Expanded Canny Edge Detection Example<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.
*
*=========================================================================*/
// Software Guide : BeginLatex
//
// This example introduces the use of the
// \doxygen{CannyEdgeDetectionImageFilter}. Canny edge detection is widely used for
// edge detection since it is the optimal solution satisfying the constraints
// of good sensitivity, localization and noise robustness. To achieve this
// end, Canny edge detection is implemented internally as a multi-stage
// algorithm, which involves Gaussian smoothing to remove noise, calculation
// of gradient magnitudes to localize edge features, non-maximum suppression
// to remove suprious features, and finally thresholding to yield a binary image.
// Though the specifics of this internal pipeline are largely abstracted from
// the user of the class, it is nonetheless beneficial to have a general
// understanding of these components so that parameters can be appropriately
// adjusted.
//
// \index{itk::CannyEdgeDetectionImageFilter|textbf}
//
// The first step required for using this filter is to include its header file.
//
// \index{itk::CannyEdgeDetectionImageFilter!header}
//
// Software Guide : EndLatex
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkCastImageFilter.h"
#include "itkRescaleIntensityImageFilter.h"
// Software Guide : BeginCodeSnippet
#include "itkCannyEdgeDetectionImageFilter.h"
// Software Guide : EndCodeSnippet
int main(int argc, char* argv[])
{
if( argc < 3 )
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0]
<< " inputImage outputImage"
<< " [variance upperThreshold lowerThreshold]" << std::endl;
return EXIT_FAILURE;
}
const char * inputFilename = argv[1];
const char * outputFilename = argv[2];
float variance = 2.0;
float upperThreshold = 0.0;
float lowerThreshold = 0.0;
if( argc > 3 )
{
variance = atof( argv[3] );
}
if( argc > 4 )
{
upperThreshold = atof( argv[4] );
}
if( argc > 5 )
{
lowerThreshold = atof( argv[5] );
}
std::cout << "Variance = " << variance << std::endl;
std::cout << "UpperThreshold = " << upperThreshold << std::endl;
std::cout << "LowerThreshold = " << lowerThreshold << std::endl;
// Software Guide : BeginLatex
//
// In this example, images are read and written with \code{unsigned char}
// pixel type. However, Canny edge detection requires floating point
// pixel types in order to avoid numerical errors. For this reason,
// a separate internal image type with pixel type \code{double} is defined
// for edge detection.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
const unsigned int Dimension = 2;
typedef unsigned char CharPixelType; // IO
typedef double RealPixelType; // Operations
typedef itk::Image<CharPixelType, Dimension> CharImageType;
typedef itk::Image<RealPixelType, Dimension> RealImageType;
// Software Guide : EndCodeSnippet
typedef itk::ImageFileReader<CharImageType> ReaderType;
typedef itk::ImageFileWriter<CharImageType> WriterType;
// Software Guide : BeginLatex
//
// The \code{CharImageType} image is cast to and from \code{RealImageType}
// using \doxygen{CastImageFilter} and \code{RescaleIntensityImageFilter},
// respectively; both the input and output of \code{CannyEdgeDetectionImageFilter}
// are \code{RealImageType}.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::CastImageFilter<CharImageType, RealImageType>
CastToRealFilterType;
typedef itk::CannyEdgeDetectionImageFilter<RealImageType, RealImageType> CannyFilter;
typedef itk::RescaleIntensityImageFilter<RealImageType, CharImageType> RescaleFilter;
// Software Guide : EndCodeSnippet
//Setting the IO
ReaderType::Pointer reader = ReaderType::New();
CastToRealFilterType::Pointer toReal = CastToRealFilterType::New();
CannyFilter::Pointer cannyFilter = CannyFilter::New();
RescaleFilter::Pointer rescale = RescaleFilter::New();
WriterType::Pointer writer = WriterType::New();
reader->SetFileName( inputFilename );
writer->SetFileName( outputFilename );
toReal->SetInput( reader->GetOutput() );
cannyFilter->SetInput( toReal->GetOutput() );
rescale->SetInput( cannyFilter->GetOutput() );
writer->SetInput( rescale->GetOutput() );
// Software Guide : BeginLatex
//
// In this example, three parameters of the Canny edge detection
// filter may be set via the \code{SetVariance()}, \code{SetUpperThreshold()},
// and \code{SetLowerThreshold()} methods. Based on the previous discussion
// of the steps in the internal pipeline, we understand that
// \code{variance} adjusts the amount of Gaussian smoothing and
// \code{upperThreshold} and \code{lowerThreshold} control which edges are
// selected in the final step.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
cannyFilter->SetVariance( variance );
cannyFilter->SetUpperThreshold( upperThreshold );
cannyFilter->SetLowerThreshold( lowerThreshold );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Finally, \code{Update()} is called on \code{writer} to trigger excecution
// of the pipeline. As usual, the call is wrapped in a \code{try/catch}
// block.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
try
{
writer->Update();
}
catch( itk::ExceptionObject & err )
{
std::cout << "ExceptionObject caught !" << std::endl;
std::cout << err << std::endl;
return EXIT_FAILURE;
}
// Software Guide : EndCodeSnippet
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include "kernel.h"
#include "ilwis.h"
#include "geometries.h"
#include "ilwisdata.h"
#include "coordinatesystem.h"
#include "georeference.h"
#include "georefimplementation.h"
#include "factory.h"
#include "abstractfactory.h"
#include "coordinatesystem.h"
#include "georeference.h"
#include "simpelgeoreference.h"
#include "cornersgeoreference.h"
#include "georefimplementationfactory.h"
using namespace Ilwis;
GeoRefImplementationFactory::GeoRefImplementationFactory() : AbstractFactory("georefimplementationfactory","ilwis","")
{
}
void GeoRefImplementationFactory::addCreator(const QString &name, CreateGeoRefImplementation func)
{
auto iter = _implCreators.find(name);
if ( iter == _implCreators.end()) {
_implCreators[name] = func;
}
}
GeoRefImplementation *GeoRefImplementationFactory::create(const QString& name) {
auto iter = _implCreators.find(name);
if ( iter != _implCreators.end()) {
return _implCreators[name]();
}
return 0;
}
bool GeoRefImplementationFactory::prepare()
{
AbstractFactory::prepare();
addCreator("simpel",SimpelGeoReference::create);
addCreator("corners",CornersGeoReference::create);
return true;
}
<commit_msg>georefctp added to the factory<commit_after>#include "kernel.h"
#include "ilwis.h"
#include "geometries.h"
#include "ilwisdata.h"
#include "coordinatesystem.h"
#include "georeference.h"
#include "georefimplementation.h"
#include "factory.h"
#include "abstractfactory.h"
#include "coordinatesystem.h"
#include "georeference.h"
#include "simpelgeoreference.h"
#include "cornersgeoreference.h"
#include "controlpoint.h"
#include "ctpgeoreference.h"
#include "Eigen/LU"
#include "mathhelper.h"
#include "planarctpgeoreference.h"
#include "georefimplementationfactory.h"
using namespace Ilwis;
GeoRefImplementationFactory::GeoRefImplementationFactory() : AbstractFactory("georefimplementationfactory","ilwis","")
{
}
void GeoRefImplementationFactory::addCreator(const QString &name, CreateGeoRefImplementation func)
{
auto iter = _implCreators.find(name);
if ( iter == _implCreators.end()) {
_implCreators[name] = func;
}
}
GeoRefImplementation *GeoRefImplementationFactory::create(const QString& name) {
auto iter = _implCreators.find(name);
if ( iter != _implCreators.end()) {
return _implCreators[name]();
}
return 0;
}
bool GeoRefImplementationFactory::prepare()
{
AbstractFactory::prepare();
addCreator("simpel",SimpelGeoReference::create);
addCreator("corners",CornersGeoReference::create);
addCreator("tiepoints",PlanarCTPGeoReference::create);
return true;
}
<|endoftext|>
|
<commit_before>#include "Halide.h"
#include <stdio.h>
#include "test/common/halide_test_dirs.h"
using namespace Halide;
int main(int argc, char **argv) {
// Make sure it's possible to generate object files for lots of
// targets. This provides early warning that you may have broken
// Halide on some other platform.
Func f("f");
Var x;
f(x) = x;
std::string targets[] = {
"x86-64-linux",
"x86-32-linux",
"x86-64-osx",
"x86-32-osx",
"x86-64-windows",
"x86-32-windows",
"arm-64-ios",
"arm-32-ios",
"arm-64-android",
"arm-32-android",
"mips-32-android"
};
for (const std::string &t : targets) {
Target target(t);
if (!target.supported()) continue;
std::string object_name = Internal::get_test_tmp_dir() + "test_object_" + t;
std::string lib_name = Internal::get_test_tmp_dir() + "test_lib_" + t;
if (target.os == Target::Windows && !target.has_feature(Target::MinGW)) {
object_name += ".obj";
lib_name += ".lib";
} else {
object_name += ".o";
lib_name += ".a";
}
Internal::ensure_no_file_exists(object_name);
Internal::ensure_no_file_exists(lib_name);
f.compile_to_file("test_object_" + t, std::vector<Argument>(), "", target);
f.compile_to_static_library("test_lib_" + t, std::vector<Argument>(), "", target);
Internal::assert_file_exists(object_name);
Internal::assert_file_exists(lib_name);
}
printf("Success!\n");
return 0;
}
<commit_msg>Fix cross_compilation<commit_after>#include "Halide.h"
#include <stdio.h>
#include "test/common/halide_test_dirs.h"
using namespace Halide;
int main(int argc, char **argv) {
// Make sure it's possible to generate object files for lots of
// targets. This provides early warning that you may have broken
// Halide on some other platform.
Func f("f");
Var x;
f(x) = x;
std::string targets[] = {
"x86-64-linux",
"x86-32-linux",
"x86-64-osx",
"x86-32-osx",
"x86-64-windows",
"x86-32-windows",
"arm-64-ios",
"arm-32-ios",
"arm-64-android",
"arm-32-android",
"mips-32-android"
};
for (const std::string &t : targets) {
Target target(t);
if (!target.supported()) continue;
std::string object_name = Internal::get_test_tmp_dir() + "test_object_" + t;
std::string lib_name = Internal::get_test_tmp_dir() + "test_lib_" + t;
if (target.os == Target::Windows && !target.has_feature(Target::MinGW)) {
object_name += ".obj";
lib_name += ".lib";
} else {
object_name += ".o";
lib_name += ".a";
}
Internal::ensure_no_file_exists(object_name);
Internal::ensure_no_file_exists(lib_name);
f.compile_to_file(Internal::get_test_tmp_dir() + "test_object_" + t, std::vector<Argument>(), "", target);
f.compile_to_static_library(Internal::get_test_tmp_dir() + "test_lib_" + t, std::vector<Argument>(), "", target);
Internal::assert_file_exists(object_name);
Internal::assert_file_exists(lib_name);
}
printf("Success!\n");
return 0;
}
<|endoftext|>
|
<commit_before><commit_msg>Remove the temporary instrumentation to getaddrinfo(). This is a revert of r31267.<commit_after><|endoftext|>
|
<commit_before>// Copyright 2019 DeepMind Technologies Ltd. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "open_spiel/games/chess/pgn.h"
#include <iostream>
#include <string>
#include <utility>
#include <vector>
#include "open_spiel/abseil-cpp/absl/strings/match.h"
#include "open_spiel/abseil-cpp/absl/strings/str_cat.h"
#include "open_spiel/abseil-cpp/absl/strings/str_join.h"
#include "open_spiel/spiel_utils.h"
namespace open_spiel {
namespace pgn {
namespace {
template <typename T>
void WriteTag(
std::ostream& os, const std::string& key, const T& value) {
os << "[" << key << " \"" << value << "\']" << std::endl;
}
void WriteComment(std::ostream& os, const std::string& comment) {
os << "{" << comment << "}";
}
std::string GetResultString(const State &state) {
std::string result_str;
if (state.IsTerminal()) {
std::vector<std::string> results;
for (double ret : state.Returns()) {
if (ret == chess::WinUtility()) {
results.emplace_back("1");
} else if (ret == chess::DrawUtility()) {
results.emplace_back("1/2");
} else if (ret == chess::LossUtility()) {
results.emplace_back("0");
} else {
SpielFatalError("Invalid chess utility");
}
}
result_str = results[chess::ColorToPlayer(chess::Color::kWhite)] + "-" +
results[chess::ColorToPlayer(chess::Color::kBlack)];
} else {
result_str = "*";
}
return result_str;
}
void WriteHeader(std::ostream& os, const std::string& event, int round,
const std::string& white, const std::string& black,
const State& state,
const std::vector<std::pair<std::string, std::string>> &tags = {}) {
WriteTag(os, "Event", event);
WriteTag(os, "Site", "OpenSpiel");
WriteTag(os, "Round", round);
std::string date_str;
if (state.IsTerminal()) {
time_t ttime = time(nullptr);
char buffer[11];
strftime(buffer,sizeof(buffer),"%Y.%m.%d", localtime(&ttime));
date_str = buffer;
} else {
date_str = "????.??.??";
}
WriteTag(os, "Date", date_str);
WriteTag(os, "White", white);
WriteTag(os, "Black", black);
WriteTag(os, "Result", GetResultString(state));
for (const auto &[key, value] : tags) {
WriteTag(os, key, value);
}
}
std::string CheckTypeToPGNString(kriegspiel::KriegspielCheckType check_type) {
switch (check_type) {
case kriegspiel::KriegspielCheckType::kNoCheck:
return "";
case kriegspiel::KriegspielCheckType::kFile:
return "F";
case kriegspiel::KriegspielCheckType::kRank:
return "R";
case kriegspiel::KriegspielCheckType::kLongDiagonal:
return "L";
case kriegspiel::KriegspielCheckType::kShortDiagonal:
return "S";
case kriegspiel::KriegspielCheckType::kKnight:
return "N";
default:
SpielFatalError("Unknown check type");
}
}
std::string CheckTypesToPGNString(
const std::pair<kriegspiel::KriegspielCheckType,
kriegspiel::KriegspielCheckType>& check_type) {
std::string str;
str += CheckTypeToPGNString(check_type.first);
if (check_type.second != kriegspiel::KriegspielCheckType::kNoCheck) {
std::string second_check_str = CheckTypeToPGNString(check_type.second);
if (second_check_str < str) {
str = second_check_str + str;
}
else {
str += second_check_str;
}
}
return str;
}
} // namespace
ChessPGN::ChessPGN(const chess::ChessState &state, const std::string& event,
int round, const std::string& white,
const std::string& black) :
state_(state),
event_(event),
round_(round),
white_(white),
black_(black) {}
void ChessPGN::WriteHeader(std::ostream& os) const {
pgn::WriteHeader(os, event_, round_, white_, black_, state_);
}
void ChessPGN::WriteMoves(std::ostream& os) const {
chess::ChessBoard board = state_.StartBoard();
for (const chess::Move& move : state_.MovesHistory()) {
if (board.ToPlay() == chess::Color::kWhite) {
os << board.Movenumber() << ". ";
}
else {
os << " ";
if (board.Movenumber() > 9) os << " ";
if (board.Movenumber() > 99) os << " ";
}
os << move.ToSAN(board) << std::endl;
board.ApplyMove(move);
}
}
void ChessPGN::WriteResult(std::ostream& os) const {
os << GetResultString(state_) << std::endl;
}
KriegspielPGN::KriegspielPGN(const kriegspiel::KriegspielState &state,
const std::string& event,
int round,
const std::string& white,
const std::string& black,
chess::Color filtered) :
state_(state),
event_(event),
round_(round),
white_(white),
black_(black),
filtered_(filtered) {}
void KriegspielPGN::WriteHeader(std::ostream &os) const {
std::vector<std::pair<std::string, std::string>> tags
{std::make_pair("Variant", "ICC"),
std::make_pair("Filtered", GetFilteredString())};
pgn::WriteHeader(os, event_, round_, white_, black_, state_, tags);
}
void KriegspielPGN::WriteMoves(std::ostream &os) const {
chess::ChessBoard board = state_.StartBoard();
std::vector<std::string> illegal_moves;
for (auto &[move, msg] : state_.MoveMsgHistory()) {
std::string move_str = move.ToSAN(board, true);
if (msg.illegal) {
illegal_moves.emplace_back(move_str);
continue;
}
if (board.ToPlay() == chess::Color::kWhite) {
os << board.Movenumber() << ". ";
}
else {
os << " ";
if (board.Movenumber() > 9) os << " ";
if (board.Movenumber() > 99) os << " ";
}
if (filtered_ == chess::Color::kEmpty || filtered_ == board.ToPlay()) {
os << move_str << " ";
}
else {
os << "??" << " ";
}
WriteUmpireComment(os, illegal_moves, msg);
os << std::endl;
board.ApplyMove(move);
illegal_moves.clear();
}
}
void KriegspielPGN::WriteResult(std::ostream &os) const {
os << GetResultString(state_) << std::endl;
}
std::string KriegspielPGN::GetFilteredString() const {
if (filtered_ == chess::Color::kEmpty) {
return "no";
}
return chess::ColorToString(filtered_);
}
void KriegspielPGN::WriteUmpireComment(
std::ostream &os, const std::vector<std::string> &illegal_moves,
const kriegspiel::KriegspielUmpireMessage& msg) const {
std::string str;
if (msg.capture_type != kriegspiel::KriegspielCaptureType::kNoCapture) {
str += chess::SquareToString(msg.square);
}
std::string check_types_str = CheckTypesToPGNString(msg.check_types);
if (!check_types_str.empty()) {
if (!str.empty()) {
str += ",";
}
str += check_types_str;
}
str += ":";
if (filtered_ == chess::Color::kEmpty ||
filtered_ == chess::OppColor(msg.to_move)) {
str += absl::StrJoin(illegal_moves.rbegin(), illegal_moves.rend(), ",");
} else {
str += std::to_string(illegal_moves.size());
}
WriteComment(os, str);
}
std::ostream& operator<<(std::ostream& os, const PGN& pgn) {
pgn.WriteHeader(os);
os << std::endl;
pgn.WriteMoves(os);
pgn.WriteResult(os);
// There is a possibility to write multiple games in one file. Those games
// should be separated by multiple empty lines.
os << std::endl << std::endl;
return os;
}
} // namespace pgn
} // namespace open_spiel
<commit_msg>PGN tag fixed<commit_after>// Copyright 2019 DeepMind Technologies Ltd. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "open_spiel/games/chess/pgn.h"
#include <iostream>
#include <string>
#include <utility>
#include <vector>
#include "open_spiel/abseil-cpp/absl/strings/match.h"
#include "open_spiel/abseil-cpp/absl/strings/str_cat.h"
#include "open_spiel/abseil-cpp/absl/strings/str_join.h"
#include "open_spiel/spiel_utils.h"
namespace open_spiel {
namespace pgn {
namespace {
template <typename T>
void WriteTag(
std::ostream& os, const std::string& key, const T& value) {
os << "[" << key << " \"" << value << "\"]" << std::endl;
}
void WriteComment(std::ostream& os, const std::string& comment) {
os << "{" << comment << "}";
}
std::string GetResultString(const State &state) {
std::string result_str;
if (state.IsTerminal()) {
std::vector<std::string> results;
for (double ret : state.Returns()) {
if (ret == chess::WinUtility()) {
results.emplace_back("1");
} else if (ret == chess::DrawUtility()) {
results.emplace_back("1/2");
} else if (ret == chess::LossUtility()) {
results.emplace_back("0");
} else {
SpielFatalError("Invalid chess utility");
}
}
result_str = results[chess::ColorToPlayer(chess::Color::kWhite)] + "-" +
results[chess::ColorToPlayer(chess::Color::kBlack)];
} else {
result_str = "*";
}
return result_str;
}
void WriteHeader(std::ostream& os, const std::string& event, int round,
const std::string& white, const std::string& black,
const State& state,
const std::vector<std::pair<std::string, std::string>> &tags = {}) {
WriteTag(os, "Event", event);
WriteTag(os, "Site", "OpenSpiel");
WriteTag(os, "Round", round);
std::string date_str;
if (state.IsTerminal()) {
time_t ttime = time(nullptr);
char buffer[11];
strftime(buffer,sizeof(buffer),"%Y.%m.%d", localtime(&ttime));
date_str = buffer;
} else {
date_str = "????.??.??";
}
WriteTag(os, "Date", date_str);
WriteTag(os, "White", white);
WriteTag(os, "Black", black);
WriteTag(os, "Result", GetResultString(state));
for (const auto &[key, value] : tags) {
WriteTag(os, key, value);
}
}
std::string CheckTypeToPGNString(kriegspiel::KriegspielCheckType check_type) {
switch (check_type) {
case kriegspiel::KriegspielCheckType::kNoCheck:
return "";
case kriegspiel::KriegspielCheckType::kFile:
return "F";
case kriegspiel::KriegspielCheckType::kRank:
return "R";
case kriegspiel::KriegspielCheckType::kLongDiagonal:
return "L";
case kriegspiel::KriegspielCheckType::kShortDiagonal:
return "S";
case kriegspiel::KriegspielCheckType::kKnight:
return "N";
default:
SpielFatalError("Unknown check type");
}
}
std::string CheckTypesToPGNString(
const std::pair<kriegspiel::KriegspielCheckType,
kriegspiel::KriegspielCheckType>& check_type) {
std::string str;
str += CheckTypeToPGNString(check_type.first);
if (check_type.second != kriegspiel::KriegspielCheckType::kNoCheck) {
std::string second_check_str = CheckTypeToPGNString(check_type.second);
if (second_check_str < str) {
str = second_check_str + str;
}
else {
str += second_check_str;
}
}
return str;
}
} // namespace
ChessPGN::ChessPGN(const chess::ChessState &state, const std::string& event,
int round, const std::string& white,
const std::string& black) :
state_(state),
event_(event),
round_(round),
white_(white),
black_(black) {}
void ChessPGN::WriteHeader(std::ostream& os) const {
pgn::WriteHeader(os, event_, round_, white_, black_, state_);
}
void ChessPGN::WriteMoves(std::ostream& os) const {
chess::ChessBoard board = state_.StartBoard();
for (const chess::Move& move : state_.MovesHistory()) {
if (board.ToPlay() == chess::Color::kWhite) {
os << board.Movenumber() << ". ";
}
else {
os << " ";
if (board.Movenumber() > 9) os << " ";
if (board.Movenumber() > 99) os << " ";
}
os << move.ToSAN(board) << std::endl;
board.ApplyMove(move);
}
}
void ChessPGN::WriteResult(std::ostream& os) const {
os << GetResultString(state_) << std::endl;
}
KriegspielPGN::KriegspielPGN(const kriegspiel::KriegspielState &state,
const std::string& event,
int round,
const std::string& white,
const std::string& black,
chess::Color filtered) :
state_(state),
event_(event),
round_(round),
white_(white),
black_(black),
filtered_(filtered) {}
void KriegspielPGN::WriteHeader(std::ostream &os) const {
std::vector<std::pair<std::string, std::string>> tags
{std::make_pair("Variant", "ICC"),
std::make_pair("Filtered", GetFilteredString())};
pgn::WriteHeader(os, event_, round_, white_, black_, state_, tags);
}
void KriegspielPGN::WriteMoves(std::ostream &os) const {
chess::ChessBoard board = state_.StartBoard();
std::vector<std::string> illegal_moves;
for (auto &[move, msg] : state_.MoveMsgHistory()) {
std::string move_str = move.ToSAN(board, true);
if (msg.illegal) {
illegal_moves.emplace_back(move_str);
continue;
}
if (board.ToPlay() == chess::Color::kWhite) {
os << board.Movenumber() << ". ";
}
else {
os << " ";
if (board.Movenumber() > 9) os << " ";
if (board.Movenumber() > 99) os << " ";
}
if (filtered_ == chess::Color::kEmpty || filtered_ == board.ToPlay()) {
os << move_str << " ";
}
else {
os << "??" << " ";
}
WriteUmpireComment(os, illegal_moves, msg);
os << std::endl;
board.ApplyMove(move);
illegal_moves.clear();
}
}
void KriegspielPGN::WriteResult(std::ostream &os) const {
os << GetResultString(state_) << std::endl;
}
std::string KriegspielPGN::GetFilteredString() const {
if (filtered_ == chess::Color::kEmpty) {
return "no";
}
return chess::ColorToString(filtered_);
}
void KriegspielPGN::WriteUmpireComment(
std::ostream &os, const std::vector<std::string> &illegal_moves,
const kriegspiel::KriegspielUmpireMessage& msg) const {
std::string str;
if (msg.capture_type != kriegspiel::KriegspielCaptureType::kNoCapture) {
str += chess::SquareToString(msg.square);
}
std::string check_types_str = CheckTypesToPGNString(msg.check_types);
if (!check_types_str.empty()) {
if (!str.empty()) {
str += ",";
}
str += check_types_str;
}
str += ":";
if (filtered_ == chess::Color::kEmpty ||
filtered_ == chess::OppColor(msg.to_move)) {
str += absl::StrJoin(illegal_moves.rbegin(), illegal_moves.rend(), ",");
} else {
str += std::to_string(illegal_moves.size());
}
WriteComment(os, str);
}
std::ostream& operator<<(std::ostream& os, const PGN& pgn) {
pgn.WriteHeader(os);
os << std::endl;
pgn.WriteMoves(os);
pgn.WriteResult(os);
// There is a possibility to write multiple games in one file. Those games
// should be separated by multiple empty lines.
os << std::endl << std::endl;
return os;
}
} // namespace pgn
} // namespace open_spiel
<|endoftext|>
|
<commit_before>/*
* SchemeSmobAV.c
*
* Scheme small objects (SMOBS) for attention values.
*
* Copyright (c) 2008,2009 Linas Vepstas <linas@linas.org>
*/
#include <cstddef>
#include <libguile.h>
#include <opencog/attentionbank/AttentionBank.h>
#include <opencog/truthvalue/AttentionValue.h>
#include <opencog/guile/SchemeSmob.h>
using namespace opencog;
/* ============================================================== */
/**
* Search for an attention value in a list of values.
* Return the attention value if found, else return null.
* Throw errors if the list is not stictly just key-value pairs
*/
AttentionValuePtr SchemeSmob::get_av_from_list(SCM slist)
{
while (scm_is_pair(slist))
{
SCM sval = SCM_CAR(slist);
if (SCM_SMOB_PREDICATE(SchemeSmob::cog_misc_tag, sval))
{
scm_t_bits misctype = SCM_SMOB_FLAGS(sval);
switch (misctype)
{
case COG_PROTOM: {
ProtoAtomPtr pa(scm_to_protom(sval));
AttentionValuePtr av(AttentionValueCast(pa));
if (av) return av;
}
default:
break;
}
}
slist = SCM_CDR(slist);
}
return nullptr;
}
/* ============================================================== */
std::string SchemeSmob::av_to_string(const AttentionValuePtr& av)
{
#define BUFLEN 120
char buff[BUFLEN];
// We pretend that they are actually short integers.
snprintf(buff, BUFLEN, "(av %f %f %f)",
av->getSTI(), av->getLTI(), av->getVLTI());
return buff;
}
/* ============================================================== */
SCM SchemeSmob::av_to_scm (const AttentionValuePtr& av)
{
return protom_to_scm(ProtoAtomCast(av));
}
/**
* Create a new attention value, with indicated sti/lti/vlti
*/
SCM SchemeSmob::ss_new_av (SCM ssti, SCM slti, SCM svlti)
{
if (!scm_is_real(ssti)) {
scm_wrong_type_arg_msg("cog-new-av", 1, ssti, "double");
}
if (!scm_is_real(slti)) {
scm_wrong_type_arg_msg("cog-new-av", 2, slti, "double");
}
if (!scm_is_real(svlti)) {
scm_wrong_type_arg_msg("cog-new-av", 3, svlti, "double");
}
AttentionValue::sti_t sti = scm_to_double(ssti);
AttentionValue::lti_t lti = scm_to_double(slti);
AttentionValue::vlti_t vlti = scm_to_double(svlti);
AttentionValuePtr av = AttentionValue::createAV(sti, lti, vlti);
return av_to_scm(av);
}
/* ============================================================== */
/**
* Return true if the scm is an attention value
*/
SCM SchemeSmob::ss_av_p (SCM s)
{
ProtoAtomPtr pa(scm_to_protom(s));
if (nullptr == pa) return SCM_BOOL_F;
if (pa->get_type() == ATTENTION_VALUE)
return SCM_BOOL_T;
scm_remember_upto_here_1(s);
return SCM_BOOL_F;
}
/* ============================================================== */
AttentionValuePtr SchemeSmob::verify_av(SCM sav, const char *subrname, int pos)
{
ProtoAtomPtr pa(scm_to_protom(sav));
AttentionValuePtr av(AttentionValueCast(pa));
if (nullptr == av)
scm_wrong_type_arg_msg(subrname, pos, sav, "opencog attention value");
return av;
}
/**
* Return association list holding contents of an attention value
*/
SCM SchemeSmob::ss_av_get_value (SCM s)
{
AttentionValuePtr av = verify_av(s, "cog-av->alist");
// Format AV values to two decimal pts.
auto format = [](double n){
char number_str[20];
sprintf(number_str, "%.2f", n);
return atof(number_str);
};
SCM sti =scm_from_double(format(av->getSTI()));
SCM lti = scm_from_double(format(av->getLTI()));
SCM vlti = scm_from_double(format(av->getVLTI()));
SCM ssti = scm_from_utf8_symbol("sti");
SCM slti = scm_from_utf8_symbol("lti");
SCM svlti = scm_from_utf8_symbol("vlti");
scm_remember_upto_here_1(s);
SCM rc = SCM_EOL;
rc = scm_acons(svlti, vlti, rc);
rc = scm_acons(slti, lti, rc);
rc = scm_acons(ssti, sti, rc);
return rc;
}
/* ===================== END OF FILE ============================ */
<commit_msg>Remove formatting.It can be done from scheme.<commit_after>/*
* SchemeSmobAV.c
*
* Scheme small objects (SMOBS) for attention values.
*
* Copyright (c) 2008,2009 Linas Vepstas <linas@linas.org>
*/
#include <cstddef>
#include <libguile.h>
#include <opencog/attentionbank/AttentionBank.h>
#include <opencog/truthvalue/AttentionValue.h>
#include <opencog/guile/SchemeSmob.h>
using namespace opencog;
/* ============================================================== */
/**
* Search for an attention value in a list of values.
* Return the attention value if found, else return null.
* Throw errors if the list is not stictly just key-value pairs
*/
AttentionValuePtr SchemeSmob::get_av_from_list(SCM slist)
{
while (scm_is_pair(slist))
{
SCM sval = SCM_CAR(slist);
if (SCM_SMOB_PREDICATE(SchemeSmob::cog_misc_tag, sval))
{
scm_t_bits misctype = SCM_SMOB_FLAGS(sval);
switch (misctype)
{
case COG_PROTOM: {
ProtoAtomPtr pa(scm_to_protom(sval));
AttentionValuePtr av(AttentionValueCast(pa));
if (av) return av;
}
default:
break;
}
}
slist = SCM_CDR(slist);
}
return nullptr;
}
/* ============================================================== */
std::string SchemeSmob::av_to_string(const AttentionValuePtr& av)
{
#define BUFLEN 120
char buff[BUFLEN];
// We pretend that they are actually short integers.
snprintf(buff, BUFLEN, "(av %f %f %f)",
av->getSTI(), av->getLTI(), av->getVLTI());
return buff;
}
/* ============================================================== */
SCM SchemeSmob::av_to_scm (const AttentionValuePtr& av)
{
return protom_to_scm(ProtoAtomCast(av));
}
/**
* Create a new attention value, with indicated sti/lti/vlti
*/
SCM SchemeSmob::ss_new_av (SCM ssti, SCM slti, SCM svlti)
{
if (!scm_is_real(ssti)) {
scm_wrong_type_arg_msg("cog-new-av", 1, ssti, "double");
}
if (!scm_is_real(slti)) {
scm_wrong_type_arg_msg("cog-new-av", 2, slti, "double");
}
if (!scm_is_real(svlti)) {
scm_wrong_type_arg_msg("cog-new-av", 3, svlti, "double");
}
AttentionValue::sti_t sti = scm_to_double(ssti);
AttentionValue::lti_t lti = scm_to_double(slti);
AttentionValue::vlti_t vlti = scm_to_double(svlti);
AttentionValuePtr av = AttentionValue::createAV(sti, lti, vlti);
return av_to_scm(av);
}
/* ============================================================== */
/**
* Return true if the scm is an attention value
*/
SCM SchemeSmob::ss_av_p (SCM s)
{
ProtoAtomPtr pa(scm_to_protom(s));
if (nullptr == pa) return SCM_BOOL_F;
if (pa->get_type() == ATTENTION_VALUE)
return SCM_BOOL_T;
scm_remember_upto_here_1(s);
return SCM_BOOL_F;
}
/* ============================================================== */
AttentionValuePtr SchemeSmob::verify_av(SCM sav, const char *subrname, int pos)
{
ProtoAtomPtr pa(scm_to_protom(sav));
AttentionValuePtr av(AttentionValueCast(pa));
if (nullptr == av)
scm_wrong_type_arg_msg(subrname, pos, sav, "opencog attention value");
return av;
}
/**
* Return association list holding contents of an attention value
*/
SCM SchemeSmob::ss_av_get_value (SCM s)
{
AttentionValuePtr av = verify_av(s, "cog-av->alist");
SCM sti =scm_from_double(av->getSTI());
SCM lti = scm_from_double(av->getLTI());
SCM vlti = scm_from_double(av->getVLTI());
SCM ssti = scm_from_utf8_symbol("sti");
SCM slti = scm_from_utf8_symbol("lti");
SCM svlti = scm_from_utf8_symbol("vlti");
scm_remember_upto_here_1(s);
SCM rc = SCM_EOL;
rc = scm_acons(svlti, vlti, rc);
rc = scm_acons(slti, lti, rc);
rc = scm_acons(ssti, sti, rc);
return rc;
}
/* ===================== END OF FILE ============================ */
<|endoftext|>
|
<commit_before>// @(#)root/net:$Id$
// Author: Fons Rademakers 19/1/2001
/*************************************************************************
* Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TPServerSocket //
// //
// This class implements parallel server sockets. A parallel server //
// socket waits for requests to come in over the network. It performs //
// some operation based on that request and then possibly returns a //
// full duplex parallel socket to the requester. The actual work is //
// done via the TSystem class (either TUnixSystem or TWinNTSystem). //
// //
//////////////////////////////////////////////////////////////////////////
#include "TPServerSocket.h"
#include "TPSocket.h"
#include "TROOT.h"
#include "TVirtualMutex.h"
ClassImp(TPServerSocket)
//______________________________________________________________________________
TPServerSocket::TPServerSocket(Int_t port, Bool_t reuse, Int_t backlog,
Int_t tcpwindowsize) :
TServerSocket(port, reuse, backlog, tcpwindowsize)
{
// Create a parallel server socket object on a specified port. Set reuse
// to true to force reuse of the server socket (i.e. do not wait for the
// time out to pass). Using backlog one can set the desirable queue length
// for pending connections.
// Use tcpwindowsize to specify the size of the receive buffer, it has
// to be specified here to make sure the window scale option is set (for
// tcpwindowsize > 65KB and for platforms supporting window scaling).
// Use IsValid() to check the validity of the
// server socket. In case server socket is not valid use GetErrorCode()
// to obtain the specific error value. These values are:
// 0 = no error (socket is valid)
// -1 = low level socket() call failed
// -2 = low level bind() call failed
// -3 = low level listen() call failed
// Every valid server socket is added to the TROOT sockets list which
// will make sure that any open sockets are properly closed on
// program termination.
fTcpWindowSize = tcpwindowsize;
SetName("PServerSocket");
}
//______________________________________________________________________________
TPServerSocket::TPServerSocket(const char *service, Bool_t reuse, Int_t backlog,
Int_t tcpwindowsize) :
TServerSocket(service, reuse, backlog, tcpwindowsize)
{
// Create a parallel server socket object for a named service. Set reuse
// to true to force reuse of the server socket (i.e. do not wait for the
// time out to pass). Using backlog one can set the desirable queue length
// for pending connections.
// Use tcpwindowsize to specify the size of the receive buffer, it has
// to be specified here to make sure the window scale option is set (for
// tcpwindowsize > 65KB and for platforms supporting window scaling).
// Use IsValid() to check the validity of the
// server socket. In case server socket is not valid use GetErrorCode()
// to obtain the specific error value. These values are:
// 0 = no error (socket is valid)
// -1 = low level socket() call failed
// -2 = low level bind() call failed
// -3 = low level listen() call failed
// Every valid server socket is added to the TROOT sockets list which
// will make sure that any open sockets are properly closed on
// program termination.
fTcpWindowSize = tcpwindowsize;
SetName("PServerSocket");
}
//______________________________________________________________________________
TSocket *TPServerSocket::Accept(UChar_t Opt)
{
// Accept a connection on a parallel server socket. Returns a full-duplex
// parallel communication TPSocket object. If no pending connections are
// present on the queue and nonblocking mode has not been enabled
// with SetOption(kNoBlock,1) the call blocks until a connection is
// present. The returned socket must be deleted by the user. The socket
// is also added to the TROOT sockets list which will make sure that
// any open sockets are properly closed on program termination.
// In case of error 0 is returned and in case non-blocking I/O is
// enabled and no connections are available -1 is returned.
TSocket *setupSocket = 0;
TSocket **pSockets;
TPSocket *newPSocket = 0;
Int_t size, port;
// wait for the incoming connections to the server and accept them
setupSocket = TServerSocket::Accept(Opt);
if (setupSocket <= 0) return 0;
// receive the port number and number of parallel sockets from the
// client and establish 'n' connections
if (setupSocket->Recv(port, size) < 0) {
Error("Accept", "error receiving port number and number of sockets");
return 0;
}
// Check if client is running in single mode
if (size == 0) {
pSockets = new TSocket*[1];
pSockets[0] = setupSocket;
// create TPSocket object with the original socket
newPSocket = new TPSocket(pSockets, 1);
} else {
pSockets = new TSocket*[size];
for (int i = 0; i < size; i++) {
pSockets[i] = new TSocket(setupSocket->GetInetAddress(),
port, fTcpWindowSize);
R__LOCKGUARD2(gROOTMutex);
gROOT->GetListOfSockets()->Remove(pSockets[i]);
}
// create TPSocket object with all the accepted sockets
newPSocket = new TPSocket(pSockets, size);
}
// Transmit authentication information, if any
if (setupSocket->IsAuthenticated())
newPSocket->SetSecContext(setupSocket->GetSecContext());
// clean up, if needed
if (size > 0)
delete setupSocket;
// return the TSocket object
return newPSocket;
}
<commit_msg>Suppress warning: ordered comparison of pointer with integer zero<commit_after>// @(#)root/net:$Id$
// Author: Fons Rademakers 19/1/2001
/*************************************************************************
* Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TPServerSocket //
// //
// This class implements parallel server sockets. A parallel server //
// socket waits for requests to come in over the network. It performs //
// some operation based on that request and then possibly returns a //
// full duplex parallel socket to the requester. The actual work is //
// done via the TSystem class (either TUnixSystem or TWinNTSystem). //
// //
//////////////////////////////////////////////////////////////////////////
#include "TPServerSocket.h"
#include "TPSocket.h"
#include "TROOT.h"
#include "TVirtualMutex.h"
ClassImp(TPServerSocket)
//______________________________________________________________________________
TPServerSocket::TPServerSocket(Int_t port, Bool_t reuse, Int_t backlog,
Int_t tcpwindowsize) :
TServerSocket(port, reuse, backlog, tcpwindowsize)
{
// Create a parallel server socket object on a specified port. Set reuse
// to true to force reuse of the server socket (i.e. do not wait for the
// time out to pass). Using backlog one can set the desirable queue length
// for pending connections.
// Use tcpwindowsize to specify the size of the receive buffer, it has
// to be specified here to make sure the window scale option is set (for
// tcpwindowsize > 65KB and for platforms supporting window scaling).
// Use IsValid() to check the validity of the
// server socket. In case server socket is not valid use GetErrorCode()
// to obtain the specific error value. These values are:
// 0 = no error (socket is valid)
// -1 = low level socket() call failed
// -2 = low level bind() call failed
// -3 = low level listen() call failed
// Every valid server socket is added to the TROOT sockets list which
// will make sure that any open sockets are properly closed on
// program termination.
fTcpWindowSize = tcpwindowsize;
SetName("PServerSocket");
}
//______________________________________________________________________________
TPServerSocket::TPServerSocket(const char *service, Bool_t reuse, Int_t backlog,
Int_t tcpwindowsize) :
TServerSocket(service, reuse, backlog, tcpwindowsize)
{
// Create a parallel server socket object for a named service. Set reuse
// to true to force reuse of the server socket (i.e. do not wait for the
// time out to pass). Using backlog one can set the desirable queue length
// for pending connections.
// Use tcpwindowsize to specify the size of the receive buffer, it has
// to be specified here to make sure the window scale option is set (for
// tcpwindowsize > 65KB and for platforms supporting window scaling).
// Use IsValid() to check the validity of the
// server socket. In case server socket is not valid use GetErrorCode()
// to obtain the specific error value. These values are:
// 0 = no error (socket is valid)
// -1 = low level socket() call failed
// -2 = low level bind() call failed
// -3 = low level listen() call failed
// Every valid server socket is added to the TROOT sockets list which
// will make sure that any open sockets are properly closed on
// program termination.
fTcpWindowSize = tcpwindowsize;
SetName("PServerSocket");
}
//______________________________________________________________________________
TSocket *TPServerSocket::Accept(UChar_t Opt)
{
// Accept a connection on a parallel server socket. Returns a full-duplex
// parallel communication TPSocket object. If no pending connections are
// present on the queue and nonblocking mode has not been enabled
// with SetOption(kNoBlock,1) the call blocks until a connection is
// present. The returned socket must be deleted by the user. The socket
// is also added to the TROOT sockets list which will make sure that
// any open sockets are properly closed on program termination.
// In case of error 0 is returned and in case non-blocking I/O is
// enabled and no connections are available -1 is returned.
TSocket *setupSocket = 0;
TSocket **pSockets;
TPSocket *newPSocket = 0;
Int_t size, port;
// wait for the incoming connections to the server and accept them
setupSocket = TServerSocket::Accept(Opt);
if (setupSocket == 0) return 0;
// receive the port number and number of parallel sockets from the
// client and establish 'n' connections
if (setupSocket->Recv(port, size) < 0) {
Error("Accept", "error receiving port number and number of sockets");
return 0;
}
// Check if client is running in single mode
if (size == 0) {
pSockets = new TSocket*[1];
pSockets[0] = setupSocket;
// create TPSocket object with the original socket
newPSocket = new TPSocket(pSockets, 1);
} else {
pSockets = new TSocket*[size];
for (int i = 0; i < size; i++) {
pSockets[i] = new TSocket(setupSocket->GetInetAddress(),
port, fTcpWindowSize);
R__LOCKGUARD2(gROOTMutex);
gROOT->GetListOfSockets()->Remove(pSockets[i]);
}
// create TPSocket object with all the accepted sockets
newPSocket = new TPSocket(pSockets, size);
}
// Transmit authentication information, if any
if (setupSocket->IsAuthenticated())
newPSocket->SetSecContext(setupSocket->GetSecContext());
// clean up, if needed
if (size > 0)
delete setupSocket;
// return the TSocket object
return newPSocket;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2018 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 "src/traced/probes/probes_producer.h"
#include <stdio.h>
#include <sys/stat.h>
#include <queue>
#include <string>
#include "perfetto/base/logging.h"
#include "perfetto/base/weak_ptr.h"
#include "perfetto/traced/traced.h"
#include "perfetto/tracing/core/data_source_config.h"
#include "perfetto/tracing/core/data_source_descriptor.h"
#include "perfetto/tracing/core/ftrace_config.h"
#include "perfetto/tracing/core/trace_config.h"
#include "perfetto/tracing/core/trace_packet.h"
#include "src/traced/probes/filesystem/inode_file_data_source.h"
#include "perfetto/trace/filesystem/inode_file_map.pbzero.h"
#include "perfetto/trace/ftrace/ftrace_event_bundle.pbzero.h"
#include "perfetto/trace/trace_packet.pbzero.h"
namespace perfetto {
namespace {
uint64_t kInitialConnectionBackoffMs = 100;
uint64_t kMaxConnectionBackoffMs = 30 * 1000;
constexpr char kFtraceSourceName[] = "com.google.perfetto.ftrace";
constexpr char kProcessStatsSourceName[] = "com.google.perfetto.process_stats";
constexpr char kInodeMapSourceName[] = "com.google.perfetto.inode_file_map";
} // namespace.
// State transition diagram:
// +----------------------------+
// v +
// NotStarted -> NotConnected -> Connecting -> Connected
// ^ +
// +--------------+
//
ProbesProducer::ProbesProducer() {}
ProbesProducer::~ProbesProducer() = default;
void ProbesProducer::OnConnect() {
PERFETTO_DCHECK(state_ == kConnecting);
state_ = kConnected;
ResetConnectionBackoff();
PERFETTO_LOG("Connected to the service");
DataSourceDescriptor ftrace_descriptor;
ftrace_descriptor.set_name(kFtraceSourceName);
endpoint_->RegisterDataSource(ftrace_descriptor, [](DataSourceInstanceID) {});
DataSourceDescriptor process_stats_descriptor;
process_stats_descriptor.set_name(kProcessStatsSourceName);
endpoint_->RegisterDataSource(process_stats_descriptor,
[](DataSourceInstanceID) {});
DataSourceDescriptor inode_map_descriptor;
inode_map_descriptor.set_name(kInodeMapSourceName);
endpoint_->RegisterDataSource(inode_map_descriptor,
[](DataSourceInstanceID) {});
}
void ProbesProducer::OnDisconnect() {
PERFETTO_DCHECK(state_ == kConnected || state_ == kConnecting);
state_ = kNotConnected;
PERFETTO_LOG("Disconnected from tracing service");
IncreaseConnectionBackoff();
// TODO(hjd): Erase all sinks and add e2e test for this.
task_runner_->PostDelayedTask([this] { this->Connect(); },
connection_backoff_ms_);
}
void ProbesProducer::CreateDataSourceInstance(DataSourceInstanceID instance_id,
const DataSourceConfig& config) {
// TODO(hjd): This a hack since we don't actually know the session id. For
// now we'll assume anything wit hthe same target buffer is in the same
// session.
TracingSessionID session_id = config.target_buffer();
if (config.name() == kFtraceSourceName) {
if (!CreateFtraceDataSourceInstance(session_id, instance_id, config))
failed_sources_.insert(instance_id);
} else if (config.name() == kInodeMapSourceName) {
CreateInodeFileDataSourceInstance(session_id, instance_id, config);
} else if (config.name() == kProcessStatsSourceName) {
CreateProcessStatsDataSourceInstance(session_id, instance_id, config);
} else {
PERFETTO_ELOG("Data source name: %s not recognised.",
config.name().c_str());
return;
}
std::map<TracingSessionID, InodeFileDataSource*> file_sources;
std::map<TracingSessionID, ProcessStatsDataSource*> ps_sources;
for (const auto& pair : file_map_sources_)
file_sources[pair.second->session_id()] = pair.second.get();
for (const auto& pair : process_stats_sources_)
ps_sources[pair.second->session_id()] = pair.second.get();
for (const auto& id_to_source : delegates_) {
const std::unique_ptr<SinkDelegate>& source = id_to_source.second;
if (session_id != source->session_id())
continue;
if (!source->ps_source() && ps_sources.count(session_id))
source->set_ps_source(ps_sources[session_id]->GetWeakPtr());
if (!source->file_source() && file_sources.count(session_id))
source->set_file_source(file_sources[session_id]->GetWeakPtr());
}
}
void ProbesProducer::AddWatchdogsTimer(DataSourceInstanceID id,
const DataSourceConfig& config) {
if (config.trace_duration_ms() != 0)
watchdogs_.emplace(id, base::Watchdog::GetInstance()->CreateFatalTimer(
5000 + 2 * config.trace_duration_ms()));
}
bool ProbesProducer::CreateFtraceDataSourceInstance(
TracingSessionID session_id,
DataSourceInstanceID id,
const DataSourceConfig& config) {
// Don't retry if FtraceController::Create() failed once.
// This can legitimately happen on user builds where we cannot access the
// debug paths, e.g., because of SELinux rules.
if (ftrace_creation_failed_)
return false;
// Lazily create on the first instance.
if (!ftrace_) {
ftrace_ = FtraceController::Create(task_runner_);
if (!ftrace_) {
PERFETTO_ELOG("Failed to create FtraceController");
ftrace_creation_failed_ = true;
return false;
}
ftrace_->DisableAllEvents();
ftrace_->ClearTrace();
}
PERFETTO_LOG("Ftrace start (id=%" PRIu64 ", target_buf=%" PRIu32 ")", id,
config.target_buffer());
FtraceConfig proto_config = config.ftrace_config();
// TODO(hjd): Static cast is bad, target_buffer() should return a BufferID.
auto trace_writer = endpoint_->CreateTraceWriter(
static_cast<BufferID>(config.target_buffer()));
auto delegate = std::unique_ptr<SinkDelegate>(
new SinkDelegate(session_id, task_runner_, std::move(trace_writer)));
auto sink = ftrace_->CreateSink(std::move(proto_config), delegate.get());
if (!sink) {
PERFETTO_ELOG("Failed to start tracing (maybe someone else is using it?)");
return false;
}
delegate->set_sink(std::move(sink));
delegates_.emplace(id, std::move(delegate));
AddWatchdogsTimer(id, config);
return true;
}
void ProbesProducer::CreateInodeFileDataSourceInstance(
TracingSessionID session_id,
DataSourceInstanceID id,
const DataSourceConfig& source_config) {
PERFETTO_LOG("Inode file map start (id=%" PRIu64 ", target_buf=%" PRIu32 ")",
id, source_config.target_buffer());
auto trace_writer = endpoint_->CreateTraceWriter(
static_cast<BufferID>(source_config.target_buffer()));
if (system_inodes_.empty())
CreateStaticDeviceToInodeMap("/system/", &system_inodes_);
auto file_map_source =
std::unique_ptr<InodeFileDataSource>(new InodeFileDataSource(
session_id, &system_inodes_, &cache_, std::move(trace_writer)));
file_map_sources_.emplace(id, std::move(file_map_source));
AddWatchdogsTimer(id, source_config);
}
void ProbesProducer::CreateProcessStatsDataSourceInstance(
TracingSessionID session_id,
DataSourceInstanceID id,
const DataSourceConfig& config) {
PERFETTO_DCHECK(process_stats_sources_.count(id) == 0);
auto trace_writer = endpoint_->CreateTraceWriter(
static_cast<BufferID>(config.target_buffer()));
auto source = std::unique_ptr<ProcessStatsDataSource>(
new ProcessStatsDataSource(session_id, std::move(trace_writer)));
auto it_and_inserted = process_stats_sources_.emplace(id, std::move(source));
PERFETTO_DCHECK(it_and_inserted.second);
it_and_inserted.first->second->WriteAllProcesses();
}
void ProbesProducer::TearDownDataSourceInstance(DataSourceInstanceID id) {
PERFETTO_LOG("Producer stop (id=%" PRIu64 ")", id);
// |id| could be the id of any of the datasources we handle:
PERFETTO_DCHECK((failed_sources_.count(id) +
process_stats_sources_.count(id) +
file_map_sources_.count(id)) == 1);
failed_sources_.erase(id);
delegates_.erase(id);
process_stats_sources_.erase(id);
file_map_sources_.erase(id);
watchdogs_.erase(id);
}
void ProbesProducer::OnTracingStart() {}
void ProbesProducer::OnTracingStop() {}
void ProbesProducer::ConnectWithRetries(const char* socket_name,
base::TaskRunner* task_runner) {
PERFETTO_DCHECK(state_ == kNotStarted);
state_ = kNotConnected;
ResetConnectionBackoff();
socket_name_ = socket_name;
task_runner_ = task_runner;
Connect();
}
void ProbesProducer::Connect() {
PERFETTO_DCHECK(state_ == kNotConnected);
state_ = kConnecting;
endpoint_ = ProducerIPCClient::Connect(socket_name_, this, task_runner_);
}
void ProbesProducer::IncreaseConnectionBackoff() {
connection_backoff_ms_ *= 2;
if (connection_backoff_ms_ > kMaxConnectionBackoffMs)
connection_backoff_ms_ = kMaxConnectionBackoffMs;
}
void ProbesProducer::ResetConnectionBackoff() {
connection_backoff_ms_ = kInitialConnectionBackoffMs;
}
ProbesProducer::SinkDelegate::SinkDelegate(TracingSessionID id,
base::TaskRunner* task_runner,
std::unique_ptr<TraceWriter> writer)
: session_id_(id),
task_runner_(task_runner),
writer_(std::move(writer)),
weak_factory_(this) {}
ProbesProducer::SinkDelegate::~SinkDelegate() = default;
ProbesProducer::FtraceBundleHandle
ProbesProducer::SinkDelegate::GetBundleForCpu(size_t) {
trace_packet_ = writer_->NewTracePacket();
return FtraceBundleHandle(trace_packet_->set_ftrace_events());
}
void ProbesProducer::SinkDelegate::OnBundleComplete(
size_t,
FtraceBundleHandle,
const FtraceMetadata& metadata) {
trace_packet_->Finalize();
if (file_source_ && !metadata.inode_and_device.empty()) {
auto inodes = metadata.inode_and_device;
auto weak_file_source = file_source_;
task_runner_->PostTask([weak_file_source, inodes] {
if (weak_file_source)
weak_file_source->OnInodes(inodes);
});
}
}
} // namespace perfetto
<commit_msg>traced_probes: Fix DCHECK<commit_after>/*
* Copyright (C) 2018 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 "src/traced/probes/probes_producer.h"
#include <stdio.h>
#include <sys/stat.h>
#include <queue>
#include <string>
#include "perfetto/base/logging.h"
#include "perfetto/base/weak_ptr.h"
#include "perfetto/traced/traced.h"
#include "perfetto/tracing/core/data_source_config.h"
#include "perfetto/tracing/core/data_source_descriptor.h"
#include "perfetto/tracing/core/ftrace_config.h"
#include "perfetto/tracing/core/trace_config.h"
#include "perfetto/tracing/core/trace_packet.h"
#include "src/traced/probes/filesystem/inode_file_data_source.h"
#include "perfetto/trace/filesystem/inode_file_map.pbzero.h"
#include "perfetto/trace/ftrace/ftrace_event_bundle.pbzero.h"
#include "perfetto/trace/trace_packet.pbzero.h"
namespace perfetto {
namespace {
uint64_t kInitialConnectionBackoffMs = 100;
uint64_t kMaxConnectionBackoffMs = 30 * 1000;
constexpr char kFtraceSourceName[] = "com.google.perfetto.ftrace";
constexpr char kProcessStatsSourceName[] = "com.google.perfetto.process_stats";
constexpr char kInodeMapSourceName[] = "com.google.perfetto.inode_file_map";
} // namespace.
// State transition diagram:
// +----------------------------+
// v +
// NotStarted -> NotConnected -> Connecting -> Connected
// ^ +
// +--------------+
//
ProbesProducer::ProbesProducer() {}
ProbesProducer::~ProbesProducer() = default;
void ProbesProducer::OnConnect() {
PERFETTO_DCHECK(state_ == kConnecting);
state_ = kConnected;
ResetConnectionBackoff();
PERFETTO_LOG("Connected to the service");
DataSourceDescriptor ftrace_descriptor;
ftrace_descriptor.set_name(kFtraceSourceName);
endpoint_->RegisterDataSource(ftrace_descriptor, [](DataSourceInstanceID) {});
DataSourceDescriptor process_stats_descriptor;
process_stats_descriptor.set_name(kProcessStatsSourceName);
endpoint_->RegisterDataSource(process_stats_descriptor,
[](DataSourceInstanceID) {});
DataSourceDescriptor inode_map_descriptor;
inode_map_descriptor.set_name(kInodeMapSourceName);
endpoint_->RegisterDataSource(inode_map_descriptor,
[](DataSourceInstanceID) {});
}
void ProbesProducer::OnDisconnect() {
PERFETTO_DCHECK(state_ == kConnected || state_ == kConnecting);
state_ = kNotConnected;
PERFETTO_LOG("Disconnected from tracing service");
IncreaseConnectionBackoff();
// TODO(hjd): Erase all sinks and add e2e test for this.
task_runner_->PostDelayedTask([this] { this->Connect(); },
connection_backoff_ms_);
}
void ProbesProducer::CreateDataSourceInstance(DataSourceInstanceID instance_id,
const DataSourceConfig& config) {
// TODO(hjd): This a hack since we don't actually know the session id. For
// now we'll assume anything wit hthe same target buffer is in the same
// session.
TracingSessionID session_id = config.target_buffer();
if (config.name() == kFtraceSourceName) {
if (!CreateFtraceDataSourceInstance(session_id, instance_id, config))
failed_sources_.insert(instance_id);
} else if (config.name() == kInodeMapSourceName) {
CreateInodeFileDataSourceInstance(session_id, instance_id, config);
} else if (config.name() == kProcessStatsSourceName) {
CreateProcessStatsDataSourceInstance(session_id, instance_id, config);
} else {
PERFETTO_ELOG("Data source name: %s not recognised.",
config.name().c_str());
return;
}
std::map<TracingSessionID, InodeFileDataSource*> file_sources;
std::map<TracingSessionID, ProcessStatsDataSource*> ps_sources;
for (const auto& pair : file_map_sources_)
file_sources[pair.second->session_id()] = pair.second.get();
for (const auto& pair : process_stats_sources_)
ps_sources[pair.second->session_id()] = pair.second.get();
for (const auto& id_to_source : delegates_) {
const std::unique_ptr<SinkDelegate>& source = id_to_source.second;
if (session_id != source->session_id())
continue;
if (!source->ps_source() && ps_sources.count(session_id))
source->set_ps_source(ps_sources[session_id]->GetWeakPtr());
if (!source->file_source() && file_sources.count(session_id))
source->set_file_source(file_sources[session_id]->GetWeakPtr());
}
}
void ProbesProducer::AddWatchdogsTimer(DataSourceInstanceID id,
const DataSourceConfig& config) {
if (config.trace_duration_ms() != 0)
watchdogs_.emplace(id, base::Watchdog::GetInstance()->CreateFatalTimer(
5000 + 2 * config.trace_duration_ms()));
}
bool ProbesProducer::CreateFtraceDataSourceInstance(
TracingSessionID session_id,
DataSourceInstanceID id,
const DataSourceConfig& config) {
// Don't retry if FtraceController::Create() failed once.
// This can legitimately happen on user builds where we cannot access the
// debug paths, e.g., because of SELinux rules.
if (ftrace_creation_failed_)
return false;
// Lazily create on the first instance.
if (!ftrace_) {
ftrace_ = FtraceController::Create(task_runner_);
if (!ftrace_) {
PERFETTO_ELOG("Failed to create FtraceController");
ftrace_creation_failed_ = true;
return false;
}
ftrace_->DisableAllEvents();
ftrace_->ClearTrace();
}
PERFETTO_LOG("Ftrace start (id=%" PRIu64 ", target_buf=%" PRIu32 ")", id,
config.target_buffer());
FtraceConfig proto_config = config.ftrace_config();
// TODO(hjd): Static cast is bad, target_buffer() should return a BufferID.
auto trace_writer = endpoint_->CreateTraceWriter(
static_cast<BufferID>(config.target_buffer()));
auto delegate = std::unique_ptr<SinkDelegate>(
new SinkDelegate(session_id, task_runner_, std::move(trace_writer)));
auto sink = ftrace_->CreateSink(std::move(proto_config), delegate.get());
if (!sink) {
PERFETTO_ELOG("Failed to start tracing (maybe someone else is using it?)");
return false;
}
delegate->set_sink(std::move(sink));
delegates_.emplace(id, std::move(delegate));
AddWatchdogsTimer(id, config);
return true;
}
void ProbesProducer::CreateInodeFileDataSourceInstance(
TracingSessionID session_id,
DataSourceInstanceID id,
const DataSourceConfig& source_config) {
PERFETTO_LOG("Inode file map start (id=%" PRIu64 ", target_buf=%" PRIu32 ")",
id, source_config.target_buffer());
auto trace_writer = endpoint_->CreateTraceWriter(
static_cast<BufferID>(source_config.target_buffer()));
if (system_inodes_.empty())
CreateStaticDeviceToInodeMap("/system/", &system_inodes_);
auto file_map_source =
std::unique_ptr<InodeFileDataSource>(new InodeFileDataSource(
session_id, &system_inodes_, &cache_, std::move(trace_writer)));
file_map_sources_.emplace(id, std::move(file_map_source));
AddWatchdogsTimer(id, source_config);
}
void ProbesProducer::CreateProcessStatsDataSourceInstance(
TracingSessionID session_id,
DataSourceInstanceID id,
const DataSourceConfig& config) {
PERFETTO_DCHECK(process_stats_sources_.count(id) == 0);
auto trace_writer = endpoint_->CreateTraceWriter(
static_cast<BufferID>(config.target_buffer()));
auto source = std::unique_ptr<ProcessStatsDataSource>(
new ProcessStatsDataSource(session_id, std::move(trace_writer)));
auto it_and_inserted = process_stats_sources_.emplace(id, std::move(source));
PERFETTO_DCHECK(it_and_inserted.second);
it_and_inserted.first->second->WriteAllProcesses();
}
void ProbesProducer::TearDownDataSourceInstance(DataSourceInstanceID id) {
PERFETTO_LOG("Producer stop (id=%" PRIu64 ")", id);
// |id| could be the id of any of the datasources we handle:
PERFETTO_DCHECK((failed_sources_.count(id) + delegates_.count(id) +
process_stats_sources_.count(id) +
file_map_sources_.count(id)) == 1);
failed_sources_.erase(id);
delegates_.erase(id);
process_stats_sources_.erase(id);
file_map_sources_.erase(id);
watchdogs_.erase(id);
}
void ProbesProducer::OnTracingStart() {}
void ProbesProducer::OnTracingStop() {}
void ProbesProducer::ConnectWithRetries(const char* socket_name,
base::TaskRunner* task_runner) {
PERFETTO_DCHECK(state_ == kNotStarted);
state_ = kNotConnected;
ResetConnectionBackoff();
socket_name_ = socket_name;
task_runner_ = task_runner;
Connect();
}
void ProbesProducer::Connect() {
PERFETTO_DCHECK(state_ == kNotConnected);
state_ = kConnecting;
endpoint_ = ProducerIPCClient::Connect(socket_name_, this, task_runner_);
}
void ProbesProducer::IncreaseConnectionBackoff() {
connection_backoff_ms_ *= 2;
if (connection_backoff_ms_ > kMaxConnectionBackoffMs)
connection_backoff_ms_ = kMaxConnectionBackoffMs;
}
void ProbesProducer::ResetConnectionBackoff() {
connection_backoff_ms_ = kInitialConnectionBackoffMs;
}
ProbesProducer::SinkDelegate::SinkDelegate(TracingSessionID id,
base::TaskRunner* task_runner,
std::unique_ptr<TraceWriter> writer)
: session_id_(id),
task_runner_(task_runner),
writer_(std::move(writer)),
weak_factory_(this) {}
ProbesProducer::SinkDelegate::~SinkDelegate() = default;
ProbesProducer::FtraceBundleHandle
ProbesProducer::SinkDelegate::GetBundleForCpu(size_t) {
trace_packet_ = writer_->NewTracePacket();
return FtraceBundleHandle(trace_packet_->set_ftrace_events());
}
void ProbesProducer::SinkDelegate::OnBundleComplete(
size_t,
FtraceBundleHandle,
const FtraceMetadata& metadata) {
trace_packet_->Finalize();
if (file_source_ && !metadata.inode_and_device.empty()) {
auto inodes = metadata.inode_and_device;
auto weak_file_source = file_source_;
task_runner_->PostTask([weak_file_source, inodes] {
if (weak_file_source)
weak_file_source->OnInodes(inodes);
});
}
}
} // namespace perfetto
<|endoftext|>
|
<commit_before>#include "rosplan_planning_system/PlannerInterface/PlannerInterface.h"
namespace KCL_rosplan {
/*----------------------*/
/* Problem subscription */
/*----------------------*/
void PlannerInterface::problemCallback(const std_msgs::String& problemInstance) {
ROS_INFO("KCL: (%s) Problem received.", ros::this_node::getName().c_str());
problem_instance_received = true;
problem_instance_time = ros::WallTime::now().toSec();
problem_instance = problemInstance.data;
}
/*--------------------*/
/* Planning interface */
/*--------------------*/
/**
* planning system service method (1)
* loads parameters from param server
*/
bool PlannerInterface::runPlanningServerDefault(std_srvs::Empty::Request &req, std_srvs::Empty::Response &res) {
// defaults
use_problem_topic = false;
data_path = "common/";
domain_path = "common/domain.pddl";
problem_path = "common/problem.pddl";
planner_command = "timeout 60 common/bin/popf -n DOMAIN PROBLEM";
// load params
node_handle->getParam("use_problem_topic", use_problem_topic);
node_handle->getParam("domain_path", domain_path);
node_handle->getParam("data_path", data_path);
node_handle->getParam("problem_path", problem_path);
node_handle->getParam("planner_command", planner_command);
// call planning server
runPlanningServer(domain_path, problem_path, data_path, planner_command, use_problem_topic);
return true;
}
/**
* planning system service method (2)
* loads parameters from service request
*/
bool PlannerInterface::runPlanningServerParams(rosplan_dispatch_msgs::PlanningService::Request &req, rosplan_dispatch_msgs::PlanningService::Response &res) {
// call planning server
res.plan_found = runPlanningServer(req.domain_path, req.problem_path, req.data_path, req.planner_command, req.use_problem_topic);
return true;
}
/**
* planning system service method (3)
* loads parameters from actionlib goal
*/
void PlannerInterface::runPlanningServerAction(const rosplan_dispatch_msgs::PlanGoalConstPtr& goal) {
// call planning server
if(runPlanningServer(goal->domain_path, goal->problem_path, goal->data_path, goal->planner_command, goal->use_problem_topic)) {
plan_server->setSucceeded();
} else {
plan_server->setAborted();
}
}
/**
* planning system; prepares planning; calls planner; parses plan.
*/
bool PlannerInterface::runPlanningServer(std::string domainPath, std::string problemPath, std::string dataPath, std::string plannerCommand, bool useProblemTopic) {
// save parameters
data_path = dataPath;
domain_path = domainPath;
problem_path = problemPath;
planner_command = plannerCommand;
use_problem_topic = useProblemTopic;
// check if data_path ends in "/" and add "/" if not
const char *last_char = &data_path.back();
if (strcmp(last_char,"/") != 0)data_path = data_path + "/";
// set problem name for ROS_INFO
std::size_t lastDivide = problem_path.find_last_of("/\\");
if(lastDivide != std::string::npos) {
problem_name = problem_path.substr(lastDivide+1);
} else {
problem_name = problem_path;
}
if(use_problem_topic && !problem_instance_received) {
ROS_INFO("KCL: (%s) (%s) Problem was not published yet.", ros::this_node::getName().c_str(), problem_name.c_str());
return false;
}
bool success = runPlanner();
// publish planner output
if(success) {
std_msgs::String planMsg;
planMsg.data = planner_output;
plan_publisher.publish(planMsg);
}
return success;
}
} // close namespace
<commit_msg>added planner interface return value until we can get a proper service in place<commit_after>#include "rosplan_planning_system/PlannerInterface/PlannerInterface.h"
namespace KCL_rosplan {
/*----------------------*/
/* Problem subscription */
/*----------------------*/
void PlannerInterface::problemCallback(const std_msgs::String& problemInstance) {
ROS_INFO("KCL: (%s) Problem received.", ros::this_node::getName().c_str());
problem_instance_received = true;
problem_instance_time = ros::WallTime::now().toSec();
problem_instance = problemInstance.data;
}
/*--------------------*/
/* Planning interface */
/*--------------------*/
/**
* planning system service method (1)
* loads parameters from param server
*/
bool PlannerInterface::runPlanningServerDefault(std_srvs::Empty::Request &req, std_srvs::Empty::Response &res) {
// defaults
use_problem_topic = false;
data_path = "common/";
domain_path = "common/domain.pddl";
problem_path = "common/problem.pddl";
planner_command = "timeout 60 common/bin/popf -n DOMAIN PROBLEM";
// load params
node_handle->getParam("use_problem_topic", use_problem_topic);
node_handle->getParam("domain_path", domain_path);
node_handle->getParam("data_path", data_path);
node_handle->getParam("problem_path", problem_path);
node_handle->getParam("planner_command", planner_command);
// call planning server
return runPlanningServer(domain_path, problem_path, data_path, planner_command, use_problem_topic);
}
/**
* planning system service method (2)
* loads parameters from service request
*/
bool PlannerInterface::runPlanningServerParams(rosplan_dispatch_msgs::PlanningService::Request &req, rosplan_dispatch_msgs::PlanningService::Response &res) {
// call planning server
res.plan_found = runPlanningServer(req.domain_path, req.problem_path, req.data_path, req.planner_command, req.use_problem_topic);
return true;
}
/**
* planning system service method (3)
* loads parameters from actionlib goal
*/
void PlannerInterface::runPlanningServerAction(const rosplan_dispatch_msgs::PlanGoalConstPtr& goal) {
// call planning server
if(runPlanningServer(goal->domain_path, goal->problem_path, goal->data_path, goal->planner_command, goal->use_problem_topic)) {
plan_server->setSucceeded();
} else {
plan_server->setAborted();
}
}
/**
* planning system; prepares planning; calls planner; parses plan.
*/
bool PlannerInterface::runPlanningServer(std::string domainPath, std::string problemPath, std::string dataPath, std::string plannerCommand, bool useProblemTopic) {
// save parameters
data_path = dataPath;
domain_path = domainPath;
problem_path = problemPath;
planner_command = plannerCommand;
use_problem_topic = useProblemTopic;
// check if data_path ends in "/" and add "/" if not
const char *last_char = &data_path.back();
if (strcmp(last_char,"/") != 0)data_path = data_path + "/";
// set problem name for ROS_INFO
std::size_t lastDivide = problem_path.find_last_of("/\\");
if(lastDivide != std::string::npos) {
problem_name = problem_path.substr(lastDivide+1);
} else {
problem_name = problem_path;
}
if(use_problem_topic && !problem_instance_received) {
ROS_INFO("KCL: (%s) (%s) Problem was not published yet.", ros::this_node::getName().c_str(), problem_name.c_str());
return false;
}
bool success = runPlanner();
// publish planner output
if(success) {
std_msgs::String planMsg;
planMsg.data = planner_output;
plan_publisher.publish(planMsg);
}
return success;
}
} // close namespace
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.