text
stringlengths 54
60.6k
|
|---|
<commit_before>/*************************************************************************
*
* $RCSfile: NeonUri.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: kso $ $Date: 2002-08-21 07:34:53 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _RTL_URI_HXX_
#include <rtl/uri.hxx>
#endif
#ifndef _RTL_OUSTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _NEONURI_HXX_
#include "NeonUri.hxx"
#endif
#ifndef _DAVEXCEPTION_HXX_
#include "DAVException.hxx"
#endif
using namespace webdav_ucp;
ne_uri NeonUri::sUriDefaultsHTTP = { "http", NULL, DEFAULT_HTTP_PORT, NULL };
ne_uri NeonUri::sUriDefaultsHTTPS = { "https", NULL, DEFAULT_HTTPS_PORT, NULL };
ne_uri NeonUri::sUriDefaultsFTP = { "ftp", NULL, DEFAULT_FTP_PORT, NULL };
// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------
namespace {
//TODO! rtl::OString::matchIgnoreAsciiCaseAsciiL() missing
inline bool matchIgnoreAsciiCase(rtl::OString const & rStr1,
sal_Char const * pStr2,
sal_Int32 nStr2Len) SAL_THROW(())
{
return
rtl_str_shortenedCompareIgnoreAsciiCase_WithLength(
rStr1.getStr(), rStr1.getLength(), pStr2, nStr2Len, nStr2Len)
== 0;
}
}
NeonUri::NeonUri( const ne_uri * inUri )
throw ( DAVException )
{
if ( inUri == 0 )
throw DAVException( DAVException::DAV_INVALID_ARG );
char * uri = ne_uri_unparse( inUri );
if ( uri == 0 )
throw DAVException( DAVException::DAV_INVALID_ARG );
init( rtl::OString( uri ), inUri );
calculateURI();
free( uri );
}
NeonUri::NeonUri( const rtl::OUString & inUri )
throw ( DAVException )
{
if ( inUri.getLength() <= 0 )
throw DAVException( DAVException::DAV_INVALID_ARG );
rtl::OString theInputUri(
inUri.getStr(), inUri.getLength(), RTL_TEXTENCODING_UTF8 );
ne_uri theUri;
if ( ne_uri_parse( theInputUri.getStr(), &theUri ) != 0 )
{
ne_uri_free( &theUri );
throw DAVException( DAVException::DAV_INVALID_ARG );
}
init( theInputUri, &theUri );
calculateURI();
ne_uri_free( &theUri );
}
void NeonUri::init( const rtl::OString & rUri, const ne_uri * pUri )
{
// Complete URI.
ne_uri * pUriDefs
= matchIgnoreAsciiCase( rUri,
RTL_CONSTASCII_STRINGPARAM( "ftp:" ) ) ?
&sUriDefaultsFTP :
matchIgnoreAsciiCase( rUri,
RTL_CONSTASCII_STRINGPARAM( "https:" ) ) ?
&sUriDefaultsHTTPS :
&sUriDefaultsHTTP;
mScheme = rtl::OStringToOUString(
pUri->scheme ? pUri->scheme : pUriDefs->scheme,
RTL_TEXTENCODING_UTF8 );
mUserInfo = rtl::OStringToOUString(
pUri->authinfo ? pUri->authinfo : pUriDefs->authinfo,
RTL_TEXTENCODING_UTF8 );
mHostName = rtl::OStringToOUString(
pUri->host ? pUri->host : pUriDefs->host,
RTL_TEXTENCODING_UTF8 );
mPort = pUri->port > 0 ? pUri->port : pUriDefs->port;
mPath = rtl::OStringToOUString(
pUri->path ? pUri->path : pUriDefs->path,
RTL_TEXTENCODING_UTF8 );
}
// -------------------------------------------------------------------
// Destructor
// -------------------------------------------------------------------
NeonUri::~NeonUri( )
{
}
void NeonUri::calculateURI ()
{
mURI = mScheme;
mURI += rtl::OUString::createFromAscii ("://");
if (mUserInfo.getLength() > 0)
{
//TODO! differentiate between empty and missing userinfo
mURI += mUserInfo;
mURI += rtl::OUString::createFromAscii ("@");
}
mURI += mHostName;
mURI += rtl::OUString::createFromAscii (":");
mURI += rtl::OUString::valueOf (mPort);
mURI += mPath;
}
::rtl::OUString NeonUri::GetPathBaseName () const
{
sal_Int32 nPos = mPath.lastIndexOf ('/');
sal_Int32 nTrail = 0;
if (nPos == mPath.getLength () - 1)
{
// Trailing slash found. Skip.
nTrail = 1;
nPos = mPath.lastIndexOf ('/', nPos);
}
if (nPos != -1)
return mPath.copy (nPos + 1, mPath.getLength () - nPos - 1 - nTrail);
else
return rtl::OUString::createFromAscii ("/");
}
bool NeonUri::operator== ( const NeonUri & rOther ) const
{
return ( mURI == rOther.mURI );
}
::rtl::OUString NeonUri::GetPathBaseNameUnescaped () const
{
return unescape( GetPathBaseName() );
}
::rtl::OUString NeonUri::GetPathDirName () const
{
sal_Int32 nPos = mPath.lastIndexOf ('/');
if (nPos == mPath.getLength () - 1)
{
// Trailing slash found. Skip.
nPos = mPath.lastIndexOf ('/', nPos);
}
if (nPos != -1)
return mPath.copy (0, nPos + 1);
else
return rtl::OUString::createFromAscii ("/");
}
void NeonUri::AppendPath (const rtl::OUString& path)
{
if (mPath.lastIndexOf ('/') != mPath.getLength () - 1)
mPath += rtl::OUString::createFromAscii ("/");
mPath += path;
calculateURI ();
};
// static
rtl::OUString NeonUri::escapeSegment( const rtl::OUString& segment )
{
return rtl::Uri::encode( segment,
rtl_UriCharClassPchar,
rtl_UriEncodeIgnoreEscapes,
RTL_TEXTENCODING_UTF8 );
}
// static
rtl::OUString NeonUri::unescape( const rtl::OUString& segment )
{
return rtl::Uri::decode( segment,
rtl_UriDecodeWithCharset,
RTL_TEXTENCODING_UTF8 );
}
// static
rtl::OUString NeonUri::makeConnectionEndPointString(
const rtl::OUString & rHostName, int nPort )
{
rtl::OUString aServer( rHostName );
if ( ( nPort != DEFAULT_HTTP_PORT ) && ( nPort != DEFAULT_HTTPS_PORT ) )
{
aServer += rtl::OUString::createFromAscii( ":" );
aServer += rtl::OUString::valueOf( sal_Int32( nPort ) );
}
return aServer;
}
<commit_msg>INTEGRATION: CWS ipv6ooo2 (1.12.192); FILE MERGED 2004/10/11 15:43:13 kso 1.12.192.1: #i33615# - IPv6 support.<commit_after>/*************************************************************************
*
* $RCSfile: NeonUri.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: pjunck $ $Date: 2004-11-03 07:59:39 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <string.h>
#ifndef _RTL_URI_HXX_
#include <rtl/uri.hxx>
#endif
#ifndef _RTL_OUSTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _NEONURI_HXX_
#include "NeonUri.hxx"
#endif
#ifndef _DAVEXCEPTION_HXX_
#include "DAVException.hxx"
#endif
using namespace webdav_ucp;
ne_uri NeonUri::sUriDefaultsHTTP = { "http", NULL, DEFAULT_HTTP_PORT, NULL };
ne_uri NeonUri::sUriDefaultsHTTPS = { "https", NULL, DEFAULT_HTTPS_PORT, NULL };
ne_uri NeonUri::sUriDefaultsFTP = { "ftp", NULL, DEFAULT_FTP_PORT, NULL };
// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------
namespace {
//TODO! rtl::OString::matchIgnoreAsciiCaseAsciiL() missing
inline bool matchIgnoreAsciiCase(rtl::OString const & rStr1,
sal_Char const * pStr2,
sal_Int32 nStr2Len) SAL_THROW(())
{
return
rtl_str_shortenedCompareIgnoreAsciiCase_WithLength(
rStr1.getStr(), rStr1.getLength(), pStr2, nStr2Len, nStr2Len)
== 0;
}
}
NeonUri::NeonUri( const ne_uri * inUri )
throw ( DAVException )
{
if ( inUri == 0 )
throw DAVException( DAVException::DAV_INVALID_ARG );
char * uri = ne_uri_unparse( inUri );
if ( uri == 0 )
throw DAVException( DAVException::DAV_INVALID_ARG );
init( rtl::OString( uri ), inUri );
free( uri );
calculateURI();
}
NeonUri::NeonUri( const rtl::OUString & inUri )
throw ( DAVException )
{
if ( inUri.getLength() <= 0 )
throw DAVException( DAVException::DAV_INVALID_ARG );
rtl::OString theInputUri(
inUri.getStr(), inUri.getLength(), RTL_TEXTENCODING_UTF8 );
ne_uri theUri;
if ( ne_uri_parse( theInputUri.getStr(), &theUri ) != 0 )
{
ne_uri_free( &theUri );
throw DAVException( DAVException::DAV_INVALID_ARG );
}
init( theInputUri, &theUri );
ne_uri_free( &theUri );
calculateURI();
}
void NeonUri::init( const rtl::OString & rUri, const ne_uri * pUri )
{
// Complete URI.
ne_uri * pUriDefs
= matchIgnoreAsciiCase( rUri,
RTL_CONSTASCII_STRINGPARAM( "ftp:" ) ) ?
&sUriDefaultsFTP :
matchIgnoreAsciiCase( rUri,
RTL_CONSTASCII_STRINGPARAM( "https:" ) ) ?
&sUriDefaultsHTTPS :
&sUriDefaultsHTTP;
mScheme = rtl::OStringToOUString(
pUri->scheme ? pUri->scheme : pUriDefs->scheme,
RTL_TEXTENCODING_UTF8 );
mUserInfo = rtl::OStringToOUString(
pUri->authinfo ? pUri->authinfo : pUriDefs->authinfo,
RTL_TEXTENCODING_UTF8 );
mHostName = rtl::OStringToOUString(
pUri->host ? pUri->host : pUriDefs->host,
RTL_TEXTENCODING_UTF8 );
mPort = pUri->port > 0 ? pUri->port : pUriDefs->port;
mPath = rtl::OStringToOUString(
pUri->path ? pUri->path : pUriDefs->path,
RTL_TEXTENCODING_UTF8 );
}
// -------------------------------------------------------------------
// Destructor
// -------------------------------------------------------------------
NeonUri::~NeonUri( )
{
}
void NeonUri::calculateURI ()
{
rtl::OUStringBuffer aBuf( mScheme );
aBuf.appendAscii( "://" );
if ( mUserInfo.getLength() > 0 )
{
//TODO! differentiate between empty and missing userinfo
aBuf.append( mUserInfo );
aBuf.appendAscii( "@" );
}
// Is host a numeric IPv6 address?
if ( ( mHostName.indexOf( ':' ) != -1 ) &&
( mHostName[ 0 ] != sal_Unicode( '[' ) ) )
{
aBuf.appendAscii( "[" );
aBuf.append( mHostName );
aBuf.appendAscii( "]" );
}
else
{
aBuf.append( mHostName );
}
aBuf.appendAscii( ":" );
aBuf.append( rtl::OUString::valueOf( mPort ) );
aBuf.append( mPath );
mURI = aBuf.makeStringAndClear();
}
::rtl::OUString NeonUri::GetPathBaseName () const
{
sal_Int32 nPos = mPath.lastIndexOf ('/');
sal_Int32 nTrail = 0;
if (nPos == mPath.getLength () - 1)
{
// Trailing slash found. Skip.
nTrail = 1;
nPos = mPath.lastIndexOf ('/', nPos);
}
if (nPos != -1)
return mPath.copy (nPos + 1, mPath.getLength () - nPos - 1 - nTrail);
else
return rtl::OUString::createFromAscii ("/");
}
bool NeonUri::operator== ( const NeonUri & rOther ) const
{
return ( mURI == rOther.mURI );
}
::rtl::OUString NeonUri::GetPathBaseNameUnescaped () const
{
return unescape( GetPathBaseName() );
}
::rtl::OUString NeonUri::GetPathDirName () const
{
sal_Int32 nPos = mPath.lastIndexOf ('/');
if (nPos == mPath.getLength () - 1)
{
// Trailing slash found. Skip.
nPos = mPath.lastIndexOf ('/', nPos);
}
if (nPos != -1)
return mPath.copy (0, nPos + 1);
else
return rtl::OUString::createFromAscii ("/");
}
void NeonUri::AppendPath (const rtl::OUString& path)
{
if (mPath.lastIndexOf ('/') != mPath.getLength () - 1)
mPath += rtl::OUString::createFromAscii ("/");
mPath += path;
calculateURI ();
};
// static
rtl::OUString NeonUri::escapeSegment( const rtl::OUString& segment )
{
return rtl::Uri::encode( segment,
rtl_UriCharClassPchar,
rtl_UriEncodeIgnoreEscapes,
RTL_TEXTENCODING_UTF8 );
}
// static
rtl::OUString NeonUri::unescape( const rtl::OUString& segment )
{
return rtl::Uri::decode( segment,
rtl_UriDecodeWithCharset,
RTL_TEXTENCODING_UTF8 );
}
// static
rtl::OUString NeonUri::makeConnectionEndPointString(
const rtl::OUString & rHostName, int nPort )
{
rtl::OUStringBuffer aBuf;
// Is host a numeric IPv6 address?
if ( ( rHostName.indexOf( ':' ) != -1 ) &&
( rHostName[ 0 ] != sal_Unicode( '[' ) ) )
{
aBuf.appendAscii( "[" );
aBuf.append( rHostName );
aBuf.appendAscii( "]" );
}
else
{
aBuf.append( rHostName );
}
if ( ( nPort != DEFAULT_HTTP_PORT ) && ( nPort != DEFAULT_HTTPS_PORT ) )
{
aBuf.appendAscii( ":" );
aBuf.append( rtl::OUString::valueOf( sal_Int32( nPort ) ) );
}
return aBuf.makeStringAndClear();
}
<|endoftext|>
|
<commit_before>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2019 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <modules/base/rendering/renderablesphere.h>
#include <modules/base/basemodule.h>
#include <openspace/documentation/documentation.h>
#include <openspace/documentation/verifier.h>
#include <openspace/engine/globals.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/util/powerscaledsphere.h>
#include <openspace/util/updatestructures.h>
#include <ghoul/glm.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/logging/logmanager.h>
#include <ghoul/io/texture/texturereader.h>
#include <ghoul/opengl/texture.h>
#include <ghoul/opengl/textureunit.h>
#include <ghoul/opengl/programobject.h>
namespace {
constexpr const char* ProgramName = "Sphere";
constexpr const std::array<const char*, 5> UniformNames = {
"opacity", "modelViewProjection", "modelViewRotation", "colorTexture",
"mirrorTexture"
};
enum class Orientation : int {
Outside = 0,
Inside,
Both
};
constexpr openspace::properties::Property::PropertyInfo TextureInfo = {
"Texture",
"Texture",
"This value specifies an image that is loaded from disk and is used as a texture "
"that is applied to this sphere. This image is expected to be an equirectangular "
"projection."
};
constexpr openspace::properties::Property::PropertyInfo MirrorTextureInfo = {
"MirrorTexture",
"Mirror Texture",
"Mirror the texture along the x-axis."
};
constexpr openspace::properties::Property::PropertyInfo OrientationInfo = {
"Orientation",
"Orientation",
"Specifies whether the texture is applied to the inside of the sphere, the "
"outside of the sphere, or both."
};
constexpr openspace::properties::Property::PropertyInfo UseAdditiveBlendingInfo = {
"UseAdditiveBlending",
"Use Additive Blending",
"Render the object using additive blending."
};
constexpr openspace::properties::Property::PropertyInfo SegmentsInfo = {
"Segments",
"Number of Segments",
"This value specifies the number of segments that the sphere is separated in."
};
constexpr openspace::properties::Property::PropertyInfo SizeInfo = {
"Size",
"Size (in meters)",
"This value specifies the radius of the sphere in meters."
};
constexpr openspace::properties::Property::PropertyInfo FadeOutThresholdInfo = {
"FadeOutThreshold",
"Fade-Out Threshold",
"This value determines percentage of the sphere is visible before starting "
"fading-out it."
};
constexpr openspace::properties::Property::PropertyInfo FadeInThresholdInfo = {
"FadeInThreshold",
"Fade-In Threshold",
"Distance from center of MilkyWay from where the astronomical object starts to "
"fade in."
};
constexpr openspace::properties::Property::PropertyInfo DisableFadeInOutInfo = {
"DisableFadeInOut",
"Disable Fade-In/Fade-Out effects",
"Enables/Disables the Fade-In/Out effects."
};
constexpr openspace::properties::Property::PropertyInfo BackgroundInfo = {
"Background",
"Sets the current sphere rendering as a background rendering type",
"Enables/Disables background rendering."
};
} // namespace
namespace openspace {
documentation::Documentation RenderableSphere::Documentation() {
using namespace documentation;
return {
"RenderableSphere",
"base_renderable_sphere",
{
{
SizeInfo.identifier,
new DoubleVerifier,
Optional::No,
SizeInfo.description
},
{
SegmentsInfo.identifier,
new IntVerifier,
Optional::No,
SegmentsInfo.description
},
{
TextureInfo.identifier,
new StringVerifier,
Optional::No,
TextureInfo.description
},
{
OrientationInfo.identifier,
new StringInListVerifier({ "Inside", "Outside", "Both" }),
Optional::Yes,
OrientationInfo.description
},
{
UseAdditiveBlendingInfo.identifier,
new BoolVerifier,
Optional::Yes,
UseAdditiveBlendingInfo.description
},
{
MirrorTextureInfo.identifier,
new BoolVerifier,
Optional::Yes,
MirrorTextureInfo.description
},
{
FadeOutThresholdInfo.identifier,
new DoubleInRangeVerifier(0.0, 1.0),
Optional::Yes,
FadeOutThresholdInfo.description
},
{
FadeInThresholdInfo.identifier,
new DoubleVerifier,
Optional::Yes,
FadeInThresholdInfo.description
},
{
DisableFadeInOutInfo.identifier,
new BoolVerifier,
Optional::Yes,
DisableFadeInOutInfo.description
},
{
BackgroundInfo.identifier,
new BoolVerifier,
Optional::Yes,
BackgroundInfo.description
},
}
};
}
RenderableSphere::RenderableSphere(const ghoul::Dictionary& dictionary)
: Renderable(dictionary)
, _texturePath(TextureInfo)
, _orientation(OrientationInfo, properties::OptionProperty::DisplayType::Dropdown)
, _size(SizeInfo, 1.f, 0.f, 1e35f)
, _segments(SegmentsInfo, 8, 4, 1000)
, _mirrorTexture(MirrorTextureInfo, false)
, _useAdditiveBlending(UseAdditiveBlendingInfo, false)
, _disableFadeInDistance(DisableFadeInOutInfo, true)
, _backgroundRendering(BackgroundInfo, false)
, _fadeInThreshold(FadeInThresholdInfo, -1.f, 0.f, 1.f)
, _fadeOutThreshold(FadeOutThresholdInfo, -1.f, 0.f, 1.f)
{
documentation::testSpecificationAndThrow(
Documentation(),
dictionary,
"RenderableSphere"
);
addProperty(_opacity);
registerUpdateRenderBinFromOpacity();
_size = static_cast<float>(dictionary.value<double>(SizeInfo.identifier));
_segments = static_cast<int>(dictionary.value<double>(SegmentsInfo.identifier));
_texturePath = absPath(dictionary.value<std::string>(TextureInfo.identifier));
_orientation.addOptions({
{ static_cast<int>(Orientation::Outside), "Outside" },
{ static_cast<int>(Orientation::Inside), "Inside" },
{ static_cast<int>(Orientation::Both), "Both" }
});
if (dictionary.hasKey(OrientationInfo.identifier)) {
const std::string& v = dictionary.value<std::string>(OrientationInfo.identifier);
if (v == "Inside") {
_orientation = static_cast<int>(Orientation::Inside);
}
else if (v == "Outside") {
_orientation = static_cast<int>(Orientation::Outside);
}
else if (v == "Both") {
_orientation = static_cast<int>(Orientation::Both);
}
else {
throw ghoul::MissingCaseException();
}
}
else {
_orientation = static_cast<int>(Orientation::Outside);
}
addProperty(_orientation);
addProperty(_size);
_size.onChange([this]() { _sphereIsDirty = true; });
addProperty(_segments);
_segments.onChange([this]() { _sphereIsDirty = true; });
addProperty(_texturePath);
_texturePath.onChange([this]() { loadTexture(); });
addProperty(_mirrorTexture);
addProperty(_useAdditiveBlending);
if (dictionary.hasKey(MirrorTextureInfo.identifier)) {
_mirrorTexture = dictionary.value<bool>(MirrorTextureInfo.identifier);
}
if (dictionary.hasKey(UseAdditiveBlendingInfo.identifier)) {
_useAdditiveBlending = dictionary.value<bool>(UseAdditiveBlendingInfo.identifier);
if (_useAdditiveBlending) {
setRenderBin(Renderable::RenderBin::Transparent);
}
}
if (dictionary.hasKey(FadeOutThresholdInfo.identifier)) {
_fadeOutThreshold = static_cast<float>(
dictionary.value<double>(FadeOutThresholdInfo.identifier)
);
addProperty(_fadeOutThreshold);
}
if (dictionary.hasKey(FadeInThresholdInfo.identifier)) {
_fadeInThreshold = static_cast<float>(
dictionary.value<double>(FadeInThresholdInfo.identifier)
);
addProperty(_fadeInThreshold);
}
if (dictionary.hasKey(FadeOutThresholdInfo.identifier) ||
dictionary.hasKey(FadeInThresholdInfo.identifier)) {
_disableFadeInDistance.set(false);
addProperty(_disableFadeInDistance);
}
if (dictionary.hasKey(BackgroundInfo.identifier)) {
_backgroundRendering = dictionary.value<bool>(BackgroundInfo.identifier);
if (_backgroundRendering) {
setRenderBin(Renderable::RenderBin::Background);
}
}
}
bool RenderableSphere::isReady() const {
return _shader && _texture;
}
void RenderableSphere::initializeGL() {
_sphere = std::make_unique<PowerScaledSphere>(_size, _segments);
_sphere->initialize();
_shader = BaseModule::ProgramObjectManager.request(
ProgramName,
[]() -> std::unique_ptr<ghoul::opengl::ProgramObject> {
return global::renderEngine.buildRenderProgram(
ProgramName,
absPath("${MODULE_BASE}/shaders/sphere_vs.glsl"),
absPath("${MODULE_BASE}/shaders/sphere_fs.glsl")
);
}
);
ghoul::opengl::updateUniformLocations(*_shader, _uniformCache, UniformNames);
loadTexture();
}
void RenderableSphere::deinitializeGL() {
_texture = nullptr;
BaseModule::ProgramObjectManager.release(
ProgramName,
[](ghoul::opengl::ProgramObject* p) {
global::renderEngine.removeRenderProgram(p);
}
);
_shader = nullptr;
}
void RenderableSphere::render(const RenderData& data, RendererTasks&) {
Orientation orientation = static_cast<Orientation>(_orientation.value());
glm::dmat4 modelTransform =
glm::translate(glm::dmat4(1.0), data.modelTransform.translation) *
glm::dmat4(data.modelTransform.rotation) *
glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale));
glm::dmat3 modelRotation =
glm::dmat3(data.modelTransform.rotation);
// Activate shader
using IgnoreError = ghoul::opengl::ProgramObject::IgnoreError;
_shader->activate();
_shader->setIgnoreUniformLocationError(IgnoreError::Yes);
glm::mat4 modelViewProjection = data.camera.projectionMatrix() *
glm::mat4(data.camera.combinedViewMatrix() * modelTransform);
_shader->setUniform(_uniformCache.modelViewProjection, modelViewProjection);
glm::mat3 modelViewRotation = glm::mat3(
glm::dmat3(data.camera.viewRotationMatrix()) * modelRotation
);
_shader->setUniform(_uniformCache.modelViewRotation, modelViewRotation);
float adjustedTransparency = _opacity;
if (_fadeInThreshold > -1.0) {
const float logDistCamera = glm::log(static_cast<float>(
glm::distance(data.camera.positionVec3(), data.modelTransform.translation)
));
const float startLogFadeDistance = glm::log(_size * _fadeInThreshold);
const float stopLogFadeDistance = startLogFadeDistance + 1.f;
if (logDistCamera > startLogFadeDistance && logDistCamera < stopLogFadeDistance) {
const float fadeFactor = glm::clamp(
(logDistCamera - startLogFadeDistance) /
(stopLogFadeDistance - startLogFadeDistance),
0.f,
1.f
);
adjustedTransparency *= fadeFactor;
}
else if (logDistCamera <= startLogFadeDistance) {
adjustedTransparency = 0.f;
}
}
if (_fadeOutThreshold > -1.0) {
const float logDistCamera = glm::log(static_cast<float>(
glm::distance(data.camera.positionVec3(), data.modelTransform.translation)
));
const float startLogFadeDistance = glm::log(_size * _fadeOutThreshold);
const float stopLogFadeDistance = startLogFadeDistance + 1.f;
if (logDistCamera > startLogFadeDistance && logDistCamera < stopLogFadeDistance) {
const float fadeFactor = glm::clamp(
(logDistCamera - startLogFadeDistance) /
(stopLogFadeDistance - startLogFadeDistance),
0.f,
1.f
);
adjustedTransparency *= (1.f - fadeFactor);
}
else if (logDistCamera >= stopLogFadeDistance) {
adjustedTransparency = 0.f;
}
}
// Performance wise
if (adjustedTransparency < 0.01f) {
return;
}
_shader->setUniform(_uniformCache.opacity, adjustedTransparency);
_shader->setUniform(_uniformCache._mirrorTexture, _mirrorTexture.value());
ghoul::opengl::TextureUnit unit;
unit.activate();
_texture->bind();
_shader->setUniform(_uniformCache.colorTexture, unit);
// Setting these states should not be necessary,
// since they are the default state in OpenSpace.
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
if (orientation == Orientation::Inside) {
glCullFace(GL_FRONT);
} else if (orientation == Orientation::Both) {
glDisable(GL_CULL_FACE);
}
bool usingFramebufferRenderer = global::renderEngine.rendererImplementation() ==
RenderEngine::RendererImplementation::Framebuffer;
bool usingABufferRenderer = global::renderEngine.rendererImplementation() ==
RenderEngine::RendererImplementation::ABuffer;
if (usingABufferRenderer && _useAdditiveBlending) {
_shader->setUniform("additiveBlending", true);
}
if (usingFramebufferRenderer && _useAdditiveBlending) {
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
glDepthMask(false);
}
_sphere->render();
if (usingFramebufferRenderer && _useAdditiveBlending) {
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDepthMask(true);
}
_shader->setIgnoreUniformLocationError(IgnoreError::No);
_shader->deactivate();
if (orientation == Orientation::Inside) {
glCullFace(GL_BACK);
} else if (orientation == Orientation::Both) {
glEnable(GL_CULL_FACE);
}
}
void RenderableSphere::update(const UpdateData&) {
if (_shader->isDirty()) {
_shader->rebuildFromFile();
ghoul::opengl::updateUniformLocations(*_shader, _uniformCache, UniformNames);
}
if (_sphereIsDirty) {
_sphere = std::make_unique<PowerScaledSphere>(_size, _segments);
_sphere->initialize();
_sphereIsDirty = false;
}
}
void RenderableSphere::loadTexture() {
if (!_texturePath.value().empty()) {
std::unique_ptr<ghoul::opengl::Texture> texture =
ghoul::io::TextureReader::ref().loadTexture(_texturePath);
if (texture) {
LDEBUGC(
"RenderableSphere",
fmt::format("Loaded texture from '{}'", absPath(_texturePath))
);
texture->uploadTexture();
texture->setFilter(ghoul::opengl::Texture::FilterMode::LinearMipMap);
_texture = std::move(texture);
}
}
}
} // namespace openspace
<commit_msg>Correctly set render bin for RenderableSphere to prevent flickering of atmosphere<commit_after>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2019 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <modules/base/rendering/renderablesphere.h>
#include <modules/base/basemodule.h>
#include <openspace/documentation/documentation.h>
#include <openspace/documentation/verifier.h>
#include <openspace/engine/globals.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/util/powerscaledsphere.h>
#include <openspace/util/updatestructures.h>
#include <ghoul/glm.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/logging/logmanager.h>
#include <ghoul/io/texture/texturereader.h>
#include <ghoul/opengl/texture.h>
#include <ghoul/opengl/textureunit.h>
#include <ghoul/opengl/programobject.h>
namespace {
constexpr const char* ProgramName = "Sphere";
constexpr const std::array<const char*, 5> UniformNames = {
"opacity", "modelViewProjection", "modelViewRotation", "colorTexture",
"mirrorTexture"
};
enum class Orientation : int {
Outside = 0,
Inside,
Both
};
constexpr openspace::properties::Property::PropertyInfo TextureInfo = {
"Texture",
"Texture",
"This value specifies an image that is loaded from disk and is used as a texture "
"that is applied to this sphere. This image is expected to be an equirectangular "
"projection."
};
constexpr openspace::properties::Property::PropertyInfo MirrorTextureInfo = {
"MirrorTexture",
"Mirror Texture",
"Mirror the texture along the x-axis."
};
constexpr openspace::properties::Property::PropertyInfo OrientationInfo = {
"Orientation",
"Orientation",
"Specifies whether the texture is applied to the inside of the sphere, the "
"outside of the sphere, or both."
};
constexpr openspace::properties::Property::PropertyInfo UseAdditiveBlendingInfo = {
"UseAdditiveBlending",
"Use Additive Blending",
"Render the object using additive blending."
};
constexpr openspace::properties::Property::PropertyInfo SegmentsInfo = {
"Segments",
"Number of Segments",
"This value specifies the number of segments that the sphere is separated in."
};
constexpr openspace::properties::Property::PropertyInfo SizeInfo = {
"Size",
"Size (in meters)",
"This value specifies the radius of the sphere in meters."
};
constexpr openspace::properties::Property::PropertyInfo FadeOutThresholdInfo = {
"FadeOutThreshold",
"Fade-Out Threshold",
"This value determines percentage of the sphere is visible before starting "
"fading-out it."
};
constexpr openspace::properties::Property::PropertyInfo FadeInThresholdInfo = {
"FadeInThreshold",
"Fade-In Threshold",
"Distance from center of MilkyWay from where the astronomical object starts to "
"fade in."
};
constexpr openspace::properties::Property::PropertyInfo DisableFadeInOutInfo = {
"DisableFadeInOut",
"Disable Fade-In/Fade-Out effects",
"Enables/Disables the Fade-In/Out effects."
};
constexpr openspace::properties::Property::PropertyInfo BackgroundInfo = {
"Background",
"Sets the current sphere rendering as a background rendering type",
"Enables/Disables background rendering."
};
} // namespace
namespace openspace {
documentation::Documentation RenderableSphere::Documentation() {
using namespace documentation;
return {
"RenderableSphere",
"base_renderable_sphere",
{
{
SizeInfo.identifier,
new DoubleVerifier,
Optional::No,
SizeInfo.description
},
{
SegmentsInfo.identifier,
new IntVerifier,
Optional::No,
SegmentsInfo.description
},
{
TextureInfo.identifier,
new StringVerifier,
Optional::No,
TextureInfo.description
},
{
OrientationInfo.identifier,
new StringInListVerifier({ "Inside", "Outside", "Both" }),
Optional::Yes,
OrientationInfo.description
},
{
UseAdditiveBlendingInfo.identifier,
new BoolVerifier,
Optional::Yes,
UseAdditiveBlendingInfo.description
},
{
MirrorTextureInfo.identifier,
new BoolVerifier,
Optional::Yes,
MirrorTextureInfo.description
},
{
FadeOutThresholdInfo.identifier,
new DoubleInRangeVerifier(0.0, 1.0),
Optional::Yes,
FadeOutThresholdInfo.description
},
{
FadeInThresholdInfo.identifier,
new DoubleVerifier,
Optional::Yes,
FadeInThresholdInfo.description
},
{
DisableFadeInOutInfo.identifier,
new BoolVerifier,
Optional::Yes,
DisableFadeInOutInfo.description
},
{
BackgroundInfo.identifier,
new BoolVerifier,
Optional::Yes,
BackgroundInfo.description
},
}
};
}
RenderableSphere::RenderableSphere(const ghoul::Dictionary& dictionary)
: Renderable(dictionary)
, _texturePath(TextureInfo)
, _orientation(OrientationInfo, properties::OptionProperty::DisplayType::Dropdown)
, _size(SizeInfo, 1.f, 0.f, 1e35f)
, _segments(SegmentsInfo, 8, 4, 1000)
, _mirrorTexture(MirrorTextureInfo, false)
, _useAdditiveBlending(UseAdditiveBlendingInfo, false)
, _disableFadeInDistance(DisableFadeInOutInfo, true)
, _backgroundRendering(BackgroundInfo, false)
, _fadeInThreshold(FadeInThresholdInfo, -1.f, 0.f, 1.f)
, _fadeOutThreshold(FadeOutThresholdInfo, -1.f, 0.f, 1.f)
{
documentation::testSpecificationAndThrow(
Documentation(),
dictionary,
"RenderableSphere"
);
addProperty(_opacity);
registerUpdateRenderBinFromOpacity();
_size = static_cast<float>(dictionary.value<double>(SizeInfo.identifier));
_segments = static_cast<int>(dictionary.value<double>(SegmentsInfo.identifier));
_texturePath = absPath(dictionary.value<std::string>(TextureInfo.identifier));
_orientation.addOptions({
{ static_cast<int>(Orientation::Outside), "Outside" },
{ static_cast<int>(Orientation::Inside), "Inside" },
{ static_cast<int>(Orientation::Both), "Both" }
});
if (dictionary.hasKey(OrientationInfo.identifier)) {
const std::string& v = dictionary.value<std::string>(OrientationInfo.identifier);
if (v == "Inside") {
_orientation = static_cast<int>(Orientation::Inside);
}
else if (v == "Outside") {
_orientation = static_cast<int>(Orientation::Outside);
}
else if (v == "Both") {
_orientation = static_cast<int>(Orientation::Both);
}
else {
throw ghoul::MissingCaseException();
}
}
else {
_orientation = static_cast<int>(Orientation::Outside);
}
addProperty(_orientation);
addProperty(_size);
_size.onChange([this]() { _sphereIsDirty = true; });
addProperty(_segments);
_segments.onChange([this]() { _sphereIsDirty = true; });
addProperty(_texturePath);
_texturePath.onChange([this]() { loadTexture(); });
addProperty(_mirrorTexture);
addProperty(_useAdditiveBlending);
if (dictionary.hasKey(MirrorTextureInfo.identifier)) {
_mirrorTexture = dictionary.value<bool>(MirrorTextureInfo.identifier);
}
if (dictionary.hasKey(UseAdditiveBlendingInfo.identifier)) {
_useAdditiveBlending = dictionary.value<bool>(UseAdditiveBlendingInfo.identifier);
if (_useAdditiveBlending) {
setRenderBin(Renderable::RenderBin::Transparent);
}
}
if (dictionary.hasKey(FadeOutThresholdInfo.identifier)) {
_fadeOutThreshold = static_cast<float>(
dictionary.value<double>(FadeOutThresholdInfo.identifier)
);
addProperty(_fadeOutThreshold);
}
if (dictionary.hasKey(FadeInThresholdInfo.identifier)) {
_fadeInThreshold = static_cast<float>(
dictionary.value<double>(FadeInThresholdInfo.identifier)
);
addProperty(_fadeInThreshold);
}
if (dictionary.hasKey(FadeOutThresholdInfo.identifier) ||
dictionary.hasKey(FadeInThresholdInfo.identifier)) {
_disableFadeInDistance.set(false);
addProperty(_disableFadeInDistance);
}
if (dictionary.hasKey(BackgroundInfo.identifier)) {
_backgroundRendering = dictionary.value<bool>(BackgroundInfo.identifier);
if (_backgroundRendering) {
setRenderBin(Renderable::RenderBin::Background);
}
}
setRenderBinFromOpacity();
}
bool RenderableSphere::isReady() const {
return _shader && _texture;
}
void RenderableSphere::initializeGL() {
_sphere = std::make_unique<PowerScaledSphere>(_size, _segments);
_sphere->initialize();
_shader = BaseModule::ProgramObjectManager.request(
ProgramName,
[]() -> std::unique_ptr<ghoul::opengl::ProgramObject> {
return global::renderEngine.buildRenderProgram(
ProgramName,
absPath("${MODULE_BASE}/shaders/sphere_vs.glsl"),
absPath("${MODULE_BASE}/shaders/sphere_fs.glsl")
);
}
);
ghoul::opengl::updateUniformLocations(*_shader, _uniformCache, UniformNames);
loadTexture();
}
void RenderableSphere::deinitializeGL() {
_texture = nullptr;
BaseModule::ProgramObjectManager.release(
ProgramName,
[](ghoul::opengl::ProgramObject* p) {
global::renderEngine.removeRenderProgram(p);
}
);
_shader = nullptr;
}
void RenderableSphere::render(const RenderData& data, RendererTasks&) {
Orientation orientation = static_cast<Orientation>(_orientation.value());
glm::dmat4 modelTransform =
glm::translate(glm::dmat4(1.0), data.modelTransform.translation) *
glm::dmat4(data.modelTransform.rotation) *
glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale));
glm::dmat3 modelRotation =
glm::dmat3(data.modelTransform.rotation);
// Activate shader
using IgnoreError = ghoul::opengl::ProgramObject::IgnoreError;
_shader->activate();
_shader->setIgnoreUniformLocationError(IgnoreError::Yes);
glm::mat4 modelViewProjection = data.camera.projectionMatrix() *
glm::mat4(data.camera.combinedViewMatrix() * modelTransform);
_shader->setUniform(_uniformCache.modelViewProjection, modelViewProjection);
glm::mat3 modelViewRotation = glm::mat3(
glm::dmat3(data.camera.viewRotationMatrix()) * modelRotation
);
_shader->setUniform(_uniformCache.modelViewRotation, modelViewRotation);
float adjustedTransparency = _opacity;
if (_fadeInThreshold > -1.0) {
const float logDistCamera = glm::log(static_cast<float>(
glm::distance(data.camera.positionVec3(), data.modelTransform.translation)
));
const float startLogFadeDistance = glm::log(_size * _fadeInThreshold);
const float stopLogFadeDistance = startLogFadeDistance + 1.f;
if (logDistCamera > startLogFadeDistance && logDistCamera < stopLogFadeDistance) {
const float fadeFactor = glm::clamp(
(logDistCamera - startLogFadeDistance) /
(stopLogFadeDistance - startLogFadeDistance),
0.f,
1.f
);
adjustedTransparency *= fadeFactor;
}
else if (logDistCamera <= startLogFadeDistance) {
adjustedTransparency = 0.f;
}
}
if (_fadeOutThreshold > -1.0) {
const float logDistCamera = glm::log(static_cast<float>(
glm::distance(data.camera.positionVec3(), data.modelTransform.translation)
));
const float startLogFadeDistance = glm::log(_size * _fadeOutThreshold);
const float stopLogFadeDistance = startLogFadeDistance + 1.f;
if (logDistCamera > startLogFadeDistance && logDistCamera < stopLogFadeDistance) {
const float fadeFactor = glm::clamp(
(logDistCamera - startLogFadeDistance) /
(stopLogFadeDistance - startLogFadeDistance),
0.f,
1.f
);
adjustedTransparency *= (1.f - fadeFactor);
}
else if (logDistCamera >= stopLogFadeDistance) {
adjustedTransparency = 0.f;
}
}
// Performance wise
if (adjustedTransparency < 0.01f) {
return;
}
_shader->setUniform(_uniformCache.opacity, adjustedTransparency);
_shader->setUniform(_uniformCache._mirrorTexture, _mirrorTexture.value());
ghoul::opengl::TextureUnit unit;
unit.activate();
_texture->bind();
_shader->setUniform(_uniformCache.colorTexture, unit);
// Setting these states should not be necessary,
// since they are the default state in OpenSpace.
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
if (orientation == Orientation::Inside) {
glCullFace(GL_FRONT);
} else if (orientation == Orientation::Both) {
glDisable(GL_CULL_FACE);
}
bool usingFramebufferRenderer = global::renderEngine.rendererImplementation() ==
RenderEngine::RendererImplementation::Framebuffer;
bool usingABufferRenderer = global::renderEngine.rendererImplementation() ==
RenderEngine::RendererImplementation::ABuffer;
if (usingABufferRenderer && _useAdditiveBlending) {
_shader->setUniform("additiveBlending", true);
}
if (usingFramebufferRenderer && _useAdditiveBlending) {
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
glDepthMask(false);
}
_sphere->render();
if (usingFramebufferRenderer && _useAdditiveBlending) {
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDepthMask(true);
}
_shader->setIgnoreUniformLocationError(IgnoreError::No);
_shader->deactivate();
if (orientation == Orientation::Inside) {
glCullFace(GL_BACK);
} else if (orientation == Orientation::Both) {
glEnable(GL_CULL_FACE);
}
}
void RenderableSphere::update(const UpdateData&) {
if (_shader->isDirty()) {
_shader->rebuildFromFile();
ghoul::opengl::updateUniformLocations(*_shader, _uniformCache, UniformNames);
}
if (_sphereIsDirty) {
_sphere = std::make_unique<PowerScaledSphere>(_size, _segments);
_sphere->initialize();
_sphereIsDirty = false;
}
}
void RenderableSphere::loadTexture() {
if (!_texturePath.value().empty()) {
std::unique_ptr<ghoul::opengl::Texture> texture =
ghoul::io::TextureReader::ref().loadTexture(_texturePath);
if (texture) {
LDEBUGC(
"RenderableSphere",
fmt::format("Loaded texture from '{}'", absPath(_texturePath))
);
texture->uploadTexture();
texture->setFilter(ghoul::opengl::Texture::FilterMode::LinearMipMap);
_texture = std::move(texture);
}
}
}
} // namespace openspace
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/dreamview/backend/hmi/hmi_worker.h"
#include <vector>
#include "gflags/gflags.h"
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/kv_db/kv_db.h"
#include "modules/common/util/file.h"
#include "modules/common/util/map_util.h"
#include "modules/common/util/string_tokenizer.h"
#include "modules/common/util/string_util.h"
#include "modules/control/proto/pad_msg.pb.h"
#include "modules/data/util/info_collector.h"
#include "modules/dreamview/backend/common/dreamview_gflags.h"
#include "modules/dreamview/backend/hmi/vehicle_manager.h"
DEFINE_string(map_data_path, "/apollo/modules/map/data", "Path to map data.");
DEFINE_string(vehicle_data_path, "/apollo/modules/calibration/data",
"Path to vehicle data.");
DEFINE_string(global_flagfile,
"/apollo/modules/common/data/global_flagfile.txt",
"Global flagfile shared by all modules.");
namespace apollo {
namespace dreamview {
namespace {
using apollo::canbus::Chassis;
using apollo::common::adapter::AdapterManager;
using apollo::common::util::ContainsKey;
using apollo::common::util::FindOrNull;
using apollo::common::util::StringTokenizer;
using apollo::control::DrivingAction;
using google::protobuf::Map;
// Convert a string to be title-like. E.g.: "hello_world" -> "Hello World".
std::string TitleCase(const std::string &origin,
const std::string &delimiter = "_") {
std::vector<std::string> parts = StringTokenizer::Split(origin, delimiter);
for (auto &part : parts) {
if (!part.empty()) {
// Upper case the first char.
part[0] = toupper(part[0]);
}
}
return apollo::common::util::PrintIter(parts);
}
// List subdirs and return a dict of {subdir_title: subdir_path}.
Map<std::string, std::string> ListDirAsDict(const std::string &dir) {
Map<std::string, std::string> result;
const auto subdirs = apollo::common::util::ListSubDirectories(dir);
for (const auto &subdir : subdirs) {
const auto subdir_title = TitleCase(subdir);
const auto subdir_path = apollo::common::util::StrCat(dir, "/", subdir);
result.insert({subdir_title, subdir_path});
}
return result;
}
// Run a supported command of some component, return the ret code.
int RunComponentCommand(
const google::protobuf::Map<std::string, Component> &components,
const std::string &component_name, const std::string &command_name) {
const auto *component = FindOrNull(components, component_name);
if (component == nullptr) {
AERROR << "Cannot find component " << component_name;
return -1;
}
const auto *cmd = FindOrNull(component->supported_commands(), command_name);
if (cmd == nullptr) {
AERROR << "Cannot find command " << component_name << "." << command_name;
return -1;
}
AINFO << "Execute system command: " << *cmd;
const int ret = std::system(cmd->c_str());
AERROR_IF(ret != 0) << "Command returns " << ret << ": " << *cmd;
return ret;
}
} // namespace
HMIWorker::HMIWorker() {
// Init HMIConfig.
CHECK(common::util::GetProtoFromFile(FLAGS_hmi_config_filename, &config_))
<< "Unable to parse HMI config file " << FLAGS_hmi_config_filename;
config_.set_docker_image(apollo::data::InfoCollector::GetDockerImage());
// If the module path doesn't exist, remove it from list.
auto *modules = config_.mutable_modules();
for (auto iter = modules->begin(); iter != modules->end();) {
const auto &conf = iter->second;
if (conf.has_path() && !common::util::PathExists(conf.path())) {
iter = modules->erase(iter);
} else {
++iter;
}
}
// Get available maps and vehicles by listing data directory.
*config_.mutable_available_maps() = ListDirAsDict(FLAGS_map_data_path);
*config_.mutable_available_vehicles() =
ListDirAsDict(FLAGS_vehicle_data_path);
ADEBUG << "Loaded HMI config: " << config_.DebugString();
// Init HMIStatus.
// If the default mode is unavailable, select the first one.
const auto &modes = config_.modes();
if (!ContainsKey(modes, status_.current_mode())) {
CHECK(!modes.empty());
status_.set_current_mode(modes.begin()->first);
}
}
bool HMIWorker::Trigger(const HMIAction action) {
AINFO << "HMIAction " << HMIAction_Name(action) << " was triggered!";
// TODO(xiaoxq): Do the action.
return false;
}
int HMIWorker::RunModuleCommand(const std::string &module,
const std::string &command) {
return RunComponentCommand(config_.modules(), module, command);
}
int HMIWorker::RunHardwareCommand(const std::string &hardware,
const std::string &command) {
return RunComponentCommand(config_.hardware(), hardware, command);
}
int HMIWorker::RunToolCommand(const std::string &tool,
const std::string &command) {
return RunComponentCommand(config_.tools(), tool, command);
}
void HMIWorker::SubmitDriveEvent(const uint64_t event_time_ms,
const std::string &event_msg) {
apollo::common::DriveEvent drive_event;
AdapterManager::FillDriveEventHeader("HMI", &drive_event);
drive_event.mutable_header()->set_timestamp_sec(event_time_ms / 1000.0);
drive_event.set_event(event_msg);
AdapterManager::PublishDriveEvent(drive_event);
}
bool HMIWorker::ChangeToDrivingMode(const Chassis::DrivingMode mode) {
// Always reset to MANUAL mode before changing to other mode.
if (mode != Chassis::COMPLETE_MANUAL) {
if (!ChangeToDrivingMode(Chassis::COMPLETE_MANUAL)) {
AERROR << "Failed to reset to MANUAL mode before changing to "
<< Chassis::DrivingMode_Name(mode);
return false;
}
}
control::PadMessage pad;
switch (mode) {
case Chassis::COMPLETE_MANUAL:
pad.set_action(DrivingAction::RESET);
break;
case Chassis::COMPLETE_AUTO_DRIVE:
pad.set_action(DrivingAction::START);
break;
default:
AFATAL << "Unknown action to change driving mode to "
<< Chassis::DrivingMode_Name(mode);
}
constexpr int kMaxTries = 3;
constexpr auto kTryInterval = std::chrono::milliseconds(500);
auto *chassis = CHECK_NOTNULL(AdapterManager::GetChassis());
for (int i = 0; i < kMaxTries; ++i) {
// Send driving action periodically until entering target driving mode.
AdapterManager::FillPadHeader("HMI", &pad);
AdapterManager::PublishPad(pad);
std::this_thread::sleep_for(kTryInterval);
chassis->Observe();
if (chassis->Empty()) {
AERROR << "No Chassis message received!";
} else if (chassis->GetLatestObserved().driving_mode() == mode) {
return true;
}
}
AERROR << "Failed to change driving mode to "
<< Chassis::DrivingMode_Name(mode);
return false;
}
void HMIWorker::RunModeCommand(const std::string &command_name) {
const Mode &mode_conf = config_.modes().at(status_.current_mode());
if (command_name == "start" || command_name == "stop") {
// Run the command on all live modules.
for (const auto &module : mode_conf.live_modules()) {
RunModuleCommand(module, command_name);
}
}
}
void HMIWorker::ChangeToMap(const std::string &map_name,
MapService *map_service) {
if (status_.current_map() == map_name) {
return;
}
const auto *map_dir = FindOrNull(config_.available_maps(), map_name);
if (map_dir == nullptr) {
AERROR << "Unknown map " << map_name;
return;
}
status_.set_current_map(map_name);
apollo::common::KVDB::Put("apollo:dreamview:map", map_name);
FLAGS_map_dir = *map_dir;
// Append new map_dir flag to global flagfile.
std::ofstream fout(FLAGS_global_flagfile, std::ios_base::app);
CHECK(fout) << "Fail to open " << FLAGS_global_flagfile;
fout << "\n--map_dir=" << *map_dir << std::endl;
// Also reload simulation map.
CHECK(map_service->ReloadMap(true)) << "Failed to load map from " << *map_dir;
RunModeCommand("stop");
}
void HMIWorker::ChangeToVehicle(const std::string &vehicle_name) {
if (status_.current_vehicle() == vehicle_name) {
return;
}
const auto *vehicle = FindOrNull(config_.available_vehicles(), vehicle_name);
if (vehicle == nullptr) {
AERROR << "Unknown vehicle " << vehicle_name;
return;
}
status_.set_current_vehicle(vehicle_name);
apollo::common::KVDB::Put("apollo:dreamview:vehicle", vehicle_name);
CHECK(VehicleManager::instance()->UseVehicle(*vehicle));
RunModeCommand("stop");
}
void HMIWorker::ChangeToMode(const std::string &mode_name) {
const std::string &old_mode = status_.current_mode();
if (old_mode == mode_name) {
return;
}
if (!ContainsKey(config_.modes(), mode_name)) {
AERROR << "Unknown mode " << mode_name;
return;
}
const auto &old_modules = config_.modes().at(old_mode).live_modules();
status_.set_current_mode(mode_name);
apollo::common::KVDB::Put("apollo:dreamview:mode", mode_name);
// Now stop all old modules.
for (const auto &module : old_modules) {
RunModuleCommand(module, "stop");
}
}
void HMIWorker::UpdateSystemStatus(const monitor::SystemStatus &system_status) {
*status_.mutable_system_status() = system_status;
}
} // namespace dreamview
} // namespace apollo
<commit_msg>Dreamview: Set and keep use_navigation_mode.<commit_after>/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/dreamview/backend/hmi/hmi_worker.h"
#include <vector>
#include "gflags/gflags.h"
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/kv_db/kv_db.h"
#include "modules/common/util/file.h"
#include "modules/common/util/map_util.h"
#include "modules/common/util/string_tokenizer.h"
#include "modules/common/util/string_util.h"
#include "modules/control/proto/pad_msg.pb.h"
#include "modules/data/util/info_collector.h"
#include "modules/dreamview/backend/common/dreamview_gflags.h"
#include "modules/dreamview/backend/hmi/vehicle_manager.h"
DEFINE_string(map_data_path, "/apollo/modules/map/data", "Path to map data.");
DEFINE_string(vehicle_data_path, "/apollo/modules/calibration/data",
"Path to vehicle data.");
namespace apollo {
namespace dreamview {
namespace {
using apollo::canbus::Chassis;
using apollo::common::adapter::AdapterManager;
using apollo::common::util::ContainsKey;
using apollo::common::util::FindOrNull;
using apollo::common::util::StringTokenizer;
using apollo::control::DrivingAction;
using google::protobuf::Map;
constexpr char kNavigationModeName[] = "Navigation";
// Convert a string to be title-like. E.g.: "hello_world" -> "Hello World".
std::string TitleCase(const std::string &origin,
const std::string &delimiter = "_") {
std::vector<std::string> parts = StringTokenizer::Split(origin, delimiter);
for (auto &part : parts) {
if (!part.empty()) {
// Upper case the first char.
part[0] = toupper(part[0]);
}
}
return apollo::common::util::PrintIter(parts);
}
// List subdirs and return a dict of {subdir_title: subdir_path}.
Map<std::string, std::string> ListDirAsDict(const std::string &dir) {
Map<std::string, std::string> result;
const auto subdirs = apollo::common::util::ListSubDirectories(dir);
for (const auto &subdir : subdirs) {
const auto subdir_title = TitleCase(subdir);
const auto subdir_path = apollo::common::util::StrCat(dir, "/", subdir);
result.insert({subdir_title, subdir_path});
}
return result;
}
// Run a supported command of some component, return the ret code.
int RunComponentCommand(const Map<std::string, Component> &components,
const std::string &component_name,
const std::string &command_name) {
const auto *component = FindOrNull(components, component_name);
if (component == nullptr) {
AERROR << "Cannot find component " << component_name;
return -1;
}
const auto *cmd = FindOrNull(component->supported_commands(), command_name);
if (cmd == nullptr) {
AERROR << "Cannot find command " << component_name << "." << command_name;
return -1;
}
AINFO << "Execute system command: " << *cmd;
const int ret = std::system(cmd->c_str());
AERROR_IF(ret != 0) << "Command returns " << ret << ": " << *cmd;
return ret;
}
template <class FlagType, class ValueType>
void SetGlobalFlag(const std::string &flag_name, const ValueType &value,
FlagType* flag) {
static constexpr char kGlobalFlagfile[] =
"/apollo/modules/common/data/global_flagfile.txt";
if (*flag != value) {
*flag = value;
// Overwrite global flagfile.
std::ofstream fout(kGlobalFlagfile, std::ios_base::app);
CHECK(fout) << "Fail to open global flagfile " << kGlobalFlagfile;
fout << "\n--" << flag_name << "=" << value << std::endl;
}
}
} // namespace
HMIWorker::HMIWorker() {
// Init HMIConfig.
CHECK(common::util::GetProtoFromFile(FLAGS_hmi_config_filename, &config_))
<< "Unable to parse HMI config file " << FLAGS_hmi_config_filename;
config_.set_docker_image(apollo::data::InfoCollector::GetDockerImage());
// If the module path doesn't exist, remove it from list.
auto *modules = config_.mutable_modules();
for (auto iter = modules->begin(); iter != modules->end();) {
const auto &conf = iter->second;
if (conf.has_path() && !common::util::PathExists(conf.path())) {
iter = modules->erase(iter);
} else {
++iter;
}
}
// Get available maps and vehicles by listing data directory.
*config_.mutable_available_maps() = ListDirAsDict(FLAGS_map_data_path);
*config_.mutable_available_vehicles() =
ListDirAsDict(FLAGS_vehicle_data_path);
ADEBUG << "Loaded HMI config: " << config_.DebugString();
// Init HMIStatus.
const auto &modes = config_.modes();
if (FLAGS_use_navigation_mode && ContainsKey(modes, kNavigationModeName)) {
// If the FLAG_use_navigation_mode is set, set it in HMIStatus.
status_.set_current_mode(kNavigationModeName);
} else if (!ContainsKey(modes, status_.current_mode())) {
CHECK(!modes.empty()) << "No available modes to run vehicle.";
// If the default mode is unavailable, select the first one.
status_.set_current_mode(modes.begin()->first);
}
// If the FLAGS_map_dir is set, set it in HMIStatus.
if (!FLAGS_map_dir.empty()) {
for (const auto &entry : config_.available_maps()) {
// entry is (map_name, map_path)
if (entry.second == FLAGS_map_dir) {
status_.set_current_map(entry.first);
break;
}
}
}
}
bool HMIWorker::Trigger(const HMIAction action) {
AINFO << "HMIAction " << HMIAction_Name(action) << " was triggered!";
// TODO(xiaoxq): Do the action.
return false;
}
int HMIWorker::RunModuleCommand(const std::string &module,
const std::string &command) {
return RunComponentCommand(config_.modules(), module, command);
}
int HMIWorker::RunHardwareCommand(const std::string &hardware,
const std::string &command) {
return RunComponentCommand(config_.hardware(), hardware, command);
}
int HMIWorker::RunToolCommand(const std::string &tool,
const std::string &command) {
return RunComponentCommand(config_.tools(), tool, command);
}
void HMIWorker::SubmitDriveEvent(const uint64_t event_time_ms,
const std::string &event_msg) {
apollo::common::DriveEvent drive_event;
AdapterManager::FillDriveEventHeader("HMI", &drive_event);
drive_event.mutable_header()->set_timestamp_sec(event_time_ms / 1000.0);
drive_event.set_event(event_msg);
AdapterManager::PublishDriveEvent(drive_event);
}
bool HMIWorker::ChangeToDrivingMode(const Chassis::DrivingMode mode) {
// Always reset to MANUAL mode before changing to other mode.
if (mode != Chassis::COMPLETE_MANUAL) {
if (!ChangeToDrivingMode(Chassis::COMPLETE_MANUAL)) {
AERROR << "Failed to reset to MANUAL mode before changing to "
<< Chassis::DrivingMode_Name(mode);
return false;
}
}
control::PadMessage pad;
switch (mode) {
case Chassis::COMPLETE_MANUAL:
pad.set_action(DrivingAction::RESET);
break;
case Chassis::COMPLETE_AUTO_DRIVE:
pad.set_action(DrivingAction::START);
break;
default:
AFATAL << "Unknown action to change driving mode to "
<< Chassis::DrivingMode_Name(mode);
}
constexpr int kMaxTries = 3;
constexpr auto kTryInterval = std::chrono::milliseconds(500);
auto *chassis = CHECK_NOTNULL(AdapterManager::GetChassis());
for (int i = 0; i < kMaxTries; ++i) {
// Send driving action periodically until entering target driving mode.
AdapterManager::FillPadHeader("HMI", &pad);
AdapterManager::PublishPad(pad);
std::this_thread::sleep_for(kTryInterval);
chassis->Observe();
if (chassis->Empty()) {
AERROR << "No Chassis message received!";
} else if (chassis->GetLatestObserved().driving_mode() == mode) {
return true;
}
}
AERROR << "Failed to change driving mode to "
<< Chassis::DrivingMode_Name(mode);
return false;
}
void HMIWorker::RunModeCommand(const std::string &command_name) {
const Mode &mode_conf = config_.modes().at(status_.current_mode());
if (command_name == "start" || command_name == "stop") {
// Run the command on all live modules.
for (const auto &module : mode_conf.live_modules()) {
RunModuleCommand(module, command_name);
}
}
}
void HMIWorker::ChangeToMap(const std::string &map_name,
MapService *map_service) {
if (status_.current_map() == map_name) {
return;
}
const auto *map_dir = FindOrNull(config_.available_maps(), map_name);
if (map_dir == nullptr) {
AERROR << "Unknown map " << map_name;
return;
}
status_.set_current_map(map_name);
apollo::common::KVDB::Put("apollo:dreamview:map", map_name);
SetGlobalFlag("map_dir", *map_dir, &FLAGS_map_dir);
// Also reload simulation map.
CHECK(map_service->ReloadMap(true)) << "Failed to load map from " << *map_dir;
RunModeCommand("stop");
}
void HMIWorker::ChangeToVehicle(const std::string &vehicle_name) {
if (status_.current_vehicle() == vehicle_name) {
return;
}
const auto *vehicle = FindOrNull(config_.available_vehicles(), vehicle_name);
if (vehicle == nullptr) {
AERROR << "Unknown vehicle " << vehicle_name;
return;
}
status_.set_current_vehicle(vehicle_name);
apollo::common::KVDB::Put("apollo:dreamview:vehicle", vehicle_name);
CHECK(VehicleManager::instance()->UseVehicle(*vehicle));
RunModeCommand("stop");
}
void HMIWorker::ChangeToMode(const std::string &mode_name) {
const std::string &old_mode = status_.current_mode();
if (old_mode == mode_name) {
return;
}
if (!ContainsKey(config_.modes(), mode_name)) {
AERROR << "Unknown mode " << mode_name;
return;
}
const auto &old_modules = config_.modes().at(old_mode).live_modules();
status_.set_current_mode(mode_name);
apollo::common::KVDB::Put("apollo:dreamview:mode", mode_name);
const bool use_navigation_mode = (mode_name == kNavigationModeName);
SetGlobalFlag("use_navigation_mode", use_navigation_mode,
&FLAGS_use_navigation_mode);
// Now stop all old modules.
for (const auto &module : old_modules) {
RunModuleCommand(module, "stop");
}
}
void HMIWorker::UpdateSystemStatus(const monitor::SystemStatus &system_status) {
*status_.mutable_system_status() = system_status;
}
} // namespace dreamview
} // namespace apollo
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/dreamview/backend/hmi/hmi_worker.h"
#include <vector>
#include "gflags/gflags.h"
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/kv_db/kv_db.h"
#include "modules/common/util/file.h"
#include "modules/common/util/map_util.h"
#include "modules/common/util/string_tokenizer.h"
#include "modules/common/util/string_util.h"
#include "modules/control/proto/pad_msg.pb.h"
#include "modules/data/util/info_collector.h"
#include "modules/dreamview/backend/common/dreamview_gflags.h"
#include "modules/dreamview/backend/hmi/vehicle_manager.h"
DEFINE_string(map_data_path, "/apollo/modules/map/data", "Path to map data.");
DEFINE_string(vehicle_data_path, "/apollo/modules/calibration/data",
"Path to vehicle data.");
namespace apollo {
namespace dreamview {
namespace {
using apollo::canbus::Chassis;
using apollo::common::adapter::AdapterManager;
using apollo::common::util::ContainsKey;
using apollo::common::util::FindOrNull;
using apollo::common::util::StringTokenizer;
using apollo::control::DrivingAction;
using google::protobuf::Map;
using RLock = boost::shared_lock<boost::shared_mutex>;
using WLock = boost::unique_lock<boost::shared_mutex>;
constexpr char kNavigationModeName[] = "Navigation";
// Convert a string to be title-like. E.g.: "hello_world" -> "Hello World".
std::string TitleCase(const std::string &origin,
const std::string &delimiter = "_") {
std::vector<std::string> parts = StringTokenizer::Split(origin, delimiter);
for (auto &part : parts) {
if (!part.empty()) {
// Upper case the first char.
part[0] = toupper(part[0]);
}
}
return apollo::common::util::PrintIter(parts);
}
// List subdirs and return a dict of {subdir_title: subdir_path}.
Map<std::string, std::string> ListDirAsDict(const std::string &dir) {
Map<std::string, std::string> result;
const auto subdirs = apollo::common::util::ListSubDirectories(dir);
for (const auto &subdir : subdirs) {
const auto subdir_title = TitleCase(subdir);
const auto subdir_path = apollo::common::util::StrCat(dir, "/", subdir);
result.insert({subdir_title, subdir_path});
}
return result;
}
// Run a supported command of some component, return the ret code.
int RunComponentCommand(const Map<std::string, Component> &components,
const std::string &component_name,
const std::string &command_name) {
const auto *component = FindOrNull(components, component_name);
if (component == nullptr) {
AERROR << "Cannot find component " << component_name;
return -1;
}
const auto *cmd = FindOrNull(component->supported_commands(), command_name);
if (cmd == nullptr) {
AERROR << "Cannot find command " << component_name << "." << command_name;
return -1;
}
AINFO << "Execute system command: " << *cmd;
const int ret = std::system(cmd->c_str());
AERROR_IF(ret != 0) << "Command returns " << ret << ": " << *cmd;
return ret;
}
template <class FlagType, class ValueType>
void SetGlobalFlag(const std::string &flag_name, const ValueType &value,
FlagType *flag) {
static constexpr char kGlobalFlagfile[] =
"/apollo/modules/common/data/global_flagfile.txt";
if (*flag != value) {
*flag = value;
// Overwrite global flagfile.
std::ofstream fout(kGlobalFlagfile, std::ios_base::app);
CHECK(fout) << "Fail to open global flagfile " << kGlobalFlagfile;
fout << "\n--" << flag_name << "=" << value << std::endl;
}
}
} // namespace
HMIWorker::HMIWorker() {
// Init HMIConfig.
CHECK(common::util::GetProtoFromFile(FLAGS_hmi_config_filename, &config_))
<< "Unable to parse HMI config file " << FLAGS_hmi_config_filename;
config_.set_docker_image(apollo::data::InfoCollector::GetDockerImage());
// If the module path doesn't exist, remove it from list.
auto *modules = config_.mutable_modules();
for (auto iter = modules->begin(); iter != modules->end();) {
const auto &conf = iter->second;
if (conf.has_path() && !common::util::PathExists(conf.path())) {
iter = modules->erase(iter);
} else {
++iter;
}
}
// Get available maps and vehicles by listing data directory.
*config_.mutable_available_maps() = ListDirAsDict(FLAGS_map_data_path);
*config_.mutable_available_vehicles() =
ListDirAsDict(FLAGS_vehicle_data_path);
config_.set_utm_zone_id(FLAGS_local_utm_zone_id);
ADEBUG << "Loaded HMI config: " << config_.DebugString();
// Init HMIStatus.
const auto &modes = config_.modes();
if (FLAGS_use_navigation_mode && ContainsKey(modes, kNavigationModeName)) {
// If the FLAG_use_navigation_mode is set, set it in HMIStatus.
status_.set_current_mode(kNavigationModeName);
} else if (!ContainsKey(modes, status_.current_mode())) {
CHECK(!modes.empty()) << "No available modes to run vehicle.";
// If the default mode is unavailable, select the first one.
status_.set_current_mode(modes.begin()->first);
}
// If the FLAGS_map_dir is set, set it in HMIStatus.
if (!FLAGS_map_dir.empty()) {
for (const auto &entry : config_.available_maps()) {
// entry is (map_name, map_path)
if (entry.second == FLAGS_map_dir) {
status_.set_current_map(entry.first);
break;
}
}
}
}
bool HMIWorker::Trigger(const HMIAction action) {
AINFO << "HMIAction " << HMIAction_Name(action) << " was triggered!";
switch (action) {
case HMIAction::SETUP:
RunModeCommand("start");
break;
case HMIAction::AUTO_MODE:
return ChangeToDrivingMode(Chassis::COMPLETE_AUTO_DRIVE);
case HMIAction::DISENGAGE:
return ChangeToDrivingMode(Chassis::COMPLETE_MANUAL);
default:
AERROR << "HMIAction not implemented, yet!";
return false;
}
return true;
}
int HMIWorker::RunModuleCommand(const std::string &module,
const std::string &command) {
return RunComponentCommand(config_.modules(), module, command);
}
int HMIWorker::RunHardwareCommand(const std::string &hardware,
const std::string &command) {
return RunComponentCommand(config_.hardware(), hardware, command);
}
int HMIWorker::RunToolCommand(const std::string &tool,
const std::string &command) {
return RunComponentCommand(config_.tools(), tool, command);
}
void HMIWorker::SubmitDriveEvent(const uint64_t event_time_ms,
const std::string &event_msg) {
apollo::common::DriveEvent drive_event;
AdapterManager::FillDriveEventHeader("HMI", &drive_event);
drive_event.mutable_header()->set_timestamp_sec(event_time_ms / 1000.0);
drive_event.set_event(event_msg);
AdapterManager::PublishDriveEvent(drive_event);
}
bool HMIWorker::ChangeToDrivingMode(const Chassis::DrivingMode mode) {
// Always reset to MANUAL mode before changing to other mode.
if (mode != Chassis::COMPLETE_MANUAL) {
if (!ChangeToDrivingMode(Chassis::COMPLETE_MANUAL)) {
AERROR << "Failed to reset to MANUAL mode before changing to "
<< Chassis::DrivingMode_Name(mode);
return false;
}
}
control::PadMessage pad;
switch (mode) {
case Chassis::COMPLETE_MANUAL:
pad.set_action(DrivingAction::RESET);
break;
case Chassis::COMPLETE_AUTO_DRIVE:
pad.set_action(DrivingAction::START);
break;
default:
AFATAL << "Unknown action to change driving mode to "
<< Chassis::DrivingMode_Name(mode);
}
constexpr int kMaxTries = 3;
constexpr auto kTryInterval = std::chrono::milliseconds(500);
auto *chassis = CHECK_NOTNULL(AdapterManager::GetChassis());
for (int i = 0; i < kMaxTries; ++i) {
// Send driving action periodically until entering target driving mode.
AdapterManager::FillPadHeader("HMI", &pad);
AdapterManager::PublishPad(pad);
std::this_thread::sleep_for(kTryInterval);
chassis->Observe();
if (chassis->Empty()) {
AERROR << "No Chassis message received!";
} else if (chassis->GetLatestObserved().driving_mode() == mode) {
return true;
}
}
AERROR << "Failed to change driving mode to "
<< Chassis::DrivingMode_Name(mode);
return false;
}
void HMIWorker::RunModeCommand(const std::string &command_name) {
std::string current_mode;
{
RLock rlock(status_mutex_);
current_mode = status_.current_mode();
}
const Mode &mode_conf = config_.modes().at(current_mode);
if (command_name == "start" || command_name == "stop") {
// Run the command on all live modules.
for (const auto &module : mode_conf.live_modules()) {
RunModuleCommand(module, command_name);
}
}
}
void HMIWorker::ChangeToMap(const std::string &map_name,
MapService *map_service) {
const auto *map_dir = FindOrNull(config_.available_maps(), map_name);
if (map_dir == nullptr) {
AERROR << "Unknown map " << map_name;
return;
}
{
// Update current_map status.
WLock wlock(status_mutex_);
if (status_.current_map() == map_name) {
return;
}
status_.set_current_map(map_name);
}
apollo::common::KVDB::Put("apollo:dreamview:map", map_name);
SetGlobalFlag("map_dir", *map_dir, &FLAGS_map_dir);
// Also reload simulation map.
CHECK(map_service->ReloadMap(true)) << "Failed to load map from " << *map_dir;
RunModeCommand("stop");
}
void HMIWorker::ChangeToVehicle(const std::string &vehicle_name) {
const auto *vehicle = FindOrNull(config_.available_vehicles(), vehicle_name);
if (vehicle == nullptr) {
AERROR << "Unknown vehicle " << vehicle_name;
return;
}
{
// Update current_vehicle status.
WLock wlock(status_mutex_);
if (status_.current_vehicle() == vehicle_name) {
return;
}
status_.set_current_vehicle(vehicle_name);
}
apollo::common::KVDB::Put("apollo:dreamview:vehicle", vehicle_name);
CHECK(VehicleManager::instance()->UseVehicle(*vehicle));
RunModeCommand("stop");
}
void HMIWorker::ChangeToMode(const std::string &mode_name) {
if (!ContainsKey(config_.modes(), mode_name)) {
AERROR << "Unknown mode " << mode_name;
return;
}
std::string old_mode;
{
// Update current_mode status.
WLock wlock(status_mutex_);
old_mode = status_.current_mode();
if (old_mode == mode_name) {
return;
}
status_.set_current_mode(mode_name);
}
apollo::common::KVDB::Put("apollo:dreamview:mode", mode_name);
const auto &old_modules = config_.modes().at(old_mode).live_modules();
const bool use_navigation_mode = (mode_name == kNavigationModeName);
SetGlobalFlag("use_navigation_mode", use_navigation_mode,
&FLAGS_use_navigation_mode);
// Now stop all old modules.
for (const auto &module : old_modules) {
RunModuleCommand(module, "stop");
}
}
void HMIWorker::UpdateSystemStatus(const monitor::SystemStatus &system_status) {
WLock wlock(status_mutex_);
*status_.mutable_system_status() = system_status;
}
} // namespace dreamview
} // namespace apollo
<commit_msg>Data: Fix missing map if it's set by default.<commit_after>/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/dreamview/backend/hmi/hmi_worker.h"
#include <vector>
#include "gflags/gflags.h"
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/kv_db/kv_db.h"
#include "modules/common/util/file.h"
#include "modules/common/util/map_util.h"
#include "modules/common/util/string_tokenizer.h"
#include "modules/common/util/string_util.h"
#include "modules/control/proto/pad_msg.pb.h"
#include "modules/data/util/info_collector.h"
#include "modules/dreamview/backend/common/dreamview_gflags.h"
#include "modules/dreamview/backend/hmi/vehicle_manager.h"
DEFINE_string(map_data_path, "/apollo/modules/map/data", "Path to map data.");
DEFINE_string(vehicle_data_path, "/apollo/modules/calibration/data",
"Path to vehicle data.");
namespace apollo {
namespace dreamview {
namespace {
using apollo::canbus::Chassis;
using apollo::common::adapter::AdapterManager;
using apollo::common::util::ContainsKey;
using apollo::common::util::FindOrNull;
using apollo::common::util::StringTokenizer;
using apollo::control::DrivingAction;
using google::protobuf::Map;
using RLock = boost::shared_lock<boost::shared_mutex>;
using WLock = boost::unique_lock<boost::shared_mutex>;
constexpr char kNavigationModeName[] = "Navigation";
// Convert a string to be title-like. E.g.: "hello_world" -> "Hello World".
std::string TitleCase(const std::string &origin,
const std::string &delimiter = "_") {
std::vector<std::string> parts = StringTokenizer::Split(origin, delimiter);
for (auto &part : parts) {
if (!part.empty()) {
// Upper case the first char.
part[0] = toupper(part[0]);
}
}
return apollo::common::util::PrintIter(parts);
}
// List subdirs and return a dict of {subdir_title: subdir_path}.
Map<std::string, std::string> ListDirAsDict(const std::string &dir) {
Map<std::string, std::string> result;
const auto subdirs = apollo::common::util::ListSubDirectories(dir);
for (const auto &subdir : subdirs) {
const auto subdir_title = TitleCase(subdir);
const auto subdir_path = apollo::common::util::StrCat(dir, "/", subdir);
result.insert({subdir_title, subdir_path});
}
return result;
}
// Run a supported command of some component, return the ret code.
int RunComponentCommand(const Map<std::string, Component> &components,
const std::string &component_name,
const std::string &command_name) {
const auto *component = FindOrNull(components, component_name);
if (component == nullptr) {
AERROR << "Cannot find component " << component_name;
return -1;
}
const auto *cmd = FindOrNull(component->supported_commands(), command_name);
if (cmd == nullptr) {
AERROR << "Cannot find command " << component_name << "." << command_name;
return -1;
}
AINFO << "Execute system command: " << *cmd;
const int ret = std::system(cmd->c_str());
AERROR_IF(ret != 0) << "Command returns " << ret << ": " << *cmd;
return ret;
}
template <class FlagType, class ValueType>
void SetGlobalFlag(const std::string &flag_name, const ValueType &value,
FlagType *flag) {
static constexpr char kGlobalFlagfile[] =
"/apollo/modules/common/data/global_flagfile.txt";
if (*flag != value) {
*flag = value;
// Overwrite global flagfile.
std::ofstream fout(kGlobalFlagfile, std::ios_base::app);
CHECK(fout) << "Fail to open global flagfile " << kGlobalFlagfile;
fout << "\n--" << flag_name << "=" << value << std::endl;
}
}
} // namespace
HMIWorker::HMIWorker() {
// Init HMIConfig.
CHECK(common::util::GetProtoFromFile(FLAGS_hmi_config_filename, &config_))
<< "Unable to parse HMI config file " << FLAGS_hmi_config_filename;
config_.set_docker_image(apollo::data::InfoCollector::GetDockerImage());
// If the module path doesn't exist, remove it from list.
auto *modules = config_.mutable_modules();
for (auto iter = modules->begin(); iter != modules->end();) {
const auto &conf = iter->second;
if (conf.has_path() && !common::util::PathExists(conf.path())) {
iter = modules->erase(iter);
} else {
++iter;
}
}
// Get available maps and vehicles by listing data directory.
*config_.mutable_available_maps() = ListDirAsDict(FLAGS_map_data_path);
*config_.mutable_available_vehicles() =
ListDirAsDict(FLAGS_vehicle_data_path);
config_.set_utm_zone_id(FLAGS_local_utm_zone_id);
ADEBUG << "Loaded HMI config: " << config_.DebugString();
// Init HMIStatus.
const auto &modes = config_.modes();
if (FLAGS_use_navigation_mode && ContainsKey(modes, kNavigationModeName)) {
// If the FLAG_use_navigation_mode is set, set it in HMIStatus.
status_.set_current_mode(kNavigationModeName);
} else if (!ContainsKey(modes, status_.current_mode())) {
CHECK(!modes.empty()) << "No available modes to run vehicle.";
// If the default mode is unavailable, select the first one.
status_.set_current_mode(modes.begin()->first);
}
// If the FLAGS_map_dir is set, set it in HMIStatus.
if (!FLAGS_map_dir.empty()) {
for (const auto &entry : config_.available_maps()) {
// entry is (map_name, map_path)
if (entry.second == FLAGS_map_dir) {
status_.set_current_map(entry.first);
apollo::common::KVDB::Put("apollo:dreamview:map", entry.first);
break;
}
}
}
}
bool HMIWorker::Trigger(const HMIAction action) {
AINFO << "HMIAction " << HMIAction_Name(action) << " was triggered!";
switch (action) {
case HMIAction::SETUP:
RunModeCommand("start");
break;
case HMIAction::AUTO_MODE:
return ChangeToDrivingMode(Chassis::COMPLETE_AUTO_DRIVE);
case HMIAction::DISENGAGE:
return ChangeToDrivingMode(Chassis::COMPLETE_MANUAL);
default:
AERROR << "HMIAction not implemented, yet!";
return false;
}
return true;
}
int HMIWorker::RunModuleCommand(const std::string &module,
const std::string &command) {
return RunComponentCommand(config_.modules(), module, command);
}
int HMIWorker::RunHardwareCommand(const std::string &hardware,
const std::string &command) {
return RunComponentCommand(config_.hardware(), hardware, command);
}
int HMIWorker::RunToolCommand(const std::string &tool,
const std::string &command) {
return RunComponentCommand(config_.tools(), tool, command);
}
void HMIWorker::SubmitDriveEvent(const uint64_t event_time_ms,
const std::string &event_msg) {
apollo::common::DriveEvent drive_event;
AdapterManager::FillDriveEventHeader("HMI", &drive_event);
drive_event.mutable_header()->set_timestamp_sec(event_time_ms / 1000.0);
drive_event.set_event(event_msg);
AdapterManager::PublishDriveEvent(drive_event);
}
bool HMIWorker::ChangeToDrivingMode(const Chassis::DrivingMode mode) {
// Always reset to MANUAL mode before changing to other mode.
if (mode != Chassis::COMPLETE_MANUAL) {
if (!ChangeToDrivingMode(Chassis::COMPLETE_MANUAL)) {
AERROR << "Failed to reset to MANUAL mode before changing to "
<< Chassis::DrivingMode_Name(mode);
return false;
}
}
control::PadMessage pad;
switch (mode) {
case Chassis::COMPLETE_MANUAL:
pad.set_action(DrivingAction::RESET);
break;
case Chassis::COMPLETE_AUTO_DRIVE:
pad.set_action(DrivingAction::START);
break;
default:
AFATAL << "Unknown action to change driving mode to "
<< Chassis::DrivingMode_Name(mode);
}
constexpr int kMaxTries = 3;
constexpr auto kTryInterval = std::chrono::milliseconds(500);
auto *chassis = CHECK_NOTNULL(AdapterManager::GetChassis());
for (int i = 0; i < kMaxTries; ++i) {
// Send driving action periodically until entering target driving mode.
AdapterManager::FillPadHeader("HMI", &pad);
AdapterManager::PublishPad(pad);
std::this_thread::sleep_for(kTryInterval);
chassis->Observe();
if (chassis->Empty()) {
AERROR << "No Chassis message received!";
} else if (chassis->GetLatestObserved().driving_mode() == mode) {
return true;
}
}
AERROR << "Failed to change driving mode to "
<< Chassis::DrivingMode_Name(mode);
return false;
}
void HMIWorker::RunModeCommand(const std::string &command_name) {
std::string current_mode;
{
RLock rlock(status_mutex_);
current_mode = status_.current_mode();
}
const Mode &mode_conf = config_.modes().at(current_mode);
if (command_name == "start" || command_name == "stop") {
// Run the command on all live modules.
for (const auto &module : mode_conf.live_modules()) {
RunModuleCommand(module, command_name);
}
}
}
void HMIWorker::ChangeToMap(const std::string &map_name,
MapService *map_service) {
const auto *map_dir = FindOrNull(config_.available_maps(), map_name);
if (map_dir == nullptr) {
AERROR << "Unknown map " << map_name;
return;
}
{
// Update current_map status.
WLock wlock(status_mutex_);
if (status_.current_map() == map_name) {
return;
}
status_.set_current_map(map_name);
}
apollo::common::KVDB::Put("apollo:dreamview:map", map_name);
SetGlobalFlag("map_dir", *map_dir, &FLAGS_map_dir);
// Also reload simulation map.
CHECK(map_service->ReloadMap(true)) << "Failed to load map from " << *map_dir;
RunModeCommand("stop");
}
void HMIWorker::ChangeToVehicle(const std::string &vehicle_name) {
const auto *vehicle = FindOrNull(config_.available_vehicles(), vehicle_name);
if (vehicle == nullptr) {
AERROR << "Unknown vehicle " << vehicle_name;
return;
}
{
// Update current_vehicle status.
WLock wlock(status_mutex_);
if (status_.current_vehicle() == vehicle_name) {
return;
}
status_.set_current_vehicle(vehicle_name);
}
apollo::common::KVDB::Put("apollo:dreamview:vehicle", vehicle_name);
CHECK(VehicleManager::instance()->UseVehicle(*vehicle));
RunModeCommand("stop");
}
void HMIWorker::ChangeToMode(const std::string &mode_name) {
if (!ContainsKey(config_.modes(), mode_name)) {
AERROR << "Unknown mode " << mode_name;
return;
}
std::string old_mode;
{
// Update current_mode status.
WLock wlock(status_mutex_);
old_mode = status_.current_mode();
if (old_mode == mode_name) {
return;
}
status_.set_current_mode(mode_name);
}
apollo::common::KVDB::Put("apollo:dreamview:mode", mode_name);
const auto &old_modules = config_.modes().at(old_mode).live_modules();
const bool use_navigation_mode = (mode_name == kNavigationModeName);
SetGlobalFlag("use_navigation_mode", use_navigation_mode,
&FLAGS_use_navigation_mode);
// Now stop all old modules.
for (const auto &module : old_modules) {
RunModuleCommand(module, "stop");
}
}
void HMIWorker::UpdateSystemStatus(const monitor::SystemStatus &system_status) {
WLock wlock(status_mutex_);
*status_.mutable_system_status() = system_status;
}
} // namespace dreamview
} // namespace apollo
<|endoftext|>
|
<commit_before>/*****************************************************************************
* EPGRuler.coo: EPGRuler
****************************************************************************
* Copyright © 2009-2010 VideoLAN
* $Id$
*
* Authors: Ludovic Fauvet <etix@l0cal.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 "EPGRuler.hpp"
#include <QPainter>
#include <QFont>
#include <QPaintEvent>
#include <QtDebug>
#include <QDateTime>
EPGRuler::EPGRuler( QWidget* parent )
: QWidget( parent )
{
setContentsMargins( 0, 0, 0, 0 );
setMinimumHeight( 30 );
setMaximumHeight( 30 );
m_offset = 0;
}
void EPGRuler::setScale( double scale )
{
m_scale = scale;
update();
}
void EPGRuler::setStartTime( const QDateTime& startTime )
{
m_startTime = startTime;
update();
}
void EPGRuler::setDuration( int duration )
{
m_duration = duration;
update();
}
void EPGRuler::setOffset( int offset )
{
m_offset = offset;
update();
}
void EPGRuler::paintEvent( QPaintEvent *event )
{
Q_UNUSED( event );
QPainter p( this );
int secondsOffset = m_offset / m_scale;
QDateTime localStartTime;
localStartTime = m_startTime.addSecs( secondsOffset );
QDateTime diff( localStartTime );
diff.setTime( QTime( localStartTime.time().hour(), 0, 0, 0 ) );
int secondsToHour = localStartTime.secsTo( diff );
QDateTime current( localStartTime.addSecs( secondsToHour ) );
int spacing = ( m_scale * 60 ) * 60;
int posx = secondsToHour * m_scale;
// Count the number of items to draw
int itemsToDraw = ( width() / spacing ) + 1;
for ( ; itemsToDraw >= 0; --itemsToDraw )
{
p.setFont( QFont( "Verdana", 8 ) );
p.drawLine( posx, 15, posx, 30 );
p.drawText( posx + 1, 12, 50, 15, Qt::AlignLeft, current.toString( "hh'h'" ) );
posx += spacing;
current = current.addSecs( 60 * 60 );
}
}
<commit_msg>qt4: don't force font and size in epg-widget<commit_after>/*****************************************************************************
* EPGRuler.coo: EPGRuler
****************************************************************************
* Copyright © 2009-2010 VideoLAN
* $Id$
*
* Authors: Ludovic Fauvet <etix@l0cal.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 "EPGRuler.hpp"
#include <QPainter>
#include <QFont>
#include <QPaintEvent>
#include <QtDebug>
#include <QDateTime>
EPGRuler::EPGRuler( QWidget* parent )
: QWidget( parent )
{
setContentsMargins( 0, 0, 0, 0 );
setMinimumHeight( 30 );
setMaximumHeight( 30 );
m_offset = 0;
}
void EPGRuler::setScale( double scale )
{
m_scale = scale;
update();
}
void EPGRuler::setStartTime( const QDateTime& startTime )
{
m_startTime = startTime;
update();
}
void EPGRuler::setDuration( int duration )
{
m_duration = duration;
update();
}
void EPGRuler::setOffset( int offset )
{
m_offset = offset;
update();
}
void EPGRuler::paintEvent( QPaintEvent *event )
{
Q_UNUSED( event );
QPainter p( this );
int secondsOffset = m_offset / m_scale;
QDateTime localStartTime;
localStartTime = m_startTime.addSecs( secondsOffset );
QDateTime diff( localStartTime );
diff.setTime( QTime( localStartTime.time().hour(), 0, 0, 0 ) );
int secondsToHour = localStartTime.secsTo( diff );
QDateTime current( localStartTime.addSecs( secondsToHour ) );
int spacing = ( m_scale * 60 ) * 60;
int posx = secondsToHour * m_scale;
// Count the number of items to draw
int itemsToDraw = ( width() / spacing ) + 1;
for ( ; itemsToDraw >= 0; --itemsToDraw )
{
p.drawLine( posx, 15, posx, 30 );
p.drawText( posx + 1, 12, 50, 15, Qt::AlignLeft, current.toString( "hh'h'" ) );
posx += spacing;
current = current.addSecs( 60 * 60 );
}
}
<|endoftext|>
|
<commit_before>/*
* server_test.cpp
*
* Created on: Jan 16, 2013
* Author: mfleder
*/
#include <stdio.h>
#include <lcm/lcm-cpp.hpp>
#include <boost/shared_ptr.hpp>
#include "affordance/AffordanceServer.h"
#include "affordance/AffordanceUpWrapper.h"
#include "affordance/AffordanceState.h"
#include <iostream>
using namespace boost;
using namespace std;
using namespace affordance;
/**populates the server w/ a bunch of affordances*/
void runPopulate(const shared_ptr<lcm::LCM> lcm)
{
AffordanceUpWrapper wrapper(lcm);
const int mapId = 0;
int uniqueObjId = 0;
//sphere
AffordanceState sphere(AffordanceState::SPHERE, uniqueObjId++, mapId,
KDL::Frame(KDL::Vector(-0.5, -0.5, 0.0)),
Eigen::Vector3f(1.0, 0.0, 1.0)); //color
sphere._params[AffordanceState::RADIUS_NAME] = 0.125;
wrapper.addNewlyFittedAffordance(sphere);
//box
AffordanceState box(AffordanceState::BOX, uniqueObjId++, mapId,
KDL::Frame(KDL::Vector(0.0, 0.0, 0.0)),
Eigen::Vector3f(0.75, 0.75, 0.0));
box._params[AffordanceState::LENGTH_NAME] = 100;
box._params[AffordanceState::WIDTH_NAME] = 100;
box._params[AffordanceState::HEIGHT_NAME] = .00001;
wrapper.addNewlyFittedAffordance(box);
//cylinder
AffordanceState cylinder(AffordanceState::CYLINDER, uniqueObjId++, mapId,
KDL::Frame(KDL::Vector(0.0, 1.0, 0.0)),
Eigen::Vector3f(0.0, 1.0, 1.0)); //color
cylinder._params[AffordanceState::RADIUS_NAME] = 0.25;
cylinder._params[AffordanceState::LENGTH_NAME] = 0.25;
wrapper.addNewlyFittedAffordance(cylinder);
//=============
//add a bunch of affordances w/ just names + ids
// wrapper.addNewlyFittedAffordance(AffordanceState("steering_cyl", uniqueObjId++, mapId));
// wrapper.addNewlyFittedAffordance(AffordanceState("box", uniqueObjId++, mapId));
// wrapper.addNewlyFittedAffordance(AffordanceState("ladder", uniqueObjId++, mapId));
// wrapper.addNewlyFittedAffordance(AffordanceState("cylinder", uniqueObjId++, mapId));
// wrapper.addNewlyFittedAffordance(AffordanceState("sphere", uniqueObjId++, mapId));
// wrapper.addNewlyFittedAffordance(AffordanceState("box", uniqueObjId++, mapId));
// wrapper.addNewlyFittedAffordance(AffordanceState("ladder_cyl", uniqueObjId++, mapId));
int j = 0;
boost::posix_time::seconds sleepTime(1); //update every 1 seconds
while (true)
{
//cout << "\n\n===" << j << endl;
cout << wrapper << endl;
boost::this_thread::sleep(sleepTime); //======sleep
//======modify server
if (j++ == 10)
{
//make a modification
}
}
}
int main(int argc, char **argv)
{
shared_ptr<lcm::LCM> theLcm(new lcm::LCM());
if (!theLcm->good())
{
cerr << "Cannot create lcm object" << endl;
return -1;
}
//create the server
AffordanceServer s(theLcm);
//thread will add to the affordance server
//and possibly make changes over time
boost::thread populateThread = boost::thread(runPopulate, theLcm);
//lcm loop
cout << "\nstarting lcm loop" << endl;
while (0 == theLcm->handle())
{
;
}
return 0;
}
<commit_msg>updated for new affordanceState constructor<commit_after>/*
* server_test.cpp
*
* Created on: Jan 16, 2013
* Author: mfleder
*/
#include <stdio.h>
#include <lcm/lcm-cpp.hpp>
#include <boost/shared_ptr.hpp>
#include "affordance/AffordanceServer.h"
#include "affordance/AffordanceUpWrapper.h"
#include "affordance/AffordanceState.h"
#include <iostream>
using namespace boost;
using namespace std;
using namespace affordance;
/**populates the server w/ a bunch of affordances*/
void runPopulate(const shared_ptr<lcm::LCM> lcm)
{
AffordanceUpWrapper wrapper(lcm);
const int mapId = 0;
int uniqueObjId = 0;
//sphere
AffordanceState sphere(uniqueObjId++, mapId,
KDL::Frame(KDL::Vector(-0.5, -0.5, 0.0)),
Eigen::Vector3f(1.0, 0.0, 1.0)); //color
sphere._params[AffordanceState::RADIUS_NAME] = 0.125;
sphere.setType(AffordanceState::SPHERE);
wrapper.addNewlyFittedAffordance(sphere);
//box
AffordanceState box(uniqueObjId++, mapId,
KDL::Frame(KDL::Vector(0.0, 0.0, 0.0)),
Eigen::Vector3f(0.75, 0.75, 0.0));
box._params[AffordanceState::LENGTH_NAME] = 100;
box._params[AffordanceState::WIDTH_NAME] = 100;
box._params[AffordanceState::HEIGHT_NAME] = .00001;
box.setType(AffordanceState::BOX);
wrapper.addNewlyFittedAffordance(box);
//cylinder
AffordanceState cylinder(uniqueObjId++, mapId,
KDL::Frame(KDL::Vector(0.0, 1.0, 0.0)),
Eigen::Vector3f(0.0, 1.0, 1.0)); //color
cylinder._params[AffordanceState::RADIUS_NAME] = 0.25;
cylinder._params[AffordanceState::LENGTH_NAME] = 0.25;
cylinder.setType(AffordanceState::CYLINDER);
wrapper.addNewlyFittedAffordance(cylinder);
//=============
//add a bunch of affordances w/ just names + ids
// wrapper.addNewlyFittedAffordance(AffordanceState("steering_cyl", uniqueObjId++, mapId));
// wrapper.addNewlyFittedAffordance(AffordanceState("box", uniqueObjId++, mapId));
// wrapper.addNewlyFittedAffordance(AffordanceState("ladder", uniqueObjId++, mapId));
// wrapper.addNewlyFittedAffordance(AffordanceState("cylinder", uniqueObjId++, mapId));
// wrapper.addNewlyFittedAffordance(AffordanceState("sphere", uniqueObjId++, mapId));
// wrapper.addNewlyFittedAffordance(AffordanceState("box", uniqueObjId++, mapId));
// wrapper.addNewlyFittedAffordance(AffordanceState("ladder_cyl", uniqueObjId++, mapId));
int j = 0;
boost::posix_time::seconds sleepTime(1); //update every 1 seconds
while (true)
{
//cout << "\n\n===" << j << endl;
cout << wrapper << endl;
boost::this_thread::sleep(sleepTime); //======sleep
//======modify server
if (j++ == 10)
{
//make a modification
}
}
}
int main(int argc, char **argv)
{
shared_ptr<lcm::LCM> theLcm(new lcm::LCM());
if (!theLcm->good())
{
cerr << "Cannot create lcm object" << endl;
return -1;
}
//create the server
AffordanceServer s(theLcm);
//thread will add to the affordance server
//and possibly make changes over time
boost::thread populateThread = boost::thread(runPopulate, theLcm);
//lcm loop
cout << "\nstarting lcm loop" << endl;
while (0 == theLcm->handle())
{
;
}
return 0;
}
<|endoftext|>
|
<commit_before>// Simple Chatterbox client written in C++
// Many of the functions are taken from the excellent Winsock FAQ at
// http://tangentsoft.net/wskfaq/
#include <iostream>
#include <string>
#include <stdexcept>
#include <winsock2.h>
// #include <winsock.h>
using namespace std;
class WASDataWrapper {
WSADATA wsaData_;
public:
WASDataWrapper() {
if(WSAStartup(MAKEWORD(2,2), &wsaData_) != 0) {
throw runtime_error("WSAStartup failed");
}
}
~WASDataWrapper() {
WSACleanup();
}
};
//// LookupAddress /////////////////////////////////////////////////////
// Given an address string, determine if it's a dotted-quad IP address
// or a domain address. If the latter, ask DNS to resolve it. In
// either case, return resolved IP address. If we fail, we return
// INADDR_NONE.
u_long LookupAddress(const char* pcHost)
{
u_long nRemoteAddr = inet_addr(pcHost);
if (nRemoteAddr == INADDR_NONE) {
// pcHost isn't a dotted IP, so resolve it through DNS
hostent* pHE = gethostbyname(pcHost);
if (pHE == 0) {
return INADDR_NONE;
}
nRemoteAddr = *((u_long*)pHE->h_addr_list[0]);
}
return nRemoteAddr;
}
//// EstablishConnection ///////////////////////////////////////////////
// Connects to a given address, on a given port, both of which must be
// in network byte order. Returns newly-connected socket if we succeed,
// or INVALID_SOCKET if we fail.
SOCKET EstablishConnection(u_long nRemoteAddr, u_short nPort)
{
// Create a stream socket
// SOCKET sd = socket(AF_INET, SOCK_STREAM, 0);
SOCKET sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sd != INVALID_SOCKET) {
SOCKADDR_IN sinRemote;
sinRemote.sin_family = AF_INET;
sinRemote.sin_addr.s_addr = nRemoteAddr;
sinRemote.sin_port = nPort;
if (connect(sd, (sockaddr*)&sinRemote, sizeof(sockaddr_in)) ==
SOCKET_ERROR) {
sd = INVALID_SOCKET;
}
}
return sd;
}
//// ShutdownConnection ////////////////////////////////////////////////
// Gracefully shuts the connection sd down. Returns true if we're
// successful, false otherwise.
bool ShutdownConnection(SOCKET sd)
{
const int kBufferSize = 1024;
// const int SD_SEND = 1;
// Disallow any further data sends. This will tell the other side
// that we want to go away now. If we skip this step, we don't
// shut the connection down nicely.
if (shutdown(sd, SD_SEND) == SOCKET_ERROR) {
return false;
}
// Receive any extra data still sitting on the socket. After all
// data is received, this call will block until the remote host
// acknowledges the TCP control packet sent by the shutdown above.
// Then we'll get a 0 back from recv, signalling that the remote
// host has closed its side of the connection.
char acReadBuffer[kBufferSize];
while (1) {
int nNewBytes = recv(sd, acReadBuffer, kBufferSize, 0);
if (nNewBytes == SOCKET_ERROR) {
return false;
}
else if (nNewBytes != 0) {
cerr << endl << "FYI, received " << nNewBytes <<
" unexpected bytes during shutdown." << endl;
}
else {
// Okay, we're done!
break;
}
}
// Close the socket.
if (closesocket(sd) == SOCKET_ERROR) {
return false;
}
return true;
}
int main() {
WASDataWrapper wsaData;
// Connect to a Chatterbox server
string host = "localhost";
u_short port = 20000;
u_long remote_addr = LookupAddress(host.c_str());
if (remote_addr == INADDR_NONE) {
cerr << "Could not detremine remote host address." ;
return 1;
}
cout << "remote_addr=" << remote_addr << '\n';
in_addr address;
memcpy(&address, &remote_addr, sizeof(u_long));
cout << "Connecting to Chatterbox server at, " << inet_ntoa(address) << ":" << port << endl;
// Create a stream socket
SOCKET sd = EstablishConnection(remote_addr, port);
if(sd == INVALID_SOCKET) {
cout << "Could not connect to Chatterbox server\n";
cerr << "WSAGetLastError() says:" << WSAGetLastError() << '\n';
return 1;
}
cout << "Connected to Chatterbox server!";
// Let user enter an id
// auto userID = "";
// userID << cin;
// Send the user ID
// socket.send(userID);
// Create a sender thread and listener thread
// Start listener thread
// Start sender thread
// Wait for threads to exit
// Shut connection down
cout << "Disconnectiong from Chatterbox server.\n";
if (ShutdownConnection(sd)) {
cout << "Disconnected successfully.\n" << endl;
}
else {
cout << "Problem disconnecting.\n";
}
cout << "Exiting Chatterbox client." << endl;
return 0;
}
<commit_msg>Add build comment.<commit_after>// Simple Chatterbox client written in C++
// Many of the functions are taken from the excellent Winsock FAQ at
// http://tangentsoft.net/wskfaq/
// Build using:
// g++ -std=c++0x -Wall -o cbclient cbclient.cpp -lws2_32
#include <iostream>
#include <string>
#include <stdexcept>
#include <winsock2.h>
// #include <winsock.h>
using namespace std;
class WASDataWrapper {
WSADATA wsaData_;
public:
WASDataWrapper() {
if(WSAStartup(MAKEWORD(2,2), &wsaData_) != 0) {
throw runtime_error("WSAStartup failed");
}
}
~WASDataWrapper() {
WSACleanup();
}
};
//// LookupAddress /////////////////////////////////////////////////////
// Given an address string, determine if it's a dotted-quad IP address
// or a domain address. If the latter, ask DNS to resolve it. In
// either case, return resolved IP address. If we fail, we return
// INADDR_NONE.
u_long LookupAddress(const char* pcHost)
{
u_long nRemoteAddr = inet_addr(pcHost);
if (nRemoteAddr == INADDR_NONE) {
// pcHost isn't a dotted IP, so resolve it through DNS
hostent* pHE = gethostbyname(pcHost);
if (pHE == 0) {
return INADDR_NONE;
}
nRemoteAddr = *((u_long*)pHE->h_addr_list[0]);
}
return nRemoteAddr;
}
//// EstablishConnection ///////////////////////////////////////////////
// Connects to a given address, on a given port, both of which must be
// in network byte order. Returns newly-connected socket if we succeed,
// or INVALID_SOCKET if we fail.
SOCKET EstablishConnection(u_long nRemoteAddr, u_short nPort)
{
// Create a stream socket
// SOCKET sd = socket(AF_INET, SOCK_STREAM, 0);
SOCKET sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sd != INVALID_SOCKET) {
SOCKADDR_IN sinRemote;
sinRemote.sin_family = AF_INET;
sinRemote.sin_addr.s_addr = nRemoteAddr;
sinRemote.sin_port = nPort;
if (connect(sd, (sockaddr*)&sinRemote, sizeof(sockaddr_in)) ==
SOCKET_ERROR) {
sd = INVALID_SOCKET;
}
}
return sd;
}
//// ShutdownConnection ////////////////////////////////////////////////
// Gracefully shuts the connection sd down. Returns true if we're
// successful, false otherwise.
bool ShutdownConnection(SOCKET sd)
{
const int kBufferSize = 1024;
// const int SD_SEND = 1;
// Disallow any further data sends. This will tell the other side
// that we want to go away now. If we skip this step, we don't
// shut the connection down nicely.
if (shutdown(sd, SD_SEND) == SOCKET_ERROR) {
return false;
}
// Receive any extra data still sitting on the socket. After all
// data is received, this call will block until the remote host
// acknowledges the TCP control packet sent by the shutdown above.
// Then we'll get a 0 back from recv, signalling that the remote
// host has closed its side of the connection.
char acReadBuffer[kBufferSize];
while (1) {
int nNewBytes = recv(sd, acReadBuffer, kBufferSize, 0);
if (nNewBytes == SOCKET_ERROR) {
return false;
}
else if (nNewBytes != 0) {
cerr << endl << "FYI, received " << nNewBytes <<
" unexpected bytes during shutdown." << endl;
}
else {
// Okay, we're done!
break;
}
}
// Close the socket.
if (closesocket(sd) == SOCKET_ERROR) {
return false;
}
return true;
}
int main() {
WASDataWrapper wsaData;
// Connect to a Chatterbox server
string host = "localhost";
u_short port = 20000;
u_long remote_addr = LookupAddress(host.c_str());
if (remote_addr == INADDR_NONE) {
cerr << "Could not detremine remote host address." ;
return 1;
}
cout << "remote_addr=" << remote_addr << '\n';
in_addr address;
memcpy(&address, &remote_addr, sizeof(u_long));
cout << "Connecting to Chatterbox server at, " << inet_ntoa(address) << ":" << port << endl;
// Create a stream socket
SOCKET sd = EstablishConnection(remote_addr, port);
if(sd == INVALID_SOCKET) {
cout << "Could not connect to Chatterbox server\n";
cerr << "WSAGetLastError() says:" << WSAGetLastError() << '\n';
return 1;
}
cout << "Connected to Chatterbox server!";
// Let user enter an id
// auto userID = "";
// userID << cin;
// Send the user ID
// socket.send(userID);
// Create a sender thread and listener thread
// Start listener thread
// Start sender thread
// Wait for threads to exit
// Shut connection down
cout << "Disconnectiong from Chatterbox server.\n";
if (ShutdownConnection(sd)) {
cout << "Disconnected successfully.\n" << endl;
}
else {
cout << "Problem disconnecting.\n";
}
cout << "Exiting Chatterbox client." << endl;
return 0;
}
<|endoftext|>
|
<commit_before>//@author A0094446X
#include "stdafx.h"
#include <QApplication>
#include <QList>
#include <QPair>
#include "task_panel_manager.h"
namespace You {
namespace GUI {
using Date = boost::gregorian::date;
const QString MainWindow::TaskPanelManager::TASK_COLUMN_1 = "Hidden ID Column";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_2 = "Index";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_3 = "Description";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_4 = "Deadline";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_5 = "Priority";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_6 = "Dependencies";
MainWindow::TaskPanelManager::TaskPanelManager(MainWindow* const parentGUI)
: BaseManager(parentGUI), deleteAction(QString("Delete"), this),
editAction(QString("Edit"), this), addAction(QString("Add"), this),
deleteSignalMapper(this), editSignalMapper(this) {
}
MainWindow::TaskPanelManager::~TaskPanelManager() {
}
void MainWindow::TaskPanelManager::setup() {
QStringList columnHeaders({
TASK_COLUMN_1,
TASK_COLUMN_2,
TASK_COLUMN_3,
TASK_COLUMN_4,
TASK_COLUMN_5,
TASK_COLUMN_6
});
QTreeWidget* taskTreePanel = parentGUI->ui.taskTreePanel;
connect(taskTreePanel, SIGNAL(itemSelectionChanged()),
parentGUI, SLOT(taskSelected()));
connect(taskTreePanel, SIGNAL(customContextMenuRequested(const QPoint &)),
this, SLOT(contextMenu(const QPoint &)));
taskTreePanel->setColumnCount(columnHeaders.size());
taskTreePanel->setHeaderItem(createItem(columnHeaders).release());
// TODO(angathorion): remove magic constants.
QHeaderView* header = taskTreePanel->header();
header->setStretchLastSection(true);
for (int i = 1; i < columnHeaders.size(); ++i) {
if (i == 2) {
continue;
}
header->resizeSection(i, header->defaultSectionSize());
}
taskTreePanel->header()->setMinimumSectionSize(75);
taskTreePanel->setColumnHidden(0, true);
taskTreePanel->setColumnHidden(5, true);
}
void MainWindow::TaskPanelManager::addTask(const Task& task) {
std::unique_ptr<QTreeWidgetItem> item(createItem(task));
parentGUI->ui.taskTreePanel->addTopLevelItem(item.release());
updateRowNumbers();
}
void MainWindow::TaskPanelManager::addSubtask(QTreeWidgetItem* parent,
const QStringList& rowStrings) {
std::unique_ptr<QTreeWidgetItem> item(createItem(rowStrings));
parent->addChild(item.release());
updateRowNumbers();
}
void MainWindow::TaskPanelManager::editTask(const Task& task) {
QList<QTreeWidgetItem*> items = findItems(task.getID());
assert(items.length() == 1);
QTreeWidgetItem item = *items.at(0);
QStringList wstr = taskToStrVec(task);
*items.at(0) = *createItem(wstr);
updateRowNumbers();
}
void MainWindow::TaskPanelManager::deleteTask(Task::ID taskID) {
QList<QTreeWidgetItem*> items = findItems(taskID);
assert(items.length() == 1);
deleteTask(items.at(0));
updateRowNumbers();
}
void MainWindow::TaskPanelManager::deleteTask(QTreeWidgetItem* task) {
delete task;
}
std::unique_ptr<QTreeWidgetItem> MainWindow::TaskPanelManager::createItem(
const Task& task) {
return createItem(taskToStrVec(task));
}
std::unique_ptr<QTreeWidgetItem> MainWindow::TaskPanelManager::createItem(
const QStringList& rowStrings) {
return std::make_unique<QTreeWidgetItem>(rowStrings);
}
QList<QTreeWidgetItem*> MainWindow::TaskPanelManager::findItems(
You::Controller::Task::ID taskID) const {
return parentGUI->ui.taskTreePanel->findItems(
boost::lexical_cast<QString>(taskID), 0);
}
QStringList MainWindow::TaskPanelManager::taskToStrVec(
const You::Controller::Task& task) {
QStringList result;
// Insert id
result.push_back(boost::lexical_cast<QString>(task.getID()));
// Insert dummy count
result.push_back("0");
// Insert description
result.push_back(QString::fromStdWString(task.getDescription()));
// Insert deadline
std::wstringstream wss;
if (task.getDeadline() == Task::NEVER) {
wss << L"Never";
} else if (isPastDue(task.getDeadline())) {
wss << L"Overdue (" << task.getDeadline() << L")";
} else if (isDueAfter(task.getDeadline(), 0)) {
wss << L"Today (" << task.getDeadline() << L")";
} else if (isDueAfter(task.getDeadline(), 1)) {
wss << L"Tomorrow (" << task.getDeadline() << L")";
} else if (isDueAfter(task.getDeadline(), 2)) {
wss << L"In two days (" << task.getDeadline() << L")";
} else if (isDueWithin(task.getDeadline(), 7)) {
wss << L"Within one week (" << task.getDeadline() << L")";
} else if (isDueWithin(task.getDeadline(), 14)) {
wss << L"Within two weeks (" << task.getDeadline() << L")";
} else if (isDueWithin(task.getDeadline(), 21)) {
wss << L"Within three weeks (" << task.getDeadline() << L")";
} else if (isDueWithin(task.getDeadline(), 28)) {
wss << L"Within one month (" << task.getDeadline() << L")";
} else {
wss << L"More than a month away (" << task.getDeadline() << L")";
}
result.push_back(boost::lexical_cast<QString>(wss.str()));
// Insert priority
QString priority[] { "High", "Normal" };
switch (task.getPriority()) {
case Task::Priority::HIGH:
result.push_back(priority[0]);
case Task::Priority::NORMAL:
result.push_back(priority[1]);
}
// Insert dependencies
std::ostringstream ss;
if (task.getDependencies().size() != 0) {
Task::Dependencies dependencies = task.getDependencies();
std::copy(dependencies.begin(), --dependencies.end(),
std::ostream_iterator<Task::ID>(ss, ", "));
ss << *dependencies.end();
result.push_back(QString::fromStdString(ss.str()));
} else {
result.push_back("None");
}
return result;
}
void MainWindow::TaskPanelManager::updateRowNumbers() {
int rowNum = 0;
for (QTreeWidgetItemIterator it(parentGUI->ui.taskTreePanel); *it; ++it) {
(*it)->setData(1, Qt::DisplayRole, rowNum++);
}
}
bool MainWindow::TaskPanelManager::isPastDue(Task::Time deadline) {
Task::Time now = boost::posix_time::second_clock::local_time();
return deadline < now;
}
bool MainWindow::TaskPanelManager::isDueAfter(
Task::Time deadline, int daysLeft) {
Date by = Date(deadline.date());
Date today = boost::gregorian::day_clock::local_day();
return by.modjulian_day() - today.modjulian_day() == daysLeft;
}
bool MainWindow::TaskPanelManager::isDueWithin(
Task::Time deadline, int daysLeft) {
Date by = Date(deadline.date());
Date today = boost::gregorian::day_clock::local_day();
return by.julian_day() - today.julian_day() < daysLeft;
}
void MainWindow::TaskPanelManager::contextMenu(const QPoint &pos) {
/// Try to get the item at the position of the context menu
QTreeWidgetItem *item = parentGUI->ui.taskTreePanel->itemAt(pos);
itemContextMenu.reset(new QMenu(parentGUI->ui.taskTreePanel));
/// Adds the Add Task action. This is always present in the menu.
itemContextMenu->addAction(&addAction);
connect(&addAction, SIGNAL(triggered()), parentGUI, SLOT(contextAddTask()));
/// Adds the Edit Task and Delete Task actions if an item is selected.
/// QSignalMapper is necessary because arguments need to be passed
/// as part of the signal.
if (item) {
deleteSignalMapper.setMapping(&deleteAction, item->text(1).toInt());
connect(&deleteAction, SIGNAL(triggered()),
&deleteSignalMapper, SLOT(map()));
itemContextMenu->addAction(&deleteAction);
connect(&deleteSignalMapper, SIGNAL(mapped(int)),
parentGUI, SLOT(contextDeleteTask(int)));
editSignalMapper.setMapping(&editAction, item->text(1).toInt());
connect(&editAction, SIGNAL(triggered()),
&editSignalMapper, SLOT(map()));
itemContextMenu->addAction(&editAction);
connect(&editSignalMapper, SIGNAL(mapped(int)),
parentGUI, SLOT(contextEditTask(int)));
}
itemContextMenu->popup(
parentGUI->ui.taskTreePanel->viewport()->mapToGlobal(pos));
}
} // namespace GUI
} // namespace You
<commit_msg>Set to element before end<commit_after>//@author A0094446X
#include "stdafx.h"
#include <QApplication>
#include <QList>
#include <QPair>
#include "task_panel_manager.h"
namespace You {
namespace GUI {
using Date = boost::gregorian::date;
const QString MainWindow::TaskPanelManager::TASK_COLUMN_1 = "Hidden ID Column";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_2 = "Index";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_3 = "Description";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_4 = "Deadline";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_5 = "Priority";
const QString MainWindow::TaskPanelManager::TASK_COLUMN_6 = "Dependencies";
MainWindow::TaskPanelManager::TaskPanelManager(MainWindow* const parentGUI)
: BaseManager(parentGUI), deleteAction(QString("Delete"), this),
editAction(QString("Edit"), this), addAction(QString("Add"), this),
deleteSignalMapper(this), editSignalMapper(this) {
}
MainWindow::TaskPanelManager::~TaskPanelManager() {
}
void MainWindow::TaskPanelManager::setup() {
QStringList columnHeaders({
TASK_COLUMN_1,
TASK_COLUMN_2,
TASK_COLUMN_3,
TASK_COLUMN_4,
TASK_COLUMN_5,
TASK_COLUMN_6
});
QTreeWidget* taskTreePanel = parentGUI->ui.taskTreePanel;
connect(taskTreePanel, SIGNAL(itemSelectionChanged()),
parentGUI, SLOT(taskSelected()));
connect(taskTreePanel, SIGNAL(customContextMenuRequested(const QPoint &)),
this, SLOT(contextMenu(const QPoint &)));
taskTreePanel->setColumnCount(columnHeaders.size());
taskTreePanel->setHeaderItem(createItem(columnHeaders).release());
// TODO(angathorion): remove magic constants.
QHeaderView* header = taskTreePanel->header();
header->setStretchLastSection(true);
for (int i = 1; i < columnHeaders.size(); ++i) {
if (i == 2) {
continue;
}
header->resizeSection(i, header->defaultSectionSize());
}
taskTreePanel->header()->setMinimumSectionSize(75);
taskTreePanel->setColumnHidden(0, true);
taskTreePanel->setColumnHidden(5, true);
}
void MainWindow::TaskPanelManager::addTask(const Task& task) {
std::unique_ptr<QTreeWidgetItem> item(createItem(task));
parentGUI->ui.taskTreePanel->addTopLevelItem(item.release());
updateRowNumbers();
}
void MainWindow::TaskPanelManager::addSubtask(QTreeWidgetItem* parent,
const QStringList& rowStrings) {
std::unique_ptr<QTreeWidgetItem> item(createItem(rowStrings));
parent->addChild(item.release());
updateRowNumbers();
}
void MainWindow::TaskPanelManager::editTask(const Task& task) {
QList<QTreeWidgetItem*> items = findItems(task.getID());
assert(items.length() == 1);
QTreeWidgetItem item = *items.at(0);
QStringList wstr = taskToStrVec(task);
*items.at(0) = *createItem(wstr);
updateRowNumbers();
}
void MainWindow::TaskPanelManager::deleteTask(Task::ID taskID) {
QList<QTreeWidgetItem*> items = findItems(taskID);
assert(items.length() == 1);
deleteTask(items.at(0));
updateRowNumbers();
}
void MainWindow::TaskPanelManager::deleteTask(QTreeWidgetItem* task) {
delete task;
}
std::unique_ptr<QTreeWidgetItem> MainWindow::TaskPanelManager::createItem(
const Task& task) {
return createItem(taskToStrVec(task));
}
std::unique_ptr<QTreeWidgetItem> MainWindow::TaskPanelManager::createItem(
const QStringList& rowStrings) {
return std::make_unique<QTreeWidgetItem>(rowStrings);
}
QList<QTreeWidgetItem*> MainWindow::TaskPanelManager::findItems(
You::Controller::Task::ID taskID) const {
return parentGUI->ui.taskTreePanel->findItems(
boost::lexical_cast<QString>(taskID), 0);
}
QStringList MainWindow::TaskPanelManager::taskToStrVec(
const You::Controller::Task& task) {
QStringList result;
// Insert id
result.push_back(boost::lexical_cast<QString>(task.getID()));
// Insert dummy count
result.push_back("0");
// Insert description
result.push_back(QString::fromStdWString(task.getDescription()));
// Insert deadline
std::wstringstream wss;
if (task.getDeadline() == Task::NEVER) {
wss << L"Never";
} else if (isPastDue(task.getDeadline())) {
wss << L"Overdue (" << task.getDeadline() << L")";
} else if (isDueAfter(task.getDeadline(), 0)) {
wss << L"Today (" << task.getDeadline() << L")";
} else if (isDueAfter(task.getDeadline(), 1)) {
wss << L"Tomorrow (" << task.getDeadline() << L")";
} else if (isDueAfter(task.getDeadline(), 2)) {
wss << L"In two days (" << task.getDeadline() << L")";
} else if (isDueWithin(task.getDeadline(), 7)) {
wss << L"Within one week (" << task.getDeadline() << L")";
} else if (isDueWithin(task.getDeadline(), 14)) {
wss << L"Within two weeks (" << task.getDeadline() << L")";
} else if (isDueWithin(task.getDeadline(), 21)) {
wss << L"Within three weeks (" << task.getDeadline() << L")";
} else if (isDueWithin(task.getDeadline(), 28)) {
wss << L"Within one month (" << task.getDeadline() << L")";
} else {
wss << L"More than a month away (" << task.getDeadline() << L")";
}
result.push_back(boost::lexical_cast<QString>(wss.str()));
// Insert priority
QString priority[] { "High", "Normal" };
switch (task.getPriority()) {
case Task::Priority::HIGH:
result.push_back(priority[0]);
case Task::Priority::NORMAL:
result.push_back(priority[1]);
}
// Insert dependencies
std::ostringstream ss;
if (task.getDependencies().size() != 0) {
Task::Dependencies dependencies = task.getDependencies();
std::copy(dependencies.begin(), --dependencies.end(),
std::ostream_iterator<Task::ID>(ss, ", "));
ss << *--dependencies.end();
result.push_back(QString::fromStdString(ss.str()));
} else {
result.push_back("None");
}
return result;
}
void MainWindow::TaskPanelManager::updateRowNumbers() {
int rowNum = 0;
for (QTreeWidgetItemIterator it(parentGUI->ui.taskTreePanel); *it; ++it) {
(*it)->setData(1, Qt::DisplayRole, rowNum++);
}
}
bool MainWindow::TaskPanelManager::isPastDue(Task::Time deadline) {
Task::Time now = boost::posix_time::second_clock::local_time();
return deadline < now;
}
bool MainWindow::TaskPanelManager::isDueAfter(
Task::Time deadline, int daysLeft) {
Date by = Date(deadline.date());
Date today = boost::gregorian::day_clock::local_day();
return by.modjulian_day() - today.modjulian_day() == daysLeft;
}
bool MainWindow::TaskPanelManager::isDueWithin(
Task::Time deadline, int daysLeft) {
Date by = Date(deadline.date());
Date today = boost::gregorian::day_clock::local_day();
return by.julian_day() - today.julian_day() < daysLeft;
}
void MainWindow::TaskPanelManager::contextMenu(const QPoint &pos) {
/// Try to get the item at the position of the context menu
QTreeWidgetItem *item = parentGUI->ui.taskTreePanel->itemAt(pos);
itemContextMenu.reset(new QMenu(parentGUI->ui.taskTreePanel));
/// Adds the Add Task action. This is always present in the menu.
itemContextMenu->addAction(&addAction);
connect(&addAction, SIGNAL(triggered()), parentGUI, SLOT(contextAddTask()));
/// Adds the Edit Task and Delete Task actions if an item is selected.
/// QSignalMapper is necessary because arguments need to be passed
/// as part of the signal.
if (item) {
deleteSignalMapper.setMapping(&deleteAction, item->text(1).toInt());
connect(&deleteAction, SIGNAL(triggered()),
&deleteSignalMapper, SLOT(map()));
itemContextMenu->addAction(&deleteAction);
connect(&deleteSignalMapper, SIGNAL(mapped(int)),
parentGUI, SLOT(contextDeleteTask(int)));
editSignalMapper.setMapping(&editAction, item->text(1).toInt());
connect(&editAction, SIGNAL(triggered()),
&editSignalMapper, SLOT(map()));
itemContextMenu->addAction(&editAction);
connect(&editSignalMapper, SIGNAL(mapped(int)),
parentGUI, SLOT(contextEditTask(int)));
}
itemContextMenu->popup(
parentGUI->ui.taskTreePanel->viewport()->mapToGlobal(pos));
}
} // namespace GUI
} // namespace You
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "internal/parser.h"
#include "exception.h"
using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;
#pragma region boost::variant visitor helpers
namespace {
struct ToStringVisitor : public boost::static_visitor<std::wstring> {
template<typename T>
std::wstring operator()(const T& value) {
return ToString(value);
}
};
}
namespace boost {
template<typename T1>
std::wstring ToString(const variant<T1>& t) {
ToStringVisitor visitor;
return apply_visitor(visitor, t);
}
}
#pragma endregion
namespace You {
namespace NLP {
namespace Internal {
template <typename Q> static std::wstring ToString(const Q& q) {
return q.toString();
}
}
namespace UnitTests {
using You::NLP::ParserException;
using You::NLP::Internal::Parser;
using You::NLP::Internal::ADD_QUERY;
using You::NLP::Internal::QUERY;
TEST_CLASS(ParserTests) {
public:
TEST_METHOD(throwsExceptionWhenParseFails) {
Assert::ExpectException<ParserException>([]() {
// "throw" is currently not defined, so this should work.
Parser::parse(L"/throw");
}, L"Throws exception on syntax error");
}
TEST_METHOD(parsesStringAsTask) {
QUERY q = Parser::parse(L"win");
Assert::AreEqual(QUERY(ADD_QUERY{
L"win",
std::wstring()
}), q);
}
};
} // namespace UnitTests
} // namespace NLP
} // namespace You
<commit_msg>Forgot to commit the test suite.<commit_after>#include "stdafx.h"
#include "internal/query_parser.h"
#include "exception.h"
using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;
#pragma region boost::variant visitor helpers
namespace {
struct ToStringVisitor : public boost::static_visitor<std::wstring> {
template<typename T>
std::wstring operator()(const T& value) {
return ToString(value);
}
};
}
namespace boost {
template<typename T1>
std::wstring ToString(const variant<T1>& t) {
ToStringVisitor visitor;
return apply_visitor(visitor, t);
}
}
#pragma endregion
namespace You {
namespace NLP {
namespace Internal {
template <typename Q> static std::wstring ToString(const Q& q) {
return q.toString();
}
}
namespace UnitTests {
using You::NLP::ParserException;
using You::NLP::Internal::QueryParser;
using You::NLP::Internal::ADD_QUERY;
using You::NLP::Internal::QUERY;
TEST_CLASS(ParserTests) {
public:
TEST_METHOD(throwsExceptionWhenParseFails) {
Assert::ExpectException<ParserException>([]() {
// "throw" is currently not defined, so this should work.
QueryParser::parse(L"/throw");
}, L"Throws exception on syntax error");
}
TEST_METHOD(parsesStringAsTask) {
QUERY q = QueryParser::parse(L"win");
Assert::AreEqual(QUERY(ADD_QUERY{
L"win",
std::wstring()
}), q);
}
};
} // namespace UnitTests
} // namespace NLP
} // namespace You
<|endoftext|>
|
<commit_before>namespace TAnomalyDetection {
/////////////////////////////////////////////
/// Nearest Neighbor based Annomaly Detection.
void TNearestNeighbor::UpdateDistance(const int& ColId, const int& IgnoreCol) {
// get vector we update distances for and precompute its norm
const TIntFltKdV& ColVec = Mat[ColId];
const double ColNorm = TLinAlg::Norm2(ColVec);
// search for nearest neighbor
int NearId = -1; double NearDist = TFlt::Mx;
for (int ColN = 0; ColN < Mat.Len(); ColN++) {
// skip column itself and columns to ignore
if (ColN == ColId) { continue; }
if (ColN == IgnoreCol) { continue; }
// get distance
const TIntFltKdV& _ColVec = Mat[ColN];
const double Dist = ColNorm - 2 * TLinAlg::DotProduct(ColVec, _ColVec) + TLinAlg::Norm2(_ColVec);
// check if new nearest neighbor for existing vector ColN
if (Dist < DistV[ColN]) { DistV[ColN] = Dist; DistColV[ColN] = ColId; }
// check if new nearest neighbor for new vector ColId
if (Dist < NearDist) { NearId = ColN; NearDist = Dist; }
}
// remember new neighbor
DistV[ColId] = NearDist;
DistColV[ColId] = NearId;
}
void TNearestNeighbor::UpdateThreshold() {
ThresholdV.Gen(RateV.Len(), 0);
// sort distances
TFltV SortedV = DistV; SortedV.Sort(true);
// establish thrashold for each rate
for (const double Rate : RateV) {
// element Id corresponding to Rate-th percentile
const int Elt = floor((1.0 - Rate) * SortedV.Len());
// remember the distance as threshold
ThresholdV.Add(SortedV[Elt]);
}
}
void TNearestNeighbor::Forget(const int& ColId) {
// identify which vectors we should update
TIntV CheckV;
for (int ColN = 0; ColN < Mat.Len(); ColN++) {
// skip self
if (ColN == ColId) { continue; }
// we are the nearest neighbor, need to find a new one
if (DistColV[ColN] == ColId) { CheckV.Add(ColN); }
}
// reasses
for (const int ColN : CheckV) {
// update distance for ColN ignoring vector ColId
UpdateDistance(ColN, ColId);
}
}
TNearestNeighbor::TNearestNeighbor(const double& Rate, const int& _WindowSize):
WindowSize(_WindowSize) {
// remember the rate
RateV.Add(Rate);
// initialize all vectors to window size
Mat.Gen(WindowSize, 0);
DistV.Gen(WindowSize, 0);
DistColV.Gen(WindowSize, 0);
}
TNearestNeighbor::TNearestNeighbor(TSIn& SIn): RateV(SIn), WindowSize(SIn), Mat(SIn),
DistV(SIn), DistColV(SIn), ThresholdV(SIn), InitVecs(SIn), NextCol(SIn) { }
void TNearestNeighbor::Save(TSOut& SOut) {
RateV.Save(SOut);
WindowSize.Save(SOut);
Mat.Save(SOut);
DistV.Save(SOut);
DistColV.Save(SOut);
ThresholdV.Save(SOut);
InitVecs.Save(SOut);
NextCol.Save(SOut);
}
void TNearestNeighbor::PartialFit(const TIntFltKdV& Vec) {
if (InitVecs < WindowSize) {
// not yet full, extend matrix and distance vectors
Mat.Add(Vec);
// make sure we are very far from everything for update distance to kick in
DistV.Add(TFlt::Mx); DistColV.Add(InitVecs);
// update distance for new vector
UpdateDistance(InitVecs);
// move onwards
InitVecs++;
// check if we are initialized
if (InitVecs == WindowSize) { UpdateThreshold(); }
} else {
// we are full, make space first
Forget(NextCol);
// overwrite
Mat[NextCol] = Vec;
DistV[NextCol] = TFlt::Mx;
DistColV[NextCol] = NextCol;
// update distance for overwriten vector
UpdateDistance(NextCol);
// establish new threshold
UpdateThreshold();
// move onwards
NextCol++;
if (NextCol >= WindowSize) { NextCol = 0; }
}
}
double TNearestNeighbor::DecisionFunction(const TIntFltKdV& Vec) const {
double NearDist = TFlt::Mx;
for (const TIntFltKdV& Col : Mat) {
const double Dist = TLinAlg::Norm2(Vec) - 2 * TLinAlg::DotProduct(Vec, Col) + TLinAlg::Norm2(Col);
if (Dist < NearDist) { NearDist = Dist; }
}
return NearDist;
}
int TNearestNeighbor::Predict(const TIntFltKdV& Vec) const {
// if not initialized, do nothing
if (!IsInit()) { return 0; }
// get distance to nearest stored element
const double Dist = DecisionFunction(Vec);
// find in which rate bucket if falls (zero means none)
int Rate = 0;
while (Rate < RateV.Len() && Dist > ThresholdV[Rate]) { Rate++; }
// we are done
return Rate;
}
};<commit_msg>Nearest neighbor checked that rate parameters is between 0 and 1.<commit_after>namespace TAnomalyDetection {
/////////////////////////////////////////////
/// Nearest Neighbor based Annomaly Detection.
void TNearestNeighbor::UpdateDistance(const int& ColId, const int& IgnoreCol) {
// get vector we update distances for and precompute its norm
const TIntFltKdV& ColVec = Mat[ColId];
const double ColNorm = TLinAlg::Norm2(ColVec);
// search for nearest neighbor
int NearId = -1; double NearDist = TFlt::Mx;
for (int ColN = 0; ColN < Mat.Len(); ColN++) {
// skip column itself and columns to ignore
if (ColN == ColId) { continue; }
if (ColN == IgnoreCol) { continue; }
// get distance
const TIntFltKdV& _ColVec = Mat[ColN];
const double Dist = ColNorm - 2 * TLinAlg::DotProduct(ColVec, _ColVec) + TLinAlg::Norm2(_ColVec);
// check if new nearest neighbor for existing vector ColN
if (Dist < DistV[ColN]) { DistV[ColN] = Dist; DistColV[ColN] = ColId; }
// check if new nearest neighbor for new vector ColId
if (Dist < NearDist) { NearId = ColN; NearDist = Dist; }
}
// remember new neighbor
DistV[ColId] = NearDist;
DistColV[ColId] = NearId;
}
void TNearestNeighbor::UpdateThreshold() {
ThresholdV.Gen(RateV.Len(), 0);
// sort distances
TFltV SortedV = DistV; SortedV.Sort(true);
// establish thrashold for each rate
for (const double Rate : RateV) {
// element Id corresponding to Rate-th percentile
const int Elt = floor((1.0 - Rate) * SortedV.Len());
// remember the distance as threshold
ThresholdV.Add(SortedV[Elt]);
}
}
void TNearestNeighbor::Forget(const int& ColId) {
// identify which vectors we should update
TIntV CheckV;
for (int ColN = 0; ColN < Mat.Len(); ColN++) {
// skip self
if (ColN == ColId) { continue; }
// we are the nearest neighbor, need to find a new one
if (DistColV[ColN] == ColId) { CheckV.Add(ColN); }
}
// reasses
for (const int ColN : CheckV) {
// update distance for ColN ignoring vector ColId
UpdateDistance(ColN, ColId);
}
}
TNearestNeighbor::TNearestNeighbor(const double& Rate, const int& _WindowSize):
WindowSize(_WindowSize) {
// assert rate parameter range
EAssertR(0.0 < Rate && Rate < 1.0, "TAnomalyDetection::TNearestNeighbor: Rate parameter not > 0.0 and < 1.0");
// remember the rate
RateV.Add(Rate);
// initialize all vectors to window size
Mat.Gen(WindowSize, 0);
DistV.Gen(WindowSize, 0);
DistColV.Gen(WindowSize, 0);
}
TNearestNeighbor::TNearestNeighbor(TSIn& SIn): RateV(SIn), WindowSize(SIn), Mat(SIn),
DistV(SIn), DistColV(SIn), ThresholdV(SIn), InitVecs(SIn), NextCol(SIn) { }
void TNearestNeighbor::Save(TSOut& SOut) {
RateV.Save(SOut);
WindowSize.Save(SOut);
Mat.Save(SOut);
DistV.Save(SOut);
DistColV.Save(SOut);
ThresholdV.Save(SOut);
InitVecs.Save(SOut);
NextCol.Save(SOut);
}
void TNearestNeighbor::PartialFit(const TIntFltKdV& Vec) {
if (InitVecs < WindowSize) {
// not yet full, extend matrix and distance vectors
Mat.Add(Vec);
// make sure we are very far from everything for update distance to kick in
DistV.Add(TFlt::Mx); DistColV.Add(InitVecs);
// update distance for new vector
UpdateDistance(InitVecs);
// move onwards
InitVecs++;
// check if we are initialized
if (InitVecs == WindowSize) { UpdateThreshold(); }
} else {
// we are full, make space first
Forget(NextCol);
// overwrite
Mat[NextCol] = Vec;
DistV[NextCol] = TFlt::Mx;
DistColV[NextCol] = NextCol;
// update distance for overwriten vector
UpdateDistance(NextCol);
// establish new threshold
UpdateThreshold();
// move onwards
NextCol++;
if (NextCol >= WindowSize) { NextCol = 0; }
}
}
double TNearestNeighbor::DecisionFunction(const TIntFltKdV& Vec) const {
double NearDist = TFlt::Mx;
for (const TIntFltKdV& Col : Mat) {
const double Dist = TLinAlg::Norm2(Vec) - 2 * TLinAlg::DotProduct(Vec, Col) + TLinAlg::Norm2(Col);
if (Dist < NearDist) { NearDist = Dist; }
}
return NearDist;
}
int TNearestNeighbor::Predict(const TIntFltKdV& Vec) const {
// if not initialized, do nothing
if (!IsInit()) { return 0; }
// get distance to nearest stored element
const double Dist = DecisionFunction(Vec);
// find in which rate bucket if falls (zero means none)
int Rate = 0;
while (Rate < RateV.Len() && Dist > ThresholdV[Rate]) { Rate++; }
// we are done
return Rate;
}
};<|endoftext|>
|
<commit_before> /**
* global_odom_to_tf.cpp
* Broadcast transform between local_origin and fcu.
*
* @author Syler Wagner <syler@mit.edu>
* @date 2016-07-01 syler creation
*
* This node listens for odometry messages on the /mavros/global_position/local topic
* and broadcasts a transform between local_origin and fcu.
**/
#include "ros/ros.h"
#include "nav_msgs/Odometry.h"
#include "tf/transform_broadcaster.h"
//$ TODO: use mavros.get_namespace() instead of hardcoding
tf::TransformBroadcaster odom_broadcaster;
void odometryCallback(const nav_msgs::Odometry::ConstPtr& odom) {
geometry_msgs::TransformStamped odom_trans;
odom_trans.header.stamp = ros::Time::now();
odom_trans.header.frame_id = "local_origin";
odom_trans.child_frame_id = "fcu";
odom_trans.transform.translation.x = odom->pose.pose.position.x;
odom_trans.transform.translation.y = odom->pose.pose.position.y;
odom_trans.transform.translation.z = odom->pose.pose.position.z;
odom_trans.transform.rotation = odom->pose.pose.orientation;
odom_broadcaster.sendTransform(odom_trans);
}
int main(int argc, char** argv) {
ros::init(argc, argv, "odometry_publisher");
ros::NodeHandle n;
ros::Subscriber odom_sub = n.subscribe("/mavros/global_position/local", 1000, odometryCallback);
ros::Rate r(1000.0);
while (n.ok()) {
ros::spin();
}
}
<commit_msg>Fixed global_odom_to_tf.cpp broadcasting runtime error<commit_after> /**
* global_odom_to_tf.cpp
* Broadcast transform between local_origin and fcu.
*
* @author Syler Wagner <syler@mit.edu>
* @date 2016-07-01 syler creation
*
* This node listens for odometry messages on the /mavros/global_position/local topic
* and broadcasts a transform between local_origin and fcu.
**/
#include "ros/ros.h"
#include "nav_msgs/Odometry.h"
#include "tf/transform_broadcaster.h"
//$ TODO: use mavros.get_namespace() instead of hardcoding
geometry_msgs::TransformStamped odom_trans;
void odometryCallback(const nav_msgs::Odometry::ConstPtr& odom) {
odom_trans.header.stamp = ros::Time::now();
odom_trans.header.frame_id = "local_origin";
odom_trans.child_frame_id = "fcu";
odom_trans.transform.translation.x = odom->pose.pose.position.x;
odom_trans.transform.translation.y = odom->pose.pose.position.y;
odom_trans.transform.translation.z = odom->pose.pose.position.z;
odom_trans.transform.rotation = odom->pose.pose.orientation;
}
int main(int argc, char** argv) {
ros::init(argc, argv, "global_odom_to_tf");
ros::NodeHandle n;
tf::TransformBroadcaster odom_broadcaster;
ros::Subscriber odom_sub = n.subscribe("/mavros/global_position/local", 1000, odometryCallback);
ros::Rate r(1000.0);
while (n.ok()) {
ros::spinOnce();
odom_broadcaster.sendTransform(odom_trans);
r.sleep();
}
}
<|endoftext|>
|
<commit_before>/*
* SPDX-FileCopyrightText: 2017-2017 CSSlayer <wengxt@gmail.com>
*
* SPDX-License-Identifier: LGPL-2.1-or-later
*
*/
#include "ime.h"
#include "config.h"
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream_buffer.hpp>
#include <boost/range/adaptor/reversed.hpp>
#include <fcitx-config/iniparser.h>
#include <fcitx-utils/log.h>
#include <fcitx-utils/standardpath.h>
#include <fcntl.h>
#include <libime/core/utils.h>
#include <libime/table/tablebaseddictionary.h>
#include <libime/table/tableoptions.h>
namespace fcitx {
FCITX_DEFINE_LOG_CATEGORY(table_logcategory, "table")
namespace {
libime::OrderPolicy converOrderPolicy(fcitx::OrderPolicy policy) {
switch (policy) {
#define POLICY_CONVERT(NAME) \
case fcitx::OrderPolicy::NAME: \
return libime::OrderPolicy::NAME;
POLICY_CONVERT(No)
POLICY_CONVERT(Freq)
POLICY_CONVERT(Fast)
}
return libime::OrderPolicy::Freq;
}
void populateOptions(libime::TableBasedDictionary *dict,
const TableConfigRoot &root) {
libime::TableOptions options;
options.setOrderPolicy(converOrderPolicy(*root.config->orderPolicy));
options.setNoSortInputLength(*root.config->noSortInputLength);
options.setAutoSelect(*root.config->autoSelect);
options.setAutoSelectLength(*root.config->autoSelectLength);
options.setNoMatchAutoSelectLength(*root.config->noMatchAutoSelectLength);
options.setCommitRawInput(*root.config->commitRawInput);
options.setMatchingKey(
Key::keySymToUnicode(root.config->matchingKey->sym()));
std::set<uint32_t> endKeys;
TABLE_DEBUG() << "End key" << *root.config->endKey;
for (const auto &key : *root.config->endKey) {
auto chr = Key::keySymToUnicode(key.sym());
if (chr) {
endKeys.insert(chr);
}
}
options.setEndKey(endKeys);
options.setExactMatch(*root.config->exactMatch);
options.setLearning(*root.config->learning);
options.setAutoPhraseLength(*root.config->autoPhraseLength);
options.setSaveAutoPhraseAfter(*root.config->saveAutoPhraseAfter);
options.setAutoRuleSet(std::unordered_set<std::string>(
root.config->autoRuleSet->begin(), root.config->autoRuleSet->end()));
options.setLanguageCode(*root.im->languageCode);
dict->setTableOptions(options);
}
} // namespace
TableIME::TableIME(libime::LanguageModelResolver *lm) : lm_(lm) {}
std::tuple<libime::TableBasedDictionary *, libime::UserLanguageModel *,
const TableConfig *>
TableIME::requestDict(const std::string &name) {
auto iter = tables_.find(name);
if (iter == tables_.end()) {
TABLE_DEBUG() << "Load table config for: " << name;
std::string filename = "inputmethod/";
filename.append(name.begin(), name.end());
filename += ".conf";
auto files = StandardPath::global().openAll(StandardPath::Type::PkgData,
filename, O_RDONLY);
RawConfig rawConfig;
// reverse the order, so we end up parse user file at last.
for (const auto &file : files | boost::adaptors::reversed) {
readFromIni(rawConfig, file.fd());
}
iter = tables_
.emplace(std::piecewise_construct, std::make_tuple(name),
std::make_tuple())
.first;
auto &root = iter->second.root;
root.load(rawConfig);
try {
auto dict = std::make_unique<libime::TableBasedDictionary>();
auto dictFile = StandardPath::global().open(
StandardPath::Type::PkgData, *root.config->file, O_RDONLY);
TABLE_DEBUG() << "Load table at: " << *root.config->file;
if (dictFile.fd() < 0) {
throw std::runtime_error("Couldn't open file");
}
boost::iostreams::stream_buffer<
boost::iostreams::file_descriptor_source>
buffer(dictFile.fd(), boost::iostreams::file_descriptor_flags::
never_close_handle);
std::istream in(&buffer);
dict->load(in);
iter->second.dict = std::move(dict);
} catch (const std::exception &) {
}
if (auto dict = iter->second.dict.get()) {
try {
auto dictFile = StandardPath::global().openUser(
StandardPath::Type::PkgData,
stringutils::concat("table/", name, ".user.dict"),
O_RDONLY);
boost::iostreams::stream_buffer<
boost::iostreams::file_descriptor_source>
buffer(dictFile.fd(),
boost::iostreams::file_descriptor_flags::
never_close_handle);
std::istream in(&buffer);
dict->loadUser(in);
} catch (const std::exception &e) {
TABLE_DEBUG() << e.what();
}
populateOptions(dict, iter->second.root);
std::shared_ptr<const libime::StaticLanguageModelFile> lmFile;
try {
lmFile = lm_->languageModelFileForLanguage(
dict->tableOptions().languageCode());
} catch (...) {
TABLE_DEBUG()
<< "Load language model for "
<< dict->tableOptions().languageCode() << " failed.";
}
iter->second.model =
std::make_unique<libime::UserLanguageModel>(lmFile);
try {
auto dictFile = StandardPath::global().openUser(
StandardPath::Type::PkgData,
stringutils::concat("table/", name, ".history"), O_RDONLY);
boost::iostreams::stream_buffer<
boost::iostreams::file_descriptor_source>
buffer(dictFile.fd(),
boost::iostreams::file_descriptor_flags::
never_close_handle);
std::istream in(&buffer);
iter->second.model->load(in);
} catch (const std::exception &e) {
TABLE_DEBUG() << e.what();
}
}
}
return {iter->second.dict.get(), iter->second.model.get(),
&(*iter->second.root.config)};
}
void TableIME::saveAll() {
for (const auto &p : tables_) {
saveDict(p.first);
}
}
void TableIME::updateConfig(const std::string &name, const RawConfig &config) {
auto iter = tables_.find(name);
if (iter == tables_.end()) {
return;
}
iter->second.root.config.mutableValue()->load(config, true);
if (iter->second.dict) {
populateOptions(iter->second.dict.get(), iter->second.root);
}
safeSaveAsIni(iter->second.root,
stringutils::concat("inputmethod/", name, ".conf"));
}
void TableIME::releaseUnusedDict(const std::unordered_set<std::string> &names) {
for (auto iter = tables_.begin(); iter != tables_.end();) {
if (names.count(iter->first) == 0) {
TABLE_DEBUG() << "Release unused table: " << iter->first;
saveDict(iter->first);
iter = tables_.erase(iter);
} else {
++iter;
}
}
}
void TableIME::saveDict(const std::string &name) {
auto iter = tables_.find(name);
if (iter == tables_.end()) {
return;
}
libime::TableBasedDictionary *dict = iter->second.dict.get();
libime::UserLanguageModel *lm = iter->second.model.get();
if (!dict || !lm || !*iter->second.root.config->learning) {
return;
}
auto fileName = stringutils::joinPath("table", name);
StandardPath::global().safeSave(
StandardPath::Type::PkgData, fileName + ".user.dict", [dict](int fd) {
boost::iostreams::stream_buffer<
boost::iostreams::file_descriptor_sink>
buffer(fd, boost::iostreams::file_descriptor_flags::
never_close_handle);
std::ostream out(&buffer);
try {
dict->saveUser(out);
return static_cast<bool>(out);
} catch (const std::exception &) {
return false;
}
});
StandardPath::global().safeSave(
StandardPath::Type::PkgData, fileName + ".history", [lm](int fd) {
boost::iostreams::stream_buffer<
boost::iostreams::file_descriptor_sink>
buffer(fd, boost::iostreams::file_descriptor_flags::
never_close_handle);
std::ostream out(&buffer);
try {
lm->save(out);
return static_cast<bool>(out);
} catch (const std::exception &) {
return false;
}
});
}
} // namespace fcitx
<commit_msg>Table input specific config should write to pkgdata.<commit_after>/*
* SPDX-FileCopyrightText: 2017-2017 CSSlayer <wengxt@gmail.com>
*
* SPDX-License-Identifier: LGPL-2.1-or-later
*
*/
#include "ime.h"
#include "config.h"
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream_buffer.hpp>
#include <boost/range/adaptor/reversed.hpp>
#include <fcitx-config/iniparser.h>
#include <fcitx-utils/log.h>
#include <fcitx-utils/standardpath.h>
#include <fcntl.h>
#include <libime/core/utils.h>
#include <libime/table/tablebaseddictionary.h>
#include <libime/table/tableoptions.h>
namespace fcitx {
FCITX_DEFINE_LOG_CATEGORY(table_logcategory, "table")
namespace {
libime::OrderPolicy converOrderPolicy(fcitx::OrderPolicy policy) {
switch (policy) {
#define POLICY_CONVERT(NAME) \
case fcitx::OrderPolicy::NAME: \
return libime::OrderPolicy::NAME;
POLICY_CONVERT(No)
POLICY_CONVERT(Freq)
POLICY_CONVERT(Fast)
}
return libime::OrderPolicy::Freq;
}
void populateOptions(libime::TableBasedDictionary *dict,
const TableConfigRoot &root) {
libime::TableOptions options;
options.setOrderPolicy(converOrderPolicy(*root.config->orderPolicy));
options.setNoSortInputLength(*root.config->noSortInputLength);
options.setAutoSelect(*root.config->autoSelect);
options.setAutoSelectLength(*root.config->autoSelectLength);
options.setNoMatchAutoSelectLength(*root.config->noMatchAutoSelectLength);
options.setCommitRawInput(*root.config->commitRawInput);
options.setMatchingKey(
Key::keySymToUnicode(root.config->matchingKey->sym()));
std::set<uint32_t> endKeys;
TABLE_DEBUG() << "End key" << *root.config->endKey;
for (const auto &key : *root.config->endKey) {
auto chr = Key::keySymToUnicode(key.sym());
if (chr) {
endKeys.insert(chr);
}
}
options.setEndKey(endKeys);
options.setExactMatch(*root.config->exactMatch);
options.setLearning(*root.config->learning);
options.setAutoPhraseLength(*root.config->autoPhraseLength);
options.setSaveAutoPhraseAfter(*root.config->saveAutoPhraseAfter);
options.setAutoRuleSet(std::unordered_set<std::string>(
root.config->autoRuleSet->begin(), root.config->autoRuleSet->end()));
options.setLanguageCode(*root.im->languageCode);
dict->setTableOptions(options);
}
} // namespace
TableIME::TableIME(libime::LanguageModelResolver *lm) : lm_(lm) {}
std::tuple<libime::TableBasedDictionary *, libime::UserLanguageModel *,
const TableConfig *>
TableIME::requestDict(const std::string &name) {
auto iter = tables_.find(name);
if (iter == tables_.end()) {
TABLE_DEBUG() << "Load table config for: " << name;
std::string filename = "inputmethod/";
filename.append(name.begin(), name.end());
filename += ".conf";
auto files = StandardPath::global().openAll(StandardPath::Type::PkgData,
filename, O_RDONLY);
RawConfig rawConfig;
// reverse the order, so we end up parse user file at last.
for (const auto &file : files | boost::adaptors::reversed) {
readFromIni(rawConfig, file.fd());
}
iter = tables_
.emplace(std::piecewise_construct, std::make_tuple(name),
std::make_tuple())
.first;
auto &root = iter->second.root;
root.load(rawConfig);
try {
auto dict = std::make_unique<libime::TableBasedDictionary>();
auto dictFile = StandardPath::global().open(
StandardPath::Type::PkgData, *root.config->file, O_RDONLY);
TABLE_DEBUG() << "Load table at: " << *root.config->file;
if (dictFile.fd() < 0) {
throw std::runtime_error("Couldn't open file");
}
boost::iostreams::stream_buffer<
boost::iostreams::file_descriptor_source>
buffer(dictFile.fd(), boost::iostreams::file_descriptor_flags::
never_close_handle);
std::istream in(&buffer);
dict->load(in);
iter->second.dict = std::move(dict);
} catch (const std::exception &) {
}
if (auto dict = iter->second.dict.get()) {
try {
auto dictFile = StandardPath::global().openUser(
StandardPath::Type::PkgData,
stringutils::concat("table/", name, ".user.dict"),
O_RDONLY);
boost::iostreams::stream_buffer<
boost::iostreams::file_descriptor_source>
buffer(dictFile.fd(),
boost::iostreams::file_descriptor_flags::
never_close_handle);
std::istream in(&buffer);
dict->loadUser(in);
} catch (const std::exception &e) {
TABLE_DEBUG() << e.what();
}
populateOptions(dict, iter->second.root);
std::shared_ptr<const libime::StaticLanguageModelFile> lmFile;
try {
lmFile = lm_->languageModelFileForLanguage(
dict->tableOptions().languageCode());
} catch (...) {
TABLE_DEBUG()
<< "Load language model for "
<< dict->tableOptions().languageCode() << " failed.";
}
iter->second.model =
std::make_unique<libime::UserLanguageModel>(lmFile);
try {
auto dictFile = StandardPath::global().openUser(
StandardPath::Type::PkgData,
stringutils::concat("table/", name, ".history"), O_RDONLY);
boost::iostreams::stream_buffer<
boost::iostreams::file_descriptor_source>
buffer(dictFile.fd(),
boost::iostreams::file_descriptor_flags::
never_close_handle);
std::istream in(&buffer);
iter->second.model->load(in);
} catch (const std::exception &e) {
TABLE_DEBUG() << e.what();
}
}
}
return {iter->second.dict.get(), iter->second.model.get(),
&(*iter->second.root.config)};
}
void TableIME::saveAll() {
for (const auto &p : tables_) {
saveDict(p.first);
}
}
void TableIME::updateConfig(const std::string &name, const RawConfig &config) {
auto iter = tables_.find(name);
if (iter == tables_.end()) {
return;
}
iter->second.root.config.mutableValue()->load(config, true);
if (iter->second.dict) {
populateOptions(iter->second.dict.get(), iter->second.root);
}
safeSaveAsIni(iter->second.root, StandardPath::Type::PkgData,
stringutils::concat("inputmethod/", name, ".conf"));
}
void TableIME::releaseUnusedDict(const std::unordered_set<std::string> &names) {
for (auto iter = tables_.begin(); iter != tables_.end();) {
if (names.count(iter->first) == 0) {
TABLE_DEBUG() << "Release unused table: " << iter->first;
saveDict(iter->first);
iter = tables_.erase(iter);
} else {
++iter;
}
}
}
void TableIME::saveDict(const std::string &name) {
auto iter = tables_.find(name);
if (iter == tables_.end()) {
return;
}
libime::TableBasedDictionary *dict = iter->second.dict.get();
libime::UserLanguageModel *lm = iter->second.model.get();
if (!dict || !lm || !*iter->second.root.config->learning) {
return;
}
auto fileName = stringutils::joinPath("table", name);
StandardPath::global().safeSave(
StandardPath::Type::PkgData, fileName + ".user.dict", [dict](int fd) {
boost::iostreams::stream_buffer<
boost::iostreams::file_descriptor_sink>
buffer(fd, boost::iostreams::file_descriptor_flags::
never_close_handle);
std::ostream out(&buffer);
try {
dict->saveUser(out);
return static_cast<bool>(out);
} catch (const std::exception &) {
return false;
}
});
StandardPath::global().safeSave(
StandardPath::Type::PkgData, fileName + ".history", [lm](int fd) {
boost::iostreams::stream_buffer<
boost::iostreams::file_descriptor_sink>
buffer(fd, boost::iostreams::file_descriptor_flags::
never_close_handle);
std::ostream out(&buffer);
try {
lm->save(out);
return static_cast<bool>(out);
} catch (const std::exception &) {
return false;
}
});
}
} // namespace fcitx
<|endoftext|>
|
<commit_before>#include "SliceRenderer.h"
#include "GLBlaat/GL.h"
#include "GLBlaat/GLFramebuffer.h"
#include "GLBlaat/GLTextureManager.h"
#include "View.h"
#include "Renderables/Renderable.h"
#include "Renderables/VBOMesh.h"
namespace NQVTK
{
// ------------------------------------------------------------------------
SliceRenderer::SliceRenderer()
: shader(0)
{
}
// ------------------------------------------------------------------------
SliceRenderer::~SliceRenderer()
{
}
// ------------------------------------------------------------------------
void SliceRenderer::PrepareForRenderable(int objectId,
Renderable *renderable)
{
if (shader)
{
if (shaderAttribs.size() > 0)
{
NQVTK::VBOMesh *mesh = dynamic_cast<NQVTK::VBOMesh*>(renderable);
if (mesh) mesh->SetupAttributes(shaderAttribs);
}
renderable->ApplyParamSets(shader, tm);
}
}
// ------------------------------------------------------------------------
void SliceRenderer::Draw()
{
// Prepare for rendering
if (fboTarget)
{
fboTarget->Bind();
}
glViewport(viewportX, viewportY, viewportWidth, viewportHeight);
// TODO: per-object textures are not initialized before SetupProgram
// This doesn't matter in layered rendering because the scribe doesn't
// use them, but will add them to the tm. However, here we don't have
// such an extra pass...
if (shader) shader->Start();
for (unsigned int objectId = 0;
objectId < view->GetNumberOfRenderables();
++objectId)
{
Renderable *renderable = view->GetRenderable(objectId);
PrepareForRenderable(objectId, renderable);
}
if (shader) shader->Stop();
glPushAttrib(GL_ALL_ATTRIB_BITS);
glDisable(GL_LIGHTING);
// Use alpha blending for now (with premultiplied alpha)
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
Clear();
if (view)
{
if (shader)
{
shader->Start();
tm->SetupProgram(shader);
tm->Bind();
}
// Draw a single slice for each renderable
for (unsigned int objectId = 0;
objectId < view->GetNumberOfRenderables();
++objectId)
{
// The shader should discard renderables without volumes and
// generate appropriate alpha values or discards for blending
// Visibility implies that the renderable is not null
if (view->GetVisibility(objectId))
{
Renderable *renderable = view->GetRenderable(objectId);
PrepareForRenderable(objectId, renderable);
glColor4d(
renderable->color.x,
renderable->color.y,
renderable->color.z,
renderable->opacity);
// Draw the full screen quad for our slice plane
glBegin(GL_QUADS);
glTexCoord3dv(origin.V);
glVertex3d(-1.0, -1.0, 0.0);
glTexCoord3dv((origin + right).V);
glVertex3d(1.0, -1.0, 0.0);
glTexCoord3dv((origin + right + up).V);
glVertex3d(1.0, 1.0, 0.0);
glTexCoord3dv((origin + up).V);
glVertex3d(-1.0, 1.0, 0.0);
glEnd();
}
}
if (shader)
{
tm->Unbind();
shader->Stop();
}
}
glPopAttrib();
if (fboTarget)
{
fboTarget->Unbind();
}
}
// ------------------------------------------------------------------------
void SliceRenderer::SetPlane(const Vector3 &origin,
const Vector3 &right, const Vector3 &up)
{
this->origin = origin;
this->right = right;
this->up = up;
}
// ------------------------------------------------------------------------
GLProgram *SliceRenderer::SetShader(GLProgram *shader)
{
GLProgram *oldshader = this->shader;
this->shader = shader;
shaderAttribs.clear();
if (shader) shaderAttribs = shader->GetActiveAttributes();
if (shader == oldshader) return 0;
return oldshader;
}
// ------------------------------------------------------------------------
bool SliceRenderer::CreateDefaultShader()
{
GLProgram *shader = GLProgram::New();
if (!shader) return false;
bool ok = true;
if (ok) ok = shader->AddVertexShader(
"void main() {"
" gl_TexCoord[0] = gl_MultiTexCoord0;"
" gl_Position = gl_Vertex;"
"}");
// TODO: we need the actual object transform here
if (ok) ok = shader->AddFragmentShader(
"uniform sampler3D volume;"
"uniform vec3 volumeOrigin;"
"uniform vec3 volumeSize;"
"uniform float volumeDataShift;"
"uniform float volumeDataScale;"
"void main() {"
" vec3 tc = (gl_TexCoord[0].xyz - volumeOrigin) / volumeSize;"
" vec3 tex = vec3(volumeDataShift) + volumeDataScale * "
" texture3D(volume, tc).xyz;"
" gl_FragColor = vec4(abs(tex), 1.0);"
"}");
if (ok) ok = shader->Link();
if (ok) SetShader(shader);
if (!ok) delete shader;
return ok;
}
}
<commit_msg>Fixed blending.<commit_after>#include "SliceRenderer.h"
#include "GLBlaat/GL.h"
#include "GLBlaat/GLFramebuffer.h"
#include "GLBlaat/GLTextureManager.h"
#include "View.h"
#include "Renderables/Renderable.h"
#include "Renderables/VBOMesh.h"
namespace NQVTK
{
// ------------------------------------------------------------------------
SliceRenderer::SliceRenderer()
: shader(0)
{
}
// ------------------------------------------------------------------------
SliceRenderer::~SliceRenderer()
{
}
// ------------------------------------------------------------------------
void SliceRenderer::PrepareForRenderable(int objectId,
Renderable *renderable)
{
if (shader)
{
shader->SetUniform1i("objectId", objectId);
if (shaderAttribs.size() > 0)
{
NQVTK::VBOMesh *mesh = dynamic_cast<NQVTK::VBOMesh*>(renderable);
if (mesh) mesh->SetupAttributes(shaderAttribs);
}
renderable->ApplyParamSets(shader, tm);
}
}
// ------------------------------------------------------------------------
void SliceRenderer::Draw()
{
// Prepare for rendering
if (fboTarget)
{
fboTarget->Bind();
}
glViewport(viewportX, viewportY, viewportWidth, viewportHeight);
// TODO: per-object textures are not initialized before SetupProgram
// This doesn't matter in layered rendering because the scribe doesn't
// use them, but will add them to the tm. However, here we don't have
// such an extra pass...
if (shader) shader->Start();
for (unsigned int objectId = 0;
objectId < view->GetNumberOfRenderables();
++objectId)
{
Renderable *renderable = view->GetRenderable(objectId);
PrepareForRenderable(objectId, renderable);
}
if (shader) shader->Stop();
glPushAttrib(GL_ALL_ATTRIB_BITS);
glDisable(GL_LIGHTING);
glDepthMask(GL_FALSE);
// Use alpha blending for now (with premultiplied alpha)
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
Clear();
if (view)
{
if (shader)
{
shader->Start();
tm->SetupProgram(shader);
tm->Bind();
}
// Draw a single slice for each renderable
for (unsigned int objectId = 0;
objectId < view->GetNumberOfRenderables();
++objectId)
{
// The shader should discard renderables without volumes and
// generate appropriate alpha values or discards for blending
// Visibility implies that the renderable is not null
if (view->GetVisibility(objectId))
{
Renderable *renderable = view->GetRenderable(objectId);
PrepareForRenderable(objectId, renderable);
glColor4d(
renderable->color.x,
renderable->color.y,
renderable->color.z,
renderable->opacity);
// Draw the full screen quad for our slice plane
glBegin(GL_QUADS);
glTexCoord3dv(origin.V);
glVertex3d(-1.0, -1.0, 0.0);
glTexCoord3dv((origin + right).V);
glVertex3d(1.0, -1.0, 0.0);
glTexCoord3dv((origin + right + up).V);
glVertex3d(1.0, 1.0, 0.0);
glTexCoord3dv((origin + up).V);
glVertex3d(-1.0, 1.0, 0.0);
glEnd();
}
}
if (shader)
{
tm->Unbind();
shader->Stop();
}
}
glPopAttrib();
if (fboTarget)
{
fboTarget->Unbind();
}
}
// ------------------------------------------------------------------------
void SliceRenderer::SetPlane(const Vector3 &origin,
const Vector3 &right, const Vector3 &up)
{
this->origin = origin;
this->right = right;
this->up = up;
}
// ------------------------------------------------------------------------
GLProgram *SliceRenderer::SetShader(GLProgram *shader)
{
GLProgram *oldshader = this->shader;
this->shader = shader;
shaderAttribs.clear();
if (shader) shaderAttribs = shader->GetActiveAttributes();
if (shader == oldshader) return 0;
return oldshader;
}
// ------------------------------------------------------------------------
bool SliceRenderer::CreateDefaultShader()
{
GLProgram *shader = GLProgram::New();
if (!shader) return false;
bool ok = true;
if (ok) ok = shader->AddVertexShader(
"void main() {"
" gl_TexCoord[0] = gl_MultiTexCoord0;"
" gl_Position = gl_Vertex;"
"}");
// TODO: we need the actual object transform here
if (ok) ok = shader->AddFragmentShader(
"uniform sampler3D volume;"
"uniform vec3 volumeOrigin;"
"uniform vec3 volumeSize;"
"uniform float volumeDataShift;"
"uniform float volumeDataScale;"
"uniform int objectId;"
"void main() {"
" vec3 tc = (gl_TexCoord[0].xyz - volumeOrigin) / volumeSize;"
" if (objectId == 1) tc.z = 1.0-tc.z;"
" vec3 tex = vec3(volumeDataShift) + volumeDataScale * "
" texture3D(volume, tc).xyz;"
" vec4 color = vec4(abs(tex), length(tex));"
" gl_FragColor = vec4(color.rgb * color.a, color.a);"
"}");
if (ok) ok = shader->Link();
if (ok) SetShader(shader);
if (!ok) delete shader;
return ok;
}
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageStack.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkImageStack.h"
#include "vtkImageSliceCollection.h"
#include "vtkImageProperty.h"
#include "vtkImageMapper3D.h"
#include "vtkMatrix4x4.h"
#include "vtkAssemblyPath.h"
#include "vtkAssemblyPaths.h"
#include "vtkObjectFactory.h"
vtkStandardNewMacro(vtkImageStack);
//----------------------------------------------------------------------------
vtkImageStack::vtkImageStack()
{
this->Images = vtkImageSliceCollection::New();
this->ImageMatrices = NULL;
this->ActiveLayer = 0;
}
//----------------------------------------------------------------------------
vtkImageStack::~vtkImageStack()
{
if (this->Images)
{
vtkCollectionSimpleIterator pit;
this->Images->InitTraversal(pit);
vtkImageSlice *image = 0;
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
image->RemoveConsumer(this);
}
this->Images->Delete();
}
if (this->ImageMatrices)
{
this->ImageMatrices->Delete();
}
}
//----------------------------------------------------------------------------
vtkImageSlice *vtkImageStack::GetActiveImage()
{
vtkImageSlice *activeImage = 0;
vtkCollectionSimpleIterator pit;
this->Images->InitTraversal(pit);
vtkImageSlice *image = 0;
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
vtkImageProperty *p = image->GetProperty();
if (p->GetLayerNumber() == this->ActiveLayer)
{
activeImage = image;
}
}
return activeImage;
}
//----------------------------------------------------------------------------
void vtkImageStack::AddImage(vtkImageSlice *prop)
{
if (!this->Images->IsItemPresent(prop) &&
!vtkImageStack::SafeDownCast(prop))
{
this->Images->AddItem(prop);
prop->AddConsumer(this);
}
}
//----------------------------------------------------------------------------
void vtkImageStack::RemoveImage(vtkImageSlice *prop)
{
if (this->Images->IsItemPresent(prop))
{
prop->RemoveConsumer(this);
this->Images->RemoveItem(prop);
}
}
//----------------------------------------------------------------------------
int vtkImageStack::HasImage(vtkImageSlice *prop)
{
return this->Images->IsItemPresent(prop);
}
//----------------------------------------------------------------------------
void vtkImageStack::GetImages(vtkPropCollection *vc)
{
vtkCollectionSimpleIterator pit;
this->Images->InitTraversal(pit);
vtkImageSlice *image = 0;
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
image->GetImages(vc);
}
}
//----------------------------------------------------------------------------
void vtkImageStack::ShallowCopy(vtkProp *prop)
{
vtkImageStack *v = vtkImageStack::SafeDownCast(prop);
if (v != NULL)
{
this->Images->RemoveAllItems();
vtkCollectionSimpleIterator pit;
v->Images->InitTraversal(pit);
vtkImageSlice *image = 0;
while ( (image = v->Images->GetNextImage(pit)) != 0)
{
this->Images->AddItem(image);
}
this->SetActiveLayer(v->GetActiveLayer());
}
// Now do prop superclass (NOT vtkImageSlice)
this->vtkProp3D::ShallowCopy(prop);
}
//----------------------------------------------------------------------------
void vtkImageStack::SetProperty(vtkImageProperty *)
{
// do nothing
}
//----------------------------------------------------------------------------
vtkImageProperty *vtkImageStack::GetProperty()
{
// Get the property with the active layer number
vtkImageSlice *image = this->GetActiveImage();
if (image)
{
return image->GetProperty();
}
// Return a dummy property, can't return NULL.
if (this->Property == 0)
{
this->Property = vtkImageProperty::New();
this->Property->Register(this);
this->Property->Delete();
}
return this->Property;
}
//----------------------------------------------------------------------------
void vtkImageStack::SetMapper(vtkImageMapper3D *)
{
// do nothing
}
//----------------------------------------------------------------------------
vtkImageMapper3D *vtkImageStack::GetMapper()
{
// Get the mapper with the active layer number
vtkImageSlice *image = this->GetActiveImage();
if (image)
{
return image->GetMapper();
}
return NULL;
}
//----------------------------------------------------------------------------
double *vtkImageStack::GetBounds()
{
this->UpdatePaths();
double bounds[6];
bool nobounds = true;
bounds[0] = VTK_DOUBLE_MAX;
bounds[1] = VTK_DOUBLE_MIN;
bounds[2] = VTK_DOUBLE_MAX;
bounds[3] = VTK_DOUBLE_MIN;
bounds[4] = VTK_DOUBLE_MAX;
bounds[5] = VTK_DOUBLE_MIN;
if (!this->IsIdentity)
{
this->PokeMatrices(this->GetMatrix());
}
vtkCollectionSimpleIterator pit;
this->Images->InitTraversal(pit);
vtkImageSlice *image = 0;
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
double *b = image->GetBounds();
if (b)
{
nobounds = false;
bounds[0] = (bounds[0] < b[0] ? bounds[0] : b[0]);
bounds[1] = (bounds[1] > b[1] ? bounds[1] : b[1]);
bounds[2] = (bounds[2] < b[2] ? bounds[2] : b[2]);
bounds[3] = (bounds[3] > b[3] ? bounds[3] : b[3]);
bounds[4] = (bounds[4] < b[4] ? bounds[4] : b[4]);
bounds[5] = (bounds[5] > b[5] ? bounds[5] : b[5]);
}
}
if (!this->IsIdentity)
{
this->PokeMatrices(NULL);
}
if (nobounds)
{
return 0;
}
this->Bounds[0] = bounds[0];
this->Bounds[1] = bounds[1];
this->Bounds[2] = bounds[2];
this->Bounds[3] = bounds[3];
this->Bounds[4] = bounds[4];
this->Bounds[5] = bounds[5];
return this->Bounds;
}
//----------------------------------------------------------------------------
// Does this prop have some translucent polygonal geometry?
int vtkImageStack::HasTranslucentPolygonalGeometry()
{
vtkCollectionSimpleIterator pit;
this->Images->InitTraversal(pit);
vtkImageSlice *image = 0;
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
if (image->HasTranslucentPolygonalGeometry())
{
return 1;
}
}
return 0;
}
//----------------------------------------------------------------------------
// Assembly-like behavior
void vtkImageStack::PokeMatrices(vtkMatrix4x4 *matrix)
{
if (this->ImageMatrices == NULL)
{
this->ImageMatrices = vtkCollection::New();
}
if (matrix)
{
vtkCollectionSimpleIterator pit;
this->Images->InitTraversal(pit);
vtkImageSlice *image = 0;
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
vtkMatrix4x4 *propMatrix = vtkMatrix4x4::New();
propMatrix->Multiply4x4(image->GetMatrix(), matrix, propMatrix);
image->PokeMatrix(propMatrix);
this->ImageMatrices->AddItem(propMatrix);
propMatrix->Delete();
}
}
else
{
vtkCollectionSimpleIterator pit;
this->Images->InitTraversal(pit);
vtkImageSlice *image = 0;
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
image->PokeMatrix(NULL);
}
this->ImageMatrices->RemoveAllItems();
}
}
//----------------------------------------------------------------------------
int vtkImageStack::RenderOpaqueGeometry(vtkViewport* viewport)
{
vtkDebugMacro(<< "vtkImageStack::RenderOpaqueGeometry");
// Opaque render is always called first, so sort here
this->Images->Sort();
this->UpdatePaths();
if (!this->IsIdentity)
{
this->PokeMatrices(this->GetMatrix());
}
int rendered = 0;
vtkImageSlice *image = 0;
vtkCollectionSimpleIterator pit;
vtkIdType n = this->Images->GetNumberOfItems();
double renderTime = this->AllocatedRenderTime/(n + (n == 0));
if (n == 1)
{
// no multi-pass if only one image
this->Images->InitTraversal(pit);
image = this->Images->GetNextImage(pit);
image->SetAllocatedRenderTime(renderTime, viewport);
return image->RenderOpaqueGeometry(viewport);
}
for (int pass = 0; pass < 3; pass++)
{
this->Images->InitTraversal(pit);
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
image->SetAllocatedRenderTime(renderTime, viewport);
image->SetStackedImagePass(pass);
rendered |= image->RenderOpaqueGeometry(viewport);
image->SetStackedImagePass(-1);
}
}
if (!this->IsIdentity)
{
this->PokeMatrices(NULL);
}
return rendered;
}
//----------------------------------------------------------------------------
int vtkImageStack::RenderTranslucentPolygonalGeometry(vtkViewport* viewport)
{
vtkDebugMacro(<< "vtkImageStack::RenderTranslucentPolygonalGeometry");
if (!this->IsIdentity)
{
this->PokeMatrices(this->GetMatrix());
}
int rendered = 0;
vtkImageSlice *image = 0;
vtkCollectionSimpleIterator pit;
vtkIdType n = this->Images->GetNumberOfItems();
double renderTime = this->AllocatedRenderTime/(n + (n == 0));
if (n == 1)
{
// no multi-pass if only one image
this->Images->InitTraversal(pit);
image = this->Images->GetNextImage(pit);
image->SetAllocatedRenderTime(renderTime, viewport);
return image->RenderTranslucentPolygonalGeometry(viewport);
}
for (int pass = 1; pass < 3; pass++)
{
this->Images->InitTraversal(pit);
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
image->SetAllocatedRenderTime(renderTime, viewport);
image->SetStackedImagePass(pass);
rendered |= image->RenderTranslucentPolygonalGeometry(viewport);
image->SetStackedImagePass(-1);
}
}
if (!this->IsIdentity)
{
this->PokeMatrices(NULL);
}
return rendered;
}
//----------------------------------------------------------------------------
int vtkImageStack::RenderOverlay(vtkViewport* viewport)
{
vtkDebugMacro(<< "vtkImageStack::RenderOverlay");
if (!this->IsIdentity)
{
this->PokeMatrices(this->GetMatrix());
}
int rendered = 0;
vtkImageSlice *image = 0;
vtkCollectionSimpleIterator pit;
vtkIdType n = this->Images->GetNumberOfItems();
double renderTime = this->AllocatedRenderTime/(n + (n == 0));
if (n == 1)
{
// no multi-pass if only one image
this->Images->InitTraversal(pit);
image = this->Images->GetNextImage(pit);
image->SetAllocatedRenderTime(renderTime, viewport);
return image->RenderOverlay(viewport);
}
for (int pass = 1; pass < 3; pass++)
{
this->Images->InitTraversal(pit);
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
image->SetAllocatedRenderTime(renderTime, viewport);
image->SetStackedImagePass(pass);
rendered |= image->RenderOverlay(viewport);
image->SetStackedImagePass(-1);
}
}
if (!this->IsIdentity)
{
this->PokeMatrices(NULL);
}
return rendered;
}
//----------------------------------------------------------------------------
void vtkImageStack::ReleaseGraphicsResources(vtkWindow *win)
{
vtkCollectionSimpleIterator pit;
this->Images->InitTraversal(pit);
vtkImageSlice *image = 0;
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
image->ReleaseGraphicsResources(win);
}
}
//----------------------------------------------------------------------------
unsigned long int vtkImageStack::GetMTime()
{
unsigned long mTime = this->Superclass::GetMTime();
unsigned long t;
// Get the max mtime of all the images
vtkCollectionSimpleIterator pit;
this->Images->InitTraversal(pit);
vtkImageSlice *image = 0;
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
t = image->GetMTime();
mTime = (t < mTime ? mTime : t);
}
return mTime;
}
//----------------------------------------------------------------------------
unsigned long int vtkImageStack::GetRedrawMTime()
{
// Just call GetMTime on ourselves, not GetRedrawMTime
unsigned long mTime = this->Superclass::GetMTime();
unsigned long t;
// Get the max mtime of all the images
vtkCollectionSimpleIterator pit;
this->Images->InitTraversal(pit);
vtkImageSlice *image = 0;
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
t = image->GetRedrawMTime();
mTime = (t < mTime ? mTime : t);
}
return mTime;
}
//----------------------------------------------------------------------------
void vtkImageStack::InitPathTraversal()
{
this->UpdatePaths();
this->Paths->InitTraversal();
}
//----------------------------------------------------------------------------
vtkAssemblyPath *vtkImageStack::GetNextPath()
{
if (this->Paths)
{
return this->Paths->GetNextItem();
}
return NULL;
}
//----------------------------------------------------------------------------
int vtkImageStack::GetNumberOfPaths()
{
this->UpdatePaths();
return this->Paths->GetNumberOfItems();
}
//----------------------------------------------------------------------------
void vtkImageStack::UpdatePaths()
{
if (this->GetMTime() > this->PathTime ||
(this->Paths && this->Paths->GetMTime() > this->PathTime))
{
if (this->Paths)
{
this->Paths->Delete();
}
// Create the list to hold all the paths
this->Paths = vtkAssemblyPaths::New();
vtkAssemblyPath *path = vtkAssemblyPath::New();
// Add ourselves to the path to start things off
path->AddNode(this, this->GetMatrix());
// Add the active image
vtkImageSlice *image = this->GetActiveImage();
if (image)
{
path->AddNode(image, image->GetMatrix());
image->BuildPaths(this->Paths, path);
path->DeleteLastNode();
}
path->Delete();
this->PathTime.Modified();
}
}
//----------------------------------------------------------------------------
void vtkImageStack::BuildPaths(vtkAssemblyPaths *paths, vtkAssemblyPath *path)
{
// the path consists only of the active image
vtkImageSlice *image = this->GetActiveImage();
if (image)
{
path->AddNode(image, image->GetMatrix());
image->BuildPaths(paths, path);
path->DeleteLastNode();
}
}
//----------------------------------------------------------------------------
void vtkImageStack::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Images: " << this->Images << "\n";
os << indent << "ActiveLayer: " << this->ActiveLayer << "\n";
os << indent << "ActiveImage: " << this->GetActiveImage() << "\n";
}
<commit_msg>BUG: Visibility was ignored for images in vtkImageStack.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageStack.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkImageStack.h"
#include "vtkImageSliceCollection.h"
#include "vtkImageProperty.h"
#include "vtkImageMapper3D.h"
#include "vtkMatrix4x4.h"
#include "vtkAssemblyPath.h"
#include "vtkAssemblyPaths.h"
#include "vtkObjectFactory.h"
vtkStandardNewMacro(vtkImageStack);
//----------------------------------------------------------------------------
vtkImageStack::vtkImageStack()
{
this->Images = vtkImageSliceCollection::New();
this->ImageMatrices = NULL;
this->ActiveLayer = 0;
}
//----------------------------------------------------------------------------
vtkImageStack::~vtkImageStack()
{
if (this->Images)
{
vtkCollectionSimpleIterator pit;
this->Images->InitTraversal(pit);
vtkImageSlice *image = 0;
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
image->RemoveConsumer(this);
}
this->Images->Delete();
}
if (this->ImageMatrices)
{
this->ImageMatrices->Delete();
}
}
//----------------------------------------------------------------------------
vtkImageSlice *vtkImageStack::GetActiveImage()
{
vtkImageSlice *activeImage = 0;
vtkCollectionSimpleIterator pit;
this->Images->InitTraversal(pit);
vtkImageSlice *image = 0;
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
vtkImageProperty *p = image->GetProperty();
if (p->GetLayerNumber() == this->ActiveLayer)
{
activeImage = image;
}
}
return activeImage;
}
//----------------------------------------------------------------------------
void vtkImageStack::AddImage(vtkImageSlice *prop)
{
if (!this->Images->IsItemPresent(prop) &&
!vtkImageStack::SafeDownCast(prop))
{
this->Images->AddItem(prop);
prop->AddConsumer(this);
}
}
//----------------------------------------------------------------------------
void vtkImageStack::RemoveImage(vtkImageSlice *prop)
{
if (this->Images->IsItemPresent(prop))
{
prop->RemoveConsumer(this);
this->Images->RemoveItem(prop);
}
}
//----------------------------------------------------------------------------
int vtkImageStack::HasImage(vtkImageSlice *prop)
{
return this->Images->IsItemPresent(prop);
}
//----------------------------------------------------------------------------
void vtkImageStack::GetImages(vtkPropCollection *vc)
{
vtkCollectionSimpleIterator pit;
this->Images->InitTraversal(pit);
vtkImageSlice *image = 0;
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
image->GetImages(vc);
}
}
//----------------------------------------------------------------------------
void vtkImageStack::ShallowCopy(vtkProp *prop)
{
vtkImageStack *v = vtkImageStack::SafeDownCast(prop);
if (v != NULL)
{
this->Images->RemoveAllItems();
vtkCollectionSimpleIterator pit;
v->Images->InitTraversal(pit);
vtkImageSlice *image = 0;
while ( (image = v->Images->GetNextImage(pit)) != 0)
{
this->Images->AddItem(image);
}
this->SetActiveLayer(v->GetActiveLayer());
}
// Now do prop superclass (NOT vtkImageSlice)
this->vtkProp3D::ShallowCopy(prop);
}
//----------------------------------------------------------------------------
void vtkImageStack::SetProperty(vtkImageProperty *)
{
// do nothing
}
//----------------------------------------------------------------------------
vtkImageProperty *vtkImageStack::GetProperty()
{
// Get the property with the active layer number
vtkImageSlice *image = this->GetActiveImage();
if (image)
{
return image->GetProperty();
}
// Return a dummy property, can't return NULL.
if (this->Property == 0)
{
this->Property = vtkImageProperty::New();
this->Property->Register(this);
this->Property->Delete();
}
return this->Property;
}
//----------------------------------------------------------------------------
void vtkImageStack::SetMapper(vtkImageMapper3D *)
{
// do nothing
}
//----------------------------------------------------------------------------
vtkImageMapper3D *vtkImageStack::GetMapper()
{
// Get the mapper with the active layer number
vtkImageSlice *image = this->GetActiveImage();
if (image)
{
return image->GetMapper();
}
return NULL;
}
//----------------------------------------------------------------------------
double *vtkImageStack::GetBounds()
{
this->UpdatePaths();
double bounds[6];
bool nobounds = true;
bounds[0] = VTK_DOUBLE_MAX;
bounds[1] = VTK_DOUBLE_MIN;
bounds[2] = VTK_DOUBLE_MAX;
bounds[3] = VTK_DOUBLE_MIN;
bounds[4] = VTK_DOUBLE_MAX;
bounds[5] = VTK_DOUBLE_MIN;
if (!this->IsIdentity)
{
this->PokeMatrices(this->GetMatrix());
}
vtkCollectionSimpleIterator pit;
this->Images->InitTraversal(pit);
vtkImageSlice *image = 0;
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
double *b = image->GetBounds();
if (b)
{
nobounds = false;
bounds[0] = (bounds[0] < b[0] ? bounds[0] : b[0]);
bounds[1] = (bounds[1] > b[1] ? bounds[1] : b[1]);
bounds[2] = (bounds[2] < b[2] ? bounds[2] : b[2]);
bounds[3] = (bounds[3] > b[3] ? bounds[3] : b[3]);
bounds[4] = (bounds[4] < b[4] ? bounds[4] : b[4]);
bounds[5] = (bounds[5] > b[5] ? bounds[5] : b[5]);
}
}
if (!this->IsIdentity)
{
this->PokeMatrices(NULL);
}
if (nobounds)
{
return 0;
}
this->Bounds[0] = bounds[0];
this->Bounds[1] = bounds[1];
this->Bounds[2] = bounds[2];
this->Bounds[3] = bounds[3];
this->Bounds[4] = bounds[4];
this->Bounds[5] = bounds[5];
return this->Bounds;
}
//----------------------------------------------------------------------------
// Does this prop have some translucent polygonal geometry?
int vtkImageStack::HasTranslucentPolygonalGeometry()
{
vtkCollectionSimpleIterator pit;
this->Images->InitTraversal(pit);
vtkImageSlice *image = 0;
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
if (image->HasTranslucentPolygonalGeometry())
{
return 1;
}
}
return 0;
}
//----------------------------------------------------------------------------
// Assembly-like behavior
void vtkImageStack::PokeMatrices(vtkMatrix4x4 *matrix)
{
if (this->ImageMatrices == NULL)
{
this->ImageMatrices = vtkCollection::New();
}
if (matrix)
{
vtkCollectionSimpleIterator pit;
this->Images->InitTraversal(pit);
vtkImageSlice *image = 0;
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
vtkMatrix4x4 *propMatrix = vtkMatrix4x4::New();
propMatrix->Multiply4x4(image->GetMatrix(), matrix, propMatrix);
image->PokeMatrix(propMatrix);
this->ImageMatrices->AddItem(propMatrix);
propMatrix->Delete();
}
}
else
{
vtkCollectionSimpleIterator pit;
this->Images->InitTraversal(pit);
vtkImageSlice *image = 0;
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
image->PokeMatrix(NULL);
}
this->ImageMatrices->RemoveAllItems();
}
}
//----------------------------------------------------------------------------
int vtkImageStack::RenderOpaqueGeometry(vtkViewport* viewport)
{
vtkDebugMacro(<< "vtkImageStack::RenderOpaqueGeometry");
// Opaque render is always called first, so sort here
this->Images->Sort();
this->UpdatePaths();
if (!this->IsIdentity)
{
this->PokeMatrices(this->GetMatrix());
}
int rendered = 0;
vtkImageSlice *image = 0;
vtkCollectionSimpleIterator pit;
vtkIdType n = 0;
this->Images->InitTraversal(pit);
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
n += (image->GetVisibility() != 0);
}
double renderTime = this->AllocatedRenderTime/(n + (n == 0));
if (n == 1)
{
// no multi-pass if only one image
this->Images->InitTraversal(pit);
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
if (image->GetVisibility())
{
image->SetAllocatedRenderTime(renderTime, viewport);
rendered = image->RenderOpaqueGeometry(viewport);
}
}
}
else
{
for (int pass = 0; pass < 3; pass++)
{
this->Images->InitTraversal(pit);
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
if (image->GetVisibility())
{
image->SetAllocatedRenderTime(renderTime, viewport);
image->SetStackedImagePass(pass);
rendered |= image->RenderOpaqueGeometry(viewport);
image->SetStackedImagePass(-1);
}
}
}
}
if (!this->IsIdentity)
{
this->PokeMatrices(NULL);
}
return rendered;
}
//----------------------------------------------------------------------------
int vtkImageStack::RenderTranslucentPolygonalGeometry(vtkViewport* viewport)
{
vtkDebugMacro(<< "vtkImageStack::RenderTranslucentPolygonalGeometry");
if (!this->IsIdentity)
{
this->PokeMatrices(this->GetMatrix());
}
int rendered = 0;
vtkImageSlice *image = 0;
vtkCollectionSimpleIterator pit;
vtkIdType n = 0;
this->Images->InitTraversal(pit);
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
n += (image->GetVisibility() != 0);
}
double renderTime = this->AllocatedRenderTime/(n + (n == 0));
if (n == 1)
{
// no multi-pass if only one image
this->Images->InitTraversal(pit);
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
if (image->GetVisibility())
{
image->SetAllocatedRenderTime(renderTime, viewport);
rendered = image->RenderTranslucentPolygonalGeometry(viewport);
}
}
}
else
{
for (int pass = 1; pass < 3; pass++)
{
this->Images->InitTraversal(pit);
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
if (image->GetVisibility())
{
image->SetAllocatedRenderTime(renderTime, viewport);
image->SetStackedImagePass(pass);
rendered |= image->RenderTranslucentPolygonalGeometry(viewport);
image->SetStackedImagePass(-1);
}
}
}
}
if (!this->IsIdentity)
{
this->PokeMatrices(NULL);
}
return rendered;
}
//----------------------------------------------------------------------------
int vtkImageStack::RenderOverlay(vtkViewport* viewport)
{
vtkDebugMacro(<< "vtkImageStack::RenderOverlay");
if (!this->IsIdentity)
{
this->PokeMatrices(this->GetMatrix());
}
int rendered = 0;
vtkImageSlice *image = 0;
vtkCollectionSimpleIterator pit;
vtkIdType n = 0;
this->Images->InitTraversal(pit);
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
n += (image->GetVisibility() != 0);
}
double renderTime = this->AllocatedRenderTime/(n + (n == 0));
if (n == 1)
{
// no multi-pass if only one image
this->Images->InitTraversal(pit);
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
if (image->GetVisibility())
{
image->SetAllocatedRenderTime(renderTime, viewport);
rendered = image->RenderOverlay(viewport);
}
}
}
else
{
for (int pass = 1; pass < 3; pass++)
{
this->Images->InitTraversal(pit);
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
if (image->GetVisibility())
{
image->SetAllocatedRenderTime(renderTime, viewport);
image->SetStackedImagePass(pass);
rendered |= image->RenderOverlay(viewport);
image->SetStackedImagePass(-1);
}
}
}
}
if (!this->IsIdentity)
{
this->PokeMatrices(NULL);
}
return rendered;
}
//----------------------------------------------------------------------------
void vtkImageStack::ReleaseGraphicsResources(vtkWindow *win)
{
vtkCollectionSimpleIterator pit;
this->Images->InitTraversal(pit);
vtkImageSlice *image = 0;
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
image->ReleaseGraphicsResources(win);
}
}
//----------------------------------------------------------------------------
unsigned long int vtkImageStack::GetMTime()
{
unsigned long mTime = this->Superclass::GetMTime();
unsigned long t;
// Get the max mtime of all the images
vtkCollectionSimpleIterator pit;
this->Images->InitTraversal(pit);
vtkImageSlice *image = 0;
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
t = image->GetMTime();
mTime = (t < mTime ? mTime : t);
}
return mTime;
}
//----------------------------------------------------------------------------
unsigned long int vtkImageStack::GetRedrawMTime()
{
// Just call GetMTime on ourselves, not GetRedrawMTime
unsigned long mTime = this->Superclass::GetMTime();
unsigned long t;
// Get the max mtime of all the images
vtkCollectionSimpleIterator pit;
this->Images->InitTraversal(pit);
vtkImageSlice *image = 0;
while ( (image = this->Images->GetNextImage(pit)) != 0)
{
t = image->GetRedrawMTime();
mTime = (t < mTime ? mTime : t);
}
return mTime;
}
//----------------------------------------------------------------------------
void vtkImageStack::InitPathTraversal()
{
this->UpdatePaths();
this->Paths->InitTraversal();
}
//----------------------------------------------------------------------------
vtkAssemblyPath *vtkImageStack::GetNextPath()
{
if (this->Paths)
{
return this->Paths->GetNextItem();
}
return NULL;
}
//----------------------------------------------------------------------------
int vtkImageStack::GetNumberOfPaths()
{
this->UpdatePaths();
return this->Paths->GetNumberOfItems();
}
//----------------------------------------------------------------------------
void vtkImageStack::UpdatePaths()
{
if (this->GetMTime() > this->PathTime ||
(this->Paths && this->Paths->GetMTime() > this->PathTime))
{
if (this->Paths)
{
this->Paths->Delete();
}
// Create the list to hold all the paths
this->Paths = vtkAssemblyPaths::New();
vtkAssemblyPath *path = vtkAssemblyPath::New();
// Add ourselves to the path to start things off
path->AddNode(this, this->GetMatrix());
// Add the active image
vtkImageSlice *image = this->GetActiveImage();
if (image)
{
path->AddNode(image, image->GetMatrix());
image->BuildPaths(this->Paths, path);
path->DeleteLastNode();
}
path->Delete();
this->PathTime.Modified();
}
}
//----------------------------------------------------------------------------
void vtkImageStack::BuildPaths(vtkAssemblyPaths *paths, vtkAssemblyPath *path)
{
// the path consists only of the active image
vtkImageSlice *image = this->GetActiveImage();
if (image)
{
path->AddNode(image, image->GetMatrix());
image->BuildPaths(paths, path);
path->DeleteLastNode();
}
}
//----------------------------------------------------------------------------
void vtkImageStack::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Images: " << this->Images << "\n";
os << indent << "ActiveLayer: " << this->ActiveLayer << "\n";
os << indent << "ActiveImage: " << this->GetActiveImage() << "\n";
}
<|endoftext|>
|
<commit_before>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*******************************************************************************/
//==============================================================================
// Raw CellML view widget
//==============================================================================
#include "corecellmleditingwidget.h"
#include "filemanager.h"
#include "qscintillawidget.h"
#include "rawcellmlviewwidget.h"
#include "viewerwidget.h"
//==============================================================================
#include "ui_rawcellmlviewwidget.h"
//==============================================================================
#include <QDesktopWidget>
#include <QLabel>
#include <QLayout>
#include <QMetaType>
#include <QSettings>
#include <QVariant>
//==============================================================================
#include "Qsci/qscilexerxml.h"
//==============================================================================
namespace OpenCOR {
namespace RawCellMLView {
//==============================================================================
RawCellmlViewWidget::RawCellmlViewWidget(QWidget *pParent) :
ViewWidget(pParent),
mGui(new Ui::RawCellmlViewWidget),
mEditingWidget(0),
mEditingWidgets(QMap<QString, CoreCellMLEditing::CoreCellmlEditingWidget *>()),
mEditingWidgetSizes(QIntList()),
mEditorZoomLevel(0)
{
// Set up the GUI
mGui->setupUi(this);
}
//==============================================================================
RawCellmlViewWidget::~RawCellmlViewWidget()
{
// Delete the GUI
delete mGui;
}
//==============================================================================
static const auto SettingsEditingWidgetSizes = QStringLiteral("EditingWidgetSizes");
static const auto SettingsEditorZoomLevel = QStringLiteral("EditorZoomLevel");
//==============================================================================
void RawCellmlViewWidget::loadSettings(QSettings *pSettings)
{
// Retrieve the editing widget's sizes and the editor's zoom level
// Note #1: the viewer's default height is 19% of the desktop's height while
// that of the editor is as big as it can be...
// Note #2: because the editor's default height is much bigger than that of
// our raw CellML view widget, the viewer's default height will
// effectively be less than 19% of the desktop's height, but that
// doesn't matter at all...
QVariantList defaultEditingWidgetSizes = QVariantList() << 0.19*qApp->desktop()->screenGeometry().height()
<< qApp->desktop()->screenGeometry().height();
mEditingWidgetSizes = qVariantListToIntList(pSettings->value(SettingsEditingWidgetSizes, defaultEditingWidgetSizes).toList());
mEditorZoomLevel = pSettings->value(SettingsEditorZoomLevel, 0).toInt();
}
//==============================================================================
void RawCellmlViewWidget::saveSettings(QSettings *pSettings) const
{
// Keep track of the editing widget's sizes and the editor's zoom level
pSettings->setValue(SettingsEditingWidgetSizes, qIntListToVariantList(mEditingWidgetSizes));
pSettings->setValue(SettingsEditorZoomLevel, mEditorZoomLevel);
}
//==============================================================================
bool RawCellmlViewWidget::contains(const QString &pFileName) const
{
// Return whether we know about the given file, i.e. whether we have an
// editing widget for it
return mEditingWidgets.value(pFileName);
}
//==============================================================================
void RawCellmlViewWidget::initialize(const QString &pFileName)
{
// Retrieve the editing widget associated with the given file, if any
mEditingWidget = mEditingWidgets.value(pFileName);
if (!mEditingWidget) {
// No editing widget exists for the given file, so create one
QString fileContents;
Core::readTextFromFile(pFileName, fileContents);
mEditingWidget = new CoreCellMLEditing::CoreCellmlEditingWidget(fileContents,
!Core::FileManager::instance()->isReadableAndWritable(pFileName),
new QsciLexerXML(this),
parentWidget());
// Keep track of our editing widget's sizes when moving the splitter and
// of changes to our editor's zoom level
connect(mEditingWidget, SIGNAL(splitterMoved(int, int)),
this, SLOT(splitterMoved()));
connect(mEditingWidget->editor(), SIGNAL(SCN_ZOOM()),
this, SLOT(editorZoomLevelChanged()));
connect(mEditingWidget->editor(), SIGNAL(cursorPositionChanged(int, int)),
this, SLOT(cursorPositionChanged()));
// Keep track of our editing widget and add it to ourselves
mEditingWidgets.insert(pFileName, mEditingWidget);
layout()->addWidget(mEditingWidget);
}
// Show/hide our editing widgets and adjust our sizes
foreach (CoreCellMLEditing::CoreCellmlEditingWidget *editingWidget, mEditingWidgets)
if (editingWidget == mEditingWidget) {
// This is the editing widget we are after, so show it and update
// its size and zoom level
editingWidget->setSizes(mEditingWidgetSizes);
editingWidget->editor()->zoomTo(mEditorZoomLevel);
editingWidget->show();
} else {
// Not the editing widget we are after, so hide it
editingWidget->hide();
}
// Set our focus proxy to our 'new' editing widget and make sure that the
// latter immediately gets the focus
// Note: if we were not to immediately give our 'new' editing widget the
// focus, then the central widget would give the focus to our 'old'
// editing widget (see CentralWidget::updateGui()), so...
setFocusProxy(mEditingWidget->editor());
mEditingWidget->editor()->setFocus();
}
//==============================================================================
void RawCellmlViewWidget::finalize(const QString &pFileName)
{
// Remove the editing widget, should there be one for the given file
CoreCellMLEditing::CoreCellmlEditingWidget *editingWidget = mEditingWidgets.value(pFileName);
if (editingWidget) {
// There is an editor for the given file name, so delete it and remove
// it from our list
delete editingWidget;
mEditingWidgets.remove(pFileName);
// Reset our memory of the current editor
mEditingWidget = 0;
}
}
//==============================================================================
void RawCellmlViewWidget::fileReloaded(const QString &pFileName)
{
// The given file has been reloaded, so reload it, should it be managed
if (contains(pFileName)) {
finalize(pFileName);
initialize(pFileName);
}
}
//==============================================================================
void RawCellmlViewWidget::fileRenamed(const QString &pOldFileName,
const QString &pNewFileName)
{
// The given file has been renamed, so update our editing widgets mapping
CoreCellMLEditing::CoreCellmlEditingWidget *editingWidget = mEditingWidgets.value(pOldFileName);
if (editingWidget) {
mEditingWidgets.insert(pNewFileName, editingWidget);
mEditingWidgets.remove(pOldFileName);
}
}
//==============================================================================
QScintillaSupport::QScintillaWidget * RawCellmlViewWidget::editor(const QString &pFileName) const
{
// Return the requested editor
CoreCellMLEditing::CoreCellmlEditingWidget *editingWidget = mEditingWidgets.value(pFileName);
return editingWidget?editingWidget->editor():0;
}
//==============================================================================
QList<QWidget *> RawCellmlViewWidget::statusBarWidgets() const
{
// Return our status bar widgets
if (mEditingWidget)
return QList<QWidget *>() << mEditingWidget->editor()->cursorPositionWidget()
<< mEditingWidget->editor()->editingModeWidget();
else
return QList<QWidget *>();
}
//==============================================================================
void RawCellmlViewWidget::splitterMoved()
{
// The splitter has moved, so keep track of the editing widget's sizes
mEditingWidgetSizes = qobject_cast<CoreCellMLEditing::CoreCellmlEditingWidget *>(sender())->sizes();
}
//==============================================================================
void RawCellmlViewWidget::editorZoomLevelChanged()
{
// One of our editors had its zoom level changed, so keep track of the new
// zoom level
mEditorZoomLevel = qobject_cast<QScintillaSupport::QScintillaWidget *>(sender())->SendScintilla(QsciScintillaBase::SCI_GETZOOM);
}
//==============================================================================
void RawCellmlViewWidget::cursorPositionChanged()
{
// The cursor has moved, so retrieve the new mathematical equation, if any,
// around our current position
qDebug("---------");
static const QString StartMathTag = "<math ";
static const QByteArray EndMathTag = "</math>";
QScintillaSupport::QScintillaWidget *editor = mEditingWidget->editor();
int crtPos = editor->currentPosition();
int crtStartMathTagPos = editor->findTextInRange(crtPos+StartMathTag.length(), 0, StartMathTag);
int prevEndMathTagPos = editor->findTextInRange(crtPos, 0, EndMathTag);
int crtEndMathTagPos = editor->findTextInRange(crtPos-EndMathTag.length()+1, editor->contentsSize(), EndMathTag);
bool foundMathBlock = true;
if ( (crtStartMathTagPos >= 0) && (crtEndMathTagPos >= 0)
&& (crtStartMathTagPos <= crtPos)
&& (crtPos <= crtEndMathTagPos+EndMathTag.length()-1)) {
if ( (prevEndMathTagPos >= 0)
&& (prevEndMathTagPos > crtStartMathTagPos)
&& (prevEndMathTagPos < crtPos))
foundMathBlock = false;
} else {
foundMathBlock = false;
}
QString mathBlock = QString();
if (foundMathBlock)
mathBlock = editor->textInRange(crtStartMathTagPos, crtEndMathTagPos+EndMathTag.length());
if (mathBlock.length())
qDebug(">>> Math block found:\n%s", qPrintable(mathBlock));
else
qDebug(">>> No math block found...");
mEditingWidget->viewer()->setContent(mathBlock);
}
//==============================================================================
} // namespace RawCellMLView
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Some minor cleaning up.<commit_after>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*******************************************************************************/
//==============================================================================
// Raw CellML view widget
//==============================================================================
#include "corecellmleditingwidget.h"
#include "filemanager.h"
#include "qscintillawidget.h"
#include "rawcellmlviewwidget.h"
#include "viewerwidget.h"
//==============================================================================
#include "ui_rawcellmlviewwidget.h"
//==============================================================================
#include <QDesktopWidget>
#include <QLabel>
#include <QLayout>
#include <QMetaType>
#include <QSettings>
#include <QVariant>
//==============================================================================
#include "Qsci/qscilexerxml.h"
//==============================================================================
namespace OpenCOR {
namespace RawCellMLView {
//==============================================================================
RawCellmlViewWidget::RawCellmlViewWidget(QWidget *pParent) :
ViewWidget(pParent),
mGui(new Ui::RawCellmlViewWidget),
mEditingWidget(0),
mEditingWidgets(QMap<QString, CoreCellMLEditing::CoreCellmlEditingWidget *>()),
mEditingWidgetSizes(QIntList()),
mEditorZoomLevel(0)
{
// Set up the GUI
mGui->setupUi(this);
}
//==============================================================================
RawCellmlViewWidget::~RawCellmlViewWidget()
{
// Delete the GUI
delete mGui;
}
//==============================================================================
static const auto SettingsEditingWidgetSizes = QStringLiteral("EditingWidgetSizes");
static const auto SettingsEditorZoomLevel = QStringLiteral("EditorZoomLevel");
//==============================================================================
void RawCellmlViewWidget::loadSettings(QSettings *pSettings)
{
// Retrieve the editing widget's sizes and the editor's zoom level
// Note #1: the viewer's default height is 19% of the desktop's height while
// that of the editor is as big as it can be...
// Note #2: because the editor's default height is much bigger than that of
// our raw CellML view widget, the viewer's default height will
// effectively be less than 19% of the desktop's height, but that
// doesn't matter at all...
QVariantList defaultEditingWidgetSizes = QVariantList() << 0.19*qApp->desktop()->screenGeometry().height()
<< qApp->desktop()->screenGeometry().height();
mEditingWidgetSizes = qVariantListToIntList(pSettings->value(SettingsEditingWidgetSizes, defaultEditingWidgetSizes).toList());
mEditorZoomLevel = pSettings->value(SettingsEditorZoomLevel, 0).toInt();
}
//==============================================================================
void RawCellmlViewWidget::saveSettings(QSettings *pSettings) const
{
// Keep track of the editing widget's sizes and the editor's zoom level
pSettings->setValue(SettingsEditingWidgetSizes, qIntListToVariantList(mEditingWidgetSizes));
pSettings->setValue(SettingsEditorZoomLevel, mEditorZoomLevel);
}
//==============================================================================
bool RawCellmlViewWidget::contains(const QString &pFileName) const
{
// Return whether we know about the given file, i.e. whether we have an
// editing widget for it
return mEditingWidgets.value(pFileName);
}
//==============================================================================
void RawCellmlViewWidget::initialize(const QString &pFileName)
{
// Retrieve the editing widget associated with the given file, if any
mEditingWidget = mEditingWidgets.value(pFileName);
if (!mEditingWidget) {
// No editing widget exists for the given file, so create one
QString fileContents;
Core::readTextFromFile(pFileName, fileContents);
mEditingWidget = new CoreCellMLEditing::CoreCellmlEditingWidget(fileContents,
!Core::FileManager::instance()->isReadableAndWritable(pFileName),
new QsciLexerXML(this),
parentWidget());
// Keep track of our editing widget's sizes when moving the splitter and
// of changes to our editor's zoom level
connect(mEditingWidget, SIGNAL(splitterMoved(int, int)),
this, SLOT(splitterMoved()));
connect(mEditingWidget->editor(), SIGNAL(SCN_ZOOM()),
this, SLOT(editorZoomLevelChanged()));
connect(mEditingWidget->editor(), SIGNAL(cursorPositionChanged(int, int)),
this, SLOT(cursorPositionChanged()));
// Keep track of our editing widget and add it to ourselves
mEditingWidgets.insert(pFileName, mEditingWidget);
layout()->addWidget(mEditingWidget);
}
// Show/hide our editing widgets and adjust our sizes
foreach (CoreCellMLEditing::CoreCellmlEditingWidget *editingWidget, mEditingWidgets)
if (editingWidget == mEditingWidget) {
// This is the editing widget we are after, so show it and update
// its size and zoom level
editingWidget->setSizes(mEditingWidgetSizes);
editingWidget->editor()->zoomTo(mEditorZoomLevel);
editingWidget->show();
} else {
// Not the editing widget we are after, so hide it
editingWidget->hide();
}
// Set our focus proxy to our 'new' editing widget and make sure that the
// latter immediately gets the focus
// Note: if we were not to immediately give our 'new' editing widget the
// focus, then the central widget would give the focus to our 'old'
// editing widget (see CentralWidget::updateGui()), so...
setFocusProxy(mEditingWidget->editor());
mEditingWidget->editor()->setFocus();
}
//==============================================================================
void RawCellmlViewWidget::finalize(const QString &pFileName)
{
// Remove the editing widget, should there be one for the given file
CoreCellMLEditing::CoreCellmlEditingWidget *editingWidget = mEditingWidgets.value(pFileName);
if (editingWidget) {
// There is an editor for the given file name, so delete it and remove
// it from our list
delete editingWidget;
mEditingWidgets.remove(pFileName);
// Reset our memory of the current editor
mEditingWidget = 0;
}
}
//==============================================================================
void RawCellmlViewWidget::fileReloaded(const QString &pFileName)
{
// The given file has been reloaded, so reload it, should it be managed
if (contains(pFileName)) {
finalize(pFileName);
initialize(pFileName);
}
}
//==============================================================================
void RawCellmlViewWidget::fileRenamed(const QString &pOldFileName,
const QString &pNewFileName)
{
// The given file has been renamed, so update our editing widgets mapping
CoreCellMLEditing::CoreCellmlEditingWidget *editingWidget = mEditingWidgets.value(pOldFileName);
if (editingWidget) {
mEditingWidgets.insert(pNewFileName, editingWidget);
mEditingWidgets.remove(pOldFileName);
}
}
//==============================================================================
QScintillaSupport::QScintillaWidget * RawCellmlViewWidget::editor(const QString &pFileName) const
{
// Return the requested editor
CoreCellMLEditing::CoreCellmlEditingWidget *editingWidget = mEditingWidgets.value(pFileName);
return editingWidget?editingWidget->editor():0;
}
//==============================================================================
QList<QWidget *> RawCellmlViewWidget::statusBarWidgets() const
{
// Return our status bar widgets
if (mEditingWidget)
return QList<QWidget *>() << mEditingWidget->editor()->cursorPositionWidget()
<< mEditingWidget->editor()->editingModeWidget();
else
return QList<QWidget *>();
}
//==============================================================================
void RawCellmlViewWidget::splitterMoved()
{
// The splitter has moved, so keep track of the editing widget's sizes
mEditingWidgetSizes = qobject_cast<CoreCellMLEditing::CoreCellmlEditingWidget *>(sender())->sizes();
}
//==============================================================================
void RawCellmlViewWidget::editorZoomLevelChanged()
{
// One of our editors had its zoom level changed, so keep track of the new
// zoom level
mEditorZoomLevel = qobject_cast<QScintillaSupport::QScintillaWidget *>(sender())->SendScintilla(QsciScintillaBase::SCI_GETZOOM);
}
//==============================================================================
void RawCellmlViewWidget::cursorPositionChanged()
{
// The cursor has moved, so retrieve the new mathematical equation, if any,
// around our current position
qDebug("---------");
static const QString StartMathTag = "<math ";
static const QByteArray EndMathTag = "</math>";
QScintillaSupport::QScintillaWidget *editor = mEditingWidget->editor();
int crtPos = editor->currentPosition();
int crtStartMathTagPos = editor->findTextInRange(crtPos+StartMathTag.length(), 0, StartMathTag);
int prevEndMathTagPos = editor->findTextInRange(crtPos, 0, EndMathTag);
int crtEndMathTagPos = editor->findTextInRange(crtPos-EndMathTag.length()+1, editor->contentsSize(), EndMathTag);
bool foundMathBlock = true;
if ( (crtStartMathTagPos >= 0) && (crtEndMathTagPos >= 0)
&& (crtStartMathTagPos <= crtPos)
&& (crtPos <= crtEndMathTagPos+EndMathTag.length()-1)) {
if ( (prevEndMathTagPos >= 0)
&& (prevEndMathTagPos > crtStartMathTagPos)
&& (prevEndMathTagPos < crtPos))
foundMathBlock = false;
} else {
foundMathBlock = false;
}
QString mathBlock = QString();
if (foundMathBlock)
mathBlock = editor->textInRange(crtStartMathTagPos, crtEndMathTagPos+EndMathTag.length());
if (mathBlock.length())
qDebug(">>> Math block found:\n%s", qPrintable(mathBlock));
else
qDebug(">>> No math block found...");
mEditingWidget->viewer()->setContents(mathBlock);
}
//==============================================================================
} // namespace RawCellMLView
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|>
|
<commit_before>//===- unittest/Support/ProgramTest.cpp -----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Program.h"
#include "gtest/gtest.h"
#include <stdlib.h>
namespace {
using namespace llvm;
using namespace sys;
static cl::opt<std::string>
ProgramTestStringArg1("program-test-string-arg1");
static cl::opt<std::string>
ProgramTestStringArg2("program-test-string-arg2");
TEST(ProgramTest, CreateProcessTrailingSlash) {
if (getenv("LLVM_PROGRAM_TEST_CHILD")) {
if (ProgramTestStringArg1 == "has\\\\ trailing\\" &&
ProgramTestStringArg2 == "has\\\\ trailing\\") {
exit(0); // Success! The arguments were passed and parsed.
}
exit(1);
}
// FIXME: Hardcoding argv0 here since I don't know a good cross-platform way
// to get it. Maybe ParseCommandLineOptions() should save it?
Path my_exe = Path::GetMainExecutable("SupportTests", &ProgramTestStringArg1);
const char *argv[] = {
my_exe.c_str(),
"--gtest_filter=ProgramTest.CreateProcessTrailingSlashChild",
"-program-test-string-arg1", "has\\\\ trailing\\",
"-program-test-string-arg2", "has\\\\ trailing\\",
0
};
const char *envp[] = { "LLVM_PROGRAM_TEST_CHILD=1", 0 };
std::string error;
bool ExecutionFailed;
// Redirect stdout and stdin to NUL, but let stderr through.
#ifdef LLVM_ON_WIN32
Path nul("NUL");
#else
Path nul("/dev/null");
#endif
const Path *redirects[] = { &nul, &nul, 0 };
int rc = Program::ExecuteAndWait(my_exe, argv, envp, redirects,
/*secondsToWait=*/10, /*memoryLimit=*/0,
&error, &ExecutionFailed);
EXPECT_FALSE(ExecutionFailed) << error;
EXPECT_EQ(0, rc);
}
} // end anonymous namespace
<commit_msg>[Support] Propagate the environment into the test child process<commit_after>//===- unittest/Support/ProgramTest.cpp -----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Program.h"
#include "gtest/gtest.h"
#include <stdlib.h>
namespace {
using namespace llvm;
using namespace sys;
static cl::opt<std::string>
ProgramTestStringArg1("program-test-string-arg1");
static cl::opt<std::string>
ProgramTestStringArg2("program-test-string-arg2");
static void CopyEnvironment(std::vector<const char *> out) {
// environ appears to be pretty portable.
char **envp = environ;
while (*envp != 0) {
out.push_back(*envp);
++envp;
}
}
TEST(ProgramTest, CreateProcessTrailingSlash) {
if (getenv("LLVM_PROGRAM_TEST_CHILD")) {
if (ProgramTestStringArg1 == "has\\\\ trailing\\" &&
ProgramTestStringArg2 == "has\\\\ trailing\\") {
exit(0); // Success! The arguments were passed and parsed.
}
exit(1);
}
// FIXME: Hardcoding argv0 here since I don't know a good cross-platform way
// to get it. Maybe ParseCommandLineOptions() should save it?
Path my_exe = Path::GetMainExecutable("SupportTests", &ProgramTestStringArg1);
const char *argv[] = {
my_exe.c_str(),
"--gtest_filter=ProgramTest.CreateProcessTrailingSlashChild",
"-program-test-string-arg1", "has\\\\ trailing\\",
"-program-test-string-arg2", "has\\\\ trailing\\",
0
};
// Add LLVM_PROGRAM_TEST_CHILD to the environment of the child.
std::vector<const char *> envp;
CopyEnvironment(envp);
envp.push_back("LLVM_PROGRAM_TEST_CHILD=1");
envp.push_back(0);
std::string error;
bool ExecutionFailed;
// Redirect stdout and stdin to NUL, but let stderr through.
#ifdef LLVM_ON_WIN32
Path nul("NUL");
#else
Path nul("/dev/null");
#endif
const Path *redirects[] = { &nul, &nul, 0 };
int rc = Program::ExecuteAndWait(my_exe, argv, &envp[0], redirects,
/*secondsToWait=*/10, /*memoryLimit=*/0,
&error, &ExecutionFailed);
EXPECT_FALSE(ExecutionFailed) << error;
EXPECT_EQ(0, rc);
}
} // end anonymous namespace
<|endoftext|>
|
<commit_before>// https://core.telegram.org/bots/api#making-requests
#include "../Logger.h"
#include "../Network.h"
#include "../User.h"
#include "../device/Switch.h"
#include "../device/Text.h"
#include "Telegram.h"
namespace micasa {
extern std::shared_ptr<Logger> g_logger;
extern std::shared_ptr<Network> g_network;
using namespace nlohmann;
void Telegram::start() {
g_logger->log( Logger::LogLevel::VERBOSE, this, "Starting..." );
Hardware::start();
// Add the devices that will initiate controller actions and the broadcast device.
this->declareDevice<Switch>( "accept", "Enable Accept Mode", {
{ DEVICE_SETTING_ALLOWED_UPDATE_SOURCES, Device::resolveUpdateSource( Device::UpdateSource::CONTROLLER | Device::UpdateSource::API ) },
{ DEVICE_SETTING_DEFAULT_SUBTYPE, Switch::resolveSubType( Switch::SubType::ACTION ) },
{ DEVICE_SETTING_MINIMUM_USER_RIGHTS, User::resolveRights( User::Rights::INSTALLER ) }
} )->updateValue( Device::UpdateSource::INIT | Device::UpdateSource::HARDWARE, Switch::Option::IDLE );
this->declareDevice<Text>( "broadcast", "Broadcast", {
{ DEVICE_SETTING_ALLOWED_UPDATE_SOURCES, Device::resolveUpdateSource( Device::UpdateSource::ANY ) },
{ DEVICE_SETTING_DEFAULT_SUBTYPE, Text::resolveSubType( Text::SubType::NOTIFICATION ) }
} );
};
void Telegram::stop() {
g_logger->log( Logger::LogLevel::VERBOSE, this, "Stopping..." );
Hardware::stop();
};
std::chrono::milliseconds Telegram::_work( const unsigned long int& iteration_ ) {
if ( ! this->m_settings->contains( { "username", "token" } ) ) {
g_logger->log( Logger::LogLevel::ERROR, this, "Missing settings." );
this->setState( Hardware::State::FAILED );
return std::chrono::milliseconds( 60 * 1000 );
}
std::stringstream url;
url << "https://api.telegram.org/bot" << this->m_settings->get( "token" ) << "/getUpdates";
json params = {
{ "timeout", 60 }
};
if ( this->m_lastUpdateId > -1 ) {
params["offset"] = this->m_lastUpdateId + 1;
}
this->setState( Hardware::State::READY );
g_network->connect( url.str(), Network::t_callback( [this]( mg_connection* connection_, int event_, void* data_ ) {
if ( event_ == MG_EV_HTTP_REPLY ) {
// See if a valid response was received from the Telegram API. It should be json encoded data with an
// "ok" property set to a boolean true.
std::string body;
body.assign( ((http_message*)data_)->body.p, ((http_message*)data_)->body.len );
try {
json data = json::parse( body );
bool success = data["ok"].get<bool>();
if ( ! success ) {
throw std::runtime_error( "Telegram API reported a failure" );
}
auto find = data.find( "result" );
if (
find != data.end()
&& (*find).is_array()
) {
for ( auto updateIt = (*find).begin(); updateIt != (*find).end(); updateIt++ ) {
int lastUpdateId = jsonGet<int>( *updateIt, "update_id" );
if ( lastUpdateId > this->m_lastUpdateId ) {
this->m_lastUpdateId = lastUpdateId;
}
if ( (*updateIt).find( "message" ) != (*updateIt).end() ) {
this->_processIncomingMessage( (*updateIt)["message"] );
}
}
}
} catch( std::invalid_argument ex_ ) {
g_logger->log( Logger::LogLevel::ERROR, this, "Invalid data received from the Telegram API." );
this->setState( Hardware::State::FAILED );
} catch( std::runtime_error ex_ ) {
g_logger->log( Logger::LogLevel::ERROR, this, ex_.what() );
this->setState( Hardware::State::FAILED );
}
connection_->flags |= MG_F_CLOSE_IMMEDIATELY;
} else if ( event_ == MG_EV_CLOSE ) {
// If a successfull response was received, a new connection needs to be made immediately (long poll),
// if not, try the Telegram API again after the default of 5 minutes.
if ( this->getState() == Hardware::State::READY ) {
this->wakeUp();
}
}
} ), params );
return std::chrono::milliseconds( 1000 * 60 * 5 );
};
bool Telegram::updateDevice( const Device::UpdateSource& source_, std::shared_ptr<Device> device_, bool& apply_ ) {
if ( this->getState() == Hardware::State::READY ) {
if ( device_->getType() == Device::Type::SWITCH ) {
std::shared_ptr<Switch> device = std::static_pointer_cast<Switch>( device_ );
if (
device->getReference() == "accept"
&& device->getValueOption() == Switch::Option::ACTIVATE
) {
if ( this->m_acceptMode ) {
g_logger->log( Logger::LogLevel::ERROR, this, "Accept Mode already enabled." );
} else {
g_logger->log( Logger::LogLevel::NORMAL, this, "Accept Mode enabled." );
this->m_acceptMode = true;
std::thread( [this, device]{
std::this_thread::sleep_for( std::chrono::minutes( 60 * 5 ) );
this->m_acceptMode = false;
device->updateValue( Device::UpdateSource::HARDWARE, Switch::Option::IDLE );
g_logger->log( Logger::LogLevel::VERBOSE, this, "Accept Mode disabled." );
} ).detach();
}
return true;
}
} else if ( device_->getType() == Device::Type::TEXT ) {
std::shared_ptr<Text> device = std::static_pointer_cast<Text>( device_ );
std::stringstream url;
url << "https://api.telegram.org/bot" << this->m_settings->get( "token" ) << "/sendMessage";
json params = {
{ "chat_id", std::stoi( device->getReference() ) },
{ "text", device->getValue() },
{ "parse_mode", "Markdown" }
};
g_network->connect( url.str(), Network::t_callback( [this]( mg_connection* connection_, int event_, void* data_ ) {
if ( event_ == MG_EV_HTTP_REPLY ) {
// See if a valid response was received from the Telegram API.
std::string body;
body.assign( ((http_message*)data_)->body.p, ((http_message*)data_)->body.len );
try {
json data = json::parse( body );
bool success = data["ok"].get<bool>();
if ( ! success ) {
throw std::runtime_error( "Telegram API reported a failure" );
}
} catch( std::invalid_argument ex_ ) {
g_logger->log( Logger::LogLevel::ERROR, this, "Invalid data received from the Telegram API." );
} catch( std::runtime_error ex_ ) {
g_logger->log( Logger::LogLevel::ERROR, this, ex_.what() );
}
connection_->flags |= MG_F_CLOSE_IMMEDIATELY;
}
} ), params );
return true;
}
}
return false;
};
json Telegram::getJson( bool full_ ) const {
json result = Hardware::getJson( full_ );
result["username"] = this->m_settings->get( "username", "" );
result["token"] = this->m_settings->get( "token", "" );
if ( full_ ) {
result["settings"] = this->getSettingsJson();
}
return result;
};
json Telegram::getSettingsJson() const {
json result = Hardware::getSettingsJson();
result += {
{ "name", "username" },
{ "label", "Username" },
{ "type", "string" },
{ "class", this->m_settings->contains( "username" ) ? "advanced" : "normal" },
{ "mandatory", true },
{ "sort", 97 }
};
result += {
{ "name", "token" },
{ "label", "Token" },
{ "type", "string" },
{ "class", this->m_settings->contains( "token" ) ? "advanced" : "normal" },
{ "mandatory", true },
{ "sort", 98 }
};
return result;
};
void Telegram::_processIncomingMessage( const json& message_ ) {
auto find = message_.find( "chat" );
if ( find != message_.end() ) {
std::string reference = jsonGet<std::string>( *find, "id" );
auto device = std::static_pointer_cast<Text>( this->getDevice( reference ) );
if (
device == nullptr
&& this->m_acceptMode
) {
std::stringstream label;
if ( (*find).find( "first_name" ) != (*find).end() ) {
label << (*find)["first_name"].get<std::string>();
}
if ( (*find).find( "last_name" ) != (*find).end() ) {
if ( label.str().size() > 0 ) {
label << " ";
}
label << (*find)["last_name"].get<std::string>();
}
if ( (*find).find( "username" ) != (*find).end() ) {
if ( label.str().size() > 0 ) {
label << " (" << (*find)["username"].get<std::string>() << ")";
} else {
label << (*find)["username"].get<std::string>();
}
}
if ( label.str().size() == 0 ) {
label << reference;
}
device = this->declareDevice<Text>( reference, label.str(), {
{ DEVICE_SETTING_ALLOWED_UPDATE_SOURCES, Device::resolveUpdateSource( Device::UpdateSource::ANY ) },
{ DEVICE_SETTING_DEFAULT_SUBTYPE, Text::resolveSubType( Text::SubType::NOTIFICATION ) }
} );
}
if (
device != nullptr
&& message_.find( "text" ) != message_.end()
) {
device->updateValue( Device::UpdateSource::HARDWARE, message_["text"].get<std::string>() );
}
}
};
}; // namespace micasa
<commit_msg>fixed broadcasting<commit_after>// https://core.telegram.org/bots/api#making-requests
#include "../Logger.h"
#include "../Network.h"
#include "../User.h"
#include "../device/Switch.h"
#include "../device/Text.h"
#include "Telegram.h"
namespace micasa {
extern std::shared_ptr<Logger> g_logger;
extern std::shared_ptr<Network> g_network;
using namespace nlohmann;
void Telegram::start() {
g_logger->log( Logger::LogLevel::VERBOSE, this, "Starting..." );
Hardware::start();
// Add the devices that will initiate controller actions and the broadcast device.
this->declareDevice<Switch>( "accept", "Enable Accept Mode", {
{ DEVICE_SETTING_ALLOWED_UPDATE_SOURCES, Device::resolveUpdateSource( Device::UpdateSource::CONTROLLER | Device::UpdateSource::API ) },
{ DEVICE_SETTING_DEFAULT_SUBTYPE, Switch::resolveSubType( Switch::SubType::ACTION ) },
{ DEVICE_SETTING_MINIMUM_USER_RIGHTS, User::resolveRights( User::Rights::INSTALLER ) }
} )->updateValue( Device::UpdateSource::INIT | Device::UpdateSource::HARDWARE, Switch::Option::IDLE );
this->declareDevice<Text>( "broadcast", "Broadcast", {
{ DEVICE_SETTING_ALLOWED_UPDATE_SOURCES, Device::resolveUpdateSource( Device::UpdateSource::ANY ) },
{ DEVICE_SETTING_DEFAULT_SUBTYPE, Text::resolveSubType( Text::SubType::NOTIFICATION ) }
} );
};
void Telegram::stop() {
g_logger->log( Logger::LogLevel::VERBOSE, this, "Stopping..." );
Hardware::stop();
};
std::chrono::milliseconds Telegram::_work( const unsigned long int& iteration_ ) {
if ( ! this->m_settings->contains( { "username", "token" } ) ) {
g_logger->log( Logger::LogLevel::ERROR, this, "Missing settings." );
this->setState( Hardware::State::FAILED );
return std::chrono::milliseconds( 60 * 1000 );
}
std::stringstream url;
url << "https://api.telegram.org/bot" << this->m_settings->get( "token" ) << "/getUpdates";
json params = {
{ "timeout", 60 }
};
if ( this->m_lastUpdateId > -1 ) {
params["offset"] = this->m_lastUpdateId + 1;
}
this->setState( Hardware::State::READY );
g_network->connect( url.str(), Network::t_callback( [this]( mg_connection* connection_, int event_, void* data_ ) {
if ( event_ == MG_EV_HTTP_REPLY ) {
// See if a valid response was received from the Telegram API. It should be json encoded data with an
// "ok" property set to a boolean true.
std::string body;
body.assign( ((http_message*)data_)->body.p, ((http_message*)data_)->body.len );
try {
json data = json::parse( body );
bool success = data["ok"].get<bool>();
if ( ! success ) {
throw std::runtime_error( "Telegram API reported a failure" );
}
auto find = data.find( "result" );
if (
find != data.end()
&& (*find).is_array()
) {
for ( auto updateIt = (*find).begin(); updateIt != (*find).end(); updateIt++ ) {
int lastUpdateId = jsonGet<int>( *updateIt, "update_id" );
if ( lastUpdateId > this->m_lastUpdateId ) {
this->m_lastUpdateId = lastUpdateId;
}
if ( (*updateIt).find( "message" ) != (*updateIt).end() ) {
this->_processIncomingMessage( (*updateIt)["message"] );
}
}
}
} catch( std::invalid_argument ex_ ) {
g_logger->log( Logger::LogLevel::ERROR, this, "Invalid data received from the Telegram API." );
this->setState( Hardware::State::FAILED );
} catch( std::runtime_error ex_ ) {
g_logger->log( Logger::LogLevel::ERROR, this, ex_.what() );
this->setState( Hardware::State::FAILED );
}
connection_->flags |= MG_F_CLOSE_IMMEDIATELY;
} else if ( event_ == MG_EV_CLOSE ) {
// If a successfull response was received, a new connection needs to be made immediately (long poll),
// if not, try the Telegram API again after the default of 5 minutes.
if ( this->getState() == Hardware::State::READY ) {
this->wakeUp();
}
}
} ), params );
return std::chrono::milliseconds( 1000 * 60 * 5 );
};
bool Telegram::updateDevice( const Device::UpdateSource& source_, std::shared_ptr<Device> device_, bool& apply_ ) {
if ( this->getState() == Hardware::State::READY ) {
if ( device_->getType() == Device::Type::SWITCH ) {
// This part takes care of temprarely enabling the accept new chats mode.
std::shared_ptr<Switch> device = std::static_pointer_cast<Switch>( device_ );
if (
device->getReference() == "accept"
&& device->getValueOption() == Switch::Option::ACTIVATE
) {
if ( this->m_acceptMode ) {
g_logger->log( Logger::LogLevel::ERROR, this, "Accept Mode already enabled." );
} else {
g_logger->log( Logger::LogLevel::NORMAL, this, "Accept Mode enabled." );
this->m_acceptMode = true;
std::thread( [this, device]{
std::this_thread::sleep_for( std::chrono::minutes( 60 * 5 ) );
this->m_acceptMode = false;
device->updateValue( Device::UpdateSource::HARDWARE, Switch::Option::IDLE );
g_logger->log( Logger::LogLevel::VERBOSE, this, "Accept Mode disabled." );
} ).detach();
}
return true;
}
} else if ( device_->getType() == Device::Type::TEXT ) {
// A message can be sent to a single device (=chat) or to the broadcast device, in which case it is send
// to all chat devices.
std::vector<std::shared_ptr<Device> > devices;
if ( device_->getReference() == "broadcast" ) {
auto allDevices = this->getAllDevices();
for ( auto deviceIt = allDevices.begin(); deviceIt != allDevices.end(); deviceIt++ ) {
if (
(*deviceIt)->getType() == Device::Type::TEXT
&& (*deviceIt)->getReference() != "broadcast"
) {
devices.push_back( *deviceIt );
}
}
} else {
devices.push_back( device_ );
}
for ( auto deviceIt = devices.begin(); deviceIt != devices.end(); deviceIt++ ) {
std::shared_ptr<Text> device = std::static_pointer_cast<Text>( *deviceIt );
std::stringstream url;
url << "https://api.telegram.org/bot" << this->m_settings->get( "token" ) << "/sendMessage";
json params = {
{ "chat_id", std::stoi( device->getReference() ) },
{ "text", std::static_pointer_cast<Text>( device_ )->getValue() },
{ "parse_mode", "Markdown" }
};
g_network->connect( url.str(), Network::t_callback( [this]( mg_connection* connection_, int event_, void* data_ ) {
if ( event_ == MG_EV_HTTP_REPLY ) {
// See if a valid response was received from the Telegram API.
std::string body;
body.assign( ((http_message*)data_)->body.p, ((http_message*)data_)->body.len );
try {
json data = json::parse( body );
bool success = data["ok"].get<bool>();
if ( ! success ) {
throw std::runtime_error( "Telegram API reported a failure" );
}
} catch( std::invalid_argument ex_ ) {
g_logger->log( Logger::LogLevel::ERROR, this, "Invalid data received from the Telegram API." );
} catch( std::runtime_error ex_ ) {
g_logger->log( Logger::LogLevel::ERROR, this, ex_.what() );
}
connection_->flags |= MG_F_CLOSE_IMMEDIATELY;
}
} ), params );
}
return true;
}
}
return false;
};
json Telegram::getJson( bool full_ ) const {
json result = Hardware::getJson( full_ );
result["username"] = this->m_settings->get( "username", "" );
result["token"] = this->m_settings->get( "token", "" );
if ( full_ ) {
result["settings"] = this->getSettingsJson();
}
return result;
};
json Telegram::getSettingsJson() const {
json result = Hardware::getSettingsJson();
result += {
{ "name", "username" },
{ "label", "Username" },
{ "type", "string" },
{ "class", this->m_settings->contains( "username" ) ? "advanced" : "normal" },
{ "mandatory", true },
{ "sort", 97 }
};
result += {
{ "name", "token" },
{ "label", "Token" },
{ "type", "string" },
{ "class", this->m_settings->contains( "token" ) ? "advanced" : "normal" },
{ "mandatory", true },
{ "sort", 98 }
};
return result;
};
void Telegram::_processIncomingMessage( const json& message_ ) {
auto find = message_.find( "chat" );
if ( find != message_.end() ) {
std::string reference = jsonGet<std::string>( *find, "id" );
auto device = std::static_pointer_cast<Text>( this->getDevice( reference ) );
if (
device == nullptr
&& this->m_acceptMode
) {
std::stringstream label;
if ( (*find).find( "first_name" ) != (*find).end() ) {
label << (*find)["first_name"].get<std::string>();
}
if ( (*find).find( "last_name" ) != (*find).end() ) {
if ( label.str().size() > 0 ) {
label << " ";
}
label << (*find)["last_name"].get<std::string>();
}
if ( (*find).find( "username" ) != (*find).end() ) {
if ( label.str().size() > 0 ) {
label << " (" << (*find)["username"].get<std::string>() << ")";
} else {
label << (*find)["username"].get<std::string>();
}
}
if ( label.str().size() == 0 ) {
label << reference;
}
device = this->declareDevice<Text>( reference, label.str(), {
{ DEVICE_SETTING_ALLOWED_UPDATE_SOURCES, Device::resolveUpdateSource( Device::UpdateSource::ANY ) },
{ DEVICE_SETTING_DEFAULT_SUBTYPE, Text::resolveSubType( Text::SubType::NOTIFICATION ) }
} );
}
if (
device != nullptr
&& message_.find( "text" ) != message_.end()
) {
device->updateValue( Device::UpdateSource::HARDWARE, message_["text"].get<std::string>() );
}
}
};
}; // namespace micasa
<|endoftext|>
|
<commit_before>
#include <memory>
#include <jsapi.h>
#ifndef MOZJS_MAJOR_VERSION
#include <jsversion.h>
#endif
#include <QtCore>
#include "webqq_calljs.hpp"
static JSClass global_class = {
"global",
JSCLASS_GLOBAL_FLAGS|JSCLASS_NEW_RESOLVE,
JS_PropertyStub,
#ifdef MOZJS_MAJOR_VERSION
JS_DeletePropertyStub,
#else
JS_PropertyStub,
#endif
JS_PropertyStub,
JS_StrictPropertyStub,
JS_EnumerateStub,
JS_ResolveStub,
JS_ConvertStub,
NULL,
JSCLASS_NO_OPTIONAL_MEMBERS
};
std::string webqq::qqimpl::call_js_helper_function_in_buffer(const char* js_content, int js_content_length, std::string helper_file, std::string function, std::vector< std::string > args)
{
#if MOZJS_MAJOR_VERSION >= 24
std::shared_ptr<JSRuntime> jsrt{ JS_NewRuntime(1024*1024*10, JS_NO_HELPER_THREADS) , JS_DestroyRuntime};
#else
std::shared_ptr<JSRuntime> jsrt{ JS_NewRuntime(1024*1024*10) , JS_DestroyRuntime};
#endif
std::shared_ptr<JSContext> jsctx{ JS_NewContext(jsrt.get(), 16*1024) , JS_DestroyContext};
JS_SetOptions(jsctx.get(), JSOPTION_VAROBJFIX|JSOPTION_COMPILE_N_GO|JSOPTION_NO_SCRIPT_RVAL);
#if JS_VERSION == 185
JSObject* global_object = JS_NewCompartmentAndGlobalObject(jsctx.get(), &global_class, NULL);
#else
JSObject* global_object = JS_NewGlobalObject(jsctx.get(), &global_class, NULL);
#endif
JS_InitStandardClasses(jsctx.get(), global_object);
#if JS_VERSION == 185
JSObject * script
#else
JSScript * script
#endif
= JS_CompileScript(jsctx.get(), global_object, js_content, js_content_length, helper_file.c_str(), 0);
JS_ExecuteScript(jsctx.get(), global_object, script, NULL);
jsval res;
std::vector<jsval> argv;
char* res_;
for (auto _a : args)
{
JSString* js_arg = JS_NewStringCopyN(jsctx.get(), _a.c_str(), _a.length());
argv.push_back(STRING_TO_JSVAL(js_arg));
}
JS_CallFunctionName(jsctx.get(), global_object, function.c_str(), argv.size(), argv.data(), &res);
res_ = JS_EncodeString(jsctx.get(),JSVAL_TO_STRING(res));
std::string ret = res_;
JS_free(jsctx.get(),res_);
return ret;
}
std::string webqq::qqimpl::call_js_helper_function(std::string helper_file, std::string function, std::vector< std::string > args)
{
QFile helperfile(helper_file.c_str());
helperfile.open(QIODevice::ReadOnly);
auto js_content = helperfile.readAll();
return call_js_helper_function_in_buffer(js_content.constData(), js_content.length(), helper_file, function, args);
}
<commit_msg>fix compatibility with mozjs-24<commit_after>
#include <memory>
#include <jsapi.h>
#ifndef MOZJS_MAJOR_VERSION
#include <jsversion.h>
#endif
#include <QtCore>
#include "webqq_calljs.hpp"
static JSClass global_class = {
"global",
JSCLASS_GLOBAL_FLAGS|JSCLASS_NEW_RESOLVE,
JS_PropertyStub,
#ifdef MOZJS_MAJOR_VERSION
JS_DeletePropertyStub,
#else
JS_PropertyStub,
#endif
JS_PropertyStub,
JS_StrictPropertyStub,
JS_EnumerateStub,
JS_ResolveStub,
JS_ConvertStub,
NULL,
JSCLASS_NO_OPTIONAL_MEMBERS
};
std::string webqq::qqimpl::call_js_helper_function_in_buffer(const char* js_content, int js_content_length, std::string helper_file, std::string function, std::vector< std::string > args)
{
#if MOZJS_MAJOR_VERSION >= 24
std::shared_ptr<JSRuntime> jsrt{ JS_NewRuntime(1024*1024*10, JS_NO_HELPER_THREADS) , JS_DestroyRuntime};
#else
std::shared_ptr<JSRuntime> jsrt{ JS_NewRuntime(1024*1024*10) , JS_DestroyRuntime};
#endif
std::shared_ptr<JSContext> jsctx{ JS_NewContext(jsrt.get(), 16*1024) , JS_DestroyContext};
JS_SetOptions(jsctx.get(), JS_GetOptions(jsctx.get()) |JSOPTION_VAROBJFIX|JSOPTION_COMPILE_N_GO|JSOPTION_NO_SCRIPT_RVAL);
#if JS_VERSION == 185
JSObject* global_object = JS_NewCompartmentAndGlobalObject(jsctx.get(), &global_class, NULL);
#else
JS::CompartmentOptions options;
options.setVersion(JSVERSION_LATEST);
JSObject* global_object = JS_NewGlobalObject(jsctx.get(), &global_class, NULL, options);
JSAutoCompartment ac(jsctx.get(), global_object);
#endif
JS_SetGlobalObject(jsctx.get(), global_object);
JS_InitStandardClasses(jsctx.get(), global_object);
#if JS_VERSION == 185
JSObject * script
#else
JSScript * script
#endif
= JS_CompileScript(jsctx.get(), global_object, js_content, js_content_length, helper_file.c_str(), 0);
JS_ExecuteScript(jsctx.get(), global_object, script, NULL);
jsval res;
std::vector<jsval> argv;
char* res_;
for (auto _a : args)
{
JSString* js_arg = JS_NewStringCopyN(jsctx.get(), _a.c_str(), _a.length());
argv.push_back(STRING_TO_JSVAL(js_arg));
}
JS_CallFunctionName(jsctx.get(), global_object, function.c_str(), argv.size(), argv.data(), &res);
res_ = JS_EncodeString(jsctx.get(),JSVAL_TO_STRING(res));
std::string ret = res_;
JS_free(jsctx.get(),res_);
return ret;
}
std::string webqq::qqimpl::call_js_helper_function(std::string helper_file, std::string function, std::vector< std::string > args)
{
QFile helperfile(helper_file.c_str());
helperfile.open(QIODevice::ReadOnly);
auto js_content = helperfile.readAll();
return call_js_helper_function_in_buffer(js_content.constData(), js_content.length(), helper_file, function, args);
}
<|endoftext|>
|
<commit_before>#include <sstream>
#include <rclcpp/rclcpp.hpp>
#include <std_msgs/String.h>
#include "std_msgs/dds_impl/String_convert.h"
#include <rclcpp/publisher/publisher.hpp>
int main(int argc, char** argv)
{
rclcpp::init(argc, argv);
auto node = rclcpp::create_node("talker");
auto publisher = node->create_publisher<std_msgs::String>("chatter", 0);
std_msgs::String msg;
int count = 0;
while(node->is_running())
{
std::stringstream ss;
ss << "[" << count++ << "]: Hello World!";
msg.data = ss.str();
publisher->publish(msg);
sleep(1);
}
}
<commit_msg>Removed unused header<commit_after>#include <sstream>
#include <rclcpp/rclcpp.hpp>
#include <std_msgs/String.h>
#include "std_msgs/dds_impl/String_convert.h"
int main(int argc, char** argv)
{
rclcpp::init(argc, argv);
auto node = rclcpp::create_node("talker");
auto publisher = node->create_publisher<std_msgs::String>("chatter", 0);
std_msgs::String msg;
int count = 0;
while(node->is_running())
{
std::stringstream ss;
ss << "[" << count++ << "]: Hello World!";
msg.data = ss.str();
publisher->publish(msg);
sleep(1);
}
}
<|endoftext|>
|
<commit_before>/** @file
A brief file description
@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.
*/
#include <yaml-cpp/yaml.h>
#include "I_Machine.h"
#include "NextHopSelectionStrategy.h"
// ring mode strings
constexpr std::string_view alternate_rings = "alternate_ring";
constexpr std::string_view exhaust_rings = "exhaust_ring";
// health check strings
constexpr std::string_view active_health_check = "active";
constexpr std::string_view passive_health_check = "passive";
constexpr const char *policy_strings[] = {"NH_UNDEFINED", "NH_FIRST_LIVE", "NH_RR_STRICT",
"NH_RR_IP", "NH_RR_LATCHED", "NH_CONSISTENT_HASH"};
NextHopSelectionStrategy::NextHopSelectionStrategy(const std::string_view &name, const NHPolicyType &policy)
{
strategy_name = name;
policy_type = policy;
NH_Debug(NH_DEBUG_TAG, "Using a selection strategy of type %s", policy_strings[policy]);
}
//
// parse out the data for this strategy.
//
bool
NextHopSelectionStrategy::Init(const YAML::Node &n)
{
NH_Debug(NH_DEBUG_TAG, "calling Init()");
try {
if (n["scheme"]) {
auto scheme_val = n["scheme"].Scalar();
if (scheme_val == "http") {
scheme = NH_SCHEME_HTTP;
} else if (scheme_val == "https") {
scheme = NH_SCHEME_HTTPS;
} else {
scheme = NH_SCHEME_NONE;
NH_Note("Invalid 'scheme' value, '%s', for the strategy named '%s', setting to NH_SCHEME_NONE", scheme_val.c_str(),
strategy_name.c_str());
}
}
// go_direct config.
if (n["go_direct"]) {
go_direct = n["go_direct"].as<bool>();
}
// parent_is_proxy config.
if (n["parent_is_proxy"]) {
parent_is_proxy = n["parent_is_proxy"].as<bool>();
}
// ignore_self_detect
if (n["ignore_self_detect"]) {
ignore_self_detect = n["ignore_self_detect"].as<bool>();
}
// failover node.
YAML::Node failover_node;
if (n["failover"]) {
failover_node = n["failover"];
if (failover_node["ring_mode"]) {
auto ring_mode_val = failover_node["ring_mode"].Scalar();
if (ring_mode_val == alternate_rings) {
ring_mode = NH_ALTERNATE_RING;
} else if (ring_mode_val == exhaust_rings) {
ring_mode = NH_EXHAUST_RING;
} else {
ring_mode = NH_ALTERNATE_RING;
NH_Note("Invalid 'ring_mode' value, '%s', for the strategy named '%s', using default '%s'.", ring_mode_val.c_str(),
strategy_name.c_str(), alternate_rings.data());
}
}
if (failover_node["max_simple_retries"]) {
max_simple_retries = failover_node["max_simple_retries"].as<int>();
}
YAML::Node resp_codes_node;
if (failover_node["response_codes"]) {
resp_codes_node = failover_node["response_codes"];
if (resp_codes_node.Type() != YAML::NodeType::Sequence) {
NH_Error("Error in the response_codes definition for the strategy named '%s', skipping response_codes.",
strategy_name.c_str());
} else {
for (unsigned int k = 0; k < resp_codes_node.size(); ++k) {
auto code = resp_codes_node[k].as<int>();
if (code > 300 && code < 599) {
resp_codes.add(code);
} else {
NH_Note("Skipping invalid response code '%d' for the strategy named '%s'.", code, strategy_name.c_str());
}
}
resp_codes.sort();
}
}
YAML::Node health_check_node;
if (failover_node["health_check"]) {
health_check_node = failover_node["health_check"];
if (health_check_node.Type() != YAML::NodeType::Sequence) {
NH_Error("Error in the health_check definition for the strategy named '%s', skipping health_checks.",
strategy_name.c_str());
} else {
for (auto it = health_check_node.begin(); it != health_check_node.end(); ++it) {
auto health_check = it->as<std::string>();
if (health_check.compare(active_health_check) == 0) {
health_checks.active = true;
}
if (health_check.compare(passive_health_check) == 0) {
health_checks.passive = true;
}
}
}
}
}
// parse and load the host data
YAML::Node groups_node;
if (n["groups"]) {
groups_node = n["groups"];
// a groups list is required.
if (groups_node.Type() != YAML::NodeType::Sequence) {
throw std::invalid_argument("Invalid groups definition, expected a sequence, '" + strategy_name + "' cannot be loaded.");
} else {
Machine *mach = Machine::instance();
HostStatus &h_stat = HostStatus::instance();
uint32_t grp_size = groups_node.size();
if (grp_size > MAX_GROUP_RINGS) {
NH_Note("the groups list exceeds the maximum of %d for the strategy '%s'. Only the first %d groups will be configured.",
MAX_GROUP_RINGS, strategy_name.c_str(), MAX_GROUP_RINGS);
groups = MAX_GROUP_RINGS;
} else {
groups = groups_node.size();
}
// resize the hosts vector.
host_groups.reserve(groups);
// loop through the groups
for (unsigned int grp = 0; grp < groups; ++grp) {
YAML::Node hosts_list = groups_node[grp];
// a list of hosts is required.
if (hosts_list.Type() != YAML::NodeType::Sequence) {
throw std::invalid_argument("Invalid hosts definition, expected a sequence, '" + strategy_name + "' cannot be loaded.");
} else {
// loop through the hosts list.
std::vector<std::shared_ptr<HostRecord>> hosts_inner;
for (unsigned int hst = 0; hst < hosts_list.size(); ++hst) {
std::shared_ptr<HostRecord> host_rec = std::make_shared<HostRecord>(hosts_list[hst].as<HostRecord>());
host_rec->group_index = grp;
host_rec->host_index = hst;
if (mach->is_self(host_rec->hostname.c_str())) {
h_stat.setHostStatus(host_rec->hostname.c_str(), HostStatus_t::HOST_STATUS_DOWN, 0, Reason::SELF_DETECT);
}
hosts_inner.push_back(std::move(host_rec));
num_parents++;
}
host_groups.push_back(std::move(hosts_inner));
}
}
}
}
} catch (std::exception &ex) {
NH_Note("Error parsing the strategy named '%s' due to '%s', this strategy will be ignored.", strategy_name.c_str(), ex.what());
return false;
}
return true;
}
void
NextHopSelectionStrategy::markNextHopDown(const uint64_t sm_id, ParentResult &result, const uint64_t fail_threshold,
const uint64_t retry_time, time_t now)
{
time_t _now;
now == 0 ? _now = time(nullptr) : _now = now;
uint32_t new_fail_count = 0;
// Make sure that we are being called back with with a
// result structure with a selected parent.
if (result.result != PARENT_SPECIFIED) {
return;
}
// If we were set through the API we currently have not failover
// so just return fail
if (result.is_api_result()) {
ink_assert(0);
return;
}
uint32_t hst_size = host_groups[result.last_group].size();
ink_assert(result.last_parent < hst_size);
std::shared_ptr<HostRecord> h = host_groups[result.last_group][result.last_parent];
// If the parent has already been marked down, just increment
// the failure count. If this is the first mark down on a
// parent we need to both set the failure time and set
// count to one. If this was the result of a retry, we
// must update move the failedAt timestamp to now so that we
// continue negative cache the parent
if (h->failedAt == 0 || result.retry == true) {
{ // start of lock_guard scope.
std::lock_guard<std::mutex> lock(h->_mutex);
if (h->failedAt == 0) {
// Mark the parent failure time.
h->failedAt = _now;
if (result.retry == false) {
new_fail_count = h->failCount = 1;
}
} else if (result.retry == true) {
h->failedAt = _now;
}
} // end of lock_guard scope
NH_Note("[%" PRIu64 "] NextHop %s marked as down %s:%d", sm_id, (result.retry) ? "retry" : "initially", h->hostname.c_str(),
h->getPort(scheme));
} else {
int old_count = 0;
// if the last failure was outside the retry window, set the failcount to 1 and failedAt to now.
{ // start of lock_guard_scope
std::lock_guard<std::mutex> lock(h->_mutex);
if ((h->failedAt + retry_time) < static_cast<unsigned>(_now)) {
h->failCount = 1;
h->failedAt = _now;
} else {
old_count = h->failCount = 1;
}
new_fail_count = old_count + 1;
} // end of lock_guard
NH_Debug("parent_select", "[%" PRIu64 "] Parent fail count increased to %d for %s:%d", sm_id, new_fail_count,
h->hostname.c_str(), h->getPort(scheme));
}
if (new_fail_count >= fail_threshold) {
h->set_unavailable();
NH_Note("[%" PRIu64 "] Failure threshold met failcount:%d >= threshold:%" PRIu64 ", http parent proxy %s:%d marked down", sm_id,
new_fail_count, fail_threshold, h->hostname.c_str(), h->getPort(scheme));
NH_Debug("parent_select", "[%" PRIu64 "] NextHop %s:%d marked unavailable, h->available=%s", sm_id, h->hostname.c_str(),
h->getPort(scheme), (h->available) ? "true" : "false");
}
}
void
NextHopSelectionStrategy::markNextHopUp(const uint64_t sm_id, ParentResult &result)
{
uint32_t old_count = 0;
// Make sure that we are being called back with with a
// result structure with a parent that is being retried
ink_assert(result.retry == true);
if (result.result != PARENT_SPECIFIED) {
return;
}
// If we were set through the API we currently have not failover
// so just return fail
if (result.is_api_result()) {
ink_assert(0);
return;
}
uint32_t hst_size = host_groups[result.last_group].size();
ink_assert(result.last_parent < hst_size);
std::shared_ptr<HostRecord> h = host_groups[result.last_group][result.last_parent];
if (!h->available) {
h->set_available();
}
if (h->available && old_count > 0) {
NH_Note("[%" PRIu64 "] http parent proxy %s:%d restored", sm_id, h->hostname.c_str(), h->getPort(scheme));
}
}
namespace YAML
{
template <> struct convert<HostRecord> {
static bool
decode(const Node &node, HostRecord &nh)
{
YAML::Node nd;
bool merge_tag_used = false;
// check for YAML merge tag.
if (node["<<"]) {
nd = node["<<"];
merge_tag_used = true;
} else {
nd = node;
}
// lookup the hostname
if (nd["host"]) {
nh.hostname = nd["host"].Scalar();
} else {
throw std::invalid_argument("Invalid host definition, missing host name.");
}
// lookup the port numbers supported by this host.
YAML::Node proto = nd["protocol"];
if (proto.Type() != YAML::NodeType::Sequence) {
throw std::invalid_argument("Invalid host protocol definition, expected a sequence.");
} else {
for (unsigned int ii = 0; ii < proto.size(); ii++) {
YAML::Node protocol_node = proto[ii];
std::shared_ptr<NHProtocol> pr = std::make_shared<NHProtocol>(protocol_node.as<NHProtocol>());
nh.protocols.push_back(std::move(pr));
}
}
// get the host's weight
YAML::Node weight;
if (merge_tag_used) {
weight = node["weight"];
nh.weight = weight.as<float>();
} else if ((weight = nd["weight"])) {
nh.weight = weight.as<float>();
} else {
NH_Note("No weight is defined for the host '%s', using default 1.0", nh.hostname.data());
nh.weight = 1.0;
}
// get the host's optional hash_string
YAML::Node hash;
if ((hash = nd["hash_string"])) {
nh.hash_string = hash.Scalar();
}
return true;
}
};
template <> struct convert<NHProtocol> {
static bool
decode(const Node &node, NHProtocol &nh)
{
if (node["scheme"]) {
if (node["scheme"].Scalar() == "http") {
nh.scheme = NH_SCHEME_HTTP;
} else if (node["scheme"].Scalar() == "https") {
nh.scheme = NH_SCHEME_HTTPS;
} else {
nh.scheme = NH_SCHEME_NONE;
}
}
if (node["port"]) {
nh.port = node["port"].as<int>();
}
if (node["health_check_url"]) {
nh.health_check_url = node["health_check_url"].Scalar();
}
return true;
}
};
}; // namespace YAML
// namespace YAML
<commit_msg>LGTM: fix a comparison that is always false.<commit_after>/** @file
A brief file description
@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.
*/
#include <yaml-cpp/yaml.h>
#include "I_Machine.h"
#include "NextHopSelectionStrategy.h"
// ring mode strings
constexpr std::string_view alternate_rings = "alternate_ring";
constexpr std::string_view exhaust_rings = "exhaust_ring";
// health check strings
constexpr std::string_view active_health_check = "active";
constexpr std::string_view passive_health_check = "passive";
constexpr const char *policy_strings[] = {"NH_UNDEFINED", "NH_FIRST_LIVE", "NH_RR_STRICT",
"NH_RR_IP", "NH_RR_LATCHED", "NH_CONSISTENT_HASH"};
NextHopSelectionStrategy::NextHopSelectionStrategy(const std::string_view &name, const NHPolicyType &policy)
{
strategy_name = name;
policy_type = policy;
NH_Debug(NH_DEBUG_TAG, "Using a selection strategy of type %s", policy_strings[policy]);
}
//
// parse out the data for this strategy.
//
bool
NextHopSelectionStrategy::Init(const YAML::Node &n)
{
NH_Debug(NH_DEBUG_TAG, "calling Init()");
try {
if (n["scheme"]) {
auto scheme_val = n["scheme"].Scalar();
if (scheme_val == "http") {
scheme = NH_SCHEME_HTTP;
} else if (scheme_val == "https") {
scheme = NH_SCHEME_HTTPS;
} else {
scheme = NH_SCHEME_NONE;
NH_Note("Invalid 'scheme' value, '%s', for the strategy named '%s', setting to NH_SCHEME_NONE", scheme_val.c_str(),
strategy_name.c_str());
}
}
// go_direct config.
if (n["go_direct"]) {
go_direct = n["go_direct"].as<bool>();
}
// parent_is_proxy config.
if (n["parent_is_proxy"]) {
parent_is_proxy = n["parent_is_proxy"].as<bool>();
}
// ignore_self_detect
if (n["ignore_self_detect"]) {
ignore_self_detect = n["ignore_self_detect"].as<bool>();
}
// failover node.
YAML::Node failover_node;
if (n["failover"]) {
failover_node = n["failover"];
if (failover_node["ring_mode"]) {
auto ring_mode_val = failover_node["ring_mode"].Scalar();
if (ring_mode_val == alternate_rings) {
ring_mode = NH_ALTERNATE_RING;
} else if (ring_mode_val == exhaust_rings) {
ring_mode = NH_EXHAUST_RING;
} else {
ring_mode = NH_ALTERNATE_RING;
NH_Note("Invalid 'ring_mode' value, '%s', for the strategy named '%s', using default '%s'.", ring_mode_val.c_str(),
strategy_name.c_str(), alternate_rings.data());
}
}
if (failover_node["max_simple_retries"]) {
max_simple_retries = failover_node["max_simple_retries"].as<int>();
}
YAML::Node resp_codes_node;
if (failover_node["response_codes"]) {
resp_codes_node = failover_node["response_codes"];
if (resp_codes_node.Type() != YAML::NodeType::Sequence) {
NH_Error("Error in the response_codes definition for the strategy named '%s', skipping response_codes.",
strategy_name.c_str());
} else {
for (unsigned int k = 0; k < resp_codes_node.size(); ++k) {
auto code = resp_codes_node[k].as<int>();
if (code > 300 && code < 599) {
resp_codes.add(code);
} else {
NH_Note("Skipping invalid response code '%d' for the strategy named '%s'.", code, strategy_name.c_str());
}
}
resp_codes.sort();
}
}
YAML::Node health_check_node;
if (failover_node["health_check"]) {
health_check_node = failover_node["health_check"];
if (health_check_node.Type() != YAML::NodeType::Sequence) {
NH_Error("Error in the health_check definition for the strategy named '%s', skipping health_checks.",
strategy_name.c_str());
} else {
for (auto it = health_check_node.begin(); it != health_check_node.end(); ++it) {
auto health_check = it->as<std::string>();
if (health_check.compare(active_health_check) == 0) {
health_checks.active = true;
}
if (health_check.compare(passive_health_check) == 0) {
health_checks.passive = true;
}
}
}
}
}
// parse and load the host data
YAML::Node groups_node;
if (n["groups"]) {
groups_node = n["groups"];
// a groups list is required.
if (groups_node.Type() != YAML::NodeType::Sequence) {
throw std::invalid_argument("Invalid groups definition, expected a sequence, '" + strategy_name + "' cannot be loaded.");
} else {
Machine *mach = Machine::instance();
HostStatus &h_stat = HostStatus::instance();
uint32_t grp_size = groups_node.size();
if (grp_size > MAX_GROUP_RINGS) {
NH_Note("the groups list exceeds the maximum of %d for the strategy '%s'. Only the first %d groups will be configured.",
MAX_GROUP_RINGS, strategy_name.c_str(), MAX_GROUP_RINGS);
groups = MAX_GROUP_RINGS;
} else {
groups = groups_node.size();
}
// resize the hosts vector.
host_groups.reserve(groups);
// loop through the groups
for (unsigned int grp = 0; grp < groups; ++grp) {
YAML::Node hosts_list = groups_node[grp];
// a list of hosts is required.
if (hosts_list.Type() != YAML::NodeType::Sequence) {
throw std::invalid_argument("Invalid hosts definition, expected a sequence, '" + strategy_name + "' cannot be loaded.");
} else {
// loop through the hosts list.
std::vector<std::shared_ptr<HostRecord>> hosts_inner;
for (unsigned int hst = 0; hst < hosts_list.size(); ++hst) {
std::shared_ptr<HostRecord> host_rec = std::make_shared<HostRecord>(hosts_list[hst].as<HostRecord>());
host_rec->group_index = grp;
host_rec->host_index = hst;
if (mach->is_self(host_rec->hostname.c_str())) {
h_stat.setHostStatus(host_rec->hostname.c_str(), HostStatus_t::HOST_STATUS_DOWN, 0, Reason::SELF_DETECT);
}
hosts_inner.push_back(std::move(host_rec));
num_parents++;
}
host_groups.push_back(std::move(hosts_inner));
}
}
}
}
} catch (std::exception &ex) {
NH_Note("Error parsing the strategy named '%s' due to '%s', this strategy will be ignored.", strategy_name.c_str(), ex.what());
return false;
}
return true;
}
void
NextHopSelectionStrategy::markNextHopDown(const uint64_t sm_id, ParentResult &result, const uint64_t fail_threshold,
const uint64_t retry_time, time_t now)
{
time_t _now;
now == 0 ? _now = time(nullptr) : _now = now;
uint32_t new_fail_count = 0;
// Make sure that we are being called back with with a
// result structure with a selected parent.
if (result.result != PARENT_SPECIFIED) {
return;
}
// If we were set through the API we currently have not failover
// so just return fail
if (result.is_api_result()) {
ink_assert(0);
return;
}
uint32_t hst_size = host_groups[result.last_group].size();
ink_assert(result.last_parent < hst_size);
std::shared_ptr<HostRecord> h = host_groups[result.last_group][result.last_parent];
// If the parent has already been marked down, just increment
// the failure count. If this is the first mark down on a
// parent we need to both set the failure time and set
// count to one. If this was the result of a retry, we
// must update move the failedAt timestamp to now so that we
// continue negative cache the parent
if (h->failedAt == 0 || result.retry == true) {
{ // start of lock_guard scope.
std::lock_guard<std::mutex> lock(h->_mutex);
if (h->failedAt == 0) {
// Mark the parent failure time.
h->failedAt = _now;
if (result.retry == false) {
new_fail_count = h->failCount = 1;
}
} else if (result.retry == true) {
h->failedAt = _now;
}
} // end of lock_guard scope
NH_Note("[%" PRIu64 "] NextHop %s marked as down %s:%d", sm_id, (result.retry) ? "retry" : "initially", h->hostname.c_str(),
h->getPort(scheme));
} else {
int old_count = 0;
// if the last failure was outside the retry window, set the failcount to 1 and failedAt to now.
{ // start of lock_guard_scope
std::lock_guard<std::mutex> lock(h->_mutex);
if ((h->failedAt + retry_time) < static_cast<unsigned>(_now)) {
h->failCount = 1;
h->failedAt = _now;
} else {
old_count = h->failCount = 1;
}
new_fail_count = old_count + 1;
} // end of lock_guard
NH_Debug("parent_select", "[%" PRIu64 "] Parent fail count increased to %d for %s:%d", sm_id, new_fail_count,
h->hostname.c_str(), h->getPort(scheme));
}
if (new_fail_count >= fail_threshold) {
h->set_unavailable();
NH_Note("[%" PRIu64 "] Failure threshold met failcount:%d >= threshold:%" PRIu64 ", http parent proxy %s:%d marked down", sm_id,
new_fail_count, fail_threshold, h->hostname.c_str(), h->getPort(scheme));
NH_Debug("parent_select", "[%" PRIu64 "] NextHop %s:%d marked unavailable, h->available=%s", sm_id, h->hostname.c_str(),
h->getPort(scheme), (h->available) ? "true" : "false");
}
}
void
NextHopSelectionStrategy::markNextHopUp(const uint64_t sm_id, ParentResult &result)
{
// Make sure that we are being called back with with a
// result structure with a parent that is being retried
ink_assert(result.retry == true);
if (result.result != PARENT_SPECIFIED) {
return;
}
// If we were set through the API we currently have not failover
// so just return fail
if (result.is_api_result()) {
ink_assert(0);
return;
}
uint32_t hst_size = host_groups[result.last_group].size();
ink_assert(result.last_parent < hst_size);
std::shared_ptr<HostRecord> h = host_groups[result.last_group][result.last_parent];
if (!h->available) {
h->set_available();
NH_Note("[%" PRIu64 "] http parent proxy %s:%d restored", sm_id, h->hostname.c_str(), h->getPort(scheme));
}
}
namespace YAML
{
template <> struct convert<HostRecord> {
static bool
decode(const Node &node, HostRecord &nh)
{
YAML::Node nd;
bool merge_tag_used = false;
// check for YAML merge tag.
if (node["<<"]) {
nd = node["<<"];
merge_tag_used = true;
} else {
nd = node;
}
// lookup the hostname
if (nd["host"]) {
nh.hostname = nd["host"].Scalar();
} else {
throw std::invalid_argument("Invalid host definition, missing host name.");
}
// lookup the port numbers supported by this host.
YAML::Node proto = nd["protocol"];
if (proto.Type() != YAML::NodeType::Sequence) {
throw std::invalid_argument("Invalid host protocol definition, expected a sequence.");
} else {
for (unsigned int ii = 0; ii < proto.size(); ii++) {
YAML::Node protocol_node = proto[ii];
std::shared_ptr<NHProtocol> pr = std::make_shared<NHProtocol>(protocol_node.as<NHProtocol>());
nh.protocols.push_back(std::move(pr));
}
}
// get the host's weight
YAML::Node weight;
if (merge_tag_used) {
weight = node["weight"];
nh.weight = weight.as<float>();
} else if ((weight = nd["weight"])) {
nh.weight = weight.as<float>();
} else {
NH_Note("No weight is defined for the host '%s', using default 1.0", nh.hostname.data());
nh.weight = 1.0;
}
// get the host's optional hash_string
YAML::Node hash;
if ((hash = nd["hash_string"])) {
nh.hash_string = hash.Scalar();
}
return true;
}
};
template <> struct convert<NHProtocol> {
static bool
decode(const Node &node, NHProtocol &nh)
{
if (node["scheme"]) {
if (node["scheme"].Scalar() == "http") {
nh.scheme = NH_SCHEME_HTTP;
} else if (node["scheme"].Scalar() == "https") {
nh.scheme = NH_SCHEME_HTTPS;
} else {
nh.scheme = NH_SCHEME_NONE;
}
}
if (node["port"]) {
nh.port = node["port"].as<int>();
}
if (node["health_check_url"]) {
nh.health_check_url = node["health_check_url"].Scalar();
}
return true;
}
};
}; // namespace YAML
// namespace YAML
<|endoftext|>
|
<commit_before>//===-- LLVMContext.cpp - Implement LLVMContext ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements LLVMContext, as a wrapper around the opaque
// class LLVMContextImpl.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/LLVMContext.h"
#include "LLVMContextImpl.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Metadata.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/SourceMgr.h"
#include <cctype>
using namespace llvm;
static ManagedStatic<LLVMContext> GlobalContext;
LLVMContext& llvm::getGlobalContext() {
return *GlobalContext;
}
LLVMContext::LLVMContext() : pImpl(new LLVMContextImpl(*this)) {
// Create the fixed metadata kinds. This is done in the same order as the
// MD_* enum values so that they correspond.
// Create the 'dbg' metadata kind.
unsigned DbgID = getMDKindID("dbg");
assert(DbgID == MD_dbg && "dbg kind id drifted"); (void)DbgID;
// Create the 'tbaa' metadata kind.
unsigned TBAAID = getMDKindID("tbaa");
assert(TBAAID == MD_tbaa && "tbaa kind id drifted"); (void)TBAAID;
// Create the 'prof' metadata kind.
unsigned ProfID = getMDKindID("prof");
assert(ProfID == MD_prof && "prof kind id drifted"); (void)ProfID;
// Create the 'fpmath' metadata kind.
unsigned FPAccuracyID = getMDKindID("fpmath");
assert(FPAccuracyID == MD_fpmath && "fpmath kind id drifted");
(void)FPAccuracyID;
// Create the 'range' metadata kind.
unsigned RangeID = getMDKindID("range");
assert(RangeID == MD_range && "range kind id drifted");
(void)RangeID;
// Create the 'tbaa.struct' metadata kind.
unsigned TBAAStructID = getMDKindID("tbaa.struct");
assert(TBAAStructID == MD_tbaa_struct && "tbaa.struct kind id drifted");
(void)TBAAStructID;
// Create the 'invariant.load' metadata kind.
unsigned InvariantLdId = getMDKindID("invariant.load");
assert(InvariantLdId == MD_invariant_load && "invariant.load kind id drifted");
(void)InvariantLdId;
// Create the 'alias.scope' metadata kind.
unsigned AliasScopeID = getMDKindID("alias.scope");
assert(AliasScopeID == MD_alias_scope && "alias.scope kind id drifted");
(void)AliasScopeID;
// Create the 'noalias' metadata kind.
unsigned NoAliasID = getMDKindID("noalias");
assert(NoAliasID == MD_noalias && "noalias kind id drifted");
(void)NoAliasID;
// Create the 'nontemporal' metadata kind.
unsigned NonTemporalID = getMDKindID("nontemporal");
assert(NonTemporalID == MD_nontemporal && "nontemporal kind id drifted");
(void)NonTemporalID;
// Create the 'llvm.mem.parallel_loop_access' metadata kind.
unsigned MemParallelLoopAccessID = getMDKindID("llvm.mem.parallel_loop_access");
assert(MemParallelLoopAccessID == MD_mem_parallel_loop_access &&
"mem_parallel_loop_access kind id drifted");
(void)MemParallelLoopAccessID;
// Create the 'nonnull' metadata kind.
unsigned NonNullID = getMDKindID("nonnull");
assert(NonNullID == MD_nonnull && "nonnull kind id drifted");
(void)NonNullID;
// Create the 'dereferenceable' metadata kind.
unsigned DereferenceableID = getMDKindID("dereferenceable");
assert(DereferenceableID == MD_dereferenceable &&
"dereferenceable kind id drifted");
(void)DereferenceableID;
// Create the 'dereferenceable_or_null' metadata kind.
unsigned DereferenceableOrNullID = getMDKindID("dereferenceable_or_null");
assert(DereferenceableOrNullID == MD_dereferenceable_or_null &&
"dereferenceable_or_null kind id drifted");
(void)DereferenceableOrNullID;
// Create the 'make.implicit' metadata kind.
unsigned MakeImplicitID = getMDKindID("make.implicit");
assert(MakeImplicitID == MD_make_implicit &&
"make.implicit kind id drifted");
(void)MakeImplicitID;
// Create the 'unpredictable' metadata kind.
unsigned UnpredictableID = getMDKindID("unpredictable");
assert(UnpredictableID == MD_unpredictable &&
"unpredictable kind id drifted");
(void)UnpredictableID;
// Create the 'invariant.group' metadata kind.
unsigned InvariantGroupId = getMDKindID("invariant.group");
assert(InvariantGroupId == MD_invariant_group &&
"invariant.group kind id drifted");
(void)InvariantGroupId;
// Create the 'align' metadata kind.
unsigned AlignID = getMDKindID("align");
assert(AlignID == MD_align && "align kind id drifted");
(void)AlignID;
// Create the 'llvm.loop' metadata kind.
unsigned LoopID = getMDKindID("llvm.loop");
assert(LoopID == MD_loop && "llvm.loop kind id drifted");
(void)LoopID;
auto *DeoptEntry = pImpl->getOrInsertBundleTag("deopt");
assert(DeoptEntry->second == LLVMContext::OB_deopt &&
"deopt operand bundle id drifted!");
(void)DeoptEntry;
auto *FuncletEntry = pImpl->getOrInsertBundleTag("funclet");
assert(FuncletEntry->second == LLVMContext::OB_funclet &&
"funclet operand bundle id drifted!");
(void)FuncletEntry;
auto *GCTransitionEntry = pImpl->getOrInsertBundleTag("gc-transition");
assert(GCTransitionEntry->second == LLVMContext::OB_gc_transition &&
"gc-transition operand bundle id drifted!");
(void)GCTransitionEntry;
}
LLVMContext::~LLVMContext() { delete pImpl; }
void LLVMContext::addModule(Module *M) {
pImpl->OwnedModules.insert(M);
}
void LLVMContext::removeModule(Module *M) {
pImpl->OwnedModules.erase(M);
}
//===----------------------------------------------------------------------===//
// Recoverable Backend Errors
//===----------------------------------------------------------------------===//
void LLVMContext::
setInlineAsmDiagnosticHandler(InlineAsmDiagHandlerTy DiagHandler,
void *DiagContext) {
pImpl->InlineAsmDiagHandler = DiagHandler;
pImpl->InlineAsmDiagContext = DiagContext;
}
/// getInlineAsmDiagnosticHandler - Return the diagnostic handler set by
/// setInlineAsmDiagnosticHandler.
LLVMContext::InlineAsmDiagHandlerTy
LLVMContext::getInlineAsmDiagnosticHandler() const {
return pImpl->InlineAsmDiagHandler;
}
/// getInlineAsmDiagnosticContext - Return the diagnostic context set by
/// setInlineAsmDiagnosticHandler.
void *LLVMContext::getInlineAsmDiagnosticContext() const {
return pImpl->InlineAsmDiagContext;
}
void LLVMContext::setDiagnosticHandler(DiagnosticHandlerTy DiagnosticHandler,
void *DiagnosticContext,
bool RespectFilters) {
pImpl->DiagnosticHandler = DiagnosticHandler;
pImpl->DiagnosticContext = DiagnosticContext;
pImpl->RespectDiagnosticFilters = RespectFilters;
}
LLVMContext::DiagnosticHandlerTy LLVMContext::getDiagnosticHandler() const {
return pImpl->DiagnosticHandler;
}
void *LLVMContext::getDiagnosticContext() const {
return pImpl->DiagnosticContext;
}
void LLVMContext::setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle)
{
pImpl->YieldCallback = Callback;
pImpl->YieldOpaqueHandle = OpaqueHandle;
}
void LLVMContext::yield() {
if (pImpl->YieldCallback)
pImpl->YieldCallback(this, pImpl->YieldOpaqueHandle);
}
void LLVMContext::emitError(const Twine &ErrorStr) {
diagnose(DiagnosticInfoInlineAsm(ErrorStr));
}
void LLVMContext::emitError(const Instruction *I, const Twine &ErrorStr) {
assert (I && "Invalid instruction");
diagnose(DiagnosticInfoInlineAsm(*I, ErrorStr));
}
static bool isDiagnosticEnabled(const DiagnosticInfo &DI) {
// Optimization remarks are selective. They need to check whether the regexp
// pattern, passed via one of the -pass-remarks* flags, matches the name of
// the pass that is emitting the diagnostic. If there is no match, ignore the
// diagnostic and return.
if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
return Remark->isEnabled();
return true;
}
static const char *getDiagnosticMessagePrefix(DiagnosticSeverity Severity) {
switch (Severity) {
case DS_Error:
return "error";
case DS_Warning:
return "warning";
case DS_Remark:
return "remark";
case DS_Note:
return "note";
}
llvm_unreachable("Unknown DiagnosticSeverity");
}
void LLVMContext::diagnose(const DiagnosticInfo &DI) {
// If there is a report handler, use it.
if (pImpl->DiagnosticHandler) {
if (!pImpl->RespectDiagnosticFilters || isDiagnosticEnabled(DI))
pImpl->DiagnosticHandler(DI, pImpl->DiagnosticContext);
return;
}
if (!isDiagnosticEnabled(DI))
return;
// Otherwise, print the message with a prefix based on the severity.
DiagnosticPrinterRawOStream DP(errs());
errs() << getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
DI.print(DP);
errs() << "\n";
if (DI.getSeverity() == DS_Error)
exit(1);
}
void LLVMContext::emitError(unsigned LocCookie, const Twine &ErrorStr) {
diagnose(DiagnosticInfoInlineAsm(LocCookie, ErrorStr));
}
//===----------------------------------------------------------------------===//
// Metadata Kind Uniquing
//===----------------------------------------------------------------------===//
/// Return a unique non-zero ID for the specified metadata kind.
unsigned LLVMContext::getMDKindID(StringRef Name) const {
// If this is new, assign it its ID.
return pImpl->CustomMDKindNames.insert(
std::make_pair(
Name, pImpl->CustomMDKindNames.size()))
.first->second;
}
/// getHandlerNames - Populate client-supplied smallvector using custom
/// metadata name and ID.
void LLVMContext::getMDKindNames(SmallVectorImpl<StringRef> &Names) const {
Names.resize(pImpl->CustomMDKindNames.size());
for (StringMap<unsigned>::const_iterator I = pImpl->CustomMDKindNames.begin(),
E = pImpl->CustomMDKindNames.end(); I != E; ++I)
Names[I->second] = I->first();
}
void LLVMContext::getOperandBundleTags(SmallVectorImpl<StringRef> &Tags) const {
pImpl->getOperandBundleTags(Tags);
}
uint32_t LLVMContext::getOperandBundleTagID(StringRef Tag) const {
return pImpl->getOperandBundleTagID(Tag);
}
void LLVMContext::setGC(const Function &Fn, std::string GCName) {
auto It = pImpl->GCNames.find(&Fn);
if (It == pImpl->GCNames.end()) {
pImpl->GCNames.insert(std::make_pair(&Fn, std::move(GCName)));
return;
}
It->second = std::move(GCName);
}
const std::string &LLVMContext::getGC(const Function &Fn) {
return pImpl->GCNames[&Fn];
}
void LLVMContext::deleteGC(const Function &Fn) {
pImpl->GCNames.erase(&Fn);
}
bool LLVMContext::shouldDiscardValueNames() const { return pImpl->DiscardValueNames; }
void LLVMContext::setDiscardValueNames(bool Discard) {
pImpl->DiscardValueNames = Discard;
}
<commit_msg>80 lines column after renaming "shouldDiscardValueNames" (NFC)<commit_after>//===-- LLVMContext.cpp - Implement LLVMContext ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements LLVMContext, as a wrapper around the opaque
// class LLVMContextImpl.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/LLVMContext.h"
#include "LLVMContextImpl.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Metadata.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/SourceMgr.h"
#include <cctype>
using namespace llvm;
static ManagedStatic<LLVMContext> GlobalContext;
LLVMContext& llvm::getGlobalContext() {
return *GlobalContext;
}
LLVMContext::LLVMContext() : pImpl(new LLVMContextImpl(*this)) {
// Create the fixed metadata kinds. This is done in the same order as the
// MD_* enum values so that they correspond.
// Create the 'dbg' metadata kind.
unsigned DbgID = getMDKindID("dbg");
assert(DbgID == MD_dbg && "dbg kind id drifted"); (void)DbgID;
// Create the 'tbaa' metadata kind.
unsigned TBAAID = getMDKindID("tbaa");
assert(TBAAID == MD_tbaa && "tbaa kind id drifted"); (void)TBAAID;
// Create the 'prof' metadata kind.
unsigned ProfID = getMDKindID("prof");
assert(ProfID == MD_prof && "prof kind id drifted"); (void)ProfID;
// Create the 'fpmath' metadata kind.
unsigned FPAccuracyID = getMDKindID("fpmath");
assert(FPAccuracyID == MD_fpmath && "fpmath kind id drifted");
(void)FPAccuracyID;
// Create the 'range' metadata kind.
unsigned RangeID = getMDKindID("range");
assert(RangeID == MD_range && "range kind id drifted");
(void)RangeID;
// Create the 'tbaa.struct' metadata kind.
unsigned TBAAStructID = getMDKindID("tbaa.struct");
assert(TBAAStructID == MD_tbaa_struct && "tbaa.struct kind id drifted");
(void)TBAAStructID;
// Create the 'invariant.load' metadata kind.
unsigned InvariantLdId = getMDKindID("invariant.load");
assert(InvariantLdId == MD_invariant_load && "invariant.load kind id drifted");
(void)InvariantLdId;
// Create the 'alias.scope' metadata kind.
unsigned AliasScopeID = getMDKindID("alias.scope");
assert(AliasScopeID == MD_alias_scope && "alias.scope kind id drifted");
(void)AliasScopeID;
// Create the 'noalias' metadata kind.
unsigned NoAliasID = getMDKindID("noalias");
assert(NoAliasID == MD_noalias && "noalias kind id drifted");
(void)NoAliasID;
// Create the 'nontemporal' metadata kind.
unsigned NonTemporalID = getMDKindID("nontemporal");
assert(NonTemporalID == MD_nontemporal && "nontemporal kind id drifted");
(void)NonTemporalID;
// Create the 'llvm.mem.parallel_loop_access' metadata kind.
unsigned MemParallelLoopAccessID = getMDKindID("llvm.mem.parallel_loop_access");
assert(MemParallelLoopAccessID == MD_mem_parallel_loop_access &&
"mem_parallel_loop_access kind id drifted");
(void)MemParallelLoopAccessID;
// Create the 'nonnull' metadata kind.
unsigned NonNullID = getMDKindID("nonnull");
assert(NonNullID == MD_nonnull && "nonnull kind id drifted");
(void)NonNullID;
// Create the 'dereferenceable' metadata kind.
unsigned DereferenceableID = getMDKindID("dereferenceable");
assert(DereferenceableID == MD_dereferenceable &&
"dereferenceable kind id drifted");
(void)DereferenceableID;
// Create the 'dereferenceable_or_null' metadata kind.
unsigned DereferenceableOrNullID = getMDKindID("dereferenceable_or_null");
assert(DereferenceableOrNullID == MD_dereferenceable_or_null &&
"dereferenceable_or_null kind id drifted");
(void)DereferenceableOrNullID;
// Create the 'make.implicit' metadata kind.
unsigned MakeImplicitID = getMDKindID("make.implicit");
assert(MakeImplicitID == MD_make_implicit &&
"make.implicit kind id drifted");
(void)MakeImplicitID;
// Create the 'unpredictable' metadata kind.
unsigned UnpredictableID = getMDKindID("unpredictable");
assert(UnpredictableID == MD_unpredictable &&
"unpredictable kind id drifted");
(void)UnpredictableID;
// Create the 'invariant.group' metadata kind.
unsigned InvariantGroupId = getMDKindID("invariant.group");
assert(InvariantGroupId == MD_invariant_group &&
"invariant.group kind id drifted");
(void)InvariantGroupId;
// Create the 'align' metadata kind.
unsigned AlignID = getMDKindID("align");
assert(AlignID == MD_align && "align kind id drifted");
(void)AlignID;
// Create the 'llvm.loop' metadata kind.
unsigned LoopID = getMDKindID("llvm.loop");
assert(LoopID == MD_loop && "llvm.loop kind id drifted");
(void)LoopID;
auto *DeoptEntry = pImpl->getOrInsertBundleTag("deopt");
assert(DeoptEntry->second == LLVMContext::OB_deopt &&
"deopt operand bundle id drifted!");
(void)DeoptEntry;
auto *FuncletEntry = pImpl->getOrInsertBundleTag("funclet");
assert(FuncletEntry->second == LLVMContext::OB_funclet &&
"funclet operand bundle id drifted!");
(void)FuncletEntry;
auto *GCTransitionEntry = pImpl->getOrInsertBundleTag("gc-transition");
assert(GCTransitionEntry->second == LLVMContext::OB_gc_transition &&
"gc-transition operand bundle id drifted!");
(void)GCTransitionEntry;
}
LLVMContext::~LLVMContext() { delete pImpl; }
void LLVMContext::addModule(Module *M) {
pImpl->OwnedModules.insert(M);
}
void LLVMContext::removeModule(Module *M) {
pImpl->OwnedModules.erase(M);
}
//===----------------------------------------------------------------------===//
// Recoverable Backend Errors
//===----------------------------------------------------------------------===//
void LLVMContext::
setInlineAsmDiagnosticHandler(InlineAsmDiagHandlerTy DiagHandler,
void *DiagContext) {
pImpl->InlineAsmDiagHandler = DiagHandler;
pImpl->InlineAsmDiagContext = DiagContext;
}
/// getInlineAsmDiagnosticHandler - Return the diagnostic handler set by
/// setInlineAsmDiagnosticHandler.
LLVMContext::InlineAsmDiagHandlerTy
LLVMContext::getInlineAsmDiagnosticHandler() const {
return pImpl->InlineAsmDiagHandler;
}
/// getInlineAsmDiagnosticContext - Return the diagnostic context set by
/// setInlineAsmDiagnosticHandler.
void *LLVMContext::getInlineAsmDiagnosticContext() const {
return pImpl->InlineAsmDiagContext;
}
void LLVMContext::setDiagnosticHandler(DiagnosticHandlerTy DiagnosticHandler,
void *DiagnosticContext,
bool RespectFilters) {
pImpl->DiagnosticHandler = DiagnosticHandler;
pImpl->DiagnosticContext = DiagnosticContext;
pImpl->RespectDiagnosticFilters = RespectFilters;
}
LLVMContext::DiagnosticHandlerTy LLVMContext::getDiagnosticHandler() const {
return pImpl->DiagnosticHandler;
}
void *LLVMContext::getDiagnosticContext() const {
return pImpl->DiagnosticContext;
}
void LLVMContext::setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle)
{
pImpl->YieldCallback = Callback;
pImpl->YieldOpaqueHandle = OpaqueHandle;
}
void LLVMContext::yield() {
if (pImpl->YieldCallback)
pImpl->YieldCallback(this, pImpl->YieldOpaqueHandle);
}
void LLVMContext::emitError(const Twine &ErrorStr) {
diagnose(DiagnosticInfoInlineAsm(ErrorStr));
}
void LLVMContext::emitError(const Instruction *I, const Twine &ErrorStr) {
assert (I && "Invalid instruction");
diagnose(DiagnosticInfoInlineAsm(*I, ErrorStr));
}
static bool isDiagnosticEnabled(const DiagnosticInfo &DI) {
// Optimization remarks are selective. They need to check whether the regexp
// pattern, passed via one of the -pass-remarks* flags, matches the name of
// the pass that is emitting the diagnostic. If there is no match, ignore the
// diagnostic and return.
if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
return Remark->isEnabled();
return true;
}
static const char *getDiagnosticMessagePrefix(DiagnosticSeverity Severity) {
switch (Severity) {
case DS_Error:
return "error";
case DS_Warning:
return "warning";
case DS_Remark:
return "remark";
case DS_Note:
return "note";
}
llvm_unreachable("Unknown DiagnosticSeverity");
}
void LLVMContext::diagnose(const DiagnosticInfo &DI) {
// If there is a report handler, use it.
if (pImpl->DiagnosticHandler) {
if (!pImpl->RespectDiagnosticFilters || isDiagnosticEnabled(DI))
pImpl->DiagnosticHandler(DI, pImpl->DiagnosticContext);
return;
}
if (!isDiagnosticEnabled(DI))
return;
// Otherwise, print the message with a prefix based on the severity.
DiagnosticPrinterRawOStream DP(errs());
errs() << getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
DI.print(DP);
errs() << "\n";
if (DI.getSeverity() == DS_Error)
exit(1);
}
void LLVMContext::emitError(unsigned LocCookie, const Twine &ErrorStr) {
diagnose(DiagnosticInfoInlineAsm(LocCookie, ErrorStr));
}
//===----------------------------------------------------------------------===//
// Metadata Kind Uniquing
//===----------------------------------------------------------------------===//
/// Return a unique non-zero ID for the specified metadata kind.
unsigned LLVMContext::getMDKindID(StringRef Name) const {
// If this is new, assign it its ID.
return pImpl->CustomMDKindNames.insert(
std::make_pair(
Name, pImpl->CustomMDKindNames.size()))
.first->second;
}
/// getHandlerNames - Populate client-supplied smallvector using custom
/// metadata name and ID.
void LLVMContext::getMDKindNames(SmallVectorImpl<StringRef> &Names) const {
Names.resize(pImpl->CustomMDKindNames.size());
for (StringMap<unsigned>::const_iterator I = pImpl->CustomMDKindNames.begin(),
E = pImpl->CustomMDKindNames.end(); I != E; ++I)
Names[I->second] = I->first();
}
void LLVMContext::getOperandBundleTags(SmallVectorImpl<StringRef> &Tags) const {
pImpl->getOperandBundleTags(Tags);
}
uint32_t LLVMContext::getOperandBundleTagID(StringRef Tag) const {
return pImpl->getOperandBundleTagID(Tag);
}
void LLVMContext::setGC(const Function &Fn, std::string GCName) {
auto It = pImpl->GCNames.find(&Fn);
if (It == pImpl->GCNames.end()) {
pImpl->GCNames.insert(std::make_pair(&Fn, std::move(GCName)));
return;
}
It->second = std::move(GCName);
}
const std::string &LLVMContext::getGC(const Function &Fn) {
return pImpl->GCNames[&Fn];
}
void LLVMContext::deleteGC(const Function &Fn) {
pImpl->GCNames.erase(&Fn);
}
bool LLVMContext::shouldDiscardValueNames() const {
return pImpl->DiscardValueNames;
}
void LLVMContext::setDiscardValueNames(bool Discard) {
pImpl->DiscardValueNames = Discard;
}
<|endoftext|>
|
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2012 Chen-Pang He <jdh8@ms63.hinet.net>
//
// 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 "matrix_functions.h"
template<typename T>
void test2dRotation(double tol)
{
Matrix<T,2,2> A, B, C;
T angle, c, s;
A << 0, 1, -1, 0;
MatrixPower<Matrix<T,2,2> > Apow(A);
for (int i=0; i<=20; ++i) {
angle = pow(10, (i-10) / 5.);
c = std::cos(angle);
s = std::sin(angle);
B << c, s, -s, c;
C = Apow(std::ldexp(angle,1) / M_PI);
std::cout << "test2dRotation: i = " << i << " error powerm = " << relerr(C,B) << '\n';
VERIFY(C.isApprox(B, tol));
}
}
template<typename T>
void test2dHyperbolicRotation(double tol)
{
Matrix<std::complex<T>,2,2> A, B, C;
T angle, ch = std::cosh((T)1);
std::complex<T> ish(0, std::sinh((T)1));
A << ch, ish, -ish, ch;
MatrixPower<Matrix<std::complex<T>,2,2> > Apow(A);
for (int i=0; i<=20; ++i) {
angle = std::ldexp(static_cast<T>(i-10), -1);
ch = std::cosh(angle);
ish = std::complex<T>(0, std::sinh(angle));
B << ch, ish, -ish, ch;
C = Apow(angle);
std::cout << "test2dHyperbolicRotation: i = " << i << " error powerm = " << relerr(C,B) << '\n';
VERIFY(C.isApprox(B, tol));
}
}
template<typename MatrixType>
void testExponentLaws(const MatrixType& m, double tol)
{
typedef typename MatrixType::RealScalar RealScalar;
MatrixType m1, m2, m3, m4, m5;
RealScalar x, y;
for (int i=0; i < g_repeat; ++i) {
generateTestMatrix<MatrixType>::run(m1, m.rows());
MatrixPower<MatrixType> mpow(m1);
x = internal::random<RealScalar>();
y = internal::random<RealScalar>();
m2 = mpow(x);
m3 = mpow(y);
m4 = mpow(x+y);
m5.noalias() = m2 * m3;
VERIFY(m4.isApprox(m5, tol));
m4 = mpow(x*y);
m5 = m2.pow(y);
VERIFY(m4.isApprox(m5, tol));
m4 = (std::abs(x) * m1).pow(y);
m5 = std::pow(std::abs(x), y) * m3;
VERIFY(m4.isApprox(m5, tol));
}
}
typedef Matrix<double,3,3,RowMajor> Matrix3dRowMajor;
typedef Matrix<long double,Dynamic,Dynamic> MatrixXe;
void test_matrix_power()
{
CALL_SUBTEST_2(test2dRotation<double>(1e-13));
CALL_SUBTEST_1(test2dRotation<float>(2e-5)); // was 1e-5, relaxed for clang 2.8 / linux / x86-64
CALL_SUBTEST_9(test2dRotation<long double>(1e-13));
CALL_SUBTEST_2(test2dHyperbolicRotation<double>(1e-14));
CALL_SUBTEST_1(test2dHyperbolicRotation<float>(1e-5));
CALL_SUBTEST_9(test2dHyperbolicRotation<long double>(1e-14));
CALL_SUBTEST_2(testExponentLaws(Matrix2d(), 1e-13));
CALL_SUBTEST_7(testExponentLaws(Matrix3dRowMajor(), 1e-13));
CALL_SUBTEST_3(testExponentLaws(Matrix4cd(), 1e-13));
CALL_SUBTEST_4(testExponentLaws(MatrixXd(8,8), 2e-12));
CALL_SUBTEST_1(testExponentLaws(Matrix2f(), 1e-4));
CALL_SUBTEST_5(testExponentLaws(Matrix3cf(), 1e-4));
CALL_SUBTEST_8(testExponentLaws(Matrix4f(), 1e-4));
CALL_SUBTEST_6(testExponentLaws(MatrixXf(2,2), 1e-3)); // see bug 614
CALL_SUBTEST_9(testExponentLaws(MatrixXe(7,7), 1e-13));
}
<commit_msg>Test power of singular matrices.<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2012 Chen-Pang He <jdh8@ms63.hinet.net>
//
// 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 "matrix_functions.h"
// for complex matrices, any matrix is fine
template<typename MatrixType, int IsComplex = NumTraits<typename internal::traits<MatrixType>::Scalar>::IsComplex>
struct generateSingularMatrix
{
static void run(MatrixType& result, typename MatrixType::Index size)
{
result = MatrixType::Random(size, size);
result.col(0).fill(0);
}
};
// for real matrices, make sure none of the eigenvalues are negative
template<typename MatrixType>
struct generateSingularMatrix<MatrixType,0>
{
static void run(MatrixType& result, typename MatrixType::Index size)
{
MatrixType mat = MatrixType::Random(size, size);
mat.col(0).fill(0);
ComplexSchur<MatrixType> schur(mat);
typename ComplexSchur<MatrixType>::ComplexMatrixType T = schur.matrixT();
for (typename MatrixType::Index i = 0; i < size; ++i) {
if (T.coeff(i,i).imag() == 0 && T.coeff(i,i).real() < 0)
T.coeffRef(i,i) = -T.coeff(i,i);
}
result = (schur.matrixU() * (T.template triangularView<Upper>() * schur.matrixU().adjoint())).real();
}
};
template<typename T>
void test2dRotation(double tol)
{
Matrix<T,2,2> A, B, C;
T angle, c, s;
A << 0, 1, -1, 0;
MatrixPower<Matrix<T,2,2> > Apow(A);
for (int i=0; i<=20; ++i) {
angle = pow(10, (i-10) / 5.);
c = std::cos(angle);
s = std::sin(angle);
B << c, s, -s, c;
C = Apow(std::ldexp(angle,1) / M_PI);
std::cout << "test2dRotation: i = " << i << " error powerm = " << relerr(C,B) << '\n';
VERIFY(C.isApprox(B, tol));
}
}
template<typename T>
void test2dHyperbolicRotation(double tol)
{
Matrix<std::complex<T>,2,2> A, B, C;
T angle, ch = std::cosh((T)1);
std::complex<T> ish(0, std::sinh((T)1));
A << ch, ish, -ish, ch;
MatrixPower<Matrix<std::complex<T>,2,2> > Apow(A);
for (int i=0; i<=20; ++i) {
angle = std::ldexp(static_cast<T>(i-10), -1);
ch = std::cosh(angle);
ish = std::complex<T>(0, std::sinh(angle));
B << ch, ish, -ish, ch;
C = Apow(angle);
std::cout << "test2dHyperbolicRotation: i = " << i << " error powerm = " << relerr(C,B) << '\n';
VERIFY(C.isApprox(B, tol));
}
}
template<typename MatrixType>
void testGeneral(const MatrixType& m, double tol)
{
typedef typename MatrixType::RealScalar RealScalar;
MatrixType m1, m2, m3, m4, m5;
RealScalar x, y;
for (int i=0; i < g_repeat; ++i) {
generateTestMatrix<MatrixType>::run(m1, m.rows());
MatrixPower<MatrixType> mpow(m1);
x = internal::random<RealScalar>();
y = internal::random<RealScalar>();
m2 = mpow(x);
m3 = mpow(y);
m4 = mpow(x+y);
m5.noalias() = m2 * m3;
VERIFY(m4.isApprox(m5, tol));
m4 = mpow(x*y);
m5 = m2.pow(y);
VERIFY(m4.isApprox(m5, tol));
m4 = (std::abs(x) * m1).pow(y);
m5 = std::pow(std::abs(x), y) * m3;
VERIFY(m4.isApprox(m5, tol));
}
}
template<typename MatrixType>
void testSingular(MatrixType m, double tol)
{
typedef typename MatrixType::RealScalar RealScalar;
MatrixType m1, m2, m3, m4, m5;
RealScalar x, y;
for (int i=0; i < g_repeat; ++i) {
generateTestMatrix<MatrixType>::run(m1, m.rows());
MatrixPower<MatrixType> mpow(m1);
x = internal::random<RealScalar>(0, 1);
y = internal::random<RealScalar>(0, 1);
m2 = mpow(x);
m3 = mpow(y);
m4 = mpow(x+y);
m5.noalias() = m2 * m3;
VERIFY(m4.isApprox(m5, tol));
m4 = mpow(x*y);
m5 = m2.pow(y);
VERIFY(m4.isApprox(m5, tol));
m4 = (x * m1).pow(y);
m5 = std::pow(x, y) * m3;
VERIFY(m4.isApprox(m5, tol));
}
}
typedef Matrix<double,3,3,RowMajor> Matrix3dRowMajor;
typedef Matrix<long double,Dynamic,Dynamic> MatrixXe;
void test_matrix_power()
{
CALL_SUBTEST_2(test2dRotation<double>(1e-13));
CALL_SUBTEST_1(test2dRotation<float>(2e-5)); // was 1e-5, relaxed for clang 2.8 / linux / x86-64
CALL_SUBTEST_9(test2dRotation<long double>(1e-13));
CALL_SUBTEST_2(test2dHyperbolicRotation<double>(1e-14));
CALL_SUBTEST_1(test2dHyperbolicRotation<float>(1e-5));
CALL_SUBTEST_9(test2dHyperbolicRotation<long double>(1e-14));
CALL_SUBTEST_2(testGeneral(Matrix2d(), 1e-13));
CALL_SUBTEST_7(testGeneral(Matrix3dRowMajor(), 1e-13));
CALL_SUBTEST_3(testGeneral(Matrix4cd(), 1e-13));
CALL_SUBTEST_4(testGeneral(MatrixXd(8,8), 2e-12));
CALL_SUBTEST_1(testGeneral(Matrix2f(), 1e-4));
CALL_SUBTEST_5(testGeneral(Matrix3cf(), 1e-4));
CALL_SUBTEST_8(testGeneral(Matrix4f(), 1e-4));
CALL_SUBTEST_6(testGeneral(MatrixXf(2,2), 1e-3)); // see bug 614
CALL_SUBTEST_9(testGeneral(MatrixXe(7,7), 1e-13));
CALL_SUBTEST_2(testSingular(Matrix2d(), 1e-13));
CALL_SUBTEST_7(testSingular(Matrix3dRowMajor(), 1e-13));
CALL_SUBTEST_3(testSingular(Matrix4cd(), 1e-13));
CALL_SUBTEST_4(testSingular(MatrixXd(8,8), 2e-12));
CALL_SUBTEST_1(testSingular(Matrix2f(), 1e-4));
CALL_SUBTEST_5(testSingular(Matrix3cf(), 1e-4));
CALL_SUBTEST_8(testSingular(Matrix4f(), 1e-4));
CALL_SUBTEST_6(testSingular(MatrixXf(2,2), 1e-3));
CALL_SUBTEST_9(testSingular(MatrixXe(7,7), 1e-13));
}
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2016-2018 Draios Inc dba Sysdig.
This file is part of falco.
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 "falco_outputs.h"
#include "config_falco.h"
#include "formats.h"
#include "logger.h"
#include "falco_output_queue.h"
using namespace std;
using namespace falco::output;
const static struct luaL_reg ll_falco_outputs [] =
{
{"handle_http", &falco_outputs::handle_http},
{"handle_grpc", &falco_outputs::handle_grpc},
{NULL,NULL}
};
falco_outputs::falco_outputs(falco_engine *engine)
: m_falco_engine(engine),
m_initialized(false),
m_buffered(true),
m_json_output(false),
m_time_format_iso_8601(false)
{
}
falco_outputs::~falco_outputs()
{
// Note: The assert()s in this destructor were previously places where
// exceptions were thrown. C++11 doesn't allow destructors to
// emit exceptions; if they're thrown, they'll trigger a call
// to 'terminate()'. To maintain similar behavior, the exceptions
// were replace with calls to 'assert()'
if(m_initialized)
{
lua_getglobal(m_ls, m_lua_output_cleanup.c_str());
if(!lua_isfunction(m_ls, -1))
{
falco_logger::log(LOG_ERR, std::string("No function ") + m_lua_output_cleanup + " found. ");
assert(nullptr == "Missing lua cleanup function in ~falco_outputs");
}
if(lua_pcall(m_ls, 0, 0, 0) != 0)
{
const char* lerr = lua_tostring(m_ls, -1);
falco_logger::log(LOG_ERR, std::string("lua_pcall failed, err: ") + lerr);
assert(nullptr == "lua_pcall failed in ~falco_outputs");
}
}
}
void falco_outputs::init(bool json_output,
bool json_include_output_property,
uint32_t rate, uint32_t max_burst, bool buffered,
bool time_format_iso_8601)
{
// The engine must have been given an inspector by now.
if(! m_inspector)
{
throw falco_exception("No inspector provided");
}
m_json_output = json_output;
falco_common::init(m_lua_main_filename.c_str(), FALCO_SOURCE_LUA_DIR);
// Note that falco_formats is added to both the lua state used
// by the falco engine as well as the separate lua state used
// by falco outputs.
falco_formats::init(m_inspector, m_falco_engine, m_ls, json_output, json_include_output_property);
falco_logger::init(m_ls);
luaL_openlib(m_ls, "c_outputs", ll_falco_outputs, 0);
m_notifications_tb.init(rate, max_burst);
m_buffered = buffered;
m_time_format_iso_8601 = time_format_iso_8601;
m_initialized = true;
}
void falco_outputs::add_output(output_config oc)
{
uint8_t nargs = 3;
lua_getglobal(m_ls, m_lua_add_output.c_str());
if(!lua_isfunction(m_ls, -1))
{
throw falco_exception("No function " + m_lua_add_output + " found. ");
}
lua_pushstring(m_ls, oc.name.c_str());
lua_pushnumber(m_ls, (m_buffered ? 1 : 0));
lua_pushnumber(m_ls, (m_time_format_iso_8601 ? 1 : 0));
// If we have options, build up a lua table containing them
if (oc.options.size())
{
nargs = 4;
lua_createtable(m_ls, 0, oc.options.size());
for (auto it = oc.options.cbegin(); it != oc.options.cend(); ++it)
{
lua_pushstring(m_ls, (*it).second.c_str());
lua_setfield(m_ls, -2, (*it).first.c_str());
}
}
if(lua_pcall(m_ls, nargs, 0, 0) != 0)
{
const char* lerr = lua_tostring(m_ls, -1);
throw falco_exception(string(lerr));
}
}
void falco_outputs::handle_event(gen_event *ev, string &rule, string &source,
falco_common::priority_type priority, string &format)
{
if(!m_notifications_tb.claim())
{
falco_logger::log(LOG_DEBUG, "Skipping rate-limited notification for rule " + rule + "\n");
return;
}
lua_getglobal(m_ls, m_lua_output_event.c_str());
if(lua_isfunction(m_ls, -1))
{
lua_pushlightuserdata(m_ls, ev);
lua_pushstring(m_ls, rule.c_str());
lua_pushstring(m_ls, source.c_str());
lua_pushstring(m_ls, falco_common::priority_names[priority].c_str());
lua_pushnumber(m_ls, priority);
lua_pushstring(m_ls, format.c_str());
if(lua_pcall(m_ls, 6, 0, 0) != 0)
{
const char* lerr = lua_tostring(m_ls, -1);
string err = "Error invoking function output: " + string(lerr);
throw falco_exception(err);
}
}
else
{
throw falco_exception("No function " + m_lua_output_event + " found in lua compiler module");
}
}
void falco_outputs::handle_msg(uint64_t now,
falco_common::priority_type priority,
std::string &msg,
std::string &rule,
std::map<std::string,std::string> &output_fields)
{
std::string full_msg;
if(m_json_output)
{
nlohmann::json jmsg;
// Convert the time-as-nanoseconds to a more json-friendly ISO8601.
time_t evttime = now/1000000000;
char time_sec[20]; // sizeof "YYYY-MM-DDTHH:MM:SS"
char time_ns[12]; // sizeof ".sssssssssZ"
string iso8601evttime;
strftime(time_sec, sizeof(time_sec), "%FT%T", gmtime(&evttime));
snprintf(time_ns, sizeof(time_ns), ".%09luZ", now % 1000000000);
iso8601evttime = time_sec;
iso8601evttime += time_ns;
jmsg["output"] = msg;
jmsg["priority"] = "Critical";
jmsg["rule"] = rule;
jmsg["time"] = iso8601evttime;
jmsg["output_fields"] = output_fields;
full_msg = jmsg.dump();
}
else
{
std::string timestr;
bool first = true;
sinsp_utils::ts_to_string(now, ×tr, false, true);
full_msg = timestr + ": " + falco_common::priority_names[LOG_CRIT] + " " + msg + " (";
for(auto &pair : output_fields)
{
if(first)
{
first = false;
}
else
{
full_msg += " ";
}
full_msg += pair.first + "=" + pair.second;
}
full_msg += ")";
}
lua_getglobal(m_ls, m_lua_output_msg.c_str());
if(lua_isfunction(m_ls, -1))
{
lua_pushstring(m_ls, full_msg.c_str());
lua_pushstring(m_ls, falco_common::priority_names[priority].c_str());
lua_pushnumber(m_ls, priority);
if(lua_pcall(m_ls, 3, 0, 0) != 0)
{
const char* lerr = lua_tostring(m_ls, -1);
string err = "Error invoking function output: " + string(lerr);
throw falco_exception(err);
}
}
else
{
throw falco_exception("No function " + m_lua_output_msg + " found in lua compiler module");
}
}
void falco_outputs::reopen_outputs()
{
lua_getglobal(m_ls, m_lua_output_reopen.c_str());
if(!lua_isfunction(m_ls, -1))
{
throw falco_exception("No function " + m_lua_output_reopen + " found. ");
}
if(lua_pcall(m_ls, 0, 0, 0) != 0)
{
const char* lerr = lua_tostring(m_ls, -1);
throw falco_exception(string(lerr));
}
}
int falco_outputs::handle_http(lua_State *ls)
{
CURL *curl = NULL;
CURLcode res = CURLE_FAILED_INIT;
struct curl_slist *slist1;
slist1 = NULL;
if (!lua_isstring(ls, -1) ||
!lua_isstring(ls, -2))
{
lua_pushstring(ls, "Invalid arguments passed to handle_http()");
lua_error(ls);
}
string url = (char *) lua_tostring(ls, 1);
string msg = (char *) lua_tostring(ls, 2);
curl = curl_easy_init();
if(curl)
{
slist1 = curl_slist_append(slist1, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist1);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, msg.c_str());
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, -1L);
res = curl_easy_perform(curl);
if(res != CURLE_OK) {
falco_logger::log(LOG_ERR,"libcurl error: " + string(curl_easy_strerror(res)));
}
curl_easy_cleanup(curl);
curl = NULL;
curl_slist_free_all(slist1);
slist1 = NULL;
}
return 1;
}
// TODO(fntlnz, leodido): verify if this works with k8s_audit as source
int falco_outputs::handle_grpc(lua_State *ls)
{
response grpc_res = response();
// TODO(fntlnz, leodido): do the checks and make sure all the fields are sent
// fixme > check parameters later
// if(!lua_isstring(ls, -1) ||
// !lua_isstring(ls, -2))
// {
// lua_pushstring(ls, "Invalid arguments passed to handle_grpc()");
// lua_error(ls);
// }
// todo(leodido, fntlnz) > pass the ID (?)
// grpc_res.set_id("...");
// rule
grpc_res.set_rule((char *)lua_tostring(ls, 2));
// priority
priority p = priority::EMERGENCY;
string pstr = (char *)lua_tostring(ls, 4);
if(!priority_Parse(pstr, &p))
{
lua_pushstring(ls, "Unknown priority passed to to handle_grpc()");
lua_error(ls);
}
grpc_res.set_priority(p);
// output
grpc_res.set_output((char *)lua_tostring(ls, 5));
// output fields
auto& fields = *grpc_res.mutable_output_fields();
lua_pushnil(ls);
while (lua_next(ls, 6) != 0) {
fields[lua_tostring(ls, -2)] = lua_tostring(ls, -1);
lua_pop(ls, 1);
}
falco_output_queue::get().push(grpc_res);
return 1;
}<commit_msg>new(usespace/falco): transmit output sources<commit_after>/*
Copyright (C) 2016-2018 Draios Inc dba Sysdig.
This file is part of falco.
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 "falco_outputs.h"
#include "config_falco.h"
#include "formats.h"
#include "logger.h"
#include "falco_output_queue.h"
using namespace std;
using namespace falco::output;
const static struct luaL_reg ll_falco_outputs [] =
{
{"handle_http", &falco_outputs::handle_http},
{"handle_grpc", &falco_outputs::handle_grpc},
{NULL,NULL}
};
falco_outputs::falco_outputs(falco_engine *engine)
: m_falco_engine(engine),
m_initialized(false),
m_buffered(true),
m_json_output(false),
m_time_format_iso_8601(false)
{
}
falco_outputs::~falco_outputs()
{
// Note: The assert()s in this destructor were previously places where
// exceptions were thrown. C++11 doesn't allow destructors to
// emit exceptions; if they're thrown, they'll trigger a call
// to 'terminate()'. To maintain similar behavior, the exceptions
// were replace with calls to 'assert()'
if(m_initialized)
{
lua_getglobal(m_ls, m_lua_output_cleanup.c_str());
if(!lua_isfunction(m_ls, -1))
{
falco_logger::log(LOG_ERR, std::string("No function ") + m_lua_output_cleanup + " found. ");
assert(nullptr == "Missing lua cleanup function in ~falco_outputs");
}
if(lua_pcall(m_ls, 0, 0, 0) != 0)
{
const char* lerr = lua_tostring(m_ls, -1);
falco_logger::log(LOG_ERR, std::string("lua_pcall failed, err: ") + lerr);
assert(nullptr == "lua_pcall failed in ~falco_outputs");
}
}
}
void falco_outputs::init(bool json_output,
bool json_include_output_property,
uint32_t rate, uint32_t max_burst, bool buffered,
bool time_format_iso_8601)
{
// The engine must have been given an inspector by now.
if(! m_inspector)
{
throw falco_exception("No inspector provided");
}
m_json_output = json_output;
falco_common::init(m_lua_main_filename.c_str(), FALCO_SOURCE_LUA_DIR);
// Note that falco_formats is added to both the lua state used
// by the falco engine as well as the separate lua state used
// by falco outputs.
falco_formats::init(m_inspector, m_falco_engine, m_ls, json_output, json_include_output_property);
falco_logger::init(m_ls);
luaL_openlib(m_ls, "c_outputs", ll_falco_outputs, 0);
m_notifications_tb.init(rate, max_burst);
m_buffered = buffered;
m_time_format_iso_8601 = time_format_iso_8601;
m_initialized = true;
}
void falco_outputs::add_output(output_config oc)
{
uint8_t nargs = 3;
lua_getglobal(m_ls, m_lua_add_output.c_str());
if(!lua_isfunction(m_ls, -1))
{
throw falco_exception("No function " + m_lua_add_output + " found. ");
}
lua_pushstring(m_ls, oc.name.c_str());
lua_pushnumber(m_ls, (m_buffered ? 1 : 0));
lua_pushnumber(m_ls, (m_time_format_iso_8601 ? 1 : 0));
// If we have options, build up a lua table containing them
if (oc.options.size())
{
nargs = 4;
lua_createtable(m_ls, 0, oc.options.size());
for (auto it = oc.options.cbegin(); it != oc.options.cend(); ++it)
{
lua_pushstring(m_ls, (*it).second.c_str());
lua_setfield(m_ls, -2, (*it).first.c_str());
}
}
if(lua_pcall(m_ls, nargs, 0, 0) != 0)
{
const char* lerr = lua_tostring(m_ls, -1);
throw falco_exception(string(lerr));
}
}
void falco_outputs::handle_event(gen_event *ev, string &rule, string &source,
falco_common::priority_type priority, string &format)
{
if(!m_notifications_tb.claim())
{
falco_logger::log(LOG_DEBUG, "Skipping rate-limited notification for rule " + rule + "\n");
return;
}
lua_getglobal(m_ls, m_lua_output_event.c_str());
if(lua_isfunction(m_ls, -1))
{
lua_pushlightuserdata(m_ls, ev);
lua_pushstring(m_ls, rule.c_str());
lua_pushstring(m_ls, source.c_str());
lua_pushstring(m_ls, falco_common::priority_names[priority].c_str());
lua_pushnumber(m_ls, priority);
lua_pushstring(m_ls, format.c_str());
if(lua_pcall(m_ls, 6, 0, 0) != 0)
{
const char* lerr = lua_tostring(m_ls, -1);
string err = "Error invoking function output: " + string(lerr);
throw falco_exception(err);
}
}
else
{
throw falco_exception("No function " + m_lua_output_event + " found in lua compiler module");
}
}
void falco_outputs::handle_msg(uint64_t now,
falco_common::priority_type priority,
std::string &msg,
std::string &rule,
std::map<std::string,std::string> &output_fields)
{
std::string full_msg;
if(m_json_output)
{
nlohmann::json jmsg;
// Convert the time-as-nanoseconds to a more json-friendly ISO8601.
time_t evttime = now/1000000000;
char time_sec[20]; // sizeof "YYYY-MM-DDTHH:MM:SS"
char time_ns[12]; // sizeof ".sssssssssZ"
string iso8601evttime;
strftime(time_sec, sizeof(time_sec), "%FT%T", gmtime(&evttime));
snprintf(time_ns, sizeof(time_ns), ".%09luZ", now % 1000000000);
iso8601evttime = time_sec;
iso8601evttime += time_ns;
jmsg["output"] = msg;
jmsg["priority"] = "Critical";
jmsg["rule"] = rule;
jmsg["time"] = iso8601evttime;
jmsg["output_fields"] = output_fields;
full_msg = jmsg.dump();
}
else
{
std::string timestr;
bool first = true;
sinsp_utils::ts_to_string(now, ×tr, false, true);
full_msg = timestr + ": " + falco_common::priority_names[LOG_CRIT] + " " + msg + " (";
for(auto &pair : output_fields)
{
if(first)
{
first = false;
}
else
{
full_msg += " ";
}
full_msg += pair.first + "=" + pair.second;
}
full_msg += ")";
}
lua_getglobal(m_ls, m_lua_output_msg.c_str());
if(lua_isfunction(m_ls, -1))
{
lua_pushstring(m_ls, full_msg.c_str());
lua_pushstring(m_ls, falco_common::priority_names[priority].c_str());
lua_pushnumber(m_ls, priority);
if(lua_pcall(m_ls, 3, 0, 0) != 0)
{
const char* lerr = lua_tostring(m_ls, -1);
string err = "Error invoking function output: " + string(lerr);
throw falco_exception(err);
}
}
else
{
throw falco_exception("No function " + m_lua_output_msg + " found in lua compiler module");
}
}
void falco_outputs::reopen_outputs()
{
lua_getglobal(m_ls, m_lua_output_reopen.c_str());
if(!lua_isfunction(m_ls, -1))
{
throw falco_exception("No function " + m_lua_output_reopen + " found. ");
}
if(lua_pcall(m_ls, 0, 0, 0) != 0)
{
const char* lerr = lua_tostring(m_ls, -1);
throw falco_exception(string(lerr));
}
}
int falco_outputs::handle_http(lua_State *ls)
{
CURL *curl = NULL;
CURLcode res = CURLE_FAILED_INIT;
struct curl_slist *slist1;
slist1 = NULL;
if (!lua_isstring(ls, -1) ||
!lua_isstring(ls, -2))
{
lua_pushstring(ls, "Invalid arguments passed to handle_http()");
lua_error(ls);
}
string url = (char *) lua_tostring(ls, 1);
string msg = (char *) lua_tostring(ls, 2);
curl = curl_easy_init();
if(curl)
{
slist1 = curl_slist_append(slist1, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist1);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, msg.c_str());
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, -1L);
res = curl_easy_perform(curl);
if(res != CURLE_OK) {
falco_logger::log(LOG_ERR,"libcurl error: " + string(curl_easy_strerror(res)));
}
curl_easy_cleanup(curl);
curl = NULL;
curl_slist_free_all(slist1);
slist1 = NULL;
}
return 1;
}
// TODO(fntlnz, leodido): verify if this works with k8s_audit as source
int falco_outputs::handle_grpc(lua_State *ls)
{
response grpc_res = response();
// TODO(fntlnz, leodido): do the checks and make sure all the fields are sent
// fixme > check parameters later
// if(!lua_isstring(ls, -1) ||
// !lua_isstring(ls, -2))
// {
// lua_pushstring(ls, "Invalid arguments passed to handle_grpc()");
// lua_error(ls);
// }
// todo(leodido, fntlnz) > pass the ID (?)
// grpc_res.set_id("...");
// rule
grpc_res.set_rule((char *)lua_tostring(ls, 2));
// source
source s = source::SYSCALL;
string sstr = (char *)lua_tostring(ls, 3);
if(!source_Parse(sstr, &s))
{
lua_pushstring(ls, "Unknown source passed to to handle_grpc()");
lua_error(ls);
}
grpc_res.set_source(s);
// priority
priority p = priority::EMERGENCY;
string pstr = (char *)lua_tostring(ls, 4);
if(!priority_Parse(pstr, &p))
{
lua_pushstring(ls, "Unknown priority passed to to handle_grpc()");
lua_error(ls);
}
grpc_res.set_priority(p);
// output
grpc_res.set_output((char *)lua_tostring(ls, 5));
// output fields
auto& fields = *grpc_res.mutable_output_fields();
lua_pushnil(ls);
while (lua_next(ls, 6) != 0) {
fields[lua_tostring(ls, -2)] = lua_tostring(ls, -1);
lua_pop(ls, 1);
}
falco_output_queue::get().push(grpc_res);
return 1;
}<|endoftext|>
|
<commit_before>//
// Copyright (c) .NET Foundation and Contributors
// See LICENSE file in the project root for full license information.
//
#include "nf_hardware_stm32_native.h"
HRESULT Library_nf_hardware_stm32_native_nanoFramework_Hardware_Stm32_BackupMemory::
ReadBytes___STATIC__VOID__U4__SZARRAY_U1(CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
uint32_t position = stack.Arg0().NumericByRef().u4;
// dereference the data buffer from the argument
CLR_RT_HeapBlock_Array *buffer = stack.Arg1().DereferenceArray();
// get a the pointer to the byffer by using the first element of the array
uint8_t *data = buffer->GetFirstElement();
// get the length of the data buffer
uint32_t dataLength = buffer->m_numOfElements;
// address of bkp register 0
__IO uint32_t *baseAddress = &(RTC->BKP0R);
uint8_t *storeAddress = ((uint8_t *)baseAddress + position);
uint32_t *registerAddress = NULL;
uint32_t tempRegisterValue;
uint32_t counter = 0;
uint32_t remainder;
int32_t index = 3;
// sanity check for out of range position
if (position > (BACKUP_SIZE - 1))
NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER);
// sanity check for over sized data buffer
if ((position + dataLength) > BACKUP_SIZE)
NANOCLR_SET_AND_LEAVE(CLR_E_OUT_OF_RANGE);
// check if the store address is starting at a register address boundary
remainder = (uint32_t)((uint32_t *)storeAddress) % sizeof(RTC_BKP0R_Msk);
if (remainder > 0)
{
// read register
registerAddress = (uint32_t *)(storeAddress - remainder);
tempRegisterValue = *registerAddress;
// adjust remainder to the amount of bytes to move
remainder = 4 - remainder;
do
{
*data = (uint8_t)(tempRegisterValue >> ((remainder - 1) * 8));
data++;
remainder--;
counter++;
} while (remainder && (counter < dataLength));
registerAddress++;
}
// keep reading into the buffer if there enough bytes
if ((dataLength - counter) >= 4)
{
// load register
tempRegisterValue = *registerAddress;
do
{
*data = (uint8_t)(tempRegisterValue >> (index-- * 8));
data++;
counter++;
if (index < 0)
{
index = 3;
registerAddress++;
// is there enough data in buffer for another round
if ((dataLength - counter) < 4)
{
// no, exit loop
break;
}
// load register
tempRegisterValue = *registerAddress;
}
} while (1);
}
// now read the remaining bytes, if any
if ((dataLength - counter) > 0)
{
remainder = dataLength - counter;
// read register
tempRegisterValue = *registerAddress;
// adjust remainder to the amount of bytes to move
remainder = 4 - remainder;
do
{
*data = (uint8_t)(tempRegisterValue >> (remainder * 8));
remainder--;
data++;
counter++;
} while (remainder);
}
NANOCLR_NOCLEANUP();
}
HRESULT Library_nf_hardware_stm32_native_nanoFramework_Hardware_Stm32_BackupMemory::
WriteBytes___STATIC__VOID__U4__SZARRAY_U1(CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
// get position to write to
uint32_t position = stack.Arg0().NumericByRef().u4;
// dereference the data buffer from the argument
CLR_RT_HeapBlock_Array *buffer = stack.Arg1().DereferenceArray();
// get a the pointer to the byffer by using the first element of the array
uint8_t *data = buffer->GetFirstElement();
// get the length of the data buffer
uint32_t dataLength = buffer->m_numOfElements;
// address of bkp register 0
__IO uint32_t *baseAddress = &(RTC->BKP0R);
uint8_t *storeAddress = ((uint8_t *)baseAddress + position);
uint32_t *registerAddress = NULL;
uint32_t tempRegisterValue;
uint32_t counter = 0;
uint32_t remainder;
int32_t index = 3;
// sanity check for out of range position
if (position > (BACKUP_SIZE - 1))
NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER);
// sanity check for over sized data buffer
if ((position + dataLength) > BACKUP_SIZE)
NANOCLR_SET_AND_LEAVE(CLR_E_OUT_OF_RANGE);
// write has to be done register wide, so if a write address is "in the middle" of a register, need to read it first
// and overwrite as required this can happen at the begining and/or at the end of the buffer
// check if the store address is starting at a register address boundary
remainder = (uint32_t)((uint32_t *)storeAddress) % sizeof(RTC_BKP0R_Msk);
if (remainder > 0)
{
// read register
registerAddress = (uint32_t *)(storeAddress - remainder);
tempRegisterValue = *registerAddress;
// adjust remainder to the amount of bytes to move
remainder = 4 - remainder;
// clear the bytes we'll be filling
tempRegisterValue &= (uint32_t)(0xFFFFFF00 << ((remainder - 1) * 8));
do
{
tempRegisterValue |= (uint32_t)((uint32_t)*data << ((remainder - 1) * 8));
remainder--;
data++;
counter++;
} while (remainder && (counter < dataLength));
// write back register
*registerAddress = tempRegisterValue;
registerAddress++;
}
// keep processing the buffer if there enough bytes
if ((dataLength - counter) >= 4)
{
// clear register
*registerAddress = 0;
do
{
*registerAddress |= (uint32_t)((uint32_t)*data << (index-- * 8));
data++;
counter++;
if (index < 0)
{
index = 3;
registerAddress++;
// is there enough data in buffer for another round
if ((dataLength - counter) < 4)
{
// no, exit loop
break;
}
// clear register
*registerAddress = 0;
}
} while (1);
}
// take care of the remaining bytes, if any
if ((dataLength - counter) > 0)
{
remainder = dataLength - counter;
// read register
tempRegisterValue = *registerAddress;
// clear the bytes we'll be filling
tempRegisterValue &= (uint32_t)(0x00FFFFFF >> ((remainder - 1) * 8));
// adjust remainder to the amount of bytes to move
remainder = 4 - remainder;
do
{
tempRegisterValue |= (uint32_t)((uint32_t)*data << (remainder * 8));
remainder--;
data++;
counter++;
} while (remainder);
// write back register
*registerAddress = tempRegisterValue;
}
NANOCLR_NOCLEANUP();
}
HRESULT Library_nf_hardware_stm32_native_nanoFramework_Hardware_Stm32_BackupMemory::GetSize___STATIC__I4(
CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
stack.SetResult_I4(BACKUP_SIZE);
NANOCLR_NOCLEANUP_NOLABEL();
}
<commit_msg>Corrected some position combinations when R/W to backup memory (#1978)<commit_after>//
// Copyright (c) .NET Foundation and Contributors
// See LICENSE file in the project root for full license information.
//
#include "nf_hardware_stm32_native.h"
HRESULT Library_nf_hardware_stm32_native_nanoFramework_Hardware_Stm32_BackupMemory::
ReadBytes___STATIC__VOID__U4__SZARRAY_U1(CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
uint32_t position = stack.Arg0().NumericByRef().u4;
// dereference the data buffer from the argument
CLR_RT_HeapBlock_Array *buffer = stack.Arg1().DereferenceArray();
// get a the pointer to the byffer by using the first element of the array
uint8_t *data = buffer->GetFirstElement();
// get the length of the data buffer
uint32_t dataLength = buffer->m_numOfElements;
// address of bkp register 0
__IO uint32_t *baseAddress = &(RTC->BKP0R);
uint8_t *storeAddress = ((uint8_t *)baseAddress + position);
uint32_t *registerAddress = NULL;
uint32_t tempRegisterValue;
uint32_t counter = 0;
uint32_t remainder;
int32_t index = 3;
// sanity check for out of range position
if (position > (BACKUP_SIZE - 1))
NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER);
// sanity check for over sized data buffer
if ((position + dataLength) > BACKUP_SIZE)
NANOCLR_SET_AND_LEAVE(CLR_E_OUT_OF_RANGE);
// check if the store address is starting at a register address boundary
remainder = (uint32_t)((uint32_t *)storeAddress) % sizeof(RTC_BKP0R_Msk);
registerAddress = (uint32_t *)(storeAddress - remainder);
if (remainder > 0)
{
// read register
tempRegisterValue = *registerAddress;
// adjust remainder to the amount of bytes to move
remainder = 4 - remainder;
do
{
*data = (uint8_t)(tempRegisterValue >> ((remainder - 1) * 8));
data++;
remainder--;
counter++;
} while (remainder && (counter < dataLength));
registerAddress++;
}
// keep reading into the buffer if there enough bytes
if ((dataLength - counter) >= 4)
{
// load register
tempRegisterValue = *registerAddress;
do
{
*data = (uint8_t)(tempRegisterValue >> (index-- * 8));
data++;
counter++;
if (index < 0)
{
index = 3;
registerAddress++;
// is there enough data in buffer for another round
if ((dataLength - counter) < 4)
{
// no, exit loop
break;
}
// load register
tempRegisterValue = *registerAddress;
}
} while (1);
}
// now read the remaining bytes, if any
if ((dataLength - counter) > 0)
{
remainder = dataLength - counter;
// read register
tempRegisterValue = *registerAddress;
int offset = 3;
do
{
*data = (uint8_t)(tempRegisterValue >> (offset * 8));
remainder--;
data++;
counter++;
offset--;
} while (remainder);
}
NANOCLR_NOCLEANUP();
}
HRESULT Library_nf_hardware_stm32_native_nanoFramework_Hardware_Stm32_BackupMemory::
WriteBytes___STATIC__VOID__U4__SZARRAY_U1(CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
// get position to write to
uint32_t position = stack.Arg0().NumericByRef().u4;
// dereference the data buffer from the argument
CLR_RT_HeapBlock_Array *buffer = stack.Arg1().DereferenceArray();
// get a the pointer to the byffer by using the first element of the array
uint8_t *data = buffer->GetFirstElement();
// get the length of the data buffer
uint32_t dataLength = buffer->m_numOfElements;
// address of bkp register 0
__IO uint32_t *baseAddress = &(RTC->BKP0R);
uint8_t *storeAddress = ((uint8_t *)baseAddress + position);
uint32_t *registerAddress = NULL;
uint32_t tempRegisterValue;
uint32_t counter = 0;
uint32_t remainder;
int32_t index = 3;
uint32_t tempMask, tempLen;
// sanity check for out of range position
if (position > (BACKUP_SIZE - 1))
NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER);
// sanity check for over sized data buffer
if ((position + dataLength) > BACKUP_SIZE)
NANOCLR_SET_AND_LEAVE(CLR_E_OUT_OF_RANGE);
// write has to be done register wide, so if a write address is "in the middle" of a register, need to read it first
// and overwrite as required this can happen at the begining and/or at the end of the buffer
// check if the store address is starting at a register address boundary
remainder = (uint32_t)((uint32_t *)storeAddress) % sizeof(RTC_BKP0R_Msk);
registerAddress = (uint32_t *)(storeAddress - remainder);
if (remainder > 0)
{
// read register
tempRegisterValue = *registerAddress;
// adjust remainder to the amount of bytes to move
remainder = 4 - remainder;
// clear the bytes we'll be filling
tempMask = 0x00000000;
tempLen = (dataLength > 2) ? 3 : (dataLength > 1) ? 2 : 1;
for (int i = remainder - 1; i >= 0 && tempLen > 0; i--, tempLen--)
{
tempMask |= (uint32_t)(0x000000FF << (i * 8));
}
tempRegisterValue &= ~tempMask;
do
{
tempRegisterValue |= (uint32_t)((uint32_t)*data << ((remainder - 1) * 8));
remainder--;
data++;
counter++;
} while (remainder && (counter < dataLength));
// write back register
*registerAddress = tempRegisterValue;
registerAddress++;
}
// keep processing the buffer if there enough bytes
if ((dataLength - counter) >= 4)
{
// clear register
*registerAddress = 0;
do
{
*registerAddress |= (uint32_t)((uint32_t)*data << (index-- * 8));
data++;
counter++;
if (index < 0)
{
index = 3;
registerAddress++;
// is there enough data in buffer for another round
if ((dataLength - counter) < 4)
{
// no, exit loop
break;
}
// clear register
*registerAddress = 0;
}
} while (1);
}
// take care of the remaining bytes, if any
if ((dataLength - counter) > 0)
{
remainder = dataLength - counter;
// read register
tempRegisterValue = *registerAddress;
// clear the bytes we'll be filling
tempRegisterValue &= (uint32_t)(0x00FFFFFF >> ((remainder - 1) * 8));
// adjust remainder to the amount of bytes to move
remainder = 4 - remainder;
int offset = 3;
do
{
tempRegisterValue |= (uint32_t)((uint32_t)*data << (offset * 8));
remainder--;
data++;
counter++;
offset--;
} while (remainder);
// write back register
*registerAddress = tempRegisterValue;
}
NANOCLR_NOCLEANUP();
}
HRESULT Library_nf_hardware_stm32_native_nanoFramework_Hardware_Stm32_BackupMemory::GetSize___STATIC__I4(
CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
stack.SetResult_I4(BACKUP_SIZE);
NANOCLR_NOCLEANUP_NOLABEL();
}
<|endoftext|>
|
<commit_before>// Copyright 2013 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <vector>
#include <algorithm>
#include <Observation.hpp>
#include <utils.hpp>
#ifndef BINS_HPP
#define BINS_HPP
namespace PulsarSearch {
template< typename T > std::vector< unsigned int > * getNrSamplesPerBin(const AstroData::Observation< T > & obs);
// Implementation
template< typename T > std::vector< unsigned int > * getNrSamplesPerBin(const AstroData::Observation< T > & obs) {
std::vector< unsigned int > * samplesPerBin = new std::vector< unsigned int >(obs.getNrPeriods() * obs.getNrBins() * isa::utils::pad(2, obs.getPadding()));
for ( unsigned int period = 0; period < obs.getNrPeriods(); period++ ) {
unsigned int offset = 0;
std::vector< unsigned int > itemsPerBin;
std::vector< unsigned int > offsetPerBin;
std::fill(itemsPerBin.begin(), itemsPerBin.end(), 0);
std::fill(offsetPerBin.begin(), offsetPerBin.end(), 0);
for ( unsigned int i = 0; i < period; i++ ) {
float samplePhase = (i / period);
for ( unsigned int bin = 0; bin < obs.getNrBins(); bin++ ) {
if ( samplePhase - ((bin + 0.5) / obs.getNrBins()) < 1.0f / obs.getNrBins() ) {
itemsPerBin[bin] += 1;
break;
}
}
}
for ( unsigned int bin = 0; bin < obs.getNrBins(); bin++ ) {
samplesPerBin->at((period * obs.getNrBins() * pad(2, obs.getPadding())) + (bin * pad(2, obs.getPadding()))) = itemsPerBin[bin];
samplesPerBin->at((period * obs.getNrBins() * pad(2, obs.getPadding())) + (bin * pad(2, obs.getPadding())) + 1) = offset;
offset += itemsPerBin[bin];
}
}
return samplesPerBin;
}
} // PulsarSearch
#endif // BINS_HPP
<commit_msg>Forgot that vectors do not allocate memory if you add elements using [].<commit_after>// Copyright 2013 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <vector>
#include <algorithm>
#include <Observation.hpp>
#include <utils.hpp>
#ifndef BINS_HPP
#define BINS_HPP
namespace PulsarSearch {
template< typename T > std::vector< unsigned int > * getNrSamplesPerBin(const AstroData::Observation< T > & obs);
// Implementation
template< typename T > std::vector< unsigned int > * getNrSamplesPerBin(const AstroData::Observation< T > & obs) {
std::vector< unsigned int > * samplesPerBin = new std::vector< unsigned int >(obs.getNrPeriods() * obs.getNrBins() * isa::utils::pad(2, obs.getPadding()));
for ( unsigned int period = 0; period < obs.getNrPeriods(); period++ ) {
unsigned int offset = 0;
std::vector< unsigned int > itemsPerBin(obs.getNrBins());
std::vector< unsigned int > offsetPerBin(obs.getNrBins());
std::fill(itemsPerBin.begin(), itemsPerBin.end(), 0);
std::fill(offsetPerBin.begin(), offsetPerBin.end(), 0);
for ( unsigned int i = 0; i < period; i++ ) {
float samplePhase = (i / period);
for ( unsigned int bin = 0; bin < obs.getNrBins(); bin++ ) {
if ( samplePhase - ((bin + 0.5) / obs.getNrBins()) < 1.0f / obs.getNrBins() ) {
itemsPerBin[bin] += 1;
break;
}
}
}
for ( unsigned int bin = 0; bin < obs.getNrBins(); bin++ ) {
samplesPerBin->at((period * obs.getNrBins() * isa::utils::pad(2, obs.getPadding())) + (bin * isa::utils::pad(2, obs.getPadding()))) = itemsPerBin[bin];
samplesPerBin->at((period * obs.getNrBins() * isa::utils::pad(2, obs.getPadding())) + (bin * isa::utils::pad(2, obs.getPadding())) + 1) = offset;
offset += itemsPerBin[bin];
}
}
return samplesPerBin;
}
} // PulsarSearch
#endif // BINS_HPP
<|endoftext|>
|
<commit_before><commit_msg>reword, rename .. not much left to do after dtr cept this entire check probably would do well in a SpamFilter object that tracks better.<commit_after><|endoftext|>
|
<commit_before>/**
* \file
*/
#include <rleahylib/rleahylib.hpp>
#include <functional>
#include <type_traits>
/**
* \cond
*/
namespace std {
template <>
struct hash<String> {
public:
size_t operator () (String str) const {
// Normalize string
str.Normalize(NormalizationForm::NFC);
// djb2
size_t retr=5381;
for (auto cp : str.CodePoints()) {
retr*=33;
retr^=cp;
}
return retr;
}
};
template <>
struct hash<IPAddress> {
public:
size_t operator () (IPAddress ip) const noexcept {
// Is this an IPv4 or IPv6
// address?
if (ip.IsV6()) {
// This static assert ensures the operation
// planned will work
static_assert(
(sizeof(UInt128)%sizeof(size_t))==0,
"Hash for IP addresses not compatible with integer sizes on this platform"
);
union {
UInt128 raw_ip;
size_t split [sizeof(UInt128)/sizeof(size_t)];
};
raw_ip=static_cast<UInt128>(ip);
size_t retr=23;
for (auto m : split) {
retr*=31;
retr+=m;
}
return retr;
}
// Just return the IPv4 address
// to use as the hash
return static_cast<size_t>(
static_cast<UInt32>(ip)
);
}
};
template <typename... Args>
struct hash<Tuple<Args...>> {
private:
template <Word i>
typename std::enable_if<
i<sizeof...(Args),
size_t
>::type compute_hash (size_t curr, const Tuple<Args...> & t) const {
curr*=31;
curr+=std::hash<
typename std::decay<
decltype(t.template Item<i>())
>::type
>()(t.template Item<i>());
return compute_hash<i+1>(curr,t);
}
template <Word i>
typename std::enable_if<
i>=sizeof...(Args),
size_t
>::type compute_hash (size_t curr, const Tuple<Args...> &) const noexcept {
return curr;
}
public:
size_t operator () (const Tuple<Args...> & t) const {
return compute_hash<0>(23,t);
}
};
template <typename T>
struct hash<SmartPointer<T>> {
public:
size_t operator () (const SmartPointer<T> & sp) const noexcept {
return hash<const T *>()(static_cast<const T *>(sp));
}
};
}
/**
* \endcond
*/
<commit_msg>Hash Header Fix<commit_after>/**
* \file
*/
#pragma once
#include <rleahylib/rleahylib.hpp>
#include <functional>
#include <type_traits>
/**
* \cond
*/
namespace std {
template <>
struct hash<String> {
public:
size_t operator () (String str) const {
// Normalize string
str.Normalize(NormalizationForm::NFC);
// djb2
size_t retr=5381;
for (auto cp : str.CodePoints()) {
retr*=33;
retr^=cp;
}
return retr;
}
};
template <>
struct hash<IPAddress> {
public:
size_t operator () (IPAddress ip) const noexcept {
// Is this an IPv4 or IPv6
// address?
if (ip.IsV6()) {
// This static assert ensures the operation
// planned will work
static_assert(
(sizeof(UInt128)%sizeof(size_t))==0,
"Hash for IP addresses not compatible with integer sizes on this platform"
);
union {
UInt128 raw_ip;
size_t split [sizeof(UInt128)/sizeof(size_t)];
};
raw_ip=static_cast<UInt128>(ip);
size_t retr=23;
for (auto m : split) {
retr*=31;
retr+=m;
}
return retr;
}
// Just return the IPv4 address
// to use as the hash
return static_cast<size_t>(
static_cast<UInt32>(ip)
);
}
};
template <typename... Args>
struct hash<Tuple<Args...>> {
private:
template <Word i>
typename std::enable_if<
i<sizeof...(Args),
size_t
>::type compute_hash (size_t curr, const Tuple<Args...> & t) const {
curr*=31;
curr+=std::hash<
typename std::decay<
decltype(t.template Item<i>())
>::type
>()(t.template Item<i>());
return compute_hash<i+1>(curr,t);
}
template <Word i>
typename std::enable_if<
i>=sizeof...(Args),
size_t
>::type compute_hash (size_t curr, const Tuple<Args...> &) const noexcept {
return curr;
}
public:
size_t operator () (const Tuple<Args...> & t) const {
return compute_hash<0>(23,t);
}
};
template <typename T>
struct hash<SmartPointer<T>> {
public:
size_t operator () (const SmartPointer<T> & sp) const noexcept {
return hash<const T *>()(static_cast<const T *>(sp));
}
};
}
/**
* \endcond
*/
<|endoftext|>
|
<commit_before>#include "read.h"
#include <boost/dynamic_bitset.hpp>
#include <numeric>
#include <iostream>
std::string ReadBase::bit_to_str(const BitSet &bits) {
size_t str_len = bits.size()/2;
std::string out;
out.resize(str_len);
size_t i = bits.size() -1;
for(size_t stridx = 0; stridx < str_len; ++stridx) {
if (bits[i] == 0 && bits[i-1] == 0) {
out[stridx] = 'A';
} else if (bits[i] == 0 && bits[i-1] == 1) {
out[stridx] = 'C';
} else if (bits[i] == 1 && bits[i-1] == 0) {
out[stridx] = 'G';
} else {
out[stridx] = 'T';
}
i -= 2;
}
return out;
}
// Read
Read Read::subread(size_t start, size_t length){
return Read(seq.substr(start, length), qual.substr(start,length), id);
}
std::string Read::subseq(size_t start, size_t length){
return seq.substr(start, length);
}
//PairedEndRead
boost::optional<BitSet> PairedEndRead::get_key(size_t start, size_t length){
return std::max(str_to_bit(one.subseq(start, length) + two.subseq(start, length)),
str_to_bit(two.subseq(start, length) + one.subseq(start, length)));
}
boost::optional<BitSet> ReadBase::reverse_complement(const std::string& str, int start, int length) {
auto rstart = str.rbegin() + start;
auto rend = str.rbegin() + start + length;
auto rv = str_to_bit(std::string(rstart, rend));
if (rv) {
return ~(*rv);
} else {
return rv;
}
}
//SingleEndRead
boost::optional<BitSet> SingleEndRead::get_key(size_t start, size_t length){
//The C ensures no PE and SE are mapped to the same locaitn
return str_to_bit("C" + one.subseq(start, length*2));
}
inline size_t qual_sum(size_t s, const char c) {
return size_t(c) + s;
}
double SingleEndRead::avg_q_score()
{
size_t sum = std::accumulate(one.get_qual().begin(), one.get_qual().end(), size_t(0), qual_sum);
return sum/double(one.get_qual().length());
}
double PairedEndRead::avg_q_score()
{
size_t sum = std::accumulate(one.get_qual().begin(), one.get_qual().end(), size_t(0), qual_sum);
sum += std::accumulate(two.get_qual().begin(), two.get_qual().end(), size_t(0), qual_sum);
return sum/double(one.get_qual().length() + two.get_qual().length());
}
<commit_msg>Removed unused header files<commit_after>#include "read.h"
#include <boost/dynamic_bitset.hpp>
#include <numeric>
std::string ReadBase::bit_to_str(const BitSet &bits) {
size_t str_len = bits.size()/2;
std::string out;
out.resize(str_len);
size_t i = bits.size() -1;
for(size_t stridx = 0; stridx < str_len; ++stridx) {
if (bits[i] == 0 && bits[i-1] == 0) {
out[stridx] = 'A';
} else if (bits[i] == 0 && bits[i-1] == 1) {
out[stridx] = 'C';
} else if (bits[i] == 1 && bits[i-1] == 0) {
out[stridx] = 'G';
} else {
out[stridx] = 'T';
}
i -= 2;
}
return out;
}
// Read
Read Read::subread(size_t start, size_t length){
return Read(seq.substr(start, length), qual.substr(start,length), id);
}
std::string Read::subseq(size_t start, size_t length){
return seq.substr(start, length);
}
//PairedEndRead
boost::optional<BitSet> PairedEndRead::get_key(size_t start, size_t length){
return std::max(str_to_bit(one.subseq(start, length) + two.subseq(start, length)),
str_to_bit(two.subseq(start, length) + one.subseq(start, length)));
}
boost::optional<BitSet> ReadBase::reverse_complement(const std::string& str, int start, int length) {
auto rstart = str.rbegin() + start;
auto rend = str.rbegin() + start + length;
auto rv = str_to_bit(std::string(rstart, rend));
if (rv) {
return ~(*rv);
} else {
return rv;
}
}
//SingleEndRead
boost::optional<BitSet> SingleEndRead::get_key(size_t start, size_t length){
//The C ensures no PE and SE are mapped to the same locaitn
return str_to_bit("C" + one.subseq(start, length*2));
}
inline size_t qual_sum(size_t s, const char c) {
return size_t(c) + s;
}
double SingleEndRead::avg_q_score()
{
size_t sum = std::accumulate(one.get_qual().begin(), one.get_qual().end(), size_t(0), qual_sum);
return sum/double(one.get_qual().length());
}
double PairedEndRead::avg_q_score()
{
size_t sum = std::accumulate(one.get_qual().begin(), one.get_qual().end(), size_t(0), qual_sum);
sum += std::accumulate(two.get_qual().begin(), two.get_qual().end(), size_t(0), qual_sum);
return sum/double(one.get_qual().length() + two.get_qual().length());
}
<|endoftext|>
|
<commit_before>#include "mitkAffineInteractor.h"
#include "mitkInteractionConst.h"
#include <mitkDataTreeNode.h>
#include "mitkGeometry3D.h"
#include "mitkAffineTransformationOperation.h"
#include "mitkPositionEvent.h"
#include "vtkTransform.h"
#include <mitkRenderWindow.h>
#include <math.h>
mitk::AffineInteractor::AffineInteractor(std::string type, DataTreeNode* dataTreeNode)
: Interactor(type, dataTreeNode)
{
//m_ScaleFactor = 1.0;
}
bool mitk::AffineInteractor::ExecuteSideEffect(int sideEffectId, mitk::StateEvent const* stateEvent, int objectEventId, int groupEventId)
{
bool ok = false;//for return type bool
mitk::Geometry3D* geometry = m_DataTreeNode->GetData()->GetGeometry();
if (geometry == NULL)
return false;
/* Each case must watch the type of the event! */
switch (sideEffectId)
{
case SeNEWPOINT:
{
break;
}
case SeTRANSLATE:
{
mitk::PositionEvent const *posEvent = dynamic_cast <const mitk::PositionEvent *> (stateEvent->GetEvent());
if (posEvent == NULL) return false;
//converting from Point3D to itk::Point
mitk::ITKPoint3D newPosition;
mitk::vm2itk(posEvent->GetWorldPosition(), newPosition);
// create operation with new position
AffineTransformationOperation* doOp = new mitk::AffineTransformationOperation(OpMOVE, newPosition, 0.0, 0); // Index is not used here
if (m_UndoEnabled) //write to UndoMechanism
{
mitk::ScalarType pos[3];
geometry->GetTransform()->GetPosition(pos);
mitk::ITKPoint3D oldPosition;
oldPosition[0] = pos[0];
oldPosition[1] = pos[1];
oldPosition[2] = pos[2];
AffineTransformationOperation* undoOp = new mitk::AffineTransformationOperation(OpMOVE, oldPosition, 0.0, 0);
OperationEvent *operationEvent = new OperationEvent(geometry,
doOp, undoOp,
objectEventId, groupEventId);
m_UndoController->SetOperationEvent(operationEvent);
}
//execute the Operation
geometry->ExecuteOperation(doOp);
ok = true;
break;
}
case SeROTATESTART:
{
mitk::PositionEvent const *posEvent = dynamic_cast <const mitk::PositionEvent *> (stateEvent->GetEvent());
if (posEvent == NULL) return false;
//converting from Point3D to itk::Point
mitk::ITKPoint3D newPosition;
mitk::vm2itk(posEvent->GetWorldPosition(), newPosition);
// save mouse down position
m_lastRotatePosition = newPosition.GetVectorFromOrigin();
ok = true;
break;
}
case SeROTATE:
{
mitk::PositionEvent const *posEvent = dynamic_cast <const mitk::PositionEvent *> (stateEvent->GetEvent());
if (posEvent == NULL) return false;
//converting from Point3D to itk::Point
mitk::ITKPoint3D dummy;
mitk::vm2itk(posEvent->GetWorldPosition(), dummy);
mitk::ITKVector3D newPosition = dummy.GetVectorFromOrigin();
mitk::ScalarType position[3];
geometry->GetTransform()->GetPosition(position);
mitk::ITKVector3D dataPosition = position;
newPosition -= dataPosition; // calculate vector from center of the data object to the mouse position
mitk::ITKVector3D startPosition = m_lastRotatePosition - dataPosition; // calculate vector from center of the data object to the last mouse position
mitk::ITKVector3D rotationaxis; // calculate rotation axis (by calculating the cross produkt of the vectors)
rotationaxis[0] = startPosition[1] * newPosition[2] - startPosition[2] * newPosition[1];
rotationaxis[1] = startPosition[2] * newPosition[0] - startPosition[0] * newPosition[2];
rotationaxis[2] = startPosition[0] * newPosition[1] - startPosition[1] * newPosition[0];
mitk::ScalarType angle = atan2(rotationaxis.GetNorm(), newPosition * startPosition) * (180/(4 * atan(1)));
m_lastRotatePosition = dummy.GetVectorFromOrigin(); // save actual mouse position as last mouse position
dummy[0] = rotationaxis[0]; // encapsulate rotation vector into a ITKPoint3D for the Operation
dummy[1] = rotationaxis[1];
dummy[2] = rotationaxis[2];
// create operation with angle and axis
AffineTransformationOperation* doOp = new mitk::AffineTransformationOperation(OpROTATE, dummy, angle, 0); // Index is not used here
if (m_UndoEnabled) //write to UndoMechanism
{
AffineTransformationOperation* undoOp = new mitk::AffineTransformationOperation(OpROTATE, dummy, -angle, 0); // Index is not used here
OperationEvent *operationEvent = new OperationEvent(geometry,
doOp, undoOp,
objectEventId, groupEventId);
m_UndoController->SetOperationEvent(operationEvent);
}
//execute the Operation
geometry->ExecuteOperation(doOp);
ok = true;
break;
}
case SeSCALESTART:
{
mitk::PositionEvent const *posEvent = dynamic_cast <const mitk::PositionEvent *> (stateEvent->GetEvent());
if (posEvent == NULL) return false;
//converting from Point3D to itk::Point
mitk::ITKPoint3D newPosition;
mitk::vm2itk(posEvent->GetWorldPosition(), newPosition);
m_lastScalePosition = newPosition;
mitk::ScalarType lastScale[3];
// Save initial scale
geometry->GetTransform()->GetScale(lastScale);
m_lastScaleData = lastScale;
ok = true;
break;
}
case SeSCALE:
{
mitk::PositionEvent const *posEvent = dynamic_cast <const mitk::PositionEvent *> (stateEvent->GetEvent());
if (posEvent == NULL) return false;
//converting from Point3D to itk::Point
mitk::ITKPoint3D newPosition;
mitk::vm2itk(posEvent->GetWorldPosition(), newPosition);
mitk::ITKPoint3D newScale;
newScale[0] = m_lastScaleData[0] + (newPosition[0] - m_lastScalePosition[0]);// * m_ScaleFactor;
newScale[1] = m_lastScaleData[1] + (newPosition[1] - m_lastScalePosition[1]);// * m_ScaleFactor;
newScale[2] = m_lastScaleData[2] + (newPosition[2] - m_lastScalePosition[2]);// * m_ScaleFactor;
newScale[0] = (newScale[0] < 1) ? 1 : newScale[0]; // cap at a minimum scale factor of 1
newScale[1] = (newScale[1] < 1) ? 1 : newScale[1];
newScale[2] = (newScale[2] < 1) ? 1 : newScale[2];
AffineTransformationOperation* doOp = new mitk::AffineTransformationOperation(OpSCALE, newScale, 0.0, 0); // Index is not used here
if (m_UndoEnabled) //write to UndoMechanism
{
mitk::ScalarType oldScale[3];
geometry->GetTransform()->GetScale(oldScale);
mitk::ITKPoint3D oldScaleData = oldScale;
AffineTransformationOperation* undoOp = new mitk::AffineTransformationOperation(OpSCALE, oldScaleData, 0.0, 0);
OperationEvent *operationEvent = new OperationEvent(geometry,
doOp, undoOp,
objectEventId, groupEventId);
m_UndoController->SetOperationEvent(operationEvent);
}
//execute the Operation
geometry->ExecuteOperation(doOp);
ok = true;
break;
}
default:
ok = true;
}
mitk::RenderWindow::UpdateAllInstances();
return ok;
}
<commit_msg>changed computation of the angle for the rotation event<commit_after>#include "mitkAffineInteractor.h"
#include "mitkInteractionConst.h"
#include <mitkDataTreeNode.h>
#include "mitkGeometry3D.h"
#include "mitkAffineTransformationOperation.h"
#include "mitkPositionEvent.h"
#include "vtkTransform.h"
#include <mitkRenderWindow.h>
#include <math.h>
mitk::AffineInteractor::AffineInteractor(std::string type, DataTreeNode* dataTreeNode)
: Interactor(type, dataTreeNode)
{
//m_ScaleFactor = 1.0;
}
bool mitk::AffineInteractor::ExecuteSideEffect(int sideEffectId, mitk::StateEvent const* stateEvent, int objectEventId, int groupEventId)
{
bool ok = false;//for return type bool
mitk::Geometry3D* geometry = m_DataTreeNode->GetData()->GetGeometry();
if (geometry == NULL)
return false;
/* Each case must watch the type of the event! */
switch (sideEffectId)
{
case SeNEWPOINT:
{
break;
}
case SeTRANSLATE:
{
mitk::PositionEvent const *posEvent = dynamic_cast <const mitk::PositionEvent *> (stateEvent->GetEvent());
if (posEvent == NULL) return false;
//converting from Point3D to itk::Point
mitk::ITKPoint3D newPosition;
mitk::vm2itk(posEvent->GetWorldPosition(), newPosition);
// create operation with new position
AffineTransformationOperation* doOp = new mitk::AffineTransformationOperation(OpMOVE, newPosition, 0.0, 0); // Index is not used here
if (m_UndoEnabled) //write to UndoMechanism
{
mitk::ScalarType pos[3];
geometry->GetTransform()->GetPosition(pos);
mitk::ITKPoint3D oldPosition;
oldPosition[0] = pos[0];
oldPosition[1] = pos[1];
oldPosition[2] = pos[2];
AffineTransformationOperation* undoOp = new mitk::AffineTransformationOperation(OpMOVE, oldPosition, 0.0, 0);
OperationEvent *operationEvent = new OperationEvent(geometry,
doOp, undoOp,
objectEventId, groupEventId);
m_UndoController->SetOperationEvent(operationEvent);
}
//execute the Operation
geometry->ExecuteOperation(doOp);
ok = true;
break;
}
case SeROTATESTART:
{
mitk::PositionEvent const *posEvent = dynamic_cast <const mitk::PositionEvent *> (stateEvent->GetEvent());
if (posEvent == NULL) return false;
//converting from Point3D to itk::Point
mitk::ITKPoint3D newPosition;
mitk::vm2itk(posEvent->GetWorldPosition(), newPosition);
// save mouse down position
m_lastRotatePosition = newPosition.GetVectorFromOrigin();
ok = true;
break;
}
case SeROTATE:
{
mitk::PositionEvent const *posEvent = dynamic_cast <const mitk::PositionEvent *> (stateEvent->GetEvent());
if (posEvent == NULL) return false;
//converting from Point3D to itk::Point
mitk::ITKPoint3D dummy;
mitk::vm2itk(posEvent->GetWorldPosition(), dummy);
mitk::ITKVector3D newPosition = dummy.GetVectorFromOrigin();
mitk::ScalarType position[3];
geometry->GetTransform()->GetPosition(position);
mitk::ITKVector3D dataPosition = position;
newPosition -= dataPosition; // calculate vector from center of the data object to the mouse position
mitk::ITKVector3D startPosition = m_lastRotatePosition - dataPosition; // calculate vector from center of the data object to the last mouse position
mitk::ITKVector3D rotationaxis; // calculate rotation axis (by calculating the cross produkt of the vectors)
rotationaxis[0] = startPosition[1] * newPosition[2] - startPosition[2] * newPosition[1];
rotationaxis[1] = startPosition[2] * newPosition[0] - startPosition[0] * newPosition[2];
rotationaxis[2] = startPosition[0] * newPosition[1] - startPosition[1] * newPosition[0];
mitk::ScalarType angle = atan2(rotationaxis.GetNorm(), newPosition * startPosition) * (180/vnl_math::pi);
m_lastRotatePosition = dummy.GetVectorFromOrigin(); // save actual mouse position as last mouse position
dummy[0] = rotationaxis[0]; // encapsulate rotation vector into a ITKPoint3D for the Operation
dummy[1] = rotationaxis[1];
dummy[2] = rotationaxis[2];
// create operation with angle and axis
AffineTransformationOperation* doOp = new mitk::AffineTransformationOperation(OpROTATE, dummy, angle, 0); // Index is not used here
if (m_UndoEnabled) //write to UndoMechanism
{
AffineTransformationOperation* undoOp = new mitk::AffineTransformationOperation(OpROTATE, dummy, -angle, 0); // Index is not used here
OperationEvent *operationEvent = new OperationEvent(geometry,
doOp, undoOp,
objectEventId, groupEventId);
m_UndoController->SetOperationEvent(operationEvent);
}
//execute the Operation
geometry->ExecuteOperation(doOp);
ok = true;
break;
}
case SeSCALESTART:
{
mitk::PositionEvent const *posEvent = dynamic_cast <const mitk::PositionEvent *> (stateEvent->GetEvent());
if (posEvent == NULL) return false;
//converting from Point3D to itk::Point
mitk::ITKPoint3D newPosition;
mitk::vm2itk(posEvent->GetWorldPosition(), newPosition);
m_lastScalePosition = newPosition;
mitk::ScalarType lastScale[3];
// Save initial scale
geometry->GetTransform()->GetScale(lastScale);
m_lastScaleData = lastScale;
ok = true;
break;
}
case SeSCALE:
{
mitk::PositionEvent const *posEvent = dynamic_cast <const mitk::PositionEvent *> (stateEvent->GetEvent());
if (posEvent == NULL) return false;
//converting from Point3D to itk::Point
mitk::ITKPoint3D newPosition;
mitk::vm2itk(posEvent->GetWorldPosition(), newPosition);
mitk::ITKPoint3D newScale;
newScale[0] = m_lastScaleData[0] + (newPosition[0] - m_lastScalePosition[0]);// * m_ScaleFactor;
newScale[1] = m_lastScaleData[1] + (newPosition[1] - m_lastScalePosition[1]);// * m_ScaleFactor;
newScale[2] = m_lastScaleData[2] + (newPosition[2] - m_lastScalePosition[2]);// * m_ScaleFactor;
newScale[0] = (newScale[0] < 1) ? 1 : newScale[0]; // cap at a minimum scale factor of 1
newScale[1] = (newScale[1] < 1) ? 1 : newScale[1];
newScale[2] = (newScale[2] < 1) ? 1 : newScale[2];
AffineTransformationOperation* doOp = new mitk::AffineTransformationOperation(OpSCALE, newScale, 0.0, 0); // Index is not used here
if (m_UndoEnabled) //write to UndoMechanism
{
mitk::ScalarType oldScale[3];
geometry->GetTransform()->GetScale(oldScale);
mitk::ITKPoint3D oldScaleData = oldScale;
AffineTransformationOperation* undoOp = new mitk::AffineTransformationOperation(OpSCALE, oldScaleData, 0.0, 0);
OperationEvent *operationEvent = new OperationEvent(geometry,
doOp, undoOp,
objectEventId, groupEventId);
m_UndoController->SetOperationEvent(operationEvent);
}
//execute the Operation
geometry->ExecuteOperation(doOp);
ok = true;
break;
}
default:
ok = true;
}
mitk::RenderWindow::UpdateAllInstances();
return ok;
}
<|endoftext|>
|
<commit_before>#pragma once
#include "common.hpp"
#include <algorithm> // for std::min, max
namespace rack {
namespace math {
////////////////////
// basic integer functions
////////////////////
/** Returns true if x is odd */
inline bool isEven(int x) {
return x % 2 == 0;
}
/** Returns true if x is odd */
inline bool isOdd(int x) {
return x % 2 != 0;
}
/** Limits `x` between `a` and `b`
Assumes a <= b
*/
inline int clamp(int x, int a, int b) {
return std::min(std::max(x, a), b);
}
/** Limits `x` between `a` and `b`
If a > b, switches the two values
*/
inline int clampBetween(int x, int a, int b) {
return clamp(x, std::min(a, b), std::max(a, b));
}
/** Euclidean modulus. Always returns 0 <= mod < b.
b must be positive.
*/
inline int eucMod(int a, int b) {
int mod = a % b;
if (mod < 0) {
mod += b;
}
return mod;
}
/** Euclidean division.
b must be positive.
*/
inline int eucDiv(int a, int b) {
int div = a / b;
int mod = a % b;
if (mod < 0) {
div -= 1;
}
return div;
}
inline void eucDivMod(int a, int b, int *div, int *mod) {
*div = a / b;
*mod = a % b;
if (*mod < 0) {
*div -= 1;
*mod += b;
}
}
/** Returns floor(log_2(n)), or 0 if n == 1.
*/
inline int log2(int n) {
int i = 0;
while (n >>= 1) {
i++;
}
return i;
}
inline bool isPow2(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
////////////////////
// basic float functions
////////////////////
/** Limits `x` between `a` and `b`
Assumes a <= b
*/
inline float clamp(float x, float a, float b) {
return std::min(std::max(x, a), b);
}
/** Limits `x` between `a` and `b`
If a > b, switches the two values
*/
inline float clampBetween(float x, float a, float b) {
return clamp(x, std::min(a, b), std::max(a, b));
}
/** Returns 1 for positive numbers, -1 for negative numbers, and 0 for zero */
inline float sgn(float x) {
return x > 0.f ? 1.f : x < 0.f ? -1.f : 0.f;
}
inline float eucMod(float a, float base) {
float mod = std::fmod(a, base);
return (mod >= 0.0f) ? mod : mod + base;
}
inline bool isNear(float a, float b, float epsilon = 1.0e-6f) {
return std::abs(a - b) <= epsilon;
}
/** If the magnitude of x if less than epsilon, return 0 */
inline float chop(float x, float epsilon = 1.0e-6f) {
return isNear(x, 0.f, epsilon) ? 0.f : x;
}
inline float rescale(float x, float a, float b, float yMin, float yMax) {
return yMin + (x - a) / (b - a) * (yMax - yMin);
}
inline float crossfade(float a, float b, float frac) {
return a + frac * (b - a);
}
/** Linearly interpolate an array `p` with index `x`
Assumes that the array at `p` is of length at least floor(x)+1.
*/
inline float interpolateLinear(const float *p, float x) {
int xi = x;
float xf = x - xi;
return crossfade(p[xi], p[xi+1], xf);
}
/** Complex multiply c = a * b
Arguments may be the same pointers
i.e. cmultf(&ar, &ai, ar, ai, br, bi)
*/
inline void cmult(float *cr, float *ci, float ar, float ai, float br, float bi) {
*cr = ar * br - ai * bi;
*ci = ar * bi + ai * br;
}
////////////////////
// 2D vector and rectangle
////////////////////
struct Rect;
struct Vec {
float x = 0.f;
float y = 0.f;
Vec() {}
Vec(float x, float y) : x(x), y(y) {}
Vec neg() const {
return Vec(-x, -y);
}
Vec plus(Vec b) const {
return Vec(x + b.x, y + b.y);
}
Vec minus(Vec b) const {
return Vec(x - b.x, y - b.y);
}
Vec mult(float s) const {
return Vec(x * s, y * s);
}
Vec mult(Vec b) const {
return Vec(x * b.x, y * b.y);
}
Vec div(float s) const {
return Vec(x / s, y / s);
}
Vec div(Vec b) const {
return Vec(x / b.x, y / b.y);
}
float dot(Vec b) const {
return x * b.x + y * b.y;
}
float norm() const {
return std::hypotf(x, y);
}
Vec flip() const {
return Vec(y, x);
}
Vec min(Vec b) const {
return Vec(std::min(x, b.x), std::min(y, b.y));
}
Vec max(Vec b) const {
return Vec(std::max(x, b.x), std::max(y, b.y));
}
Vec round() const {
return Vec(std::round(x), std::round(y));
}
Vec floor() const {
return Vec(std::floor(x), std::floor(y));
}
Vec ceil() const {
return Vec(std::ceil(x), std::ceil(y));
}
bool isEqual(Vec b) const {
return x == b.x && y == b.y;
}
bool isZero() const {
return x == 0.0f && y == 0.0f;
}
bool isFinite() const {
return std::isfinite(x) && std::isfinite(y);
}
Vec clamp(Rect bound) const;
Vec clampBetween(Rect bound) const;
DEPRECATED Vec clamp2(Rect bound) const;
};
struct Rect {
Vec pos;
Vec size;
Rect() {}
Rect(Vec pos, Vec size) : pos(pos), size(size) {}
/** Constructs a Rect from the upper-left position `a` and lower-right pos `b` */
static Rect fromMinMax(Vec a, Vec b) {
return Rect(a, b.minus(a));
}
/** Returns whether this Rect contains an entire point, inclusive on the top/left, non-inclusive on the bottom/right */
bool contains(Vec v) const {
return pos.x <= v.x && v.x < pos.x + size.x
&& pos.y <= v.y && v.y < pos.y + size.y;
}
/** Returns whether this Rect contains an entire Rect */
bool contains(Rect r) const {
return pos.x <= r.pos.x && r.pos.x + r.size.x <= pos.x + size.x
&& pos.y <= r.pos.y && r.pos.y + r.size.y <= pos.y + size.y;
}
/** Returns whether this Rect overlaps with another Rect */
bool intersects(Rect r) const {
return (pos.x + size.x > r.pos.x && r.pos.x + r.size.x > pos.x)
&& (pos.y + size.y > r.pos.y && r.pos.y + r.size.y > pos.y);
}
bool isEqual(Rect r) const {
return pos.isEqual(r.pos) && size.isEqual(r.size);
}
float getLeft() const {
return pos.x + size.x;
}
float getBottom() const {
return pos.y + size.y;
}
Vec getCenter() const {
return pos.plus(size.mult(0.5f));
}
Vec getTopLeft() const {
return pos;
}
Vec getTopRight() const {
return pos.plus(Vec(size.x, 0.f));
}
Vec getBottomLeft() const {
return pos.plus(Vec(0.f, size.y));
}
Vec getBottomRight() const {
return pos.plus(size);
}
/** Clamps the edges of the rectangle to fit within a bound */
Rect clamp(Rect bound) const {
Rect r;
r.pos.x = clampBetween(pos.x, bound.pos.x, bound.pos.x + bound.size.x);
r.pos.y = clampBetween(pos.y, bound.pos.y, bound.pos.y + bound.size.y);
r.size.x = math::clamp(pos.x + size.x, bound.pos.x, bound.pos.x + bound.size.x) - r.pos.x;
r.size.y = math::clamp(pos.y + size.y, bound.pos.y, bound.pos.y + bound.size.y) - r.pos.y;
return r;
}
/** Nudges the position to fix inside a bounding box */
Rect nudge(Rect bound) const {
Rect r;
r.size = size;
r.pos.x = clampBetween(pos.x, bound.pos.x, bound.pos.x + bound.size.x - size.x);
r.pos.y = clampBetween(pos.y, bound.pos.y, bound.pos.y + bound.size.y - size.y);
return r;
}
/** Expands this Rect to contain `other` */
Rect expand(Rect other) const {
Rect r;
r.pos.x = std::min(pos.x, other.pos.x);
r.pos.y = std::min(pos.y, other.pos.y);
r.size.x = std::max(pos.x + size.x, other.pos.x + other.size.x) - r.pos.x;
r.size.y = std::max(pos.y + size.y, other.pos.y + other.size.y) - r.pos.y;
return r;
}
/** Returns a Rect with its position set to zero */
Rect zeroPos() const {
return Rect(Vec(), size);
}
/** Expands each corner
Use a negative delta to shrink.
*/
Rect grow(Vec delta) const {
Rect r;
r.pos = pos.minus(delta);
r.size = size.plus(delta.mult(2.f));
return r;
}
};
inline Vec Vec::clamp(Rect bound) const {
return Vec(
math::clamp(x, bound.pos.x, bound.pos.x + bound.size.x),
math::clamp(y, bound.pos.y, bound.pos.y + bound.size.y));
}
inline Vec Vec::clampBetween(Rect bound) const {
return Vec(
math::clampBetween(x, bound.pos.x, bound.pos.x + bound.size.x),
math::clampBetween(y, bound.pos.y, bound.pos.y + bound.size.y));
}
inline Vec Vec::clamp2(Rect bound) const {return clampBetween(bound);}
} // namespace math
} // namespace rack
<commit_msg>Add Vec::rotate()<commit_after>#pragma once
#include "common.hpp"
#include <algorithm> // for std::min, max
namespace rack {
namespace math {
////////////////////
// basic integer functions
////////////////////
/** Returns true if x is odd */
inline bool isEven(int x) {
return x % 2 == 0;
}
/** Returns true if x is odd */
inline bool isOdd(int x) {
return x % 2 != 0;
}
/** Limits `x` between `a` and `b`
Assumes a <= b
*/
inline int clamp(int x, int a, int b) {
return std::min(std::max(x, a), b);
}
/** Limits `x` between `a` and `b`
If a > b, switches the two values
*/
inline int clampBetween(int x, int a, int b) {
return clamp(x, std::min(a, b), std::max(a, b));
}
/** Euclidean modulus. Always returns 0 <= mod < b.
b must be positive.
*/
inline int eucMod(int a, int b) {
int mod = a % b;
if (mod < 0) {
mod += b;
}
return mod;
}
/** Euclidean division.
b must be positive.
*/
inline int eucDiv(int a, int b) {
int div = a / b;
int mod = a % b;
if (mod < 0) {
div -= 1;
}
return div;
}
inline void eucDivMod(int a, int b, int *div, int *mod) {
*div = a / b;
*mod = a % b;
if (*mod < 0) {
*div -= 1;
*mod += b;
}
}
/** Returns floor(log_2(n)), or 0 if n == 1.
*/
inline int log2(int n) {
int i = 0;
while (n >>= 1) {
i++;
}
return i;
}
inline bool isPow2(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
////////////////////
// basic float functions
////////////////////
/** Limits `x` between `a` and `b`
Assumes a <= b
*/
inline float clamp(float x, float a, float b) {
return std::min(std::max(x, a), b);
}
/** Limits `x` between `a` and `b`
If a > b, switches the two values
*/
inline float clampBetween(float x, float a, float b) {
return clamp(x, std::min(a, b), std::max(a, b));
}
/** Returns 1 for positive numbers, -1 for negative numbers, and 0 for zero */
inline float sgn(float x) {
return x > 0.f ? 1.f : x < 0.f ? -1.f : 0.f;
}
inline float eucMod(float a, float base) {
float mod = std::fmod(a, base);
return (mod >= 0.0f) ? mod : mod + base;
}
inline bool isNear(float a, float b, float epsilon = 1.0e-6f) {
return std::abs(a - b) <= epsilon;
}
/** If the magnitude of x if less than epsilon, return 0 */
inline float chop(float x, float epsilon = 1.0e-6f) {
return isNear(x, 0.f, epsilon) ? 0.f : x;
}
inline float rescale(float x, float a, float b, float yMin, float yMax) {
return yMin + (x - a) / (b - a) * (yMax - yMin);
}
inline float crossfade(float a, float b, float frac) {
return a + frac * (b - a);
}
/** Linearly interpolate an array `p` with index `x`
Assumes that the array at `p` is of length at least floor(x)+1.
*/
inline float interpolateLinear(const float *p, float x) {
int xi = x;
float xf = x - xi;
return crossfade(p[xi], p[xi+1], xf);
}
/** Complex multiply c = a * b
Arguments may be the same pointers
i.e. cmultf(&ar, &ai, ar, ai, br, bi)
*/
inline void cmult(float *cr, float *ci, float ar, float ai, float br, float bi) {
*cr = ar * br - ai * bi;
*ci = ar * bi + ai * br;
}
////////////////////
// 2D vector and rectangle
////////////////////
struct Rect;
struct Vec {
float x = 0.f;
float y = 0.f;
Vec() {}
Vec(float x, float y) : x(x), y(y) {}
/** Negates the vector
Equivalent to a reflection across the y=-x line.
*/
Vec neg() const {
return Vec(-x, -y);
}
Vec plus(Vec b) const {
return Vec(x + b.x, y + b.y);
}
Vec minus(Vec b) const {
return Vec(x - b.x, y - b.y);
}
Vec mult(float s) const {
return Vec(x * s, y * s);
}
Vec mult(Vec b) const {
return Vec(x * b.x, y * b.y);
}
Vec div(float s) const {
return Vec(x / s, y / s);
}
Vec div(Vec b) const {
return Vec(x / b.x, y / b.y);
}
float dot(Vec b) const {
return x * b.x + y * b.y;
}
float norm() const {
return std::hypotf(x, y);
}
/** Rotates counterclockwise in radians */
Vec rotate(float angle) {
float sin = std::sin(angle);
float cos = std::cos(angle);
return Vec(x * cos - y * sin, x * sin + y * cos);
}
/** Swaps the coordinates
Equivalent to a reflection across the y=x line.
*/
Vec flip() const {
return Vec(y, x);
}
Vec min(Vec b) const {
return Vec(std::min(x, b.x), std::min(y, b.y));
}
Vec max(Vec b) const {
return Vec(std::max(x, b.x), std::max(y, b.y));
}
Vec round() const {
return Vec(std::round(x), std::round(y));
}
Vec floor() const {
return Vec(std::floor(x), std::floor(y));
}
Vec ceil() const {
return Vec(std::ceil(x), std::ceil(y));
}
bool isEqual(Vec b) const {
return x == b.x && y == b.y;
}
bool isZero() const {
return x == 0.0f && y == 0.0f;
}
bool isFinite() const {
return std::isfinite(x) && std::isfinite(y);
}
Vec clamp(Rect bound) const;
Vec clampBetween(Rect bound) const;
DEPRECATED Vec clamp2(Rect bound) const;
};
struct Rect {
Vec pos;
Vec size;
Rect() {}
Rect(Vec pos, Vec size) : pos(pos), size(size) {}
/** Constructs a Rect from the upper-left position `a` and lower-right pos `b` */
static Rect fromMinMax(Vec a, Vec b) {
return Rect(a, b.minus(a));
}
/** Returns whether this Rect contains an entire point, inclusive on the top/left, non-inclusive on the bottom/right */
bool contains(Vec v) const {
return pos.x <= v.x && v.x < pos.x + size.x
&& pos.y <= v.y && v.y < pos.y + size.y;
}
/** Returns whether this Rect contains an entire Rect */
bool contains(Rect r) const {
return pos.x <= r.pos.x && r.pos.x + r.size.x <= pos.x + size.x
&& pos.y <= r.pos.y && r.pos.y + r.size.y <= pos.y + size.y;
}
/** Returns whether this Rect overlaps with another Rect */
bool intersects(Rect r) const {
return (pos.x + size.x > r.pos.x && r.pos.x + r.size.x > pos.x)
&& (pos.y + size.y > r.pos.y && r.pos.y + r.size.y > pos.y);
}
bool isEqual(Rect r) const {
return pos.isEqual(r.pos) && size.isEqual(r.size);
}
float getLeft() const {
return pos.x + size.x;
}
float getBottom() const {
return pos.y + size.y;
}
Vec getCenter() const {
return pos.plus(size.mult(0.5f));
}
Vec getTopLeft() const {
return pos;
}
Vec getTopRight() const {
return pos.plus(Vec(size.x, 0.f));
}
Vec getBottomLeft() const {
return pos.plus(Vec(0.f, size.y));
}
Vec getBottomRight() const {
return pos.plus(size);
}
/** Clamps the edges of the rectangle to fit within a bound */
Rect clamp(Rect bound) const {
Rect r;
r.pos.x = clampBetween(pos.x, bound.pos.x, bound.pos.x + bound.size.x);
r.pos.y = clampBetween(pos.y, bound.pos.y, bound.pos.y + bound.size.y);
r.size.x = math::clamp(pos.x + size.x, bound.pos.x, bound.pos.x + bound.size.x) - r.pos.x;
r.size.y = math::clamp(pos.y + size.y, bound.pos.y, bound.pos.y + bound.size.y) - r.pos.y;
return r;
}
/** Nudges the position to fix inside a bounding box */
Rect nudge(Rect bound) const {
Rect r;
r.size = size;
r.pos.x = clampBetween(pos.x, bound.pos.x, bound.pos.x + bound.size.x - size.x);
r.pos.y = clampBetween(pos.y, bound.pos.y, bound.pos.y + bound.size.y - size.y);
return r;
}
/** Expands this Rect to contain `other` */
Rect expand(Rect other) const {
Rect r;
r.pos.x = std::min(pos.x, other.pos.x);
r.pos.y = std::min(pos.y, other.pos.y);
r.size.x = std::max(pos.x + size.x, other.pos.x + other.size.x) - r.pos.x;
r.size.y = std::max(pos.y + size.y, other.pos.y + other.size.y) - r.pos.y;
return r;
}
/** Returns a Rect with its position set to zero */
Rect zeroPos() const {
return Rect(Vec(), size);
}
/** Expands each corner
Use a negative delta to shrink.
*/
Rect grow(Vec delta) const {
Rect r;
r.pos = pos.minus(delta);
r.size = size.plus(delta.mult(2.f));
return r;
}
};
inline Vec Vec::clamp(Rect bound) const {
return Vec(
math::clamp(x, bound.pos.x, bound.pos.x + bound.size.x),
math::clamp(y, bound.pos.y, bound.pos.y + bound.size.y));
}
inline Vec Vec::clampBetween(Rect bound) const {
return Vec(
math::clampBetween(x, bound.pos.x, bound.pos.x + bound.size.x),
math::clampBetween(y, bound.pos.y, bound.pos.y + bound.size.y));
}
inline Vec Vec::clamp2(Rect bound) const {return clampBetween(bound);}
} // namespace math
} // namespace rack
<|endoftext|>
|
<commit_before>/*
Copyright 2002-2013 CEA LIST
This file is part of LIMA.
LIMA is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
LIMA is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with LIMA. If not, see <http://www.gnu.org/licenses/>
*/
/**
* @file configurationStructure.cpp
* @brief originally detectConfigurationStructure.cpp in detectlibraries
* @date begin Mon Oct, 13 2003 (ven oct 18 2002)
* @author Gael de Chalendar <Gael.de-Chalendar@cea.fr>
* copyright (C) 2002-2003 by CEA
*/
#include "common/LimaCommon.h"
#include "xmlConfigurationFileExceptions.h"
#include "configurationStructure.h"
#include <iostream>
using namespace std;
namespace Lima
{
namespace Common
{
namespace XMLConfigurationFiles
{
ConfigurationStructure::ConfigurationStructure() : std::map< std::string, ModuleConfigurationStructure >()
{}
ConfigurationStructure::~ConfigurationStructure()
{}
void ConfigurationStructure::addParamValuePairForModuleAndGroup(const string ¶m,
const string &value, const string &moduleName, const string & group)
{
XMLCFGLOGINIT;
iterator itC = find(moduleName);
if (itC == end())
{
LERROR << "Error adding param '" << moduleName.c_str() << "': no such module !" ;
throw NoSuchModule(moduleName);
}
ModuleConfigurationStructure& moduleGroups = (*itC).second;
moduleGroups.addParamValuePairForGroup(param, value, group);
// erase(moduleName);
// insert(make_pair(moduleName, moduleGroups));
}
void ConfigurationStructure::addListNamedForModuleAndGroup(const string &listName,
const string &moduleName, const string & groupName)
{
XMLCFGLOGINIT;
iterator itC = find(moduleName);
if (itC == end())
{
LERROR << "Error adding param '" << moduleName.c_str() << "': no such module !" ;
throw NoSuchModule(moduleName);
}
ModuleConfigurationStructure& moduleGroups = (*itC).second;
moduleGroups.addListNamedForGroup(listName, groupName);
// erase(moduleName);
// insert(make_pair(moduleName, moduleGroups));
}
void ConfigurationStructure::addItemInListNamedForModuleAndGroup(const string& item,
const string &listName, const string &moduleName, const string & groupName)
{
XMLCFGLOGINIT;
iterator itC = find(moduleName);
if (itC == end())
{
LERROR << "Error adding param '" << moduleName.c_str() << "': no such module !" ;
throw NoSuchModule(moduleName);
}
ModuleConfigurationStructure& moduleGroups = (*itC).second;
moduleGroups.addItemInListNamedForGroup(item, listName, groupName);
// erase(moduleName);
// insert(make_pair(moduleName, moduleGroups));
}
void ConfigurationStructure::addGroupNamedForModuleNamed(const string& groupName,
const string& moduleName)
{
XMLCFGLOGINIT;
iterator itC = find(moduleName);
if (itC == end())
{
LERROR << "Error adding group '" << groupName.c_str() << "': no such module '" << moduleName.c_str() << "' !" ;
throw NoSuchModule(moduleName);
}
ModuleConfigurationStructure& moduleGroups = (*itC).second;
moduleGroups.addGroupNamed(groupName);
// erase(moduleName);
// insert(make_pair(moduleName, moduleGroups));
}
void ConfigurationStructure::addMapNamedForModuleAndGroup(const std::string &mapName, const std::string& moduleName, const std::string& groupName)
{
XMLCFGLOGINIT;
iterator itC = find(moduleName);
if (itC == end())
{
LERROR << "Error adding map '" << mapName.c_str() << "' in group '" << groupName.c_str() << "': no such module '" << moduleName.c_str() << "' !" ;
throw NoSuchModule(moduleName);
}
itC->second.addMapInGroup(mapName,groupName);
}
void ConfigurationStructure::addEntryInMapNamedForModuleAndGroup(const std::string& entryKey,const std::string& entryValue,const std::string& mapName,const std::string& moduleName,const std::string& groupName)
{
XMLCFGLOGINIT;
iterator itC = find(moduleName);
if (itC == end())
{
LERROR << "Error adding mapEntry in '" << mapName.c_str() << "' in group '" << groupName.c_str() << "': no such module '" << moduleName.c_str() << "' !" ;
throw NoSuchModule(moduleName);
}
itC->second.addEntryInMapInGroup(entryKey,entryValue,mapName,groupName);
}
void ConfigurationStructure::addAttributeForGroupInModule(const std::string& attKey,const std::string& attValue,const std::string& groupName,const std::string& moduleName)
{
XMLCFGLOGINIT;
iterator itC = find(moduleName);
if (itC == end())
{
LERROR << "Error adding mapattribute in group '" << groupName.c_str() << "': no such module '" << moduleName.c_str() << "' !" ;
throw NoSuchModule(moduleName);
}
LDEBUG << "add attribute: module='"<<moduleName.c_str()<<"' group='"<<groupName.c_str()<<"' attribute='"<<attKey.c_str()<<"' value='"<<attValue.c_str()<<"'" ;
itC->second.addAttributeInGroup(attKey,attValue,groupName);
}
GroupConfigurationStructure& ConfigurationStructure::
getGroupConf(const std::string& moduleName,
const std::string& group)
{
XMLCFGLOGINIT;
iterator itC = find(moduleName);
if (itC == end())
{
LERROR << "'No such module '" << moduleName.c_str() << "'" ;
throw NoSuchModule(moduleName);
}
return (*itC).second.getGroupNamed(group) ;
}
void ConfigurationStructure::
addListOfItemsForModuleAndGroup(const std::string &listName,
const std::string& moduleName,
const std::string& group)
{
getGroupConf(moduleName,group).addListOfItems(listName);
}
void ConfigurationStructure::
addItemInListOfItemsForModuleAndGroup(const ItemWithAttributes& item,
const std::string &listName,
const std::string& moduleName,
const std::string& group)
{
getGroupConf(moduleName,group).addItemInListOfItems(listName,item);
}
void ConfigurationStructure::
addMapOfItemsForModuleAndGroup(const std::string &mapName,
const std::string& moduleName,
const std::string& group)
{
getGroupConf(moduleName,group).addMapOfItems(mapName);
}
void ConfigurationStructure::
addEntryInMapOfItemsForModuleAndGroup(const std::string& key,
const ItemWithAttributes& item,
const std::string& mapName,
const std::string& moduleName,
const std::string& group)
{
getGroupConf(moduleName,group).addEntryInMapOfItems(mapName,key,item);
}
std::ostream& operator<<(std::ostream &os, const ConfigurationStructure& conf)
{
for (ConfigurationStructure::const_iterator it = conf.begin(); it != conf.end(); it++)
{
const ModuleConfigurationStructure& dmcs((*it).second);
os << (*it).first << std::endl << dmcs;
}
return os;
}
void ConfigurationStructure::
changeListToListOfItems(const std::string &listName,
const std::string& moduleName,
const std::string& group)
{
getGroupConf(moduleName,group).changeListToListOfItems(listName);
}
void ConfigurationStructure::
changeMapToMapOfItems(const std::string &mapName,
const std::string& moduleName,
const std::string& group)
{
getGroupConf(moduleName,group).changeMapToMapOfItems(mapName);
}
} //closing namespace XMLConfigurationFiles
} //closing namespace Common
} //closing namespace Lima
<commit_msg>Move a logger init near its use<commit_after>/*
Copyright 2002-2013 CEA LIST
This file is part of LIMA.
LIMA is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
LIMA is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with LIMA. If not, see <http://www.gnu.org/licenses/>
*/
/**
* @file configurationStructure.cpp
* @brief originally detectConfigurationStructure.cpp in detectlibraries
* @date begin Mon Oct, 13 2003 (ven oct 18 2002)
* @author Gael de Chalendar <Gael.de-Chalendar@cea.fr>
* copyright (C) 2002-2003 by CEA
*/
#include "common/LimaCommon.h"
#include "xmlConfigurationFileExceptions.h"
#include "configurationStructure.h"
#include <iostream>
using namespace std;
namespace Lima
{
namespace Common
{
namespace XMLConfigurationFiles
{
ConfigurationStructure::ConfigurationStructure() : std::map< std::string, ModuleConfigurationStructure >()
{}
ConfigurationStructure::~ConfigurationStructure()
{}
void ConfigurationStructure::addParamValuePairForModuleAndGroup(const string ¶m,
const string &value, const string &moduleName, const string & group)
{
XMLCFGLOGINIT;
iterator itC = find(moduleName);
if (itC == end())
{
LERROR << "Error adding param '" << moduleName.c_str() << "': no such module !" ;
throw NoSuchModule(moduleName);
}
ModuleConfigurationStructure& moduleGroups = (*itC).second;
moduleGroups.addParamValuePairForGroup(param, value, group);
// erase(moduleName);
// insert(make_pair(moduleName, moduleGroups));
}
void ConfigurationStructure::addListNamedForModuleAndGroup(const string &listName,
const string &moduleName, const string & groupName)
{
XMLCFGLOGINIT;
iterator itC = find(moduleName);
if (itC == end())
{
LERROR << "Error adding param '" << moduleName.c_str() << "': no such module !" ;
throw NoSuchModule(moduleName);
}
ModuleConfigurationStructure& moduleGroups = (*itC).second;
moduleGroups.addListNamedForGroup(listName, groupName);
// erase(moduleName);
// insert(make_pair(moduleName, moduleGroups));
}
void ConfigurationStructure::addItemInListNamedForModuleAndGroup(const string& item,
const string &listName, const string &moduleName, const string & groupName)
{
XMLCFGLOGINIT;
iterator itC = find(moduleName);
if (itC == end())
{
LERROR << "Error adding param '" << moduleName.c_str() << "': no such module !" ;
throw NoSuchModule(moduleName);
}
ModuleConfigurationStructure& moduleGroups = (*itC).second;
moduleGroups.addItemInListNamedForGroup(item, listName, groupName);
// erase(moduleName);
// insert(make_pair(moduleName, moduleGroups));
}
void ConfigurationStructure::addGroupNamedForModuleNamed(const string& groupName,
const string& moduleName)
{
XMLCFGLOGINIT;
iterator itC = find(moduleName);
if (itC == end())
{
LERROR << "Error adding group '" << groupName.c_str() << "': no such module '" << moduleName.c_str() << "' !" ;
throw NoSuchModule(moduleName);
}
ModuleConfigurationStructure& moduleGroups = (*itC).second;
moduleGroups.addGroupNamed(groupName);
// erase(moduleName);
// insert(make_pair(moduleName, moduleGroups));
}
void ConfigurationStructure::addMapNamedForModuleAndGroup(const std::string &mapName, const std::string& moduleName, const std::string& groupName)
{
XMLCFGLOGINIT;
iterator itC = find(moduleName);
if (itC == end())
{
LERROR << "Error adding map '" << mapName.c_str() << "' in group '" << groupName.c_str() << "': no such module '" << moduleName.c_str() << "' !" ;
throw NoSuchModule(moduleName);
}
itC->second.addMapInGroup(mapName,groupName);
}
void ConfigurationStructure::addEntryInMapNamedForModuleAndGroup(const std::string& entryKey,const std::string& entryValue,const std::string& mapName,const std::string& moduleName,const std::string& groupName)
{
XMLCFGLOGINIT;
iterator itC = find(moduleName);
if (itC == end())
{
LERROR << "Error adding mapEntry in '" << mapName.c_str() << "' in group '" << groupName.c_str() << "': no such module '" << moduleName.c_str() << "' !" ;
throw NoSuchModule(moduleName);
}
itC->second.addEntryInMapInGroup(entryKey,entryValue,mapName,groupName);
}
void ConfigurationStructure::addAttributeForGroupInModule(const std::string& attKey,const std::string& attValue,const std::string& groupName,const std::string& moduleName)
{
XMLCFGLOGINIT;
iterator itC = find(moduleName);
if (itC == end())
{
LERROR << "Error adding mapattribute in group '" << groupName.c_str() << "': no such module '" << moduleName.c_str() << "' !" ;
throw NoSuchModule(moduleName);
}
LDEBUG << "add attribute: module='"<<moduleName.c_str()<<"' group='"<<groupName.c_str()<<"' attribute='"<<attKey.c_str()<<"' value='"<<attValue.c_str()<<"'" ;
itC->second.addAttributeInGroup(attKey,attValue,groupName);
}
GroupConfigurationStructure& ConfigurationStructure::
getGroupConf(const std::string& moduleName,
const std::string& group)
{
iterator itC = find(moduleName);
if (itC == end())
{
XMLCFGLOGINIT;
LERROR << "'No such module '" << moduleName.c_str() << "'" ;
throw NoSuchModule(moduleName);
}
return (*itC).second.getGroupNamed(group) ;
}
void ConfigurationStructure::
addListOfItemsForModuleAndGroup(const std::string &listName,
const std::string& moduleName,
const std::string& group)
{
getGroupConf(moduleName,group).addListOfItems(listName);
}
void ConfigurationStructure::
addItemInListOfItemsForModuleAndGroup(const ItemWithAttributes& item,
const std::string &listName,
const std::string& moduleName,
const std::string& group)
{
getGroupConf(moduleName,group).addItemInListOfItems(listName,item);
}
void ConfigurationStructure::
addMapOfItemsForModuleAndGroup(const std::string &mapName,
const std::string& moduleName,
const std::string& group)
{
getGroupConf(moduleName,group).addMapOfItems(mapName);
}
void ConfigurationStructure::
addEntryInMapOfItemsForModuleAndGroup(const std::string& key,
const ItemWithAttributes& item,
const std::string& mapName,
const std::string& moduleName,
const std::string& group)
{
getGroupConf(moduleName,group).addEntryInMapOfItems(mapName,key,item);
}
std::ostream& operator<<(std::ostream &os, const ConfigurationStructure& conf)
{
for (ConfigurationStructure::const_iterator it = conf.begin(); it != conf.end(); it++)
{
const ModuleConfigurationStructure& dmcs((*it).second);
os << (*it).first << std::endl << dmcs;
}
return os;
}
void ConfigurationStructure::
changeListToListOfItems(const std::string &listName,
const std::string& moduleName,
const std::string& group)
{
getGroupConf(moduleName,group).changeListToListOfItems(listName);
}
void ConfigurationStructure::
changeMapToMapOfItems(const std::string &mapName,
const std::string& moduleName,
const std::string& group)
{
getGroupConf(moduleName,group).changeMapToMapOfItems(mapName);
}
} //closing namespace XMLConfigurationFiles
} //closing namespace Common
} //closing namespace Lima
<|endoftext|>
|
<commit_before>//===--- LoadCopyToLoadBorrowOpt.cpp --------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// \file
///
/// Defines the main optimization that converts load [copy] -> load_borrow if we
/// can prove that the +1 is not actually needed and the memory loaded from is
/// never written to while the load [copy]'s object value is being used.
///
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-semantic-arc-opts"
#include "OwnershipLiveRange.h"
#include "SemanticARCOptVisitor.h"
#include "swift/SIL/LinearLifetimeChecker.h"
#include "swift/SIL/MemAccessUtils.h"
#include "swift/SIL/OwnershipUtils.h"
#include "swift/SIL/Projection.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILValue.h"
#include "swift/SILOptimizer/Utils/ValueLifetime.h"
#include "llvm/Support/CommandLine.h"
using namespace swift;
using namespace swift::semanticarc;
//===----------------------------------------------------------------------===//
// Memory Analysis
//===----------------------------------------------------------------------===//
namespace {
/// A class that computes in a flow insensitive way if we can prove that our
/// storage is either never written to, or is initialized exactly once and never
/// written to again. In both cases, we can convert load [copy] -> load_borrow
/// safely.
class StorageGuaranteesLoadVisitor
: public AccessUseDefChainVisitor<StorageGuaranteesLoadVisitor> {
// The context that contains global state used across all semantic arc
// optimizations.
Context &ctx;
// The live range of the original load.
const OwnershipLiveRange &liveRange;
// The current address being visited.
SILValue currentAddress;
Optional<bool> isWritten;
public:
StorageGuaranteesLoadVisitor(Context &context, LoadInst *load,
const OwnershipLiveRange &liveRange)
: ctx(context), liveRange(liveRange), currentAddress(load->getOperand()) {
}
void answer(bool written) {
currentAddress = nullptr;
isWritten = written;
}
void next(SILValue address) { currentAddress = address; }
void visitNestedAccess(BeginAccessInst *access) {
// First see if we have read/modify. If we do not, just look through the
// nested access.
switch (access->getAccessKind()) {
case SILAccessKind::Init:
case SILAccessKind::Deinit:
return next(access->getOperand());
case SILAccessKind::Read:
case SILAccessKind::Modify:
break;
}
// Next check if our live range is completely in the begin/end access
// scope. If so, we may be able to use a load_borrow here!
SmallVector<Operand *, 8> endScopeUses;
transform(access->getEndAccesses(), std::back_inserter(endScopeUses),
[](EndAccessInst *eai) { return &eai->getAllOperands()[0]; });
LinearLifetimeChecker checker(ctx.getDeadEndBlocks());
if (!checker.validateLifetime(access, endScopeUses,
liveRange.getAllConsumingUses())) {
// If we fail the linear lifetime check, then just recur:
return next(access->getOperand());
}
// Otherwise, if we have read, then we are done!
if (access->getAccessKind() == SILAccessKind::Read) {
return answer(false);
}
// If we have a modify, check if our value is /ever/ written to. If it is
// never actually written to, then we convert to a load_borrow.
auto result = ctx.addressToExhaustiveWriteListCache.get(access);
if (!result.hasValue()) {
return answer(true);
}
if (result.getValue().empty()) {
return answer(false);
}
return answer(true);
}
void visitArgumentAccess(SILFunctionArgument *arg) {
// If this load_copy is from an indirect in_guaranteed argument, then we
// know for sure that it will never be written to.
if (arg->hasConvention(SILArgumentConvention::Indirect_In_Guaranteed)) {
return answer(false);
}
// If we have an inout parameter that isn't ever actually written to, return
// false.
if (arg->getKnownParameterInfo().isIndirectMutating()) {
auto wellBehavedWrites = ctx.addressToExhaustiveWriteListCache.get(arg);
if (!wellBehavedWrites.hasValue()) {
return answer(true);
}
// No writes.
if (wellBehavedWrites->empty()) {
return answer(false);
}
// Ok, we have some writes. See if any of them are within our live
// range. If any are, we definitely can not promote to load_borrow.
SmallVector<BeginAccessInst *, 16> foundBeginAccess;
LinearLifetimeChecker checker(ctx.getDeadEndBlocks());
SILValue introducerValue = liveRange.getIntroducer().value;
if (!checker.usesNotContainedWithinLifetime(introducerValue,
liveRange.getDestroyingUses(),
*wellBehavedWrites)) {
return answer(true);
}
// Finally, check if our live range is strictly contained within any of
// our scoped writes.
SmallVector<Operand *, 16> endAccessList;
for (Operand *use : *wellBehavedWrites) {
auto *bai = dyn_cast<BeginAccessInst>(use->getUser());
if (!bai) {
continue;
}
endAccessList.clear();
llvm::transform(
bai->getUsersOfType<EndAccessInst>(),
std::back_inserter(endAccessList),
[](EndAccessInst *eai) { return &eai->getAllOperands()[0]; });
// We know that our live range is based on a load [copy], so we know
// that our value must have a defining inst.
auto *definingInst =
cast<LoadInst>(introducerValue->getDefiningInstruction());
// Then if our defining inst is not in our bai, endAccessList region, we
// know that the two ranges must be disjoint, so continue.
if (!checker.validateLifetime(bai, endAccessList,
&definingInst->getAllOperands()[0])) {
continue;
}
// Otherwise, we do have an overlap, return true.
return answer(true);
}
// Otherwise, there isn't an overlap, so we don't write to it.
return answer(false);
}
// TODO: This should be extended:
//
// 1. We should be able to analyze in arguments and see if they are only
// ever destroyed at the end of the function. In such a case, we may be
// able to also to promote load [copy] from such args to load_borrow.
return answer(true);
}
void visitGlobalAccess(SILValue global) {
return answer(
!AccessedStorage(global, AccessedStorage::Global).isLetAccess());
}
void visitClassAccess(RefElementAddrInst *field) {
currentAddress = nullptr;
// We know a let property won't be written to if the base object is
// guaranteed for the duration of the access.
// For non-let properties conservatively assume they may be written to.
if (!field->getField()->isLet()) {
return answer(true);
}
// The lifetime of the `let` is guaranteed if it's dominated by the
// guarantee on the base. See if we can find a single borrow introducer for
// this object. If we could not find a single such borrow introducer, assume
// that our property is conservatively written to.
SILValue baseObject = field->getOperand();
auto value = getSingleBorrowIntroducingValue(baseObject);
if (!value) {
return answer(true);
}
// Ok, we have a single borrow introducing value. First do a quick check if
// we have a non-local scope that is a function argument. In such a case, we
// know statically that our let can not be written to in the current
// function. To be conservative, assume that all other non-local scopes
// write to memory.
if (!value.isLocalScope()) {
if (value.kind == BorrowedValueKind::SILFunctionArgument) {
return answer(false);
}
// TODO: Once we model Coroutine results as non-local scopes, we should be
// able to return false here for them as well.
return answer(true);
}
// TODO: This is disabled temporarily for guaranteed phi args just for
// staging purposes. Thus be conservative and assume true in these cases.
if (value.kind == BorrowedValueKind::Phi) {
return answer(true);
}
// Ok, we now know that we have a local scope whose lifetime we need to
// analyze. With that in mind, gather up the lifetime ending uses of our
// borrow scope introducing value and then use the linear lifetime checker
// to check whether the copied value is dominated by the lifetime of the
// borrow it's based on.
SmallVector<Operand *, 4> endScopeInsts;
value.visitLocalScopeEndingUses(
[&](Operand *use) { endScopeInsts.push_back(use); return true; });
LinearLifetimeChecker checker(ctx.getDeadEndBlocks());
// Returns true on success. So we invert.
bool foundError = !checker.validateLifetime(
baseObject, endScopeInsts, liveRange.getAllConsumingUses());
return answer(foundError);
}
// TODO: Handle other access kinds?
void visitBase(SILValue base, AccessedStorage::Kind kind) {
return answer(true);
}
void visitNonAccess(SILValue addr) { return answer(true); }
void visitCast(SingleValueInstruction *cast, Operand *parentAddr) {
return next(parentAddr->get());
}
void visitStorageCast(SingleValueInstruction *projectedAddr,
Operand *parentAddr) {
return next(parentAddr->get());
}
void visitAccessProjection(SingleValueInstruction *projectedAddr,
Operand *parentAddr) {
return next(parentAddr->get());
}
void visitPhi(SILPhiArgument *phi) {
// We shouldn't have address phis in OSSA SIL, so we don't need to recur
// through the predecessors here.
return answer(true);
}
/// See if we have an alloc_stack that is only written to once by an
/// initializing instruction.
void visitStackAccess(AllocStackInst *stack) {
SmallVector<Operand *, 8> destroyAddrOperands;
bool initialAnswer = isSingleInitAllocStack(stack, destroyAddrOperands);
if (!initialAnswer)
return answer(true);
// Then make sure that all of our load [copy] uses are within the
// destroy_addr.
LinearLifetimeChecker checker(ctx.getDeadEndBlocks());
// Returns true on success. So we invert.
bool foundError = !checker.validateLifetime(
stack, destroyAddrOperands /*consuming users*/,
liveRange.getAllConsumingUses() /*non consuming users*/);
return answer(foundError);
}
bool doIt() {
while (currentAddress) {
visit(currentAddress);
}
return *isWritten;
}
};
} // namespace
static bool isWrittenTo(Context &ctx, LoadInst *load,
const OwnershipLiveRange &lr) {
StorageGuaranteesLoadVisitor visitor(ctx, load, lr);
return visitor.doIt();
}
//===----------------------------------------------------------------------===//
// Top Level Entrypoint
//===----------------------------------------------------------------------===//
// Convert a load [copy] from unique storage [read] that has all uses that can
// accept a guaranteed parameter to a load_borrow.
bool SemanticARCOptVisitor::visitLoadInst(LoadInst *li) {
// This optimization can use more complex analysis. We should do some
// experiments before enabling this by default as a guaranteed optimization.
if (ctx.onlyMandatoryOpts)
return false;
// If we are not supposed to perform this transform, bail.
if (!ctx.shouldPerform(ARCTransformKind::LoadCopyToLoadBorrowPeephole))
return false;
if (li->getOwnershipQualifier() != LoadOwnershipQualifier::Copy)
return false;
// Ok, we have our load [copy]. Make sure its value is truly a dead live range
// implying it is only ever consumed by destroy_value instructions. If it is
// consumed, we need to pass off a +1 value, so bail.
//
// FIXME: We should consider if it is worth promoting a load [copy]
// -> load_borrow if we can put a copy_value on a cold path and thus
// eliminate RR traffic on a hot path.
OwnershipLiveRange lr(li);
if (bool(lr.hasUnknownConsumingUse()))
return false;
// Then check if our address is ever written to. If it is, then we cannot use
// the load_borrow because the stored value may be released during the loaded
// value's live range.
if (isWrittenTo(ctx, li, lr))
return false;
// Ok, we can perform our optimization. Convert the load [copy] into a
// load_borrow.
auto *lbi =
SILBuilderWithScope(li).createLoadBorrow(li->getLoc(), li->getOperand());
lr.insertEndBorrowsAtDestroys(lbi, getDeadEndBlocks(), ctx.lifetimeFrontier);
std::move(lr).convertToGuaranteedAndRAUW(lbi, getCallbacks());
return true;
}
<commit_msg>[semantic-arc] Add a comment dexplaining that isSingleInitAllocStack does not necessarily contain operands of destroy_addr now that it handles checked_cast_addr_br, unchecked_checked_cast_addr.<commit_after>//===--- LoadCopyToLoadBorrowOpt.cpp --------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// \file
///
/// Defines the main optimization that converts load [copy] -> load_borrow if we
/// can prove that the +1 is not actually needed and the memory loaded from is
/// never written to while the load [copy]'s object value is being used.
///
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-semantic-arc-opts"
#include "OwnershipLiveRange.h"
#include "SemanticARCOptVisitor.h"
#include "swift/SIL/LinearLifetimeChecker.h"
#include "swift/SIL/MemAccessUtils.h"
#include "swift/SIL/OwnershipUtils.h"
#include "swift/SIL/Projection.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILValue.h"
#include "swift/SILOptimizer/Utils/ValueLifetime.h"
#include "llvm/Support/CommandLine.h"
using namespace swift;
using namespace swift::semanticarc;
//===----------------------------------------------------------------------===//
// Memory Analysis
//===----------------------------------------------------------------------===//
namespace {
/// A class that computes in a flow insensitive way if we can prove that our
/// storage is either never written to, or is initialized exactly once and never
/// written to again. In both cases, we can convert load [copy] -> load_borrow
/// safely.
class StorageGuaranteesLoadVisitor
: public AccessUseDefChainVisitor<StorageGuaranteesLoadVisitor> {
// The context that contains global state used across all semantic arc
// optimizations.
Context &ctx;
// The live range of the original load.
const OwnershipLiveRange &liveRange;
// The current address being visited.
SILValue currentAddress;
Optional<bool> isWritten;
public:
StorageGuaranteesLoadVisitor(Context &context, LoadInst *load,
const OwnershipLiveRange &liveRange)
: ctx(context), liveRange(liveRange), currentAddress(load->getOperand()) {
}
void answer(bool written) {
currentAddress = nullptr;
isWritten = written;
}
void next(SILValue address) { currentAddress = address; }
void visitNestedAccess(BeginAccessInst *access) {
// First see if we have read/modify. If we do not, just look through the
// nested access.
switch (access->getAccessKind()) {
case SILAccessKind::Init:
case SILAccessKind::Deinit:
return next(access->getOperand());
case SILAccessKind::Read:
case SILAccessKind::Modify:
break;
}
// Next check if our live range is completely in the begin/end access
// scope. If so, we may be able to use a load_borrow here!
SmallVector<Operand *, 8> endScopeUses;
transform(access->getEndAccesses(), std::back_inserter(endScopeUses),
[](EndAccessInst *eai) { return &eai->getAllOperands()[0]; });
LinearLifetimeChecker checker(ctx.getDeadEndBlocks());
if (!checker.validateLifetime(access, endScopeUses,
liveRange.getAllConsumingUses())) {
// If we fail the linear lifetime check, then just recur:
return next(access->getOperand());
}
// Otherwise, if we have read, then we are done!
if (access->getAccessKind() == SILAccessKind::Read) {
return answer(false);
}
// If we have a modify, check if our value is /ever/ written to. If it is
// never actually written to, then we convert to a load_borrow.
auto result = ctx.addressToExhaustiveWriteListCache.get(access);
if (!result.hasValue()) {
return answer(true);
}
if (result.getValue().empty()) {
return answer(false);
}
return answer(true);
}
void visitArgumentAccess(SILFunctionArgument *arg) {
// If this load_copy is from an indirect in_guaranteed argument, then we
// know for sure that it will never be written to.
if (arg->hasConvention(SILArgumentConvention::Indirect_In_Guaranteed)) {
return answer(false);
}
// If we have an inout parameter that isn't ever actually written to, return
// false.
if (arg->getKnownParameterInfo().isIndirectMutating()) {
auto wellBehavedWrites = ctx.addressToExhaustiveWriteListCache.get(arg);
if (!wellBehavedWrites.hasValue()) {
return answer(true);
}
// No writes.
if (wellBehavedWrites->empty()) {
return answer(false);
}
// Ok, we have some writes. See if any of them are within our live
// range. If any are, we definitely can not promote to load_borrow.
SmallVector<BeginAccessInst *, 16> foundBeginAccess;
LinearLifetimeChecker checker(ctx.getDeadEndBlocks());
SILValue introducerValue = liveRange.getIntroducer().value;
if (!checker.usesNotContainedWithinLifetime(introducerValue,
liveRange.getDestroyingUses(),
*wellBehavedWrites)) {
return answer(true);
}
// Finally, check if our live range is strictly contained within any of
// our scoped writes.
SmallVector<Operand *, 16> endAccessList;
for (Operand *use : *wellBehavedWrites) {
auto *bai = dyn_cast<BeginAccessInst>(use->getUser());
if (!bai) {
continue;
}
endAccessList.clear();
llvm::transform(
bai->getUsersOfType<EndAccessInst>(),
std::back_inserter(endAccessList),
[](EndAccessInst *eai) { return &eai->getAllOperands()[0]; });
// We know that our live range is based on a load [copy], so we know
// that our value must have a defining inst.
auto *definingInst =
cast<LoadInst>(introducerValue->getDefiningInstruction());
// Then if our defining inst is not in our bai, endAccessList region, we
// know that the two ranges must be disjoint, so continue.
if (!checker.validateLifetime(bai, endAccessList,
&definingInst->getAllOperands()[0])) {
continue;
}
// Otherwise, we do have an overlap, return true.
return answer(true);
}
// Otherwise, there isn't an overlap, so we don't write to it.
return answer(false);
}
// TODO: This should be extended:
//
// 1. We should be able to analyze in arguments and see if they are only
// ever destroyed at the end of the function. In such a case, we may be
// able to also to promote load [copy] from such args to load_borrow.
return answer(true);
}
void visitGlobalAccess(SILValue global) {
return answer(
!AccessedStorage(global, AccessedStorage::Global).isLetAccess());
}
void visitClassAccess(RefElementAddrInst *field) {
currentAddress = nullptr;
// We know a let property won't be written to if the base object is
// guaranteed for the duration of the access.
// For non-let properties conservatively assume they may be written to.
if (!field->getField()->isLet()) {
return answer(true);
}
// The lifetime of the `let` is guaranteed if it's dominated by the
// guarantee on the base. See if we can find a single borrow introducer for
// this object. If we could not find a single such borrow introducer, assume
// that our property is conservatively written to.
SILValue baseObject = field->getOperand();
auto value = getSingleBorrowIntroducingValue(baseObject);
if (!value) {
return answer(true);
}
// Ok, we have a single borrow introducing value. First do a quick check if
// we have a non-local scope that is a function argument. In such a case, we
// know statically that our let can not be written to in the current
// function. To be conservative, assume that all other non-local scopes
// write to memory.
if (!value.isLocalScope()) {
if (value.kind == BorrowedValueKind::SILFunctionArgument) {
return answer(false);
}
// TODO: Once we model Coroutine results as non-local scopes, we should be
// able to return false here for them as well.
return answer(true);
}
// TODO: This is disabled temporarily for guaranteed phi args just for
// staging purposes. Thus be conservative and assume true in these cases.
if (value.kind == BorrowedValueKind::Phi) {
return answer(true);
}
// Ok, we now know that we have a local scope whose lifetime we need to
// analyze. With that in mind, gather up the lifetime ending uses of our
// borrow scope introducing value and then use the linear lifetime checker
// to check whether the copied value is dominated by the lifetime of the
// borrow it's based on.
SmallVector<Operand *, 4> endScopeInsts;
value.visitLocalScopeEndingUses(
[&](Operand *use) { endScopeInsts.push_back(use); return true; });
LinearLifetimeChecker checker(ctx.getDeadEndBlocks());
// Returns true on success. So we invert.
bool foundError = !checker.validateLifetime(
baseObject, endScopeInsts, liveRange.getAllConsumingUses());
return answer(foundError);
}
// TODO: Handle other access kinds?
void visitBase(SILValue base, AccessedStorage::Kind kind) {
return answer(true);
}
void visitNonAccess(SILValue addr) { return answer(true); }
void visitCast(SingleValueInstruction *cast, Operand *parentAddr) {
return next(parentAddr->get());
}
void visitStorageCast(SingleValueInstruction *projectedAddr,
Operand *parentAddr) {
return next(parentAddr->get());
}
void visitAccessProjection(SingleValueInstruction *projectedAddr,
Operand *parentAddr) {
return next(parentAddr->get());
}
void visitPhi(SILPhiArgument *phi) {
// We shouldn't have address phis in OSSA SIL, so we don't need to recur
// through the predecessors here.
return answer(true);
}
/// See if we have an alloc_stack that is only written to once by an
/// initializing instruction.
void visitStackAccess(AllocStackInst *stack) {
// These will contain all of the address destroying operands that form the
// lifetime of the object. They may not be destroy_addr!
SmallVector<Operand *, 8> addrDestroyingOperands;
bool initialAnswer = isSingleInitAllocStack(stack, addrDestroyingOperands);
if (!initialAnswer)
return answer(true);
// Then make sure that all of our load [copy] uses are within the
// destroy_addr.
LinearLifetimeChecker checker(ctx.getDeadEndBlocks());
// Returns true on success. So we invert.
bool foundError = !checker.validateLifetime(
stack, addrDestroyingOperands /*consuming users*/,
liveRange.getAllConsumingUses() /*non consuming users*/);
return answer(foundError);
}
bool doIt() {
while (currentAddress) {
visit(currentAddress);
}
return *isWritten;
}
};
} // namespace
static bool isWrittenTo(Context &ctx, LoadInst *load,
const OwnershipLiveRange &lr) {
StorageGuaranteesLoadVisitor visitor(ctx, load, lr);
return visitor.doIt();
}
//===----------------------------------------------------------------------===//
// Top Level Entrypoint
//===----------------------------------------------------------------------===//
// Convert a load [copy] from unique storage [read] that has all uses that can
// accept a guaranteed parameter to a load_borrow.
bool SemanticARCOptVisitor::visitLoadInst(LoadInst *li) {
// This optimization can use more complex analysis. We should do some
// experiments before enabling this by default as a guaranteed optimization.
if (ctx.onlyMandatoryOpts)
return false;
// If we are not supposed to perform this transform, bail.
if (!ctx.shouldPerform(ARCTransformKind::LoadCopyToLoadBorrowPeephole))
return false;
if (li->getOwnershipQualifier() != LoadOwnershipQualifier::Copy)
return false;
// Ok, we have our load [copy]. Make sure its value is truly a dead live range
// implying it is only ever consumed by destroy_value instructions. If it is
// consumed, we need to pass off a +1 value, so bail.
//
// FIXME: We should consider if it is worth promoting a load [copy]
// -> load_borrow if we can put a copy_value on a cold path and thus
// eliminate RR traffic on a hot path.
OwnershipLiveRange lr(li);
if (bool(lr.hasUnknownConsumingUse()))
return false;
// Then check if our address is ever written to. If it is, then we cannot use
// the load_borrow because the stored value may be released during the loaded
// value's live range.
if (isWrittenTo(ctx, li, lr))
return false;
// Ok, we can perform our optimization. Convert the load [copy] into a
// load_borrow.
auto *lbi =
SILBuilderWithScope(li).createLoadBorrow(li->getLoc(), li->getOperand());
lr.insertEndBorrowsAtDestroys(lbi, getDeadEndBlocks(), ctx.lifetimeFrontier);
std::move(lr).convertToGuaranteedAndRAUW(lbi, getCallbacks());
return true;
}
<|endoftext|>
|
<commit_before>#include "game.hpp"
#include "paddle.hpp"
void PaddleBase::draw() const
{
arduboy.fillRect(x, y, PADDLE_WIDTH, PADDLE_HEIGHT, WHITE);
}
void PaddleBase::move(int16_t distance)
{
int16_t newY = y + distance;
if (newY <= 0)
{
y = 1;
}
else if (newY > HEIGHT - PADDLE_HEIGHT - 1)
{
y = HEIGHT - PADDLE_HEIGHT - 1;
}
else
{
y = newY;
}
}
void Player::move_impl()
{
if (arduboy.pressed(UP_BUTTON))
{
PaddleBase::move(-1);
}
if (arduboy.pressed(DOWN_BUTTON))
{
PaddleBase::move(1);
}
}
void Computer::move_impl()
{
// bother the paddle if the ball is close or a random time
if (ball.x > 80 || !random(10))
{
// move up if the ball is higher
if (ball.y <= y)
{
PaddleBase::move(-1);
}
// move down if the ball is lower
if (ball.y + BALL_SIZE >= y + PADDLE_HEIGHT)
{
PaddleBase::move(1);
}
}
}
<commit_msg>Tweak AI again<commit_after>#include "game.hpp"
#include "paddle.hpp"
void PaddleBase::draw() const
{
arduboy.fillRect(x, y, PADDLE_WIDTH, PADDLE_HEIGHT, WHITE);
}
void PaddleBase::move(int16_t distance)
{
int16_t newY = y + distance;
if (newY <= 0)
{
y = 1;
}
else if (newY > HEIGHT - PADDLE_HEIGHT - 1)
{
y = HEIGHT - PADDLE_HEIGHT - 1;
}
else
{
y = newY;
}
}
void Player::move_impl()
{
if (arduboy.pressed(UP_BUTTON))
{
PaddleBase::move(-1);
}
if (arduboy.pressed(DOWN_BUTTON))
{
PaddleBase::move(1);
}
}
void Computer::move_impl()
{
// bother the paddle if the ball is close or a random time
if (ball.x > 85 || !random(15))
{
// move up if the ball is higher
if (ball.y <= y)
{
PaddleBase::move(-1);
}
// move down if the ball is lower
if (ball.y + BALL_SIZE >= y + PADDLE_HEIGHT)
{
PaddleBase::move(1);
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2009 Nokia Corporation.
*
* Contact: Marius Vollmer <marius.vollmer@nokia.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <QtTest/QtTest>
#include <QtCore>
#include "nanoxml.h"
#include "fileutils.h"
#include "contexttypeinfo.h"
#include "contexttyperegistryinfo.h"
ContextTypeRegistryInfo* ContextTypeRegistryInfo::registryInstance = new ContextTypeRegistryInfo();
/* Mocked ContextTypeRegistryInfo */
ContextTypeRegistryInfo::ContextTypeRegistryInfo()
{
}
ContextTypeRegistryInfo* ContextTypeRegistryInfo::instance()
{
return registryInstance;
}
NanoTree ContextTypeRegistryInfo::typeDefinitionForName(QString name)
{
if (name == "double") {
QVariantList tree;
QVariantList doc;
QVariantList name;
name << QVariant("name");
name << QVariant("double");
doc << QVariant("doc");
doc << QVariant("double doc");
tree << QVariant("type");
tree << QVariant(name);
tree << QVariant(doc);
return ContextTypeInfo(QVariant(tree));
} else if (name == "complex") {
QVariantList tree;
QVariantList doc;
QVariantList base;
QVariantList name;
QVariantList params;
QVariantList p1;
QVariantList p1Doc;
name << QVariant("name");
name << QVariant("complex");
doc << QVariant("doc");
doc << QVariant("complex doc");
base << QVariant("base");
base << QVariant("double");
p1 << QVariant("p1");
p1Doc << QVariant("doc");
p1Doc << QVariant("p1 doc");
p1 << QVariant(p1Doc);
params << QVariant("params");
params << QVariant(p1);
tree << QVariant("type");
tree << QVariant(name);
tree << QVariant(params);
tree << QVariant(doc);
tree << QVariant(base);
return ContextTypeInfo(QVariant(tree));
} else
return ContextTypeInfo();
}
class ContextTypeInfoUnitTest : public QObject
{
Q_OBJECT
private slots:
void name();
void doc();
void base();
void definition();
void parameterDoc();
void ensureNewTypes();
void parameterValue();
void parameterNode();
};
void ContextTypeInfoUnitTest::name()
{
QCOMPARE(ContextTypeInfo(QString("bool")).name(), QString("bool"));
QCOMPARE(ContextTypeInfo(QString("string")).name(), QString("string"));
QVariantList lst;
lst << QVariant("int32");
QCOMPARE(ContextTypeInfo(QVariant(lst)).name(), QString("int32"));
}
void ContextTypeInfoUnitTest::doc()
{
QCOMPARE(ContextTypeInfo(QString("double")).doc(), QString("double doc"));
}
void ContextTypeInfoUnitTest::definition()
{
NanoTree def = ContextTypeInfo(QString("double")).definition();
QCOMPARE(def.keyValue("name").toString(), QString("double"));
QCOMPARE(def.keyValue("doc").toString(), QString("double doc"));
}
void ContextTypeInfoUnitTest::base()
{
ContextTypeInfo base = ContextTypeInfo(QString("complex")).base();
QCOMPARE(base.name(), QString("double"));
QCOMPARE(base.doc(), QString("double doc"));
}
void ContextTypeInfoUnitTest::parameterDoc()
{
ContextTypeInfo typeInfo = ContextTypeInfo(QString("complex"));
QCOMPARE(typeInfo.parameterDoc("p1"), QString("p1 doc"));
}
void ContextTypeInfoUnitTest::ensureNewTypes()
{
QCOMPARE(ContextTypeInfo(QString("INTEGER")).ensureNewTypes().name(), QString("int32"));
QCOMPARE(ContextTypeInfo(QString("INT")).ensureNewTypes().name(), QString("int32"));
QCOMPARE(ContextTypeInfo(QString("TRUTH")).ensureNewTypes().name(), QString("bool"));
QCOMPARE(ContextTypeInfo(QString("STRING")).ensureNewTypes().name(), QString("string"));
QCOMPARE(ContextTypeInfo(QString("DOUBLE")).ensureNewTypes().name(), QString("double"));
QCOMPARE(ContextTypeInfo(QString("bool")).ensureNewTypes().name(), QString("bool"));
}
void ContextTypeInfoUnitTest::parameterValue()
{
QVariantList lst;
QVariantList minParam;
lst << QVariant("complex");
minParam << QVariant("min");
minParam << QVariant("0");
lst << QVariant(minParam);
QVariant tree(lst);
ContextTypeInfo typeInfo(tree);
QCOMPARE(typeInfo.parameterValue("min").toString(), QString("0"));
}
void ContextTypeInfoUnitTest::parameterNode()
{
QVariantList lst;
QVariantList minParam;
lst << QVariant("complex");
minParam << QVariant("min");
minParam << QVariant("0");
lst << QVariant(minParam);
QVariant tree(lst);
ContextTypeInfo typeInfo(tree);
QCOMPARE(typeInfo.parameterNode("min").toList().at(1).toString(), QString("0"));
}
#include "contexttypeinfounittest.moc"
QTEST_MAIN(ContextTypeInfoUnitTest);
<commit_msg>Coverage improvements.<commit_after>/*
* Copyright (C) 2009 Nokia Corporation.
*
* Contact: Marius Vollmer <marius.vollmer@nokia.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <QtTest/QtTest>
#include <QtCore>
#include "nanoxml.h"
#include "fileutils.h"
#include "contexttypeinfo.h"
#include "contexttyperegistryinfo.h"
ContextTypeRegistryInfo* ContextTypeRegistryInfo::registryInstance = new ContextTypeRegistryInfo();
/* Mocked ContextTypeRegistryInfo */
ContextTypeRegistryInfo::ContextTypeRegistryInfo()
{
}
ContextTypeRegistryInfo* ContextTypeRegistryInfo::instance()
{
return registryInstance;
}
NanoTree ContextTypeRegistryInfo::typeDefinitionForName(QString name)
{
if (name == "double") {
QVariantList tree;
QVariantList doc;
QVariantList name;
name << QVariant("name");
name << QVariant("double");
doc << QVariant("doc");
doc << QVariant("double doc");
tree << QVariant("type");
tree << QVariant(name);
tree << QVariant(doc);
return ContextTypeInfo(QVariant(tree));
} else if (name == "complex") {
QVariantList tree;
QVariantList doc;
QVariantList base;
QVariantList name;
QVariantList params;
QVariantList p1;
QVariantList p1Doc;
name << QVariant("name");
name << QVariant("complex");
doc << QVariant("doc");
doc << QVariant("complex doc");
base << QVariant("base");
base << QVariant("double");
p1 << QVariant("p1");
p1Doc << QVariant("doc");
p1Doc << QVariant("p1 doc");
p1 << QVariant(p1Doc);
params << QVariant("params");
params << QVariant(p1);
tree << QVariant("type");
tree << QVariant(name);
tree << QVariant(params);
tree << QVariant(doc);
tree << QVariant(base);
return ContextTypeInfo(QVariant(tree));
} else
return ContextTypeInfo();
}
class ContextTypeInfoUnitTest : public QObject
{
Q_OBJECT
private slots:
void name();
void doc();
void base();
void definition();
void parameterDoc();
void ensureNewTypes();
void parameterValue();
void parameterNode();
void parameters();
};
void ContextTypeInfoUnitTest::name()
{
QCOMPARE(ContextTypeInfo(QString("bool")).name(), QString("bool"));
QCOMPARE(ContextTypeInfo(QString("string")).name(), QString("string"));
QVariantList lst;
lst << QVariant("int32");
QCOMPARE(ContextTypeInfo(QVariant(lst)).name(), QString("int32"));
}
void ContextTypeInfoUnitTest::doc()
{
QCOMPARE(ContextTypeInfo(QString("double")).doc(), QString("double doc"));
}
void ContextTypeInfoUnitTest::definition()
{
NanoTree def = ContextTypeInfo(QString("double")).definition();
QCOMPARE(def.keyValue("name").toString(), QString("double"));
QCOMPARE(def.keyValue("doc").toString(), QString("double doc"));
}
void ContextTypeInfoUnitTest::base()
{
ContextTypeInfo base = ContextTypeInfo(QString("complex")).base();
QCOMPARE(base.name(), QString("double"));
QCOMPARE(base.doc(), QString("double doc"));
}
void ContextTypeInfoUnitTest::parameterDoc()
{
ContextTypeInfo typeInfo = ContextTypeInfo(QString("complex"));
QCOMPARE(typeInfo.parameterDoc("p1"), QString("p1 doc"));
}
void ContextTypeInfoUnitTest::ensureNewTypes()
{
QCOMPARE(ContextTypeInfo(QString("INTEGER")).ensureNewTypes().name(), QString("int32"));
QCOMPARE(ContextTypeInfo(QString("INT")).ensureNewTypes().name(), QString("int32"));
QCOMPARE(ContextTypeInfo(QString("TRUTH")).ensureNewTypes().name(), QString("bool"));
QCOMPARE(ContextTypeInfo(QString("STRING")).ensureNewTypes().name(), QString("string"));
QCOMPARE(ContextTypeInfo(QString("DOUBLE")).ensureNewTypes().name(), QString("double"));
QCOMPARE(ContextTypeInfo(QString("bool")).ensureNewTypes().name(), QString("bool"));
}
void ContextTypeInfoUnitTest::parameterValue()
{
QVariantList lst;
QVariantList minParam;
lst << QVariant("complex");
minParam << QVariant("min");
minParam << QVariant("0");
lst << QVariant(minParam);
QVariant tree(lst);
ContextTypeInfo typeInfo(tree);
QCOMPARE(typeInfo.parameterValue("min").toString(), QString("0"));
}
void ContextTypeInfoUnitTest::parameterNode()
{
QVariantList lst;
QVariantList minParam;
lst << QVariant("complex");
minParam << QVariant("min");
minParam << QVariant("0");
lst << QVariant(minParam);
QVariant tree(lst);
ContextTypeInfo typeInfo(tree);
QCOMPARE(typeInfo.parameterNode("min").toList().at(1).toString(), QString("0"));
}
void ContextTypeInfoUnitTest::parameters()
{
QVariantList lst;
QVariantList minParam;
lst << QVariant("complex");
minParam << QVariant("min");
minParam << QVariant("0");
lst << QVariant(minParam);
QVariant tree(lst);
ContextTypeInfo typeInfo(tree);
QVariantList params = typeInfo.parameters();
QCOMPARE(params.size(), 1);
QCOMPARE(params.at(0).toList().at(0).toString(), QString("min"));
QVariant variant("double");
QVERIFY(ContextTypeInfo(variant).parameters().size() == 0);
}
#include "contexttypeinfounittest.moc"
QTEST_MAIN(ContextTypeInfoUnitTest);
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2010 Matt Fichman
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, APEXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "String.hpp"
char String::escape(const std::string& str) {
// Returns the escaped character for 'in', e.g., if '\n' is given to this
// function, it returns the newline character.
const char* c = &str[0];
if (*c != '\\') {
return *c;
}
c++;
if (isdigit(c[0]) && isdigit(c[1]) && isdigit(c[2])) {
return 64*(c[0]-'0') + 8*(c[1]-'0') + (c[2]-'0');
}
if (*c == 'x' && isxdigit(c[1]) && isxdigit(c[2])) {
char ret = 0;
if (isupper(c[1])) {
ret += 10 + c[1] - 'A';
} else if (islower(c[1])) {
ret += 10 + c[1] - 'a';
} else {
ret += c[1] - '0';
}
ret = ret << 4;
if (isupper(c[2])) {
ret += 10 + c[2] - 'A';
} else if (islower(c[2])) {
ret += 10 + c[2] - 'a';
} else {
ret += c[2] - '0';
}
return ret;
}
switch (*c) {
case 'a': return 0x7; // alarm
case 'b': return 0x8; // backspace
case 't': return 0x9; // horizontal tab
case 'n': return 0xa; // newline
case 'v': return 0xb; // vertical tab
case 'f': return 0xc; // form feed
case 'r': return 0xd; // carriage return
case '"': return 0x22; // quote
case '\'': return 0x27; // quote
default: return c[0];
}
}
std::string const String::unescaped() const {
// Removes the escape sequences from this string and returns the actual
// string, as intended by the programmer
std::string const& in = string();
std::string out;
int length = 0;
for (int i = 0; i < in.length(); i++) {
char c = in[i];
if (c == '\\') {
// Output escape sequences. For NASM, the actual hex codes must
// be output for non-visible characters; there is no escape
// character.
c = in[++i];
if (isdigit(c)) { // Octal code
char c2 = in[++i];
char c3 = in[++i];
out += std::string("0o") + c + c2 + c3;
} else if (c == 'x') { // Hexadecimal code
char c1 = in[++i];
char c2 = in[++i];
out += std::string("0x") + c1 + c2;
} else {
switch (c) {
case 'a': out += "\a"; break; // alarm
case 'b': out += "\b"; break; // backspace
case 't': out += "\t"; break; // horizontal tab
case 'n': out += "\n"; break; // newline
case 'v': out += "\v"; break; // vertical tab
case 'f': out += "\f"; break; // form feed
case 'r': out += "\r"; break; // carriage return
case '"': out += "\""; break; // quote
case '\'': out += "\'"; break; // quote
default: out += c; break;
}
}
} else {
out += c;
}
}
return out;
}
<commit_msg>Fixed string escape<commit_after>/*
* Copyright (c) 2010 Matt Fichman
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, APEXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "String.hpp"
char String::escape(const std::string& str) {
// Returns the escaped character for 'in', e.g., if '\n' is given to this
// function, it returns the newline character.
const char* c = &str[0];
if (*c != '\\') {
return *c;
}
c++;
if (isdigit(c[0]) && isdigit(c[1]) && isdigit(c[2])) {
return 64*(c[0]-'0') + 8*(c[1]-'0') + (c[2]-'0');
}
if (*c == 'x' && isxdigit(c[1]) && isxdigit(c[2])) {
char ret = 0;
if (isupper(c[1])) {
ret += 10 + c[1] - 'A';
} else if (islower(c[1])) {
ret += 10 + c[1] - 'a';
} else {
ret += c[1] - '0';
}
ret = ret << 4;
if (isupper(c[2])) {
ret += 10 + c[2] - 'A';
} else if (islower(c[2])) {
ret += 10 + c[2] - 'a';
} else {
ret += c[2] - '0';
}
return ret;
}
switch (*c) {
case 'a': return 0x7; // alarm
case 'b': return 0x8; // backspace
case 't': return 0x9; // horizontal tab
case 'n': return 0xa; // newline
case 'v': return 0xb; // vertical tab
case 'f': return 0xc; // form feed
case 'r': return 0xd; // carriage return
case '"': return 0x22; // quote
case '\'': return 0x27; // quote
default: return c[0];
}
}
std::string const String::unescaped() const {
// Removes the escape sequences from this string and returns the actual
// string, as intended by the programmer
std::string const& in = string();
std::string out;
int length = 0;
for (int i = 0; i < in.length(); i++) {
char c = in[i];
if (c == '\\') {
// Output escape sequences. For NASM, the actual hex codes must
// be output for non-visible characters; there is no escape
// character.
c = in[++i];
if (isdigit(c)) { // Octal code
char c2 = in[++i];
char c3 = in[++i];
out += (c-'0')*64 + (c2-'0')*8 + (c3-'0');
} else if (c == 'x') { // Hexadecimal code
char c1 = in[++i];
char c2 = in[++i];
char byte = 0;
if (isupper(c1)) {
byte += c1-'A'+10;
} else if (islower(c1)) {
byte += c1-'a'+10;
} else {
byte += c1-'0';
}
byte *= 16;
if (isupper(c2)) {
byte += c2-'A'+10;
} else if (islower(c2)) {
byte += c2-'a'+10;
} else {
byte += c2-'0';
}
out += byte;
} else {
switch (c) {
case 'a': out += "\a"; break; // alarm
case 'b': out += "\b"; break; // backspace
case 't': out += "\t"; break; // horizontal tab
case 'n': out += "\n"; break; // newline
case 'v': out += "\v"; break; // vertical tab
case 'f': out += "\f"; break; // form feed
case 'r': out += "\r"; break; // carriage return
case '"': out += "\""; break; // quote
case '\'': out += "\'"; break; // quote
default: out += c; break;
}
}
} else {
out += c;
}
}
return out;
}
<|endoftext|>
|
<commit_before>#include "CAudioSys.hpp"
#include "CSimplePool.hpp"
#include "CAudioGroupSet.hpp"
namespace urde {
namespace {
std::unordered_map<std::string, TLockedToken<CAudioGroupSet>> mpGroupSetDB;
std::unordered_map<CAssetId, std::string> mpGroupSetResNameDB;
const std::string mpDefaultInvalidString = "NULL";
float s_MasterVol = 1.f;
float s_SfxVol = 1.f;
s16 s_VolumeScale = 0x7f;
s16 s_DefaultVolumeScale = 0x7f;
} // Anonymous namespace
CAudioSys* CAudioSys::g_SharedSys = nullptr;
TLockedToken<CAudioGroupSet> CAudioSys::FindGroupSet(std::string_view name) {
auto search = mpGroupSetDB.find(name.data());
if (search == mpGroupSetDB.cend())
return {};
return search->second;
}
std::string_view CAudioSys::SysGetGroupSetName(CAssetId id) {
auto search = mpGroupSetResNameDB.find(id);
if (search == mpGroupSetResNameDB.cend())
return mpDefaultInvalidString;
return search->second;
}
bool CAudioSys::SysLoadGroupSet(CSimplePool* pool, CAssetId id) {
if (!FindGroupSet(SysGetGroupSetName(id))) {
TLockedToken<CAudioGroupSet> set = pool->GetObj(SObjectTag{FOURCC('AGSC'), id});
mpGroupSetDB.emplace(std::make_pair(set->GetName(), set));
mpGroupSetResNameDB.emplace(std::make_pair(id, set->GetName()));
return false;
} else {
return true;
}
}
bool CAudioSys::SysLoadGroupSet(const TLockedToken<CAudioGroupSet>& set, std::string_view name, CAssetId id) {
if (!FindGroupSet(name)) {
mpGroupSetDB.emplace(std::make_pair(set->GetName(), set));
mpGroupSetResNameDB.emplace(std::make_pair(id, set->GetName()));
return false;
} else {
return true;
}
}
void CAudioSys::SysUnloadAudioGroupSet(std::string_view name) {
auto set = FindGroupSet(name);
if (!set)
return;
mpGroupSetDB.erase(name.data());
mpGroupSetResNameDB.erase(set.GetObjectTag()->id);
}
bool CAudioSys::SysIsGroupSetLoaded(std::string_view name) { return FindGroupSet(name).operator bool(); }
void CAudioSys::SysAddGroupIntoAmuse(std::string_view name) {
if (auto set = FindGroupSet(name))
AddAudioGroup(set->GetAudioGroupData());
}
void CAudioSys::SysRemoveGroupFromAmuse(std::string_view name) {
if (auto set = FindGroupSet(name))
RemoveAudioGroup(set->GetAudioGroupData());
}
void CAudioSys::_UpdateVolume() { GetAmuseEngine().setVolume(s_MasterVol * s_SfxVol); }
void CAudioSys::SysSetVolume(u8 volume) {
s_MasterVol = volume / 127.f;
_UpdateVolume();
}
void CAudioSys::SysSetSfxVolume(u8 volume, u16 time, bool music, bool fx) {
s_SfxVol = volume / 127.f;
_UpdateVolume();
}
s16 CAudioSys::GetDefaultVolumeScale() { return s_DefaultVolumeScale; }
void CAudioSys::SetDefaultVolumeScale(s16 scale) { s_DefaultVolumeScale = scale; }
void CAudioSys::SetVolumeScale(s16 scale) { s_VolumeScale = scale; }
} // namespace urde
<commit_msg>CAudioSys: Remove construction of pairs in emplace calls<commit_after>#include "CAudioSys.hpp"
#include "CSimplePool.hpp"
#include "CAudioGroupSet.hpp"
namespace urde {
namespace {
std::unordered_map<std::string, TLockedToken<CAudioGroupSet>> mpGroupSetDB;
std::unordered_map<CAssetId, std::string> mpGroupSetResNameDB;
const std::string mpDefaultInvalidString = "NULL";
float s_MasterVol = 1.f;
float s_SfxVol = 1.f;
s16 s_VolumeScale = 0x7f;
s16 s_DefaultVolumeScale = 0x7f;
} // Anonymous namespace
CAudioSys* CAudioSys::g_SharedSys = nullptr;
TLockedToken<CAudioGroupSet> CAudioSys::FindGroupSet(std::string_view name) {
auto search = mpGroupSetDB.find(name.data());
if (search == mpGroupSetDB.cend())
return {};
return search->second;
}
std::string_view CAudioSys::SysGetGroupSetName(CAssetId id) {
auto search = mpGroupSetResNameDB.find(id);
if (search == mpGroupSetResNameDB.cend())
return mpDefaultInvalidString;
return search->second;
}
bool CAudioSys::SysLoadGroupSet(CSimplePool* pool, CAssetId id) {
if (!FindGroupSet(SysGetGroupSetName(id))) {
TLockedToken<CAudioGroupSet> set = pool->GetObj(SObjectTag{FOURCC('AGSC'), id});
mpGroupSetDB.emplace(set->GetName(), set);
mpGroupSetResNameDB.emplace(id, set->GetName());
return false;
} else {
return true;
}
}
bool CAudioSys::SysLoadGroupSet(const TLockedToken<CAudioGroupSet>& set, std::string_view name, CAssetId id) {
if (!FindGroupSet(name)) {
mpGroupSetDB.emplace(set->GetName(), set);
mpGroupSetResNameDB.emplace(id, set->GetName());
return false;
} else {
return true;
}
}
void CAudioSys::SysUnloadAudioGroupSet(std::string_view name) {
auto set = FindGroupSet(name);
if (!set)
return;
mpGroupSetDB.erase(name.data());
mpGroupSetResNameDB.erase(set.GetObjectTag()->id);
}
bool CAudioSys::SysIsGroupSetLoaded(std::string_view name) { return FindGroupSet(name).operator bool(); }
void CAudioSys::SysAddGroupIntoAmuse(std::string_view name) {
if (auto set = FindGroupSet(name))
AddAudioGroup(set->GetAudioGroupData());
}
void CAudioSys::SysRemoveGroupFromAmuse(std::string_view name) {
if (auto set = FindGroupSet(name))
RemoveAudioGroup(set->GetAudioGroupData());
}
void CAudioSys::_UpdateVolume() { GetAmuseEngine().setVolume(s_MasterVol * s_SfxVol); }
void CAudioSys::SysSetVolume(u8 volume) {
s_MasterVol = volume / 127.f;
_UpdateVolume();
}
void CAudioSys::SysSetSfxVolume(u8 volume, u16 time, bool music, bool fx) {
s_SfxVol = volume / 127.f;
_UpdateVolume();
}
s16 CAudioSys::GetDefaultVolumeScale() { return s_DefaultVolumeScale; }
void CAudioSys::SetDefaultVolumeScale(s16 scale) { s_DefaultVolumeScale = scale; }
void CAudioSys::SetVolumeScale(s16 scale) { s_VolumeScale = scale; }
} // namespace urde
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/dreamview/backend/util/trajectory_point_collector.h"
#include <cmath>
#include "gtest/gtest.h"
#include "modules/common/configs/vehicle_config_helper.h"
using apollo::common::TrajectoryPoint;
namespace apollo {
namespace dreamview {
namespace util {
class TrajectoryPointCollectorTest : public ::testing::Test {
public:
virtual void SetUp() { apollo::common::VehicleConfigHelper::Init(); }
};
TEST_F(TrajectoryPointCollectorTest, ThreePoints) {
SimulationWorld world;
TrajectoryPointCollector collector(&world);
const double base_time = 1000.0;
for (int i = 0; i < 4; ++i) {
TrajectoryPoint point;
point.mutable_path_point()->set_x(i * 100.0);
point.mutable_path_point()->set_y(i * 100.0 + 100.0);
point.set_relative_time(i * 1000.0);
collector.Collect(point, base_time);
}
EXPECT_EQ(world.planning_trajectory_size(), 3);
{
const Object &point = world.planning_trajectory(0);
EXPECT_DOUBLE_EQ(0.0, point.position_x());
EXPECT_DOUBLE_EQ(100.0, point.position_y());
EXPECT_DOUBLE_EQ(2000.0, point.timestamp_sec());
EXPECT_DOUBLE_EQ(atan2(100.0, 100.0), point.heading());
}
{
const Object &point = world.planning_trajectory(1);
EXPECT_DOUBLE_EQ(100.0, point.position_x());
EXPECT_DOUBLE_EQ(200.0, point.position_y());
EXPECT_DOUBLE_EQ(3000.0, point.timestamp_sec());
EXPECT_DOUBLE_EQ(atan2(100.0, 100.0), point.heading());
}
{
const Object &point = world.planning_trajectory(2);
EXPECT_DOUBLE_EQ(200.0, point.position_x());
EXPECT_DOUBLE_EQ(300.0, point.position_y());
EXPECT_DOUBLE_EQ(4000.0, point.timestamp_sec());
EXPECT_DOUBLE_EQ(atan2(100.0, 100.0), point.heading());
}
}
} // namespace util
} // namespace dreamview
} // namespace apollo
<commit_msg>Dreamview: fixed a unit test<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/dreamview/backend/util/trajectory_point_collector.h"
#include <cmath>
#include "gtest/gtest.h"
#include "modules/common/configs/vehicle_config_helper.h"
using apollo::common::TrajectoryPoint;
namespace apollo {
namespace dreamview {
namespace util {
class TrajectoryPointCollectorTest : public ::testing::Test {
public:
virtual void SetUp() { apollo::common::VehicleConfigHelper::Init(); }
};
TEST_F(TrajectoryPointCollectorTest, ThreePoints) {
SimulationWorld world;
TrajectoryPointCollector collector(&world);
const double base_time = 1000.0;
for (int i = 0; i < 4; ++i) {
TrajectoryPoint point;
point.mutable_path_point()->set_x(i * 100.0);
point.mutable_path_point()->set_y(i * 100.0 + 100.0);
point.set_relative_time(i * 1000.0);
collector.Collect(point, base_time);
}
EXPECT_EQ(world.planning_trajectory_size(), 3);
{
const Object &point = world.planning_trajectory(0);
EXPECT_DOUBLE_EQ(0.0, point.position_x());
EXPECT_DOUBLE_EQ(100.0, point.position_y());
EXPECT_DOUBLE_EQ(1000.0, point.timestamp_sec());
EXPECT_DOUBLE_EQ(atan2(100.0, 100.0), point.heading());
}
{
const Object &point = world.planning_trajectory(1);
EXPECT_DOUBLE_EQ(100.0, point.position_x());
EXPECT_DOUBLE_EQ(200.0, point.position_y());
EXPECT_DOUBLE_EQ(2000.0, point.timestamp_sec());
EXPECT_DOUBLE_EQ(atan2(100.0, 100.0), point.heading());
}
{
const Object &point = world.planning_trajectory(2);
EXPECT_DOUBLE_EQ(200.0, point.position_x());
EXPECT_DOUBLE_EQ(300.0, point.position_y());
EXPECT_DOUBLE_EQ(3000.0, point.timestamp_sec());
EXPECT_DOUBLE_EQ(atan2(100.0, 100.0), point.heading());
}
}
} // namespace util
} // namespace dreamview
} // namespace apollo
<|endoftext|>
|
<commit_before><commit_msg>Use std::initializer_list<commit_after><|endoftext|>
|
<commit_before>#pragma once
#include <memory>
#include <optional>
#include <unordered_map>
#include <vector>
#include "DNACommon/CMDL.hpp"
#include "DNAMP1/CMDLMaterials.hpp"
#include "Runtime/CFactoryMgr.hpp"
#include "Runtime/CToken.hpp"
#include "Runtime/RetroTypes.hpp"
#include "Shaders/CModelShaders.hpp"
#include <boo/graphicsdev/IGraphicsDataFactory.hpp>
#include <hecl/HMDLMeta.hpp>
#include <zeus/CAABox.hpp>
#include <zeus/CColor.hpp>
namespace urde {
class CLight;
class CModel;
class CPoseAsTransforms;
class CSkinRules;
class CTexture;
class IObjectStore;
struct CModelFlags {
u8 x0_blendMode = 0; /* 2: add color, >6: additive, >4: blend, else opaque */
u8 x1_matSetIdx = 0;
EExtendedShader m_extendedShader = EExtendedShader::Lighting;
bool m_noCull = false;
bool m_noZWrite = false;
bool m_depthGreater = false;
u16 x2_flags = 0; /* Flags */
zeus::CColor x4_color; /* Set into kcolor slot specified by material */
zeus::CColor addColor = zeus::skClear;
zeus::CAABox mbShadowBox;
CModelFlags() = default;
CModelFlags(u8 blendMode, u8 shadIdx, u16 flags, const zeus::CColor& col)
: x0_blendMode(blendMode), x1_matSetIdx(shadIdx), x2_flags(flags), x4_color(col) {
/* Blend mode will override this if the surface's original material is opaque */
m_noZWrite = !(x2_flags & 0x2);
m_depthGreater = (x2_flags & 0x8);
}
/* Flags
0x1: depth equal
0x2: depth update
0x4: render without texture lock
0x8: depth greater
0x10: depth non-inclusive
*/
bool operator==(const CModelFlags& other) const {
return x0_blendMode == other.x0_blendMode && x1_matSetIdx == other.x1_matSetIdx && x2_flags == other.x2_flags &&
x4_color == other.x4_color;
}
bool operator!=(const CModelFlags& other) const {
return x0_blendMode != other.x0_blendMode || x1_matSetIdx != other.x1_matSetIdx || x2_flags != other.x2_flags ||
x4_color != other.x4_color;
}
};
/* urde addition: doesn't require hacky stashing of
* pointers within loaded CMDL buffer */
struct CBooSurface {
DataSpec::DNACMDL::SurfaceHeader_2 m_data;
size_t selfIdx;
class CBooModel* m_parent = nullptr;
CBooSurface* m_next = nullptr;
zeus::CAABox GetBounds() const {
if (!m_data.aabbSz)
return zeus::CAABox(m_data.centroid, m_data.centroid);
else
return zeus::CAABox(m_data.aabb[0], m_data.aabb[1]);
}
};
using MaterialSet = DataSpec::DNAMP1::HMDLMaterialSet;
struct GeometryUniformLayout {
mutable std::vector<boo::ObjToken<boo::IGraphicsBufferD>> m_sharedBuffer;
size_t m_geomBufferSize = 0;
size_t m_skinBankCount = 0;
size_t m_weightVecCount = 0;
std::vector<size_t> m_skinOffs;
std::vector<size_t> m_skinSizes;
std::vector<size_t> m_uvOffs;
std::vector<size_t> m_uvSizes;
GeometryUniformLayout(const CModel* model, const MaterialSet* matSet);
void Update(const CModelFlags& flags, const CSkinRules* cskr, const CPoseAsTransforms* pose,
const MaterialSet* matSet, const boo::ObjToken<boo::IGraphicsBufferD>& buf,
const CBooModel* parent) const;
void ReserveSharedBuffers(boo::IGraphicsDataFactory::Context& ctx, int size);
boo::ObjToken<boo::IGraphicsBufferD> GetSharedBuffer(int idx) const;
};
struct SShader {
std::unordered_map<CAssetId, TCachedToken<CTexture>> x0_textures;
std::unordered_map<int, CModelShaders::ShaderPipelines> m_shaders;
MaterialSet m_matSet;
std::optional<GeometryUniformLayout> m_geomLayout;
int m_matSetIdx;
SShader(int idx) : m_matSetIdx(idx) {
x0_textures.clear();
m_shaders.clear();
}
void InitializeLayout(const CModel* model) { m_geomLayout.emplace(model, &m_matSet); }
void UnlockTextures();
CModelShaders::ShaderPipelines BuildShader(const hecl::HMDLMeta& meta, const MaterialSet::Material& mat);
void BuildShaders(const hecl::HMDLMeta& meta, std::unordered_map<int, CModelShaders::ShaderPipelines>& shaders);
void BuildShaders(const hecl::HMDLMeta& meta) { BuildShaders(meta, m_shaders); }
};
class CBooModel {
friend class CBooRenderer;
friend class CGameArea;
friend class CMetroidModelInstance;
friend class CModel;
friend class CSkinnedModel;
friend struct GeometryUniformLayout;
public:
enum class ESurfaceSelection { UnsortedOnly, SortedOnly, All };
private:
CBooModel* m_next = nullptr;
CBooModel* m_prev = nullptr;
size_t m_uniUpdateCount = 0;
TToken<CModel> m_modelTok;
CModel* m_model;
std::vector<CBooSurface>* x0_surfaces;
const MaterialSet* x4_matSet;
const GeometryUniformLayout* m_geomLayout;
int m_matSetIdx = -1;
const std::unordered_map<int, CModelShaders::ShaderPipelines>* m_pipelines;
std::unordered_map<CAssetId, TCachedToken<CTexture>> x1c_textures;
zeus::CAABox x20_aabb;
CBooSurface* x38_firstUnsortedSurface = nullptr;
CBooSurface* x3c_firstSortedSurface = nullptr;
bool x40_24_texturesLoaded : 1;
bool x40_25_modelVisible : 1;
u8 x41_mask;
u32 x44_areaInstanceIdx = UINT32_MAX;
struct UVAnimationBuffer {
static void ProcessAnimation(u8*& bufOut, const MaterialSet::Material::PASS& anim);
static void PadOutBuffer(u8*& bufStart, u8*& bufOut);
static void Update(u8*& bufOut, const MaterialSet* matSet, const CModelFlags& flags, const CBooModel* parent);
};
CModelShaders::LightingUniform m_lightingData;
/* urde addition: boo! */
size_t m_uniformDataSize = 0;
struct ModelInstance {
boo::ObjToken<boo::IGraphicsBufferD> m_geomUniformBuffer;
boo::ObjToken<boo::IGraphicsBufferD> m_uniformBuffer;
std::vector<std::vector<boo::ObjToken<boo::IShaderDataBinding>>> m_shaderDataBindings;
boo::ObjToken<boo::IGraphicsBufferD> m_dynamicVbo;
boo::ObjToken<boo::IGraphicsBuffer> GetBooVBO(const CBooModel& model, boo::IGraphicsDataFactory::Context& ctx);
};
std::vector<ModelInstance> m_instances;
ModelInstance m_ballShadowInstance;
boo::ObjToken<boo::IGraphicsBufferS> m_staticVbo;
boo::ObjToken<boo::IGraphicsBufferS> m_staticIbo;
boo::ObjToken<boo::ITexture> m_lastDrawnShadowMap;
boo::ObjToken<boo::ITexture> m_lastDrawnOneTexture;
boo::ObjToken<boo::ITextureCubeR> m_lastDrawnReflectionCube;
ModelInstance* PushNewModelInstance(int sharedLayoutBuf = -1);
void DrawAlphaSurfaces(const CModelFlags& flags) const;
void DrawNormalSurfaces(const CModelFlags& flags) const;
void DrawSurfaces(const CModelFlags& flags) const;
void DrawSurface(const CBooSurface& surf, const CModelFlags& flags) const;
void WarmupDrawSurfaces() const;
void WarmupDrawSurface(const CBooSurface& surf) const;
static zeus::CVector3f g_PlayerPosition;
static float g_ModSeconds;
static float g_TransformedTime;
static float g_TransformedTime2;
static CBooModel* g_LastModelCached;
static bool g_DummyTextures;
static bool g_RenderModelBlack;
public:
~CBooModel();
CBooModel(TToken<CModel>& token, CModel* parent, std::vector<CBooSurface>* surfaces, SShader& shader,
const boo::ObjToken<boo::IGraphicsBufferS>& vbo, const boo::ObjToken<boo::IGraphicsBufferS>& ibo,
const zeus::CAABox& aabb, u8 renderMask, int numInsts);
static void MakeTexturesFromMats(const MaterialSet& matSet,
std::unordered_map<CAssetId, TCachedToken<CTexture>>& toksOut,
IObjectStore& store);
void MakeTexturesFromMats(std::unordered_map<CAssetId, TCachedToken<CTexture>>& toksOut, IObjectStore& store);
bool IsOpaque() const { return x3c_firstSortedSurface == nullptr; }
void ActivateLights(const std::vector<CLight>& lights);
void SetAmbientColor(const zeus::CColor& color) { m_lightingData.ambient = color; }
void DisableAllLights();
void RemapMaterialData(SShader& shader);
void RemapMaterialData(SShader& shader, const std::unordered_map<int, CModelShaders::ShaderPipelines>& pipelines);
bool TryLockTextures() const;
void UnlockTextures() const;
void SyncLoadTextures() const;
void Touch(int shaderIdx) const;
void VerifyCurrentShader(int shaderIdx);
boo::ObjToken<boo::IGraphicsBufferD> UpdateUniformData(const CModelFlags& flags, const CSkinRules* cskr,
const CPoseAsTransforms* pose, int sharedLayoutBuf = -1) const;
void DrawAlpha(const CModelFlags& flags, const CSkinRules* cskr, const CPoseAsTransforms* pose) const;
void DrawNormal(const CModelFlags& flags, const CSkinRules* cskr, const CPoseAsTransforms* pose) const;
void Draw(const CModelFlags& flags, const CSkinRules* cskr, const CPoseAsTransforms* pose) const;
void DrawFlat(ESurfaceSelection sel, EExtendedShader extendedIdx) const;
void LockParent() { m_modelTok.Lock(); }
void UnlockParent() { m_modelTok.Unlock(); }
const MaterialSet::Material& GetMaterialByIndex(int idx) const { return x4_matSet->materials.at(idx); }
void ClearUniformCounter() { m_uniUpdateCount = 0; }
static void ClearModelUniformCounters();
static bool g_DrawingOccluders;
static void SetDrawingOccluders(bool occ) { g_DrawingOccluders = occ; }
static void SetNewPlayerPositionAndTime(const zeus::CVector3f& pos);
static zeus::CVector3f g_ReflectViewPos;
static void KillCachedViewDepState();
static void EnsureViewDepStateCached(const CBooModel& model, const CBooSurface* surf, zeus::CMatrix4f* mtxsOut,
float& alphaOut);
static boo::ObjToken<boo::ITexture> g_shadowMap;
static zeus::CTransform g_shadowTexXf;
static void EnableShadowMaps(const boo::ObjToken<boo::ITexture>& map, const zeus::CTransform& texXf);
static void DisableShadowMaps();
static boo::ObjToken<boo::ITexture> g_disintegrateTexture;
static void SetDisintegrateTexture(const boo::ObjToken<boo::ITexture>& map) { g_disintegrateTexture = map; }
static boo::ObjToken<boo::ITextureCubeR> g_reflectionCube;
static void SetReflectionCube(const boo::ObjToken<boo::ITextureCubeR>& map) { g_reflectionCube = map; }
static void SetDummyTextures(bool b) { g_DummyTextures = b; }
static void SetRenderModelBlack(bool b) { g_RenderModelBlack = b; }
static void Shutdown();
const zeus::CAABox& GetAABB() const { return x20_aabb; }
};
class CModel {
friend class CBooModel;
friend struct GeometryUniformLayout;
// std::unique_ptr<u8[]> x0_data;
// u32 x4_dataLen;
TToken<CModel> m_selfToken; /* DO NOT LOCK! */
zeus::CAABox m_aabb;
u32 m_flags;
std::vector<CBooSurface> x8_surfaces;
std::vector<SShader> x18_matSets;
std::unique_ptr<CBooModel> x28_modelInst;
// CModel* x30_next = nullptr;
// CModel* x34_prev = nullptr;
int x38_lastFrame;
/* urde addition: boo! */
boo::ObjToken<boo::IGraphicsBufferS> m_staticVbo;
hecl::HMDLMeta m_hmdlMeta;
std::unique_ptr<uint8_t[]> m_dynamicVertexData;
boo::ObjToken<boo::IGraphicsBufferS> m_ibo;
public:
using MaterialSet = DataSpec::DNAMP1::HMDLMaterialSet;
CModel(std::unique_ptr<u8[]>&& in, u32 dataLen, IObjectStore* store, CObjectReference* selfRef);
void DrawSortedParts(const CModelFlags& flags) const;
void DrawUnsortedParts(const CModelFlags& flags) const;
void Draw(const CModelFlags& flags) const;
bool IsLoaded(int shaderIdx) const;
void Touch(int shaderIdx) { x28_modelInst->Touch(shaderIdx); }
const zeus::CAABox& GetAABB() const { return m_aabb; }
CBooModel& GetInstance() { return *x28_modelInst; }
const CBooModel& GetInstance() const { return *x28_modelInst; }
std::unique_ptr<CBooModel> MakeNewInstance(int shaderIdx, int subInsts, bool lockParent = true);
void UpdateLastFrame() const { const_cast<CModel&>(*this).x38_lastFrame = CGraphics::GetFrameCounter(); }
size_t GetPoolVertexOffset(size_t idx) const;
zeus::CVector3f GetPoolVertex(size_t idx) const;
size_t GetPoolNormalOffset(size_t idx) const;
zeus::CVector3f GetPoolNormal(size_t idx) const;
void ApplyVerticesCPU(const boo::ObjToken<boo::IGraphicsBufferD>& vertBuf,
const std::vector<std::pair<zeus::CVector3f, zeus::CVector3f>>& vn) const;
void RestoreVerticesCPU(const boo::ObjToken<boo::IGraphicsBufferD>& vertBuf) const;
void _WarmupShaders();
static void WarmupShaders(const SObjectTag& cmdlTag);
};
CFactoryFnReturn FModelFactory(const urde::SObjectTag& tag, std::unique_ptr<u8[]>&& in, u32 len,
const urde::CVParamTransfer& vparms, CObjectReference* selfRef);
} // namespace urde
<commit_msg>CModel: Implement CModelFlags' operator!= in terms of operator==<commit_after>#pragma once
#include <memory>
#include <optional>
#include <unordered_map>
#include <vector>
#include "DNACommon/CMDL.hpp"
#include "DNAMP1/CMDLMaterials.hpp"
#include "Runtime/CFactoryMgr.hpp"
#include "Runtime/CToken.hpp"
#include "Runtime/RetroTypes.hpp"
#include "Shaders/CModelShaders.hpp"
#include <boo/graphicsdev/IGraphicsDataFactory.hpp>
#include <hecl/HMDLMeta.hpp>
#include <zeus/CAABox.hpp>
#include <zeus/CColor.hpp>
namespace urde {
class CLight;
class CModel;
class CPoseAsTransforms;
class CSkinRules;
class CTexture;
class IObjectStore;
struct CModelFlags {
u8 x0_blendMode = 0; /* 2: add color, >6: additive, >4: blend, else opaque */
u8 x1_matSetIdx = 0;
EExtendedShader m_extendedShader = EExtendedShader::Lighting;
bool m_noCull = false;
bool m_noZWrite = false;
bool m_depthGreater = false;
u16 x2_flags = 0; /* Flags */
zeus::CColor x4_color; /* Set into kcolor slot specified by material */
zeus::CColor addColor = zeus::skClear;
zeus::CAABox mbShadowBox;
CModelFlags() = default;
CModelFlags(u8 blendMode, u8 shadIdx, u16 flags, const zeus::CColor& col)
: x0_blendMode(blendMode), x1_matSetIdx(shadIdx), x2_flags(flags), x4_color(col) {
/* Blend mode will override this if the surface's original material is opaque */
m_noZWrite = !(x2_flags & 0x2);
m_depthGreater = (x2_flags & 0x8);
}
/* Flags
0x1: depth equal
0x2: depth update
0x4: render without texture lock
0x8: depth greater
0x10: depth non-inclusive
*/
bool operator==(const CModelFlags& other) const {
return x0_blendMode == other.x0_blendMode && x1_matSetIdx == other.x1_matSetIdx && x2_flags == other.x2_flags &&
x4_color == other.x4_color;
}
bool operator!=(const CModelFlags& other) const { return !operator==(other); }
};
/* urde addition: doesn't require hacky stashing of
* pointers within loaded CMDL buffer */
struct CBooSurface {
DataSpec::DNACMDL::SurfaceHeader_2 m_data;
size_t selfIdx;
class CBooModel* m_parent = nullptr;
CBooSurface* m_next = nullptr;
zeus::CAABox GetBounds() const {
if (!m_data.aabbSz)
return zeus::CAABox(m_data.centroid, m_data.centroid);
else
return zeus::CAABox(m_data.aabb[0], m_data.aabb[1]);
}
};
using MaterialSet = DataSpec::DNAMP1::HMDLMaterialSet;
struct GeometryUniformLayout {
mutable std::vector<boo::ObjToken<boo::IGraphicsBufferD>> m_sharedBuffer;
size_t m_geomBufferSize = 0;
size_t m_skinBankCount = 0;
size_t m_weightVecCount = 0;
std::vector<size_t> m_skinOffs;
std::vector<size_t> m_skinSizes;
std::vector<size_t> m_uvOffs;
std::vector<size_t> m_uvSizes;
GeometryUniformLayout(const CModel* model, const MaterialSet* matSet);
void Update(const CModelFlags& flags, const CSkinRules* cskr, const CPoseAsTransforms* pose,
const MaterialSet* matSet, const boo::ObjToken<boo::IGraphicsBufferD>& buf,
const CBooModel* parent) const;
void ReserveSharedBuffers(boo::IGraphicsDataFactory::Context& ctx, int size);
boo::ObjToken<boo::IGraphicsBufferD> GetSharedBuffer(int idx) const;
};
struct SShader {
std::unordered_map<CAssetId, TCachedToken<CTexture>> x0_textures;
std::unordered_map<int, CModelShaders::ShaderPipelines> m_shaders;
MaterialSet m_matSet;
std::optional<GeometryUniformLayout> m_geomLayout;
int m_matSetIdx;
SShader(int idx) : m_matSetIdx(idx) {
x0_textures.clear();
m_shaders.clear();
}
void InitializeLayout(const CModel* model) { m_geomLayout.emplace(model, &m_matSet); }
void UnlockTextures();
CModelShaders::ShaderPipelines BuildShader(const hecl::HMDLMeta& meta, const MaterialSet::Material& mat);
void BuildShaders(const hecl::HMDLMeta& meta, std::unordered_map<int, CModelShaders::ShaderPipelines>& shaders);
void BuildShaders(const hecl::HMDLMeta& meta) { BuildShaders(meta, m_shaders); }
};
class CBooModel {
friend class CBooRenderer;
friend class CGameArea;
friend class CMetroidModelInstance;
friend class CModel;
friend class CSkinnedModel;
friend struct GeometryUniformLayout;
public:
enum class ESurfaceSelection { UnsortedOnly, SortedOnly, All };
private:
CBooModel* m_next = nullptr;
CBooModel* m_prev = nullptr;
size_t m_uniUpdateCount = 0;
TToken<CModel> m_modelTok;
CModel* m_model;
std::vector<CBooSurface>* x0_surfaces;
const MaterialSet* x4_matSet;
const GeometryUniformLayout* m_geomLayout;
int m_matSetIdx = -1;
const std::unordered_map<int, CModelShaders::ShaderPipelines>* m_pipelines;
std::unordered_map<CAssetId, TCachedToken<CTexture>> x1c_textures;
zeus::CAABox x20_aabb;
CBooSurface* x38_firstUnsortedSurface = nullptr;
CBooSurface* x3c_firstSortedSurface = nullptr;
bool x40_24_texturesLoaded : 1;
bool x40_25_modelVisible : 1;
u8 x41_mask;
u32 x44_areaInstanceIdx = UINT32_MAX;
struct UVAnimationBuffer {
static void ProcessAnimation(u8*& bufOut, const MaterialSet::Material::PASS& anim);
static void PadOutBuffer(u8*& bufStart, u8*& bufOut);
static void Update(u8*& bufOut, const MaterialSet* matSet, const CModelFlags& flags, const CBooModel* parent);
};
CModelShaders::LightingUniform m_lightingData;
/* urde addition: boo! */
size_t m_uniformDataSize = 0;
struct ModelInstance {
boo::ObjToken<boo::IGraphicsBufferD> m_geomUniformBuffer;
boo::ObjToken<boo::IGraphicsBufferD> m_uniformBuffer;
std::vector<std::vector<boo::ObjToken<boo::IShaderDataBinding>>> m_shaderDataBindings;
boo::ObjToken<boo::IGraphicsBufferD> m_dynamicVbo;
boo::ObjToken<boo::IGraphicsBuffer> GetBooVBO(const CBooModel& model, boo::IGraphicsDataFactory::Context& ctx);
};
std::vector<ModelInstance> m_instances;
ModelInstance m_ballShadowInstance;
boo::ObjToken<boo::IGraphicsBufferS> m_staticVbo;
boo::ObjToken<boo::IGraphicsBufferS> m_staticIbo;
boo::ObjToken<boo::ITexture> m_lastDrawnShadowMap;
boo::ObjToken<boo::ITexture> m_lastDrawnOneTexture;
boo::ObjToken<boo::ITextureCubeR> m_lastDrawnReflectionCube;
ModelInstance* PushNewModelInstance(int sharedLayoutBuf = -1);
void DrawAlphaSurfaces(const CModelFlags& flags) const;
void DrawNormalSurfaces(const CModelFlags& flags) const;
void DrawSurfaces(const CModelFlags& flags) const;
void DrawSurface(const CBooSurface& surf, const CModelFlags& flags) const;
void WarmupDrawSurfaces() const;
void WarmupDrawSurface(const CBooSurface& surf) const;
static zeus::CVector3f g_PlayerPosition;
static float g_ModSeconds;
static float g_TransformedTime;
static float g_TransformedTime2;
static CBooModel* g_LastModelCached;
static bool g_DummyTextures;
static bool g_RenderModelBlack;
public:
~CBooModel();
CBooModel(TToken<CModel>& token, CModel* parent, std::vector<CBooSurface>* surfaces, SShader& shader,
const boo::ObjToken<boo::IGraphicsBufferS>& vbo, const boo::ObjToken<boo::IGraphicsBufferS>& ibo,
const zeus::CAABox& aabb, u8 renderMask, int numInsts);
static void MakeTexturesFromMats(const MaterialSet& matSet,
std::unordered_map<CAssetId, TCachedToken<CTexture>>& toksOut,
IObjectStore& store);
void MakeTexturesFromMats(std::unordered_map<CAssetId, TCachedToken<CTexture>>& toksOut, IObjectStore& store);
bool IsOpaque() const { return x3c_firstSortedSurface == nullptr; }
void ActivateLights(const std::vector<CLight>& lights);
void SetAmbientColor(const zeus::CColor& color) { m_lightingData.ambient = color; }
void DisableAllLights();
void RemapMaterialData(SShader& shader);
void RemapMaterialData(SShader& shader, const std::unordered_map<int, CModelShaders::ShaderPipelines>& pipelines);
bool TryLockTextures() const;
void UnlockTextures() const;
void SyncLoadTextures() const;
void Touch(int shaderIdx) const;
void VerifyCurrentShader(int shaderIdx);
boo::ObjToken<boo::IGraphicsBufferD> UpdateUniformData(const CModelFlags& flags, const CSkinRules* cskr,
const CPoseAsTransforms* pose, int sharedLayoutBuf = -1) const;
void DrawAlpha(const CModelFlags& flags, const CSkinRules* cskr, const CPoseAsTransforms* pose) const;
void DrawNormal(const CModelFlags& flags, const CSkinRules* cskr, const CPoseAsTransforms* pose) const;
void Draw(const CModelFlags& flags, const CSkinRules* cskr, const CPoseAsTransforms* pose) const;
void DrawFlat(ESurfaceSelection sel, EExtendedShader extendedIdx) const;
void LockParent() { m_modelTok.Lock(); }
void UnlockParent() { m_modelTok.Unlock(); }
const MaterialSet::Material& GetMaterialByIndex(int idx) const { return x4_matSet->materials.at(idx); }
void ClearUniformCounter() { m_uniUpdateCount = 0; }
static void ClearModelUniformCounters();
static bool g_DrawingOccluders;
static void SetDrawingOccluders(bool occ) { g_DrawingOccluders = occ; }
static void SetNewPlayerPositionAndTime(const zeus::CVector3f& pos);
static zeus::CVector3f g_ReflectViewPos;
static void KillCachedViewDepState();
static void EnsureViewDepStateCached(const CBooModel& model, const CBooSurface* surf, zeus::CMatrix4f* mtxsOut,
float& alphaOut);
static boo::ObjToken<boo::ITexture> g_shadowMap;
static zeus::CTransform g_shadowTexXf;
static void EnableShadowMaps(const boo::ObjToken<boo::ITexture>& map, const zeus::CTransform& texXf);
static void DisableShadowMaps();
static boo::ObjToken<boo::ITexture> g_disintegrateTexture;
static void SetDisintegrateTexture(const boo::ObjToken<boo::ITexture>& map) { g_disintegrateTexture = map; }
static boo::ObjToken<boo::ITextureCubeR> g_reflectionCube;
static void SetReflectionCube(const boo::ObjToken<boo::ITextureCubeR>& map) { g_reflectionCube = map; }
static void SetDummyTextures(bool b) { g_DummyTextures = b; }
static void SetRenderModelBlack(bool b) { g_RenderModelBlack = b; }
static void Shutdown();
const zeus::CAABox& GetAABB() const { return x20_aabb; }
};
class CModel {
friend class CBooModel;
friend struct GeometryUniformLayout;
// std::unique_ptr<u8[]> x0_data;
// u32 x4_dataLen;
TToken<CModel> m_selfToken; /* DO NOT LOCK! */
zeus::CAABox m_aabb;
u32 m_flags;
std::vector<CBooSurface> x8_surfaces;
std::vector<SShader> x18_matSets;
std::unique_ptr<CBooModel> x28_modelInst;
// CModel* x30_next = nullptr;
// CModel* x34_prev = nullptr;
int x38_lastFrame;
/* urde addition: boo! */
boo::ObjToken<boo::IGraphicsBufferS> m_staticVbo;
hecl::HMDLMeta m_hmdlMeta;
std::unique_ptr<uint8_t[]> m_dynamicVertexData;
boo::ObjToken<boo::IGraphicsBufferS> m_ibo;
public:
using MaterialSet = DataSpec::DNAMP1::HMDLMaterialSet;
CModel(std::unique_ptr<u8[]>&& in, u32 dataLen, IObjectStore* store, CObjectReference* selfRef);
void DrawSortedParts(const CModelFlags& flags) const;
void DrawUnsortedParts(const CModelFlags& flags) const;
void Draw(const CModelFlags& flags) const;
bool IsLoaded(int shaderIdx) const;
void Touch(int shaderIdx) { x28_modelInst->Touch(shaderIdx); }
const zeus::CAABox& GetAABB() const { return m_aabb; }
CBooModel& GetInstance() { return *x28_modelInst; }
const CBooModel& GetInstance() const { return *x28_modelInst; }
std::unique_ptr<CBooModel> MakeNewInstance(int shaderIdx, int subInsts, bool lockParent = true);
void UpdateLastFrame() const { const_cast<CModel&>(*this).x38_lastFrame = CGraphics::GetFrameCounter(); }
size_t GetPoolVertexOffset(size_t idx) const;
zeus::CVector3f GetPoolVertex(size_t idx) const;
size_t GetPoolNormalOffset(size_t idx) const;
zeus::CVector3f GetPoolNormal(size_t idx) const;
void ApplyVerticesCPU(const boo::ObjToken<boo::IGraphicsBufferD>& vertBuf,
const std::vector<std::pair<zeus::CVector3f, zeus::CVector3f>>& vn) const;
void RestoreVerticesCPU(const boo::ObjToken<boo::IGraphicsBufferD>& vertBuf) const;
void _WarmupShaders();
static void WarmupShaders(const SObjectTag& cmdlTag);
};
CFactoryFnReturn FModelFactory(const urde::SObjectTag& tag, std::unique_ptr<u8[]>&& in, u32 len,
const urde::CVParamTransfer& vparms, CObjectReference* selfRef);
} // namespace urde
<|endoftext|>
|
<commit_before>/*
* illarionserver - server for the game Illarion
* Copyright 2011 Illarion e.V.
*
* This file is part of illarionserver.
*
* illarionserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* illarionserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with illarionserver. If not, see <http://www.gnu.org/licenses/>.
*/
#include "LuaQuestScript.hpp"
#include "Character.hpp"
#include "character_ptr.hpp"
LuaQuestScript::LuaQuestScript(const std::string &filename, TYPE_OF_QUEST_ID quest) throw(ScriptException)
: LuaScript(filename), quest(quest) {
}
LuaQuestScript::~LuaQuestScript() throw() {}
std::string LuaQuestScript::title(Character *user) {
character_ptr fuse_user(user);
return callEntrypoint<std::string>("QuestTitle", fuse_user);
}
std::string LuaQuestScript::description(Character *user, TYPE_OF_QUESTSTATUS status) {
character_ptr fuse_user(user);
return callEntrypoint<std::string>("QuestDescription", fuse_user, status);
}
QuestAvailability LuaQuestScript::available(Character *user, TYPE_OF_QUESTSTATUS status) {
character_ptr fuse_user(user);
return callEntrypoint<QuestAvailability>("QuestAvailability", fuse_user, status);
}
position LuaQuestScript::start() {
using namespace luabind;
auto startPosition = callEntrypoint<object>("QuestStart");
try {
return getPosition(startPosition);
} catch (std::logic_error &e) {
std::stringstream error;
error << "No valid QuestStart entrypoint in quest " << quest << ".";
writeDebugMsg(error.str());
throw;
}
}
void LuaQuestScript::targets(Character *user, TYPE_OF_QUESTSTATUS status, std::vector<position> &targets) {
using namespace luabind;
targets.clear();
character_ptr fuse_user(user);
auto luaTargets = callEntrypoint<object>("QuestTargets", fuse_user, status);
if (!luaTargets.is_valid()) {
std::stringstream error;
error << "No valid QuestTarget entrypoint in quest " << quest << ".";
writeDebugMsg(error.str());
return;
}
try {
targets.push_back(getPosition(luaTargets));
return;
} catch (std::logic_error &e) {
}
auto mapType = type(luaTargets);
if (mapType == LUA_TTABLE) {
for (iterator it(luaTargets), end; it != end; ++it) {
try {
targets.push_back(getPosition(*it));
} catch (std::logic_error &e) {
std::stringstream error;
error << "Usage of invalid target table entry in quest " << quest;
error << " for status " << status << ". A target table entry ";
error << "must be either a position or a table of three coordinates.";
writeDebugMsg(error.str());
}
}
} else if (mapType == LUA_TNIL) {
// no targets to add
} else {
std::stringstream error;
error << "Usage of invalid quest target type in quest " << quest;
error << " for status " << status << ". You must return a table of positions and/or";
error << " coordinates, a position, a table of three coordinates or nil in QuestTargets!";
writeDebugMsg(error.str());
}
}
TYPE_OF_QUESTSTATUS LuaQuestScript::finalStatus() {
return callEntrypoint<TYPE_OF_QUESTSTATUS>("QuestFinalStatus");
}
position LuaQuestScript::getPosition(const luabind::object &potentialPosition) {
using namespace luabind;
if (!potentialPosition.is_valid()) {
throw std::logic_error("no position found");
}
try {
return object_cast<position>(potentialPosition);
} catch (cast_failed &e) {
}
auto positionType = type(potentialPosition);
if (positionType == LUA_TTABLE) {
try {
int16_t x = object_cast<int16_t>(potentialPosition[1]);
int16_t y = object_cast<int16_t>(potentialPosition[2]);
int16_t z = object_cast<int16_t>(potentialPosition[3]);
return position(x, y, z);
} catch (cast_failed &e) {
}
}
throw std::logic_error("no position found");
}
<commit_msg>Fix default for missing QuestAvailability entry point<commit_after>/*
* illarionserver - server for the game Illarion
* Copyright 2011 Illarion e.V.
*
* This file is part of illarionserver.
*
* illarionserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* illarionserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with illarionserver. If not, see <http://www.gnu.org/licenses/>.
*/
#include "LuaQuestScript.hpp"
#include "Character.hpp"
#include "character_ptr.hpp"
LuaQuestScript::LuaQuestScript(const std::string &filename, TYPE_OF_QUEST_ID quest) throw(ScriptException)
: LuaScript(filename), quest(quest) {
}
LuaQuestScript::~LuaQuestScript() throw() {}
std::string LuaQuestScript::title(Character *user) {
character_ptr fuse_user(user);
return callEntrypoint<std::string>("QuestTitle", fuse_user);
}
std::string LuaQuestScript::description(Character *user, TYPE_OF_QUESTSTATUS status) {
character_ptr fuse_user(user);
return callEntrypoint<std::string>("QuestDescription", fuse_user, status);
}
QuestAvailability LuaQuestScript::available(Character *user, TYPE_OF_QUESTSTATUS status) {
if (!existsEntrypoint("QuestAvailability")) {
return questDefaultAvailable;
}
character_ptr fuse_user(user);
return callEntrypoint<QuestAvailability>("QuestAvailability", fuse_user, status);
}
position LuaQuestScript::start() {
using namespace luabind;
auto startPosition = callEntrypoint<object>("QuestStart");
try {
return getPosition(startPosition);
} catch (std::logic_error &e) {
std::stringstream error;
error << "No valid QuestStart entrypoint in quest " << quest << ".";
writeDebugMsg(error.str());
throw;
}
}
void LuaQuestScript::targets(Character *user, TYPE_OF_QUESTSTATUS status, std::vector<position> &targets) {
using namespace luabind;
targets.clear();
character_ptr fuse_user(user);
auto luaTargets = callEntrypoint<object>("QuestTargets", fuse_user, status);
if (!luaTargets.is_valid()) {
std::stringstream error;
error << "No valid QuestTarget entrypoint in quest " << quest << ".";
writeDebugMsg(error.str());
return;
}
try {
targets.push_back(getPosition(luaTargets));
return;
} catch (std::logic_error &e) {
}
auto mapType = type(luaTargets);
if (mapType == LUA_TTABLE) {
for (iterator it(luaTargets), end; it != end; ++it) {
try {
targets.push_back(getPosition(*it));
} catch (std::logic_error &e) {
std::stringstream error;
error << "Usage of invalid target table entry in quest " << quest;
error << " for status " << status << ". A target table entry ";
error << "must be either a position or a table of three coordinates.";
writeDebugMsg(error.str());
}
}
} else if (mapType == LUA_TNIL) {
// no targets to add
} else {
std::stringstream error;
error << "Usage of invalid quest target type in quest " << quest;
error << " for status " << status << ". You must return a table of positions and/or";
error << " coordinates, a position, a table of three coordinates or nil in QuestTargets!";
writeDebugMsg(error.str());
}
}
TYPE_OF_QUESTSTATUS LuaQuestScript::finalStatus() {
return callEntrypoint<TYPE_OF_QUESTSTATUS>("QuestFinalStatus");
}
position LuaQuestScript::getPosition(const luabind::object &potentialPosition) {
using namespace luabind;
if (!potentialPosition.is_valid()) {
throw std::logic_error("no position found");
}
try {
return object_cast<position>(potentialPosition);
} catch (cast_failed &e) {
}
auto positionType = type(potentialPosition);
if (positionType == LUA_TTABLE) {
try {
int16_t x = object_cast<int16_t>(potentialPosition[1]);
int16_t y = object_cast<int16_t>(potentialPosition[2]);
int16_t z = object_cast<int16_t>(potentialPosition[3]);
return position(x, y, z);
} catch (cast_failed &e) {
}
}
throw std::logic_error("no position found");
}
<|endoftext|>
|
<commit_before>/*
* This file is part of signon
*
* Copyright (C) 2009-2010 Nokia Corporation.
*
* Contact: Alberto Mardegan <alberto.mardegan@nokia.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
extern "C" {
#include <signal.h>
#include <stdlib.h>
#include <stddef.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/poll.h>
}
#include <remotepluginprocess.h>
using namespace RemotePluginProcessNS;
RemotePluginProcess *process = NULL;
int main(int argc, char *argv[])
{
TRACE();
#ifndef NO_SIGNON_USER
if (!::getuid()) {
BLAME() << argv[0] << " cannot be started with root priviledges!!!";
exit(2);
}
#endif
QCoreApplication app(argc, argv);
if (argc < 2) {
TRACE() << "Type of plugin is not specified";
exit(1);
}
QString type = app.arguments().at(1); TRACE() << type;
fcntl(fileno(stdin), F_SETFL, fcntl(fileno(stdin), F_GETFL, 0) | O_NONBLOCK);
process = RemotePluginProcess::createRemotePluginProcess(type, &app);
if (!process)
return 1;
fprintf(stdout, "process started");
fflush(stdout);
QObject::connect(process, SIGNAL(processStopped()), &app, SLOT(quit()));
return app.exec();
}
<commit_msg>RemotePluginProcess: use syslog for debugging<commit_after>/*
* This file is part of signon
*
* Copyright (C) 2009-2010 Nokia Corporation.
*
* Contact: Alberto Mardegan <alberto.mardegan@nokia.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
extern "C" {
#include <signal.h>
#include <stdlib.h>
#include <stddef.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/poll.h>
#include <syslog.h>
}
#include "remotepluginprocess.h"
#include <QDebug>
using namespace RemotePluginProcessNS;
RemotePluginProcess *process = NULL;
static void messageHandler(QtMsgType type, const char *msg)
{
int priority;
switch (type) {
case QtWarningMsg: priority = LOG_WARNING; break;
case QtCriticalMsg: priority = LOG_CRIT; break;
case QtFatalMsg: priority = LOG_EMERG; break;
case QtDebugMsg:
/* fall through */
default: priority = LOG_INFO; break;
}
syslog(priority, msg);
}
int main(int argc, char *argv[])
{
qInstallMsgHandler(messageHandler);
TRACE();
#ifndef NO_SIGNON_USER
if (!::getuid()) {
BLAME() << argv[0] << " cannot be started with root priviledges!!!";
exit(2);
}
#endif
QCoreApplication app(argc, argv);
if (argc < 2) {
TRACE() << "Type of plugin is not specified";
exit(1);
}
QString type = app.arguments().at(1); TRACE() << type;
fcntl(fileno(stdin), F_SETFL, fcntl(fileno(stdin), F_GETFL, 0) | O_NONBLOCK);
process = RemotePluginProcess::createRemotePluginProcess(type, &app);
if (!process)
return 1;
fprintf(stdout, "process started");
fflush(stdout);
QObject::connect(process, SIGNAL(processStopped()), &app, SLOT(quit()));
return app.exec();
}
<|endoftext|>
|
<commit_before><commit_msg>cppcheck: Possible inefficient checking for emptiness<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright (C) 2014 Love Park Robotics, 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 distribted 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 "o3d3xx_framegrabber/frame_grabber.h"
#include <algorithm>
#include <chrono>
#include <cstdint>
#include <cstdlib>
#include <exception>
#include <stdexcept>
#include <functional>
#include <iomanip>
#include <mutex>
#include <sstream>
#include <string>
#include <system_error>
#include <boost/asio.hpp>
#include <boost/system/system_error.hpp>
#include <glog/logging.h>
#include "o3d3xx_camera/camera.hpp"
#include "o3d3xx_camera/err.h"
#include "o3d3xx_camera/device_config.h"
#include "o3d3xx_camera/app_config.h"
#include "o3d3xx_framegrabber/byte_buffer.hpp"
#include "o3d3xx_framegrabber/pcic_schema.h"
// <Ticket><Length>CR+LF (16 bytes)
const std::size_t o3d3xx::TICKET_ID_SZ = 16;
const std::string o3d3xx::TICKET_image = "0000";
const std::string o3d3xx::TICKET_c = "1000";
const std::string o3d3xx::TICKET_t = "1001";
o3d3xx::FrameGrabber::FrameGrabber(o3d3xx::Camera::Ptr cam,
std::uint16_t mask)
: cam_(cam),
io_service_(),
sock_(io_service_),
pcic_ready_(false),
mask_(mask)
{
this->SetSchemaBuffer(this->mask_);
this->SetTriggerBuffer();
try
{
this->cam_ip_ = this->cam_->GetIP();
this->cam_port_ = std::stoi(this->cam_->GetParameter("PcicTcpPort"));
}
catch (const o3d3xx::error_t& ex)
{
LOG(ERROR) << "Could not get IP/Port of the camera: "
<< ex.what();
// NOTE: GetIP() won't throw, so, the problem must be getting the PCIC
// port. Here we assume the default. Former behavior was to throw!
LOG(WARNING) << "Assuming default PCIC port!";
this->cam_port_ = o3d3xx::DEFAULT_PCIC_PORT;
}
LOG(INFO) << "Camera connection info: ip=" << this->cam_ip_
<< ", port=" << this->cam_port_;
this->endpoint_ =
boost::asio::ip::tcp::endpoint(
boost::asio::ip::address::from_string(this->cam_ip_), this->cam_port_);
this->thread_ =
std::unique_ptr<std::thread>(
new std::thread(std::bind(&o3d3xx::FrameGrabber::Run, this)));
}
o3d3xx::FrameGrabber::~FrameGrabber()
{
DLOG(INFO) << "FrameGrabber dtor running...";
if (this->thread_ && this->thread_->joinable())
{
// NOTE: If Stop() was already called, that is fine
// because the ASIO event loop is already done so the posted exception
// will never get emitted.
this->Stop();
this->thread_->join();
}
DLOG(INFO) << "FrameGrabber done.";
}
void
o3d3xx::FrameGrabber::SetSchemaBuffer(std::uint16_t mask)
{
std::string schema = o3d3xx::make_pcic_schema(mask);
int c_len = 4 + 1 + 9 + schema.size() + 2;
std::ostringstream str;
str << o3d3xx::TICKET_c
<< 'L' << std::setfill('0') << std::setw(9) << c_len
<< '\r' << '\n'
<< o3d3xx::TICKET_c << 'c'
<< std::setfill('0') << std::setw(9)
<< schema.size()
<< schema
<< '\r' << '\n';
std::string c_command = str.str();
this->schema_buffer_.assign(c_command.begin(), c_command.end());
DLOG(INFO) << "c_command: " << c_command;
}
void
o3d3xx::FrameGrabber::SetTriggerBuffer()
{
int t_len = 4 + 1 + 2;
std::ostringstream str;
str << o3d3xx::TICKET_t
<< 'L' << std::setfill('0') << std::setw(9) << t_len
<< '\r' << '\n'
<< o3d3xx::TICKET_t << 't' << '\r' << '\n';
std::string t_command = str.str();
this->trigger_buffer_.assign(t_command.begin(), t_command.end());
}
void
o3d3xx::FrameGrabber::SWTrigger()
{
int i = 0;
while (! this->pcic_ready_.load())
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
i++;
if (i > 2000)
{
LOG(WARNING) << "pcic_ready_ flag not set!";
return;
}
}
this->io_service_.post(
[=]()
{
boost::asio::async_write(
this->sock_,
boost::asio::buffer(this->trigger_buffer_.data(),
this->trigger_buffer_.size()),
[=] (const boost::system::error_code& ec,
std::size_t bytes_transferred)
{
if (ec) { throw o3d3xx::error_t(ec.value()); }
});
});
}
void
o3d3xx::FrameGrabber::Stop()
{
this->io_service_.post([]() {
throw o3d3xx::error_t(O3D3XX_THREAD_INTERRUPTED); });
}
bool
o3d3xx::FrameGrabber::WaitForFrame(o3d3xx::ByteBuffer* buff,
long timeout_millis,
bool copy_buff,
bool organize)
{
// mutex will unlock in `unique_lock' dtor if not explicitly unlocked prior
std::unique_lock<std::mutex> lock(this->front_buffer_mutex_);
try
{
if (timeout_millis <= 0)
{
this->front_buffer_cv_.wait(lock);
}
else
{
if (this->front_buffer_cv_.wait_for(
lock, std::chrono::milliseconds(timeout_millis)) ==
std::cv_status::timeout)
{
LOG(WARNING) << "Timeout waiting for image buffer from camera";
return false;
}
}
}
catch (const std::system_error& ex)
{
LOG(WARNING) << "WaitForFrame: " << ex.what();
return false;
}
DLOG(INFO) << "Client fetching new image data";
buff->SetBytes(this->front_buffer_, copy_buff);
lock.unlock();
if (organize)
{
buff->Organize();
}
return true;
}
void
o3d3xx::FrameGrabber::ImageHandler(const boost::system::error_code& ec,
std::size_t bytes_transferred,
std::size_t bytes_read)
{
if (ec) { throw o3d3xx::error_t(ec.value()); }
bytes_read += bytes_transferred;
if (bytes_read != this->back_buffer_.size())
{
this->sock_.async_read_some(
boost::asio::buffer(&this->back_buffer_[bytes_read],
this->back_buffer_.size() - bytes_read),
std::bind(&o3d3xx::FrameGrabber::ImageHandler, this,
std::placeholders::_1, std::placeholders::_2, bytes_read));
return;
}
if (o3d3xx::verify_image_buffer(this->back_buffer_))
{
// Move data to front buffer in O(1)
this->front_buffer_mutex_.lock();
this->back_buffer_.swap(this->front_buffer_);
this->front_buffer_mutex_.unlock();
// notify waiting clients
this->front_buffer_cv_.notify_all();
}
else
{
LOG(WARNING) << "Bad image!";
}
this->ticket_buffer_.clear();
this->ticket_buffer_.resize(o3d3xx::TICKET_ID_SZ);
this->sock_.async_read_some(
boost::asio::buffer(this->ticket_buffer_.data(),
o3d3xx::TICKET_ID_SZ),
std::bind(&o3d3xx::FrameGrabber::TicketHandler, this,
std::placeholders::_1, std::placeholders::_2, 0));
}
void
o3d3xx::FrameGrabber::TicketHandler(const boost::system::error_code& ec,
std::size_t bytes_transferred,
std::size_t bytes_read)
{
if (ec) { throw o3d3xx::error_t(ec.value()); }
bytes_read += bytes_transferred;
if (bytes_read < o3d3xx::TICKET_ID_SZ)
{
bytes_read +=
boost::asio::read(
this->sock_,
boost::asio::buffer(&this->ticket_buffer_[bytes_read],
o3d3xx::TICKET_ID_SZ - bytes_read));
if (bytes_read != o3d3xx::TICKET_ID_SZ)
{
LOG(ERROR) << "Timeout reading ticket!";
throw o3d3xx::error_t(O3D3XX_IO_ERROR);
}
}
std::string ticket;
ticket.assign(this->ticket_buffer_.begin(),
this->ticket_buffer_.begin() + 4);
std::string payload_sz_str;
payload_sz_str.assign(this->ticket_buffer_.begin()+5,
this->ticket_buffer_.begin()+14);
int payload_sz = std::stoi(payload_sz_str);
int ticket_sz = o3d3xx::TICKET_ID_SZ;
if (ticket != o3d3xx::TICKET_image)
{
this->ticket_buffer_.resize(ticket_sz + payload_sz);
bytes_read +=
boost::asio::read(
this->sock_,
boost::asio::buffer(&this->ticket_buffer_[bytes_read],
(ticket_sz + payload_sz) - bytes_read));
if (bytes_read != (ticket_sz + payload_sz))
{
LOG(ERROR) << "Timeout reading whole response!";
LOG(ERROR) << "Got " << bytes_read << " bytes of "
<< ticket_sz << " bytes expected";
throw o3d3xx::error_t(O3D3XX_IO_ERROR);
}
}
std::string ticket_str;
ticket_str.assign(this->ticket_buffer_.begin(),
this->ticket_buffer_.end());
DLOG(INFO) << "Ticket Full: '" << ticket_str << "'";
if (ticket == o3d3xx::TICKET_image)
{
if (o3d3xx::verify_ticket_buffer(this->ticket_buffer_))
{
this->back_buffer_.resize(
o3d3xx::get_image_buffer_size(this->ticket_buffer_));
this->sock_.async_read_some(
boost::asio::buffer(this->back_buffer_.data(),
this->back_buffer_.size()),
std::bind(&o3d3xx::FrameGrabber::ImageHandler, this,
std::placeholders::_1, std::placeholders::_2, 0));
return;
}
else
{
LOG(ERROR) << "Bad image ticket: " << ticket_str;
throw(o3d3xx::error_t(O3D3XX_PCIC_BAD_REPLY));
}
}
else if ((ticket == o3d3xx::TICKET_c) ||
(ticket == o3d3xx::TICKET_t))
{
if (this->ticket_buffer_.at(20) != '*')
{
LOG(ERROR) << "Bad ticket: " << ticket_str;
if ((ticket == o3d3xx::TICKET_t) &&
(this->ticket_buffer_.at(20) == '!'))
{
LOG(WARNING) << "Are you software triggering in free run mode?";
}
else
{
throw(o3d3xx::error_t(O3D3XX_PCIC_BAD_REPLY));
}
}
this->ticket_buffer_.clear();
this->ticket_buffer_.resize(o3d3xx::TICKET_ID_SZ);
this->sock_.async_read_some(
boost::asio::buffer(this->ticket_buffer_.data(),
o3d3xx::TICKET_ID_SZ),
std::bind(&o3d3xx::FrameGrabber::TicketHandler, this,
std::placeholders::_1, std::placeholders::_2, 0));
return;
}
else
{
LOG(WARNING) << "Unexpected ticket: " << ticket;
LOG(WARNING) << "Ticket Full: '" << ticket_str << "'";
//throw(std::logic_error("Unexpected ticket type: " + ticket));
this->ticket_buffer_.clear();
this->ticket_buffer_.resize(o3d3xx::TICKET_ID_SZ);
this->sock_.async_read_some(
boost::asio::buffer(this->ticket_buffer_.data(),
o3d3xx::TICKET_ID_SZ),
std::bind(&o3d3xx::FrameGrabber::TicketHandler, this,
std::placeholders::_1, std::placeholders::_2, 0));
return;
}
}
void
o3d3xx::FrameGrabber::Run()
{
boost::asio::io_service::work work(this->io_service_);
auto result_schema_write_handler =
[&, this]
(const boost::system::error_code& ec, std::size_t bytes_transferred)
{
if (ec) { throw o3d3xx::error_t(ec.value()); }
this->ticket_buffer_.clear();
this->ticket_buffer_.resize(o3d3xx::TICKET_ID_SZ);
this->sock_.async_read_some(
boost::asio::buffer(this->ticket_buffer_.data(),
o3d3xx::TICKET_ID_SZ),
std::bind(&o3d3xx::FrameGrabber::TicketHandler,
this, std::placeholders::_1,
std::placeholders::_2, 0));
this->pcic_ready_.store(true);
};
//
// Establish TCP connection to sensor and
// set PCIC schema for this session
//
try
{
this->sock_.async_connect(
this->endpoint_,
[&, this] (const boost::system::error_code& ec)
{
if (ec) { throw o3d3xx::error_t(ec.value()); }
boost::asio::async_write(
this->sock_,
boost::asio::buffer(this->schema_buffer_.data(),
this->schema_buffer_.size()),
result_schema_write_handler);
});
this->io_service_.run();
}
catch (const std::exception& ex)
{
LOG(WARNING) << "Exception: " << ex.what();
}
LOG(INFO) << "Framegrabber thread done.";
}
<commit_msg>Handle spurious wakeups in WaitForFrame<commit_after>/*
* Copyright (C) 2014 Love Park Robotics, 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 distribted 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 "o3d3xx_framegrabber/frame_grabber.h"
#include <algorithm>
#include <chrono>
#include <cstdint>
#include <cstdlib>
#include <exception>
#include <stdexcept>
#include <functional>
#include <iomanip>
#include <mutex>
#include <sstream>
#include <string>
#include <system_error>
#include <boost/asio.hpp>
#include <boost/system/system_error.hpp>
#include <glog/logging.h>
#include "o3d3xx_camera/camera.hpp"
#include "o3d3xx_camera/err.h"
#include "o3d3xx_camera/device_config.h"
#include "o3d3xx_camera/app_config.h"
#include "o3d3xx_framegrabber/byte_buffer.hpp"
#include "o3d3xx_framegrabber/pcic_schema.h"
// <Ticket><Length>CR+LF (16 bytes)
const std::size_t o3d3xx::TICKET_ID_SZ = 16;
const std::string o3d3xx::TICKET_image = "0000";
const std::string o3d3xx::TICKET_c = "1000";
const std::string o3d3xx::TICKET_t = "1001";
o3d3xx::FrameGrabber::FrameGrabber(o3d3xx::Camera::Ptr cam,
std::uint16_t mask)
: cam_(cam),
io_service_(),
sock_(io_service_),
pcic_ready_(false),
mask_(mask)
{
this->SetSchemaBuffer(this->mask_);
this->SetTriggerBuffer();
try
{
this->cam_ip_ = this->cam_->GetIP();
this->cam_port_ = std::stoi(this->cam_->GetParameter("PcicTcpPort"));
}
catch (const o3d3xx::error_t& ex)
{
LOG(ERROR) << "Could not get IP/Port of the camera: "
<< ex.what();
// NOTE: GetIP() won't throw, so, the problem must be getting the PCIC
// port. Here we assume the default. Former behavior was to throw!
LOG(WARNING) << "Assuming default PCIC port!";
this->cam_port_ = o3d3xx::DEFAULT_PCIC_PORT;
}
LOG(INFO) << "Camera connection info: ip=" << this->cam_ip_
<< ", port=" << this->cam_port_;
this->endpoint_ =
boost::asio::ip::tcp::endpoint(
boost::asio::ip::address::from_string(this->cam_ip_), this->cam_port_);
this->thread_ =
std::unique_ptr<std::thread>(
new std::thread(std::bind(&o3d3xx::FrameGrabber::Run, this)));
}
o3d3xx::FrameGrabber::~FrameGrabber()
{
DLOG(INFO) << "FrameGrabber dtor running...";
if (this->thread_ && this->thread_->joinable())
{
// NOTE: If Stop() was already called, that is fine
// because the ASIO event loop is already done so the posted exception
// will never get emitted.
this->Stop();
this->thread_->join();
}
DLOG(INFO) << "FrameGrabber done.";
}
void
o3d3xx::FrameGrabber::SetSchemaBuffer(std::uint16_t mask)
{
std::string schema = o3d3xx::make_pcic_schema(mask);
int c_len = 4 + 1 + 9 + schema.size() + 2;
std::ostringstream str;
str << o3d3xx::TICKET_c
<< 'L' << std::setfill('0') << std::setw(9) << c_len
<< '\r' << '\n'
<< o3d3xx::TICKET_c << 'c'
<< std::setfill('0') << std::setw(9)
<< schema.size()
<< schema
<< '\r' << '\n';
std::string c_command = str.str();
this->schema_buffer_.assign(c_command.begin(), c_command.end());
DLOG(INFO) << "c_command: " << c_command;
}
void
o3d3xx::FrameGrabber::SetTriggerBuffer()
{
int t_len = 4 + 1 + 2;
std::ostringstream str;
str << o3d3xx::TICKET_t
<< 'L' << std::setfill('0') << std::setw(9) << t_len
<< '\r' << '\n'
<< o3d3xx::TICKET_t << 't' << '\r' << '\n';
std::string t_command = str.str();
this->trigger_buffer_.assign(t_command.begin(), t_command.end());
}
void
o3d3xx::FrameGrabber::SWTrigger()
{
int i = 0;
while (! this->pcic_ready_.load())
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
i++;
if (i > 2000)
{
LOG(WARNING) << "pcic_ready_ flag not set!";
return;
}
}
this->io_service_.post(
[=]()
{
boost::asio::async_write(
this->sock_,
boost::asio::buffer(this->trigger_buffer_.data(),
this->trigger_buffer_.size()),
[=] (const boost::system::error_code& ec,
std::size_t bytes_transferred)
{
if (ec) { throw o3d3xx::error_t(ec.value()); }
});
});
}
void
o3d3xx::FrameGrabber::Stop()
{
this->io_service_.post([]() {
throw o3d3xx::error_t(O3D3XX_THREAD_INTERRUPTED); });
}
bool
o3d3xx::FrameGrabber::WaitForFrame(o3d3xx::ByteBuffer* buff,
long timeout_millis,
bool copy_buff,
bool organize)
{
// mutex will unlock in `unique_lock' dtor if not explicitly unlocked prior
std::unique_lock<std::mutex> lock(this->front_buffer_mutex_);
try
{
// Store the current pointer backing the front buffer - this will be the
// condition checked by the condition_variable predicate (pointer should
// have changed) below
std::uint8_t* initial_buff_ptr = this->front_buffer_.data();
auto predicate =
[this, initial_buff_ptr]()
{
return this->front_buffer_.data() != initial_buff_ptr;
};
if (timeout_millis <= 0)
{
this->front_buffer_cv_.wait(lock, predicate);
}
else
{
if (!this->front_buffer_cv_.wait_for(
lock,
std::chrono::milliseconds(timeout_millis),
predicate))
{
LOG(WARNING) << "Timeout waiting for image buffer from camera";
return false;
}
}
}
catch (const std::system_error& ex)
{
LOG(WARNING) << "WaitForFrame: " << ex.what();
return false;
}
DLOG(INFO) << "Client fetching new image data";
buff->SetBytes(this->front_buffer_, copy_buff);
lock.unlock();
if (organize)
{
buff->Organize();
}
return true;
}
void
o3d3xx::FrameGrabber::ImageHandler(const boost::system::error_code& ec,
std::size_t bytes_transferred,
std::size_t bytes_read)
{
if (ec) { throw o3d3xx::error_t(ec.value()); }
bytes_read += bytes_transferred;
if (bytes_read != this->back_buffer_.size())
{
this->sock_.async_read_some(
boost::asio::buffer(&this->back_buffer_[bytes_read],
this->back_buffer_.size() - bytes_read),
std::bind(&o3d3xx::FrameGrabber::ImageHandler, this,
std::placeholders::_1, std::placeholders::_2, bytes_read));
return;
}
if (o3d3xx::verify_image_buffer(this->back_buffer_))
{
// Move data to front buffer in O(1)
this->front_buffer_mutex_.lock();
this->back_buffer_.swap(this->front_buffer_);
this->front_buffer_mutex_.unlock();
// notify waiting clients
this->front_buffer_cv_.notify_all();
}
else
{
LOG(WARNING) << "Bad image!";
}
this->ticket_buffer_.clear();
this->ticket_buffer_.resize(o3d3xx::TICKET_ID_SZ);
this->sock_.async_read_some(
boost::asio::buffer(this->ticket_buffer_.data(),
o3d3xx::TICKET_ID_SZ),
std::bind(&o3d3xx::FrameGrabber::TicketHandler, this,
std::placeholders::_1, std::placeholders::_2, 0));
}
void
o3d3xx::FrameGrabber::TicketHandler(const boost::system::error_code& ec,
std::size_t bytes_transferred,
std::size_t bytes_read)
{
if (ec) { throw o3d3xx::error_t(ec.value()); }
bytes_read += bytes_transferred;
if (bytes_read < o3d3xx::TICKET_ID_SZ)
{
bytes_read +=
boost::asio::read(
this->sock_,
boost::asio::buffer(&this->ticket_buffer_[bytes_read],
o3d3xx::TICKET_ID_SZ - bytes_read));
if (bytes_read != o3d3xx::TICKET_ID_SZ)
{
LOG(ERROR) << "Timeout reading ticket!";
throw o3d3xx::error_t(O3D3XX_IO_ERROR);
}
}
std::string ticket;
ticket.assign(this->ticket_buffer_.begin(),
this->ticket_buffer_.begin() + 4);
std::string payload_sz_str;
payload_sz_str.assign(this->ticket_buffer_.begin()+5,
this->ticket_buffer_.begin()+14);
int payload_sz = std::stoi(payload_sz_str);
int ticket_sz = o3d3xx::TICKET_ID_SZ;
if (ticket != o3d3xx::TICKET_image)
{
this->ticket_buffer_.resize(ticket_sz + payload_sz);
bytes_read +=
boost::asio::read(
this->sock_,
boost::asio::buffer(&this->ticket_buffer_[bytes_read],
(ticket_sz + payload_sz) - bytes_read));
if (bytes_read != (ticket_sz + payload_sz))
{
LOG(ERROR) << "Timeout reading whole response!";
LOG(ERROR) << "Got " << bytes_read << " bytes of "
<< ticket_sz << " bytes expected";
throw o3d3xx::error_t(O3D3XX_IO_ERROR);
}
}
std::string ticket_str;
ticket_str.assign(this->ticket_buffer_.begin(),
this->ticket_buffer_.end());
DLOG(INFO) << "Ticket Full: '" << ticket_str << "'";
if (ticket == o3d3xx::TICKET_image)
{
if (o3d3xx::verify_ticket_buffer(this->ticket_buffer_))
{
this->back_buffer_.resize(
o3d3xx::get_image_buffer_size(this->ticket_buffer_));
this->sock_.async_read_some(
boost::asio::buffer(this->back_buffer_.data(),
this->back_buffer_.size()),
std::bind(&o3d3xx::FrameGrabber::ImageHandler, this,
std::placeholders::_1, std::placeholders::_2, 0));
return;
}
else
{
LOG(ERROR) << "Bad image ticket: " << ticket_str;
throw(o3d3xx::error_t(O3D3XX_PCIC_BAD_REPLY));
}
}
else if ((ticket == o3d3xx::TICKET_c) ||
(ticket == o3d3xx::TICKET_t))
{
if (this->ticket_buffer_.at(20) != '*')
{
LOG(ERROR) << "Bad ticket: " << ticket_str;
if ((ticket == o3d3xx::TICKET_t) &&
(this->ticket_buffer_.at(20) == '!'))
{
LOG(WARNING) << "Are you software triggering in free run mode?";
}
else
{
throw(o3d3xx::error_t(O3D3XX_PCIC_BAD_REPLY));
}
}
this->ticket_buffer_.clear();
this->ticket_buffer_.resize(o3d3xx::TICKET_ID_SZ);
this->sock_.async_read_some(
boost::asio::buffer(this->ticket_buffer_.data(),
o3d3xx::TICKET_ID_SZ),
std::bind(&o3d3xx::FrameGrabber::TicketHandler, this,
std::placeholders::_1, std::placeholders::_2, 0));
return;
}
else
{
LOG(WARNING) << "Unexpected ticket: " << ticket;
LOG(WARNING) << "Ticket Full: '" << ticket_str << "'";
//throw(std::logic_error("Unexpected ticket type: " + ticket));
this->ticket_buffer_.clear();
this->ticket_buffer_.resize(o3d3xx::TICKET_ID_SZ);
this->sock_.async_read_some(
boost::asio::buffer(this->ticket_buffer_.data(),
o3d3xx::TICKET_ID_SZ),
std::bind(&o3d3xx::FrameGrabber::TicketHandler, this,
std::placeholders::_1, std::placeholders::_2, 0));
return;
}
}
void
o3d3xx::FrameGrabber::Run()
{
boost::asio::io_service::work work(this->io_service_);
auto result_schema_write_handler =
[&, this]
(const boost::system::error_code& ec, std::size_t bytes_transferred)
{
if (ec) { throw o3d3xx::error_t(ec.value()); }
this->ticket_buffer_.clear();
this->ticket_buffer_.resize(o3d3xx::TICKET_ID_SZ);
this->sock_.async_read_some(
boost::asio::buffer(this->ticket_buffer_.data(),
o3d3xx::TICKET_ID_SZ),
std::bind(&o3d3xx::FrameGrabber::TicketHandler,
this, std::placeholders::_1,
std::placeholders::_2, 0));
this->pcic_ready_.store(true);
};
//
// Establish TCP connection to sensor and
// set PCIC schema for this session
//
try
{
this->sock_.async_connect(
this->endpoint_,
[&, this] (const boost::system::error_code& ec)
{
if (ec) { throw o3d3xx::error_t(ec.value()); }
boost::asio::async_write(
this->sock_,
boost::asio::buffer(this->schema_buffer_.data(),
this->schema_buffer_.size()),
result_schema_write_handler);
});
this->io_service_.run();
}
catch (const std::exception& ex)
{
LOG(WARNING) << "Exception: " << ex.what();
}
LOG(INFO) << "Framegrabber thread done.";
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: unomodel.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2004-02-25 16:44:39 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "unomodel.hxx"
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#include <sfx2/docfac.hxx>
#include <sfx2/objsh.hxx>
#include <iderdll.hxx>
#include <basdoc.hxx>
using namespace ::vos;
using namespace ::rtl;
using namespace ::cppu;
using namespace ::std;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
SIDEModel::SIDEModel( SfxObjectShell *pObjSh )
: SfxBaseModel(pObjSh)
{
}
SIDEModel::~SIDEModel()
{
}
uno::Any SAL_CALL SIDEModel::queryInterface( const uno::Type& rType ) throw(uno::RuntimeException)
{
uno::Any aRet = ::cppu::queryInterface ( rType,
// OWeakObject interfaces
reinterpret_cast< XInterface* > ( this ),
static_cast< XWeak* > ( this ),
static_cast< XServiceInfo* > ( this ) );
if (!aRet.hasValue())
aRet = SfxBaseModel::queryInterface ( rType );
return aRet;
}
void SAL_CALL SIDEModel::acquire() throw()
{
::vos::OGuard aGuard(Application::GetSolarMutex());
OWeakObject::acquire();
}
void SAL_CALL SIDEModel::release() throw()
{
::vos::OGuard aGuard(Application::GetSolarMutex());
OWeakObject::release();
}
uno::Sequence< uno::Type > SAL_CALL SIDEModel::getTypes( ) throw(uno::RuntimeException)
{
uno::Sequence< uno::Type > aTypes = SfxBaseModel::getTypes();
sal_Int32 nLen = aTypes.getLength();
aTypes.realloc(nLen + 1);
uno::Type* pTypes = aTypes.getArray();
pTypes[nLen++] = ::getCppuType((Reference<XServiceInfo>*)0);
return aTypes;
}
OUString SIDEModel::getImplementationName(void) throw( uno::RuntimeException )
{
return getImplementationName_Static();
}
::rtl::OUString SIDEModel::getImplementationName_Static()
{
return rtl::OUString::createFromAscii("com.sun.star.comp.basic.BasicIDE");
}
sal_Bool SIDEModel::supportsService(const OUString& rServiceName) throw( uno::RuntimeException )
{
return rServiceName == ::rtl::OUString::createFromAscii("com.sun.star.script.BasicIDE");
}
uno::Sequence< OUString > SIDEModel::getSupportedServiceNames(void) throw( uno::RuntimeException )
{
return getSupportedServiceNames_Static();
}
uno::Sequence< OUString > SIDEModel::getSupportedServiceNames_Static(void)
{
uno::Sequence< OUString > aRet(1);
OUString* pArray = aRet.getArray();
pArray[0] = ::rtl::OUString::createFromAscii("com.sun.star.script.BasicIDE");
return aRet;
}
uno::Reference< uno::XInterface > SAL_CALL SIDEModel_createInstance(
const uno::Reference< lang::XMultiServiceFactory > & rSMgr ) throw( uno::Exception )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
BasicIDEDLL::Init();
SfxObjectShell* pShell = new BasicDocShell();
return uno::Reference< uno::XInterface >( pShell->GetModel() );
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.206); FILE MERGED 2005/09/05 13:55:50 rt 1.4.206.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: unomodel.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-07 20:12:34 $
*
* 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 "unomodel.hxx"
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#include <sfx2/docfac.hxx>
#include <sfx2/objsh.hxx>
#include <iderdll.hxx>
#include <basdoc.hxx>
using namespace ::vos;
using namespace ::rtl;
using namespace ::cppu;
using namespace ::std;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
SIDEModel::SIDEModel( SfxObjectShell *pObjSh )
: SfxBaseModel(pObjSh)
{
}
SIDEModel::~SIDEModel()
{
}
uno::Any SAL_CALL SIDEModel::queryInterface( const uno::Type& rType ) throw(uno::RuntimeException)
{
uno::Any aRet = ::cppu::queryInterface ( rType,
// OWeakObject interfaces
reinterpret_cast< XInterface* > ( this ),
static_cast< XWeak* > ( this ),
static_cast< XServiceInfo* > ( this ) );
if (!aRet.hasValue())
aRet = SfxBaseModel::queryInterface ( rType );
return aRet;
}
void SAL_CALL SIDEModel::acquire() throw()
{
::vos::OGuard aGuard(Application::GetSolarMutex());
OWeakObject::acquire();
}
void SAL_CALL SIDEModel::release() throw()
{
::vos::OGuard aGuard(Application::GetSolarMutex());
OWeakObject::release();
}
uno::Sequence< uno::Type > SAL_CALL SIDEModel::getTypes( ) throw(uno::RuntimeException)
{
uno::Sequence< uno::Type > aTypes = SfxBaseModel::getTypes();
sal_Int32 nLen = aTypes.getLength();
aTypes.realloc(nLen + 1);
uno::Type* pTypes = aTypes.getArray();
pTypes[nLen++] = ::getCppuType((Reference<XServiceInfo>*)0);
return aTypes;
}
OUString SIDEModel::getImplementationName(void) throw( uno::RuntimeException )
{
return getImplementationName_Static();
}
::rtl::OUString SIDEModel::getImplementationName_Static()
{
return rtl::OUString::createFromAscii("com.sun.star.comp.basic.BasicIDE");
}
sal_Bool SIDEModel::supportsService(const OUString& rServiceName) throw( uno::RuntimeException )
{
return rServiceName == ::rtl::OUString::createFromAscii("com.sun.star.script.BasicIDE");
}
uno::Sequence< OUString > SIDEModel::getSupportedServiceNames(void) throw( uno::RuntimeException )
{
return getSupportedServiceNames_Static();
}
uno::Sequence< OUString > SIDEModel::getSupportedServiceNames_Static(void)
{
uno::Sequence< OUString > aRet(1);
OUString* pArray = aRet.getArray();
pArray[0] = ::rtl::OUString::createFromAscii("com.sun.star.script.BasicIDE");
return aRet;
}
uno::Reference< uno::XInterface > SAL_CALL SIDEModel_createInstance(
const uno::Reference< lang::XMultiServiceFactory > & rSMgr ) throw( uno::Exception )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
BasicIDEDLL::Init();
SfxObjectShell* pShell = new BasicDocShell();
return uno::Reference< uno::XInterface >( pShell->GetModel() );
}
<|endoftext|>
|
<commit_before><commit_msg>Removes move in types.hpp which could prevent RVO<commit_after><|endoftext|>
|
<commit_before>//
// Created by dar on 1/25/16.
//
#include <render/block/ChunkRender.h>
#include <render/entity/PlayerRender.h>
#include <render/entity/SimpleShapeRender.h>
#include "../RenderManager.h"
#include "GameRender.h"
#include "../../window/Game.h"
#include "../../core/Core.h"
#include <core/map/entity/EntityBullet.h>
#include <core/map/entity/EntityFather.h>
#include <core/map/entity/EntityMachinery.h>
#include <core/map/entity/EntityDoor.h>
#include <core/map/entity/EntityFurniture.h>
#include <core/map/entity/EntityTable.h>
#include <core/map/entity/EntityGlassDebris.h>
#include <core/map/entity/EntityCouch.h>
#include <core/map/block/SimpleBlock.h>
#include <logging.h>
#include <render/entity/EntityMachineryRender.h>
#include <render/entity/EntityStaticRender.h>
#include <render/entity/EntityWideRender.h>
GameRender::GameRender() : WindowRender() { }
void GameRender::init(RenderContext *const renderContext) {
this->initRenders();
fbo.init(3, renderContext->getWindowWidth(), renderContext->getWindowHeight(), new float[4]{0.9, 0.9, 0.9, 1.0}, "fboshader");
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
this->resize(renderContext);
}
void GameRender::resize(RenderContext *const renderContext) {
viewMatrix = glm::lookAt(glm::vec3(0, 0, 0.0f), glm::vec3(0, 0, 1.0f), glm::vec3(0.0f, 1.0f, 0.0f));
this->projectionMatrix = glm::ortho(0.0f, float(renderContext->getWindowWidth()), 0.0f, float(renderContext->getWindowHeight()));
this->fbo.resize(renderContext->getWindowWidth(), renderContext->getWindowHeight());
}
void GameRender::render(Window *window, RenderContext *const renderContext) {
Game *game = ((Game *) window);
Core *core = game->getCore();
unsigned int windowWidth = renderContext->getWindowWidth();
unsigned int windowHeight = renderContext->getWindowHeight();
double scale = core->getBlockSize() * core->getGeneralScale();
double camX = core->getCamX() * (core->getBlockSize() * core->getGeneralScale());
double camY = core->getCamY() * (core->getBlockSize() * core->getGeneralScale());
fbo.bind();
glClearColor(0.9, 0.9, 0.9, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
scale *= Chunk::size;
for (Chunk *const chunk : core->getMap()->getChunks()) {
getChunkRender()->render(chunk, projectionMatrix, glm::translate(viewMatrix, glm::vec3(
-(signed) windowWidth / 2.0f - camX,
(signed) windowHeight / 2.0f - camY, 0.0f
)), core->getBlockSize() * core->getGeneralScale());
chunk->setRedrawn();
}
scale /= Chunk::size;
int entitiesNum = 0;
for (int i = core->getMap()->getEntities().size() - 1; i >= 0; i--) {
Entity *entity = core->getMap()->getEntities().at(i);
double maxSize = entity->getWidth() > entity->getHeight() ? entity->getWidth() : entity->getHeight();
if (entity->getX() * scale > -(signed) windowWidth / 2.0f - camX &&
(entity->getX() - 1 - maxSize) * scale < -(signed) windowWidth / 2.0f - camX + (signed) windowWidth &&
entity->getY() * scale > -(signed) windowHeight / 2.0f - camY &&
(entity->getY() - 1 - maxSize) * scale < -(signed) windowHeight / 2.0f - camY + (signed) windowHeight) {
getEntityRender(entity)->render(entity, projectionMatrix, glm::translate(viewMatrix, glm::vec3(
-(signed) windowWidth / 2.0f - camX,
(signed) windowHeight / 2.0f - camY,
0.0f)), core->getBlockSize() * core->getGeneralScale());
if (IEntityLighted *elighted = dynamic_cast<IEntityLighted *>(entity)) {
fbo.getShaderProgram()->useProgram();
if (entitiesNum < fbo.MAX_LIGHT_SRCS) {
char *uniform_name_formatted = new char[16 + (int) log((double) fbo.MAX_LIGHT_SRCS)];
sprintf(uniform_name_formatted, "lightPoints[%d]", entitiesNum);
fbo.getShaderProgram()->setUniform(uniform_name_formatted, glm::vec2(
camX + (entity->getX() - 1 + entity->getWidth() / 2) * scale + (double) windowWidth / 2,
-camY - (entity->getY() - 1 + entity->getHeight() / 2) * scale + (double) windowHeight / 2));
entitiesNum++;
}
}
}
}
#ifndef EDITOR
//TODO
static int grayout[][4] = {{20, 3, 4, 6},
{21, 9, 1, 1},
{25, 3, 5, 3},
{30, 3, 1, 1},
{31, 3, 4, 3},
{35, 4, 1, 1},
{34, 6, 1, 1},
{31, 7, 7, 11}};
/*for (int i = 0; i < 8; i++) {
this->voidRender->render(grayout[i][0], grayout[i][1], grayout[i][2], grayout[i][3], projectionMatrix, glm::translate(viewMatrix, glm::vec3(
-(signed) windowWidth / 2.0f - camX,
(signed) windowHeight / 2.0f - camY,
0.0f)), core->getBlockSize() * core->getGeneralScale());
}*/
#endif //EDITOR
fbo.unbind();
fbo.getShaderProgram()->useProgram();
fbo.getShaderProgram()->setUniform("lightPointsNum", entitiesNum);
fbo.getShaderProgram()->setUniform("scale", (float) (core->getBlockSize() * core->getGeneralScale()));
fbo.render(0);
#if !defined(EDITOR) && !defined(DEBUG)
float voidAlpha = 1.0f;
if (game->getCore()->getMap()->getWorldTime() > 21.25f) {
voidAlpha = std::max(0.0f, 22.25f - (float) game->getCore()->getMap()->getWorldTime());
}
this->voidRender->render(0, 0, windowWidth + 1, windowHeight + 1, projectionMatrix, glm::translate(viewMatrix, glm::vec3(
0,
(int) ((signed) windowHeight),
0.0f)), 1.0f, 0.7f, 0.7f, 0.7f, voidAlpha);
#endif
for (GuiElement *guiElement : game->getGuiElements()) {
renderContext->getGuiElementRender(guiElement)->render(guiElement, projectionMatrix, glm::translate(viewMatrix, glm::vec3(
0,
(int) ((signed) windowHeight),
0.0f)), core->getGeneralScale());
}
}
ChunkRender *GameRender::getChunkRender() const {
return this->chunkRender;
}
EntityRender *GameRender::getEntityRender(const Entity *const entity) {
EntityRender *r = entityRenders[typeid(*entity).name()];
if (r == nullptr) {
if (const EntityFurniture *const f = dynamic_cast<const EntityFurniture *const>(entity)) {
return entityRenders[typeid(EntityFurniture).name()];
} else {
return nullptr;
}
}
return r;
}
void GameRender::cleanRenders() {
delete this->voidRender;
delete this->chunkRender;
for (std::pair<const char *, EntityRender *> renderPair : entityRenders) {
delete renderPair.second;
}
entityRenders.clear();
}
void GameRender::initRenders() {
this->voidRender = new VoidRender();
this->chunkRender = new ChunkRender();
entityRenders.insert(std::make_pair(typeid(EntityPlayer).name(), new PlayerRender()));
EntityMachineryRender *machineryRender = new EntityMachineryRender();
entityRenders.insert(std::make_pair(typeid(EntityTruck).name(), machineryRender));
entityRenders.insert(std::make_pair(typeid(EntityBulldozer).name(), machineryRender));
entityRenders.insert(std::make_pair(typeid(EntityHoover).name(), machineryRender));
//entityRenders.insert(std::make_pair(typeid(EntityBullet).name(), new DefaultEntityRender("bullet", "shader")));
EntityWideRender *wideRender = new EntityWideRender();
entityRenders.insert(std::make_pair(typeid(EntityTable).name(), wideRender));
entityRenders.insert(std::make_pair(typeid(EntityCoffeeTable).name(), wideRender));
entityRenders.insert(std::make_pair(typeid(EntityCouch).name(), wideRender));
EntityStaticRender *staticRender = new EntityStaticRender();
entityRenders.insert(std::make_pair(typeid(EntityFurniture).name(), staticRender));
entityRenders.insert(std::make_pair(typeid(EntityGlassDebris).name(), staticRender));
entityRenders.insert(std::make_pair(typeid(SimpleShape).name(), new SimpleShapeRender()));
entityRenders.insert(std::make_pair(typeid(EntityFather).name(), new DefaultEntityRender("parents", "shader")));
}
GameRender::~GameRender() {
cleanRenders();
}
<commit_msg>Reenabled grayouts<commit_after>//
// Created by dar on 1/25/16.
//
#include <render/block/ChunkRender.h>
#include <render/entity/PlayerRender.h>
#include <render/entity/SimpleShapeRender.h>
#include "../RenderManager.h"
#include "GameRender.h"
#include "../../window/Game.h"
#include "../../core/Core.h"
#include <core/map/entity/EntityBullet.h>
#include <core/map/entity/EntityFather.h>
#include <core/map/entity/EntityMachinery.h>
#include <core/map/entity/EntityDoor.h>
#include <core/map/entity/EntityFurniture.h>
#include <core/map/entity/EntityTable.h>
#include <core/map/entity/EntityGlassDebris.h>
#include <core/map/entity/EntityCouch.h>
#include <core/map/block/SimpleBlock.h>
#include <logging.h>
#include <render/entity/EntityMachineryRender.h>
#include <render/entity/EntityStaticRender.h>
#include <render/entity/EntityWideRender.h>
GameRender::GameRender() : WindowRender() { }
void GameRender::init(RenderContext *const renderContext) {
this->initRenders();
fbo.init(3, renderContext->getWindowWidth(), renderContext->getWindowHeight(), new float[4]{0.9, 0.9, 0.9, 1.0}, "fboshader");
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
this->resize(renderContext);
}
void GameRender::resize(RenderContext *const renderContext) {
viewMatrix = glm::lookAt(glm::vec3(0, 0, 0.0f), glm::vec3(0, 0, 1.0f), glm::vec3(0.0f, 1.0f, 0.0f));
this->projectionMatrix = glm::ortho(0.0f, float(renderContext->getWindowWidth()), 0.0f, float(renderContext->getWindowHeight()));
this->fbo.resize(renderContext->getWindowWidth(), renderContext->getWindowHeight());
}
void GameRender::render(Window *window, RenderContext *const renderContext) {
Game *game = ((Game *) window);
Core *core = game->getCore();
unsigned int windowWidth = renderContext->getWindowWidth();
unsigned int windowHeight = renderContext->getWindowHeight();
double scale = core->getBlockSize() * core->getGeneralScale();
double camX = core->getCamX() * (core->getBlockSize() * core->getGeneralScale());
double camY = core->getCamY() * (core->getBlockSize() * core->getGeneralScale());
fbo.bind();
glClearColor(0.9, 0.9, 0.9, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
scale *= Chunk::size;
for (Chunk *const chunk : core->getMap()->getChunks()) {
getChunkRender()->render(chunk, projectionMatrix, glm::translate(viewMatrix, glm::vec3(
-(signed) windowWidth / 2.0f - camX,
(signed) windowHeight / 2.0f - camY, 0.0f
)), core->getBlockSize() * core->getGeneralScale());
chunk->setRedrawn();
}
scale /= Chunk::size;
int entitiesNum = 0;
for (int i = core->getMap()->getEntities().size() - 1; i >= 0; i--) {
Entity *entity = core->getMap()->getEntities().at(i);
double maxSize = entity->getWidth() > entity->getHeight() ? entity->getWidth() : entity->getHeight();
if (entity->getX() * scale > -(signed) windowWidth / 2.0f - camX &&
(entity->getX() - 1 - maxSize) * scale < -(signed) windowWidth / 2.0f - camX + (signed) windowWidth &&
entity->getY() * scale > -(signed) windowHeight / 2.0f - camY &&
(entity->getY() - 1 - maxSize) * scale < -(signed) windowHeight / 2.0f - camY + (signed) windowHeight) {
getEntityRender(entity)->render(entity, projectionMatrix, glm::translate(viewMatrix, glm::vec3(
-(signed) windowWidth / 2.0f - camX,
(signed) windowHeight / 2.0f - camY,
0.0f)), core->getBlockSize() * core->getGeneralScale());
if (IEntityLighted *elighted = dynamic_cast<IEntityLighted *>(entity)) {
fbo.getShaderProgram()->useProgram();
if (entitiesNum < fbo.MAX_LIGHT_SRCS) {
char *uniform_name_formatted = new char[16 + (int) log((double) fbo.MAX_LIGHT_SRCS)];
sprintf(uniform_name_formatted, "lightPoints[%d]", entitiesNum);
fbo.getShaderProgram()->setUniform(uniform_name_formatted, glm::vec2(
camX + (entity->getX() - 1 + entity->getWidth() / 2) * scale + (double) windowWidth / 2,
-camY - (entity->getY() - 1 + entity->getHeight() / 2) * scale + (double) windowHeight / 2));
entitiesNum++;
}
}
}
}
#ifndef EDITOR
//TODO
static int grayout[][4] = {{20, 3, 4, 6},
{21, 9, 1, 1},
{25, 3, 5, 3},
{30, 3, 1, 1},
{31, 3, 4, 3},
{35, 4, 1, 1},
{34, 6, 1, 1},
{31, 7, 7, 11}};
for (int i = 0; i < 8; i++) {
this->voidRender->render(grayout[i][0], grayout[i][1], grayout[i][2], grayout[i][3], projectionMatrix, glm::translate(viewMatrix, glm::vec3(
-(signed) windowWidth / 2.0f - camX,
(signed) windowHeight / 2.0f - camY,
0.0f)), core->getBlockSize() * core->getGeneralScale());
}
#endif //EDITOR
fbo.unbind();
fbo.getShaderProgram()->useProgram();
fbo.getShaderProgram()->setUniform("lightPointsNum", entitiesNum);
fbo.getShaderProgram()->setUniform("scale", (float) (core->getBlockSize() * core->getGeneralScale()));
fbo.render(0);
#if !defined(EDITOR) && !defined(DEBUG)
float voidAlpha = 1.0f;
if (game->getCore()->getMap()->getWorldTime() > 21.25f) {
voidAlpha = std::max(0.0f, 22.25f - (float) game->getCore()->getMap()->getWorldTime());
}
this->voidRender->render(0, 0, windowWidth + 1, windowHeight + 1, projectionMatrix, glm::translate(viewMatrix, glm::vec3(
0,
(int) ((signed) windowHeight),
0.0f)), 1.0f, 0.7f, 0.7f, 0.7f, voidAlpha);
#endif
for (GuiElement *guiElement : game->getGuiElements()) {
renderContext->getGuiElementRender(guiElement)->render(guiElement, projectionMatrix, glm::translate(viewMatrix, glm::vec3(
0,
(int) ((signed) windowHeight),
0.0f)), core->getGeneralScale());
}
}
ChunkRender *GameRender::getChunkRender() const {
return this->chunkRender;
}
EntityRender *GameRender::getEntityRender(const Entity *const entity) {
EntityRender *r = entityRenders[typeid(*entity).name()];
if (r == nullptr) {
if (const EntityFurniture *const f = dynamic_cast<const EntityFurniture *const>(entity)) {
return entityRenders[typeid(EntityFurniture).name()];
} else {
return nullptr;
}
}
return r;
}
void GameRender::cleanRenders() {
delete this->voidRender;
delete this->chunkRender;
for (std::pair<const char *, EntityRender *> renderPair : entityRenders) {
delete renderPair.second;
}
entityRenders.clear();
}
void GameRender::initRenders() {
this->voidRender = new VoidRender();
this->chunkRender = new ChunkRender();
entityRenders.insert(std::make_pair(typeid(EntityPlayer).name(), new PlayerRender()));
EntityMachineryRender *machineryRender = new EntityMachineryRender();
entityRenders.insert(std::make_pair(typeid(EntityTruck).name(), machineryRender));
entityRenders.insert(std::make_pair(typeid(EntityBulldozer).name(), machineryRender));
entityRenders.insert(std::make_pair(typeid(EntityHoover).name(), machineryRender));
//entityRenders.insert(std::make_pair(typeid(EntityBullet).name(), new DefaultEntityRender("bullet", "shader")));
EntityWideRender *wideRender = new EntityWideRender();
entityRenders.insert(std::make_pair(typeid(EntityTable).name(), wideRender));
entityRenders.insert(std::make_pair(typeid(EntityCoffeeTable).name(), wideRender));
entityRenders.insert(std::make_pair(typeid(EntityCouch).name(), wideRender));
EntityStaticRender *staticRender = new EntityStaticRender();
entityRenders.insert(std::make_pair(typeid(EntityFurniture).name(), staticRender));
entityRenders.insert(std::make_pair(typeid(EntityGlassDebris).name(), staticRender));
entityRenders.insert(std::make_pair(typeid(SimpleShape).name(), new SimpleShapeRender()));
entityRenders.insert(std::make_pair(typeid(EntityFather).name(), new DefaultEntityRender("parents", "shader")));
}
GameRender::~GameRender() {
cleanRenders();
}
<|endoftext|>
|
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <fcntl.h>
#include <cerrno>
#include <unistd.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/resource.h>
#include <sys/file.h>
#include <vespa/defaults.h>
#include <vespa/log/llparser.h>
#include "llreader.h"
#include <vespa/log/log.h>
#include <chrono>
LOG_SETUP("runserver");
// XXX should close all file descriptors,
// XXX but that makes logging go haywire
static volatile sig_atomic_t gotstopsig = 0;
static volatile sig_atomic_t lastsig = 0;
static volatile sig_atomic_t unhandledsig = 0;
extern "C" {
void termsig(int sig) {
lastsig = sig;
gotstopsig = 1;
unhandledsig = 1;
}
}
namespace {
using namespace std::chrono;
time_t steady_time() {
return duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
}
}
class PidFile
{
private:
char *_pidfile;
int _fd;
PidFile(const PidFile&);
PidFile& operator= (const PidFile&);
public:
PidFile(const char *pidfile) : _pidfile(strdup(pidfile)), _fd(-1) {}
~PidFile() { free(_pidfile); if (_fd >= 0) close(_fd); }
int readPid();
void writePid();
bool writeOpen();
bool anotherRunning();
bool canStealLock();
void cleanUp();
};
void
PidFile::cleanUp()
{
if (!anotherRunning()) remove(_pidfile);
if (_fd >= 0) close(_fd);
_fd = -1;
}
bool
PidFile::writeOpen()
{
if (_fd >= 0) close(_fd);
int flags = O_CREAT | O_WRONLY | O_NONBLOCK;
_fd = open(_pidfile, flags, 0644);
if (_fd < 0) {
fprintf(stderr, "could not create pidfile %s: %s\n", _pidfile,
strerror(errno));
return false;
}
if (flock(_fd, LOCK_EX | LOCK_NB) != 0) {
fprintf(stderr, "could not lock pidfile %s: %s\n", _pidfile,
strerror(errno));
close(_fd);
_fd = -1;
return false;
}
fcntl(_fd, F_SETFD, FD_CLOEXEC);
return true;
}
void
PidFile::writePid()
{
if (_fd < 0) abort();
int didtruncate = ftruncate(_fd, (off_t)0);
if (didtruncate != 0) {
fprintf(stderr, "could not truncate pid file %s: %s\n",
_pidfile, strerror(errno));
exit(1);
}
char buf[100];
sprintf(buf, "%d\n", getpid());
int l = strlen(buf);
ssize_t didw = write(_fd, buf, l);
if (didw != l) {
fprintf(stderr, "could not write pid to %s: %s\n",
_pidfile, strerror(errno));
exit(1);
}
LOG(debug, "wrote '%s' to %s (fd %d)", buf, _pidfile, _fd);
}
int
PidFile::readPid()
{
FILE *pf = fopen(_pidfile, "r");
if (pf == NULL) return 0;
char buf[100];
strcpy(buf, "0");
char *fgetsres = fgets(buf, 100, pf);
fclose(pf);
return ((fgetsres != nullptr) ? atoi(buf) : 0);
}
bool
PidFile::anotherRunning()
{
int pid = readPid();
if (pid < 1 || pid == getpid()) {
// no valid pid, or my own pid
return false;
}
if (canStealLock()) {
return false;
}
return (kill(pid, 0) == 0 || errno == EPERM);
}
bool
PidFile::canStealLock()
{
int flags = O_WRONLY | O_NONBLOCK;
int desc = open(_pidfile, flags, 0644);
if (desc < 0) {
return false;
}
if (flock(desc, LOCK_EX | LOCK_NB) != 0) {
close(desc);
return false;
}
flock(desc, LOCK_UN | LOCK_NB);
close(desc);
return true;
}
using namespace ns_log;
int loop(const char *svc, char * const * run)
{
int pstdout[2];
int pstderr[2];
if (pipe(pstdout) < 0 || pipe(pstderr) < 0) {
LOG(error, "pipe: %s", strerror(errno));
exit(1);
}
LOG(debug, "stdout pipe %d <- %d; stderr pipe %d <- %d",
pstdout[0], pstdout[1],
pstderr[0], pstderr[1]);
int high = 1 + pstdout[0] + pstderr[0];
pid_t child = fork();
if (child == 0) {
// I am the child process
dup2(pstdout[1], 1);
dup2(pstderr[1], 2);
close(pstdout[0]);
close(pstderr[0]);
close(pstdout[1]);
close(pstderr[1]);
execvp(run[0], run);
LOG(error, "exec %s: %s", run[0], strerror(errno));
exit(1);
}
if (child < 0) {
LOG(error, "fork(): %s", strerror(errno));
exit(1);
}
// I am the parent process
LOG(debug, "started %s (pid %d)", run[0], (int)child);
std::string torun = run[0];
for (char * const *arg = (run + 1); *arg != NULL; ++arg) {
torun += " ";
torun += *arg;
}
{
torun += " (pid ";
char buf[20];
sprintf(buf, "%d", (int)child);
torun += buf;
torun += ")";
}
EV_STARTING(torun.c_str());
close(pstdout[1]);
close(pstderr[1]);
LLParser outvia;
LLParser errvia;
outvia.setDefaultLevel(Logger::info);
errvia.setDefaultLevel(Logger::warning);
outvia.setService(svc);
errvia.setService(svc);
outvia.setComponent("stdout");
errvia.setComponent("stderr");
outvia.setPid(child);
errvia.setPid(child);
InputBuf outReader(pstdout[0]);
InputBuf errReader(pstderr[0]);
bool outeof = false;
bool erreof = false;
int wstat = 0;
while (child || !outeof || !erreof) {
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 100000; // == 100 ms == 1/10 s
fd_set pipes;
FD_ZERO(&pipes);
if (!outeof) FD_SET(pstdout[0], &pipes);
if (!erreof) FD_SET(pstderr[0], &pipes);
int n = select(high, &pipes, NULL, NULL, &timeout);
if (n > 0) {
if (FD_ISSET(pstdout[0], &pipes)) {
LOG(debug, "out reader has input");
if (outReader.blockRead()) {
while (outReader.hasInput()) {
LOG(debug, "process out reader input");
outReader.doInput(outvia);
}
} else {
LOG(debug, "eof on stdout");
outeof = true; // EOF on stdout
close(pstdout[0]);
}
}
if (FD_ISSET(pstderr[0], &pipes)) {
LOG(debug, "err reader has input");
if (errReader.blockRead()) {
while (errReader.hasInput()) {
LOG(debug, "process err reader input");
errReader.doInput(errvia);
}
} else {
LOG(debug, "eof on stderr");
erreof = true; // EOF on stderr
close(pstderr[0]);
}
}
}
if (child != 0) {
int cpid = waitpid(child, &wstat, WNOHANG);
if (cpid == child) {
if (WIFSTOPPED(wstat)) {
LOG(info, "child %d stopped, waiting for it to continue",
cpid);
} else if (WIFEXITED(wstat)) {
// child terminated
LOG(debug, "child %d exit status: %d", cpid,
(int)WEXITSTATUS(wstat));
EV_STOPPED(torun.c_str(), (int)child, (int)WEXITSTATUS(wstat));
child = 0;
} else if (WIFSIGNALED(wstat)) {
if (WTERMSIG(wstat) != lastsig) {
LOG(warning, "child died from signal: %d", WTERMSIG(wstat));
if (WCOREDUMP(wstat)) {
LOG(info, "child %d dumped core", cpid);
}
}
child = 0;
} else {
LOG(error, "unexpected status %d from waidpit", wstat);
abort();
}
} else if (cpid < 0) {
LOG(error, "waitpid: %s", strerror(errno));
abort();
} else if (cpid != 0) {
LOG(warning, "unexpected status %d for pid %d",
wstat, cpid);
abort();
}
}
if (unhandledsig && child != 0) {
LOG(debug, "got signal %d, sending to pid %d",
(int)lastsig, (int)child);
char why[256];
sprintf(why, "got signal %d", (int)lastsig);
EV_STOPPING(torun.c_str(), why);
kill(child, lastsig);
unhandledsig = 0;
}
}
if (WIFSIGNALED(wstat))
return WTERMSIG(wstat);
return WEXITSTATUS(wstat);
}
void usage(char *prog, int es)
{
fprintf(stderr, "Usage: %s\n"
" [-s service] [-r restartinterval] [-p pidfile]"
" program [args ...]\n"
"or: [-p pidfile] [-k killcmd] -S\n", prog);
exit(es);
}
int main(int argc, char *argv[])
{
bool doStop = false;
int restart = 0;
const char *service = "runserver";
const char *pidfile = "vespa-runserver.pid"; // XXX bad default?
const char *killcmd = NULL;
signal(SIGQUIT, SIG_IGN);
int ch;
while ((ch = getopt(argc, argv, "k:s:r:p:Sh")) != -1) {
switch (ch) {
case 's':
service = optarg;
break;
case 'r':
restart = atoi(optarg);
break;
case 'p':
pidfile = optarg;
break;
case 'S':
doStop = true;
break;
case 'k':
killcmd = optarg;
break;
default:
usage(argv[0], ch != 'h');
}
}
const char *envROOT = getenv("ROOT");
if (envROOT == NULL || envROOT[0] == '\0') {
envROOT = vespa::Defaults::vespaHome();
setenv("ROOT", envROOT, 1);
}
if (chdir(envROOT) != 0) {
fprintf(stderr, "Cannot chdir to %s: %s\n", envROOT, strerror(errno));
exit(1);
}
PidFile mypf(pidfile);
if (doStop) {
if (mypf.anotherRunning()) {
int pid = mypf.readPid();
if (killcmd != NULL) {
fprintf(stdout, "%s was running with pid %d, running '%s' to stop it\n",
service, pid, killcmd);
if (system(killcmd) != 0) {
fprintf(stderr, "WARNING: stop command '%s' had some problem\n", killcmd);
}
} else {
fprintf(stdout, "%s was running with pid %d, sending SIGTERM\n",
service, pid);
if (killpg(pid, SIGTERM) != 0) {
fprintf(stderr, "could not signal %d: %s\n", pid,
strerror(errno));
exit(1);
}
}
fprintf(stdout, "Waiting for exit (up to 60 seconds)\n");
for (int cnt(0); cnt < 1800; cnt++) {
usleep(100000); // wait 0.1 seconds
if ((cnt > 300) && (cnt % 100 == 0)) {
killpg(pid, SIGTERM);
}
if (killpg(pid, 0) == 0) {
if (cnt%10 == 0) {
fprintf(stdout, ".");
fflush(stdout);
}
} else {
fprintf(stdout, "DONE\n");
break;
}
if (cnt == 900) {
printf("\ngiving up, sending KILL signal\n");
killpg(pid, SIGKILL);
}
}
} else {
fprintf(stdout, "%s not running according to %s\n",
service, pidfile);
}
mypf.cleanUp();
exit(0);
}
if (optind >= argc || killcmd != NULL) {
usage(argv[0], 1);
}
if (mypf.anotherRunning()) {
fprintf(stderr, "runserver already running with pid %d\n",
mypf.readPid());
exit(0);
}
if (!mypf.writeOpen()) {
perror(pidfile);
return 1;
}
pid_t rsp = fork();
if (rsp == 0) {
close(0);
if (open("/dev/null", O_RDONLY) != 0) {
perror("open /dev/null for reading failed");
exit(1);
}
close(1);
if (open("/dev/null", O_WRONLY) != 1) {
perror("open /dev/null for writing failed");
exit(1);
}
dup2(1, 2);
if (setsid() < 0) {
perror("setsid");
exit(1);
}
struct sigaction act;
struct sigaction oact;
memset(&act, 0, sizeof(act));
act.sa_handler = termsig;
sigaction(SIGINT, &act, &oact);
sigaction(SIGTERM, &act, &oact);
int stat = 0;
try {
mypf.writePid();
do {
time_t laststart = steady_time();
stat = loop(service, argv+optind);
if (restart > 0 && !gotstopsig) {
int wt = restart + laststart - steady_time();
if (wt < 0) wt = 0;
LOG(info, "will restart in %d seconds", wt);
}
while (!gotstopsig && steady_time() - laststart < restart) {
sleep(1);
}
} while (!gotstopsig && restart > 0);
} catch (MsgException& ex) {
LOG(error, "exception: '%s'", ex.what());
exit(1);
}
if (restart > 0) {
LOG(debug, "final exit status: %d", stat);
}
mypf.cleanUp();
exit(stat);
}
if (rsp < 0) {
perror("fork");
return 1;
}
printf("runserver(%s) running with pid: %d\n", service, rsp);
return 0;
}
<commit_msg>Add include of header file for signal handling.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <fcntl.h>
#include <cerrno>
#include <unistd.h>
#include <csignal>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/resource.h>
#include <sys/file.h>
#include <vespa/defaults.h>
#include <vespa/log/llparser.h>
#include "llreader.h"
#include <vespa/log/log.h>
#include <chrono>
LOG_SETUP("runserver");
// XXX should close all file descriptors,
// XXX but that makes logging go haywire
static volatile sig_atomic_t gotstopsig = 0;
static volatile sig_atomic_t lastsig = 0;
static volatile sig_atomic_t unhandledsig = 0;
extern "C" {
void termsig(int sig) {
lastsig = sig;
gotstopsig = 1;
unhandledsig = 1;
}
}
namespace {
using namespace std::chrono;
time_t steady_time() {
return duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
}
}
class PidFile
{
private:
char *_pidfile;
int _fd;
PidFile(const PidFile&);
PidFile& operator= (const PidFile&);
public:
PidFile(const char *pidfile) : _pidfile(strdup(pidfile)), _fd(-1) {}
~PidFile() { free(_pidfile); if (_fd >= 0) close(_fd); }
int readPid();
void writePid();
bool writeOpen();
bool anotherRunning();
bool canStealLock();
void cleanUp();
};
void
PidFile::cleanUp()
{
if (!anotherRunning()) remove(_pidfile);
if (_fd >= 0) close(_fd);
_fd = -1;
}
bool
PidFile::writeOpen()
{
if (_fd >= 0) close(_fd);
int flags = O_CREAT | O_WRONLY | O_NONBLOCK;
_fd = open(_pidfile, flags, 0644);
if (_fd < 0) {
fprintf(stderr, "could not create pidfile %s: %s\n", _pidfile,
strerror(errno));
return false;
}
if (flock(_fd, LOCK_EX | LOCK_NB) != 0) {
fprintf(stderr, "could not lock pidfile %s: %s\n", _pidfile,
strerror(errno));
close(_fd);
_fd = -1;
return false;
}
fcntl(_fd, F_SETFD, FD_CLOEXEC);
return true;
}
void
PidFile::writePid()
{
if (_fd < 0) abort();
int didtruncate = ftruncate(_fd, (off_t)0);
if (didtruncate != 0) {
fprintf(stderr, "could not truncate pid file %s: %s\n",
_pidfile, strerror(errno));
exit(1);
}
char buf[100];
sprintf(buf, "%d\n", getpid());
int l = strlen(buf);
ssize_t didw = write(_fd, buf, l);
if (didw != l) {
fprintf(stderr, "could not write pid to %s: %s\n",
_pidfile, strerror(errno));
exit(1);
}
LOG(debug, "wrote '%s' to %s (fd %d)", buf, _pidfile, _fd);
}
int
PidFile::readPid()
{
FILE *pf = fopen(_pidfile, "r");
if (pf == NULL) return 0;
char buf[100];
strcpy(buf, "0");
char *fgetsres = fgets(buf, 100, pf);
fclose(pf);
return ((fgetsres != nullptr) ? atoi(buf) : 0);
}
bool
PidFile::anotherRunning()
{
int pid = readPid();
if (pid < 1 || pid == getpid()) {
// no valid pid, or my own pid
return false;
}
if (canStealLock()) {
return false;
}
return (kill(pid, 0) == 0 || errno == EPERM);
}
bool
PidFile::canStealLock()
{
int flags = O_WRONLY | O_NONBLOCK;
int desc = open(_pidfile, flags, 0644);
if (desc < 0) {
return false;
}
if (flock(desc, LOCK_EX | LOCK_NB) != 0) {
close(desc);
return false;
}
flock(desc, LOCK_UN | LOCK_NB);
close(desc);
return true;
}
using namespace ns_log;
int loop(const char *svc, char * const * run)
{
int pstdout[2];
int pstderr[2];
if (pipe(pstdout) < 0 || pipe(pstderr) < 0) {
LOG(error, "pipe: %s", strerror(errno));
exit(1);
}
LOG(debug, "stdout pipe %d <- %d; stderr pipe %d <- %d",
pstdout[0], pstdout[1],
pstderr[0], pstderr[1]);
int high = 1 + pstdout[0] + pstderr[0];
pid_t child = fork();
if (child == 0) {
// I am the child process
dup2(pstdout[1], 1);
dup2(pstderr[1], 2);
close(pstdout[0]);
close(pstderr[0]);
close(pstdout[1]);
close(pstderr[1]);
execvp(run[0], run);
LOG(error, "exec %s: %s", run[0], strerror(errno));
exit(1);
}
if (child < 0) {
LOG(error, "fork(): %s", strerror(errno));
exit(1);
}
// I am the parent process
LOG(debug, "started %s (pid %d)", run[0], (int)child);
std::string torun = run[0];
for (char * const *arg = (run + 1); *arg != NULL; ++arg) {
torun += " ";
torun += *arg;
}
{
torun += " (pid ";
char buf[20];
sprintf(buf, "%d", (int)child);
torun += buf;
torun += ")";
}
EV_STARTING(torun.c_str());
close(pstdout[1]);
close(pstderr[1]);
LLParser outvia;
LLParser errvia;
outvia.setDefaultLevel(Logger::info);
errvia.setDefaultLevel(Logger::warning);
outvia.setService(svc);
errvia.setService(svc);
outvia.setComponent("stdout");
errvia.setComponent("stderr");
outvia.setPid(child);
errvia.setPid(child);
InputBuf outReader(pstdout[0]);
InputBuf errReader(pstderr[0]);
bool outeof = false;
bool erreof = false;
int wstat = 0;
while (child || !outeof || !erreof) {
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 100000; // == 100 ms == 1/10 s
fd_set pipes;
FD_ZERO(&pipes);
if (!outeof) FD_SET(pstdout[0], &pipes);
if (!erreof) FD_SET(pstderr[0], &pipes);
int n = select(high, &pipes, NULL, NULL, &timeout);
if (n > 0) {
if (FD_ISSET(pstdout[0], &pipes)) {
LOG(debug, "out reader has input");
if (outReader.blockRead()) {
while (outReader.hasInput()) {
LOG(debug, "process out reader input");
outReader.doInput(outvia);
}
} else {
LOG(debug, "eof on stdout");
outeof = true; // EOF on stdout
close(pstdout[0]);
}
}
if (FD_ISSET(pstderr[0], &pipes)) {
LOG(debug, "err reader has input");
if (errReader.blockRead()) {
while (errReader.hasInput()) {
LOG(debug, "process err reader input");
errReader.doInput(errvia);
}
} else {
LOG(debug, "eof on stderr");
erreof = true; // EOF on stderr
close(pstderr[0]);
}
}
}
if (child != 0) {
int cpid = waitpid(child, &wstat, WNOHANG);
if (cpid == child) {
if (WIFSTOPPED(wstat)) {
LOG(info, "child %d stopped, waiting for it to continue",
cpid);
} else if (WIFEXITED(wstat)) {
// child terminated
LOG(debug, "child %d exit status: %d", cpid,
(int)WEXITSTATUS(wstat));
EV_STOPPED(torun.c_str(), (int)child, (int)WEXITSTATUS(wstat));
child = 0;
} else if (WIFSIGNALED(wstat)) {
if (WTERMSIG(wstat) != lastsig) {
LOG(warning, "child died from signal: %d", WTERMSIG(wstat));
if (WCOREDUMP(wstat)) {
LOG(info, "child %d dumped core", cpid);
}
}
child = 0;
} else {
LOG(error, "unexpected status %d from waidpit", wstat);
abort();
}
} else if (cpid < 0) {
LOG(error, "waitpid: %s", strerror(errno));
abort();
} else if (cpid != 0) {
LOG(warning, "unexpected status %d for pid %d",
wstat, cpid);
abort();
}
}
if (unhandledsig && child != 0) {
LOG(debug, "got signal %d, sending to pid %d",
(int)lastsig, (int)child);
char why[256];
sprintf(why, "got signal %d", (int)lastsig);
EV_STOPPING(torun.c_str(), why);
kill(child, lastsig);
unhandledsig = 0;
}
}
if (WIFSIGNALED(wstat))
return WTERMSIG(wstat);
return WEXITSTATUS(wstat);
}
void usage(char *prog, int es)
{
fprintf(stderr, "Usage: %s\n"
" [-s service] [-r restartinterval] [-p pidfile]"
" program [args ...]\n"
"or: [-p pidfile] [-k killcmd] -S\n", prog);
exit(es);
}
int main(int argc, char *argv[])
{
bool doStop = false;
int restart = 0;
const char *service = "runserver";
const char *pidfile = "vespa-runserver.pid"; // XXX bad default?
const char *killcmd = NULL;
signal(SIGQUIT, SIG_IGN);
int ch;
while ((ch = getopt(argc, argv, "k:s:r:p:Sh")) != -1) {
switch (ch) {
case 's':
service = optarg;
break;
case 'r':
restart = atoi(optarg);
break;
case 'p':
pidfile = optarg;
break;
case 'S':
doStop = true;
break;
case 'k':
killcmd = optarg;
break;
default:
usage(argv[0], ch != 'h');
}
}
const char *envROOT = getenv("ROOT");
if (envROOT == NULL || envROOT[0] == '\0') {
envROOT = vespa::Defaults::vespaHome();
setenv("ROOT", envROOT, 1);
}
if (chdir(envROOT) != 0) {
fprintf(stderr, "Cannot chdir to %s: %s\n", envROOT, strerror(errno));
exit(1);
}
PidFile mypf(pidfile);
if (doStop) {
if (mypf.anotherRunning()) {
int pid = mypf.readPid();
if (killcmd != NULL) {
fprintf(stdout, "%s was running with pid %d, running '%s' to stop it\n",
service, pid, killcmd);
if (system(killcmd) != 0) {
fprintf(stderr, "WARNING: stop command '%s' had some problem\n", killcmd);
}
} else {
fprintf(stdout, "%s was running with pid %d, sending SIGTERM\n",
service, pid);
if (killpg(pid, SIGTERM) != 0) {
fprintf(stderr, "could not signal %d: %s\n", pid,
strerror(errno));
exit(1);
}
}
fprintf(stdout, "Waiting for exit (up to 60 seconds)\n");
for (int cnt(0); cnt < 1800; cnt++) {
usleep(100000); // wait 0.1 seconds
if ((cnt > 300) && (cnt % 100 == 0)) {
killpg(pid, SIGTERM);
}
if (killpg(pid, 0) == 0) {
if (cnt%10 == 0) {
fprintf(stdout, ".");
fflush(stdout);
}
} else {
fprintf(stdout, "DONE\n");
break;
}
if (cnt == 900) {
printf("\ngiving up, sending KILL signal\n");
killpg(pid, SIGKILL);
}
}
} else {
fprintf(stdout, "%s not running according to %s\n",
service, pidfile);
}
mypf.cleanUp();
exit(0);
}
if (optind >= argc || killcmd != NULL) {
usage(argv[0], 1);
}
if (mypf.anotherRunning()) {
fprintf(stderr, "runserver already running with pid %d\n",
mypf.readPid());
exit(0);
}
if (!mypf.writeOpen()) {
perror(pidfile);
return 1;
}
pid_t rsp = fork();
if (rsp == 0) {
close(0);
if (open("/dev/null", O_RDONLY) != 0) {
perror("open /dev/null for reading failed");
exit(1);
}
close(1);
if (open("/dev/null", O_WRONLY) != 1) {
perror("open /dev/null for writing failed");
exit(1);
}
dup2(1, 2);
if (setsid() < 0) {
perror("setsid");
exit(1);
}
struct sigaction act;
struct sigaction oact;
memset(&act, 0, sizeof(act));
act.sa_handler = termsig;
sigaction(SIGINT, &act, &oact);
sigaction(SIGTERM, &act, &oact);
int stat = 0;
try {
mypf.writePid();
do {
time_t laststart = steady_time();
stat = loop(service, argv+optind);
if (restart > 0 && !gotstopsig) {
int wt = restart + laststart - steady_time();
if (wt < 0) wt = 0;
LOG(info, "will restart in %d seconds", wt);
}
while (!gotstopsig && steady_time() - laststart < restart) {
sleep(1);
}
} while (!gotstopsig && restart > 0);
} catch (MsgException& ex) {
LOG(error, "exception: '%s'", ex.what());
exit(1);
}
if (restart > 0) {
LOG(debug, "final exit status: %d", stat);
}
mypf.cleanUp();
exit(stat);
}
if (rsp < 0) {
perror("fork");
return 1;
}
printf("runserver(%s) running with pid: %d\n", service, rsp);
return 0;
}
<|endoftext|>
|
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file EthashGPUMiner.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*
* Determines the PoW algorithm.
*/
#if ETH_ETHASHCL || !ETH_TRUE
#include "EthashGPUMiner.h"
#include <thread>
#include <chrono>
#include <libethash-cl/ethash_cl_miner.h>
using namespace std;
using namespace dev;
using namespace eth;
namespace dev
{
namespace eth
{
class EthashCLHook: public ethash_cl_miner::search_hook
{
public:
EthashCLHook(EthashGPUMiner* _owner): m_owner(_owner) {}
EthashCLHook(EthashCLHook const&) = delete;
void abort()
{
{
UniqueGuard l(x_all);
if (m_aborted)
return;
// cdebug << "Attempting to abort";
m_abort = true;
}
// m_abort is true so now searched()/found() will return true to abort the search.
// we hang around on this thread waiting for them to point out that they have aborted since
// otherwise we may end up deleting this object prior to searched()/found() being called.
m_aborted.wait(true);
// for (unsigned timeout = 0; timeout < 100 && !m_aborted; ++timeout)
// std::this_thread::sleep_for(chrono::milliseconds(30));
// if (!m_aborted)
// cwarn << "Couldn't abort. Abandoning OpenCL process.";
}
void reset()
{
UniqueGuard l(x_all);
m_aborted = m_abort = false;
}
protected:
virtual bool found(uint64_t const* _nonces, uint32_t _count) override
{
// dev::operator <<(std::cerr << "Found nonces: ", vector<uint64_t>(_nonces, _nonces + _count)) << std::endl;
for (uint32_t i = 0; i < _count; ++i)
if (m_owner->report(_nonces[i]))
return (m_aborted = true);
return m_owner->shouldStop();
}
virtual bool searched(uint64_t _startNonce, uint32_t _count) override
{
UniqueGuard l(x_all);
// std::cerr << "Searched " << _count << " from " << _startNonce << std::endl;
m_owner->accumulateHashes(_count);
m_last = _startNonce + _count;
if (m_abort || m_owner->shouldStop())
return (m_aborted = true);
return false;
}
private:
Mutex x_all;
uint64_t m_last;
bool m_abort = false;
Notified<bool> m_aborted = {true};
EthashGPUMiner* m_owner = nullptr;
};
}
}
unsigned EthashGPUMiner::s_platformId = 0;
unsigned EthashGPUMiner::s_deviceId = 0;
unsigned EthashGPUMiner::s_numInstances = 0;
EthashGPUMiner::EthashGPUMiner(ConstructionInfo const& _ci):
GenericMiner<EthashProofOfWork>(_ci),
Worker("gpuminer" + toString(index())),
m_hook(new EthashCLHook(this))
{
}
EthashGPUMiner::~EthashGPUMiner()
{
pause();
delete m_miner;
delete m_hook;
}
bool EthashGPUMiner::report(uint64_t _nonce)
{
Nonce n = (Nonce)(u64)_nonce;
EthashProofOfWork::Result r = EthashAux::eval(work().seedHash, work().headerHash, n);
if (r.value < work().boundary)
return submitProof(Solution{n, r.mixHash});
return false;
}
void EthashGPUMiner::kickOff()
{
m_hook->reset();
startWorking();
}
void EthashGPUMiner::workLoop()
{
// take local copy of work since it may end up being overwritten by kickOff/pause.
try {
WorkPackage w = work();
cnote << "workLoop" << !!m_miner << m_minerSeed << w.seedHash;
if (!m_miner || m_minerSeed != w.seedHash)
{
cnote << "Initialising miner...";
m_minerSeed = w.seedHash;
delete m_miner;
m_miner = new ethash_cl_miner;
unsigned device = instances() > 1 ? index() : s_deviceId;
EthashAux::FullType dag;
while (true)
{
if ((dag = EthashAux::full(w.seedHash, true)))
break;
if (shouldStop())
{
delete m_miner;
m_miner = nullptr;
return;
}
cnote << "Awaiting DAG";
this_thread::sleep_for(chrono::milliseconds(500));
}
bytesConstRef dagData = dag->data();
m_miner->init(dagData.data(), dagData.size(), s_platformId, device);
}
uint64_t upper64OfBoundary = (uint64_t)(u64)((u256)w.boundary >> 192);
m_miner->search(w.headerHash.data(), upper64OfBoundary, *m_hook);
}
catch (cl::Error const& _e)
{
delete m_miner;
m_miner = nullptr;
cwarn << "Error GPU mining: " << _e.what() << "(" << _e.err() << ")";
}
}
void EthashGPUMiner::pause()
{
m_hook->abort();
stopWorking();
}
std::string EthashGPUMiner::platformInfo()
{
return ethash_cl_miner::platform_info(s_platformId, s_deviceId);
}
unsigned EthashGPUMiner::getNumDevices()
{
return ethash_cl_miner::getNumDevices(s_platformId);
}
void EthashGPUMiner::listDevices()
{
return ethash_cl_miner::listDevices();
}
bool EthashGPUMiner::configureGPU(
unsigned _localWorkSize,
unsigned _globalWorkSizeMultiplier,
unsigned _msPerBatch,
unsigned _platformId,
unsigned _deviceId,
bool _allowCPU,
unsigned _extraGPUMemory,
uint64_t _currentBlock
)
{
s_platformId = _platformId;
s_deviceId = _deviceId;
if (_localWorkSize != 32 && _localWorkSize != 64 && _localWorkSize != 128 && _localWorkSize != 256)
{
cout << "Given localWorkSize of " << toString(_localWorkSize) << "is invalid. Must be either 32,64, or 128" << endl;
return false;
}
if (!ethash_cl_miner::configureGPU(
_platformId,
_localWorkSize,
_globalWorkSizeMultiplier * _localWorkSize,
_msPerBatch,
_allowCPU,
_extraGPUMemory,
_currentBlock)
)
{
cout << "No GPU device with sufficient memory was found. Can't GPU mine. Remove the -G argument" << endl;
return false;
}
return true;
}
#endif
<commit_msg>Update EthashGPUMiner.cpp<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file EthashGPUMiner.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*
* Determines the PoW algorithm.
*/
#if ETH_ETHASHCL || !ETH_TRUE
#include "EthashGPUMiner.h"
#include <thread>
#include <chrono>
#include <libethash-cl/ethash_cl_miner.h>
using namespace std;
using namespace dev;
using namespace eth;
namespace dev
{
namespace eth
{
class EthashCLHook: public ethash_cl_miner::search_hook
{
public:
EthashCLHook(EthashGPUMiner* _owner): m_owner(_owner) {}
EthashCLHook(EthashCLHook const&) = delete;
void abort()
{
{
UniqueGuard l(x_all);
if (m_aborted)
return;
// cdebug << "Attempting to abort";
m_abort = true;
}
// m_abort is true so now searched()/found() will return true to abort the search.
// we hang around on this thread waiting for them to point out that they have aborted since
// otherwise we may end up deleting this object prior to searched()/found() being called.
m_aborted.wait(true);
// for (unsigned timeout = 0; timeout < 100 && !m_aborted; ++timeout)
// std::this_thread::sleep_for(chrono::milliseconds(30));
// if (!m_aborted)
// cwarn << "Couldn't abort. Abandoning OpenCL process.";
}
void reset()
{
UniqueGuard l(x_all);
m_aborted = m_abort = false;
}
protected:
virtual bool found(uint64_t const* _nonces, uint32_t _count) override
{
// dev::operator <<(std::cerr << "Found nonces: ", vector<uint64_t>(_nonces, _nonces + _count)) << std::endl;
for (uint32_t i = 0; i < _count; ++i)
if (m_owner->report(_nonces[i]))
return (m_aborted = true);
return m_owner->shouldStop();
}
virtual bool searched(uint64_t _startNonce, uint32_t _count) override
{
UniqueGuard l(x_all);
// std::cerr << "Searched " << _count << " from " << _startNonce << std::endl;
m_owner->accumulateHashes(_count);
m_last = _startNonce + _count;
if (m_abort || m_owner->shouldStop())
return (m_aborted = true);
return false;
}
private:
Mutex x_all;
uint64_t m_last;
bool m_abort = false;
Notified<bool> m_aborted = {true};
EthashGPUMiner* m_owner = nullptr;
};
}
}
unsigned EthashGPUMiner::s_platformId = 0;
unsigned EthashGPUMiner::s_deviceId = 0;
unsigned EthashGPUMiner::s_numInstances = 0;
EthashGPUMiner::EthashGPUMiner(ConstructionInfo const& _ci):
GenericMiner<EthashProofOfWork>(_ci),
Worker("gpuminer" + toString(index())),
m_hook(new EthashCLHook(this))
{
}
EthashGPUMiner::~EthashGPUMiner()
{
pause();
delete m_miner;
delete m_hook;
}
bool EthashGPUMiner::report(uint64_t _nonce)
{
Nonce n = (Nonce)(u64)_nonce;
EthashProofOfWork::Result r = EthashAux::eval(work().seedHash, work().headerHash, n);
if (r.value < work().boundary)
return submitProof(Solution{n, r.mixHash});
return false;
}
void EthashGPUMiner::kickOff()
{
m_hook->reset();
startWorking();
}
void EthashGPUMiner::workLoop()
{
// take local copy of work since it may end up being overwritten by kickOff/pause.
try {
WorkPackage w = work();
cnote << "workLoop" << !!m_miner << m_minerSeed << w.seedHash;
if (!m_miner || m_minerSeed != w.seedHash)
{
cnote << "Initialising miner...";
m_minerSeed = w.seedHash;
delete m_miner;
m_miner = new ethash_cl_miner;
unsigned device = instances() > 1 ? index() : s_deviceId;
EthashAux::FullType dag;
while (true)
{
if ((dag = EthashAux::full(w.seedHash, true)))
break;
if (shouldStop())
{
delete m_miner;
m_miner = nullptr;
return;
}
cnote << "Awaiting DAG";
this_thread::sleep_for(chrono::milliseconds(500));
}
bytesConstRef dagData = dag->data();
m_miner->init(dagData.data(), dagData.size(), s_platformId, device);
}
uint64_t upper64OfBoundary = (uint64_t)(u64)((u256)w.boundary >> 192);
m_miner->search(w.headerHash.data(), upper64OfBoundary, *m_hook);
}
catch (cl::Error const& _e)
{
delete m_miner;
m_miner = nullptr;
cwarn << "Error GPU mining: " << _e.what() << "(" << _e.err() << ")";
}
}
void EthashGPUMiner::pause()
{
m_hook->abort();
stopWorking();
}
std::string EthashGPUMiner::platformInfo()
{
return ethash_cl_miner::platform_info(s_platformId, s_deviceId);
}
unsigned EthashGPUMiner::getNumDevices()
{
return ethash_cl_miner::getNumDevices(s_platformId);
}
void EthashGPUMiner::listDevices()
{
return ethash_cl_miner::listDevices();
}
bool EthashGPUMiner::configureGPU(
unsigned _localWorkSize,
unsigned _globalWorkSizeMultiplier,
unsigned _msPerBatch,
unsigned _platformId,
unsigned _deviceId,
bool _allowCPU,
unsigned _extraGPUMemory,
uint64_t _currentBlock
)
{
s_platformId = _platformId;
s_deviceId = _deviceId;
if (_localWorkSize != 32 && _localWorkSize != 64 && _localWorkSize != 128 && _localWorkSize != 256)
{
cout << "Given localWorkSize of " << toString(_localWorkSize) << "is invalid. Must be either 32,64,128 or 256" << endl;
return false;
}
if (!ethash_cl_miner::configureGPU(
_platformId,
_localWorkSize,
_globalWorkSizeMultiplier * _localWorkSize,
_msPerBatch,
_allowCPU,
_extraGPUMemory,
_currentBlock)
)
{
cout << "No GPU device with sufficient memory was found. Can't GPU mine. Remove the -G argument" << endl;
return false;
}
return true;
}
#endif
<|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 "webkit/glue/webpreferences.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "third_party/WebKit/WebKit/chromium/public/WebRuntimeFeatures.h"
#include "third_party/WebKit/WebKit/chromium/public/WebKit.h"
#include "third_party/WebKit/WebKit/chromium/public/WebSettings.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/WebKit/chromium/public/WebURL.h"
#include "third_party/WebKit/WebKit/chromium/public/WebView.h"
#include "webkit/glue/webkit_glue.h"
using WebKit::WebRuntimeFeatures;
using WebKit::WebSettings;
using WebKit::WebString;
using WebKit::WebURL;
using WebKit::WebView;
void WebPreferences::Apply(WebView* web_view) const {
WebSettings* settings = web_view->settings();
settings->setStandardFontFamily(WideToUTF16Hack(standard_font_family));
settings->setFixedFontFamily(WideToUTF16Hack(fixed_font_family));
settings->setSerifFontFamily(WideToUTF16Hack(serif_font_family));
settings->setSansSerifFontFamily(WideToUTF16Hack(sans_serif_font_family));
settings->setCursiveFontFamily(WideToUTF16Hack(cursive_font_family));
settings->setFantasyFontFamily(WideToUTF16Hack(fantasy_font_family));
settings->setDefaultFontSize(default_font_size);
settings->setDefaultFixedFontSize(default_fixed_font_size);
settings->setMinimumFontSize(minimum_font_size);
settings->setMinimumLogicalFontSize(minimum_logical_font_size);
settings->setDefaultTextEncodingName(ASCIIToUTF16(default_encoding));
settings->setJavaScriptEnabled(javascript_enabled);
settings->setWebSecurityEnabled(web_security_enabled);
settings->setJavaScriptCanOpenWindowsAutomatically(
javascript_can_open_windows_automatically);
settings->setLoadsImagesAutomatically(loads_images_automatically);
settings->setPluginsEnabled(plugins_enabled);
settings->setDOMPasteAllowed(dom_paste_enabled);
settings->setDeveloperExtrasEnabled(developer_extras_enabled);
settings->setNeedsSiteSpecificQuirks(site_specific_quirks_enabled);
settings->setShrinksStandaloneImagesToFit(shrinks_standalone_images_to_fit);
settings->setUsesEncodingDetector(uses_universal_detector);
settings->setTextAreasAreResizable(text_areas_are_resizable);
settings->setAllowScriptsToCloseWindows(allow_scripts_to_close_windows);
if (user_style_sheet_enabled)
settings->setUserStyleSheetLocation(user_style_sheet_location);
else
settings->setUserStyleSheetLocation(WebURL());
settings->setAuthorAndUserStylesEnabled(author_and_user_styles_enabled);
settings->setUsesPageCache(uses_page_cache);
settings->setDownloadableBinaryFontsEnabled(remote_fonts_enabled);
settings->setJavaScriptCanAccessClipboard(javascript_can_access_clipboard);
settings->setXSSAuditorEnabled(xss_auditor_enabled);
settings->setLocalStorageEnabled(local_storage_enabled);
WebRuntimeFeatures::enableDatabase(
WebRuntimeFeatures::isDatabaseEnabled() || databases_enabled);
settings->setOfflineWebApplicationCacheEnabled(application_cache_enabled);
settings->setHTML5ParserEnabled(enable_html5_parser);
// This setting affects the behavior of links in an editable region:
// clicking the link should select it rather than navigate to it.
// Safari uses the same default. It is unlikley an embedder would want to
// change this, since it would break existing rich text editors.
settings->setEditableLinkBehaviorNeverLive();
settings->setFontRenderingModeNormal();
settings->setJavaEnabled(java_enabled);
// Turn this on to cause WebCore to paint the resize corner for us.
settings->setShouldPaintCustomScrollbars(true);
// By default, allow_universal_access_from_file_urls is set to false and thus
// we mitigate attacks from local HTML files by not granting file:// URLs
// universal access. Only test shell will enable this.
settings->setAllowUniversalAccessFromFileURLs(
allow_universal_access_from_file_urls);
settings->setAllowFileAccessFromFileURLs(allow_file_access_from_file_urls);
// We prevent WebKit from checking if it needs to add a "text direction"
// submenu to a context menu. it is not only because we don't need the result
// but also because it cause a possible crash in Editor::hasBidiSelection().
settings->setTextDirectionSubmenuInclusionBehaviorNeverIncluded();
// Enable experimental WebGL support if requested on command line
// and support is compiled in.
settings->setExperimentalWebGLEnabled(experimental_webgl_enabled);
// Display colored borders around composited render layers if requested
// on command line.
settings->setShowDebugBorders(show_composited_layer_borders);
// Enable gpu-accelerated compositing if requested on the command line.
settings->setAcceleratedCompositingEnabled(accelerated_compositing_enabled);
// Enable gpu-accelerated 2d canvas if requested on the command line.
settings->setAccelerated2dCanvasEnabled(accelerated_2d_canvas_enabled);
// Enable memory info reporting to page if requested on the command line.
settings->setMemoryInfoEnabled(memory_info_enabled);
for (WebInspectorPreferences::const_iterator it = inspector_settings.begin();
it != inspector_settings.end(); ++it)
web_view->setInspectorSetting(WebString::fromUTF8(it->first),
WebString::fromUTF8(it->second));
// Tabs to link is not part of the settings. WebCore calls
// ChromeClient::tabsToLinks which is part of the glue code.
web_view->setTabsToLinks(tabs_to_links);
}
<commit_msg>WebGL web preferences do not disable WebGL if already enabled.<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 "webkit/glue/webpreferences.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "third_party/WebKit/WebKit/chromium/public/WebRuntimeFeatures.h"
#include "third_party/WebKit/WebKit/chromium/public/WebKit.h"
#include "third_party/WebKit/WebKit/chromium/public/WebSettings.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/WebKit/chromium/public/WebURL.h"
#include "third_party/WebKit/WebKit/chromium/public/WebView.h"
#include "webkit/glue/webkit_glue.h"
using WebKit::WebRuntimeFeatures;
using WebKit::WebSettings;
using WebKit::WebString;
using WebKit::WebURL;
using WebKit::WebView;
void WebPreferences::Apply(WebView* web_view) const {
WebSettings* settings = web_view->settings();
settings->setStandardFontFamily(WideToUTF16Hack(standard_font_family));
settings->setFixedFontFamily(WideToUTF16Hack(fixed_font_family));
settings->setSerifFontFamily(WideToUTF16Hack(serif_font_family));
settings->setSansSerifFontFamily(WideToUTF16Hack(sans_serif_font_family));
settings->setCursiveFontFamily(WideToUTF16Hack(cursive_font_family));
settings->setFantasyFontFamily(WideToUTF16Hack(fantasy_font_family));
settings->setDefaultFontSize(default_font_size);
settings->setDefaultFixedFontSize(default_fixed_font_size);
settings->setMinimumFontSize(minimum_font_size);
settings->setMinimumLogicalFontSize(minimum_logical_font_size);
settings->setDefaultTextEncodingName(ASCIIToUTF16(default_encoding));
settings->setJavaScriptEnabled(javascript_enabled);
settings->setWebSecurityEnabled(web_security_enabled);
settings->setJavaScriptCanOpenWindowsAutomatically(
javascript_can_open_windows_automatically);
settings->setLoadsImagesAutomatically(loads_images_automatically);
settings->setPluginsEnabled(plugins_enabled);
settings->setDOMPasteAllowed(dom_paste_enabled);
settings->setDeveloperExtrasEnabled(developer_extras_enabled);
settings->setNeedsSiteSpecificQuirks(site_specific_quirks_enabled);
settings->setShrinksStandaloneImagesToFit(shrinks_standalone_images_to_fit);
settings->setUsesEncodingDetector(uses_universal_detector);
settings->setTextAreasAreResizable(text_areas_are_resizable);
settings->setAllowScriptsToCloseWindows(allow_scripts_to_close_windows);
if (user_style_sheet_enabled)
settings->setUserStyleSheetLocation(user_style_sheet_location);
else
settings->setUserStyleSheetLocation(WebURL());
settings->setAuthorAndUserStylesEnabled(author_and_user_styles_enabled);
settings->setUsesPageCache(uses_page_cache);
settings->setDownloadableBinaryFontsEnabled(remote_fonts_enabled);
settings->setJavaScriptCanAccessClipboard(javascript_can_access_clipboard);
settings->setXSSAuditorEnabled(xss_auditor_enabled);
settings->setLocalStorageEnabled(local_storage_enabled);
WebRuntimeFeatures::enableDatabase(
WebRuntimeFeatures::isDatabaseEnabled() || databases_enabled);
settings->setOfflineWebApplicationCacheEnabled(application_cache_enabled);
settings->setHTML5ParserEnabled(enable_html5_parser);
// This setting affects the behavior of links in an editable region:
// clicking the link should select it rather than navigate to it.
// Safari uses the same default. It is unlikley an embedder would want to
// change this, since it would break existing rich text editors.
settings->setEditableLinkBehaviorNeverLive();
settings->setFontRenderingModeNormal();
settings->setJavaEnabled(java_enabled);
// Turn this on to cause WebCore to paint the resize corner for us.
settings->setShouldPaintCustomScrollbars(true);
// By default, allow_universal_access_from_file_urls is set to false and thus
// we mitigate attacks from local HTML files by not granting file:// URLs
// universal access. Only test shell will enable this.
settings->setAllowUniversalAccessFromFileURLs(
allow_universal_access_from_file_urls);
settings->setAllowFileAccessFromFileURLs(allow_file_access_from_file_urls);
// We prevent WebKit from checking if it needs to add a "text direction"
// submenu to a context menu. it is not only because we don't need the result
// but also because it cause a possible crash in Editor::hasBidiSelection().
settings->setTextDirectionSubmenuInclusionBehaviorNeverIncluded();
// Enable experimental WebGL support if requested on command line
// and support is compiled in.
settings->setExperimentalWebGLEnabled(
WebRuntimeFeatures::isWebGLEnabled() || experimental_webgl_enabled);
// Display colored borders around composited render layers if requested
// on command line.
settings->setShowDebugBorders(show_composited_layer_borders);
// Enable gpu-accelerated compositing if requested on the command line.
settings->setAcceleratedCompositingEnabled(accelerated_compositing_enabled);
// Enable gpu-accelerated 2d canvas if requested on the command line.
settings->setAccelerated2dCanvasEnabled(accelerated_2d_canvas_enabled);
// Enable memory info reporting to page if requested on the command line.
settings->setMemoryInfoEnabled(memory_info_enabled);
for (WebInspectorPreferences::const_iterator it = inspector_settings.begin();
it != inspector_settings.end(); ++it)
web_view->setInspectorSetting(WebString::fromUTF8(it->first),
WebString::fromUTF8(it->second));
// Tabs to link is not part of the settings. WebCore calls
// ChromeClient::tabsToLinks which is part of the glue code.
web_view->setTabsToLinks(tabs_to_links);
}
<|endoftext|>
|
<commit_before>#include <bench/tests/qdb/quasardb_facade.hpp>
#include <utils/detailed_error.hpp>
#ifdef WIN32
#include <utils/win32.hpp>
#endif
#include <utils/invocation_string.hpp>
#include <qdb/blob.h>
#include <qdb/deque.h>
#include <qdb/hset.h>
#include <qdb/integer.h>
#include <qdb/stream.h>
#include <qdb/tag.h>
#include <cppformat/format.h>
#ifndef WIN32
#include <cstring>
#include <cerrno>
#endif
using namespace bench::tests::qdb;
#define ARG0(x, ...) x
#define STR0(x) #x
#define STR1(x) STR0(x)
#define INVOKE(...) named_invoke(STR1(ARG0(__VA_ARGS__, )), __VA_ARGS__)
using namespace bench::tests::qdb;
static bool is_error(qdb_error_t err)
{
switch (err)
{
case qdb_e_ok:
case qdb_e_ok_created:
case qdb_e_element_already_exists:
case qdb_e_element_not_found:
return false;
default:
return true;
}
}
template <typename Function, typename... Args>
static qdb_error_t named_invoke(const char * name, Function function, Args &&... args)
{
qdb_error_t err = function(args...);
if (is_error(err))
{
std::string message = qdb_error(err);
std::string details =
fmt::format("{} returned {:#08x}", utils::make_invocation_string(name, std::forward<Args>(args)...),
std::uint32_t(err));
if ((err == qdb_e_system_local) || (err == qdb_e_system_remote))
{
#ifdef WIN32
std::uint32_t lastError = utils::win32::get_last_error();
message = utils::win32::get_error_string(lastError);
details += fmt::format(" and GetLastError() returned {}", lastError);
#else
message = std::strerror(errno);
details += fmt::format(" and errno equals {}", errno);
#endif
}
throw utils::detailed_error(message, details);
}
return err;
}
quasardb_facade::quasardb_facade()
{
_handle = qdb_open_tcp();
}
quasardb_facade::~quasardb_facade()
{
qdb_close(_handle);
}
void quasardb_facade::connect(const std::string & cluster_uri)
{
INVOKE(qdb_connect, _handle, cluster_uri.c_str());
}
void quasardb_facade::close()
{
INVOKE(qdb_close, _handle);
}
void quasardb_facade::trim_all(int timeout)
{
INVOKE(qdb_trim_all, _handle, timeout);
}
void quasardb_facade::free_buffer(const char * buffer)
{
qdb_free_buffer(_handle, buffer);
}
std::string quasardb_facade::node_status(const std::string & node_uri) const
{
const char * content;
size_t content_size;
INVOKE(qdb_node_status, _handle, node_uri.c_str(), &content, &content_size);
std::string json(content, content_size);
qdb_free_buffer(_handle, content);
return json;
}
std::string quasardb_facade::node_topology(const std::string & node_uri) const
{
const char * content;
size_t content_size;
INVOKE(qdb_node_topology, _handle, node_uri.c_str(), &content, &content_size);
std::string json(content, content_size);
qdb_free_buffer(_handle, content);
return json;
}
void quasardb_facade::blob_put(const std::string & alias, const std::string & content)
{
INVOKE(qdb_blob_put, _handle, alias.c_str(), content.data(), content.size(), qdb_never_expires);
}
bool quasardb_facade::blob_update(const std::string & alias, const std::string & content)
{
return INVOKE(qdb_blob_update, _handle, alias.c_str(), content.data(), content.size(), qdb_preserve_expiration)
== qdb_e_ok_created;
}
qdb_buffer quasardb_facade::blob_get(const std::string & alias)
{
const void * result;
std::size_t result_size;
INVOKE(qdb_blob_get, _handle, alias.c_str(), &result, &result_size);
return qdb_buffer(_handle, result, result_size);
}
void quasardb_facade::blob_get_noalloc(const std::string & alias, std::string & content)
{
std::size_t result_size = content.capacity();
INVOKE(qdb_blob_get_noalloc, _handle, alias.c_str(), const_cast<char *>(content.data()), &result_size);
content.resize(result_size);
}
void quasardb_facade::remove(const std::string & alias)
{
INVOKE(qdb_remove, _handle, alias.c_str());
}
qdb_buffer quasardb_facade::deque_pop_back(const std::string & alias)
{
const void * result;
std::size_t result_size;
INVOKE(qdb_deque_pop_back, _handle, alias.c_str(), &result, &result_size);
return qdb_buffer(_handle, result, result_size);
}
qdb_buffer quasardb_facade::deque_pop_front(const std::string & alias)
{
const void * result;
std::size_t result_size;
INVOKE(qdb_deque_pop_front, _handle, alias.c_str(), &result, &result_size);
return qdb_buffer(_handle, result, result_size);
}
void quasardb_facade::deque_push_back(const std::string & alias, const std::string & content)
{
INVOKE(qdb_deque_push_back, _handle, alias.c_str(), content.data(), content.size());
}
void quasardb_facade::deque_push_front(const std::string & alias, const std::string & content)
{
INVOKE(qdb_deque_push_front, _handle, alias.c_str(), content.data(), content.size());
}
std::int64_t quasardb_facade::int_add(const std::string & alias, std::int64_t value)
{
std::int64_t total;
INVOKE(qdb_int_add, _handle, alias.c_str(), 1, &total);
return total;
}
void quasardb_facade::int_put(const std::string & alias, std::int64_t value)
{
INVOKE(qdb_int_put, _handle, alias.c_str(), value, qdb_never_expires);
}
bool quasardb_facade::int_update(const std::string & alias, std::int64_t value)
{
return INVOKE(qdb_int_update, _handle, alias.c_str(), value, qdb_preserve_expiration) == qdb_e_ok_created;
}
std::int64_t quasardb_facade::int_get(const std::string & alias)
{
std::int64_t value;
INVOKE(qdb_int_get, _handle, alias.c_str(), &value);
return value;
}
bool quasardb_facade::hset_contains(const std::string & alias, const std::string & content)
{
return INVOKE(qdb_hset_contains, _handle, alias.c_str(), content.data(), content.size())
== qdb_e_element_already_exists;
}
bool quasardb_facade::hset_erase(const std::string & alias, const std::string & content)
{
return INVOKE(qdb_hset_contains, _handle, alias.c_str(), content.data(), content.size()) != qdb_e_element_not_found;
}
bool quasardb_facade::hset_insert(const std::string & alias, const std::string & content)
{
return INVOKE(qdb_hset_insert, _handle, alias.c_str(), content.data(), content.size())
!= qdb_e_element_already_exists;
}
void quasardb_facade::attach_tag(const std::string & alias, const std::string & tag)
{
INVOKE(qdb_attach_tag, _handle, alias.c_str(), tag.c_str());
}
void quasardb_facade::has_tag(const std::string & alias, const std::string & tag)
{
INVOKE(qdb_has_tag, _handle, alias.c_str(), tag.c_str());
}
void quasardb_facade::detach_tag(const std::string & alias, const std::string & tag)
{
INVOKE(qdb_detach_tag, _handle, alias.c_str(), tag.c_str());
}
qdb_stream_t quasardb_facade::stream_open(const std::string & alias, qdb_stream_mode_t mode)
{
qdb_stream_t stream;
INVOKE(qdb_stream_open, _handle, alias.c_str(), mode, &stream);
return stream;
}
void qdb_stream_facade::close()
{
INVOKE(qdb_stream_close, _handle);
}
void qdb_stream_facade::write(const std::string & content)
{
INVOKE(qdb_stream_write, _handle, content.data(), content.size());
}
<commit_msg>Add missing include.<commit_after>#include <bench/tests/qdb/quasardb_facade.hpp>
#include <utils/detailed_error.hpp>
#ifdef WIN32
#include <utils/win32.hpp>
#endif
#include <utils/invocation_string.hpp>
#include <qdb/blob.h>
#include <qdb/deque.h>
#include <qdb/hset.h>
#include <qdb/node.h>
#include <qdb/integer.h>
#include <qdb/stream.h>
#include <qdb/tag.h>
#include <cppformat/format.h>
#ifndef WIN32
#include <cstring>
#include <cerrno>
#endif
using namespace bench::tests::qdb;
#define ARG0(x, ...) x
#define STR0(x) #x
#define STR1(x) STR0(x)
#define INVOKE(...) named_invoke(STR1(ARG0(__VA_ARGS__, )), __VA_ARGS__)
using namespace bench::tests::qdb;
static bool is_error(qdb_error_t err)
{
switch (err)
{
case qdb_e_ok:
case qdb_e_ok_created:
case qdb_e_element_already_exists:
case qdb_e_element_not_found:
return false;
default:
return true;
}
}
template <typename Function, typename... Args>
static qdb_error_t named_invoke(const char * name, Function function, Args &&... args)
{
qdb_error_t err = function(args...);
if (is_error(err))
{
std::string message = qdb_error(err);
std::string details =
fmt::format("{} returned {:#08x}", utils::make_invocation_string(name, std::forward<Args>(args)...),
std::uint32_t(err));
if ((err == qdb_e_system_local) || (err == qdb_e_system_remote))
{
#ifdef WIN32
std::uint32_t lastError = utils::win32::get_last_error();
message = utils::win32::get_error_string(lastError);
details += fmt::format(" and GetLastError() returned {}", lastError);
#else
message = std::strerror(errno);
details += fmt::format(" and errno equals {}", errno);
#endif
}
throw utils::detailed_error(message, details);
}
return err;
}
quasardb_facade::quasardb_facade()
{
_handle = qdb_open_tcp();
}
quasardb_facade::~quasardb_facade()
{
qdb_close(_handle);
}
void quasardb_facade::connect(const std::string & cluster_uri)
{
INVOKE(qdb_connect, _handle, cluster_uri.c_str());
}
void quasardb_facade::close()
{
INVOKE(qdb_close, _handle);
}
void quasardb_facade::trim_all(int timeout)
{
INVOKE(qdb_trim_all, _handle, timeout);
}
void quasardb_facade::free_buffer(const char * buffer)
{
qdb_free_buffer(_handle, buffer);
}
std::string quasardb_facade::node_status(const std::string & node_uri) const
{
const char * content;
size_t content_size;
INVOKE(qdb_node_status, _handle, node_uri.c_str(), &content, &content_size);
std::string json(content, content_size);
qdb_free_buffer(_handle, content);
return json;
}
std::string quasardb_facade::node_topology(const std::string & node_uri) const
{
const char * content;
size_t content_size;
INVOKE(qdb_node_topology, _handle, node_uri.c_str(), &content, &content_size);
std::string json(content, content_size);
qdb_free_buffer(_handle, content);
return json;
}
void quasardb_facade::blob_put(const std::string & alias, const std::string & content)
{
INVOKE(qdb_blob_put, _handle, alias.c_str(), content.data(), content.size(), qdb_never_expires);
}
bool quasardb_facade::blob_update(const std::string & alias, const std::string & content)
{
return INVOKE(qdb_blob_update, _handle, alias.c_str(), content.data(), content.size(), qdb_preserve_expiration)
== qdb_e_ok_created;
}
qdb_buffer quasardb_facade::blob_get(const std::string & alias)
{
const void * result;
std::size_t result_size;
INVOKE(qdb_blob_get, _handle, alias.c_str(), &result, &result_size);
return qdb_buffer(_handle, result, result_size);
}
void quasardb_facade::blob_get_noalloc(const std::string & alias, std::string & content)
{
std::size_t result_size = content.capacity();
INVOKE(qdb_blob_get_noalloc, _handle, alias.c_str(), const_cast<char *>(content.data()), &result_size);
content.resize(result_size);
}
void quasardb_facade::remove(const std::string & alias)
{
INVOKE(qdb_remove, _handle, alias.c_str());
}
qdb_buffer quasardb_facade::deque_pop_back(const std::string & alias)
{
const void * result;
std::size_t result_size;
INVOKE(qdb_deque_pop_back, _handle, alias.c_str(), &result, &result_size);
return qdb_buffer(_handle, result, result_size);
}
qdb_buffer quasardb_facade::deque_pop_front(const std::string & alias)
{
const void * result;
std::size_t result_size;
INVOKE(qdb_deque_pop_front, _handle, alias.c_str(), &result, &result_size);
return qdb_buffer(_handle, result, result_size);
}
void quasardb_facade::deque_push_back(const std::string & alias, const std::string & content)
{
INVOKE(qdb_deque_push_back, _handle, alias.c_str(), content.data(), content.size());
}
void quasardb_facade::deque_push_front(const std::string & alias, const std::string & content)
{
INVOKE(qdb_deque_push_front, _handle, alias.c_str(), content.data(), content.size());
}
std::int64_t quasardb_facade::int_add(const std::string & alias, std::int64_t value)
{
std::int64_t total;
INVOKE(qdb_int_add, _handle, alias.c_str(), 1, &total);
return total;
}
void quasardb_facade::int_put(const std::string & alias, std::int64_t value)
{
INVOKE(qdb_int_put, _handle, alias.c_str(), value, qdb_never_expires);
}
bool quasardb_facade::int_update(const std::string & alias, std::int64_t value)
{
return INVOKE(qdb_int_update, _handle, alias.c_str(), value, qdb_preserve_expiration) == qdb_e_ok_created;
}
std::int64_t quasardb_facade::int_get(const std::string & alias)
{
std::int64_t value;
INVOKE(qdb_int_get, _handle, alias.c_str(), &value);
return value;
}
bool quasardb_facade::hset_contains(const std::string & alias, const std::string & content)
{
return INVOKE(qdb_hset_contains, _handle, alias.c_str(), content.data(), content.size())
== qdb_e_element_already_exists;
}
bool quasardb_facade::hset_erase(const std::string & alias, const std::string & content)
{
return INVOKE(qdb_hset_contains, _handle, alias.c_str(), content.data(), content.size()) != qdb_e_element_not_found;
}
bool quasardb_facade::hset_insert(const std::string & alias, const std::string & content)
{
return INVOKE(qdb_hset_insert, _handle, alias.c_str(), content.data(), content.size())
!= qdb_e_element_already_exists;
}
void quasardb_facade::attach_tag(const std::string & alias, const std::string & tag)
{
INVOKE(qdb_attach_tag, _handle, alias.c_str(), tag.c_str());
}
void quasardb_facade::has_tag(const std::string & alias, const std::string & tag)
{
INVOKE(qdb_has_tag, _handle, alias.c_str(), tag.c_str());
}
void quasardb_facade::detach_tag(const std::string & alias, const std::string & tag)
{
INVOKE(qdb_detach_tag, _handle, alias.c_str(), tag.c_str());
}
qdb_stream_t quasardb_facade::stream_open(const std::string & alias, qdb_stream_mode_t mode)
{
qdb_stream_t stream;
INVOKE(qdb_stream_open, _handle, alias.c_str(), mode, &stream);
return stream;
}
void qdb_stream_facade::close()
{
INVOKE(qdb_stream_close, _handle);
}
void qdb_stream_facade::write(const std::string & content)
{
INVOKE(qdb_stream_write, _handle, content.data(), content.size());
}
<|endoftext|>
|
<commit_before>#include <isl/set.h>
#include <isl/union_map.h>
#include <isl/union_set.h>
#include <isl/ast_build.h>
#include <isl/schedule.h>
#include <isl/schedule_node.h>
#include <coli/debug.h>
#include <coli/core.h>
#include <string.h>
#include <Halide.h>
#include "halide_image_io.h"
using namespace coli;
int main(int argc, char **argv)
{
// Set default coli options.
global::set_default_coli_options();
coli::function gaussian_coli("gaussian_coli");
Halide::Image<uint8_t> in_image = Halide::Tools::load_image("./images/rgb.png");
int SIZE0 = in_image.extent(0);
int SIZE1 = in_image.extent(1);
int SIZE2 = in_image.extent(2);
// Output buffers.
int gaussian_extent_2 = SIZE2;
int gaussian_extent_1 = SIZE1 - 8;
int gaussian_extent_0 = SIZE0 - 8;
coli::buffer buff_gaussian("buff_gaussian", 3, {coli::expr(gaussian_extent_2), coli::expr(gaussian_extent_1), coli::expr(gaussian_extent_0)}, coli::p_uint8, NULL, coli::a_output, &gaussian_coli);
// Input buffers.
int input_extent_2 = SIZE2;
int input_extent_1 = SIZE1;
int input_extent_0 = SIZE0;
coli::buffer buff_input("buff_input", 3, {coli::expr(input_extent_2), coli::expr(input_extent_1), coli::expr(input_extent_0)}, coli::p_uint8, NULL, coli::a_input, &gaussian_coli);
coli::computation input("[input_extent_2, input_extent_1, input_extent_0]->{input[i2, i1, i0]: (0 <= i2 <= (input_extent_2 + -1)) and (0 <= i1 <= (input_extent_1 + -1)) and (0 <= i0 <= (input_extent_0 + -1))}", expr(), false, coli::p_uint8, &gaussian_coli);
input.set_access("{input[i2, i1, i0]->buff_input[i2, i1, i0]}");
int kernelx_extent_0 = 5;
coli::buffer buff_kernelx("buff_kernelx", 1, {coli::expr(kernelx_extent_0)}, coli::p_float32, NULL, coli::a_input, &gaussian_coli);
coli::computation kernelx("[kernelx_extent_0]->{kernelx[i0]: (0 <= i0 <= (kernelx_extent_0 + -1))}", expr(), false, coli::p_float32, &gaussian_coli);
kernelx.set_access("{kernelx[i0]->buff_kernelx[i0]}");
int kernely_extent_0 = 5;
coli::buffer buff_kernely("buff_kernely", 1, {coli::expr(kernely_extent_0)}, coli::p_float32, NULL, coli::a_input, &gaussian_coli);
coli::computation kernely("[kernely_extent_0]->{kernely[i0]: (0 <= i0 <= (kernely_extent_0 + -1))}", expr(), false, coli::p_float32, &gaussian_coli);
kernely.set_access("{kernely[i0]->buff_kernely[i0]}");
// Define temporary buffers for "gaussian_x".
coli::buffer buff_gaussian_x("buff_gaussian_x", 3, {coli::expr(gaussian_extent_2), (coli::expr(gaussian_extent_1) + coli::expr((int32_t)4)), coli::expr(gaussian_extent_0)}, coli::p_float32, NULL, coli::a_temporary, &gaussian_coli);
// Define loop bounds for dimension "gaussian_x_s0_c".
coli::constant gaussian_x_s0_c_loop_min("gaussian_x_s0_c_loop_min", coli::expr((int32_t)0), coli::p_int32, true, NULL, 0, &gaussian_coli);
coli::constant gaussian_x_s0_c_loop_extent("gaussian_x_s0_c_loop_extent", coli::expr(gaussian_extent_2), coli::p_int32, true, NULL, 0, &gaussian_coli);
// Define loop bounds for dimension "gaussian_x_s0_y".
coli::constant gaussian_x_s0_y_loop_min("gaussian_x_s0_y_loop_min", coli::expr((int32_t)0), coli::p_int32, true, NULL, 0, &gaussian_coli);
coli::constant gaussian_x_s0_y_loop_extent("gaussian_x_s0_y_loop_extent", (coli::expr(gaussian_extent_1) + coli::expr((int32_t)4)), coli::p_int32, true, NULL, 0, &gaussian_coli);
// Define loop bounds for dimension "gaussian_x_s0_x".
coli::constant gaussian_x_s0_x_loop_min("gaussian_x_s0_x_loop_min", coli::expr((int32_t)0), coli::p_int32, true, NULL, 0, &gaussian_coli);
coli::constant gaussian_x_s0_x_loop_extent("gaussian_x_s0_x_loop_extent", coli::expr(gaussian_extent_0), coli::p_int32, true, NULL, 0, &gaussian_coli);
coli::computation gaussian_x_s0("[gaussian_x_s0_c_loop_min, gaussian_x_s0_c_loop_extent, gaussian_x_s0_y_loop_min, gaussian_x_s0_y_loop_extent, gaussian_x_s0_x_loop_min, gaussian_x_s0_x_loop_extent]->{gaussian_x_s0[gaussian_x_s0_c, gaussian_x_s0_y, gaussian_x_s0_x]: "
"(gaussian_x_s0_c_loop_min <= gaussian_x_s0_c <= ((gaussian_x_s0_c_loop_min + gaussian_x_s0_c_loop_extent) + -1)) and (gaussian_x_s0_y_loop_min <= gaussian_x_s0_y <= ((gaussian_x_s0_y_loop_min + gaussian_x_s0_y_loop_extent) + -1)) and (gaussian_x_s0_x_loop_min <= gaussian_x_s0_x <= ((gaussian_x_s0_x_loop_min + gaussian_x_s0_x_loop_extent) + -1))}",
(((((coli::expr((float)0) + (coli::expr(coli::o_cast, coli::p_float32, input(coli::idx("gaussian_x_s0_c"), coli::idx("gaussian_x_s0_y"), (coli::idx("gaussian_x_s0_x") + coli::expr((int32_t)0))))*kernelx(coli::expr((int32_t)0)))) + (coli::expr(coli::o_cast, coli::p_float32, input(coli::idx("gaussian_x_s0_c"), coli::idx("gaussian_x_s0_y"), (coli::idx("gaussian_x_s0_x") + coli::expr((int32_t)1))))*kernelx(coli::expr((int32_t)1)))) + (coli::expr(coli::o_cast, coli::p_float32, input(coli::idx("gaussian_x_s0_c"), coli::idx("gaussian_x_s0_y"), (coli::idx("gaussian_x_s0_x") + coli::expr((int32_t)2))))*kernelx(coli::expr((int32_t)2)))) + (coli::expr(coli::o_cast, coli::p_float32, input(coli::idx("gaussian_x_s0_c"), coli::idx("gaussian_x_s0_y"), (coli::idx("gaussian_x_s0_x") + coli::expr((int32_t)3))))*kernelx(coli::expr((int32_t)3)))) + (coli::expr(coli::o_cast, coli::p_float32, input(coli::idx("gaussian_x_s0_c"), coli::idx("gaussian_x_s0_y"), (coli::idx("gaussian_x_s0_x") + coli::expr((int32_t)4))))*kernelx(coli::expr((int32_t)4)))), true, coli::p_float32, &gaussian_coli);
gaussian_x_s0.set_access("{gaussian_x_s0[gaussian_x_s0_c, gaussian_x_s0_y, gaussian_x_s0_x]->buff_gaussian_x[gaussian_x_s0_c, gaussian_x_s0_y, gaussian_x_s0_x]}");
// Define compute level for "gaussian_x".
gaussian_x_s0.first(computation::root_dimension);
// Define loop bounds for dimension "gaussian_s0_c".
coli::constant gaussian_s0_c_loop_min("gaussian_s0_c_loop_min", coli::expr((int32_t)0), coli::p_int32, true, NULL, 0, &gaussian_coli);
coli::constant gaussian_s0_c_loop_extent("gaussian_s0_c_loop_extent", coli::expr(gaussian_extent_2), coli::p_int32, true, NULL, 0, &gaussian_coli);
// Define loop bounds for dimension "gaussian_s0_y".
coli::constant gaussian_s0_y_loop_min("gaussian_s0_y_loop_min", coli::expr((int32_t)0), coli::p_int32, true, NULL, 0, &gaussian_coli);
coli::constant gaussian_s0_y_loop_extent("gaussian_s0_y_loop_extent", coli::expr(gaussian_extent_1), coli::p_int32, true, NULL, 0, &gaussian_coli);
// Define loop bounds for dimension "gaussian_s0_x".
coli::constant gaussian_s0_x_loop_min("gaussian_s0_x_loop_min", coli::expr((int32_t)0), coli::p_int32, true, NULL, 0, &gaussian_coli);
coli::constant gaussian_s0_x_loop_extent("gaussian_s0_x_loop_extent", coli::expr(gaussian_extent_0), coli::p_int32, true, NULL, 0, &gaussian_coli);
coli::computation gaussian_s0("[gaussian_s0_c_loop_min, gaussian_s0_c_loop_extent, gaussian_s0_y_loop_min, gaussian_s0_y_loop_extent, gaussian_s0_x_loop_min, gaussian_s0_x_loop_extent]->{gaussian_s0[gaussian_s0_c, gaussian_s0_y, gaussian_s0_x]: "
"(gaussian_s0_c_loop_min <= gaussian_s0_c <= ((gaussian_s0_c_loop_min + gaussian_s0_c_loop_extent) + -1)) and (gaussian_s0_y_loop_min <= gaussian_s0_y <= ((gaussian_s0_y_loop_min + gaussian_s0_y_loop_extent) + -1)) and (gaussian_s0_x_loop_min <= gaussian_s0_x <= ((gaussian_s0_x_loop_min + gaussian_s0_x_loop_extent) + -1))}",
coli::expr(coli::o_cast, coli::p_uint8, (((((coli::expr((float)0) + (gaussian_x_s0(coli::idx("gaussian_s0_c"), (coli::idx("gaussian_s0_y") + coli::expr((int32_t)0)), coli::idx("gaussian_s0_x"))*kernely(coli::expr((int32_t)0)))) + (gaussian_x_s0(coli::idx("gaussian_s0_c"), (coli::idx("gaussian_s0_y") + coli::expr((int32_t)1)), coli::idx("gaussian_s0_x"))*kernely(coli::expr((int32_t)1)))) + (gaussian_x_s0(coli::idx("gaussian_s0_c"), (coli::idx("gaussian_s0_y") + coli::expr((int32_t)2)), coli::idx("gaussian_s0_x"))*kernely(coli::expr((int32_t)2)))) + (gaussian_x_s0(coli::idx("gaussian_s0_c"), (coli::idx("gaussian_s0_y") + coli::expr((int32_t)3)), coli::idx("gaussian_s0_x"))*kernely(coli::expr((int32_t)3)))) + (gaussian_x_s0(coli::idx("gaussian_s0_c"), (coli::idx("gaussian_s0_y") + coli::expr((int32_t)4)), coli::idx("gaussian_s0_x"))*kernely(coli::expr((int32_t)4))))), true, coli::p_uint8, &gaussian_coli);
gaussian_s0.set_access("{gaussian_s0[gaussian_s0_c, gaussian_s0_y, gaussian_s0_x]->buff_gaussian[gaussian_s0_c, gaussian_s0_y, gaussian_s0_x]}");
// Define compute level for "gaussian".
gaussian_s0.after(gaussian_x_s0, computation::root_dimension);
// Add schedules.
gaussian_coli.set_arguments({&buff_input, &buff_kernelx, &buff_kernely, &buff_gaussian});
gaussian_coli.gen_time_processor_domain();
gaussian_coli.gen_isl_ast();
gaussian_coli.gen_halide_stmt();
gaussian_coli.dump_halide_stmt();
gaussian_coli.gen_halide_obj("build/generated_fct_gaussian_coli.o");
return 0;
}
<commit_msg>Call .first later<commit_after>#include <isl/set.h>
#include <isl/union_map.h>
#include <isl/union_set.h>
#include <isl/ast_build.h>
#include <isl/schedule.h>
#include <isl/schedule_node.h>
#include <coli/debug.h>
#include <coli/core.h>
#include <string.h>
#include <Halide.h>
#include "halide_image_io.h"
using namespace coli;
int main(int argc, char **argv)
{
// Set default coli options.
global::set_default_coli_options();
coli::function gaussian_coli("gaussian_coli");
Halide::Image<uint8_t> in_image = Halide::Tools::load_image("./images/rgb.png");
int SIZE0 = in_image.extent(0);
int SIZE1 = in_image.extent(1);
int SIZE2 = in_image.extent(2);
// Output buffers.
int gaussian_extent_2 = SIZE2;
int gaussian_extent_1 = SIZE1 - 8;
int gaussian_extent_0 = SIZE0 - 8;
coli::buffer buff_gaussian("buff_gaussian", 3, {coli::expr(gaussian_extent_2), coli::expr(gaussian_extent_1), coli::expr(gaussian_extent_0)}, coli::p_uint8, NULL, coli::a_output, &gaussian_coli);
// Input buffers.
int input_extent_2 = SIZE2;
int input_extent_1 = SIZE1;
int input_extent_0 = SIZE0;
coli::buffer buff_input("buff_input", 3, {coli::expr(input_extent_2), coli::expr(input_extent_1), coli::expr(input_extent_0)}, coli::p_uint8, NULL, coli::a_input, &gaussian_coli);
coli::computation input("[input_extent_2, input_extent_1, input_extent_0]->{input[i2, i1, i0]: (0 <= i2 <= (input_extent_2 + -1)) and (0 <= i1 <= (input_extent_1 + -1)) and (0 <= i0 <= (input_extent_0 + -1))}", expr(), false, coli::p_uint8, &gaussian_coli);
input.set_access("{input[i2, i1, i0]->buff_input[i2, i1, i0]}");
int kernelx_extent_0 = 5;
coli::buffer buff_kernelx("buff_kernelx", 1, {coli::expr(kernelx_extent_0)}, coli::p_float32, NULL, coli::a_input, &gaussian_coli);
coli::computation kernelx("[kernelx_extent_0]->{kernelx[i0]: (0 <= i0 <= (kernelx_extent_0 + -1))}", expr(), false, coli::p_float32, &gaussian_coli);
kernelx.set_access("{kernelx[i0]->buff_kernelx[i0]}");
int kernely_extent_0 = 5;
coli::buffer buff_kernely("buff_kernely", 1, {coli::expr(kernely_extent_0)}, coli::p_float32, NULL, coli::a_input, &gaussian_coli);
coli::computation kernely("[kernely_extent_0]->{kernely[i0]: (0 <= i0 <= (kernely_extent_0 + -1))}", expr(), false, coli::p_float32, &gaussian_coli);
kernely.set_access("{kernely[i0]->buff_kernely[i0]}");
// Define temporary buffers for "gaussian_x".
coli::buffer buff_gaussian_x("buff_gaussian_x", 3, {coli::expr(gaussian_extent_2), (coli::expr(gaussian_extent_1) + coli::expr((int32_t)4)), coli::expr(gaussian_extent_0)}, coli::p_float32, NULL, coli::a_temporary, &gaussian_coli);
// Define loop bounds for dimension "gaussian_x_s0_c".
coli::constant gaussian_x_s0_c_loop_min("gaussian_x_s0_c_loop_min", coli::expr((int32_t)0), coli::p_int32, true, NULL, 0, &gaussian_coli);
coli::constant gaussian_x_s0_c_loop_extent("gaussian_x_s0_c_loop_extent", coli::expr(gaussian_extent_2), coli::p_int32, true, NULL, 0, &gaussian_coli);
// Define loop bounds for dimension "gaussian_x_s0_y".
coli::constant gaussian_x_s0_y_loop_min("gaussian_x_s0_y_loop_min", coli::expr((int32_t)0), coli::p_int32, true, NULL, 0, &gaussian_coli);
coli::constant gaussian_x_s0_y_loop_extent("gaussian_x_s0_y_loop_extent", (coli::expr(gaussian_extent_1) + coli::expr((int32_t)4)), coli::p_int32, true, NULL, 0, &gaussian_coli);
// Define loop bounds for dimension "gaussian_x_s0_x".
coli::constant gaussian_x_s0_x_loop_min("gaussian_x_s0_x_loop_min", coli::expr((int32_t)0), coli::p_int32, true, NULL, 0, &gaussian_coli);
coli::constant gaussian_x_s0_x_loop_extent("gaussian_x_s0_x_loop_extent", coli::expr(gaussian_extent_0), coli::p_int32, true, NULL, 0, &gaussian_coli);
coli::computation gaussian_x_s0("[gaussian_x_s0_c_loop_min, gaussian_x_s0_c_loop_extent, gaussian_x_s0_y_loop_min, gaussian_x_s0_y_loop_extent, gaussian_x_s0_x_loop_min, gaussian_x_s0_x_loop_extent]->{gaussian_x_s0[gaussian_x_s0_c, gaussian_x_s0_y, gaussian_x_s0_x]: "
"(gaussian_x_s0_c_loop_min <= gaussian_x_s0_c <= ((gaussian_x_s0_c_loop_min + gaussian_x_s0_c_loop_extent) + -1)) and (gaussian_x_s0_y_loop_min <= gaussian_x_s0_y <= ((gaussian_x_s0_y_loop_min + gaussian_x_s0_y_loop_extent) + -1)) and (gaussian_x_s0_x_loop_min <= gaussian_x_s0_x <= ((gaussian_x_s0_x_loop_min + gaussian_x_s0_x_loop_extent) + -1))}",
(((((coli::expr((float)0) + (coli::expr(coli::o_cast, coli::p_float32, input(coli::idx("gaussian_x_s0_c"), coli::idx("gaussian_x_s0_y"), (coli::idx("gaussian_x_s0_x") + coli::expr((int32_t)0))))*kernelx(coli::expr((int32_t)0)))) + (coli::expr(coli::o_cast, coli::p_float32, input(coli::idx("gaussian_x_s0_c"), coli::idx("gaussian_x_s0_y"), (coli::idx("gaussian_x_s0_x") + coli::expr((int32_t)1))))*kernelx(coli::expr((int32_t)1)))) + (coli::expr(coli::o_cast, coli::p_float32, input(coli::idx("gaussian_x_s0_c"), coli::idx("gaussian_x_s0_y"), (coli::idx("gaussian_x_s0_x") + coli::expr((int32_t)2))))*kernelx(coli::expr((int32_t)2)))) + (coli::expr(coli::o_cast, coli::p_float32, input(coli::idx("gaussian_x_s0_c"), coli::idx("gaussian_x_s0_y"), (coli::idx("gaussian_x_s0_x") + coli::expr((int32_t)3))))*kernelx(coli::expr((int32_t)3)))) + (coli::expr(coli::o_cast, coli::p_float32, input(coli::idx("gaussian_x_s0_c"), coli::idx("gaussian_x_s0_y"), (coli::idx("gaussian_x_s0_x") + coli::expr((int32_t)4))))*kernelx(coli::expr((int32_t)4)))), true, coli::p_float32, &gaussian_coli);
gaussian_x_s0.set_access("{gaussian_x_s0[gaussian_x_s0_c, gaussian_x_s0_y, gaussian_x_s0_x]->buff_gaussian_x[gaussian_x_s0_c, gaussian_x_s0_y, gaussian_x_s0_x]}");
// Define loop bounds for dimension "gaussian_s0_c".
coli::constant gaussian_s0_c_loop_min("gaussian_s0_c_loop_min", coli::expr((int32_t)0), coli::p_int32, true, NULL, 0, &gaussian_coli);
coli::constant gaussian_s0_c_loop_extent("gaussian_s0_c_loop_extent", coli::expr(gaussian_extent_2), coli::p_int32, true, NULL, 0, &gaussian_coli);
// Define loop bounds for dimension "gaussian_s0_y".
coli::constant gaussian_s0_y_loop_min("gaussian_s0_y_loop_min", coli::expr((int32_t)0), coli::p_int32, true, NULL, 0, &gaussian_coli);
coli::constant gaussian_s0_y_loop_extent("gaussian_s0_y_loop_extent", coli::expr(gaussian_extent_1), coli::p_int32, true, NULL, 0, &gaussian_coli);
// Define loop bounds for dimension "gaussian_s0_x".
coli::constant gaussian_s0_x_loop_min("gaussian_s0_x_loop_min", coli::expr((int32_t)0), coli::p_int32, true, NULL, 0, &gaussian_coli);
coli::constant gaussian_s0_x_loop_extent("gaussian_s0_x_loop_extent", coli::expr(gaussian_extent_0), coli::p_int32, true, NULL, 0, &gaussian_coli);
coli::computation gaussian_s0("[gaussian_s0_c_loop_min, gaussian_s0_c_loop_extent, gaussian_s0_y_loop_min, gaussian_s0_y_loop_extent, gaussian_s0_x_loop_min, gaussian_s0_x_loop_extent]->{gaussian_s0[gaussian_s0_c, gaussian_s0_y, gaussian_s0_x]: "
"(gaussian_s0_c_loop_min <= gaussian_s0_c <= ((gaussian_s0_c_loop_min + gaussian_s0_c_loop_extent) + -1)) and (gaussian_s0_y_loop_min <= gaussian_s0_y <= ((gaussian_s0_y_loop_min + gaussian_s0_y_loop_extent) + -1)) and (gaussian_s0_x_loop_min <= gaussian_s0_x <= ((gaussian_s0_x_loop_min + gaussian_s0_x_loop_extent) + -1))}",
coli::expr(coli::o_cast, coli::p_uint8, (((((coli::expr((float)0) + (gaussian_x_s0(coli::idx("gaussian_s0_c"), (coli::idx("gaussian_s0_y") + coli::expr((int32_t)0)), coli::idx("gaussian_s0_x"))*kernely(coli::expr((int32_t)0)))) + (gaussian_x_s0(coli::idx("gaussian_s0_c"), (coli::idx("gaussian_s0_y") + coli::expr((int32_t)1)), coli::idx("gaussian_s0_x"))*kernely(coli::expr((int32_t)1)))) + (gaussian_x_s0(coli::idx("gaussian_s0_c"), (coli::idx("gaussian_s0_y") + coli::expr((int32_t)2)), coli::idx("gaussian_s0_x"))*kernely(coli::expr((int32_t)2)))) + (gaussian_x_s0(coli::idx("gaussian_s0_c"), (coli::idx("gaussian_s0_y") + coli::expr((int32_t)3)), coli::idx("gaussian_s0_x"))*kernely(coli::expr((int32_t)3)))) + (gaussian_x_s0(coli::idx("gaussian_s0_c"), (coli::idx("gaussian_s0_y") + coli::expr((int32_t)4)), coli::idx("gaussian_s0_x"))*kernely(coli::expr((int32_t)4))))), true, coli::p_uint8, &gaussian_coli);
gaussian_s0.set_access("{gaussian_s0[gaussian_s0_c, gaussian_s0_y, gaussian_s0_x]->buff_gaussian[gaussian_s0_c, gaussian_s0_y, gaussian_s0_x]}");
// Define compute level for "gaussian_x".
gaussian_x_s0.first(computation::root_dimension);
// Define compute level for "gaussian".
gaussian_s0.after(gaussian_x_s0, computation::root_dimension);
// Add schedules.
gaussian_coli.set_arguments({&buff_input, &buff_kernelx, &buff_kernely, &buff_gaussian});
gaussian_coli.gen_time_processor_domain();
gaussian_coli.gen_isl_ast();
gaussian_coli.gen_halide_stmt();
gaussian_coli.dump_halide_stmt();
gaussian_coli.gen_halide_obj("build/generated_fct_gaussian_coli.o");
return 0;
}
<|endoftext|>
|
<commit_before>#include "Halide.h"
using namespace Halide;
constexpr auto block_size = 16;
int main(int argc, char **argv) {
ImageParam in(Float(32), 2, "input");
float alpha = 0.3;
float beta = 0.4;
Func heat2d("heat2dgpu");
Var x("x"), y("y"), x0, y0, x1, y1, rx0, ry0, rx1, ry1;
RDom r(1, in.width()-2, 1, in.height()-2);
heat2d(x, y) = 0.0f;
heat2d(r.x, r.y) = alpha * in(r.x, r.y) +
beta * (in(r.x+1, r.y) + in(r.x-1, r.y) + in(r.x, r.y+1) + in(r.x, r.y-1));
heat2d.gpu_tile(x, y, x0, y0, x1, y1, block_size, block_size);
heat2d.update().gpu_tile(r.x, r.y, block_size, block_size);
Halide::Target target = Halide::get_host_target();
target.set_feature(Target::Feature::CUDA, true);
heat2d.compile_to_object("build/generated_fct_heat2dgpu_ref.o",
{in},
"heat2d_ref",
target);
heat2d.compile_to_lowered_stmt("build/generated_fct_heat2dgpu_ref.txt",
{in},
Text,
target);
return 0;
}
<commit_msg>fixed heat2dgpu<commit_after>#include "Halide.h"
using namespace Halide;
constexpr auto block_size = 16;
int main(int argc, char **argv) {
ImageParam in(Float(32), 2, "input");
float alpha = 0.3;
float beta = 0.4;
Func heat2d("heat2dgpu");
Var x("x"), y("y"), x0, y0, x1, y1, rx0, ry0, rx1, ry1;
RDom r(1, in.width()-2, 1, in.height()-2);
heat2d(x, y) = 0.0f;
heat2d(r.x, r.y) = alpha * in(r.x, r.y) +
beta * (in(r.x+1, r.y) + in(r.x-1, r.y) + in(r.x, r.y+1) + in(r.x, r.y-1));
heat2d.gpu_tile(x, y, x0, y0, x1, y1, block_size, block_size);
heat2d.update().gpu_tile(r.x, r.y, block_size, block_size);
Halide::Target target = Halide::get_host_target();
target.set_feature(Target::Feature::CUDA, true);
heat2d.compile_to_object("build/generated_fct_heat2dgpu_ref.o",
{in},
"heat2dgpu_ref",
target);
heat2d.compile_to_lowered_stmt("build/generated_fct_heat2dgpu_ref.txt",
{in},
Text,
target);
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2016 neurodata (http://neurodata.io/)
* Written by Disa Mhembere (disa@jhu.edu)
*
* This file is part of knor
*
* 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 CURRENT_KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <random>
#include <stdexcept>
#include "gmeans_coordinator.hpp"
#include "gmeans.hpp"
#include "io.hpp"
#include "clusters.hpp"
#include "linalg.hpp"
#include "AndersonDarling.hpp"
#include "hclust_id_generator.hpp"
#include "thd_safe_bool_vector.hpp"
namespace knor {
gmeans_coordinator::gmeans_coordinator(const std::string fn,
const size_t nrow,
const size_t ncol, const unsigned k, const unsigned max_iters,
const unsigned nnodes, const unsigned nthreads,
const double* centers, const base::init_t it,
const double tolerance, const base::dist_t dt,
const unsigned min_clust_size, const short strictness) :
xmeans_coordinator(fn, nrow, ncol, k, max_iters, nnodes, nthreads,
centers, it, tolerance, dt, min_clust_size),
strictness(strictness) {
}
void gmeans_coordinator::deactivate(const unsigned id) {
cltr_active_vec->check_set(id, false);
}
void gmeans_coordinator::activate(const unsigned id) {
cltr_active_vec->check_set(id, true);
if (id > 0)
curr_nclust++;
}
void gmeans_coordinator::build_thread_state() {
// NUMA node affinity binding policy is round-robin
unsigned thds_row = nrow / nthreads;
for (unsigned thd_id = 0; thd_id < nthreads; thd_id++) {
std::pair<unsigned, unsigned> tup = get_rid_len_tup(thd_id);
thd_max_row_idx.push_back((thd_id*thds_row) + tup.second);
threads.push_back(gmeans::create((thd_id % nnodes),
thd_id, tup.first, tup.second,
ncol, k, hcltrs, &cluster_assignments[0], fn,
_dist_t, cltr_active_vec, partition_dist, nearest_cdist,
compute_pdist));
threads[thd_id]->set_parent_cond(&cond);
threads[thd_id]->set_parent_pending_threads(&pending_threads);
threads[thd_id]->start(WAIT); // Thread puts itself to sleep
std::static_pointer_cast<gmeans>(threads[thd_id])
->set_part_id(&part_id[0]);
std::static_pointer_cast<gmeans>(threads[thd_id])
->set_g_clusters(cltrs);
}
}
void gmeans_coordinator::assemble_ad_vecs(std::unordered_map<unsigned,
std::vector<double>>& ad_vecs) {
for (size_t i = 0; i < nearest_cdist.size(); i++) {
ad_vecs[part_id[i]].push_back(nearest_cdist[i]);
}
}
void gmeans_coordinator::compute_ad_stats(
std::unordered_map<unsigned, std::vector<double>>& ad_vecs) {
std::vector<unsigned> keys;
for (auto const& kv : ad_vecs)
keys.push_back(kv.first);
std::vector<double> scores(keys.size());
#pragma omp parallel for
for (size_t idx = 0; idx < keys.size(); idx++) {
double score = base::AndersonDarling::compute_statistic(
ad_vecs[keys[idx]].size(), &(ad_vecs[keys[idx]][0]));
scores[idx] = score;
}
// NOTE: We push the score onto the back
for (size_t idx = 0; idx < keys.size(); idx++)
ad_vecs[keys[idx]].push_back(scores[idx]);
}
// NOTE: This modifies hcltrs
void gmeans_coordinator::partition_decision() {
// Each Anderson Darling (AD) vector represents the vector for which
// each cluster gets its AD statistic.
std::unordered_map<unsigned, std::vector<double>> ad_vecs;
std::vector<double> critical_values;
// Populate the AD vectors
assemble_ad_vecs(ad_vecs);
for (auto& kv : ad_vecs) {
base::linalg::scale(&(kv.second)[0], kv.second.size());
}
// Compute Critical values
base::AndersonDarling::compute_critical_values(
ad_vecs.size(), critical_values);
// Compute AD statistics
compute_ad_stats(ad_vecs);
std::vector<size_t> keys;
hcltrs.get_keys(keys);
std::vector<bool> revert_cache;
auto max_pid = (*std::max_element(keys.begin(), keys.end()));
revert_cache.assign(max_pid+1, false);
// NOTE: We use ad_vecs.back() to store the score
for (size_t i = 0; i < keys.size(); i++) {
unsigned pid = keys[i];
auto const& v = ad_vecs[pid];
auto score = ad_vecs[pid].back();
if (score <= critical_values[strictness]) {
unsigned lid = hcltrs[pid]->get_zeroid();
unsigned rid = hcltrs[pid]->get_oneid();
// Deactivate both lid and rid
deactivate(lid); deactivate(rid);
// Deactivate pid
deactivate(pid);
revert_cache[pid] = true;
hcltrs.erase(pid);
// We can reuse these children ids
ider->reclaim_id(lid);
ider->reclaim_id(rid);
curr_nclust -= 2;
final_centroids[pid] = std::vector<double>(
cltrs->get_mean_rawptr(pid),
cltrs->get_mean_rawptr(pid) + ncol);
cluster_assignment_counts[pid] =
cluster_assignment_counts[lid] + cluster_assignment_counts[rid];
cluster_assignment_counts[lid] = cluster_assignment_counts[rid] = 0;
}
}
// Assemble cluster membership
// TODO: Use dynamic or guided scheduler
#ifdef _OPENMP
#pragma omp parallel for default(shared) firstprivate(revert_cache)
#endif
for (size_t rid = 0; rid < nrow; rid++) {
auto pid = part_id[rid];
// Ignore keys outside in hcltrs
if (pid < revert_cache.size() && revert_cache[pid]) {
// Means that row assignments needs to be reverted to part_id
cluster_assignments[rid] = pid;
}
}
}
void gmeans_coordinator::compute_cluster_diffs() {
auto itr = hcltrs.get_iterator();
while (itr.has_next()) {
auto kv = itr.next();
auto c = std::static_pointer_cast<base::h_clusters>(kv.second);
c->metadata.resize(ncol+1); // +1th index stores the divisor
// Compute difference
for (size_t i = 0; i < ncol; i++)
base::linalg::vdiff(c->get_mean_rawptr(0),
c->get_mean_rawptr(1), ncol, c->metadata);
// Compute v.dot(v)
c->metadata[ncol] = base::linalg::dot(&c->metadata[0],
&c->metadata[0], ncol); // NOTE: last element intentionally ignored
}
}
// Main driver
base::cluster_t gmeans_coordinator::run(
double* allocd_data, const bool numa_opt) {
#ifdef PROFILER
ProfilerStart("gmeans_coordinator.perf");
#endif
build_thread_state();
if (!numa_opt && NULL == allocd_data) {
wake4run(ALLOC_DATA);
wait4complete();
} else if (allocd_data) { // No NUMA opt
set_thread_data_ptr(allocd_data);
}
struct timeval start, end;
gettimeofday(&start , NULL);
run_hinit(); // Initialize clusters
// Run loop
size_t iter = 0;
while (true) {
// TODO: Do this simultaneously with H_EM step
wake4run(MEAN);
wait4complete();
combine_partition_means();
compute_pdist = true;
for (iter = 0; iter < max_iters; iter++) {
#ifndef BIND
printf("\nNCLUST: %lu, Iteration: %lu\n", curr_nclust, iter);
#endif
// Now pick between the cluster splits
wake4run(H_EM);
wait4complete();
update_clusters();
#ifndef BIND
printf("\nAssignment counts:\n");
base::sparse_print(cluster_assignment_counts);
printf("\n*****************************************************\n");
#endif
if (compute_pdist)
compute_pdist = false;
}
compute_cluster_diffs();
wake4run(H_SPLIT);
wait4complete();
// Decide on split or not here
partition_decision();
if (at_cluster_cap()) {
#ifndef BIND
printf("\n\nCLUSTER SIZE EXIT @ %lu!\n", curr_nclust);
#endif
break;
}
// Update global state
init_splits(); // Initialize possible splits
// Break when clusters are inactive due to size
if (hcltrs.keyless()) {
assert(steady_state()); // NOTE: Comment when benchmarking
#ifndef BIND
printf("\n\nSTEADY STATE EXIT!\n");
#endif
break;
}
}
complete_final_centroids();
#ifdef PROFILER
ProfilerStop();
#endif
gettimeofday(&end, NULL);
#ifndef BIND
printf("\n\nAlgorithmic time taken = %.6f sec\n",
base::time_diff(start, end));
printf("\n******************************************\n");
verify_consistency();
#endif
#ifndef BIND
printf("Final cluster counts: \n");
base::sparse_print(cluster_assignment_counts);
//printf("Final centroids\n");
//for (auto const& kv : final_centroids) {
//printf("k: %u, v: ", kv.first); base::print(kv.second);
//}
printf("\n******************************************\n");
#endif
return base::cluster_t(this->nrow, this->ncol, iter,
cluster_assignments, cluster_assignment_counts,
final_centroids);
}
} // End namespace knor
<commit_msg>remove unused<commit_after>/*
* Copyright 2016 neurodata (http://neurodata.io/)
* Written by Disa Mhembere (disa@jhu.edu)
*
* This file is part of knor
*
* 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 CURRENT_KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <random>
#include <stdexcept>
#include "gmeans_coordinator.hpp"
#include "gmeans.hpp"
#include "io.hpp"
#include "clusters.hpp"
#include "linalg.hpp"
#include "AndersonDarling.hpp"
#include "hclust_id_generator.hpp"
#include "thd_safe_bool_vector.hpp"
namespace knor {
gmeans_coordinator::gmeans_coordinator(const std::string fn,
const size_t nrow,
const size_t ncol, const unsigned k, const unsigned max_iters,
const unsigned nnodes, const unsigned nthreads,
const double* centers, const base::init_t it,
const double tolerance, const base::dist_t dt,
const unsigned min_clust_size, const short strictness) :
xmeans_coordinator(fn, nrow, ncol, k, max_iters, nnodes, nthreads,
centers, it, tolerance, dt, min_clust_size),
strictness(strictness) {
}
void gmeans_coordinator::deactivate(const unsigned id) {
cltr_active_vec->check_set(id, false);
}
void gmeans_coordinator::activate(const unsigned id) {
cltr_active_vec->check_set(id, true);
if (id > 0)
curr_nclust++;
}
void gmeans_coordinator::build_thread_state() {
// NUMA node affinity binding policy is round-robin
unsigned thds_row = nrow / nthreads;
for (unsigned thd_id = 0; thd_id < nthreads; thd_id++) {
std::pair<unsigned, unsigned> tup = get_rid_len_tup(thd_id);
thd_max_row_idx.push_back((thd_id*thds_row) + tup.second);
threads.push_back(gmeans::create((thd_id % nnodes),
thd_id, tup.first, tup.second,
ncol, k, hcltrs, &cluster_assignments[0], fn,
_dist_t, cltr_active_vec, partition_dist, nearest_cdist,
compute_pdist));
threads[thd_id]->set_parent_cond(&cond);
threads[thd_id]->set_parent_pending_threads(&pending_threads);
threads[thd_id]->start(WAIT); // Thread puts itself to sleep
std::static_pointer_cast<gmeans>(threads[thd_id])
->set_part_id(&part_id[0]);
std::static_pointer_cast<gmeans>(threads[thd_id])
->set_g_clusters(cltrs);
}
}
void gmeans_coordinator::assemble_ad_vecs(std::unordered_map<unsigned,
std::vector<double>>& ad_vecs) {
for (size_t i = 0; i < nearest_cdist.size(); i++) {
ad_vecs[part_id[i]].push_back(nearest_cdist[i]);
}
}
void gmeans_coordinator::compute_ad_stats(
std::unordered_map<unsigned, std::vector<double>>& ad_vecs) {
std::vector<unsigned> keys;
for (auto const& kv : ad_vecs)
keys.push_back(kv.first);
std::vector<double> scores(keys.size());
#pragma omp parallel for
for (size_t idx = 0; idx < keys.size(); idx++) {
double score = base::AndersonDarling::compute_statistic(
ad_vecs[keys[idx]].size(), &(ad_vecs[keys[idx]][0]));
scores[idx] = score;
}
// NOTE: We push the score onto the back
for (size_t idx = 0; idx < keys.size(); idx++)
ad_vecs[keys[idx]].push_back(scores[idx]);
}
// NOTE: This modifies hcltrs
void gmeans_coordinator::partition_decision() {
// Each Anderson Darling (AD) vector represents the vector for which
// each cluster gets its AD statistic.
std::unordered_map<unsigned, std::vector<double>> ad_vecs;
std::vector<double> critical_values;
// Populate the AD vectors
assemble_ad_vecs(ad_vecs);
for (auto& kv : ad_vecs) {
base::linalg::scale(&(kv.second)[0], kv.second.size());
}
// Compute Critical values
base::AndersonDarling::compute_critical_values(
ad_vecs.size(), critical_values);
// Compute AD statistics
compute_ad_stats(ad_vecs);
std::vector<size_t> keys;
hcltrs.get_keys(keys);
std::vector<bool> revert_cache;
auto max_pid = (*std::max_element(keys.begin(), keys.end()));
revert_cache.assign(max_pid+1, false);
// NOTE: We use ad_vecs.back() to store the score
for (size_t i = 0; i < keys.size(); i++) {
unsigned pid = keys[i];
auto score = ad_vecs[pid].back();
if (score <= critical_values[strictness]) {
unsigned lid = hcltrs[pid]->get_zeroid();
unsigned rid = hcltrs[pid]->get_oneid();
// Deactivate both lid and rid
deactivate(lid); deactivate(rid);
// Deactivate pid
deactivate(pid);
revert_cache[pid] = true;
hcltrs.erase(pid);
// We can reuse these children ids
ider->reclaim_id(lid);
ider->reclaim_id(rid);
curr_nclust -= 2;
final_centroids[pid] = std::vector<double>(
cltrs->get_mean_rawptr(pid),
cltrs->get_mean_rawptr(pid) + ncol);
cluster_assignment_counts[pid] =
cluster_assignment_counts[lid] + cluster_assignment_counts[rid];
cluster_assignment_counts[lid] = cluster_assignment_counts[rid] = 0;
}
}
// Assemble cluster membership
// TODO: Use dynamic or guided scheduler
#ifdef _OPENMP
#pragma omp parallel for default(shared) firstprivate(revert_cache)
#endif
for (size_t rid = 0; rid < nrow; rid++) {
auto pid = part_id[rid];
// Ignore keys outside in hcltrs
if (pid < revert_cache.size() && revert_cache[pid]) {
// Means that row assignments needs to be reverted to part_id
cluster_assignments[rid] = pid;
}
}
}
void gmeans_coordinator::compute_cluster_diffs() {
auto itr = hcltrs.get_iterator();
while (itr.has_next()) {
auto kv = itr.next();
auto c = std::static_pointer_cast<base::h_clusters>(kv.second);
c->metadata.resize(ncol+1); // +1th index stores the divisor
// Compute difference
for (size_t i = 0; i < ncol; i++)
base::linalg::vdiff(c->get_mean_rawptr(0),
c->get_mean_rawptr(1), ncol, c->metadata);
// Compute v.dot(v)
c->metadata[ncol] = base::linalg::dot(&c->metadata[0],
&c->metadata[0], ncol); // NOTE: last element intentionally ignored
}
}
// Main driver
base::cluster_t gmeans_coordinator::run(
double* allocd_data, const bool numa_opt) {
#ifdef PROFILER
ProfilerStart("gmeans_coordinator.perf");
#endif
build_thread_state();
if (!numa_opt && NULL == allocd_data) {
wake4run(ALLOC_DATA);
wait4complete();
} else if (allocd_data) { // No NUMA opt
set_thread_data_ptr(allocd_data);
}
struct timeval start, end;
gettimeofday(&start , NULL);
run_hinit(); // Initialize clusters
// Run loop
size_t iter = 0;
while (true) {
// TODO: Do this simultaneously with H_EM step
wake4run(MEAN);
wait4complete();
combine_partition_means();
compute_pdist = true;
for (iter = 0; iter < max_iters; iter++) {
#ifndef BIND
printf("\nNCLUST: %lu, Iteration: %lu\n", curr_nclust, iter);
#endif
// Now pick between the cluster splits
wake4run(H_EM);
wait4complete();
update_clusters();
#ifndef BIND
printf("\nAssignment counts:\n");
base::sparse_print(cluster_assignment_counts);
printf("\n*****************************************************\n");
#endif
if (compute_pdist)
compute_pdist = false;
}
compute_cluster_diffs();
wake4run(H_SPLIT);
wait4complete();
// Decide on split or not here
partition_decision();
if (at_cluster_cap()) {
#ifndef BIND
printf("\n\nCLUSTER SIZE EXIT @ %lu!\n", curr_nclust);
#endif
break;
}
// Update global state
init_splits(); // Initialize possible splits
// Break when clusters are inactive due to size
if (hcltrs.keyless()) {
assert(steady_state()); // NOTE: Comment when benchmarking
#ifndef BIND
printf("\n\nSTEADY STATE EXIT!\n");
#endif
break;
}
}
complete_final_centroids();
#ifdef PROFILER
ProfilerStop();
#endif
gettimeofday(&end, NULL);
#ifndef BIND
printf("\n\nAlgorithmic time taken = %.6f sec\n",
base::time_diff(start, end));
printf("\n******************************************\n");
verify_consistency();
#endif
#ifndef BIND
printf("Final cluster counts: \n");
base::sparse_print(cluster_assignment_counts);
//printf("Final centroids\n");
//for (auto const& kv : final_centroids) {
//printf("k: %u, v: ", kv.first); base::print(kv.second);
//}
printf("\n******************************************\n");
#endif
return base::cluster_t(this->nrow, this->ncol, iter,
cluster_assignments, cluster_assignment_counts,
final_centroids);
}
} // End namespace knor
<|endoftext|>
|
<commit_before>#include <unit_test_merge_text.h>
#include <utils_merge_text.h>
#include <vector>
#include <iostream>
REGISTRY_UNIT_TEST(UnitTestMergeText)
UnitTestMergeText::UnitTestMergeText()
: UnitTestBase("UnitTestMergeText") {
//
}
// ---------------------------------------------------------------------
void UnitTestMergeText::init() {
}
// ---------------------------------------------------------------------
bool UnitTestMergeText::run() {
struct LTest {
LTest(
std::string txt1,
std::string txt2,
std::string txt3,
std::vector<UtilsMergeTextRow *> arr1,
std::vector<UtilsMergeTextRow *> arr2,
unsigned int n
) : txt1(txt1), txt2(txt2), txt3(txt3), arr1(arr1), arr2(arr2), n(n) {
//
}
std::string txt1;
std::string txt2;
std::string txt3;
std::vector<UtilsMergeTextRow *> arr1;
std::vector<UtilsMergeTextRow *> arr2;
unsigned int n;
};
std::vector<LTest *> tests1;
std::vector<UtilsMergeTextRow *> arr1, arr2;
std::string text1 = text001();
std::string text2 = text002();
// std::cout << text1.toStdString() << "\n";
//empty (Test №1)
tests1.push_back(new LTest("", "", "", arr1, arr2, 0));
//without any difference (Test №2)
tests1.push_back(new LTest("I\r\ngot\r\nMike", "I\r\ngot\r\nMike", "I\r\ngot\r\nMike", arr1, arr2, 0));
//with a difference in the ending (Tests №3-6)
tests1.push_back(new LTest("I/got/Mike", "I/got/Mike", "I/got/Nike", arr1, arr2, 1));
tests1.push_back(new LTest("I/got/Nike", "I/got/Mike", "I/got/Mike", arr1, arr2, 1));
tests1.push_back(new LTest("I/got/Nike", "I/got/Mike", "I/got/Nike", arr1, arr2, 1));
tests1.push_back(new LTest("I/got/Bike", "I/got/Mike", "I/got/Nike", arr1, arr2, 1));
//with a difference in the beginning (Tests №7-10)
tests1.push_back(new LTest("I/got/Mike", "I/got/Mike", "You/got/Mike", arr1, arr2, 1));
tests1.push_back(new LTest("You/got/Mike", "I/got/Mike", "I/got/Mike", arr1, arr2, 1));
tests1.push_back(new LTest("You/got/Mike", "I/got/Mike", "You/got/Mike", arr1, arr2, 1));
tests1.push_back(new LTest("We/got/Mike", "I/got/Mike", "You/got/Mike", arr1, arr2, 1));
//with a difference in the middle of the row (Tests №11-15)
tests1.push_back(new LTest("I/have/cute/cats", "I/have/cute/cats", "I/have/huge/cats", arr1, arr2, 1));
tests1.push_back(new LTest("I/have/huge/cats", "I/have/cute/cats", "I/have/cute/cats", arr1, arr2, 1));
tests1.push_back(new LTest("I/have/huge/cats", "I/have/cute/cats", "I/have/huge/cats", arr1, arr2, 1));
tests1.push_back(new LTest("I/have/difference/cats", "I/have/cute/cats", "I/have/huge/cats", arr1, arr2, 1));
tests1.push_back(new LTest("I/betray/cats", "I/have/cats", "I/love/cats", arr1, arr2, 1));
//delete lines from the end of text (Tests №16-19)
tests1.push_back(new LTest("Go\r\nto\r\nthe\r\nschool", "Go\r\nto\r\nthe\r\nschool", "Go\r\nto", arr1, arr2, 2));
tests1.push_back(new LTest("Go/to", "Go/to/the/school", "Go/to/the/school", arr1, arr2, 2));
tests1.push_back(new LTest("Go/to/the", "Go/to/the/school", "Go/to", arr1, arr2, 2));
tests1.push_back(new LTest("Go/to", "Go/to/the/school", "Go/to/the", arr1, arr2, 2));
//add lines in the end of text (Tests №20-23)
tests1.push_back(new LTest("Go/to", "Go/to", "Go/to/the/school", arr1, arr2, 2));
tests1.push_back(new LTest("Go/to/the/school", "Go/to", "Go/to", arr1, arr2, 2));
tests1.push_back(new LTest("Go/to/the", "Go/to", "Go/to/the/school", arr1, arr2, 2));
tests1.push_back(new LTest("Go/to/the/school", "Go/to", "Go/to/the", arr1, arr2, 2));
//delete rows from the beginning and the middle of text (Tests №24-27)
tests1.push_back(new LTest("Go/to/the/school", "Go/to/the/school", "the/school", arr1, arr2, 2));
tests1.push_back(new LTest("the/school", "Go/to/the/school", "Go/to/the/school", arr1, arr2, 2));
tests1.push_back(new LTest("Go/to/the/school", "Go/to/the/school", "Go/to/school", arr1, arr2, 1));
tests1.push_back(new LTest("Go/to/school", "Go/to/the/school", "Go/to/the/school", arr1, arr2, 1));
//add rows to the beginning and the middle of text (Tests №28-31)
tests1.push_back(new LTest("the/school", "the/school", "Go/to/the/school", arr1, arr2, 2));
tests1.push_back(new LTest("Go/to/the/school", "the/school", "the/school", arr1, arr2, 2));
tests1.push_back(new LTest("Go/the/school", "the/school", "the/school", arr1, arr2, 1));
tests1.push_back(new LTest("the/school", "the/school", "Go/the/school", arr1, arr2, 1));
//complex (Tests №32-33)
tests1.push_back(new LTest("You/are/got/and/good", "I/got/Mike/and/this is/good/boy", "I/cure/damn/ill/cancer", arr1, arr2, 8));
tests1.push_back(new LTest("We/spent/the rest/of our life/on/this/course/work", "We/spent/a lot of/time/on/this/course/work", "We/gonna/spend/a lot of/funky/time/on/course/work", arr1, arr2, 6));
unsigned int nSuccess = 0;
for (unsigned int i = 0; i < tests1.size(); i++){
std::string txt1 = tests1[i]->txt1;
std::string txt2 = tests1[i]->txt2;
std::string txt3 = tests1[i]->txt3;
UtilsMergeText::merge(txt1, txt2, txt3, arr1, arr2);
unsigned int n = tests1[i]->n;
if(arr1.size()==n) {
nSuccess++;
} else {
Log::err(TAG, "In the test №" + std::to_string(i + 1) + " the length of the vector is expected: "
+ std::to_string(n) + ", but obtained: " + std::to_string(arr1.size()));
}
arr1.clear(), arr2.clear();
}
//sort module test
struct LTest2 {
LTest2(
std::string txt1,
std::string txt2,
std::string txt3,
std::vector<UtilsMergeTextRow *> arr1,
std::vector<UtilsMergeTextRow *> arr2,
std::vector<UtilsMergeTextRow *> arr3
) : txt1(txt1), txt2(txt2), txt3(txt3), arr1(arr1), arr2(arr2), arr3(arr3) {
//
}
std::string txt1;
std::string txt2;
std::string txt3;
std::vector<UtilsMergeTextRow *> arr1;
std::vector<UtilsMergeTextRow *> arr2;
std::vector<UtilsMergeTextRow *> arr3;
};
std::vector<LTest2 *> tests2;
std::vector<UtilsMergeTextRow *> arr3;
int id[8] = {0,1,1,2,3,4,5,6};
std::vector<std::string> skey;
skey.push_back("I");
skey.push_back("got");
skey.push_back("!add");
skey.push_back("Mike");
skey.push_back("and");
skey.push_back("this is");
skey.push_back("!del");
skey.push_back("!del");
std::vector<std::string> sline;
sline.push_back("You");
sline.push_back("cure");
sline.push_back("are");
sline.push_back("damn");
sline.push_back("ill");
sline.push_back("cancer");
sline.push_back("good");
sline.push_back("boy");
for(int i=0;i<skey.size();++i) arr3.push_back(new UtilsMergeTextRow(id[i], skey.at(i), sline.at(i)));
tests2.push_back(new LTest2(
"You\r\nare\r\ngot\r\nand\r\ngood",
"I\r\ngot\r\nMike\r\nand\r\nthis is\r\ngood\r\nboy",
"I\r\ncure\r\ndamn\r\nill\r\ncancer",
arr1, arr2, arr3));
std::string txt1 = tests2[0]->txt1;
std::string txt2 = tests2[0]->txt2;
std::string txt3 = tests2[0]->txt3;
UtilsMergeText::merge(txt1, txt2, txt3, arr1, arr2);
unsigned int Success = 0;
for (int i = 0; i < 8; ++i) {
int id1 = arr1.at(i)->id;
int id2 = arr3.at(i)->id;
std::string key1 = arr1.at(i)->key;
std::string key2 = arr3.at(i)->key;
std::string line1 = arr1.at(i)->line;
std::string line2 = arr3.at(i)->line;
if (id1==id2 && key1==key2 && line1==line2) {
Success+=1;
} else {
Log::info(TAG, "In the sort test in the element №" + std::to_string(i+1) + ":");
if (id1!=id2) {
Log::err(TAG, "expected id: '" + std::to_string(id2) + "', but obtained: '" + std::to_string(id1) + "'");
}
if (key1!=key2) {
Log::err(TAG, "expected key: '" + key2 + "', but obtained: '" + key1 + "'");
}
if (line1!=line2) {
Log::err(TAG, "expected line: '" + line2 + "', but obtained: '" + line1 + "'");
}
}
}
if (Success == 8) {
nSuccess++;
}
return nSuccess == tests1.size() + 1;
}
// ---------------------------------------------------------------------
std::string UnitTestMergeText::text001() {
return "Str1\r\n"
"Str\r\n"
"Str\r\n"
"Str\r\n"
"Str2\r\n"
"Str3\r\n"
"Str\r\n"
"Str\r\n"
"Str\r\n";
}
// ---------------------------------------------------------------------
std::string UnitTestMergeText::text002() {
return "Str1\r\n"
"Str \r\n"
"Str\r\n"
"Str\r\n"
"Str2\r\n"
"Str\r\n"
"Str3\r\n"
"Str\r\n"
"Str\r\n"
"Str\r\n";
}
// ---------------------------------------------------------------------<commit_msg>Fixed unit for merge<commit_after>#include <unit_test_merge_text.h>
#include <utils_merge_text.h>
#include <vector>
#include <iostream>
REGISTRY_UNIT_TEST(UnitTestMergeText)
UnitTestMergeText::UnitTestMergeText()
: UnitTestBase("UnitTestMergeText") {
//
}
// ---------------------------------------------------------------------
void UnitTestMergeText::init() {
}
// ---------------------------------------------------------------------
bool UnitTestMergeText::run() {
struct LTest {
LTest(
std::string txt1,
std::string txt2,
std::string txt3,
std::vector<UtilsMergeTextRow *> arr1,
std::vector<UtilsMergeTextRow *> arr2,
unsigned int n
) : txt1(txt1), txt2(txt2), txt3(txt3), arr1(arr1), arr2(arr2), n(n) {
//
}
std::string txt1;
std::string txt2;
std::string txt3;
std::vector<UtilsMergeTextRow *> arr1;
std::vector<UtilsMergeTextRow *> arr2;
unsigned int n;
};
std::vector<LTest *> tests1;
std::vector<UtilsMergeTextRow *> arr1, arr2;
std::string text1 = text001();
std::string text2 = text002();
// std::cout << text1.toStdString() << "\n";
//empty (Test №1)
tests1.push_back(new LTest("", "", "", arr1, arr2, 0));
//without any difference (Test №2)
tests1.push_back(new LTest("I\ngot\nMike", "I\ngot\nMike", "I\ngot\nMike", arr1, arr2, 0));
//with a difference in the ending (Tests №3-6)
tests1.push_back(new LTest("I\ngot\nMike", "I\ngot\nMike", "I\ngot\nNike", arr1, arr2, 1));
tests1.push_back(new LTest("I\ngot\nNike", "I\ngot\nMike", "I\ngot\nMike", arr1, arr2, 1));
tests1.push_back(new LTest("I\ngot\nNike", "I\ngot\nMike", "I\ngot\nNike", arr1, arr2, 1));
tests1.push_back(new LTest("I\ngot\nBike", "I\ngot\nMike", "I\ngot\nNike", arr1, arr2, 1));
//with a difference in the beginning (Tests №7-10)
tests1.push_back(new LTest("I\ngot\nMike", "I\ngot\nMike", "You\ngot\nMike", arr1, arr2, 1));
tests1.push_back(new LTest("You\ngot\nMike", "I\ngot\nMike", "I\ngot\nMike", arr1, arr2, 1));
tests1.push_back(new LTest("You\ngot\nMike", "I\ngot\nMike", "You\ngot\nMike", arr1, arr2, 1));
tests1.push_back(new LTest("We\ngot\nMike", "I\ngot\nMike", "You\ngot\nMike", arr1, arr2, 1));
//with a difference in the middle of the row (Tests №11-15)
tests1.push_back(new LTest("I\nhave\ncute\ncats", "I\nhave\ncute\ncats", "I\nhave\nhuge\ncats", arr1, arr2, 1));
tests1.push_back(new LTest("I\nhave\nhuge\ncats", "I\nhave\ncute\ncats", "I\nhave\ncute\ncats", arr1, arr2, 1));
tests1.push_back(new LTest("I\nhave\nhuge\ncats", "I\nhave\ncute\ncats", "I\nhave\nhuge\ncats", arr1, arr2, 1));
tests1.push_back(new LTest("I\nhave\ndifference\ncats", "I\nhave\ncute\ncats", "I\nhave\nhuge\ncats", arr1, arr2, 1));
tests1.push_back(new LTest("I\nbetray\ncats", "I\nhave\ncats", "I\nlove\ncats", arr1, arr2, 1));
//delete lines from the end of text (Tests №16-19)
tests1.push_back(new LTest("Go\nto\nthe\nschool", "Go\nto\nthe\nschool", "Go\nto", arr1, arr2, 2));
tests1.push_back(new LTest("Go\nto", "Go\nto\nthe\nschool", "Go\nto\nthe\nschool", arr1, arr2, 2));
tests1.push_back(new LTest("Go\nto\nthe", "Go\nto\nthe\nschool", "Go\nto", arr1, arr2, 2));
tests1.push_back(new LTest("Go\nto", "Go\nto\nthe\nschool", "Go\nto\nthe", arr1, arr2, 2));
//add lines in the end of text (Tests №20-23)
tests1.push_back(new LTest("Go\nto", "Go\nto", "Go\nto\nthe\nschool", arr1, arr2, 2));
tests1.push_back(new LTest("Go\nto\nthe\nschool", "Go\nto", "Go\nto", arr1, arr2, 2));
tests1.push_back(new LTest("Go\nto\nthe", "Go\nto", "Go\nto\nthe\nschool", arr1, arr2, 2));
tests1.push_back(new LTest("Go\nto\nthe\nschool", "Go\nto", "Go\nto\nthe", arr1, arr2, 2));
//delete rows from the beginning and the middle of text (Tests №24-27)
tests1.push_back(new LTest("Go\nto\nthe\nschool", "Go\nto\nthe\nschool", "the\nschool", arr1, arr2, 2));
tests1.push_back(new LTest("the\nschool", "Go\nto\nthe\nschool", "Go\nto\nthe\nschool", arr1, arr2, 2));
tests1.push_back(new LTest("Go\nto\nthe\nschool", "Go\nto\nthe\nschool", "Go\nto\nschool", arr1, arr2, 1));
tests1.push_back(new LTest("Go\nto\nschool", "Go\nto\nthe\nschool", "Go\nto\nthe\nschool", arr1, arr2, 1));
//add rows to the beginning and the middle of text (Tests №28-31)
tests1.push_back(new LTest("the\nschool", "the\nschool", "Go\nto\nthe\nschool", arr1, arr2, 2));
tests1.push_back(new LTest("Go\nto\nthe\nschool", "the\nschool", "the\nschool", arr1, arr2, 2));
tests1.push_back(new LTest("Go\nthe\nschool", "the\nschool", "the\nschool", arr1, arr2, 1));
tests1.push_back(new LTest("the\nschool", "the\nschool", "Go\nthe\nschool", arr1, arr2, 1));
//complex (Tests №32-33)
tests1.push_back(new LTest("You\nare\ngot\nand\ngood", "I\ngot\nMike\nand\nthis is\ngood\nboy", "I\ncure\ndamn\nill\ncancer", arr1, arr2, 8));
tests1.push_back(new LTest("We\nspent\nthe rest\nof our life\non\nthis\ncourse\nwork", "We\nspent\na lot of\ntime\non\nthis\ncourse\nwork", "We\ngonna\nspend\na lot of\nfunky\ntime\non\ncourse\nwork", arr1, arr2, 6));
unsigned int nSuccess = 0;
for (unsigned int i = 0; i < tests1.size(); i++){
std::string txt1 = tests1[i]->txt1;
std::string txt2 = tests1[i]->txt2;
std::string txt3 = tests1[i]->txt3;
UtilsMergeText::merge(txt1, txt2, txt3, arr1, arr2);
unsigned int n = tests1[i]->n;
if(arr1.size()==n) {
nSuccess++;
} else {
Log::err(TAG, "In the test №" + std::to_string(i + 1) + " the length of the vector is expected: "
+ std::to_string(n) + ", but obtained: " + std::to_string(arr1.size()));
}
arr1.clear(), arr2.clear();
}
//sort module test
struct LTest2 {
LTest2(
std::string txt1,
std::string txt2,
std::string txt3,
std::vector<UtilsMergeTextRow *> arr1,
std::vector<UtilsMergeTextRow *> arr2,
std::vector<UtilsMergeTextRow *> arr3
) : txt1(txt1), txt2(txt2), txt3(txt3), arr1(arr1), arr2(arr2), arr3(arr3) {
//
}
std::string txt1;
std::string txt2;
std::string txt3;
std::vector<UtilsMergeTextRow *> arr1;
std::vector<UtilsMergeTextRow *> arr2;
std::vector<UtilsMergeTextRow *> arr3;
};
std::vector<LTest2 *> tests2;
std::vector<UtilsMergeTextRow *> arr3;
int id[8] = {0,1,1,2,3,4,5,6};
std::vector<std::string> skey;
skey.push_back("I");
skey.push_back("got");
skey.push_back("!add");
skey.push_back("Mike");
skey.push_back("and");
skey.push_back("this is");
skey.push_back("!del");
skey.push_back("!del");
std::vector<std::string> sline;
sline.push_back("You");
sline.push_back("cure");
sline.push_back("are");
sline.push_back("damn");
sline.push_back("ill");
sline.push_back("cancer");
sline.push_back("good");
sline.push_back("boy");
for(int i=0;i<skey.size();++i) arr3.push_back(new UtilsMergeTextRow(id[i], skey.at(i), sline.at(i)));
tests2.push_back(new LTest2(
"You\nare\ngot\nand\ngood",
"I\ngot\nMike\nand\nthis is\ngood\nboy",
"I\ncure\ndamn\nill\ncancer",
arr1, arr2, arr3));
std::string txt1 = tests2[0]->txt1;
std::string txt2 = tests2[0]->txt2;
std::string txt3 = tests2[0]->txt3;
UtilsMergeText::merge(txt1, txt2, txt3, arr1, arr2);
unsigned int Success = 0;
for (int i = 0; i < 8; ++i) {
int id1 = arr1.at(i)->id;
int id2 = arr3.at(i)->id;
std::string key1 = arr1.at(i)->key;
std::string key2 = arr3.at(i)->key;
std::string line1 = arr1.at(i)->line;
std::string line2 = arr3.at(i)->line;
if (id1==id2 && key1==key2 && line1==line2) {
Success+=1;
} else {
Log::info(TAG, "In the sort test in the element №" + std::to_string(i+1) + ":");
if (id1!=id2) {
Log::err(TAG, "expected id: '" + std::to_string(id2) + "', but obtained: '" + std::to_string(id1) + "'");
}
if (key1!=key2) {
Log::err(TAG, "expected key: '" + key2 + "', but obtained: '" + key1 + "'");
}
if (line1!=line2) {
Log::err(TAG, "expected line: '" + line2 + "', but obtained: '" + line1 + "'");
}
}
}
if (Success == 8) {
nSuccess++;
}
return nSuccess == tests1.size() + 1;
}
// ---------------------------------------------------------------------
std::string UnitTestMergeText::text001() {
return "Str1\n"
"Str\n"
"Str\n"
"Str\n"
"Str2\n"
"Str3\n"
"Str\n"
"Str\n"
"Str\n";
}
// ---------------------------------------------------------------------
std::string UnitTestMergeText::text002() {
return "Str1\n"
"Str \n"
"Str\n"
"Str\n"
"Str2\n"
"Str\n"
"Str3\n"
"Str\n"
"Str\n"
"Str\n";
}
// ---------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/common_runtime/control_flow_deps_to_chains.h"
#include <cstdint>
#include "tensorflow/core/framework/attr_value.pb.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/framework/op_def_builder.h"
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/strcat.h"
#include "tensorflow/core/util/dump_graph.h"
namespace tensorflow {
// TODO(mdan): Move this into Grappler - cleaner interface.
Status ControlFlowDepsToChainsPass::Run(
const GraphOptimizationPassOptions& options) {
VLOG(1) << "ControlFlowDepsToChainsPass::Run";
if (options.graph == nullptr) {
VLOG(1) << "ControlFlowDepsToChainsPass::Run Aborted";
return Status::OK();
}
Graph* g = options.graph->get();
DCHECK(g != nullptr);
FunctionLibraryDefinition* flib_def = options.flib_def;
DCHECK(flib_def != nullptr);
if (VLOG_IS_ON(1)) {
DumpGraphToFile("control_flow_deps_to_chains_before", *g, flib_def);
}
for (Node* n : g->nodes()) {
if (n == nullptr) continue;
if (!n->IsWhileNode()) continue;
// TODO(mdan): This breaks encapsulation of Node/Graph. Is there any needed?
// TODO(mdan): Consolidate this with AddWhileInputHack.
NodeDef* while_node = n->mutable_def();
const auto& attrs = while_node->attr();
auto* mattrs = while_node->mutable_attr();
string body_name = attrs.at("body").func().name();
auto* body_graph = flib_def->Find(body_name);
DCHECK(body_graph != nullptr);
// Look for required annotations.
if (attrs.find("_stateful_parallelism") == attrs.end()) continue;
if (!attrs.at("_stateful_parallelism").b()) continue;
// TODO(mdan): We don't really need this attribute.
if (attrs.find("_num_original_outputs") == attrs.end()) continue;
int body_barrier_loc = -1;
std::map<string, int> node_index;
for (int i = 0, s = body_graph->node_def_size(); i < s; i++) {
node_index.emplace(body_graph->node_def(i).name(), i);
if (body_barrier_loc < 0) {
const auto& node_attr = body_graph->node_def(i).attr();
if (node_attr.find("_acd_function_control_output") != node_attr.end()) {
body_barrier_loc = i;
}
}
}
if (body_barrier_loc < 0) continue;
bool ok_for_lowering = true;
for (int i = 0; i < body_graph->control_ret_size(); i++) {
const auto& control_node = body_graph->node_def(
node_index[body_graph->signature().control_output(i)]);
const auto& control_attr = control_node.attr();
if (control_attr.find("_res_first_used_by") == control_attr.end()) {
ok_for_lowering = false;
break;
}
}
if (!ok_for_lowering) continue;
int num_loop_vars = body_graph->signature().input_arg_size();
int num_new_chains = body_graph->control_ret_size();
int num_node_inputs = while_node->input_size();
if (!num_new_chains) continue; // Nothing to do for stateless loops.
// Add extra loop vars to the while node.
// TODO(mdan): If the loop vars contains the resource, we should reuse it.
// Note that stateful ops of resource inputs cause their resources to be
// captured into the loop vars (through the body/cond captures). We could
// effectively use those as chains.
// TODO(mdan): Is there a more efficient way to do this?
// Insert the new While node inputs: at the end of the loop vars, but before
// any non-loop var inputs (like control dependencies). Once the initial
// chain values are created below, they will be added to these inputs.
for (int i = 0; i < num_new_chains; i++) {
while_node->add_input();
}
for (int i = num_node_inputs - 1; i >= num_loop_vars; i--) {
while_node->set_input(i + num_new_chains, while_node->input(i));
}
std::vector<Node*> new_inputs;
std::vector<int> new_input_locations;
// Set their name to a gensym, type to float and shape to scalar.
for (int i = 0; i < num_new_chains; i++) {
string c_name = g->NewName("acd__chain");
// The initial value for the i'th chain loop var.
NodeDef new_in;
new_in.set_name(c_name);
new_in.set_op("Const");
AttrValue att_dtype;
att_dtype.set_type(DT_FLOAT);
new_in.mutable_attr()->insert({"dtype", att_dtype});
AttrValue att_value;
att_value.mutable_tensor()->set_dtype(DT_FLOAT);
att_value.mutable_tensor()->mutable_tensor_shape();
att_value.mutable_tensor()->add_int_val(0);
new_in.mutable_attr()->insert({"value", att_value});
Status status;
new_inputs.push_back(g->AddNode(new_in, &status));
TF_RETURN_WITH_CONTEXT_IF_ERROR(status, "while creating chain", c_name);
int loc = num_loop_vars + i;
new_input_locations.push_back(loc);
while_node->set_input(loc, c_name);
mattrs->at("T").mutable_list()->add_type(DT_FLOAT);
mattrs->at("output_shapes").mutable_list()->add_shape();
}
// TODO(mdan): This should not be necessary to update. Delete?
mattrs->at("_num_original_outputs").set_i(num_loop_vars + num_new_chains);
n->UpdateProperties();
for (int i = 0; i < num_new_chains; i++) {
g->AddEdge(new_inputs[i], 0, n, new_input_locations[i]);
}
// TODO(mdan): This is wasteful. Can we just mutate the original proto?
FunctionDef modified_body = *body_graph;
// Disable the global end-of-body barrier from the body function.
// Because removing a node is too inefficient (would have to walk all the
// inputs of all graph nodes), we instead clear its control dependencies.
modified_body.mutable_node_def(body_barrier_loc)->clear_input();
// Add extra loop vars to the body function.
for (int i = 0; i < num_new_chains; i++) {
// Input loop vars.
// TODO(mdan): Double check that this doesn't clash with names in body.
string c_name = g->NewName("acd__chainv");
std::replace(c_name.begin(), c_name.end(), '/', '_');
auto* new_arg = modified_body.mutable_signature()->add_input_arg();
new_arg->set_name(c_name);
new_arg->set_type(DT_FLOAT);
// Output ops. These are copies of the inputs conditioned on the actual
// control outputs.
string c_out_name = g->NewName("acd__outchain");
auto* new_out = modified_body.add_node_def();
new_out->set_name(c_out_name);
new_out->set_op("Identity");
new_out->add_input(c_name);
new_out->add_input(
strings::StrCat("^", body_graph->signature().control_output(i)));
AttrValue attr;
attr.set_type(DT_FLOAT);
new_out->mutable_attr()->insert({"T", attr});
// Output loop var declarations.
string c_ret_name = c_out_name;
std::replace(c_ret_name.begin(), c_ret_name.end(), '/', '_');
auto* new_out_arg = modified_body.mutable_signature()->add_output_arg();
new_out_arg->set_name(c_ret_name);
new_out_arg->set_type(DT_FLOAT);
// Actual output loop vars.
modified_body.mutable_ret()->insert(
{c_ret_name, strings::StrCat(c_out_name, ":output:0")});
AttrValue attr_val;
attr_val.mutable_list()->mutable_shape();
FunctionDef_ArgAttrs arg_attrs;
arg_attrs.mutable_attr()->insert({"_output_shapes", attr_val});
modified_body.mutable_arg_attr()->insert(
{static_cast<uint32_t>(i + num_loop_vars), arg_attrs});
}
// Wire chain loop vars to the ops they need to condition.
node_index.clear();
for (int i = 0; i < modified_body.node_def_size(); i++) {
node_index.emplace(modified_body.node_def(i).name(), i);
}
auto& modified_sig = modified_body.signature();
for (int i = 0; i < num_new_chains; i++) {
const auto& control_node =
modified_body.node_def(node_index[modified_sig.control_output(i)]);
for (const auto& r :
control_node.attr().at("_res_first_used_by").list().s()) {
NodeDef* first_node = modified_body.mutable_node_def(node_index[r]);
// This control dependency ensures proper sequencing of stateful ops
// upon entry into the loop body, so that they run after the ops
// which affected the same resource in the previous iteration.
first_node->add_input(strings::StrCat(
"^", modified_sig.input_arg(i + num_loop_vars).name()));
}
}
// Clear body function's control returns.
modified_body.mutable_control_ret()->clear();
// Add extra loop vars to the cond function.
// TODO(mdan): This is wasteful. Can't we just mutate the original proto?
string cond_name = attrs.at("cond").func().name();
auto* cond_graph = flib_def->Find(cond_name);
DCHECK(cond_graph != nullptr);
FunctionDef modified_cond = *cond_graph;
int cond_barrier_loc = -1;
for (int i = 0, s = cond_graph->node_def_size(); i < s; i++) {
if (cond_barrier_loc < 0) {
const auto& node_attr = cond_graph->node_def(i).attr();
if (node_attr.find("_acd_function_control_output") != node_attr.end()) {
cond_barrier_loc = i;
}
}
}
if (cond_barrier_loc > 0) {
// Disable the global end-of-body barrier from the cond function.
// Because removing a node is too inefficient (would have to walk all the
// inputs of all graph nodes), we instead clear its control dependencies.
modified_cond.mutable_node_def(cond_barrier_loc)->clear_input();
}
for (int i = 0; i < num_new_chains; i++) {
// Input loop vars.
// TODO(mdan): These should gate the stateful ops in the cond.
// Until ACD supplies the necessary information, these are dummies in this
// function.
string c_name = g->NewName("acd__chain");
auto* new_arg = modified_cond.mutable_signature()->add_input_arg();
new_arg->set_name(c_name);
new_arg->set_type(DT_FLOAT);
// TODO(mdan): Return values on the cond function? Most likely a bug.
AttrValue attr_val;
attr_val.mutable_list()->mutable_shape();
FunctionDef_ArgAttrs arg_attrs;
arg_attrs.mutable_attr()->insert({"_output_shapes", attr_val});
modified_cond.mutable_arg_attr()->insert(
{static_cast<uint32_t>(i + num_loop_vars), arg_attrs});
}
// Wire the new cond/body functions to the While node.
string new_cond_name = g->NewName("acd__while_cond");
modified_cond.mutable_signature()->set_name(new_cond_name);
mattrs->at("cond").mutable_func()->set_name(new_cond_name);
string new_body_name = g->NewName("acd__while_body");
modified_body.mutable_signature()->set_name(new_body_name);
mattrs->at("body").mutable_func()->set_name(new_body_name);
// Commit the new functions.
TF_RETURN_WITH_CONTEXT_IF_ERROR(
flib_def->AddFunctionDef(modified_body,
flib_def->GetStackTraces(body_name)),
"while attaching ", new_body_name, " to flib_def");
TF_RETURN_WITH_CONTEXT_IF_ERROR(
flib_def->AddFunctionDef(modified_cond,
flib_def->GetStackTraces(cond_name)),
"while attaching ", new_cond_name, " to flib_def");
// TODO(b/183666205): This should not be necessary.
// It's unclear why adding the functions here is also required.
// Moreover, it's unclear when graph_lib's parent is flib_def itself.
auto* graph_lib = g->mutable_flib_def();
if (graph_lib->default_registry() != flib_def) {
TF_RETURN_WITH_CONTEXT_IF_ERROR(
graph_lib->AddFunctionDef(modified_body,
graph_lib->GetStackTraces(body_name)),
"while attaching ", new_body_name, " to graph");
TF_RETURN_WITH_CONTEXT_IF_ERROR(
graph_lib->AddFunctionDef(modified_cond,
graph_lib->GetStackTraces(cond_name)),
"while attaching ", new_cond_name, " to graph");
}
}
if (VLOG_IS_ON(1)) {
DumpGraphToFile("control_flow_deps_to_chains_after", *g, flib_def);
}
return Status::OK();
}
// Note: This needs to run before functional control flow lowering, which is 10.
REGISTER_OPTIMIZATION(OptimizationPassRegistry::PRE_PLACEMENT, 9,
ControlFlowDepsToChainsPass);
} // namespace tensorflow
<commit_msg>Actually add an empty shape to the attribute (it's a repeated field, not an optional one).<commit_after>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/common_runtime/control_flow_deps_to_chains.h"
#include <cstdint>
#include "tensorflow/core/framework/attr_value.pb.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/framework/op_def_builder.h"
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/strcat.h"
#include "tensorflow/core/util/dump_graph.h"
namespace tensorflow {
// TODO(mdan): Move this into Grappler - cleaner interface.
Status ControlFlowDepsToChainsPass::Run(
const GraphOptimizationPassOptions& options) {
VLOG(1) << "ControlFlowDepsToChainsPass::Run";
if (options.graph == nullptr) {
VLOG(1) << "ControlFlowDepsToChainsPass::Run Aborted";
return Status::OK();
}
Graph* g = options.graph->get();
DCHECK(g != nullptr);
FunctionLibraryDefinition* flib_def = options.flib_def;
DCHECK(flib_def != nullptr);
if (VLOG_IS_ON(1)) {
DumpGraphToFile("control_flow_deps_to_chains_before", *g, flib_def);
}
for (Node* n : g->nodes()) {
if (n == nullptr) continue;
if (!n->IsWhileNode()) continue;
// TODO(mdan): This breaks encapsulation of Node/Graph. Is there any needed?
// TODO(mdan): Consolidate this with AddWhileInputHack.
NodeDef* while_node = n->mutable_def();
const auto& attrs = while_node->attr();
auto* mattrs = while_node->mutable_attr();
string body_name = attrs.at("body").func().name();
auto* body_graph = flib_def->Find(body_name);
DCHECK(body_graph != nullptr);
// Look for required annotations.
if (attrs.find("_stateful_parallelism") == attrs.end()) continue;
if (!attrs.at("_stateful_parallelism").b()) continue;
// TODO(mdan): We don't really need this attribute.
if (attrs.find("_num_original_outputs") == attrs.end()) continue;
int body_barrier_loc = -1;
std::map<string, int> node_index;
for (int i = 0, s = body_graph->node_def_size(); i < s; i++) {
node_index.emplace(body_graph->node_def(i).name(), i);
if (body_barrier_loc < 0) {
const auto& node_attr = body_graph->node_def(i).attr();
if (node_attr.find("_acd_function_control_output") != node_attr.end()) {
body_barrier_loc = i;
}
}
}
if (body_barrier_loc < 0) continue;
bool ok_for_lowering = true;
for (int i = 0; i < body_graph->control_ret_size(); i++) {
const auto& control_node = body_graph->node_def(
node_index[body_graph->signature().control_output(i)]);
const auto& control_attr = control_node.attr();
if (control_attr.find("_res_first_used_by") == control_attr.end()) {
ok_for_lowering = false;
break;
}
}
if (!ok_for_lowering) continue;
int num_loop_vars = body_graph->signature().input_arg_size();
int num_new_chains = body_graph->control_ret_size();
int num_node_inputs = while_node->input_size();
if (!num_new_chains) continue; // Nothing to do for stateless loops.
// Add extra loop vars to the while node.
// TODO(mdan): If the loop vars contains the resource, we should reuse it.
// Note that stateful ops of resource inputs cause their resources to be
// captured into the loop vars (through the body/cond captures). We could
// effectively use those as chains.
// TODO(mdan): Is there a more efficient way to do this?
// Insert the new While node inputs: at the end of the loop vars, but before
// any non-loop var inputs (like control dependencies). Once the initial
// chain values are created below, they will be added to these inputs.
for (int i = 0; i < num_new_chains; i++) {
while_node->add_input();
}
for (int i = num_node_inputs - 1; i >= num_loop_vars; i--) {
while_node->set_input(i + num_new_chains, while_node->input(i));
}
std::vector<Node*> new_inputs;
std::vector<int> new_input_locations;
// Set their name to a gensym, type to float and shape to scalar.
for (int i = 0; i < num_new_chains; i++) {
string c_name = g->NewName("acd__chain");
// The initial value for the i'th chain loop var.
NodeDef new_in;
new_in.set_name(c_name);
new_in.set_op("Const");
AttrValue att_dtype;
att_dtype.set_type(DT_FLOAT);
new_in.mutable_attr()->insert({"dtype", att_dtype});
AttrValue att_value;
att_value.mutable_tensor()->set_dtype(DT_FLOAT);
att_value.mutable_tensor()->mutable_tensor_shape();
att_value.mutable_tensor()->add_int_val(0);
new_in.mutable_attr()->insert({"value", att_value});
Status status;
new_inputs.push_back(g->AddNode(new_in, &status));
TF_RETURN_WITH_CONTEXT_IF_ERROR(status, "while creating chain", c_name);
int loc = num_loop_vars + i;
new_input_locations.push_back(loc);
while_node->set_input(loc, c_name);
mattrs->at("T").mutable_list()->add_type(DT_FLOAT);
mattrs->at("output_shapes").mutable_list()->add_shape();
}
// TODO(mdan): This should not be necessary to update. Delete?
mattrs->at("_num_original_outputs").set_i(num_loop_vars + num_new_chains);
n->UpdateProperties();
for (int i = 0; i < num_new_chains; i++) {
g->AddEdge(new_inputs[i], 0, n, new_input_locations[i]);
}
// TODO(mdan): This is wasteful. Can we just mutate the original proto?
FunctionDef modified_body = *body_graph;
// Disable the global end-of-body barrier from the body function.
// Because removing a node is too inefficient (would have to walk all the
// inputs of all graph nodes), we instead clear its control dependencies.
modified_body.mutable_node_def(body_barrier_loc)->clear_input();
// Add extra loop vars to the body function.
for (int i = 0; i < num_new_chains; i++) {
// Input loop vars.
// TODO(mdan): Double check that this doesn't clash with names in body.
string c_name = g->NewName("acd__chainv");
std::replace(c_name.begin(), c_name.end(), '/', '_');
auto* new_arg = modified_body.mutable_signature()->add_input_arg();
new_arg->set_name(c_name);
new_arg->set_type(DT_FLOAT);
// Output ops. These are copies of the inputs conditioned on the actual
// control outputs.
string c_out_name = g->NewName("acd__outchain");
auto* new_out = modified_body.add_node_def();
new_out->set_name(c_out_name);
new_out->set_op("Identity");
new_out->add_input(c_name);
new_out->add_input(
strings::StrCat("^", body_graph->signature().control_output(i)));
AttrValue attr;
attr.set_type(DT_FLOAT);
new_out->mutable_attr()->insert({"T", attr});
// Output loop var declarations.
string c_ret_name = c_out_name;
std::replace(c_ret_name.begin(), c_ret_name.end(), '/', '_');
auto* new_out_arg = modified_body.mutable_signature()->add_output_arg();
new_out_arg->set_name(c_ret_name);
new_out_arg->set_type(DT_FLOAT);
// Actual output loop vars.
modified_body.mutable_ret()->insert(
{c_ret_name, strings::StrCat(c_out_name, ":output:0")});
AttrValue attr_val;
attr_val.mutable_list()->add_shape();
FunctionDef_ArgAttrs arg_attrs;
arg_attrs.mutable_attr()->insert({"_output_shapes", attr_val});
modified_body.mutable_arg_attr()->insert(
{static_cast<uint32_t>(i + num_loop_vars), arg_attrs});
}
// Wire chain loop vars to the ops they need to condition.
node_index.clear();
for (int i = 0; i < modified_body.node_def_size(); i++) {
node_index.emplace(modified_body.node_def(i).name(), i);
}
auto& modified_sig = modified_body.signature();
for (int i = 0; i < num_new_chains; i++) {
const auto& control_node =
modified_body.node_def(node_index[modified_sig.control_output(i)]);
for (const auto& r :
control_node.attr().at("_res_first_used_by").list().s()) {
NodeDef* first_node = modified_body.mutable_node_def(node_index[r]);
// This control dependency ensures proper sequencing of stateful ops
// upon entry into the loop body, so that they run after the ops
// which affected the same resource in the previous iteration.
first_node->add_input(strings::StrCat(
"^", modified_sig.input_arg(i + num_loop_vars).name()));
}
}
// Clear body function's control returns.
modified_body.mutable_control_ret()->clear();
// Add extra loop vars to the cond function.
// TODO(mdan): This is wasteful. Can't we just mutate the original proto?
string cond_name = attrs.at("cond").func().name();
auto* cond_graph = flib_def->Find(cond_name);
DCHECK(cond_graph != nullptr);
FunctionDef modified_cond = *cond_graph;
int cond_barrier_loc = -1;
for (int i = 0, s = cond_graph->node_def_size(); i < s; i++) {
if (cond_barrier_loc < 0) {
const auto& node_attr = cond_graph->node_def(i).attr();
if (node_attr.find("_acd_function_control_output") != node_attr.end()) {
cond_barrier_loc = i;
}
}
}
if (cond_barrier_loc > 0) {
// Disable the global end-of-body barrier from the cond function.
// Because removing a node is too inefficient (would have to walk all the
// inputs of all graph nodes), we instead clear its control dependencies.
modified_cond.mutable_node_def(cond_barrier_loc)->clear_input();
}
for (int i = 0; i < num_new_chains; i++) {
// Input loop vars.
// TODO(mdan): These should gate the stateful ops in the cond.
// Until ACD supplies the necessary information, these are dummies in this
// function.
string c_name = g->NewName("acd__chain");
auto* new_arg = modified_cond.mutable_signature()->add_input_arg();
new_arg->set_name(c_name);
new_arg->set_type(DT_FLOAT);
// TODO(mdan): Return values on the cond function? Most likely a bug.
AttrValue attr_val;
attr_val.mutable_list()->add_shape();
FunctionDef_ArgAttrs arg_attrs;
arg_attrs.mutable_attr()->insert({"_output_shapes", attr_val});
modified_cond.mutable_arg_attr()->insert(
{static_cast<uint32_t>(i + num_loop_vars), arg_attrs});
}
// Wire the new cond/body functions to the While node.
string new_cond_name = g->NewName("acd__while_cond");
modified_cond.mutable_signature()->set_name(new_cond_name);
mattrs->at("cond").mutable_func()->set_name(new_cond_name);
string new_body_name = g->NewName("acd__while_body");
modified_body.mutable_signature()->set_name(new_body_name);
mattrs->at("body").mutable_func()->set_name(new_body_name);
// Commit the new functions.
TF_RETURN_WITH_CONTEXT_IF_ERROR(
flib_def->AddFunctionDef(modified_body,
flib_def->GetStackTraces(body_name)),
"while attaching ", new_body_name, " to flib_def");
TF_RETURN_WITH_CONTEXT_IF_ERROR(
flib_def->AddFunctionDef(modified_cond,
flib_def->GetStackTraces(cond_name)),
"while attaching ", new_cond_name, " to flib_def");
// TODO(b/183666205): This should not be necessary.
// It's unclear why adding the functions here is also required.
// Moreover, it's unclear when graph_lib's parent is flib_def itself.
auto* graph_lib = g->mutable_flib_def();
if (graph_lib->default_registry() != flib_def) {
TF_RETURN_WITH_CONTEXT_IF_ERROR(
graph_lib->AddFunctionDef(modified_body,
graph_lib->GetStackTraces(body_name)),
"while attaching ", new_body_name, " to graph");
TF_RETURN_WITH_CONTEXT_IF_ERROR(
graph_lib->AddFunctionDef(modified_cond,
graph_lib->GetStackTraces(cond_name)),
"while attaching ", new_cond_name, " to graph");
}
}
if (VLOG_IS_ON(1)) {
DumpGraphToFile("control_flow_deps_to_chains_after", *g, flib_def);
}
return Status::OK();
}
// Note: This needs to run before functional control flow lowering, which is 10.
REGISTER_OPTIMIZATION(OptimizationPassRegistry::PRE_PLACEMENT, 9,
ControlFlowDepsToChainsPass);
} // namespace tensorflow
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: cacheupdatelistener.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: svesik $ $Date: 2004-04-21 11:58:02 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef __FILTER_CONFIG_CACHEUPDATELISTENER_HXX_
#define __FILTER_CONFIG_CACHEUPDATELISTENER_HXX_
//_______________________________________________
// includes
#include "filtercache.hxx"
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEVENTLISTENER_HPP_
#include <com/sun/star/document/XEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEVENTBROADCASTER_HPP_
#include <com/sun/star/document/XEventBroadcaster.hpp>
#endif
#ifndef _SALHELPER_SINGLETONREF_HXX_
#include <salhelper/singletonref.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
//_______________________________________________
// namespace
namespace filter{
namespace config{
//_______________________________________________
// definitions
//_______________________________________________
/** @short implements a listener, which will update the
global filter cache of an office, after zje office
startup was finished.
@descr To perform startup of an office, the filter cache starts
with a minimum set of properties only. After the first document
was loaded successfully a thread will be started to fill the
cache with all other proeprties, so it can work with the whole
filter configuration.
*/
class CacheUpdateListener : public BaseLock // must be the first one to guarantee right initialized mutex member!
, public ::cppu::WeakImplHelper1< css::document::XEventListener >
{
//-------------------------------------------
// member
private:
/** @short reference to an uno service manager, which can be used
to create own needed services. */
css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR;
/** @short reference(!) to the singleton filter cache implementation,
which should be updated by this thread. */
::salhelper::SingletonRef< FilterCache > m_rCache;
/** @short reference to the global event broadcaster, which is usde to find
out, when the first office document was opened successfully. */
css::uno::Reference< css::document::XEventBroadcaster > m_xBroadcaster;
//-------------------------------------------
// native interface
public:
//---------------------------------------
// ctor/dtor
/** @short initialize new instance of this class.
@descr It set a reference to the global filter cache singleton,
which should be updated here. Further it starts listening
on the global event broadcaster to get the information, when
loading of the first document was finished.
@param xSMGR
reference to a service manager, which can be used to create
own needed uno services.
*/
CacheUpdateListener(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR);
//---------------------------------------
/** @short standard dtor.
*/
virtual ~CacheUpdateListener();
//-------------------------------------------
// uno interface
public:
//---------------------------------------
// document.XEventListener
virtual void SAL_CALL notifyEvent(const css::document::EventObject& aEvent)
throw(css::uno::RuntimeException);
//---------------------------------------
// lang.XEventListener
virtual void SAL_CALL disposing(const css::lang::EventObject& aEvent)
throw(css::uno::RuntimeException);
};
} // namespace config
} // namespace filter
#endif // __FILTER_CONFIG_CACHEUPDATELISTENER_HXX_
<commit_msg>INTEGRATION: CWS os12 (1.2.26); FILE MERGED 2004/03/08 10:53:59 as 1.2.26.2: #114059# use clone/takeover instead of configuration listener 2004/03/05 13:53:58 as 1.2.26.1: #114059#, #115733# start implementation of listener mode, read old typedetection file, fix build dependencies<commit_after>/*************************************************************************
*
* $RCSfile: cacheupdatelistener.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2004-04-29 13:39:26 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef __FILTER_CONFIG_CACHEUPDATELISTENER_HXX_
#define __FILTER_CONFIG_CACHEUPDATELISTENER_HXX_
//_______________________________________________
// includes
#include "filtercache.hxx"
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XCHANGESLISTENER_HPP_
#include <com/sun/star/util/XChangesListener.hpp>
#endif
#ifndef _SALHELPER_SINGLETONREF_HXX_
#include <salhelper/singletonref.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
//_______________________________________________
// namespace
namespace filter{
namespace config{
//_______________________________________________
// definitions
//_______________________________________________
/** @short implements a listener, which will update the
global filter cache, if the underlying configuration
wa changed by other processes.
*/
class CacheUpdateListener : public BaseLock // must be the first one to guarantee right initialized mutex member!
, public ::cppu::WeakImplHelper1< css::util::XChangesListener >
{
//-------------------------------------------
// member
private:
/** @short reference to an uno service manager, which can be used
to create own needed services. */
css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR;
/** @short reference to the singleton(!) filter cache implementation,
which should be updated by this thread. */
::salhelper::SingletonRef< FilterCache > m_rCache;
//-------------------------------------------
// native interface
public:
//---------------------------------------
// ctor/dtor
/** @short initialize new instance of this class.
@descr Listening wont be started here. It can be done
by calling startListening() on this instance.
@see startListening()
@param xSMGR
reference to a service manager, which can be used to create
own needed uno services.
*/
CacheUpdateListener(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR);
//---------------------------------------
/** @short standard dtor.
*/
virtual ~CacheUpdateListener();
//---------------------------------------
/** @short starts listening on the given configuration access.
@descr There wont be a check, if this instance is already a listener
on the given configuration access! Such things must be checked
by the outside code.
=> startListening() and stopListening() must be called in pairs.
But calling of stopListening() isnt required in real.
If the configuration access dies, the listener dies automaticly too.
@param xConfigAccess
the configuration access, where this instance should listen for changes.
*/
virtual void startListening(const css::uno::Reference< css::uno::XInterface >& xConfigAccess);
//---------------------------------------
/** @short stop listening on the given configuration access.
@descr There wont be a check, if this instance is a listener
on the given configuration access or not! Such things must be checked
by the outside code.
=> startListening() and stopListening() must be called in pairs.
But calling of stopListening() isnt required in real.
If the configuration access dies, the listener dies automaticly too.
@param xConfigAccess
the configuration access, where this instance should stop listening.
*/
virtual void stopListening(const css::uno::Reference< css::uno::XInterface >& xConfigAccess);
//-------------------------------------------
// uno interface
public:
//---------------------------------------
// XChangesListener
virtual void SAL_CALL changesOccurred(const css::util::ChangesEvent& aEvent)
throw(css::uno::RuntimeException);
//---------------------------------------
// lang.XEventListener
virtual void SAL_CALL disposing(const css::lang::EventObject& aEvent)
throw(css::uno::RuntimeException);
};
} // namespace config
} // namespace filter
#endif // __FILTER_CONFIG_CACHEUPDATELISTENER_HXX_
<|endoftext|>
|
<commit_before>#include "regiondataremote.h"
#include "regionmatrixproxy.h"
#include "workerthread.h"
using namespace petabricks;
using namespace petabricks::RegionDataRemoteMessage;
RegionDataRemote::RegionDataRemote(const int dimensions, const IndexT* size, const RegionDataRemoteObjectPtr remoteObject) {
init(dimensions, size, remoteObject);
}
RegionDataRemote::RegionDataRemote(const int dimensions, const IndexT* size, RemoteHostPtr host) {
init(dimensions, size, new RegionDataRemoteObject());
// InitialMsg
size_t size_sz = _D * sizeof(IndexT);
size_t msg_len = sizeof(CreateRegionDataInitialMessage) + size_sz;
char buf[msg_len];
CreateRegionDataInitialMessage* msg = (CreateRegionDataInitialMessage*)buf;
msg->type = MessageTypes::CREATEREGIONDATA;
msg->dimensions = _D;
memcpy(msg->size, size, size_sz);
host->createRemoteObject(_remoteObject.asPtr(), &RegionMatrixProxy::genRemote, buf, msg_len);
}
RegionDataRemote::RegionDataRemote(const int dimensions, const IndexT* size, RemoteHost& host, const MessageType initialMessageType, const EncodedPtr encodePtr) {
init(dimensions, size, new RegionDataRemoteObject());
// InitialMsg
EncodedPtrInitialMessage msg;
msg.type = initialMessageType;
msg.encodedPtr = encodePtr;
int len = sizeof(EncodedPtrInitialMessage);
host.createRemoteObject(_remoteObject.asPtr(), &RegionMatrixProxy::genRemote, &msg, len);
}
void RegionDataRemote::init(const int dimensions, const IndexT* size, const RegionDataRemoteObjectPtr remoteObject) {
_D = dimensions;
_type = RegionDataTypes::REGIONDATAREMOTE;
_remoteObject = remoteObject;
memcpy(_size, size, sizeof(IndexT) * _D);
}
int RegionDataRemote::allocData() {
void* data;
size_t len;
this->fetchData(0, MessageTypes::ALLOCDATA, 0, &data, &len);
AllocDataReplyMessage* reply = (AllocDataReplyMessage*)data;
ElementT result = reply->result;
free(reply);
return result;
}
void RegionDataRemote::randomize() {
void* data;
size_t len;
this->fetchData(0, MessageTypes::RANDOMIZEDATA, 0, &data, &len);
free(data);
}
IRegionCachePtr RegionDataRemote::cacheGenerator() const {
IndexT multipliers[_D];
multipliers[0] = 1;
for (int i = 1; i < _D; i++) {
multipliers[i] = multipliers[i - 1] * _size[i - 1];
}
return new RegionDataRemoteCache(this, _D, multipliers);
}
IRegionCachePtr RegionDataRemote::cache() const {
#ifdef DISTRIBUTED_CACHE
if (WorkerThread::self()) {
return WorkerThread::self()->cache()->get(this);
} else {
// in listening loop
return NULL;
}
#else
return NULL;
#endif
}
void RegionDataRemote::invalidateCache() {
#ifdef DISTRIBUTED_CACHE
if (cache()) {
cache()->invalidate();
}
#endif
}
ElementT RegionDataRemote::readCell(const IndexT* coord) const {
#ifdef DISTRIBUTED_CACHE
if (cache()) {
return cache()->readCell(coord);
} else {
return readNoCache(coord);
}
#else
return readNoCache(coord);
#endif
}
ElementT RegionDataRemote::readNoCache(const IndexT* coord) const {
size_t coord_sz = _D * sizeof(IndexT);
size_t msg_len = sizeof(ReadCellMessage) + coord_sz;
char buf[msg_len];
ReadCellMessage* msg = (ReadCellMessage*)buf;
memcpy(msg->coord, coord, coord_sz);
void* data;
size_t len;
this->fetchData(buf, MessageTypes::READCELL, msg_len, &data, &len);
ReadCellReplyMessage* reply = (ReadCellReplyMessage*)data;
ElementT value = reply->value;
free(reply);
return value;
}
void RegionDataRemote::readByCache(void* request, size_t request_len, void* reply, size_t &/*reply_len*/) const {
void* data;
size_t len;
this->fetchData(request, MessageTypes::READCELLCACHE, request_len, &data, &len);
ReadCellCacheReplyMessage* r = (ReadCellCacheReplyMessage*)data;
RegionDataRemoteCacheLine* cacheLine = (RegionDataRemoteCacheLine*)reply;
cacheLine->start = r->start;
cacheLine->end = r->end;
memcpy(cacheLine->base, r->values, sizeof(ElementT) * (r->end + 1));
free(r);
}
void RegionDataRemote::writeCell(const IndexT* coord, ElementT value) {
#ifdef DISTRIBUTED_CACHE
if (cache()) {
cache()->writeCell(coord, value);
} else {
writeNoCache(coord, value);
}
#else
writeNoCache(coord, value);
#endif
}
void RegionDataRemote::writeNoCache(const IndexT* coord, ElementT value) {
size_t coord_sz = _D * sizeof(IndexT);
size_t msg_len = sizeof(WriteCellMessage) + coord_sz;
char buf[msg_len];
WriteCellMessage* msg = (WriteCellMessage*)buf;
msg->value = value;
memcpy(msg->coord, coord, coord_sz);
//JTRACE("write")(_D)(sizeof(IndexT))(coord_sz)(msg_len);
void* data;
size_t len;
this->fetchData(buf, MessageTypes::WRITECELL, msg_len, &data, &len);
WriteCellReplyMessage* reply = (WriteCellReplyMessage*)data;
free(reply);
}
void RegionDataRemote::writeByCache(const IndexT* coord, ElementT value) const {
size_t coord_sz = _D * sizeof(IndexT);
size_t msg_len = sizeof(WriteCellMessage) + coord_sz;
char buf[msg_len];
WriteCellMessage* msg = (WriteCellMessage*)buf;
msg->value = value;
memcpy(msg->coord, coord, coord_sz);
void* data;
size_t len;
this->fetchData(msg, MessageTypes::WRITECELL, msg_len, &data, &len);
WriteCellReplyMessage* reply = (WriteCellReplyMessage*)data;
free(reply);
}
void RegionDataRemote::copyToScratchMatrixStorage(CopyToMatrixStorageMessage* origMetadata, size_t len, MatrixStoragePtr scratchStorage, MatrixRegionMetadata* scratchMetadata) const {
void* data;
size_t replyLen;
this->fetchData(origMetadata, MessageTypes::TOSCRATCHSTORAGE, len, &data, &replyLen);
CopyToMatrixStorageReplyMessage* reply = (CopyToMatrixStorageReplyMessage*)data;
if (scratchMetadata == 0) {
JASSERT(reply->count == scratchStorage->count());
memcpy(scratchStorage->data(), reply->storage, sizeof(ElementT) * reply->count);
} else {
UNIMPLEMENTED();
}
free(reply);
}
void RegionDataRemote::copyFromScratchMatrixStorage(CopyFromMatrixStorageMessage* metadata, size_t size) const {
void* data;
size_t len;
this->fetchData(metadata, MessageTypes::FROMSCRATCHSTORAGE, size, &data, &len);
free(data);
}
DataHostPidList RegionDataRemote::hosts(IndexT* begin, IndexT* end) {
GetHostListMessage msg;
memcpy(msg.begin, begin, _D * sizeof(IndexT));
memcpy(msg.end, end, _D * sizeof(IndexT));
void* data;
size_t len;
this->fetchData(&msg, MessageTypes::GETHOSTLIST, sizeof(GetHostListMessage), &data, &len);
GetHostListReplyMessage* reply = (GetHostListReplyMessage*)data;
DataHostPidList list;
for (int i = 0; i < reply->numHosts; i++) {
list.push_back(reply->hosts[i]);
}
free(reply);
return list;
}
RemoteHostPtr RegionDataRemote::host() {
return _remoteObject->host();
}
UpdateHandlerChainReplyMessage RegionDataRemote::updateHandlerChain(UpdateHandlerChainMessage& msg) {
msg.numHops += 1;
void* data;
size_t len;
this->fetchData(&msg, MessageTypes::UPDATEHANDLERCHAIN, sizeof(UpdateHandlerChainMessage), &data, &len);
UpdateHandlerChainReplyMessage* _reply = (UpdateHandlerChainReplyMessage*)data;
UpdateHandlerChainReplyMessage reply = *_reply;
free(_reply);
return reply;
}
UpdateHandlerChainReplyMessage RegionDataRemote::updateHandlerChain() {
UpdateHandlerChainMessage msg;
msg.requester = HostPid::self();
msg.numHops = 0;
return this->updateHandlerChain(msg);
}
void RegionDataRemote::fetchData(const void* msg, MessageType type, size_t len, void** responseData, size_t* responseLen) const {
*responseData = 0;
*responseLen = 0;
size_t dataLen = sizeof(GeneralMessageHeader) + len;
GeneralMessageHeader* header = (GeneralMessageHeader*)malloc(dataLen);
header->isForwardMessage = false;
header->type = type;
header->contentOffset = sizeof(GeneralMessageHeader);
header->responseData = reinterpret_cast<EncodedPtr>(responseData);
header->responseLen = reinterpret_cast<EncodedPtr>(responseLen);
memcpy(header->content(), msg, len);
JLOCKSCOPE(*_remoteObject);
_remoteObject->send(header, dataLen);
free(header);
// wait for the data
while (*responseData == 0 || *responseLen == 0) {
_remoteObject->waitMsgMu();
}
}
void RegionDataRemote::onRecv(const void* data, size_t len) {
const BaseMessageHeader* base = (const BaseMessageHeader*)data;
if (base->isForwardMessage) {
const ForwardMessageHeader* header = (const ForwardMessageHeader*)data;
IRegionReplyProxy* proxy = reinterpret_cast<IRegionReplyProxy*>(header->callback);
proxy->processReplyMsg(base, len);
} else {
const GeneralMessageHeader* header = (const GeneralMessageHeader*)data;
const void** responseData = reinterpret_cast<const void**>(header->responseData);
size_t* responseLen = reinterpret_cast<size_t*>(header->responseLen);
size_t sz = len - base->contentOffset;
void* msg = malloc(sz);
memcpy(msg, base->content(), sz);
*responseData = msg;
*responseLen = sz;
}
}
// Process remote messages
void RegionDataRemote::forwardMessage(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller) {
size_t len = sizeof(ForwardMessageHeader) + baseLen;
ForwardMessageHeader* data = (ForwardMessageHeader*)malloc(len);
data->isForwardMessage = true;
data->type = base->type;
data->contentOffset = sizeof(ForwardMessageHeader) + base->contentOffset;
data->callback = reinterpret_cast<EncodedPtr>(caller);
memcpy(data->next(), base, baseLen);
_remoteObject->send(data, len);
free(data);
}
void RegionDataRemote::processReadCellMsg(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller) {
this->forwardMessage(base, baseLen, caller);
}
void RegionDataRemote::processWriteCellMsg(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller) {
this->forwardMessage(base, baseLen, caller);
}
void RegionDataRemote::processAllocDataMsg(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller) {
this->forwardMessage(base, baseLen, caller);
}
void RegionDataRemote::processRandomizeDataMsg(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller) {
this->forwardMessage(base, baseLen, caller);
}
void RegionDataRemote::processUpdateHandlerChainMsg(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller, RegionDataIPtr) {
UpdateHandlerChainMessage* msg = (UpdateHandlerChainMessage*)base->content();
msg->numHops++;
this->forwardMessage(base, baseLen, caller);
}
void RegionDataRemote::processGetHostListMsg(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller) {
this->forwardMessage(base, baseLen, caller);
}
void RegionDataRemote::processGetMatrixStorageMsg(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller) {
this->forwardMessage(base, baseLen, caller);
}
RemoteObjectPtr RegionDataRemote::genRemote() {
return new RegionDataRemoteObject();
}
<commit_msg>bugfix?<commit_after>#include "regiondataremote.h"
#include "regionmatrixproxy.h"
#include "workerthread.h"
using namespace petabricks;
using namespace petabricks::RegionDataRemoteMessage;
RegionDataRemote::RegionDataRemote(const int dimensions, const IndexT* size, const RegionDataRemoteObjectPtr remoteObject) {
init(dimensions, size, remoteObject);
}
RegionDataRemote::RegionDataRemote(const int dimensions, const IndexT* size, RemoteHostPtr host) {
init(dimensions, size, new RegionDataRemoteObject());
// InitialMsg
size_t size_sz = _D * sizeof(IndexT);
size_t msg_len = sizeof(CreateRegionDataInitialMessage) + size_sz;
char buf[msg_len];
CreateRegionDataInitialMessage* msg = (CreateRegionDataInitialMessage*)buf;
msg->type = MessageTypes::CREATEREGIONDATA;
msg->dimensions = _D;
memcpy(msg->size, size, size_sz);
host->createRemoteObject(_remoteObject.asPtr(), &RegionMatrixProxy::genRemote, buf, msg_len);
}
RegionDataRemote::RegionDataRemote(const int dimensions, const IndexT* size, RemoteHost& host, const MessageType initialMessageType, const EncodedPtr encodePtr) {
init(dimensions, size, new RegionDataRemoteObject());
// InitialMsg
EncodedPtrInitialMessage msg;
msg.type = initialMessageType;
msg.encodedPtr = encodePtr;
int len = sizeof(EncodedPtrInitialMessage);
host.createRemoteObject(_remoteObject.asPtr(), &RegionMatrixProxy::genRemote, &msg, len);
}
void RegionDataRemote::init(const int dimensions, const IndexT* size, const RegionDataRemoteObjectPtr remoteObject) {
_D = dimensions;
_type = RegionDataTypes::REGIONDATAREMOTE;
_remoteObject = remoteObject;
memcpy(_size, size, sizeof(IndexT) * _D);
}
int RegionDataRemote::allocData() {
void* data;
size_t len;
this->fetchData(0, MessageTypes::ALLOCDATA, 0, &data, &len);
AllocDataReplyMessage* reply = (AllocDataReplyMessage*)data;
ElementT result = reply->result;
free(reply);
return result;
}
void RegionDataRemote::randomize() {
void* data;
size_t len;
this->fetchData(0, MessageTypes::RANDOMIZEDATA, 0, &data, &len);
free(data);
}
IRegionCachePtr RegionDataRemote::cacheGenerator() const {
IndexT multipliers[_D];
multipliers[0] = 1;
for (int i = 1; i < _D; i++) {
multipliers[i] = multipliers[i - 1] * _size[i - 1];
}
return new RegionDataRemoteCache(this, _D, multipliers);
}
IRegionCachePtr RegionDataRemote::cache() const {
#ifdef DISTRIBUTED_CACHE
if (WorkerThread::self()) {
return WorkerThread::self()->cache()->get(this);
} else {
// in listening loop
return NULL;
}
#else
return NULL;
#endif
}
void RegionDataRemote::invalidateCache() {
#ifdef DISTRIBUTED_CACHE
if (cache()) {
cache()->invalidate();
}
#endif
}
ElementT RegionDataRemote::readCell(const IndexT* coord) const {
#ifdef DISTRIBUTED_CACHE
if (cache()) {
return cache()->readCell(coord);
} else {
return readNoCache(coord);
}
#else
return readNoCache(coord);
#endif
}
ElementT RegionDataRemote::readNoCache(const IndexT* coord) const {
size_t coord_sz = _D * sizeof(IndexT);
size_t msg_len = sizeof(ReadCellMessage) + coord_sz;
char buf[msg_len];
ReadCellMessage* msg = (ReadCellMessage*)buf;
memcpy(msg->coord, coord, coord_sz);
void* data;
size_t len;
this->fetchData(buf, MessageTypes::READCELL, msg_len, &data, &len);
ReadCellReplyMessage* reply = (ReadCellReplyMessage*)data;
ElementT value = reply->value;
free(reply);
return value;
}
void RegionDataRemote::readByCache(void* request, size_t request_len, void* reply, size_t &/*reply_len*/) const {
void* data;
size_t len;
this->fetchData(request, MessageTypes::READCELLCACHE, request_len, &data, &len);
ReadCellCacheReplyMessage* r = (ReadCellCacheReplyMessage*)data;
RegionDataRemoteCacheLine* cacheLine = (RegionDataRemoteCacheLine*)reply;
cacheLine->start = r->start;
cacheLine->end = r->end;
memcpy(cacheLine->base, r->values, sizeof(ElementT) * (r->end + 1));
free(r);
}
void RegionDataRemote::writeCell(const IndexT* coord, ElementT value) {
#ifdef DISTRIBUTED_CACHE
if (cache()) {
cache()->writeCell(coord, value);
} else {
writeNoCache(coord, value);
}
#else
writeNoCache(coord, value);
#endif
}
void RegionDataRemote::writeNoCache(const IndexT* coord, ElementT value) {
size_t coord_sz = _D * sizeof(IndexT);
size_t msg_len = sizeof(WriteCellMessage) + coord_sz;
char buf[msg_len];
WriteCellMessage* msg = (WriteCellMessage*)buf;
msg->value = value;
memcpy(msg->coord, coord, coord_sz);
//JTRACE("write")(_D)(sizeof(IndexT))(coord_sz)(msg_len);
void* data;
size_t len;
this->fetchData(buf, MessageTypes::WRITECELL, msg_len, &data, &len);
WriteCellReplyMessage* reply = (WriteCellReplyMessage*)data;
free(reply);
}
void RegionDataRemote::writeByCache(const IndexT* coord, ElementT value) const {
size_t coord_sz = _D * sizeof(IndexT);
size_t msg_len = sizeof(WriteCellMessage) + coord_sz;
char buf[msg_len];
WriteCellMessage* msg = (WriteCellMessage*)buf;
msg->value = value;
memcpy(msg->coord, coord, coord_sz);
void* data;
size_t len;
this->fetchData(msg, MessageTypes::WRITECELL, msg_len, &data, &len);
WriteCellReplyMessage* reply = (WriteCellReplyMessage*)data;
free(reply);
}
void RegionDataRemote::copyToScratchMatrixStorage(CopyToMatrixStorageMessage* origMetadata, size_t len, MatrixStoragePtr scratchStorage, MatrixRegionMetadata* scratchMetadata) const {
void* data;
size_t replyLen;
this->fetchData(origMetadata, MessageTypes::TOSCRATCHSTORAGE, len, &data, &replyLen);
CopyToMatrixStorageReplyMessage* reply = (CopyToMatrixStorageReplyMessage*)data;
if (scratchMetadata == 0) {
JASSERT(reply->count == scratchStorage->count());
memcpy(scratchStorage->data(), reply->storage, sizeof(ElementT) * reply->count);
} else {
UNIMPLEMENTED();
}
free(reply);
}
void RegionDataRemote::copyFromScratchMatrixStorage(CopyFromMatrixStorageMessage* metadata, size_t size) const {
void* data;
size_t len;
this->fetchData(metadata, MessageTypes::FROMSCRATCHSTORAGE, size, &data, &len);
free(data);
}
DataHostPidList RegionDataRemote::hosts(IndexT* begin, IndexT* end) {
GetHostListMessage msg;
memcpy(msg.begin, begin, _D * sizeof(IndexT));
memcpy(msg.end, end, _D * sizeof(IndexT));
void* data;
size_t len;
this->fetchData(&msg, MessageTypes::GETHOSTLIST, sizeof(GetHostListMessage), &data, &len);
GetHostListReplyMessage* reply = (GetHostListReplyMessage*)data;
DataHostPidList list;
for (int i = 0; i < reply->numHosts; i++) {
list.push_back(reply->hosts[i]);
}
free(reply);
return list;
}
RemoteHostPtr RegionDataRemote::host() {
return _remoteObject->host();
}
UpdateHandlerChainReplyMessage RegionDataRemote::updateHandlerChain(UpdateHandlerChainMessage& msg) {
msg.numHops += 1;
void* data;
size_t len;
this->fetchData(&msg, MessageTypes::UPDATEHANDLERCHAIN, sizeof(UpdateHandlerChainMessage), &data, &len);
UpdateHandlerChainReplyMessage* _reply = (UpdateHandlerChainReplyMessage*)data;
UpdateHandlerChainReplyMessage reply = *_reply;
free(_reply);
return reply;
}
UpdateHandlerChainReplyMessage RegionDataRemote::updateHandlerChain() {
UpdateHandlerChainMessage msg;
msg.requester = HostPid::self();
msg.numHops = 0;
return this->updateHandlerChain(msg);
}
void RegionDataRemote::fetchData(const void* msg, MessageType type, size_t len, void** responseData, size_t* responseLen) const {
*responseData = 0;
*responseLen = 0;
size_t dataLen = sizeof(GeneralMessageHeader) + len;
GeneralMessageHeader* header = (GeneralMessageHeader*)malloc(dataLen);
header->isForwardMessage = false;
header->type = type;
header->contentOffset = sizeof(GeneralMessageHeader);
header->responseData = reinterpret_cast<EncodedPtr>(responseData);
header->responseLen = reinterpret_cast<EncodedPtr>(responseLen);
memcpy(header->content(), msg, len);
_remoteObject->send(header, dataLen);
free(header);
JLOCKSCOPE(*_remoteObject);
// wait for the data
while (*responseData == 0 || *responseLen == 0) {
_remoteObject->waitMsgMu();
}
}
void RegionDataRemote::onRecv(const void* data, size_t len) {
const BaseMessageHeader* base = (const BaseMessageHeader*)data;
if (base->isForwardMessage) {
const ForwardMessageHeader* header = (const ForwardMessageHeader*)data;
IRegionReplyProxy* proxy = reinterpret_cast<IRegionReplyProxy*>(header->callback);
proxy->processReplyMsg(base, len);
} else {
const GeneralMessageHeader* header = (const GeneralMessageHeader*)data;
const void** responseData = reinterpret_cast<const void**>(header->responseData);
size_t* responseLen = reinterpret_cast<size_t*>(header->responseLen);
size_t sz = len - base->contentOffset;
void* msg = malloc(sz);
memcpy(msg, base->content(), sz);
*responseData = msg;
*responseLen = sz;
}
}
// Process remote messages
void RegionDataRemote::forwardMessage(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller) {
size_t len = sizeof(ForwardMessageHeader) + baseLen;
ForwardMessageHeader* data = (ForwardMessageHeader*)malloc(len);
data->isForwardMessage = true;
data->type = base->type;
data->contentOffset = sizeof(ForwardMessageHeader) + base->contentOffset;
data->callback = reinterpret_cast<EncodedPtr>(caller);
memcpy(data->next(), base, baseLen);
_remoteObject->send(data, len);
free(data);
}
void RegionDataRemote::processReadCellMsg(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller) {
this->forwardMessage(base, baseLen, caller);
}
void RegionDataRemote::processWriteCellMsg(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller) {
this->forwardMessage(base, baseLen, caller);
}
void RegionDataRemote::processAllocDataMsg(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller) {
this->forwardMessage(base, baseLen, caller);
}
void RegionDataRemote::processRandomizeDataMsg(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller) {
this->forwardMessage(base, baseLen, caller);
}
void RegionDataRemote::processUpdateHandlerChainMsg(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller, RegionDataIPtr) {
UpdateHandlerChainMessage* msg = (UpdateHandlerChainMessage*)base->content();
msg->numHops++;
this->forwardMessage(base, baseLen, caller);
}
void RegionDataRemote::processGetHostListMsg(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller) {
this->forwardMessage(base, baseLen, caller);
}
void RegionDataRemote::processGetMatrixStorageMsg(const BaseMessageHeader* base, size_t baseLen, IRegionReplyProxy* caller) {
this->forwardMessage(base, baseLen, caller);
}
RemoteObjectPtr RegionDataRemote::genRemote() {
return new RegionDataRemoteObject();
}
<|endoftext|>
|
<commit_before><commit_msg>add MAYACAL<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "views/bubble/bubble_frame_view.h"
#include <algorithm>
#include "views/bubble/bubble_border.h"
#include "views/bubble/border_contents_view.h"
#include "views/widget/widget.h"
#include "views/window/client_view.h"
namespace views {
BubbleFrameView::BubbleFrameView(BubbleBorder::ArrowLocation location,
const gfx::Size& client_size,
SkColor color,
bool allow_bubble_offscreen)
: border_contents_(new BorderContentsView()),
location_(location),
allow_bubble_offscreen_(allow_bubble_offscreen) {
border_contents_->Init();
bubble_border()->set_arrow_location(location_);
bubble_border()->set_background_color(color);
AddChildView(border_contents_);
gfx::Rect bounds(gfx::Point(), client_size);
gfx::Rect windows_bounds = GetWindowBoundsForClientBounds(bounds);
border_contents_->SetBoundsRect(
gfx::Rect(gfx::Point(), windows_bounds.size()));
SetBoundsRect(windows_bounds);
}
BubbleFrameView::~BubbleFrameView() {}
gfx::Rect BubbleFrameView::GetBoundsForClientView() const {
gfx::Insets margin;
bubble_border()->GetInsets(&margin);
margin += border_contents_->content_margins();
return gfx::Rect(margin.left(),
margin.top(),
std::max(width() - margin.width(), 0),
std::max(height() - margin.height(), 0));
}
gfx::Rect BubbleFrameView::GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const {
// The |client_bounds| origin is the bubble arrow anchor point.
gfx::Rect position_relative_to(client_bounds.origin(), gfx::Size());
// The |client_bounds| size is the bubble client view size.
gfx::Rect content_bounds;
gfx::Rect window_bounds;
border_contents_->SizeAndGetBounds(position_relative_to,
location_,
allow_bubble_offscreen_,
client_bounds.size(),
&content_bounds,
&window_bounds);
return window_bounds;
}
int BubbleFrameView::NonClientHitTest(const gfx::Point& point) {
return GetWidget()->client_view()->NonClientHitTest(point);
}
gfx::Size BubbleFrameView::GetPreferredSize() {
Widget* widget = GetWidget();
gfx::Rect rect(gfx::Point(), widget->client_view()->GetPreferredSize());
return widget->non_client_view()->GetWindowBoundsForClientBounds(rect).size();
}
BubbleBorder* BubbleFrameView::bubble_border() const {
return static_cast<BubbleBorder*>(border_contents_->border());
}
} // namespace views
<commit_msg>Set FillLayout on BubbleFrameView. Make bubbles' BorderContentsView fill the BubbleFrameView. Fixes a sizing issue with the in-progress bubble conversions.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "views/bubble/bubble_frame_view.h"
#include <algorithm>
#include "views/bubble/bubble_border.h"
#include "views/bubble/border_contents_view.h"
#include "views/layout/fill_layout.h"
#include "views/widget/widget.h"
#include "views/window/client_view.h"
namespace views {
BubbleFrameView::BubbleFrameView(BubbleBorder::ArrowLocation location,
const gfx::Size& client_size,
SkColor color,
bool allow_bubble_offscreen)
: border_contents_(new BorderContentsView()),
location_(location),
allow_bubble_offscreen_(allow_bubble_offscreen) {
border_contents_->Init();
bubble_border()->set_arrow_location(location_);
bubble_border()->set_background_color(color);
SetLayoutManager(new views::FillLayout());
AddChildView(border_contents_);
gfx::Rect bounds(gfx::Point(), client_size);
gfx::Rect windows_bounds = GetWindowBoundsForClientBounds(bounds);
border_contents_->SetBoundsRect(
gfx::Rect(gfx::Point(), windows_bounds.size()));
SetBoundsRect(windows_bounds);
}
BubbleFrameView::~BubbleFrameView() {}
gfx::Rect BubbleFrameView::GetBoundsForClientView() const {
gfx::Insets margin;
bubble_border()->GetInsets(&margin);
margin += border_contents_->content_margins();
return gfx::Rect(margin.left(),
margin.top(),
std::max(width() - margin.width(), 0),
std::max(height() - margin.height(), 0));
}
gfx::Rect BubbleFrameView::GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const {
// The |client_bounds| origin is the bubble arrow anchor point.
gfx::Rect position_relative_to(client_bounds.origin(), gfx::Size());
// The |client_bounds| size is the bubble client view size.
gfx::Rect content_bounds;
gfx::Rect window_bounds;
border_contents_->SizeAndGetBounds(position_relative_to,
location_,
allow_bubble_offscreen_,
client_bounds.size(),
&content_bounds,
&window_bounds);
return window_bounds;
}
int BubbleFrameView::NonClientHitTest(const gfx::Point& point) {
return GetWidget()->client_view()->NonClientHitTest(point);
}
gfx::Size BubbleFrameView::GetPreferredSize() {
Widget* widget = GetWidget();
gfx::Rect rect(gfx::Point(), widget->client_view()->GetPreferredSize());
return widget->non_client_view()->GetWindowBoundsForClientBounds(rect).size();
}
BubbleBorder* BubbleFrameView::bubble_border() const {
return static_cast<BubbleBorder*>(border_contents_->border());
}
} // namespace views
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id: mapnik_envelope.cc 27 2005-03-30 21:45:40Z pavlenko $
// boost
#include <boost/python.hpp>
// mapnik
#include <mapnik/box2d.hpp>
#include <mapnik/value_error.hpp>
using mapnik::coord;
using mapnik::box2d;
struct envelope_pickle_suite : boost::python::pickle_suite
{
static boost::python::tuple
getinitargs(const box2d<double>& e)
{
using namespace boost::python;
return boost::python::make_tuple(e.minx(),e.miny(),e.maxx(),e.maxy());
}
};
box2d<double> from_string(std::string const& s)
{
box2d<double> bbox;
bool success = bbox.from_string(s);
if (success)
{
return bbox;
}
else
{
std::stringstream ss;
ss << "Could not parse bbox from string: '" << s << "'";
throw mapnik::value_error(ss.str());
}
}
//define overloads here
void (box2d<double>::*width_p1)(double) = &box2d<double>::width;
double (box2d<double>::*width_p2)() const = &box2d<double>::width;
void (box2d<double>::*height_p1)(double) = &box2d<double>::height;
double (box2d<double>::*height_p2)() const = &box2d<double>::height;
void (box2d<double>::*expand_to_include_p1)(double,double) = &box2d<double>::expand_to_include;
void (box2d<double>::*expand_to_include_p2)(coord<double,2> const& ) = &box2d<double>::expand_to_include;
void (box2d<double>::*expand_to_include_p3)(box2d<double> const& ) = &box2d<double>::expand_to_include;
bool (box2d<double>::*contains_p1)(double,double) const = &box2d<double>::contains;
bool (box2d<double>::*contains_p2)(coord<double,2> const&) const = &box2d<double>::contains;
bool (box2d<double>::*contains_p3)(box2d<double> const&) const = &box2d<double>::contains;
//intersects
bool (box2d<double>::*intersects_p1)(double,double) const = &box2d<double>::intersects;
bool (box2d<double>::*intersects_p2)(coord<double,2> const&) const = &box2d<double>::intersects;
bool (box2d<double>::*intersects_p3)(box2d<double> const&) const = &box2d<double>::intersects;
// intersect
box2d<double> (box2d<double>::*intersect)(box2d<double> const&) const = &box2d<double>::intersect;
// re_center
void (box2d<double>::*re_center_p1)(double,double) = &box2d<double>::re_center;
void (box2d<double>::*re_center_p2)(coord<double,2> const& ) = &box2d<double>::re_center;
// clip
void (box2d<double>::*clip)(box2d<double> const&) = &box2d<double>::clip;
void export_envelope()
{
using namespace boost::python;
class_<box2d<double> >("Box2d",
// class docstring is in mapnik/__init__.py, class _Coord
init<double,double,double,double>(
(arg("minx"),arg("miny"),arg("maxx"),arg("maxy")),
"Constructs a new envelope from the coordinates\n"
"of its lower left and upper right corner points.\n"))
.def(init<>("Equivalent to Box2d(0, 0, -1, -1).\n"))
.def(init<const coord<double,2>&, const coord<double,2>&>(
(arg("ll"),arg("ur")),
"Equivalent to Box2d(ll.x, ll.y, ur.x, ur.y).\n"))
.def("from_string",from_string)
.staticmethod("from_string")
.add_property("minx", &box2d<double>::minx,
"X coordinate for the lower left corner")
.add_property("miny", &box2d<double>::miny,
"Y coordinate for the lower left corner")
.add_property("maxx", &box2d<double>::maxx,
"X coordinate for the upper right corner")
.add_property("maxy", &box2d<double>::maxy,
"Y coordinate for the upper right corner")
.def("center", &box2d<double>::center,
"Returns the coordinates of the center of the bounding box.\n"
"\n"
"Example:\n"
">>> e = Box2d(0, 0, 100, 100)\n"
">>> e.center()\n"
"Coord(50, 50)\n")
.def("center", re_center_p1,
(arg("x"), arg("y")),
"Moves the envelope so that the given coordinates become its new center.\n"
"The width and the height are preserved.\n"
"\n "
"Example:\n"
">>> e = Box2d(0, 0, 100, 100)\n"
">>> e.center(60, 60)\n"
">>> e.center()\n"
"Coord(60.0,60.0)\n"
">>> (e.width(), e.height())\n"
"(100.0, 100.0)\n"
">>> e\n"
"Box2d(10.0, 10.0, 110.0, 110.0)\n"
)
.def("center", re_center_p2,
(arg("Coord")),
"Moves the envelope so that the given coordinates become its new center.\n"
"The width and the height are preserved.\n"
"\n "
"Example:\n"
">>> e = Box2d(0, 0, 100, 100)\n"
">>> e.center(Coord60, 60)\n"
">>> e.center()\n"
"Coord(60.0,60.0)\n"
">>> (e.width(), e.height())\n"
"(100.0, 100.0)\n"
">>> e\n"
"Box2d(10.0, 10.0, 110.0, 110.0)\n"
)
.def("clip", clip,
(arg("other")),
"Clip the envelope based on the bounds of another envelope.\n"
"\n "
"Example:\n"
">>> e = Box2d(0, 0, 100, 100)\n"
">>> e.center(Coord60, 60)\n"
">>> e.center()\n"
"Coord(60.0,60.0)\n"
">>> (e.width(), e.height())\n"
"(100.0, 100.0)\n"
">>> e\n"
"Box2d(10.0, 10.0, 110.0, 110.0)\n"
)
.def("width", width_p1,
(arg("new_width")),
"Sets the width to new_width of the envelope preserving its center.\n"
"\n "
"Example:\n"
">>> e = Box2d(0, 0, 100, 100)\n"
">>> e.width(120)\n"
">>> e.center()\n"
"Coord(50.0,50.0)\n"
">>> e\n"
"Box2d(-10.0, 0.0, 110.0, 100.0)\n"
)
.def("width", width_p2,
"Returns the width of this envelope.\n"
)
.def("height", height_p1,
(arg("new_height")),
"Sets the height to new_height of the envelope preserving its center.\n"
"\n "
"Example:\n"
">>> e = Box2d(0, 0, 100, 100)\n"
">>> e.height(120)\n"
">>> e.center()\n"
"Coord(50.0,50.0)\n"
">>> e\n"
"Box2d(0.0, -10.0, 100.0, 110.0)\n"
)
.def("height", height_p2,
"Returns the height of this envelope.\n"
)
.def("expand_to_include",expand_to_include_p1,
(arg("x"),arg("y")),
"Expands this envelope to include the point given by x and y.\n"
"\n"
"Example:\n",
">>> e = Box2d(0, 0, 100, 100)\n"
">>> e.expand_to_include(110, 110)\n"
">>> e\n"
"Box2d(0.0, 00.0, 110.0, 110.0)\n"
)
.def("expand_to_include",expand_to_include_p2,
(arg("p")),
"Equivalent to expand_to_include(p.x, p.y)\n"
)
.def("expand_to_include",expand_to_include_p3,
(arg("other")),
"Equivalent to:\n"
" expand_to_include(other.minx, other.miny)\n"
" expand_to_include(other.maxx, other.maxy)\n"
)
.def("contains",contains_p1,
(arg("x"),arg("y")),
"Returns True iff this envelope contains the point\n"
"given by x and y.\n"
)
.def("contains",contains_p2,
(arg("p")),
"Equivalent to contains(p.x, p.y)\n"
)
.def("contains",contains_p3,
(arg("other")),
"Equivalent to:\n"
" contains(other.minx, other.miny) and contains(other.maxx, other.maxy)\n"
)
.def("intersects",intersects_p1,
(arg("x"),arg("y")),
"Returns True iff this envelope intersects the point\n"
"given by x and y.\n"
"\n"
"Note: For points, intersection is equivalent\n"
"to containment, i.e. the following holds:\n"
" e.contains(x, y) == e.intersects(x, y)\n"
)
.def("intersects",intersects_p2,
(arg("p")),
"Equivalent to contains(p.x, p.y)\n")
.def("intersects",intersects_p3,
(arg("other")),
"Returns True iff this envelope intersects the other envelope,\n"
"This relationship is symmetric."
"\n"
"Example:\n"
">>> e1 = Box2d(0, 0, 100, 100)\n"
">>> e2 = Box2d(50, 50, 150, 150)\n"
">>> e1.intersects(e2)\n"
"True\n"
">>> e1.contains(e2)\n"
"False\n"
)
.def("intersect",intersect,
(arg("other")),
"Returns the overlap of this envelope and the other envelope\n"
"as a new envelope.\n"
"\n"
"Example:\n"
">>> e1 = Box2d(0, 0, 100, 100)\n"
">>> e2 = Box2d(50, 50, 150, 150)\n"
">>> e1.intersect(e2)\n"
"Box2d(50.0, 50.0, 100.0, 100.0)\n"
)
.def(self == self) // __eq__
.def(self + self) // __add__
//.def(self - self) // __sub__
.def(self * float()) // __mult__
.def(float() * self)
.def(self / float()) // __div__
.def("__getitem__",&box2d<double>::operator[])
.def_pickle(envelope_pickle_suite())
;
}
<commit_msg>+ add __neq__ operator<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id: mapnik_envelope.cc 27 2005-03-30 21:45:40Z pavlenko $
// boost
#include <boost/python.hpp>
// mapnik
#include <mapnik/box2d.hpp>
#include <mapnik/value_error.hpp>
using mapnik::coord;
using mapnik::box2d;
struct envelope_pickle_suite : boost::python::pickle_suite
{
static boost::python::tuple
getinitargs(const box2d<double>& e)
{
using namespace boost::python;
return boost::python::make_tuple(e.minx(),e.miny(),e.maxx(),e.maxy());
}
};
box2d<double> from_string(std::string const& s)
{
box2d<double> bbox;
bool success = bbox.from_string(s);
if (success)
{
return bbox;
}
else
{
std::stringstream ss;
ss << "Could not parse bbox from string: '" << s << "'";
throw mapnik::value_error(ss.str());
}
}
//define overloads here
void (box2d<double>::*width_p1)(double) = &box2d<double>::width;
double (box2d<double>::*width_p2)() const = &box2d<double>::width;
void (box2d<double>::*height_p1)(double) = &box2d<double>::height;
double (box2d<double>::*height_p2)() const = &box2d<double>::height;
void (box2d<double>::*expand_to_include_p1)(double,double) = &box2d<double>::expand_to_include;
void (box2d<double>::*expand_to_include_p2)(coord<double,2> const& ) = &box2d<double>::expand_to_include;
void (box2d<double>::*expand_to_include_p3)(box2d<double> const& ) = &box2d<double>::expand_to_include;
bool (box2d<double>::*contains_p1)(double,double) const = &box2d<double>::contains;
bool (box2d<double>::*contains_p2)(coord<double,2> const&) const = &box2d<double>::contains;
bool (box2d<double>::*contains_p3)(box2d<double> const&) const = &box2d<double>::contains;
//intersects
bool (box2d<double>::*intersects_p1)(double,double) const = &box2d<double>::intersects;
bool (box2d<double>::*intersects_p2)(coord<double,2> const&) const = &box2d<double>::intersects;
bool (box2d<double>::*intersects_p3)(box2d<double> const&) const = &box2d<double>::intersects;
// intersect
box2d<double> (box2d<double>::*intersect)(box2d<double> const&) const = &box2d<double>::intersect;
// re_center
void (box2d<double>::*re_center_p1)(double,double) = &box2d<double>::re_center;
void (box2d<double>::*re_center_p2)(coord<double,2> const& ) = &box2d<double>::re_center;
// clip
void (box2d<double>::*clip)(box2d<double> const&) = &box2d<double>::clip;
void export_envelope()
{
using namespace boost::python;
class_<box2d<double> >("Box2d",
// class docstring is in mapnik/__init__.py, class _Coord
init<double,double,double,double>(
(arg("minx"),arg("miny"),arg("maxx"),arg("maxy")),
"Constructs a new envelope from the coordinates\n"
"of its lower left and upper right corner points.\n"))
.def(init<>("Equivalent to Box2d(0, 0, -1, -1).\n"))
.def(init<const coord<double,2>&, const coord<double,2>&>(
(arg("ll"),arg("ur")),
"Equivalent to Box2d(ll.x, ll.y, ur.x, ur.y).\n"))
.def("from_string",from_string)
.staticmethod("from_string")
.add_property("minx", &box2d<double>::minx,
"X coordinate for the lower left corner")
.add_property("miny", &box2d<double>::miny,
"Y coordinate for the lower left corner")
.add_property("maxx", &box2d<double>::maxx,
"X coordinate for the upper right corner")
.add_property("maxy", &box2d<double>::maxy,
"Y coordinate for the upper right corner")
.def("center", &box2d<double>::center,
"Returns the coordinates of the center of the bounding box.\n"
"\n"
"Example:\n"
">>> e = Box2d(0, 0, 100, 100)\n"
">>> e.center()\n"
"Coord(50, 50)\n")
.def("center", re_center_p1,
(arg("x"), arg("y")),
"Moves the envelope so that the given coordinates become its new center.\n"
"The width and the height are preserved.\n"
"\n "
"Example:\n"
">>> e = Box2d(0, 0, 100, 100)\n"
">>> e.center(60, 60)\n"
">>> e.center()\n"
"Coord(60.0,60.0)\n"
">>> (e.width(), e.height())\n"
"(100.0, 100.0)\n"
">>> e\n"
"Box2d(10.0, 10.0, 110.0, 110.0)\n"
)
.def("center", re_center_p2,
(arg("Coord")),
"Moves the envelope so that the given coordinates become its new center.\n"
"The width and the height are preserved.\n"
"\n "
"Example:\n"
">>> e = Box2d(0, 0, 100, 100)\n"
">>> e.center(Coord60, 60)\n"
">>> e.center()\n"
"Coord(60.0,60.0)\n"
">>> (e.width(), e.height())\n"
"(100.0, 100.0)\n"
">>> e\n"
"Box2d(10.0, 10.0, 110.0, 110.0)\n"
)
.def("clip", clip,
(arg("other")),
"Clip the envelope based on the bounds of another envelope.\n"
"\n "
"Example:\n"
">>> e = Box2d(0, 0, 100, 100)\n"
">>> e.center(Coord60, 60)\n"
">>> e.center()\n"
"Coord(60.0,60.0)\n"
">>> (e.width(), e.height())\n"
"(100.0, 100.0)\n"
">>> e\n"
"Box2d(10.0, 10.0, 110.0, 110.0)\n"
)
.def("width", width_p1,
(arg("new_width")),
"Sets the width to new_width of the envelope preserving its center.\n"
"\n "
"Example:\n"
">>> e = Box2d(0, 0, 100, 100)\n"
">>> e.width(120)\n"
">>> e.center()\n"
"Coord(50.0,50.0)\n"
">>> e\n"
"Box2d(-10.0, 0.0, 110.0, 100.0)\n"
)
.def("width", width_p2,
"Returns the width of this envelope.\n"
)
.def("height", height_p1,
(arg("new_height")),
"Sets the height to new_height of the envelope preserving its center.\n"
"\n "
"Example:\n"
">>> e = Box2d(0, 0, 100, 100)\n"
">>> e.height(120)\n"
">>> e.center()\n"
"Coord(50.0,50.0)\n"
">>> e\n"
"Box2d(0.0, -10.0, 100.0, 110.0)\n"
)
.def("height", height_p2,
"Returns the height of this envelope.\n"
)
.def("expand_to_include",expand_to_include_p1,
(arg("x"),arg("y")),
"Expands this envelope to include the point given by x and y.\n"
"\n"
"Example:\n",
">>> e = Box2d(0, 0, 100, 100)\n"
">>> e.expand_to_include(110, 110)\n"
">>> e\n"
"Box2d(0.0, 00.0, 110.0, 110.0)\n"
)
.def("expand_to_include",expand_to_include_p2,
(arg("p")),
"Equivalent to expand_to_include(p.x, p.y)\n"
)
.def("expand_to_include",expand_to_include_p3,
(arg("other")),
"Equivalent to:\n"
" expand_to_include(other.minx, other.miny)\n"
" expand_to_include(other.maxx, other.maxy)\n"
)
.def("contains",contains_p1,
(arg("x"),arg("y")),
"Returns True iff this envelope contains the point\n"
"given by x and y.\n"
)
.def("contains",contains_p2,
(arg("p")),
"Equivalent to contains(p.x, p.y)\n"
)
.def("contains",contains_p3,
(arg("other")),
"Equivalent to:\n"
" contains(other.minx, other.miny) and contains(other.maxx, other.maxy)\n"
)
.def("intersects",intersects_p1,
(arg("x"),arg("y")),
"Returns True iff this envelope intersects the point\n"
"given by x and y.\n"
"\n"
"Note: For points, intersection is equivalent\n"
"to containment, i.e. the following holds:\n"
" e.contains(x, y) == e.intersects(x, y)\n"
)
.def("intersects",intersects_p2,
(arg("p")),
"Equivalent to contains(p.x, p.y)\n")
.def("intersects",intersects_p3,
(arg("other")),
"Returns True iff this envelope intersects the other envelope,\n"
"This relationship is symmetric."
"\n"
"Example:\n"
">>> e1 = Box2d(0, 0, 100, 100)\n"
">>> e2 = Box2d(50, 50, 150, 150)\n"
">>> e1.intersects(e2)\n"
"True\n"
">>> e1.contains(e2)\n"
"False\n"
)
.def("intersect",intersect,
(arg("other")),
"Returns the overlap of this envelope and the other envelope\n"
"as a new envelope.\n"
"\n"
"Example:\n"
">>> e1 = Box2d(0, 0, 100, 100)\n"
">>> e2 = Box2d(50, 50, 150, 150)\n"
">>> e1.intersect(e2)\n"
"Box2d(50.0, 50.0, 100.0, 100.0)\n"
)
.def(self == self) // __eq__
.def(self != self) // __neq__
.def(self + self) // __add__
//.def(self - self) // __sub__
.def(self * float()) // __mult__
.def(float() * self)
.def(self / float()) // __div__
.def("__getitem__",&box2d<double>::operator[])
.def_pickle(envelope_pickle_suite())
;
}
<|endoftext|>
|
<commit_before><commit_msg>fixed: function with 4 args (0.9)<commit_after><|endoftext|>
|
<commit_before>#include "object_manipulation_actions/actionExecutorInspectLocation.h"
#include <pluginlib/class_list_macros.h>
#include <ork_to_planning_scene_msgs/UpdatePlanningSceneFromOrkAction.h>
//#include <moveit/move_group_interface/move_group.h>
#include <control_msgs/SingleJointPositionActionFeedback.h>
#include <control_msgs/SingleJointPositionFeedback.h>
#include <tidyup_utils/stringutil.h>
#include <symbolic_planning_utils/extractPose.h>
#include <symbolic_planning_utils/planning_scene_monitor.h>
#include <symbolic_planning_utils/planning_scene_service.h>
#include <set>
#include <boost/foreach.hpp>
#define for_each BOOST_FOREACH
#include <pluginlib/class_loader.h>
#include <ros/ros.h>
PLUGINLIB_EXPORT_CLASS(object_manipulation_actions::ActionExecutorInspectLocation, continual_planning_executive::ActionExecutorInterface)
namespace object_manipulation_actions
{
ActionExecutorInspectLocation::ActionExecutorInspectLocation() :
actionLiftTorso_("torso_controller/position_joint_action", true),
actionPointHead_("head_traj_controller/point_head_action", true),
actionOrkToPs_("ork_to_planning_scene", true)
{
actionTimeOut_ = ros::Duration(30.0);
torsoPosition_ = -1.0;
setTorsoPosition_ = false;
ROS_INFO("ActionExecutorInspectLocation::%s: Waiting for torso_controller/position_joint_action "
"action server to start.", __func__);
actionLiftTorso_.waitForServer();
ROS_INFO("ActionExecutorInspectLocation::%s: Waiting for head_traj_controller/point_head_action "
"action server to start.", __func__);
actionPointHead_.waitForServer();
ROS_INFO("ActionExecutorInspectLocation::%s: Waiting for ork_to_planning_scene "
"action server to start.", __func__);
actionOrkToPs_.waitForServer();
ROS_INFO("ActionExecutorInspectLocation::%s: Action clients are ready", __func__);
ros::NodeHandle nhPriv("~");
// Namespace is "/continual_planning_executive"(/vdist_head_to_table)
nhPriv.param("vdist_head_to_table", vdist_head_to_table_, 0.8);
nhPriv.param("vdist_threshold", vdist_threshold_, 0.002);
nhPriv.param("min_torso_vel", min_torso_vel_, 0.0001);
nhPriv.param("stallThreshold", stallThreshold_, 5);
add_tables_ = true;
verify_planning_scene_update_ = true;
psi_.reset(new symbolic_planning_utils::PlanningSceneMonitor());
//psi_.reset(new symbolic_planning_utils::PlanningSceneService());
}
ActionExecutorInspectLocation::~ActionExecutorInspectLocation()
{
}
void ActionExecutorInspectLocation::initialize(const std::deque<std::string> & arguments)
{
ROS_ASSERT(arguments.size() >= 3);
action_name_ = arguments[0];
action_topic_ = arguments[1];
for (int i = 2; i < arguments.size(); i++)
{
predicate_names_.push_back(arguments[i]);
}
}
bool ActionExecutorInspectLocation::canExecute(const DurativeAction & a, const SymbolicState & currentState) const
{
return a.name == action_name_;
}
bool ActionExecutorInspectLocation::executeBlocking(const DurativeAction & a, SymbolicState & currentState)
{
ROS_ASSERT(a.parameters.size() == 2);
std::string mani_loc = a.parameters[0];
std::string table = a.parameters[1];
// get tablePose
geometry_msgs::PoseStamped tablePose;
if (!symbolic_planning_utils::extractPoseStampedFromSymbolicState(currentState, table, tablePose))
{
ROS_ERROR("ActionExecutorInspectLocation::%s: Could not extract pose of table:%s from symbolic state", __func__, table.c_str());
return false;
}
if (!executeLiftTorso(tablePose))
return false;
if (!executePointHead(tablePose))
return false;
if (!executeUpdatePlanningSceneFromORK(currentState, table, mani_loc))
return false;
renameTableCollisionObject(table);
return true;
}
void ActionExecutorInspectLocation::cancelAction()
{
}
void ActionExecutorInspectLocation::feedbackLiftTorso(const control_msgs::SingleJointPositionFeedbackConstPtr& feedback)
{
if (setTorsoPosition_)
{
torsoPosition_ = feedback->position;
actionLiftTorso_.cancelGoal();
setTorsoPosition_ = false;
return;
}
if (fabs(feedback->velocity) < min_torso_vel_)
{
if (startStallTime_ == 0)
startStallTime_ = ros::Time::now().toSec();
// waited longer than stallThreshold_ -> torso is stalled
else if ((ros::Time::now().toSec() - startStallTime_) > stallThreshold_)
{
ROS_WARN("ActionExecutorInspectLocation::%s: Torso stalled - limit reached (Position: %lf, Velocity: %lf)",
__func__, feedback->position, feedback->velocity);
actionLiftTorso_.cancelGoal();
control_msgs::SingleJointPositionGoal liftTorsoGoal;
liftTorsoGoal.position = feedback->position;
actionLiftTorso_.sendGoal(liftTorsoGoal);
}
}
ROS_DEBUG_STREAM_THROTTLE(0.10, "Torso Joint Position: " << feedback->position << " , Velocity: " << feedback->velocity << " , Error: " << feedback->error);
}
bool ActionExecutorInspectLocation::executeLiftTorso(const geometry_msgs::PoseStamped tablePose)
{
// compute difference in height between head_mount_link and table
// transform tablePose into frame of /base link
geometry_msgs::PoseStamped table_transformed;
try {
tf_.waitForTransform("/base_link", tablePose.header.frame_id, tablePose.header.stamp,
ros::Duration(0.5));
tf_.transformPose("/base_link", tablePose, table_transformed);
} catch (tf::TransformException& ex) {
ROS_ERROR("%s", ex.what());
return false;
}
ROS_DEBUG_STREAM("table pose" << tablePose);
ROS_DEBUG_STREAM("table pose transformed" << table_transformed);
// transform headPose into frame of /base link
tf::Pose tfHead;
geometry_msgs::PoseStamped headPose;
headPose.header.frame_id = "/head_mount_link";
headPose.header.stamp = ros::Time::now();
geometry_msgs::Quaternion q;
q.x = 0;
q.y = 0;
q.z = 0;
q.w = 1;
headPose.pose.orientation = q;
geometry_msgs::Point p;
p.x = 0;
p.y = 0;
p.z = 0;
headPose.pose.position = p;
geometry_msgs::PoseStamped head_transformed;
try {
tf_.waitForTransform("/map", headPose.header.frame_id, headPose.header.stamp,
ros::Duration(0.5));
tf_.transformPose("/map", headPose, head_transformed);
} catch (tf::TransformException& ex) {
ROS_ERROR("%s", ex.what());
return false;
}
ROS_DEBUG_STREAM("head pose transformed" << head_transformed);
double distance = fabs(head_transformed.pose.position.z - table_transformed.pose.position.z);
ROS_DEBUG("Distance: %lf, head: %lf, table: %lf", distance, head_transformed.pose.position.z, table_transformed.pose.position.z);
if (vdist_head_to_table_ - vdist_threshold_ < distance &&
distance < vdist_head_to_table_ + vdist_threshold_)
// head_mount_link is about vdist_head_to_table_ above table, no need to lift torso
return true;
setTorsoPosition();
ROS_INFO("ActionExecutorInspectLocation::%s: Sending LiftTorso request.", __func__);
control_msgs::SingleJointPositionGoal liftTorsoGoal;
liftTorsoGoal.position = torsoPosition_ + vdist_head_to_table_ - distance;
ROS_DEBUG_STREAM("Lift torso about : " << torsoPosition_ << " + " << vdist_head_to_table_ << " - " << distance <<
" = " << torsoPosition_ + vdist_head_to_table_ - distance);
startStallTime_ = 0;
//actionLiftTorso_.sendGoal(liftTorsoGoal);
// Checking if torso is stalled, if so cancel action and start new action with current position
// Then actionLiftTorso will end immediately with success
actionLiftTorso_.sendGoal(liftTorsoGoal,
actionlib::SimpleActionClient<control_msgs::SingleJointPositionAction>::SimpleDoneCallback(), // = NULL
actionlib::SimpleActionClient<control_msgs::SingleJointPositionAction>::SimpleActiveCallback(), // = NULL
boost::bind(&ActionExecutorInspectLocation::feedbackLiftTorso, this, _1));
bool finished_before_timeout = actionLiftTorso_.waitForResult(actionTimeOut_);
if (finished_before_timeout)
{
actionlib::SimpleClientGoalState state = actionLiftTorso_.getState();
ROS_DEBUG("ActionExecutorInspectLocation::%s: Lift Torso Action finished: %s", __func__, state.toString().c_str());
if (state != actionlib::SimpleClientGoalState::SUCCEEDED)
{
ROS_ERROR("ActionExecutorInspectLocation::%s: Lift Torso Action failed.", __func__);
return false;
}
}
return true;
}
void ActionExecutorInspectLocation::setTorsoPosition()
{
ROS_INFO("ActionExecutorInspectLocation::%s: Sending LiftTorso request.", __func__);
control_msgs::SingleJointPositionGoal liftTorsoGoal;
liftTorsoGoal.position = 0.32;
setTorsoPosition_ = true;
// http://library.isr.ist.utl.pt/docs/roswiki/actionlib_tutorials%282f%29Tutorials%282f%29Writing%2820%29a%2820%29Callback%2820%29Based%2820%29Simple%2820%29Action%2820%29Client.html
// actionLiftTorso_.sendGoal(liftTorsoGoal,
// boost::bind(&ActionExecutorInspectLocation::doneLiftTorso, this, _1, _2),
// actionlib::SimpleActionClient<control_msgs::SingleJointPositionAction>::SimpleActiveCallback(),
// actionlib::SimpleActionClient<control_msgs::SingleJointPositionAction>::SimpleFeedbackCallback());
actionLiftTorso_.sendGoal(liftTorsoGoal,
actionlib::SimpleActionClient<control_msgs::SingleJointPositionAction>::SimpleDoneCallback(), // = NULL
actionlib::SimpleActionClient<control_msgs::SingleJointPositionAction>::SimpleActiveCallback(), // = NULL
boost::bind(&ActionExecutorInspectLocation::feedbackLiftTorso, this, _1));
actionLiftTorso_.waitForResult(actionTimeOut_);
}
bool ActionExecutorInspectLocation::executePointHead(const geometry_msgs::PoseStamped tablePose)
{
ROS_INFO("ActionExecutorInspectLocation::%s: Sending PointHead request.", __func__);
control_msgs::PointHeadGoal pointHeadGoal;
geometry_msgs::PointStamped target;
// Set the target pose to the pose of the table
target.point = tablePose.pose.position;
target.header = tablePose.header;
pointHeadGoal.target = target;
// Using x-axis of frame "head_mount_link" for pointing
pointHeadGoal.pointing_axis.x = 1;
pointHeadGoal.pointing_axis.y = 0;
pointHeadGoal.pointing_axis.z = 0;
pointHeadGoal.pointing_frame = "head_mount_link";
actionPointHead_.sendGoal(pointHeadGoal);
bool finished_before_timeout = actionPointHead_.waitForResult(actionTimeOut_);
if (finished_before_timeout)
{
actionlib::SimpleClientGoalState state = actionPointHead_.getState();
ROS_DEBUG("ActionExecutorInspectLocation::%s: Point Head Action finished: %s", __func__, state.toString().c_str());
if (state != actionlib::SimpleClientGoalState::SUCCEEDED)
{
ROS_ERROR("ActionExecutorInspectLocation::%s: Point Head Action failed.", __func__);
return false;
}
}
return true;
}
bool ActionExecutorInspectLocation::executeUpdatePlanningSceneFromORK(SymbolicState& currentState,
const std::string& tableName, const std::string& manipulationLocation)
{
// execute action ork-to-planning-scene
ROS_INFO("ActionExecutorInspectLocation::%s: Sending UpdatePlanningSceneFromORK request.", __func__);
ork_to_planning_scene_msgs::UpdatePlanningSceneFromOrkGoal updatePSGoal;
updatePSGoal.verify_planning_scene_update = verify_planning_scene_update_;
updatePSGoal.add_tables = add_tables_;
updatePSGoal.table_prefix = tableName;
const multimap<string, string> objects = currentState.getTypedObjects();
std::pair<multimap<string, string>::const_iterator, multimap<string, string>::const_iterator> iterators = objects.equal_range("movable_object");
for (multimap<string, string>::const_iterator it = iterators.first; it != iterators.second; it++)
{
Predicate on;
on.name = "object-on";
on.parameters.push_back(it->second);
on.parameters.push_back(tableName);
bool value = false;
currentState.hasBooleanPredicate(on, &value);
if (value)
{
updatePSGoal.expected_objects.push_back(it->second);
}
}
actionOrkToPs_.sendGoal(updatePSGoal);
bool finished_before_timeout = actionOrkToPs_.waitForResult(actionTimeOut_);
if (finished_before_timeout)
{
actionlib::SimpleClientGoalState state = actionOrkToPs_.getState();
ROS_DEBUG("ActionExecutorInspectLocation::%s: ORK to Planning Scene Action finished: %s", __func__, state.toString().c_str());
if (state == actionlib::SimpleClientGoalState::SUCCEEDED)
{
// delete all movable objects from symbolic state, and re-add the important objects later (from PS)
const multimap<string, string> objects = currentState.getTypedObjects();
std::pair<multimap<string, string>::const_iterator, multimap<string, string>::const_iterator> iterators =
objects.equal_range("manipulation_location");
for (multimap<string, string>::const_iterator it = iterators.first; it != iterators.second; it++)
{
// also predicates with the objects are removed
ROS_INFO("ActionExecutorInspectLocation::%s: %s, %s, false", __func__, predicate_names_[0].c_str(), it->second.c_str());
currentState.setBooleanPredicate(predicate_names_[0], it->second, false);
}
ROS_INFO("Inspect location succeeded.");
for_each(const string& predicate, predicate_names_)
{
currentState.setBooleanPredicate(predicate, manipulationLocation, true);
}
}
else
{
ROS_ERROR("ActionExecutorInspectLocation::%s: ORK to Planning Scene Action failed.", __func__);
return false;
}
}
return true;
}
void ActionExecutorInspectLocation::renameTableCollisionObject(const std::string& tableName)
{
moveit_msgs::CollisionObject tableCO;
forEach (const moveit_msgs::CollisionObject& co, psi_->getCollisionObjects())
{
if (StringUtil::startsWith(co.id, tableName))
{
ROS_INFO("ActionExecutorInspectLocation::%s: Found object with id: %s, renaming to: %s", __func__, co.id.c_str(), tableName.c_str());
tableCO = co;
psi_->renameCollisionObject(tableName, tableCO);
}
}
}
}; // namespace
<commit_msg>removed deletion of location-inspected-recently<commit_after>#include "object_manipulation_actions/actionExecutorInspectLocation.h"
#include <pluginlib/class_list_macros.h>
#include <ork_to_planning_scene_msgs/UpdatePlanningSceneFromOrkAction.h>
//#include <moveit/move_group_interface/move_group.h>
#include <control_msgs/SingleJointPositionActionFeedback.h>
#include <control_msgs/SingleJointPositionFeedback.h>
#include <tidyup_utils/stringutil.h>
#include <symbolic_planning_utils/extractPose.h>
#include <symbolic_planning_utils/planning_scene_monitor.h>
#include <symbolic_planning_utils/planning_scene_service.h>
#include <set>
#include <boost/foreach.hpp>
#define for_each BOOST_FOREACH
#include <pluginlib/class_loader.h>
#include <ros/ros.h>
PLUGINLIB_EXPORT_CLASS(object_manipulation_actions::ActionExecutorInspectLocation, continual_planning_executive::ActionExecutorInterface)
namespace object_manipulation_actions
{
ActionExecutorInspectLocation::ActionExecutorInspectLocation() :
actionLiftTorso_("torso_controller/position_joint_action", true),
actionPointHead_("head_traj_controller/point_head_action", true),
actionOrkToPs_("ork_to_planning_scene", true)
{
actionTimeOut_ = ros::Duration(30.0);
torsoPosition_ = -1.0;
setTorsoPosition_ = false;
ROS_INFO("ActionExecutorInspectLocation::%s: Waiting for torso_controller/position_joint_action "
"action server to start.", __func__);
actionLiftTorso_.waitForServer();
ROS_INFO("ActionExecutorInspectLocation::%s: Waiting for head_traj_controller/point_head_action "
"action server to start.", __func__);
actionPointHead_.waitForServer();
ROS_INFO("ActionExecutorInspectLocation::%s: Waiting for ork_to_planning_scene "
"action server to start.", __func__);
actionOrkToPs_.waitForServer();
ROS_INFO("ActionExecutorInspectLocation::%s: Action clients are ready", __func__);
ros::NodeHandle nhPriv("~");
// Namespace is "/continual_planning_executive"(/vdist_head_to_table)
nhPriv.param("vdist_head_to_table", vdist_head_to_table_, 0.8);
nhPriv.param("vdist_threshold", vdist_threshold_, 0.002);
nhPriv.param("min_torso_vel", min_torso_vel_, 0.0001);
nhPriv.param("stallThreshold", stallThreshold_, 5);
add_tables_ = true;
verify_planning_scene_update_ = true;
psi_.reset(new symbolic_planning_utils::PlanningSceneMonitor());
//psi_.reset(new symbolic_planning_utils::PlanningSceneService());
}
ActionExecutorInspectLocation::~ActionExecutorInspectLocation()
{
}
void ActionExecutorInspectLocation::initialize(const std::deque<std::string> & arguments)
{
ROS_ASSERT(arguments.size() >= 3);
action_name_ = arguments[0];
action_topic_ = arguments[1];
for (int i = 2; i < arguments.size(); i++)
{
predicate_names_.push_back(arguments[i]);
}
}
bool ActionExecutorInspectLocation::canExecute(const DurativeAction & a, const SymbolicState & currentState) const
{
return a.name == action_name_;
}
bool ActionExecutorInspectLocation::executeBlocking(const DurativeAction & a, SymbolicState & currentState)
{
ROS_ASSERT(a.parameters.size() == 2);
std::string mani_loc = a.parameters[0];
std::string table = a.parameters[1];
// get tablePose
geometry_msgs::PoseStamped tablePose;
if (!symbolic_planning_utils::extractPoseStampedFromSymbolicState(currentState, table, tablePose))
{
ROS_ERROR("ActionExecutorInspectLocation::%s: Could not extract pose of table:%s from symbolic state", __func__, table.c_str());
return false;
}
if (!executeLiftTorso(tablePose))
return false;
if (!executePointHead(tablePose))
return false;
if (!executeUpdatePlanningSceneFromORK(currentState, table, mani_loc))
return false;
renameTableCollisionObject(table);
return true;
}
void ActionExecutorInspectLocation::cancelAction()
{
}
void ActionExecutorInspectLocation::feedbackLiftTorso(const control_msgs::SingleJointPositionFeedbackConstPtr& feedback)
{
if (setTorsoPosition_)
{
torsoPosition_ = feedback->position;
actionLiftTorso_.cancelGoal();
setTorsoPosition_ = false;
return;
}
if (fabs(feedback->velocity) < min_torso_vel_)
{
if (startStallTime_ == 0)
startStallTime_ = ros::Time::now().toSec();
// waited longer than stallThreshold_ -> torso is stalled
else if ((ros::Time::now().toSec() - startStallTime_) > stallThreshold_)
{
ROS_WARN("ActionExecutorInspectLocation::%s: Torso stalled - limit reached (Position: %lf, Velocity: %lf)",
__func__, feedback->position, feedback->velocity);
actionLiftTorso_.cancelGoal();
control_msgs::SingleJointPositionGoal liftTorsoGoal;
liftTorsoGoal.position = feedback->position;
actionLiftTorso_.sendGoal(liftTorsoGoal);
}
}
ROS_DEBUG_STREAM_THROTTLE(0.10, "Torso Joint Position: " << feedback->position << " , Velocity: " << feedback->velocity << " , Error: " << feedback->error);
}
bool ActionExecutorInspectLocation::executeLiftTorso(const geometry_msgs::PoseStamped tablePose)
{
// compute difference in height between head_mount_link and table
// transform tablePose into frame of /base link
geometry_msgs::PoseStamped table_transformed;
try {
tf_.waitForTransform("/base_link", tablePose.header.frame_id, tablePose.header.stamp,
ros::Duration(0.5));
tf_.transformPose("/base_link", tablePose, table_transformed);
} catch (tf::TransformException& ex) {
ROS_ERROR("%s", ex.what());
return false;
}
ROS_DEBUG_STREAM("table pose" << tablePose);
ROS_DEBUG_STREAM("table pose transformed" << table_transformed);
// transform headPose into frame of /base link
tf::Pose tfHead;
geometry_msgs::PoseStamped headPose;
headPose.header.frame_id = "/head_mount_link";
headPose.header.stamp = ros::Time::now();
geometry_msgs::Quaternion q;
q.x = 0;
q.y = 0;
q.z = 0;
q.w = 1;
headPose.pose.orientation = q;
geometry_msgs::Point p;
p.x = 0;
p.y = 0;
p.z = 0;
headPose.pose.position = p;
geometry_msgs::PoseStamped head_transformed;
try {
tf_.waitForTransform("/map", headPose.header.frame_id, headPose.header.stamp,
ros::Duration(0.5));
tf_.transformPose("/map", headPose, head_transformed);
} catch (tf::TransformException& ex) {
ROS_ERROR("%s", ex.what());
return false;
}
ROS_DEBUG_STREAM("head pose transformed" << head_transformed);
double distance = fabs(head_transformed.pose.position.z - table_transformed.pose.position.z);
ROS_DEBUG("Distance: %lf, head: %lf, table: %lf", distance, head_transformed.pose.position.z, table_transformed.pose.position.z);
if (vdist_head_to_table_ - vdist_threshold_ < distance &&
distance < vdist_head_to_table_ + vdist_threshold_)
// head_mount_link is about vdist_head_to_table_ above table, no need to lift torso
return true;
setTorsoPosition();
ROS_INFO("ActionExecutorInspectLocation::%s: Sending LiftTorso request.", __func__);
control_msgs::SingleJointPositionGoal liftTorsoGoal;
liftTorsoGoal.position = torsoPosition_ + vdist_head_to_table_ - distance;
ROS_DEBUG_STREAM("Lift torso about : " << torsoPosition_ << " + " << vdist_head_to_table_ << " - " << distance <<
" = " << torsoPosition_ + vdist_head_to_table_ - distance);
startStallTime_ = 0;
//actionLiftTorso_.sendGoal(liftTorsoGoal);
// Checking if torso is stalled, if so cancel action and start new action with current position
// Then actionLiftTorso will end immediately with success
actionLiftTorso_.sendGoal(liftTorsoGoal,
actionlib::SimpleActionClient<control_msgs::SingleJointPositionAction>::SimpleDoneCallback(), // = NULL
actionlib::SimpleActionClient<control_msgs::SingleJointPositionAction>::SimpleActiveCallback(), // = NULL
boost::bind(&ActionExecutorInspectLocation::feedbackLiftTorso, this, _1));
bool finished_before_timeout = actionLiftTorso_.waitForResult(actionTimeOut_);
if (finished_before_timeout)
{
actionlib::SimpleClientGoalState state = actionLiftTorso_.getState();
ROS_DEBUG("ActionExecutorInspectLocation::%s: Lift Torso Action finished: %s", __func__, state.toString().c_str());
if (state != actionlib::SimpleClientGoalState::SUCCEEDED)
{
ROS_ERROR("ActionExecutorInspectLocation::%s: Lift Torso Action failed.", __func__);
return false;
}
}
return true;
}
void ActionExecutorInspectLocation::setTorsoPosition()
{
ROS_INFO("ActionExecutorInspectLocation::%s: Sending LiftTorso request.", __func__);
control_msgs::SingleJointPositionGoal liftTorsoGoal;
liftTorsoGoal.position = 0.32;
setTorsoPosition_ = true;
// http://library.isr.ist.utl.pt/docs/roswiki/actionlib_tutorials%282f%29Tutorials%282f%29Writing%2820%29a%2820%29Callback%2820%29Based%2820%29Simple%2820%29Action%2820%29Client.html
// actionLiftTorso_.sendGoal(liftTorsoGoal,
// boost::bind(&ActionExecutorInspectLocation::doneLiftTorso, this, _1, _2),
// actionlib::SimpleActionClient<control_msgs::SingleJointPositionAction>::SimpleActiveCallback(),
// actionlib::SimpleActionClient<control_msgs::SingleJointPositionAction>::SimpleFeedbackCallback());
actionLiftTorso_.sendGoal(liftTorsoGoal,
actionlib::SimpleActionClient<control_msgs::SingleJointPositionAction>::SimpleDoneCallback(), // = NULL
actionlib::SimpleActionClient<control_msgs::SingleJointPositionAction>::SimpleActiveCallback(), // = NULL
boost::bind(&ActionExecutorInspectLocation::feedbackLiftTorso, this, _1));
actionLiftTorso_.waitForResult(actionTimeOut_);
}
bool ActionExecutorInspectLocation::executePointHead(const geometry_msgs::PoseStamped tablePose)
{
ROS_INFO("ActionExecutorInspectLocation::%s: Sending PointHead request.", __func__);
control_msgs::PointHeadGoal pointHeadGoal;
geometry_msgs::PointStamped target;
// Set the target pose to the pose of the table
target.point = tablePose.pose.position;
target.header = tablePose.header;
pointHeadGoal.target = target;
// Using x-axis of frame "head_mount_link" for pointing
pointHeadGoal.pointing_axis.x = 1;
pointHeadGoal.pointing_axis.y = 0;
pointHeadGoal.pointing_axis.z = 0;
pointHeadGoal.pointing_frame = "head_mount_link";
actionPointHead_.sendGoal(pointHeadGoal);
bool finished_before_timeout = actionPointHead_.waitForResult(actionTimeOut_);
if (finished_before_timeout)
{
actionlib::SimpleClientGoalState state = actionPointHead_.getState();
ROS_DEBUG("ActionExecutorInspectLocation::%s: Point Head Action finished: %s", __func__, state.toString().c_str());
if (state != actionlib::SimpleClientGoalState::SUCCEEDED)
{
ROS_ERROR("ActionExecutorInspectLocation::%s: Point Head Action failed.", __func__);
return false;
}
}
return true;
}
bool ActionExecutorInspectLocation::executeUpdatePlanningSceneFromORK(SymbolicState& currentState,
const std::string& tableName, const std::string& manipulationLocation)
{
// execute action ork-to-planning-scene
ROS_INFO("ActionExecutorInspectLocation::%s: Sending UpdatePlanningSceneFromORK request.", __func__);
ork_to_planning_scene_msgs::UpdatePlanningSceneFromOrkGoal updatePSGoal;
updatePSGoal.verify_planning_scene_update = verify_planning_scene_update_;
updatePSGoal.add_tables = add_tables_;
updatePSGoal.table_prefix = tableName;
const multimap<string, string> objects = currentState.getTypedObjects();
std::pair<multimap<string, string>::const_iterator, multimap<string, string>::const_iterator> iterators = objects.equal_range("movable_object");
for (multimap<string, string>::const_iterator it = iterators.first; it != iterators.second; it++)
{
Predicate on;
on.name = "object-on";
on.parameters.push_back(it->second);
on.parameters.push_back(tableName);
bool value = false;
currentState.hasBooleanPredicate(on, &value);
if (value)
{
updatePSGoal.expected_objects.push_back(it->second);
}
}
actionOrkToPs_.sendGoal(updatePSGoal);
bool finished_before_timeout = actionOrkToPs_.waitForResult(actionTimeOut_);
if (finished_before_timeout)
{
actionlib::SimpleClientGoalState state = actionOrkToPs_.getState();
ROS_DEBUG("ActionExecutorInspectLocation::%s: ORK to Planning Scene Action finished: %s", __func__, state.toString().c_str());
if (state == actionlib::SimpleClientGoalState::SUCCEEDED)
{
ROS_INFO("Inspect location succeeded.");
for_each(const string& predicate, predicate_names_)
{
currentState.setBooleanPredicate(predicate, manipulationLocation, true);
}
}
else
{
ROS_ERROR("ActionExecutorInspectLocation::%s: ORK to Planning Scene Action failed.", __func__);
return false;
}
}
return true;
}
void ActionExecutorInspectLocation::renameTableCollisionObject(const std::string& tableName)
{
moveit_msgs::CollisionObject tableCO;
forEach (const moveit_msgs::CollisionObject& co, psi_->getCollisionObjects())
{
if (StringUtil::startsWith(co.id, tableName))
{
ROS_INFO("ActionExecutorInspectLocation::%s: Found object with id: %s, renaming to: %s", __func__, co.id.c_str(), tableName.c_str());
tableCO = co;
psi_->renameCollisionObject(tableName, tableCO);
}
}
}
}; // namespace
<|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.
#include "kudu/rpc/messenger.h"
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <list>
#include <mutex>
#include <set>
#include <string>
#include "kudu/gutil/gscoped_ptr.h"
#include "kudu/gutil/map-util.h"
#include "kudu/gutil/stl_util.h"
#include "kudu/gutil/strings/substitute.h"
#include "kudu/rpc/acceptor_pool.h"
#include "kudu/rpc/connection.h"
#include "kudu/rpc/constants.h"
#include "kudu/rpc/reactor.h"
#include "kudu/rpc/rpc_header.pb.h"
#include "kudu/rpc/rpc_service.h"
#include "kudu/rpc/rpcz_store.h"
#include "kudu/rpc/sasl_common.h"
#include "kudu/rpc/transfer.h"
#include "kudu/util/errno.h"
#include "kudu/util/flag_tags.h"
#include "kudu/util/metrics.h"
#include "kudu/util/monotime.h"
#include "kudu/util/net/socket.h"
#include "kudu/util/status.h"
#include "kudu/util/threadpool.h"
#include "kudu/util/trace.h"
using std::string;
using std::shared_ptr;
using strings::Substitute;
DEFINE_int32(rpc_default_keepalive_time_ms, 65000,
"If an RPC connection from a client is idle for this amount of time, the server "
"will disconnect the client.");
TAG_FLAG(rpc_default_keepalive_time_ms, advanced);
namespace kudu {
namespace rpc {
class Messenger;
class ServerBuilder;
MessengerBuilder::MessengerBuilder(std::string name)
: name_(std::move(name)),
connection_keepalive_time_(
MonoDelta::FromMilliseconds(FLAGS_rpc_default_keepalive_time_ms)),
num_reactors_(4),
num_negotiation_threads_(4),
coarse_timer_granularity_(MonoDelta::FromMilliseconds(100)) {}
MessengerBuilder& MessengerBuilder::set_connection_keepalive_time(const MonoDelta &keepalive) {
connection_keepalive_time_ = keepalive;
return *this;
}
MessengerBuilder& MessengerBuilder::set_num_reactors(int num_reactors) {
num_reactors_ = num_reactors;
return *this;
}
MessengerBuilder& MessengerBuilder::set_negotiation_threads(int num_negotiation_threads) {
num_negotiation_threads_ = num_negotiation_threads;
return *this;
}
MessengerBuilder& MessengerBuilder::set_coarse_timer_granularity(const MonoDelta &granularity) {
coarse_timer_granularity_ = granularity;
return *this;
}
MessengerBuilder &MessengerBuilder::set_metric_entity(
const scoped_refptr<MetricEntity>& metric_entity) {
metric_entity_ = metric_entity;
return *this;
}
Status MessengerBuilder::Build(shared_ptr<Messenger> *msgr) {
RETURN_NOT_OK(SaslInit(kSaslAppName)); // Initialize SASL library before we start making requests
gscoped_ptr<Messenger> new_msgr(new Messenger(*this));
Status build_status = new_msgr->Init();
if (!build_status.ok()) {
new_msgr->AllExternalReferencesDropped();
return build_status;
}
// See docs on Messenger::retain_self_ for info about this odd hack.
*msgr = shared_ptr<Messenger>(
new_msgr.release(), std::mem_fun(&Messenger::AllExternalReferencesDropped));
return Status::OK();
}
// See comment on Messenger::retain_self_ member.
void Messenger::AllExternalReferencesDropped() {
Shutdown();
CHECK(retain_self_.get());
// If we have no more external references, then we no longer
// need to retain ourself. We'll destruct as soon as all our
// internal-facing references are dropped (ie those from reactor
// threads).
retain_self_.reset();
}
void Messenger::Shutdown() {
// Since we're shutting down, it's OK to block.
ThreadRestrictions::ScopedAllowWait allow_wait;
std::lock_guard<percpu_rwlock> guard(lock_);
if (closing_) {
return;
}
VLOG(1) << "shutting down messenger " << name_;
closing_ = true;
DCHECK(rpc_services_.empty()) << "Unregister RPC services before shutting down Messenger";
rpc_services_.clear();
for (const shared_ptr<AcceptorPool>& acceptor_pool : acceptor_pools_) {
acceptor_pool->Shutdown();
}
acceptor_pools_.clear();
// Need to shut down negotiation pool before the reactors, since the
// reactors close the Connection sockets, and may race against the negotiation
// threads' blocking reads & writes.
negotiation_pool_->Shutdown();
for (Reactor* reactor : reactors_) {
reactor->Shutdown();
}
}
Status Messenger::AddAcceptorPool(const Sockaddr &accept_addr,
shared_ptr<AcceptorPool>* pool) {
Socket sock;
RETURN_NOT_OK(sock.Init(0));
RETURN_NOT_OK(sock.SetReuseAddr(true));
RETURN_NOT_OK(sock.Bind(accept_addr));
Sockaddr remote;
RETURN_NOT_OK(sock.GetSocketAddress(&remote));
shared_ptr<AcceptorPool> acceptor_pool(new AcceptorPool(this, &sock, remote));
std::lock_guard<percpu_rwlock> guard(lock_);
acceptor_pools_.push_back(acceptor_pool);
*pool = acceptor_pool;
return Status::OK();
}
// Register a new RpcService to handle inbound requests.
Status Messenger::RegisterService(const string& service_name,
const scoped_refptr<RpcService>& service) {
DCHECK(service);
std::lock_guard<percpu_rwlock> guard(lock_);
if (InsertIfNotPresent(&rpc_services_, service_name, service)) {
return Status::OK();
} else {
return Status::AlreadyPresent("This service is already present");
}
}
Status Messenger::UnregisterAllServices() {
std::lock_guard<percpu_rwlock> guard(lock_);
rpc_services_.clear();
return Status::OK();
}
// Unregister an RpcService.
Status Messenger::UnregisterService(const string& service_name) {
std::lock_guard<percpu_rwlock> guard(lock_);
if (rpc_services_.erase(service_name)) {
return Status::OK();
} else {
return Status::ServiceUnavailable(Substitute("service $0 not registered on $1",
service_name, name_));
}
}
void Messenger::QueueOutboundCall(const shared_ptr<OutboundCall> &call) {
Reactor *reactor = RemoteToReactor(call->conn_id().remote());
reactor->QueueOutboundCall(call);
}
void Messenger::QueueInboundCall(gscoped_ptr<InboundCall> call) {
shared_lock<rw_spinlock> guard(lock_.get_lock());
scoped_refptr<RpcService>* service = FindOrNull(rpc_services_,
call->remote_method().service_name());
if (PREDICT_FALSE(!service)) {
Status s = Status::ServiceUnavailable(Substitute("service $0 not registered on $1",
call->remote_method().service_name(), name_));
LOG(INFO) << s.ToString();
call.release()->RespondFailure(ErrorStatusPB::ERROR_NO_SUCH_SERVICE, s);
return;
}
call->set_method_info((*service)->LookupMethod(call->remote_method()));
// The RpcService will respond to the client on success or failure.
WARN_NOT_OK((*service)->QueueInboundCall(std::move(call)), "Unable to handle RPC call");
}
void Messenger::RegisterInboundSocket(Socket *new_socket, const Sockaddr &remote) {
Reactor *reactor = RemoteToReactor(remote);
reactor->RegisterInboundSocket(new_socket, remote);
}
Messenger::Messenger(const MessengerBuilder &bld)
: name_(bld.name_),
closing_(false),
rpcz_store_(new RpczStore()),
metric_entity_(bld.metric_entity_),
retain_self_(this) {
for (int i = 0; i < bld.num_reactors_; i++) {
reactors_.push_back(new Reactor(retain_self_, i, bld));
}
CHECK_OK(ThreadPoolBuilder("negotiator")
.set_max_threads(bld.num_negotiation_threads_)
.Build(&negotiation_pool_));
}
Messenger::~Messenger() {
std::lock_guard<percpu_rwlock> guard(lock_);
CHECK(closing_) << "Should have already shut down";
STLDeleteElements(&reactors_);
}
Reactor* Messenger::RemoteToReactor(const Sockaddr &remote) {
uint32_t hashCode = remote.HashCode();
int reactor_idx = hashCode % reactors_.size();
// This is just a static partitioning; we could get a lot
// fancier with assigning Sockaddrs to Reactors.
return reactors_[reactor_idx];
}
Status Messenger::Init() {
Status status;
for (Reactor* r : reactors_) {
RETURN_NOT_OK(r->Init());
}
return Status::OK();
}
Status Messenger::DumpRunningRpcs(const DumpRunningRpcsRequestPB& req,
DumpRunningRpcsResponsePB* resp) {
shared_lock<rw_spinlock> guard(lock_.get_lock());
for (Reactor* reactor : reactors_) {
RETURN_NOT_OK(reactor->DumpRunningRpcs(req, resp));
}
return Status::OK();
}
void Messenger::ScheduleOnReactor(const boost::function<void(const Status&)>& func,
MonoDelta when) {
DCHECK(!reactors_.empty());
// If we're already running on a reactor thread, reuse it.
Reactor* chosen = nullptr;
for (Reactor* r : reactors_) {
if (r->IsCurrentThread()) {
chosen = r;
}
}
if (chosen == nullptr) {
// Not running on a reactor thread, pick one at random.
chosen = reactors_[rand() % reactors_.size()];
}
DelayedTask* task = new DelayedTask(func, when);
chosen->ScheduleReactorTask(task);
}
const scoped_refptr<RpcService> Messenger::rpc_service(const string& service_name) const {
std::lock_guard<percpu_rwlock> guard(lock_);
scoped_refptr<RpcService> service;
if (FindCopy(rpc_services_, service_name, &service)) {
return service;
} else {
return scoped_refptr<RpcService>(nullptr);
}
}
} // namespace rpc
} // namespace kudu
<commit_msg>KUDU-1719: Heap use-after-free and deadlock on Messenger::Init() failure<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.
#include "kudu/rpc/messenger.h"
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <list>
#include <mutex>
#include <set>
#include <string>
#include "kudu/gutil/gscoped_ptr.h"
#include "kudu/gutil/map-util.h"
#include "kudu/gutil/stl_util.h"
#include "kudu/gutil/strings/substitute.h"
#include "kudu/rpc/acceptor_pool.h"
#include "kudu/rpc/connection.h"
#include "kudu/rpc/constants.h"
#include "kudu/rpc/reactor.h"
#include "kudu/rpc/rpc_header.pb.h"
#include "kudu/rpc/rpc_service.h"
#include "kudu/rpc/rpcz_store.h"
#include "kudu/rpc/sasl_common.h"
#include "kudu/rpc/transfer.h"
#include "kudu/util/errno.h"
#include "kudu/util/flag_tags.h"
#include "kudu/util/metrics.h"
#include "kudu/util/monotime.h"
#include "kudu/util/net/socket.h"
#include "kudu/util/status.h"
#include "kudu/util/threadpool.h"
#include "kudu/util/trace.h"
using std::string;
using std::shared_ptr;
using strings::Substitute;
DEFINE_int32(rpc_default_keepalive_time_ms, 65000,
"If an RPC connection from a client is idle for this amount of time, the server "
"will disconnect the client.");
TAG_FLAG(rpc_default_keepalive_time_ms, advanced);
namespace kudu {
namespace rpc {
class Messenger;
class ServerBuilder;
MessengerBuilder::MessengerBuilder(std::string name)
: name_(std::move(name)),
connection_keepalive_time_(
MonoDelta::FromMilliseconds(FLAGS_rpc_default_keepalive_time_ms)),
num_reactors_(4),
num_negotiation_threads_(4),
coarse_timer_granularity_(MonoDelta::FromMilliseconds(100)) {}
MessengerBuilder& MessengerBuilder::set_connection_keepalive_time(const MonoDelta &keepalive) {
connection_keepalive_time_ = keepalive;
return *this;
}
MessengerBuilder& MessengerBuilder::set_num_reactors(int num_reactors) {
num_reactors_ = num_reactors;
return *this;
}
MessengerBuilder& MessengerBuilder::set_negotiation_threads(int num_negotiation_threads) {
num_negotiation_threads_ = num_negotiation_threads;
return *this;
}
MessengerBuilder& MessengerBuilder::set_coarse_timer_granularity(const MonoDelta &granularity) {
coarse_timer_granularity_ = granularity;
return *this;
}
MessengerBuilder &MessengerBuilder::set_metric_entity(
const scoped_refptr<MetricEntity>& metric_entity) {
metric_entity_ = metric_entity;
return *this;
}
Status MessengerBuilder::Build(shared_ptr<Messenger> *msgr) {
RETURN_NOT_OK(SaslInit(kSaslAppName)); // Initialize SASL library before we start making requests
Messenger* new_msgr(new Messenger(*this));
Status build_status = new_msgr->Init();
if (!build_status.ok()) {
// 'new_msgr' will be freed when 'retain_self_' is reset, so no need to explicitly free it.
new_msgr->AllExternalReferencesDropped();
return build_status;
}
// See docs on Messenger::retain_self_ for info about this odd hack.
*msgr = shared_ptr<Messenger>(
new_msgr, std::mem_fun(&Messenger::AllExternalReferencesDropped));
return Status::OK();
}
// See comment on Messenger::retain_self_ member.
void Messenger::AllExternalReferencesDropped() {
Shutdown();
CHECK(retain_self_.get());
// If we have no more external references, then we no longer
// need to retain ourself. We'll destruct as soon as all our
// internal-facing references are dropped (ie those from reactor
// threads).
retain_self_.reset();
}
void Messenger::Shutdown() {
// Since we're shutting down, it's OK to block.
ThreadRestrictions::ScopedAllowWait allow_wait;
std::lock_guard<percpu_rwlock> guard(lock_);
if (closing_) {
return;
}
VLOG(1) << "shutting down messenger " << name_;
closing_ = true;
DCHECK(rpc_services_.empty()) << "Unregister RPC services before shutting down Messenger";
rpc_services_.clear();
for (const shared_ptr<AcceptorPool>& acceptor_pool : acceptor_pools_) {
acceptor_pool->Shutdown();
}
acceptor_pools_.clear();
// Need to shut down negotiation pool before the reactors, since the
// reactors close the Connection sockets, and may race against the negotiation
// threads' blocking reads & writes.
negotiation_pool_->Shutdown();
for (Reactor* reactor : reactors_) {
reactor->Shutdown();
}
}
Status Messenger::AddAcceptorPool(const Sockaddr &accept_addr,
shared_ptr<AcceptorPool>* pool) {
Socket sock;
RETURN_NOT_OK(sock.Init(0));
RETURN_NOT_OK(sock.SetReuseAddr(true));
RETURN_NOT_OK(sock.Bind(accept_addr));
Sockaddr remote;
RETURN_NOT_OK(sock.GetSocketAddress(&remote));
shared_ptr<AcceptorPool> acceptor_pool(new AcceptorPool(this, &sock, remote));
std::lock_guard<percpu_rwlock> guard(lock_);
acceptor_pools_.push_back(acceptor_pool);
*pool = acceptor_pool;
return Status::OK();
}
// Register a new RpcService to handle inbound requests.
Status Messenger::RegisterService(const string& service_name,
const scoped_refptr<RpcService>& service) {
DCHECK(service);
std::lock_guard<percpu_rwlock> guard(lock_);
if (InsertIfNotPresent(&rpc_services_, service_name, service)) {
return Status::OK();
} else {
return Status::AlreadyPresent("This service is already present");
}
}
Status Messenger::UnregisterAllServices() {
std::lock_guard<percpu_rwlock> guard(lock_);
rpc_services_.clear();
return Status::OK();
}
// Unregister an RpcService.
Status Messenger::UnregisterService(const string& service_name) {
std::lock_guard<percpu_rwlock> guard(lock_);
if (rpc_services_.erase(service_name)) {
return Status::OK();
} else {
return Status::ServiceUnavailable(Substitute("service $0 not registered on $1",
service_name, name_));
}
}
void Messenger::QueueOutboundCall(const shared_ptr<OutboundCall> &call) {
Reactor *reactor = RemoteToReactor(call->conn_id().remote());
reactor->QueueOutboundCall(call);
}
void Messenger::QueueInboundCall(gscoped_ptr<InboundCall> call) {
shared_lock<rw_spinlock> guard(lock_.get_lock());
scoped_refptr<RpcService>* service = FindOrNull(rpc_services_,
call->remote_method().service_name());
if (PREDICT_FALSE(!service)) {
Status s = Status::ServiceUnavailable(Substitute("service $0 not registered on $1",
call->remote_method().service_name(), name_));
LOG(INFO) << s.ToString();
call.release()->RespondFailure(ErrorStatusPB::ERROR_NO_SUCH_SERVICE, s);
return;
}
call->set_method_info((*service)->LookupMethod(call->remote_method()));
// The RpcService will respond to the client on success or failure.
WARN_NOT_OK((*service)->QueueInboundCall(std::move(call)), "Unable to handle RPC call");
}
void Messenger::RegisterInboundSocket(Socket *new_socket, const Sockaddr &remote) {
Reactor *reactor = RemoteToReactor(remote);
reactor->RegisterInboundSocket(new_socket, remote);
}
Messenger::Messenger(const MessengerBuilder &bld)
: name_(bld.name_),
closing_(false),
rpcz_store_(new RpczStore()),
metric_entity_(bld.metric_entity_),
retain_self_(this) {
for (int i = 0; i < bld.num_reactors_; i++) {
reactors_.push_back(new Reactor(retain_self_, i, bld));
}
CHECK_OK(ThreadPoolBuilder("negotiator")
.set_max_threads(bld.num_negotiation_threads_)
.Build(&negotiation_pool_));
}
Messenger::~Messenger() {
std::lock_guard<percpu_rwlock> guard(lock_);
CHECK(closing_) << "Should have already shut down";
STLDeleteElements(&reactors_);
}
Reactor* Messenger::RemoteToReactor(const Sockaddr &remote) {
uint32_t hashCode = remote.HashCode();
int reactor_idx = hashCode % reactors_.size();
// This is just a static partitioning; we could get a lot
// fancier with assigning Sockaddrs to Reactors.
return reactors_[reactor_idx];
}
Status Messenger::Init() {
Status status;
for (Reactor* r : reactors_) {
RETURN_NOT_OK(r->Init());
}
return Status::OK();
}
Status Messenger::DumpRunningRpcs(const DumpRunningRpcsRequestPB& req,
DumpRunningRpcsResponsePB* resp) {
shared_lock<rw_spinlock> guard(lock_.get_lock());
for (Reactor* reactor : reactors_) {
RETURN_NOT_OK(reactor->DumpRunningRpcs(req, resp));
}
return Status::OK();
}
void Messenger::ScheduleOnReactor(const boost::function<void(const Status&)>& func,
MonoDelta when) {
DCHECK(!reactors_.empty());
// If we're already running on a reactor thread, reuse it.
Reactor* chosen = nullptr;
for (Reactor* r : reactors_) {
if (r->IsCurrentThread()) {
chosen = r;
}
}
if (chosen == nullptr) {
// Not running on a reactor thread, pick one at random.
chosen = reactors_[rand() % reactors_.size()];
}
DelayedTask* task = new DelayedTask(func, when);
chosen->ScheduleReactorTask(task);
}
const scoped_refptr<RpcService> Messenger::rpc_service(const string& service_name) const {
std::lock_guard<percpu_rwlock> guard(lock_);
scoped_refptr<RpcService> service;
if (FindCopy(rpc_services_, service_name, &service)) {
return service;
} else {
return scoped_refptr<RpcService>(nullptr);
}
}
} // namespace rpc
} // namespace kudu
<|endoftext|>
|
<commit_before>#include "ImageLayer.hpp"
#include "../arch/mpi/mpi.h"
#include "structures/Image.hpp"
#include <algorithm>
#include <cassert>
#include <cstring>
#include <iostream>
namespace PV {
ImageLayer::ImageLayer(const char *name, HyPerCol *hc) { initialize(name, hc); }
int ImageLayer::countInputImages() {
// Check if the input path ends in ".txt" and enable the file list if so
std::string txt = ".txt";
if (getInputPath().size() > txt.size()
&& getInputPath().compare(getInputPath().size() - txt.size(), txt.size(), txt) == 0) {
mUsingFileList = true;
// Calculate file positions for beginning of each frame
populateFileList();
InfoLog() << "File " << getInputPath() << " contains " << mFileList.size() << " frames\n";
return mFileList.size();
}
else {
mUsingFileList = false;
return 1;
}
}
std::string const &ImageLayer::getCurrentFilename(int localBatchElement, int mpiBatchIndex) const {
if (mUsingFileList) {
int blockBatchElement = localBatchElement + getLayerLoc()->nbatch * mpiBatchIndex;
int inputIndex = mBatchIndexer->getIndex(blockBatchElement);
return mFileList.at(inputIndex);
}
else {
return getInputPath();
}
}
Response::Status ImageLayer::registerData(Checkpointer *checkpointer) {
auto status = InputLayer::registerData(checkpointer);
if (!Response::completed(status)) {
return status;
}
mURLDownloadTemplate = checkpointer->getOutputPath() + "/temp.XXXXXX";
return Response::SUCCESS;
}
void ImageLayer::populateFileList() {
if (getMPIBlock()->getRank() == 0) {
std::string line;
mFileList.clear();
InfoLog() << "Reading list: " << getInputPath() << "\n";
std::ifstream infile(getInputPath(), std::ios_base::in);
FatalIf(
infile.fail(), "Unable to open \"%s\": %s\n", getInputPath().c_str(), strerror(errno));
while (getline(infile, line, '\n')) {
std::string noWhiteSpace = line;
noWhiteSpace.erase(
std::remove_if(noWhiteSpace.begin(), noWhiteSpace.end(), ::isspace),
noWhiteSpace.end());
if (!noWhiteSpace.empty()) {
mFileList.push_back(noWhiteSpace);
}
}
}
}
Buffer<float> ImageLayer::retrieveData(int inputIndex) {
std::string filename;
if (mUsingFileList) {
filename = mFileList.at(inputIndex);
}
else {
filename = getInputPath();
}
readImage(filename);
if (mImage->getFeatures() != getLayerLoc()->nf) {
switch (getLayerLoc()->nf) {
case 1: // Grayscale
mImage->convertToGray(false);
break;
case 2: // Grayscale + Alpha
mImage->convertToGray(true);
break;
case 3: // RGB
mImage->convertToColor(false);
break;
case 4: // RGBA
mImage->convertToColor(true);
break;
default:
Fatal() << "Failed to read " << filename << ": Could not convert "
<< mImage->getFeatures() << " channels to " << getLayerLoc()->nf << std::endl;
break;
}
}
Buffer<float> result(
mImage->asVector(), mImage->getWidth(), mImage->getHeight(), getLayerLoc()->nf);
return result;
}
void ImageLayer::readImage(std::string filename) {
const PVLayerLoc *loc = getLayerLoc();
bool usingTempFile = false;
// Attempt to download our input file if we've been passed a URL or AWS path
if (filename.find("://") != std::string::npos) {
usingTempFile = true;
std::string extension = filename.substr(filename.find_last_of("."));
std::string pathstring = mURLDownloadTemplate + extension;
char tempStr[256];
strcpy(tempStr, pathstring.c_str());
int tempFileID = mkstemps(tempStr, extension.size());
pathstring = std::string(tempStr);
FatalIf(tempFileID < 0, "Cannot create temp image file.\n");
std::string systemstring;
if (filename.find("s3://") != std::string::npos) {
systemstring = std::string("aws s3 cp \'") + filename + std::string("\' ") + pathstring;
}
else { // URLs other than s3://
systemstring = std::string("wget -O ") + pathstring + std::string(" \'") + filename
+ std::string("\'");
}
filename = pathstring;
const int numAttempts = 5;
for (int attemptNum = 0; attemptNum < numAttempts; attemptNum++) {
if (system(systemstring.c_str()) == 0) {
break;
}
sleep(1);
FatalIf(
attemptNum == numAttempts - 1,
"download command \"%s\" failed: %s. Exiting\n",
systemstring.c_str(),
strerror(errno));
}
}
mImage = std::unique_ptr<Image>(new Image(std::string(filename)));
FatalIf(
usingTempFile && remove(filename.c_str()),
"remove(\"%s\") failed. Exiting.\n",
filename.c_str());
}
std::string ImageLayer::describeInput(int index) {
std::string description("");
if (mUsingFileList) {
description = mFileList.at(index);
}
return description;
}
}
<commit_msg>ImageLayer checks whether list of files is empty.<commit_after>#include "ImageLayer.hpp"
#include "../arch/mpi/mpi.h"
#include "structures/Image.hpp"
#include <algorithm>
#include <cassert>
#include <cstring>
#include <iostream>
namespace PV {
ImageLayer::ImageLayer(const char *name, HyPerCol *hc) { initialize(name, hc); }
int ImageLayer::countInputImages() {
// Check if the input path ends in ".txt" and enable the file list if so
std::string txt = ".txt";
if (getInputPath().size() > txt.size()
&& getInputPath().compare(getInputPath().size() - txt.size(), txt.size(), txt) == 0) {
mUsingFileList = true;
// Calculate file positions for beginning of each frame
populateFileList();
InfoLog() << "File " << getInputPath() << " contains " << mFileList.size() << " frames\n";
return mFileList.size();
}
else {
mUsingFileList = false;
return 1;
}
}
std::string const &ImageLayer::getCurrentFilename(int localBatchElement, int mpiBatchIndex) const {
if (mUsingFileList) {
int blockBatchElement = localBatchElement + getLayerLoc()->nbatch * mpiBatchIndex;
int inputIndex = mBatchIndexer->getIndex(blockBatchElement);
return mFileList.at(inputIndex);
}
else {
return getInputPath();
}
}
Response::Status ImageLayer::registerData(Checkpointer *checkpointer) {
auto status = InputLayer::registerData(checkpointer);
if (!Response::completed(status)) {
return status;
}
mURLDownloadTemplate = checkpointer->getOutputPath() + "/temp.XXXXXX";
return Response::SUCCESS;
}
void ImageLayer::populateFileList() {
if (getMPIBlock()->getRank() == 0) {
std::string line;
mFileList.clear();
InfoLog() << "Reading list: " << getInputPath() << "\n";
std::ifstream infile(getInputPath(), std::ios_base::in);
FatalIf(
infile.fail(), "Unable to open \"%s\": %s\n", getInputPath().c_str(), strerror(errno));
while (getline(infile, line, '\n')) {
std::string noWhiteSpace = line;
noWhiteSpace.erase(
std::remove_if(noWhiteSpace.begin(), noWhiteSpace.end(), ::isspace),
noWhiteSpace.end());
if (!noWhiteSpace.empty()) {
mFileList.push_back(noWhiteSpace);
}
}
FatalIf(
mFileList.empty(),
"%s inputPath file list \"%s\" is empty.\n",
getDescription_c(),
getInputPath().c_str());
}
}
Buffer<float> ImageLayer::retrieveData(int inputIndex) {
std::string filename;
if (mUsingFileList) {
filename = mFileList.at(inputIndex);
}
else {
filename = getInputPath();
}
readImage(filename);
if (mImage->getFeatures() != getLayerLoc()->nf) {
switch (getLayerLoc()->nf) {
case 1: // Grayscale
mImage->convertToGray(false);
break;
case 2: // Grayscale + Alpha
mImage->convertToGray(true);
break;
case 3: // RGB
mImage->convertToColor(false);
break;
case 4: // RGBA
mImage->convertToColor(true);
break;
default:
Fatal() << "Failed to read " << filename << ": Could not convert "
<< mImage->getFeatures() << " channels to " << getLayerLoc()->nf << std::endl;
break;
}
}
Buffer<float> result(
mImage->asVector(), mImage->getWidth(), mImage->getHeight(), getLayerLoc()->nf);
return result;
}
void ImageLayer::readImage(std::string filename) {
const PVLayerLoc *loc = getLayerLoc();
bool usingTempFile = false;
// Attempt to download our input file if we've been passed a URL or AWS path
if (filename.find("://") != std::string::npos) {
usingTempFile = true;
std::string extension = filename.substr(filename.find_last_of("."));
std::string pathstring = mURLDownloadTemplate + extension;
char tempStr[256];
strcpy(tempStr, pathstring.c_str());
int tempFileID = mkstemps(tempStr, extension.size());
pathstring = std::string(tempStr);
FatalIf(tempFileID < 0, "Cannot create temp image file.\n");
std::string systemstring;
if (filename.find("s3://") != std::string::npos) {
systemstring = std::string("aws s3 cp \'") + filename + std::string("\' ") + pathstring;
}
else { // URLs other than s3://
systemstring = std::string("wget -O ") + pathstring + std::string(" \'") + filename
+ std::string("\'");
}
filename = pathstring;
const int numAttempts = 5;
for (int attemptNum = 0; attemptNum < numAttempts; attemptNum++) {
if (system(systemstring.c_str()) == 0) {
break;
}
sleep(1);
FatalIf(
attemptNum == numAttempts - 1,
"download command \"%s\" failed: %s. Exiting\n",
systemstring.c_str(),
strerror(errno));
}
}
mImage = std::unique_ptr<Image>(new Image(std::string(filename)));
FatalIf(
usingTempFile && remove(filename.c_str()),
"remove(\"%s\") failed. Exiting.\n",
filename.c_str());
}
std::string ImageLayer::describeInput(int index) {
std::string description("");
if (mUsingFileList) {
description = mFileList.at(index);
}
return description;
}
}
<|endoftext|>
|
<commit_before>#include "master.hpp"
namespace factor
{
void init_globals()
{
init_mvm();
}
void factor_vm::default_parameters(vm_parameters *p)
{
p->image_path = NULL;
p->datastack_size = 32 * sizeof(cell);
p->retainstack_size = 32 * sizeof(cell);
#ifdef FACTOR_PPC
p->callstack_size = 256 * sizeof(cell);
#else
p->callstack_size = 128 * sizeof(cell);
#endif
p->code_size = 8 * sizeof(cell);
p->young_size = sizeof(cell) / 4;
p->aging_size = sizeof(cell) / 2;
p->tenured_size = 24 * sizeof(cell);
p->max_pic_size = 3;
p->fep = false;
p->signals = true;
#ifdef WINDOWS
p->console = false;
#else
p->console = true;
#endif
p->callback_size = 256;
}
bool factor_vm::factor_arg(const vm_char* str, const vm_char* arg, cell* value)
{
int val;
if(SSCANF(str,arg,&val) > 0)
{
*value = val;
return true;
}
else
return false;
}
void factor_vm::init_parameters_from_args(vm_parameters *p, int argc, vm_char **argv)
{
default_parameters(p);
p->executable_path = argv[0];
int i = 0;
for(i = 1; i < argc; i++)
{
vm_char *arg = argv[i];
if(STRCMP(arg,STRING_LITERAL("--")) == 0) break;
else if(factor_arg(arg,STRING_LITERAL("-datastack=%d"),&p->datastack_size));
else if(factor_arg(arg,STRING_LITERAL("-retainstack=%d"),&p->retainstack_size));
else if(factor_arg(arg,STRING_LITERAL("-callstack=%d"),&p->callstack_size));
else if(factor_arg(arg,STRING_LITERAL("-young=%d"),&p->young_size));
else if(factor_arg(arg,STRING_LITERAL("-aging=%d"),&p->aging_size));
else if(factor_arg(arg,STRING_LITERAL("-tenured=%d"),&p->tenured_size));
else if(factor_arg(arg,STRING_LITERAL("-codeheap=%d"),&p->code_size));
else if(factor_arg(arg,STRING_LITERAL("-pic=%d"),&p->max_pic_size));
else if(factor_arg(arg,STRING_LITERAL("-callbacks=%d"),&p->callback_size));
else if(STRCMP(arg,STRING_LITERAL("-fep")) == 0) p->fep = true;
else if(STRCMP(arg,STRING_LITERAL("-nosignals")) == 0) p->signals = false;
else if(STRNCMP(arg,STRING_LITERAL("-i="),3) == 0) p->image_path = arg + 3;
else if(STRCMP(arg,STRING_LITERAL("-console")) == 0) p->console = true;
}
}
/* Compile code in boot image so that we can execute the startup quotation */
void factor_vm::prepare_boot_image()
{
std::cout << "*** Stage 2 early init... ";
fflush(stdout);
compile_all_words();
update_code_heap_words(true);
initialize_all_quotations();
special_objects[OBJ_STAGE2] = true_object;
std::cout << "done\n";
}
void factor_vm::init_factor(vm_parameters *p)
{
/* Kilobytes */
p->datastack_size = align_page(p->datastack_size << 10);
p->retainstack_size = align_page(p->retainstack_size << 10);
p->callstack_size = align_page(p->callstack_size << 10);
p->callback_size = align_page(p->callback_size << 10);
/* Megabytes */
p->young_size <<= 20;
p->aging_size <<= 20;
p->tenured_size <<= 20;
p->code_size <<= 20;
/* Disable GC during init as a sanity check */
gc_off = true;
/* OS-specific initialization */
early_init();
const vm_char *executable_path = vm_executable_path();
if(executable_path)
p->executable_path = executable_path;
if(p->image_path == NULL)
p->image_path = default_image_path();
srand((unsigned int)system_micros());
init_ffi();
init_contexts(p->datastack_size,p->retainstack_size,p->callstack_size);
init_callbacks(p->callback_size);
load_image(p);
init_c_io();
init_inline_caching(p->max_pic_size);
if(p->signals)
init_signals();
if(p->console)
open_console();
init_profiler();
special_objects[OBJ_CPU] = allot_alien(false_object,(cell)FACTOR_CPU_STRING);
special_objects[OBJ_OS] = allot_alien(false_object,(cell)FACTOR_OS_STRING);
special_objects[OBJ_CELL_SIZE] = tag_fixnum(sizeof(cell));
special_objects[OBJ_EXECUTABLE] = allot_alien(false_object,(cell)p->executable_path);
special_objects[OBJ_ARGS] = false_object;
special_objects[OBJ_EMBEDDED] = false_object;
special_objects[OBJ_VM_COMPILER] = allot_alien(false_object,(cell)FACTOR_COMPILER_VERSION);
/* We can GC now */
gc_off = false;
if(!to_boolean(special_objects[OBJ_STAGE2]))
prepare_boot_image();
}
/* May allocate memory */
void factor_vm::pass_args_to_factor(int argc, vm_char **argv)
{
growable_array args(this);
for(fixnum i = 1; i < argc; i++)
args.add(allot_alien(false_object,(cell)argv[i]));
args.trim();
special_objects[OBJ_ARGS] = args.elements.value();
}
void factor_vm::start_factor(vm_parameters *p)
{
if(p->fep) factorbug();
c_to_factor_toplevel(special_objects[OBJ_STARTUP_QUOT]);
}
void factor_vm::stop_factor()
{
c_to_factor_toplevel(special_objects[OBJ_SHUTDOWN_QUOT]);
}
char *factor_vm::factor_eval_string(char *string)
{
char *(*callback)(char *) = (char *(*)(char *))alien_offset(special_objects[OBJ_EVAL_CALLBACK]);
return callback(string);
}
void factor_vm::factor_eval_free(char *result)
{
free(result);
}
void factor_vm::factor_yield()
{
void (*callback)() = (void (*)())alien_offset(special_objects[OBJ_YIELD_CALLBACK]);
callback();
}
void factor_vm::factor_sleep(long us)
{
void (*callback)(long) = (void (*)(long))alien_offset(special_objects[OBJ_SLEEP_CALLBACK]);
callback(us);
}
void factor_vm::start_standalone_factor(int argc, vm_char **argv)
{
vm_parameters p;
default_parameters(&p);
init_parameters_from_args(&p,argc,argv);
init_factor(&p);
pass_args_to_factor(argc,argv);
start_factor(&p);
}
factor_vm *new_factor_vm()
{
factor_vm *newvm = new factor_vm();
register_vm_with_thread(newvm);
thread_vms[thread_id()] = newvm;
return newvm;
}
VM_C_API void start_standalone_factor(int argc, vm_char **argv)
{
factor_vm *newvm = new_factor_vm();
return newvm->start_standalone_factor(argc,argv);
}
}
<commit_msg>vm: try a smaller call stack size on OpenBSD again, now that x86-32 stack frames are smaller<commit_after>#include "master.hpp"
namespace factor
{
void init_globals()
{
init_mvm();
}
void factor_vm::default_parameters(vm_parameters *p)
{
p->image_path = NULL;
p->datastack_size = 32 * sizeof(cell);
p->retainstack_size = 32 * sizeof(cell);
#if defined(__OpenBSD__) && defined(FACTOR_X86)
p->callstack_size = 64 * sizeof(cell);
#elif defined(FACTOR_PPC)
p->callstack_size = 256 * sizeof(cell);
#else
p->callstack_size = 128 * sizeof(cell);
#endif
p->code_size = 8 * sizeof(cell);
p->young_size = sizeof(cell) / 4;
p->aging_size = sizeof(cell) / 2;
p->tenured_size = 24 * sizeof(cell);
p->max_pic_size = 3;
p->fep = false;
p->signals = true;
#ifdef WINDOWS
p->console = false;
#else
p->console = true;
#endif
p->callback_size = 256;
}
bool factor_vm::factor_arg(const vm_char* str, const vm_char* arg, cell* value)
{
int val;
if(SSCANF(str,arg,&val) > 0)
{
*value = val;
return true;
}
else
return false;
}
void factor_vm::init_parameters_from_args(vm_parameters *p, int argc, vm_char **argv)
{
default_parameters(p);
p->executable_path = argv[0];
int i = 0;
for(i = 1; i < argc; i++)
{
vm_char *arg = argv[i];
if(STRCMP(arg,STRING_LITERAL("--")) == 0) break;
else if(factor_arg(arg,STRING_LITERAL("-datastack=%d"),&p->datastack_size));
else if(factor_arg(arg,STRING_LITERAL("-retainstack=%d"),&p->retainstack_size));
else if(factor_arg(arg,STRING_LITERAL("-callstack=%d"),&p->callstack_size));
else if(factor_arg(arg,STRING_LITERAL("-young=%d"),&p->young_size));
else if(factor_arg(arg,STRING_LITERAL("-aging=%d"),&p->aging_size));
else if(factor_arg(arg,STRING_LITERAL("-tenured=%d"),&p->tenured_size));
else if(factor_arg(arg,STRING_LITERAL("-codeheap=%d"),&p->code_size));
else if(factor_arg(arg,STRING_LITERAL("-pic=%d"),&p->max_pic_size));
else if(factor_arg(arg,STRING_LITERAL("-callbacks=%d"),&p->callback_size));
else if(STRCMP(arg,STRING_LITERAL("-fep")) == 0) p->fep = true;
else if(STRCMP(arg,STRING_LITERAL("-nosignals")) == 0) p->signals = false;
else if(STRNCMP(arg,STRING_LITERAL("-i="),3) == 0) p->image_path = arg + 3;
else if(STRCMP(arg,STRING_LITERAL("-console")) == 0) p->console = true;
}
}
/* Compile code in boot image so that we can execute the startup quotation */
void factor_vm::prepare_boot_image()
{
std::cout << "*** Stage 2 early init... ";
fflush(stdout);
compile_all_words();
update_code_heap_words(true);
initialize_all_quotations();
special_objects[OBJ_STAGE2] = true_object;
std::cout << "done\n";
}
void factor_vm::init_factor(vm_parameters *p)
{
/* Kilobytes */
p->datastack_size = align_page(p->datastack_size << 10);
p->retainstack_size = align_page(p->retainstack_size << 10);
p->callstack_size = align_page(p->callstack_size << 10);
p->callback_size = align_page(p->callback_size << 10);
/* Megabytes */
p->young_size <<= 20;
p->aging_size <<= 20;
p->tenured_size <<= 20;
p->code_size <<= 20;
/* Disable GC during init as a sanity check */
gc_off = true;
/* OS-specific initialization */
early_init();
const vm_char *executable_path = vm_executable_path();
if(executable_path)
p->executable_path = executable_path;
if(p->image_path == NULL)
p->image_path = default_image_path();
srand((unsigned int)system_micros());
init_ffi();
init_contexts(p->datastack_size,p->retainstack_size,p->callstack_size);
init_callbacks(p->callback_size);
load_image(p);
init_c_io();
init_inline_caching(p->max_pic_size);
if(p->signals)
init_signals();
if(p->console)
open_console();
init_profiler();
special_objects[OBJ_CPU] = allot_alien(false_object,(cell)FACTOR_CPU_STRING);
special_objects[OBJ_OS] = allot_alien(false_object,(cell)FACTOR_OS_STRING);
special_objects[OBJ_CELL_SIZE] = tag_fixnum(sizeof(cell));
special_objects[OBJ_EXECUTABLE] = allot_alien(false_object,(cell)p->executable_path);
special_objects[OBJ_ARGS] = false_object;
special_objects[OBJ_EMBEDDED] = false_object;
special_objects[OBJ_VM_COMPILER] = allot_alien(false_object,(cell)FACTOR_COMPILER_VERSION);
/* We can GC now */
gc_off = false;
if(!to_boolean(special_objects[OBJ_STAGE2]))
prepare_boot_image();
}
/* May allocate memory */
void factor_vm::pass_args_to_factor(int argc, vm_char **argv)
{
growable_array args(this);
for(fixnum i = 1; i < argc; i++)
args.add(allot_alien(false_object,(cell)argv[i]));
args.trim();
special_objects[OBJ_ARGS] = args.elements.value();
}
void factor_vm::start_factor(vm_parameters *p)
{
if(p->fep) factorbug();
c_to_factor_toplevel(special_objects[OBJ_STARTUP_QUOT]);
}
void factor_vm::stop_factor()
{
c_to_factor_toplevel(special_objects[OBJ_SHUTDOWN_QUOT]);
}
char *factor_vm::factor_eval_string(char *string)
{
char *(*callback)(char *) = (char *(*)(char *))alien_offset(special_objects[OBJ_EVAL_CALLBACK]);
return callback(string);
}
void factor_vm::factor_eval_free(char *result)
{
free(result);
}
void factor_vm::factor_yield()
{
void (*callback)() = (void (*)())alien_offset(special_objects[OBJ_YIELD_CALLBACK]);
callback();
}
void factor_vm::factor_sleep(long us)
{
void (*callback)(long) = (void (*)(long))alien_offset(special_objects[OBJ_SLEEP_CALLBACK]);
callback(us);
}
void factor_vm::start_standalone_factor(int argc, vm_char **argv)
{
vm_parameters p;
default_parameters(&p);
init_parameters_from_args(&p,argc,argv);
init_factor(&p);
pass_args_to_factor(argc,argv);
start_factor(&p);
}
factor_vm *new_factor_vm()
{
factor_vm *newvm = new factor_vm();
register_vm_with_thread(newvm);
thread_vms[thread_id()] = newvm;
return newvm;
}
VM_C_API void start_standalone_factor(int argc, vm_char **argv)
{
factor_vm *newvm = new_factor_vm();
return newvm->start_standalone_factor(argc,argv);
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Native Client Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// NaCl module Pepper extensions interface. Audio API.
// This file implements the untrusted client interface to audio.
#include "native_client/src/shared/npruntime/audio.h"
#include <inttypes.h>
#include <stdlib.h>
#include <nacl/nacl_inttypes.h>
#include <sys/errno.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <limits>
#include <map>
#include <utility>
#include "native_client/src/include/portability_string.h"
#include "gen/native_client/src/shared/npruntime/npmodule_rpc.h"
#include "native_client/src/shared/npruntime/npnavigator.h"
#include "native_client/src/shared/npruntime/pointer_translations.h"
#include "native_client/src/shared/srpc/nacl_srpc.h"
#include "third_party/npapi/bindings/npapi_extensions.h"
using nacl::NPClosureTable;
using nacl::NPNavigator;
using nacl::NPPToWireFormat;
using nacl::DebugPrintf;
namespace {
static const int kInvalidDesc = -1;
struct AudioImpl {
public:
NPDeviceContextAudio* context;
int shared_memory_desc;
size_t shared_memory_size;
int sync_desc;
};
static NPError QueryCapability(NPP instance,
int32 capability,
int32 *value) {
// UNREFERENCED_PARAMETER(instance);
// UNREFERENCED_PARAMETER(capability);
// UNREFERENCED_PARAMETER(value);
// There is no corresponding function in the trusted pepper implementation.
return NPERR_GENERIC_ERROR;
}
static NPError QueryConfig(NPP instance,
const NPDeviceConfig* request,
NPDeviceConfig* obtain) {
// UNREFERENCED_PARAMETER(instance);
// UNREFERENCED_PARAMETER(request);
// UNREFERENCED_PARAMETER(obtain);
// There is no corresponding function in the trusted pepper implementation.
return NPERR_GENERIC_ERROR;
}
static NPError InitializeContext(NPP instance,
const NPDeviceConfig* config,
NPDeviceContext* context) {
DebugPrintf("Audio::InitializeContext %p %p\n",
reinterpret_cast<const void*>(config),
reinterpret_cast<void*>(context));
const NPDeviceContextAudioConfig* config_audio =
reinterpret_cast<const NPDeviceContextAudioConfig*>(config);
NPDeviceContextAudio* context_audio =
reinterpret_cast<NPDeviceContextAudio*>(context);
// Initialize the context structure.
context_audio->config = *config_audio;
context_audio->outBuffer = NULL;
context_audio->inBuffer = NULL;
context_audio->reserved = NULL;
DebugPrintf("Set the config and base stuff\n");
// Get the configuration parameters for passing.
// TODO(sehr): the SRPC generators speak int32_t, while npruntime likes
// int32. Find a way to avoid all these casts.
int32_t sample_rate = static_cast<int32_t>(config_audio->sampleRate);
int32_t sample_type = static_cast<int32_t>(config_audio->sampleType);
int32_t output_channel_map =
static_cast<int32_t>(config_audio->outputChannelMap);
int32_t input_channel_map =
static_cast<int32_t>(config_audio->inputChannelMap);
int32_t sample_frame_count =
static_cast<int32_t>(config_audio->sampleFrameCount);
int32_t flags = static_cast<int32_t>(config_audio->flags);
DebugPrintf("Set the configs\n");
// Create an implementation structure to hold the descriptors
// when they are returned.
AudioImpl* impl = new(std::nothrow) AudioImpl();
if (NULL == impl) {
return NPERR_GENERIC_ERROR;
}
DebugPrintf("Created the impl\n");
context_audio->reserved = reinterpret_cast<void*>(impl);
// Remember the context this is for so that the callback can get it.
impl->context = context_audio;
// Create a closure to be called when NPModule calls us back with
// the descriptors. We are remembering the user-supplied callback
// function and our implementation data. When the RPC to invoke the
// callback comes from the browser, we will copy some descriptors into
// the implementation and then invoke the user-supplied callback with
// the context.
uint32_t id;
NPNavigator* nav = NPNavigator::GetNavigator();
NPClosureTable::FunctionPointer func =
reinterpret_cast<NPClosureTable::FunctionPointer>(
context_audio->config.callback);
// Pedantic mode refuses zu format, hence casting to void*. The cast to size_t
// fixes the GCC warning about the cast of function ptr to data ptr.
DebugPrintf("Created the closure %p for %p\n",
reinterpret_cast<void*>(reinterpret_cast<size_t>(func)),
reinterpret_cast<void*>(
reinterpret_cast<size_t>(context_audio->config.callback)));
if (NULL == nav->closure_table() ||
!nav->closure_table()->Add(func,
context_audio->reserved,
&id)) {
return NPERR_GENERIC_ERROR;
}
DebugPrintf("Added the closure %p\n",
reinterpret_cast<void*>(reinterpret_cast<size_t>(func)));
// Make the SRPC to request the setup for the context.
NaClSrpcChannel* channel = nav->channel();
NaClSrpcError retval =
AudioRpcClient::AudioInitialize(
channel,
NPPToWireFormat(instance),
id,
sample_rate,
sample_type,
output_channel_map,
input_channel_map,
sample_frame_count,
flags);
DebugPrintf("Called init\n");
if (NACL_SRPC_RESULT_OK != retval) {
return NPERR_GENERIC_ERROR;
}
return NPERR_NO_ERROR;
}
static NPError GetStateContext(NPP instance,
NPDeviceContext* context,
int32 state,
intptr_t *value) {
// UNREFERENCED_PARAMETER(context);
NPNavigator* nav = NPNavigator::GetNavigator();
NaClSrpcChannel* channel = nav->channel();
// Value is only intptr_t to allow passing of the TransportDIB function
// pointer. Otherwise they're all int32_t.
int32_t value32;
NaClSrpcError retval =
AudioRpcClient::AudioGetState(
channel,
NPPToWireFormat(instance),
state,
&value32);
if (NACL_SRPC_RESULT_OK != retval) {
return NPERR_GENERIC_ERROR;
}
*value = static_cast<intptr_t>(value32);
return NPERR_NO_ERROR;
}
static NPError SetStateContext(NPP instance,
NPDeviceContext* context,
int32 state,
intptr_t value) {
// UNREFERENCED_PARAMETER(context);
NPNavigator* nav = NPNavigator::GetNavigator();
NaClSrpcChannel* channel = nav->channel();
// Value is only intptr_t to allow passing of the TransportDIB function
// pointer. Otherwise they're all int32_t. Verify anyway.
// TODO(sehr,ilewis): use checked_cast<> here.
if (INT32_MAX < value || INT32_MIN > value) {
return NPERR_GENERIC_ERROR;
}
int32_t value32 = static_cast<int32_t>(value);
NaClSrpcError retval =
AudioRpcClient::AudioSetState(
channel,
NPPToWireFormat(instance),
state,
value32);
if (NACL_SRPC_RESULT_OK != retval) {
return NPERR_GENERIC_ERROR;
}
return NPERR_NO_ERROR;
}
static NPError FlushContext(NPP instance,
NPDeviceContext* context,
NPDeviceFlushContextCallbackPtr callback,
void* userData) {
// UNREFERENCED_PARAMETER(instance);
// UNREFERENCED_PARAMETER(context);
// UNREFERENCED_PARAMETER(callback);
// UNREFERENCED_PARAMETER(userData);
// NOTE: this method does not appear to be used in the current version of the
// Pepper API. Instead, the callback from InitializeContext invokes a method
// that will synchronize by means of impl->sync_desc.
return NPERR_GENERIC_ERROR;
}
static NPError DestroyContext(NPP instance, NPDeviceContext* context) {
NPDeviceContextAudio* context_audio =
reinterpret_cast<NPDeviceContextAudio*>(context);
AudioImpl* impl = NULL;
// If the context wasn't initialized, return an error.
if (NULL == context_audio->reserved) {
return NPERR_GENERIC_ERROR;
}
impl = reinterpret_cast<AudioImpl*>(context_audio->reserved);
if (NULL != context_audio->outBuffer) {
munmap(context_audio->outBuffer, impl->shared_memory_size);
context_audio->outBuffer = NULL;
}
// Close the shared memory descriptor.
if (kInvalidDesc != impl->shared_memory_desc) {
close(impl->shared_memory_desc);
}
// Close the sync descriptor.
if (kInvalidDesc != impl->sync_desc) {
close(impl->sync_desc);
}
// Remove the implementation artifacts.
delete impl;
context_audio->reserved = NULL;
// And destroy the corresponding structure in the renderer.
NPNavigator* nav = NPNavigator::GetNavigator();
NaClSrpcChannel* channel = nav->channel();
NaClSrpcError retval =
AudioRpcClient::AudioDestroy(
channel,
NPPToWireFormat(instance));
if (NACL_SRPC_RESULT_OK != retval) {
return NPERR_GENERIC_ERROR;
}
return NPERR_NO_ERROR;
}
NPError CreateBuffer(NPP instance,
NPDeviceContext* context,
size_t size,
int32* id) {
// There is no corresponding function in the trusted pepper implementation.
return NPERR_GENERIC_ERROR;
}
NPError DestroyBuffer(NPP instance,
NPDeviceContext* context,
int32 id) {
// There is no corresponding function in the trusted pepper implementation.
return NPERR_GENERIC_ERROR;
}
NPError MapBuffer(NPP instance,
NPDeviceContext* context,
int32 id,
NPDeviceBuffer* buffer) {
// There is no corresponding function in the trusted pepper implementation.
return NPERR_GENERIC_ERROR;
}
static void* AudioCallbackThread(void* data) {
NPDeviceContextAudio* context_audio =
reinterpret_cast<NPDeviceContextAudio*>(data);
DebugPrintf("AudioCallbackThread %p\n", data);
if (NULL == context_audio) {
return NULL;
}
DebugPrintf("AudioCallbackThread impl %p\n", context_audio->reserved);
AudioImpl* impl = reinterpret_cast<AudioImpl*>(context_audio->reserved);
if (NULL == impl) {
return NULL;
}
DebugPrintf("AudioCallbackThread entering loop\n");
int pending_data;
while (sizeof(pending_data) ==
read(impl->sync_desc, &pending_data, sizeof(pending_data))) {
DebugPrintf("invoking callback\n");
if (NULL != context_audio->config.callback) {
context_audio->config.callback(context_audio);
}
}
return NULL;
}
} // namespace
namespace nacl {
const NPDevice* GetAudio() {
static const struct NPDevice deviceAudio = {
QueryCapability,
QueryConfig,
InitializeContext,
SetStateContext,
GetStateContext,
FlushContext,
DestroyContext,
CreateBuffer,
DestroyBuffer,
MapBuffer
};
return &deviceAudio;
}
bool DoAudioCallback(NPClosureTable* closure_table,
int32_t number,
int shm_desc,
int32_t shm_size,
int sync_desc) {
uint32_t id = static_cast<uint32_t>(number);
NPClosureTable::FunctionPointer func;
void* user_data;
DebugPrintf("DoAudioCallback\n");
if (NULL == closure_table ||
!closure_table->Remove(id, &func, &user_data) ||
NULL == func ||
NULL == user_data) {
return false;
}
// Place the returned handle in the struct passed as user_data.
AudioImpl* impl = reinterpret_cast<AudioImpl*>(user_data);
impl->sync_desc = sync_desc;
impl->shared_memory_desc = shm_desc;
impl->shared_memory_size = shm_size;
void* buf = mmap(NULL,
shm_size,
PROT_READ | PROT_WRITE,
MAP_SHARED,
shm_desc,
0);
if (MAP_FAILED == buf) {
DebugPrintf("mmap failed %"NACL_PRIx32" %d %d\n",
shm_size, shm_desc, sync_desc);
return false;
}
DebugPrintf("mmap succeeded %p\n", buf);
impl->context->outBuffer = buf;
if (impl->context->config.startThread) {
DebugPrintf("starting thread\n");
pthread_t callback_thread;
int ret = pthread_create(&callback_thread,
NULL,
AudioCallbackThread,
impl->context);
if (0 != ret) {
DebugPrintf("Thread creation failed %d %d\n", ret, errno);
return false;
}
} else {
// Invoke the function with the data.
(*func)(reinterpret_cast<void*>(impl->context));
}
// Return success.
return true;
}
} // namespace nacl
<commit_msg>Nexuiz is specifying "--wrap read" to the linker, which changes all undefined calls to read to __wrap_read. The audio thread needs the syscall read to read the SyncSocket, so I am adding a local definition of the wrapper for that syscall.<commit_after>// Copyright (c) 2010 The Native Client Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// NaCl module Pepper extensions interface. Audio API.
// This file implements the untrusted client interface to audio.
#include "native_client/src/shared/npruntime/audio.h"
#include <inttypes.h>
#include <stdlib.h>
#include <nacl/nacl_inttypes.h>
#include <sys/errno.h>
#include <sys/mman.h>
#include <sys/nacl_syscalls.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <limits>
#include <map>
#include <utility>
#include "native_client/src/include/portability_string.h"
#include "gen/native_client/src/shared/npruntime/npmodule_rpc.h"
#include "native_client/src/shared/npruntime/npnavigator.h"
#include "native_client/src/shared/npruntime/pointer_translations.h"
#include "native_client/src/shared/srpc/nacl_srpc.h"
#include "native_client/src/untrusted/nacl/syscall_bindings_trampoline.h"
#include "third_party/npapi/bindings/npapi_extensions.h"
using nacl::NPClosureTable;
using nacl::NPNavigator;
using nacl::NPPToWireFormat;
using nacl::DebugPrintf;
namespace {
static const int kInvalidDesc = -1;
struct AudioImpl {
public:
NPDeviceContextAudio* context;
int shared_memory_desc;
size_t shared_memory_size;
int sync_desc;
};
static NPError QueryCapability(NPP instance,
int32 capability,
int32 *value) {
// UNREFERENCED_PARAMETER(instance);
// UNREFERENCED_PARAMETER(capability);
// UNREFERENCED_PARAMETER(value);
// There is no corresponding function in the trusted pepper implementation.
return NPERR_GENERIC_ERROR;
}
static NPError QueryConfig(NPP instance,
const NPDeviceConfig* request,
NPDeviceConfig* obtain) {
// UNREFERENCED_PARAMETER(instance);
// UNREFERENCED_PARAMETER(request);
// UNREFERENCED_PARAMETER(obtain);
// There is no corresponding function in the trusted pepper implementation.
return NPERR_GENERIC_ERROR;
}
static NPError InitializeContext(NPP instance,
const NPDeviceConfig* config,
NPDeviceContext* context) {
DebugPrintf("Audio::InitializeContext %p %p\n",
reinterpret_cast<const void*>(config),
reinterpret_cast<void*>(context));
const NPDeviceContextAudioConfig* config_audio =
reinterpret_cast<const NPDeviceContextAudioConfig*>(config);
NPDeviceContextAudio* context_audio =
reinterpret_cast<NPDeviceContextAudio*>(context);
// Initialize the context structure.
context_audio->config = *config_audio;
context_audio->outBuffer = NULL;
context_audio->inBuffer = NULL;
context_audio->reserved = NULL;
DebugPrintf("Set the config and base stuff\n");
// Get the configuration parameters for passing.
// TODO(sehr): the SRPC generators speak int32_t, while npruntime likes
// int32. Find a way to avoid all these casts.
int32_t sample_rate = static_cast<int32_t>(config_audio->sampleRate);
int32_t sample_type = static_cast<int32_t>(config_audio->sampleType);
int32_t output_channel_map =
static_cast<int32_t>(config_audio->outputChannelMap);
int32_t input_channel_map =
static_cast<int32_t>(config_audio->inputChannelMap);
int32_t sample_frame_count =
static_cast<int32_t>(config_audio->sampleFrameCount);
int32_t flags = static_cast<int32_t>(config_audio->flags);
DebugPrintf("Set the configs\n");
// Create an implementation structure to hold the descriptors
// when they are returned.
AudioImpl* impl = new(std::nothrow) AudioImpl();
if (NULL == impl) {
return NPERR_GENERIC_ERROR;
}
DebugPrintf("Created the impl\n");
context_audio->reserved = reinterpret_cast<void*>(impl);
// Remember the context this is for so that the callback can get it.
impl->context = context_audio;
// Create a closure to be called when NPModule calls us back with
// the descriptors. We are remembering the user-supplied callback
// function and our implementation data. When the RPC to invoke the
// callback comes from the browser, we will copy some descriptors into
// the implementation and then invoke the user-supplied callback with
// the context.
uint32_t id;
NPNavigator* nav = NPNavigator::GetNavigator();
NPClosureTable::FunctionPointer func =
reinterpret_cast<NPClosureTable::FunctionPointer>(
context_audio->config.callback);
// Pedantic mode refuses zu format, hence casting to void*. The cast to size_t
// fixes the GCC warning about the cast of function ptr to data ptr.
DebugPrintf("Created the closure %p for %p\n",
reinterpret_cast<void*>(reinterpret_cast<size_t>(func)),
reinterpret_cast<void*>(
reinterpret_cast<size_t>(context_audio->config.callback)));
if (NULL == nav->closure_table() ||
!nav->closure_table()->Add(func,
context_audio->reserved,
&id)) {
return NPERR_GENERIC_ERROR;
}
DebugPrintf("Added the closure %p\n",
reinterpret_cast<void*>(reinterpret_cast<size_t>(func)));
// Make the SRPC to request the setup for the context.
NaClSrpcChannel* channel = nav->channel();
NaClSrpcError retval =
AudioRpcClient::AudioInitialize(
channel,
NPPToWireFormat(instance),
id,
sample_rate,
sample_type,
output_channel_map,
input_channel_map,
sample_frame_count,
flags);
DebugPrintf("Called init\n");
if (NACL_SRPC_RESULT_OK != retval) {
return NPERR_GENERIC_ERROR;
}
return NPERR_NO_ERROR;
}
static NPError GetStateContext(NPP instance,
NPDeviceContext* context,
int32 state,
intptr_t *value) {
// UNREFERENCED_PARAMETER(context);
NPNavigator* nav = NPNavigator::GetNavigator();
NaClSrpcChannel* channel = nav->channel();
// Value is only intptr_t to allow passing of the TransportDIB function
// pointer. Otherwise they're all int32_t.
int32_t value32;
NaClSrpcError retval =
AudioRpcClient::AudioGetState(
channel,
NPPToWireFormat(instance),
state,
&value32);
if (NACL_SRPC_RESULT_OK != retval) {
return NPERR_GENERIC_ERROR;
}
*value = static_cast<intptr_t>(value32);
return NPERR_NO_ERROR;
}
static NPError SetStateContext(NPP instance,
NPDeviceContext* context,
int32 state,
intptr_t value) {
// UNREFERENCED_PARAMETER(context);
NPNavigator* nav = NPNavigator::GetNavigator();
NaClSrpcChannel* channel = nav->channel();
// Value is only intptr_t to allow passing of the TransportDIB function
// pointer. Otherwise they're all int32_t. Verify anyway.
// TODO(sehr,ilewis): use checked_cast<> here.
if (INT32_MAX < value || INT32_MIN > value) {
return NPERR_GENERIC_ERROR;
}
int32_t value32 = static_cast<int32_t>(value);
NaClSrpcError retval =
AudioRpcClient::AudioSetState(
channel,
NPPToWireFormat(instance),
state,
value32);
if (NACL_SRPC_RESULT_OK != retval) {
return NPERR_GENERIC_ERROR;
}
return NPERR_NO_ERROR;
}
static NPError FlushContext(NPP instance,
NPDeviceContext* context,
NPDeviceFlushContextCallbackPtr callback,
void* userData) {
// UNREFERENCED_PARAMETER(instance);
// UNREFERENCED_PARAMETER(context);
// UNREFERENCED_PARAMETER(callback);
// UNREFERENCED_PARAMETER(userData);
// NOTE: this method does not appear to be used in the current version of the
// Pepper API. Instead, the callback from InitializeContext invokes a method
// that will synchronize by means of impl->sync_desc.
return NPERR_GENERIC_ERROR;
}
static NPError DestroyContext(NPP instance, NPDeviceContext* context) {
NPDeviceContextAudio* context_audio =
reinterpret_cast<NPDeviceContextAudio*>(context);
AudioImpl* impl = NULL;
// If the context wasn't initialized, return an error.
if (NULL == context_audio->reserved) {
return NPERR_GENERIC_ERROR;
}
impl = reinterpret_cast<AudioImpl*>(context_audio->reserved);
if (NULL != context_audio->outBuffer) {
munmap(context_audio->outBuffer, impl->shared_memory_size);
context_audio->outBuffer = NULL;
}
// Close the shared memory descriptor.
if (kInvalidDesc != impl->shared_memory_desc) {
close(impl->shared_memory_desc);
}
// Close the sync descriptor.
if (kInvalidDesc != impl->sync_desc) {
close(impl->sync_desc);
}
// Remove the implementation artifacts.
delete impl;
context_audio->reserved = NULL;
// And destroy the corresponding structure in the renderer.
NPNavigator* nav = NPNavigator::GetNavigator();
NaClSrpcChannel* channel = nav->channel();
NaClSrpcError retval =
AudioRpcClient::AudioDestroy(
channel,
NPPToWireFormat(instance));
if (NACL_SRPC_RESULT_OK != retval) {
return NPERR_GENERIC_ERROR;
}
return NPERR_NO_ERROR;
}
NPError CreateBuffer(NPP instance,
NPDeviceContext* context,
size_t size,
int32* id) {
// There is no corresponding function in the trusted pepper implementation.
return NPERR_GENERIC_ERROR;
}
NPError DestroyBuffer(NPP instance,
NPDeviceContext* context,
int32 id) {
// There is no corresponding function in the trusted pepper implementation.
return NPERR_GENERIC_ERROR;
}
NPError MapBuffer(NPP instance,
NPDeviceContext* context,
int32 id,
NPDeviceBuffer* buffer) {
// There is no corresponding function in the trusted pepper implementation.
return NPERR_GENERIC_ERROR;
}
// Some clients may use --wrap read, which replaces read by a user-specified
// alternate function. That will cause major problems here as we need to use
// the real read syscall. To handle this, we add a static binding to the
// real system call.
// TODO(sehr): All of this support will be unnecessary once we have file
// system access from Pepper. Remove this once we do.
static ssize_t socketread(int desc, void *buf, size_t count) {
ssize_t retval = NACL_SYSCALL(read)(desc, buf, count);
if (retval < 0) {
errno = -retval;
return -1;
}
return retval;
}
static void* AudioCallbackThread(void* data) {
NPDeviceContextAudio* context_audio =
reinterpret_cast<NPDeviceContextAudio*>(data);
DebugPrintf("AudioCallbackThread %p\n", data);
if (NULL == context_audio) {
return NULL;
}
DebugPrintf("AudioCallbackThread impl %p\n", context_audio->reserved);
AudioImpl* impl = reinterpret_cast<AudioImpl*>(context_audio->reserved);
if (NULL == impl) {
return NULL;
}
DebugPrintf("AudioCallbackThread entering loop\n");
int pending_data;
while (sizeof(pending_data) ==
socketread(impl->sync_desc, &pending_data, sizeof(pending_data))) {
DebugPrintf("invoking callback\n");
if (NULL != context_audio->config.callback) {
context_audio->config.callback(context_audio);
}
}
return NULL;
}
} // namespace
namespace nacl {
const NPDevice* GetAudio() {
static const struct NPDevice deviceAudio = {
QueryCapability,
QueryConfig,
InitializeContext,
SetStateContext,
GetStateContext,
FlushContext,
DestroyContext,
CreateBuffer,
DestroyBuffer,
MapBuffer
};
return &deviceAudio;
}
bool DoAudioCallback(NPClosureTable* closure_table,
int32_t number,
int shm_desc,
int32_t shm_size,
int sync_desc) {
uint32_t id = static_cast<uint32_t>(number);
NPClosureTable::FunctionPointer func;
void* user_data;
DebugPrintf("DoAudioCallback\n");
if (NULL == closure_table ||
!closure_table->Remove(id, &func, &user_data) ||
NULL == func ||
NULL == user_data) {
return false;
}
// Place the returned handle in the struct passed as user_data.
AudioImpl* impl = reinterpret_cast<AudioImpl*>(user_data);
impl->sync_desc = sync_desc;
impl->shared_memory_desc = shm_desc;
impl->shared_memory_size = shm_size;
void* buf = mmap(NULL,
shm_size,
PROT_READ | PROT_WRITE,
MAP_SHARED,
shm_desc,
0);
if (MAP_FAILED == buf) {
DebugPrintf("mmap failed %"NACL_PRIx32" %d %d\n",
shm_size, shm_desc, sync_desc);
return false;
}
DebugPrintf("mmap succeeded %p\n", buf);
impl->context->outBuffer = buf;
if (impl->context->config.startThread) {
DebugPrintf("starting thread\n");
pthread_t callback_thread;
int ret = pthread_create(&callback_thread,
NULL,
AudioCallbackThread,
impl->context);
if (0 != ret) {
DebugPrintf("Thread creation failed %d %d\n", ret, errno);
return false;
}
} else {
// Invoke the function with the data.
(*func)(reinterpret_cast<void*>(impl->context));
}
// Return success.
return true;
}
} // namespace nacl
<|endoftext|>
|
<commit_before>/*
* Monitor which expects a string on a TCP connection.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "lb_expect_monitor.hxx"
#include "lb_monitor.hxx"
#include "lb_config.hxx"
#include "pool.hxx"
#include "async.hxx"
#include "gerrno.h"
#include "net/ConnectSocket.hxx"
#include "net/SocketDescriptor.hxx"
#include "net/SocketAddress.hxx"
#include "util/Cast.hxx"
#include <event.h>
#include <unistd.h>
#include <sys/socket.h>
#include <string.h>
#include <errno.h>
struct ExpectMonitor {
struct pool *pool;
const lb_monitor_config *config;
int fd;
struct event event;
LBMonitorHandler *handler;
struct async_operation_ref *async_ref;
struct async_operation async_operation;
ExpectMonitor(struct pool *_pool, const lb_monitor_config *_config,
LBMonitorHandler &_handler,
async_operation_ref *_async_ref)
:pool(_pool), config(_config),
handler(&_handler),
async_ref(_async_ref) {}
ExpectMonitor(const ExpectMonitor &other) = delete;
};
static bool
check_expectation(char *received, size_t received_length,
const char *expect)
{
return g_strrstr_len(received, received_length, expect) != NULL;
}
/*
* async operation
*
*/
static void
expect_monitor_request_abort(struct async_operation *ao)
{
ExpectMonitor *expect =
&ContainerCast2(*ao, &ExpectMonitor::async_operation);
event_del(&expect->event);
close(expect->fd);
pool_unref(expect->pool);
delete expect;
}
static const struct async_operation_class expect_monitor_async_operation = {
.abort = expect_monitor_request_abort,
};
/*
* libevent callback
*
*/
static void
expect_monitor_event_callback(gcc_unused int fd, short event, void *ctx)
{
ExpectMonitor *expect =
(ExpectMonitor *)ctx;
expect->async_operation.Finished();
if (event & EV_TIMEOUT) {
close(expect->fd);
expect->handler->Timeout();
} else {
char buffer[1024];
ssize_t nbytes = recv(expect->fd, buffer, sizeof(buffer),
MSG_DONTWAIT);
if (nbytes < 0) {
GError *error = new_error_errno();
close(fd);
expect->handler->Error(error);
} else if (!expect->config->fade_expect.empty() &&
check_expectation(buffer, nbytes,
expect->config->fade_expect.c_str())) {
close(fd);
expect->handler->Fade();
} else if (expect->config->expect.empty() ||
check_expectation(buffer, nbytes,
expect->config->expect.c_str())) {
close(fd);
expect->handler->Success();
} else {
close(fd);
GError *error = g_error_new_literal(g_file_error_quark(), 0,
"Expectation failed");
expect->handler->Error(error);
}
}
pool_unref(expect->pool);
delete expect;
pool_commit();
}
/*
* client_socket handler
*
*/
static void
expect_monitor_success(SocketDescriptor &&fd, void *ctx)
{
ExpectMonitor *expect =
(ExpectMonitor *)ctx;
if (!expect->config->send.empty()) {
ssize_t nbytes = send(fd.Get(), expect->config->send.data(),
expect->config->send.length(),
MSG_DONTWAIT);
if (nbytes < 0) {
GError *error = new_error_errno();
expect->handler->Error(error);
return;
}
}
struct timeval expect_timeout = {
time_t(expect->config->timeout > 0 ? expect->config->timeout : 10),
0,
};
expect->fd = fd.Steal();
event_set(&expect->event, expect->fd, EV_READ|EV_TIMEOUT,
expect_monitor_event_callback, expect);
event_add(&expect->event, &expect_timeout);
expect->async_operation.Init(expect_monitor_async_operation);
expect->async_ref->Set(expect->async_operation);
pool_ref(expect->pool);
}
static void
expect_monitor_timeout(void *ctx)
{
ExpectMonitor *expect =
(ExpectMonitor *)ctx;
expect->handler->Timeout();
delete expect;
}
static void
expect_monitor_error(GError *error, void *ctx)
{
ExpectMonitor *expect =
(ExpectMonitor *)ctx;
expect->handler->Error(error);
delete expect;
}
static constexpr ConnectSocketHandler expect_monitor_handler = {
.success = expect_monitor_success,
.timeout = expect_monitor_timeout,
.error = expect_monitor_error,
};
/*
* lb_monitor_class
*
*/
static void
expect_monitor_run(struct pool *pool, const struct lb_monitor_config *config,
SocketAddress address,
LBMonitorHandler &handler,
struct async_operation_ref *async_ref)
{
ExpectMonitor *expect = new ExpectMonitor(pool, config,
handler,
async_ref);
const unsigned connect_timeout = config->connect_timeout > 0
? config->connect_timeout
: (config->timeout > 0
? config->timeout
: 30);
client_socket_new(*pool, address.GetFamily(), SOCK_STREAM, 0,
false,
SocketAddress::Null(),
address,
connect_timeout,
expect_monitor_handler, expect,
*async_ref);
}
const struct lb_monitor_class expect_monitor_class = {
.run = expect_monitor_run,
};
<commit_msg>lb_expect_monitor: use class Event<commit_after>/*
* Monitor which expects a string on a TCP connection.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "lb_expect_monitor.hxx"
#include "lb_monitor.hxx"
#include "lb_config.hxx"
#include "pool.hxx"
#include "async.hxx"
#include "gerrno.h"
#include "net/ConnectSocket.hxx"
#include "net/SocketDescriptor.hxx"
#include "net/SocketAddress.hxx"
#include "event/Event.hxx"
#include "util/Cast.hxx"
#include <unistd.h>
#include <sys/socket.h>
#include <string.h>
#include <errno.h>
struct ExpectMonitor {
struct pool *pool;
const lb_monitor_config *config;
int fd;
Event event;
LBMonitorHandler *handler;
struct async_operation_ref *async_ref;
struct async_operation async_operation;
ExpectMonitor(struct pool *_pool, const lb_monitor_config *_config,
LBMonitorHandler &_handler,
async_operation_ref *_async_ref)
:pool(_pool), config(_config),
handler(&_handler),
async_ref(_async_ref) {}
ExpectMonitor(const ExpectMonitor &other) = delete;
};
static bool
check_expectation(char *received, size_t received_length,
const char *expect)
{
return g_strrstr_len(received, received_length, expect) != NULL;
}
/*
* async operation
*
*/
static void
expect_monitor_request_abort(struct async_operation *ao)
{
ExpectMonitor *expect =
&ContainerCast2(*ao, &ExpectMonitor::async_operation);
expect->event.Delete();
close(expect->fd);
pool_unref(expect->pool);
delete expect;
}
static const struct async_operation_class expect_monitor_async_operation = {
.abort = expect_monitor_request_abort,
};
/*
* libevent callback
*
*/
static void
expect_monitor_event_callback(gcc_unused int fd, short event, void *ctx)
{
ExpectMonitor *expect =
(ExpectMonitor *)ctx;
expect->async_operation.Finished();
if (event & EV_TIMEOUT) {
close(expect->fd);
expect->handler->Timeout();
} else {
char buffer[1024];
ssize_t nbytes = recv(expect->fd, buffer, sizeof(buffer),
MSG_DONTWAIT);
if (nbytes < 0) {
GError *error = new_error_errno();
close(fd);
expect->handler->Error(error);
} else if (!expect->config->fade_expect.empty() &&
check_expectation(buffer, nbytes,
expect->config->fade_expect.c_str())) {
close(fd);
expect->handler->Fade();
} else if (expect->config->expect.empty() ||
check_expectation(buffer, nbytes,
expect->config->expect.c_str())) {
close(fd);
expect->handler->Success();
} else {
close(fd);
GError *error = g_error_new_literal(g_file_error_quark(), 0,
"Expectation failed");
expect->handler->Error(error);
}
}
pool_unref(expect->pool);
delete expect;
pool_commit();
}
/*
* client_socket handler
*
*/
static void
expect_monitor_success(SocketDescriptor &&fd, void *ctx)
{
ExpectMonitor *expect =
(ExpectMonitor *)ctx;
if (!expect->config->send.empty()) {
ssize_t nbytes = send(fd.Get(), expect->config->send.data(),
expect->config->send.length(),
MSG_DONTWAIT);
if (nbytes < 0) {
GError *error = new_error_errno();
expect->handler->Error(error);
return;
}
}
struct timeval expect_timeout = {
time_t(expect->config->timeout > 0 ? expect->config->timeout : 10),
0,
};
expect->fd = fd.Steal();
expect->event.Set(expect->fd, EV_READ|EV_TIMEOUT,
expect_monitor_event_callback, expect);
expect->event.Add(expect_timeout);
expect->async_operation.Init(expect_monitor_async_operation);
expect->async_ref->Set(expect->async_operation);
pool_ref(expect->pool);
}
static void
expect_monitor_timeout(void *ctx)
{
ExpectMonitor *expect =
(ExpectMonitor *)ctx;
expect->handler->Timeout();
delete expect;
}
static void
expect_monitor_error(GError *error, void *ctx)
{
ExpectMonitor *expect =
(ExpectMonitor *)ctx;
expect->handler->Error(error);
delete expect;
}
static constexpr ConnectSocketHandler expect_monitor_handler = {
.success = expect_monitor_success,
.timeout = expect_monitor_timeout,
.error = expect_monitor_error,
};
/*
* lb_monitor_class
*
*/
static void
expect_monitor_run(struct pool *pool, const struct lb_monitor_config *config,
SocketAddress address,
LBMonitorHandler &handler,
struct async_operation_ref *async_ref)
{
ExpectMonitor *expect = new ExpectMonitor(pool, config,
handler,
async_ref);
const unsigned connect_timeout = config->connect_timeout > 0
? config->connect_timeout
: (config->timeout > 0
? config->timeout
: 30);
client_socket_new(*pool, address.GetFamily(), SOCK_STREAM, 0,
false,
SocketAddress::Null(),
address,
connect_timeout,
expect_monitor_handler, expect,
*async_ref);
}
const struct lb_monitor_class expect_monitor_class = {
.run = expect_monitor_run,
};
<|endoftext|>
|
<commit_before>#include "vector.h"
#include "MinIMU9.h"
#include <stdio.h>
MinIMU9::MinIMU9(I2CBus& i2c) : compass(i2c), gyro(i2c)
{
}
void MinIMU9::checkConnection()
{
uint8_t result = compass.readMagReg(LSM303_WHO_AM_I_M);
if (result != 0x3C)
{
fprintf(stderr, "Error getting \"Who Am I\" register.\n");
exit(2);
}
}
void MinIMU9::enableSensors()
{
//compass.enableDefault();
//gyro.enableDefault();
compass.writeAccReg(LSM303_CTRL_REG1_A, 0x47); // normal power mode, all axes enabled, 50 Hz
compass.writeAccReg(LSM303_CTRL_REG4_A, 0x20); // 8 g full scale
compass.writeMagReg(LSM303_MR_REG_M, 0x00); // continuous conversion mode
// 15 Hz default
gyro.writeReg(L3G_CTRL_REG1, 0x0F); // normal power mode, all axes enabled, 100 Hz
gyro.writeReg(L3G_CTRL_REG4, 0x20); // 2000 dps full scale
}
void MinIMU9::loadCalibration()
{
// TODO: load from ~/.lsm303_mag_cal instead of hardcoding
mag_min = int_vector(-550, -800, -780);
mag_max = int_vector(770, 640, 680);
}
// Calculate offsets, assuming the MinIMU is resting
// with is z axis pointing up.
void MinIMU9::measureOffsets()
{
// LSM303 accelerometer: 8 g sensitivity. 3.8 mg/digit; 1 g = 256.
// TODO: unify this with the other place in the code where we scale accelerometer readings.
const int gravity = 256;
gyro_offset = accel_offset = vector::Zero();
const int sampleCount = 32;
for(int i = 0; i < sampleCount; i++)
{
gyro.read();
compass.readAcc();
gyro_offset += vector_from_ints(&gyro.g);
accel_offset += vector_from_ints(&compass.a);
usleep(20*1000);
}
gyro_offset /= sampleCount;
accel_offset /= sampleCount;
accel_offset(2) -= gravity;
if (accel_offset.norm() > 50)
{
fprintf(stderr, "Unable to calculate accelerometer offset because board was not resting in the correct orientation.\n");
accel_offset = vector::Zero();
}
}
vector MinIMU9::readMag()
{
compass.readMag();
IMU::m = int_vector_from_ints(&compass.m);
vector v;
v(0) = (float)(compass.m[0] - mag_min(0)) / (mag_max(0) - mag_min(0)) * 2 - 1;
v(1) = (float)(compass.m[1] - mag_min(1)) / (mag_max(1) - mag_min(1)) * 2 - 1;
v(2) = (float)(compass.m[2] - mag_min(2)) / (mag_max(2) - mag_min(2)) * 2 - 1;
return v;
}
vector MinIMU9::readAcc()
{
// LSM303 accelerometer: At 8 g sensitivity, the datasheet says
// we get 3.9 mg/digit.
// TODO: double check this figure using the correct datasheet
const float accel_scale = 0.0039;
compass.readAcc();
IMU::a = int_vector_from_ints(&compass.a);
return ( vector_from_ints(&compass.a) - accel_offset ) * accel_scale;
}
vector MinIMU9::readGyro()
{
// At the full-scale=2000 dps setting, the gyro datasheet says
// we get 0.07 dps/digit.
const float gyro_scale = 0.07 * 3.14159265 / 180;
gyro.read();
IMU::g = int_vector_from_ints(&gyro.g);
return ( vector_from_ints(&gyro.g) - gyro_offset ) * gyro_scale;
}
<commit_msg>New mag calibration<commit_after>#include "vector.h"
#include "MinIMU9.h"
#include <stdio.h>
MinIMU9::MinIMU9(I2CBus& i2c) : compass(i2c), gyro(i2c)
{
}
void MinIMU9::checkConnection()
{
uint8_t result = compass.readMagReg(LSM303_WHO_AM_I_M);
if (result != 0x3C)
{
fprintf(stderr, "Error getting \"Who Am I\" register.\n");
exit(2);
}
}
void MinIMU9::enableSensors()
{
//compass.enableDefault();
//gyro.enableDefault();
compass.writeAccReg(LSM303_CTRL_REG1_A, 0x47); // normal power mode, all axes enabled, 50 Hz
compass.writeAccReg(LSM303_CTRL_REG4_A, 0x20); // 8 g full scale
compass.writeMagReg(LSM303_MR_REG_M, 0x00); // continuous conversion mode
// 15 Hz default
gyro.writeReg(L3G_CTRL_REG1, 0x0F); // normal power mode, all axes enabled, 100 Hz
gyro.writeReg(L3G_CTRL_REG4, 0x20); // 2000 dps full scale
}
void MinIMU9::loadCalibration()
{
// TODO: load from ~/.lsm303_mag_cal instead of hardcoding
mag_min = int_vector(-525, -746, -728);
mag_max = int_vector(737, 665, 633);
}
// Calculate offsets, assuming the MinIMU is resting
// with is z axis pointing up.
void MinIMU9::measureOffsets()
{
// LSM303 accelerometer: 8 g sensitivity. 3.8 mg/digit; 1 g = 256.
// TODO: unify this with the other place in the code where we scale accelerometer readings.
const int gravity = 256;
gyro_offset = accel_offset = vector::Zero();
const int sampleCount = 32;
for(int i = 0; i < sampleCount; i++)
{
gyro.read();
compass.readAcc();
gyro_offset += vector_from_ints(&gyro.g);
accel_offset += vector_from_ints(&compass.a);
usleep(20*1000);
}
gyro_offset /= sampleCount;
accel_offset /= sampleCount;
accel_offset(2) -= gravity;
if (accel_offset.norm() > 50)
{
fprintf(stderr, "Unable to calculate accelerometer offset because board was not resting in the correct orientation.\n");
accel_offset = vector::Zero();
}
}
vector MinIMU9::readMag()
{
compass.readMag();
IMU::m = int_vector_from_ints(&compass.m);
vector v;
v(0) = (float)(compass.m[0] - mag_min(0)) / (mag_max(0) - mag_min(0)) * 2 - 1;
v(1) = (float)(compass.m[1] - mag_min(1)) / (mag_max(1) - mag_min(1)) * 2 - 1;
v(2) = (float)(compass.m[2] - mag_min(2)) / (mag_max(2) - mag_min(2)) * 2 - 1;
return v;
}
vector MinIMU9::readAcc()
{
// LSM303 accelerometer: At 8 g sensitivity, the datasheet says
// we get 3.9 mg/digit.
// TODO: double check this figure using the correct datasheet
const float accel_scale = 0.0039;
compass.readAcc();
IMU::a = int_vector_from_ints(&compass.a);
return ( vector_from_ints(&compass.a) - accel_offset ) * accel_scale;
}
vector MinIMU9::readGyro()
{
// At the full-scale=2000 dps setting, the gyro datasheet says
// we get 0.07 dps/digit.
const float gyro_scale = 0.07 * 3.14159265 / 180;
gyro.read();
IMU::g = int_vector_from_ints(&gyro.g);
return ( vector_from_ints(&gyro.g) - gyro_offset ) * gyro_scale;
}
<|endoftext|>
|
<commit_before>
<commit_msg>Delete 1.cpp<commit_after><|endoftext|>
|
<commit_before>#include <nan.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <v8.h>
#include "napi.h"
extern "C" {
#include "rpi_ws281x/ws2811.h"
}
using namespace v8;
#define DEFAULT_TARGET_FREQ 800000
#define DEFAULT_GPIO_PIN 18
#define DEFAULT_DMANUM 10
#define PARAM_FREQ 1
#define PARAM_DMANUM 2
#define PARAM_GPIONUM 3
#define PARAM_COUNT 4
#define PARAM_INVERT 5
#define PARAM_BRIGHTNESS 6
#define PARAM_STRIP_TYPE 7
ws2811_t ws281x;
/**
* ws281x.setParam(param:Number, value:Number)
* wrap setting global params in ws2811_t
*/
void setParam(const Nan::FunctionCallbackInfo<v8::Value> &info) {
if (info.Length() != 2) {
Nan::ThrowTypeError("setParam(): expected two params");
return;
}
if (!info[0]->IsNumber()) {
Nan::ThrowTypeError(
"setParam(): expected argument 1 to be the parameter-id");
return;
}
if (!info[1]->IsNumber()) {
Nan::ThrowTypeError("setParam(): expected argument 2 to be the value");
return;
}
const int param = Nan::To<int32_t>(info[0]).FromJust();
const int value = Nan::To<int32_t>(info[1]).FromJust();
switch (param) {
case PARAM_FREQ:
ws281x.freq = value;
break;
case PARAM_DMANUM:
ws281x.dmanum = value;
break;
default:
Nan::ThrowTypeError("setParam(): invalid parameter-id");
return;
}
}
/**
* ws281x.setChannelParam(channel:Number, param:Number, value:Number)
*
* wrap setting params in ws2811_channel_t
*/
void setChannelParam(const Nan::FunctionCallbackInfo<v8::Value> &info) {
if (info.Length() != 3) {
Nan::ThrowTypeError("setChannelParam(): missing argument");
return;
}
// retrieve channelNumber from argument 1
if (!info[0]->IsNumber()) {
Nan::ThrowTypeError(
"setChannelParam(): expected argument 1 to be the channel-number");
return;
}
const int channelNumber = Nan::To<int32_t>(info[0]).FromJust();
if (channelNumber > 1 || channelNumber < 0) {
Nan::ThrowError("setChannelParam(): invalid chanel-number");
return;
}
if (!info[1]->IsNumber()) {
Nan::ThrowTypeError(
"setChannelParam(): expected argument 2 to be the parameter-id");
return;
}
if (!info[2]->IsNumber() && !info[2]->IsBoolean()) {
Nan::ThrowTypeError(
"setChannelParam(): expected argument 3 to be the value");
return;
}
ws2811_channel_t *channel = &ws281x.channel[channelNumber];
const int param = Nan::To<int32_t>(info[1]).FromJust();
const int value = Nan::To<int32_t>(info[2]).FromJust();
switch (param) {
case PARAM_GPIONUM:
channel->gpionum = value;
break;
case PARAM_COUNT:
channel->count = value;
break;
case PARAM_INVERT:
channel->invert = value;
break;
case PARAM_BRIGHTNESS:
channel->brightness = (uint8_t)value;
break;
case PARAM_STRIP_TYPE:
channel->strip_type = value;
break;
default:
Nan::ThrowTypeError("setChannelParam(): invalid parameter-id");
return;
}
}
/**
* ws281x.setChannelData(channel:Number, buffer:Buffer)
*
* wrap copying data to ws2811_channel_t.leds
*/
void setChannelData(const Nan::FunctionCallbackInfo<v8::Value> &info) {
if (info.Length() != 2) {
Nan::ThrowTypeError("setChannelData(): missing argument.");
return;
}
// retrieve channelNumber from argument 1
if (!info[0]->IsNumber()) {
Nan::ThrowTypeError(
"setChannelData(): expected argument 1 to be the channel-number.");
return;
}
int channelNumber = Nan::To<int32_t>(info[0]).FromJust();
if (channelNumber > 1 || channelNumber < 0) {
Nan::ThrowError("setChannelData(): invalid chanel-number");
return;
}
ws2811_channel_t channel = ws281x.channel[channelNumber];
// retrieve buffer from argument 2
if (!node::Buffer::HasInstance(info[1])) {
Nan::ThrowTypeError("setChannelData(): expected argument 2 to be a Buffer");
return;
}
v8::Local<v8::Context> context = info.GetIsolate()->GetCurrentContext();
auto buffer = info[1]->ToObject(context).ToLocalChecked();
uint32_t *data = (uint32_t *)node::Buffer::Data(buffer);
if (channel.count == 0 || channel.leds == NULL) {
Nan::ThrowError("setChannelData(): channel not ready");
return;
}
const int numBytes = std::min(node::Buffer::Length(buffer),
sizeof(ws2811_led_t) * channel.count);
// FIXME: handle memcpy-result
memcpy(channel.leds, data, numBytes);
}
/**
* ws281x.init()
*
* wrap ws2811_init()
*/
void init(const Nan::FunctionCallbackInfo<v8::Value> &info) {
ws2811_return_t ret;
ret = ws2811_init(&ws281x);
if (ret != WS2811_SUCCESS) {
Nan::ThrowError(ws2811_get_return_t_str(ret));
return;
}
}
/**
* ws281x.render()
*
* wrap ws2811_wait() and ws2811_render()
*/
void render(const Nan::FunctionCallbackInfo<v8::Value> &info) {
ws2811_return_t ret;
ret = ws2811_wait(&ws281x);
if (ret != WS2811_SUCCESS) {
Nan::ThrowError(ws2811_get_return_t_str(ret));
return;
}
ret = ws2811_render(&ws281x);
if (ret != WS2811_SUCCESS) {
Nan::ThrowError(ws2811_get_return_t_str(ret));
return;
}
}
/**
* ws281x.finalize()
*
* wrap ws2811_wait() and ws2811_fini()
*/
void finalize(const Nan::FunctionCallbackInfo<v8::Value> &info) {
ws2811_return_t ret;
ret = ws2811_wait(&ws281x);
if (ret != WS2811_SUCCESS) {
Nan::ThrowError(ws2811_get_return_t_str(ret));
return;
}
ws2811_fini(&ws281x);
}
/**
* initializes the module.
*/
void initialize(Local<Object> exports) {
ws281x.freq = DEFAULT_TARGET_FREQ;
ws281x.dmanum = DEFAULT_DMANUM;
NAN_EXPORT(exports, setParam);
NAN_EXPORT(exports, setChannelParam);
NAN_EXPORT(exports, setChannelData);
NAN_EXPORT(exports, init);
NAN_EXPORT(exports, render);
NAN_EXPORT(exports, finalize);
}
Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set(Napi::String::New(env, "init"), Napi::Function::New(env, init));
exports.Set(Napi::String::New(env, "setBrightness"), Napi::Function::New(env, setBrightness));
exports.Set(Napi::String::New(env, "reset"), Napi::Function::New(env, reset));
exports.Set(Napi::String::New(env, "render"), Napi::Function::New(env, render));
return exports;
}
// vi: ts=2 sw=2 expandtab<commit_msg>fix: remove napi.h dependency<commit_after>#include <nan.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <v8.h>
extern "C" {
#include "rpi_ws281x/ws2811.h"
}
using namespace v8;
#define DEFAULT_TARGET_FREQ 800000
#define DEFAULT_GPIO_PIN 18
#define DEFAULT_DMANUM 10
#define PARAM_FREQ 1
#define PARAM_DMANUM 2
#define PARAM_GPIONUM 3
#define PARAM_COUNT 4
#define PARAM_INVERT 5
#define PARAM_BRIGHTNESS 6
#define PARAM_STRIP_TYPE 7
ws2811_t ws281x;
/**
* ws281x.setParam(param:Number, value:Number)
* wrap setting global params in ws2811_t
*/
void setParam(const Nan::FunctionCallbackInfo<v8::Value> &info) {
if (info.Length() != 2) {
Nan::ThrowTypeError("setParam(): expected two params");
return;
}
if (!info[0]->IsNumber()) {
Nan::ThrowTypeError(
"setParam(): expected argument 1 to be the parameter-id");
return;
}
if (!info[1]->IsNumber()) {
Nan::ThrowTypeError("setParam(): expected argument 2 to be the value");
return;
}
const int param = Nan::To<int32_t>(info[0]).FromJust();
const int value = Nan::To<int32_t>(info[1]).FromJust();
switch (param) {
case PARAM_FREQ:
ws281x.freq = value;
break;
case PARAM_DMANUM:
ws281x.dmanum = value;
break;
default:
Nan::ThrowTypeError("setParam(): invalid parameter-id");
return;
}
}
/**
* ws281x.setChannelParam(channel:Number, param:Number, value:Number)
*
* wrap setting params in ws2811_channel_t
*/
void setChannelParam(const Nan::FunctionCallbackInfo<v8::Value> &info) {
if (info.Length() != 3) {
Nan::ThrowTypeError("setChannelParam(): missing argument");
return;
}
// retrieve channelNumber from argument 1
if (!info[0]->IsNumber()) {
Nan::ThrowTypeError(
"setChannelParam(): expected argument 1 to be the channel-number");
return;
}
const int channelNumber = Nan::To<int32_t>(info[0]).FromJust();
if (channelNumber > 1 || channelNumber < 0) {
Nan::ThrowError("setChannelParam(): invalid chanel-number");
return;
}
if (!info[1]->IsNumber()) {
Nan::ThrowTypeError(
"setChannelParam(): expected argument 2 to be the parameter-id");
return;
}
if (!info[2]->IsNumber() && !info[2]->IsBoolean()) {
Nan::ThrowTypeError(
"setChannelParam(): expected argument 3 to be the value");
return;
}
ws2811_channel_t *channel = &ws281x.channel[channelNumber];
const int param = Nan::To<int32_t>(info[1]).FromJust();
const int value = Nan::To<int32_t>(info[2]).FromJust();
switch (param) {
case PARAM_GPIONUM:
channel->gpionum = value;
break;
case PARAM_COUNT:
channel->count = value;
break;
case PARAM_INVERT:
channel->invert = value;
break;
case PARAM_BRIGHTNESS:
channel->brightness = (uint8_t)value;
break;
case PARAM_STRIP_TYPE:
channel->strip_type = value;
break;
default:
Nan::ThrowTypeError("setChannelParam(): invalid parameter-id");
return;
}
}
/**
* ws281x.setChannelData(channel:Number, buffer:Buffer)
*
* wrap copying data to ws2811_channel_t.leds
*/
void setChannelData(const Nan::FunctionCallbackInfo<v8::Value> &info) {
if (info.Length() != 2) {
Nan::ThrowTypeError("setChannelData(): missing argument.");
return;
}
// retrieve channelNumber from argument 1
if (!info[0]->IsNumber()) {
Nan::ThrowTypeError(
"setChannelData(): expected argument 1 to be the channel-number.");
return;
}
int channelNumber = Nan::To<int32_t>(info[0]).FromJust();
if (channelNumber > 1 || channelNumber < 0) {
Nan::ThrowError("setChannelData(): invalid chanel-number");
return;
}
ws2811_channel_t channel = ws281x.channel[channelNumber];
// retrieve buffer from argument 2
if (!node::Buffer::HasInstance(info[1])) {
Nan::ThrowTypeError("setChannelData(): expected argument 2 to be a Buffer");
return;
}
v8::Local<v8::Context> context = info.GetIsolate()->GetCurrentContext();
auto buffer = info[1]->ToObject(context).ToLocalChecked();
uint32_t *data = (uint32_t *)node::Buffer::Data(buffer);
if (channel.count == 0 || channel.leds == NULL) {
Nan::ThrowError("setChannelData(): channel not ready");
return;
}
const int numBytes = std::min(node::Buffer::Length(buffer),
sizeof(ws2811_led_t) * channel.count);
// FIXME: handle memcpy-result
memcpy(channel.leds, data, numBytes);
}
/**
* ws281x.init()
*
* wrap ws2811_init()
*/
void init(const Nan::FunctionCallbackInfo<v8::Value> &info) {
ws2811_return_t ret;
ret = ws2811_init(&ws281x);
if (ret != WS2811_SUCCESS) {
Nan::ThrowError(ws2811_get_return_t_str(ret));
return;
}
}
/**
* ws281x.render()
*
* wrap ws2811_wait() and ws2811_render()
*/
void render(const Nan::FunctionCallbackInfo<v8::Value> &info) {
ws2811_return_t ret;
ret = ws2811_wait(&ws281x);
if (ret != WS2811_SUCCESS) {
Nan::ThrowError(ws2811_get_return_t_str(ret));
return;
}
ret = ws2811_render(&ws281x);
if (ret != WS2811_SUCCESS) {
Nan::ThrowError(ws2811_get_return_t_str(ret));
return;
}
}
/**
* ws281x.finalize()
*
* wrap ws2811_wait() and ws2811_fini()
*/
void finalize(const Nan::FunctionCallbackInfo<v8::Value> &info) {
ws2811_return_t ret;
ret = ws2811_wait(&ws281x);
if (ret != WS2811_SUCCESS) {
Nan::ThrowError(ws2811_get_return_t_str(ret));
return;
}
ws2811_fini(&ws281x);
}
NAN_MODULE_INIT(InitAll) {
Set(target, New<String>("init").ToLocalChecked(),
GetFunction(New<FunctionTemplate>(init)).ToLocalChecked());
Set(target, New<String>("setBrightness").ToLocalChecked(),
GetFunction(New<FunctionTemplate>(setBrightness)).ToLocalChecked());
Set(target, New<String>("reset").ToLocalChecked(),
GetFunction(New<FunctionTemplate>(reset)).ToLocalChecked());
Set(target, New<String>("render").ToLocalChecked(),
GetFunction(New<FunctionTemplate>(render)).ToLocalChecked());
Set(target, New<String>("finalize").ToLocalChecked(),
GetFunction(New<FunctionTemplate>(finalize)).ToLocalChecked());
}
NODE_MODULE(addon, InitAll)
// vi: ts=2 sw=2 expandtab<|endoftext|>
|
<commit_before><commit_msg>sim: Fix clang warning for unused variable<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2009, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// The ExceptionHandler object installs signal handlers for a number of
// signals. We rely on the signal handler running on the thread which crashed
// in order to identify it. This is true of the synchronous signals (SEGV etc),
// but not true of ABRT. Thus, if you send ABRT to yourself in a program which
// uses ExceptionHandler, you need to use tgkill to direct it to the current
// thread.
//
// The signal flow looks like this:
//
// SignalHandler (uses a global stack of ExceptionHandler objects to find
// | one to handle the signal. If the first rejects it, try
// | the second etc...)
// V
// HandleSignal ----------------------------| (clones a new process which
// | | shares an address space with
// (wait for cloned | the crashed process. This
// process) | allows us to ptrace the crashed
// | | process)
// V V
// (set signal handler to ThreadEntry (static function to bounce
// SIG_DFL and rethrow, | back into the object)
// killing the crashed |
// process) V
// DoDump (writes minidump)
// |
// V
// sys_exit
//
// This code is a little fragmented. Different functions of the ExceptionHandler
// class run in a number of different contexts. Some of them run in a normal
// context and are easy to code, others run in a compromised context and the
// restrictions at the top of minidump_writer.cc apply: no libc and use the
// alternative malloc. Each function should have comment above it detailing the
// context which it runs in.
#include "breakpad/linux/exception_handler.h"
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>
#include <signal.h>
#include <sys/signal.h>
#include <sys/ucontext.h>
#include <sys/user.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <sched.h>
#include "breakpad/linux/linux_syscall_support.h"
#include "breakpad/linux/memory.h"
#include "breakpad/linux/minidump_writer.h"
#include "common/linux/guid_creator.h"
// A wrapper for the tgkill syscall: send a signal to a specific thread.
static int tgkill(pid_t tgid, pid_t tid, int sig) {
syscall(__NR_tgkill, tgid, tid, sig);
}
namespace google_breakpad {
// The list of signals which we consider to be crashes. The default action for
// all these signals must be Core (see man 7 signal) because we rethrow the
// signal after handling it and expect that it'll be fatal.
static const int kExceptionSignals[] = {
SIGSEGV, SIGABRT, SIGFPE, SIGILL, SIGBUS, -1
};
// We can stack multiple exception handlers. In that case, this is the global
// which holds the stack.
std::vector<ExceptionHandler*>* ExceptionHandler::handler_stack_ = NULL;
unsigned ExceptionHandler::handler_stack_index_ = 0;
pthread_mutex_t ExceptionHandler::handler_stack_mutex_ =
PTHREAD_MUTEX_INITIALIZER;
// Runs before crashing: normal context.
ExceptionHandler::ExceptionHandler(const std::string &dump_path,
FilterCallback filter,
MinidumpCallback callback,
void *callback_context,
bool install_handler)
: filter_(filter),
callback_(callback),
callback_context_(callback_context),
dump_path_(),
handler_installed_(install_handler),
crash_handler_(NULL) {
set_dump_path(dump_path);
if (install_handler) {
InstallHandlers();
pthread_mutex_lock(&handler_stack_mutex_);
if (handler_stack_ == NULL)
handler_stack_ = new std::vector<ExceptionHandler *>;
handler_stack_->push_back(this);
pthread_mutex_unlock(&handler_stack_mutex_);
}
}
// Runs before crashing: normal context.
ExceptionHandler::~ExceptionHandler() {
UninstallHandlers();
}
// Runs before crashing: normal context.
bool ExceptionHandler::InstallHandlers() {
// We run the signal handlers on an alternative stack because we might have
// crashed because of a stack overflow.
// We use this value rather than SIGSTKSZ because we would end up overrunning
// such a small stack.
static const unsigned kSigStackSize = 8192;
signal_stack = malloc(kSigStackSize);
stack_t stack;
memset(&stack, 0, sizeof(stack));
stack.ss_sp = signal_stack;
stack.ss_size = kSigStackSize;
if (sigaltstack(&stack, NULL) == -1)
return false;
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sigemptyset(&sa.sa_mask);
// mask all exception signals when we're handling one of them.
for (unsigned i = 0; kExceptionSignals[i] != -1; ++i)
sigaddset(&sa.sa_mask, kExceptionSignals[i]);
sa.sa_sigaction = SignalHandler;
sa.sa_flags = SA_ONSTACK | SA_SIGINFO;
for (unsigned i = 0; kExceptionSignals[i] != -1; ++i) {
struct sigaction* old = new struct sigaction;
if (sigaction(kExceptionSignals[i], &sa, old) == -1)
return false;
old_handlers_.push_back(std::make_pair(kExceptionSignals[i], old));
}
}
// Runs before crashing: normal context.
void ExceptionHandler::UninstallHandlers() {
for (unsigned i = 0; i < old_handlers_.size(); ++i) {
struct sigaction *action =
reinterpret_cast<struct sigaction*>(old_handlers_[i].second);
sigaction(old_handlers_[i].first, action, NULL);
delete action;
}
old_handlers_.clear();
}
// Runs before crashing: normal context.
void ExceptionHandler::UpdateNextID() {
GUID guid;
char guid_str[kGUIDStringLength + 1];
if (CreateGUID(&guid) && GUIDToString(&guid, guid_str, sizeof(guid_str))) {
next_minidump_id_ = guid_str;
next_minidump_id_c_ = next_minidump_id_.c_str();
char minidump_path[PATH_MAX];
snprintf(minidump_path, sizeof(minidump_path), "%s/%s.dmp",
dump_path_c_,
guid_str);
next_minidump_path_ = minidump_path;
next_minidump_path_c_ = next_minidump_path_.c_str();
}
}
// This function runs in a compromised context: see the top of the file.
// Runs on the crashing thread.
// static
void ExceptionHandler::SignalHandler(int sig, siginfo_t* info, void* uc) {
// All the exception signals are blocked at this point.
pthread_mutex_lock(&handler_stack_mutex_);
if (!handler_stack_->size()) {
pthread_mutex_unlock(&handler_stack_mutex_);
return;
}
for (int i = handler_stack_->size() - 1; i >= 0; --i) {
if ((*handler_stack_)[i]->HandleSignal(sig, info, uc)) {
// successfully handled: We are in an invalid state since an exception
// signal has been delivered. We don't call the exit handlers because
// they could end up corrupting on-disk state.
break;
}
}
pthread_mutex_unlock(&handler_stack_mutex_);
// Terminate ourselves with the same signal so that our parent knows that we
// crashed. The default action for all the signals which we catch is Core, so
// this is the end of us.
signal(sig, SIG_DFL);
tgkill(getpid(), sys_gettid(), sig);
// not reached.
}
struct ThreadArgument {
pid_t pid; // the crashing process
ExceptionHandler* handler;
const void* context; // a CrashContext structure
size_t context_size;
};
// This is the entry function for the cloned process. We are in a compromised
// context here: see the top of the file.
// static
int ExceptionHandler::ThreadEntry(void *arg) {
const ThreadArgument *thread_arg = reinterpret_cast<ThreadArgument*>(arg);
return thread_arg->handler->DoDump(thread_arg->pid, thread_arg->context,
thread_arg->context_size) == false;
}
// This function runs in a compromised context: see the top of the file.
// Runs on the crashing thread.
bool ExceptionHandler::HandleSignal(int sig, siginfo_t* info, void* uc) {
if (filter_ && !filter_(callback_context_))
return false;
CrashContext context;
memcpy(&context.siginfo, info, sizeof(siginfo_t));
memcpy(&context.context, uc, sizeof(struct ucontext));
context.tid = sys_gettid();
if (crash_handler_ && crash_handler_(&context, sizeof(context),
callback_context_))
return true;
PageAllocator allocator;
void* const stack = allocator.Alloc(8000);
ThreadArgument thread_arg;
thread_arg.handler = this;
thread_arg.pid = getpid();
thread_arg.context = &context;
thread_arg.context_size = sizeof(context);
const pid_t child = sys_clone(
ThreadEntry, stack, CLONE_FILES | CLONE_FS | CLONE_UNTRACED,
&thread_arg, NULL, NULL, NULL);
int r, status;
do {
r = sys_waitpid(child, &status, __WALL);
} while (r == -1 && errno == EINTR);
if (r == -1) {
static const char msg[] = "ExceptionHandler::HandleSignal: waitpid failed:";
sys_write(2, msg, sizeof(msg) - 1);
sys_write(2, strerror(errno), strlen(strerror(errno)));
sys_write(2, "\n", 1);
}
bool success = r != -1 && WIFEXITED(status) && WEXITSTATUS(status) == 0;
if (callback_)
success = callback_(dump_path_c_, next_minidump_id_c_,
callback_context_, success);
return success;
}
// This function runs in a compromised context: see the top of the file.
// Runs on the cloned process.
bool ExceptionHandler::DoDump(pid_t crashing_process, const void* context,
size_t context_size) {
return google_breakpad::WriteMinidump(
next_minidump_path_c_, crashing_process, context, context_size);
}
} // namespace google_breakpad
<commit_msg>Fix a missing include in exception_handler.cc, fix compilation on Jaunty. Review URL: http://codereview.chromium.org/113774<commit_after>// Copyright (c) 2009, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// The ExceptionHandler object installs signal handlers for a number of
// signals. We rely on the signal handler running on the thread which crashed
// in order to identify it. This is true of the synchronous signals (SEGV etc),
// but not true of ABRT. Thus, if you send ABRT to yourself in a program which
// uses ExceptionHandler, you need to use tgkill to direct it to the current
// thread.
//
// The signal flow looks like this:
//
// SignalHandler (uses a global stack of ExceptionHandler objects to find
// | one to handle the signal. If the first rejects it, try
// | the second etc...)
// V
// HandleSignal ----------------------------| (clones a new process which
// | | shares an address space with
// (wait for cloned | the crashed process. This
// process) | allows us to ptrace the crashed
// | | process)
// V V
// (set signal handler to ThreadEntry (static function to bounce
// SIG_DFL and rethrow, | back into the object)
// killing the crashed |
// process) V
// DoDump (writes minidump)
// |
// V
// sys_exit
//
// This code is a little fragmented. Different functions of the ExceptionHandler
// class run in a number of different contexts. Some of them run in a normal
// context and are easy to code, others run in a compromised context and the
// restrictions at the top of minidump_writer.cc apply: no libc and use the
// alternative malloc. Each function should have comment above it detailing the
// context which it runs in.
#include "breakpad/linux/exception_handler.h"
#include <errno.h>
#include <fcntl.h>
#include <linux/limits.h>
#include <sched.h>
#include <signal.h>
#include <sys/mman.h>
#include <sys/signal.h>
#include <sys/syscall.h>
#include <sys/ucontext.h>
#include <sys/user.h>
#include <sys/wait.h>
#include <unistd.h>
#include "breakpad/linux/linux_syscall_support.h"
#include "breakpad/linux/memory.h"
#include "breakpad/linux/minidump_writer.h"
#include "common/linux/guid_creator.h"
// A wrapper for the tgkill syscall: send a signal to a specific thread.
static int tgkill(pid_t tgid, pid_t tid, int sig) {
syscall(__NR_tgkill, tgid, tid, sig);
}
namespace google_breakpad {
// The list of signals which we consider to be crashes. The default action for
// all these signals must be Core (see man 7 signal) because we rethrow the
// signal after handling it and expect that it'll be fatal.
static const int kExceptionSignals[] = {
SIGSEGV, SIGABRT, SIGFPE, SIGILL, SIGBUS, -1
};
// We can stack multiple exception handlers. In that case, this is the global
// which holds the stack.
std::vector<ExceptionHandler*>* ExceptionHandler::handler_stack_ = NULL;
unsigned ExceptionHandler::handler_stack_index_ = 0;
pthread_mutex_t ExceptionHandler::handler_stack_mutex_ =
PTHREAD_MUTEX_INITIALIZER;
// Runs before crashing: normal context.
ExceptionHandler::ExceptionHandler(const std::string &dump_path,
FilterCallback filter,
MinidumpCallback callback,
void *callback_context,
bool install_handler)
: filter_(filter),
callback_(callback),
callback_context_(callback_context),
dump_path_(),
handler_installed_(install_handler),
crash_handler_(NULL) {
set_dump_path(dump_path);
if (install_handler) {
InstallHandlers();
pthread_mutex_lock(&handler_stack_mutex_);
if (handler_stack_ == NULL)
handler_stack_ = new std::vector<ExceptionHandler *>;
handler_stack_->push_back(this);
pthread_mutex_unlock(&handler_stack_mutex_);
}
}
// Runs before crashing: normal context.
ExceptionHandler::~ExceptionHandler() {
UninstallHandlers();
}
// Runs before crashing: normal context.
bool ExceptionHandler::InstallHandlers() {
// We run the signal handlers on an alternative stack because we might have
// crashed because of a stack overflow.
// We use this value rather than SIGSTKSZ because we would end up overrunning
// such a small stack.
static const unsigned kSigStackSize = 8192;
signal_stack = malloc(kSigStackSize);
stack_t stack;
memset(&stack, 0, sizeof(stack));
stack.ss_sp = signal_stack;
stack.ss_size = kSigStackSize;
if (sigaltstack(&stack, NULL) == -1)
return false;
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sigemptyset(&sa.sa_mask);
// mask all exception signals when we're handling one of them.
for (unsigned i = 0; kExceptionSignals[i] != -1; ++i)
sigaddset(&sa.sa_mask, kExceptionSignals[i]);
sa.sa_sigaction = SignalHandler;
sa.sa_flags = SA_ONSTACK | SA_SIGINFO;
for (unsigned i = 0; kExceptionSignals[i] != -1; ++i) {
struct sigaction* old = new struct sigaction;
if (sigaction(kExceptionSignals[i], &sa, old) == -1)
return false;
old_handlers_.push_back(std::make_pair(kExceptionSignals[i], old));
}
}
// Runs before crashing: normal context.
void ExceptionHandler::UninstallHandlers() {
for (unsigned i = 0; i < old_handlers_.size(); ++i) {
struct sigaction *action =
reinterpret_cast<struct sigaction*>(old_handlers_[i].second);
sigaction(old_handlers_[i].first, action, NULL);
delete action;
}
old_handlers_.clear();
}
// Runs before crashing: normal context.
void ExceptionHandler::UpdateNextID() {
GUID guid;
char guid_str[kGUIDStringLength + 1];
if (CreateGUID(&guid) && GUIDToString(&guid, guid_str, sizeof(guid_str))) {
next_minidump_id_ = guid_str;
next_minidump_id_c_ = next_minidump_id_.c_str();
char minidump_path[PATH_MAX];
snprintf(minidump_path, sizeof(minidump_path), "%s/%s.dmp",
dump_path_c_,
guid_str);
next_minidump_path_ = minidump_path;
next_minidump_path_c_ = next_minidump_path_.c_str();
}
}
// This function runs in a compromised context: see the top of the file.
// Runs on the crashing thread.
// static
void ExceptionHandler::SignalHandler(int sig, siginfo_t* info, void* uc) {
// All the exception signals are blocked at this point.
pthread_mutex_lock(&handler_stack_mutex_);
if (!handler_stack_->size()) {
pthread_mutex_unlock(&handler_stack_mutex_);
return;
}
for (int i = handler_stack_->size() - 1; i >= 0; --i) {
if ((*handler_stack_)[i]->HandleSignal(sig, info, uc)) {
// successfully handled: We are in an invalid state since an exception
// signal has been delivered. We don't call the exit handlers because
// they could end up corrupting on-disk state.
break;
}
}
pthread_mutex_unlock(&handler_stack_mutex_);
// Terminate ourselves with the same signal so that our parent knows that we
// crashed. The default action for all the signals which we catch is Core, so
// this is the end of us.
signal(sig, SIG_DFL);
tgkill(getpid(), sys_gettid(), sig);
// not reached.
}
struct ThreadArgument {
pid_t pid; // the crashing process
ExceptionHandler* handler;
const void* context; // a CrashContext structure
size_t context_size;
};
// This is the entry function for the cloned process. We are in a compromised
// context here: see the top of the file.
// static
int ExceptionHandler::ThreadEntry(void *arg) {
const ThreadArgument *thread_arg = reinterpret_cast<ThreadArgument*>(arg);
return thread_arg->handler->DoDump(thread_arg->pid, thread_arg->context,
thread_arg->context_size) == false;
}
// This function runs in a compromised context: see the top of the file.
// Runs on the crashing thread.
bool ExceptionHandler::HandleSignal(int sig, siginfo_t* info, void* uc) {
if (filter_ && !filter_(callback_context_))
return false;
CrashContext context;
memcpy(&context.siginfo, info, sizeof(siginfo_t));
memcpy(&context.context, uc, sizeof(struct ucontext));
context.tid = sys_gettid();
if (crash_handler_ && crash_handler_(&context, sizeof(context),
callback_context_))
return true;
PageAllocator allocator;
void* const stack = allocator.Alloc(8000);
ThreadArgument thread_arg;
thread_arg.handler = this;
thread_arg.pid = getpid();
thread_arg.context = &context;
thread_arg.context_size = sizeof(context);
const pid_t child = sys_clone(
ThreadEntry, stack, CLONE_FILES | CLONE_FS | CLONE_UNTRACED,
&thread_arg, NULL, NULL, NULL);
int r, status;
do {
r = sys_waitpid(child, &status, __WALL);
} while (r == -1 && errno == EINTR);
if (r == -1) {
static const char msg[] = "ExceptionHandler::HandleSignal: waitpid failed:";
sys_write(2, msg, sizeof(msg) - 1);
sys_write(2, strerror(errno), strlen(strerror(errno)));
sys_write(2, "\n", 1);
}
bool success = r != -1 && WIFEXITED(status) && WEXITSTATUS(status) == 0;
if (callback_)
success = callback_(dump_path_c_, next_minidump_id_c_,
callback_context_, success);
return success;
}
// This function runs in a compromised context: see the top of the file.
// Runs on the cloned process.
bool ExceptionHandler::DoDump(pid_t crashing_process, const void* context,
size_t context_size) {
return google_breakpad::WriteMinidump(
next_minidump_path_c_, crashing_process, context, context_size);
}
} // namespace google_breakpad
<|endoftext|>
|
<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium 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.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "BhBase.hpp"
#include "util.hpp"
#include <ostream>
#include <vector>
namespace bhxx {
template <typename T>
class BhArray {
public:
// The data type of each array element
typedef T scalar_type;
// The array offset (from the start of the base in number of elements)
size_t offset;
// The array shape (size of each dimension in number of elements)
Shape shape;
// The array stride (the absolute stride of each dimension in number of elements)
Stride stride;
// Pointer to the base of this array
std::shared_ptr<BhBase> base;
// Create a new view that points to a new base
BhArray(Shape shape, Stride stride, const size_t offset = 0)
: offset(offset),
shape(std::move(shape)),
stride(std::move(stride)),
base(new BhBase(shape.prod()), BhBaseDeleter{}) {
base->set_type<T>();
}
// Create a new view that points to a new base (contiguous stride, row-major)
BhArray(Shape shape, const size_t offset = 0)
: BhArray(shape, contiguous_stride(shape), offset) {}
// Create a view that points to the given base
BhArray(std::shared_ptr<BhBase> base, Shape shape, Stride stride,
const size_t offset = 0)
: offset(offset),
shape(std::move(shape)),
stride(std::move(stride)),
base(std::move(base)) {}
// Create a view that points to the given base (contiguous stride, row-major)
BhArray(std::shared_ptr<BhBase> base, Shape shape, const size_t offset = 0)
: BhArray(std::move(base), shape, contiguous_stride(shape), offset) {}
// Pretty printing the content of the array
// TODO: for now it always print the flatten array
void pprint(std::ostream& os) const;
//@{
/** Obtain the data pointer of the base array, not taking
* ownership of any kind.
*
* \note This pointer might be a nullptr if the data in
* the base is not yet initialised
*
* \note You can always force initialisation using
* ```
* sync(array);
* Runtime::instance().flush();
* ```
* after which ``data()`` should not be nullptr.
*/
const T* data() const { return static_cast<T*>(base->data); }
T* data() { return static_cast<T*>(base->data); }
//@}
};
template <typename T>
std::ostream& operator<<(std::ostream& os, const BhArray<T>& ary) {
ary.pprint(os);
return os;
}
} // namespace bhxx
<commit_msg>Don't move stuff we still need<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium 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.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "BhBase.hpp"
#include "util.hpp"
#include <ostream>
#include <vector>
namespace bhxx {
template <typename T>
class BhArray {
public:
// The data type of each array element
typedef T scalar_type;
// The array offset (from the start of the base in number of elements)
size_t offset;
// The array shape (size of each dimension in number of elements)
Shape shape;
// The array stride (the absolute stride of each dimension in number of elements)
Stride stride;
// Pointer to the base of this array
std::shared_ptr<BhBase> base;
// Create a new view that points to a new base
BhArray(Shape shape, Stride stride, const size_t offset = 0)
: offset(offset),
shape(shape),
stride(std::move(stride)),
base(new BhBase(shape.prod()), BhBaseDeleter{}) {
base->set_type<T>();
}
// Create a new view that points to a new base (contiguous stride, row-major)
BhArray(Shape shape, const size_t offset = 0)
: BhArray(shape, contiguous_stride(shape), offset) {}
// Create a view that points to the given base
BhArray(std::shared_ptr<BhBase> base, Shape shape, Stride stride,
const size_t offset = 0)
: offset(offset),
shape(std::move(shape)),
stride(std::move(stride)),
base(std::move(base)) {}
// Create a view that points to the given base (contiguous stride, row-major)
BhArray(std::shared_ptr<BhBase> base, Shape shape, const size_t offset = 0)
: BhArray(std::move(base), shape, contiguous_stride(shape), offset) {}
// Pretty printing the content of the array
// TODO: for now it always print the flatten array
void pprint(std::ostream& os) const;
//@{
/** Obtain the data pointer of the base array, not taking
* ownership of any kind.
*
* \note This pointer might be a nullptr if the data in
* the base is not yet initialised
*
* \note You can always force initialisation using
* ```
* sync(array);
* Runtime::instance().flush();
* ```
* after which ``data()`` should not be nullptr.
*/
const T* data() const { return static_cast<T*>(base->data); }
T* data() { return static_cast<T*>(base->data); }
//@}
};
template <typename T>
std::ostream& operator<<(std::ostream& os, const BhArray<T>& ary) {
ary.pprint(os);
return os;
}
} // namespace bhxx
<|endoftext|>
|
<commit_before>#include <v8.h>
#include "js_macros.h"
#ifdef windows
# include <my_global.h>
#endif
#include <mysql.h>
#include <stdlib.h>
#include <string>
v8::Persistent<v8::FunctionTemplate> rest;
JS_METHOD(_mysql) {
if (args.This()->InternalFieldCount() == 0) {
return JS_EXCEPTION("Invalid call format. Use 'new MySQL()'");
}
SAVE_VALUE(0, JS_BOOL(false));
return args.This();
}
JS_METHOD(_connect) {
if (args.Length() < 4) {
return JS_EXCEPTION("Invalid call format. Use 'mysql.connect(host, user, pass, db)'");
}
MYSQL *conn;
v8::String::Utf8Value host(args[0]);
v8::String::Utf8Value user(args[1]);
v8::String::Utf8Value pass(args[2]);
v8::String::Utf8Value db(args[3]);
conn = mysql_init(NULL);
if (!mysql_real_connect(conn, *host, *user, *pass, *db, 0, NULL, 0)) {
return JS_BOOL(false);
} else {
mysql_query(conn, "SET NAMES 'utf8'");
SAVE_PTR(0, conn);
return args.This();
}
}
JS_METHOD(_query) {
v8::Handle<v8::Value> c = LOAD_VALUE(0);
if (c->IsFalse()) {
return JS_EXCEPTION("No connection established");
}
if (args.Length() < 1) {
return JS_EXCEPTION("No query specified");
}
v8::String::Utf8Value q(args[0]);
int qc = args.This()->Get(JS_STR("queryCount"))->ToInteger()->Int32Value();
args.This()->Set(JS_STR("queryCount"), JS_INT(qc+1));
MYSQL * conn = LOAD_PTR(0, MYSQL *);
MYSQL_RES *res;
int code = mysql_real_query(conn, *q, q.length());
if (code != 0) { return JS_BOOL(false); }
res = mysql_store_result(conn);
if (res) {
v8::Handle<v8::Value> resargs[] = { v8::External::New((void *) res) };
return rest->GetFunction()->NewInstance(1, resargs);
} else {
if (mysql_field_count(conn)) {
return JS_BOOL(false);
} else {
return JS_BOOL(true);
}
}
}
JS_METHOD(_error) {
v8::Handle<v8::Value> c = LOAD_VALUE(0);
if (c->IsFalse()) {
return JS_EXCEPTION("No connection established");
}
MYSQL * conn = LOAD_PTR(0, MYSQL *);
return JS_STR(mysql_error(conn));
}
JS_METHOD(_errno) {
v8::Handle<v8::Value> c = LOAD_VALUE(0);
if (c->IsFalse()) {
return JS_EXCEPTION("No connection established");
}
MYSQL * conn = LOAD_PTR(0, MYSQL *);
return JS_INT(mysql_errno(conn));
}
JS_METHOD(_affectedrows) {
v8::Handle<v8::Value> c = LOAD_VALUE(0);
if (c->IsFalse()) {
return JS_EXCEPTION("No connection established");
}
MYSQL * conn = LOAD_PTR(0, MYSQL *)
return JS_INT(mysql_affected_rows(conn));
}
JS_METHOD(_insertid) {
v8::Handle<v8::Value> c = LOAD_VALUE(0);
if (c->IsFalse()) {
return JS_EXCEPTION("No connection established");
}
MYSQL * conn = LOAD_PTR(0, MYSQL *);
return JS_INT(mysql_insert_id(conn));
}
JS_METHOD(_escape) {
v8::Handle<v8::Value> c = LOAD_VALUE(0);
if (c->IsFalse()) {
return JS_EXCEPTION("No connection established");
}
if (args.Length() < 1) {
return JS_EXCEPTION("Nothing to escape");
}
v8::String::Utf8Value str(args[0]);
int len = args[0]->ToString()->Utf8Length();
char * result = new char[2*len + 1];
MYSQL * conn = LOAD_PTR(0, MYSQL *);
int length = mysql_real_escape_string(conn, result, *str, len);
v8::Handle<v8::Value> output = JS_STR(result, length);
delete[] result;
return output;
}
JS_METHOD(_qualify) {
if (args.Length() < 1) {
return JS_EXCEPTION("Nothing to qualify");
}
v8::String::Utf8Value str(args[0]);
std::string result = "`";
result += *str;
result += "`";
v8::Handle<v8::Value> output = JS_STR(result.c_str());
return output;
}
JS_METHOD(_result) {
SAVE_VALUE(0, args[0]);
return args.This();
}
JS_METHOD(_numrows) {
MYSQL_RES * res = LOAD_PTR(0, MYSQL_RES *);
return JS_INT(mysql_num_rows(res));
}
JS_METHOD(_numfields) {
MYSQL_RES * res = LOAD_PTR(0, MYSQL_RES *);
return JS_INT(mysql_num_fields(res));
}
JS_METHOD(_fetchnames) {
MYSQL_RES * res = LOAD_PTR(0, MYSQL_RES *);
int cnt = mysql_num_fields(res);
MYSQL_FIELD * fields = mysql_fetch_fields(res);
v8::Handle<v8::Array> result = v8::Array::New(cnt);
for(int i = 0; i < cnt; i++) {
result->Set(JS_INT(i), JS_STR(fields[i].name));
}
return result;
}
JS_METHOD(_fetcharrays) {
MYSQL_RES * res = LOAD_PTR(0, MYSQL_RES *);
mysql_data_seek(res, 0);
int x = mysql_num_fields(res);
int y = mysql_num_rows(res);
MYSQL_ROW row;
v8::Handle<v8::Array> result = v8::Array::New(y);
for (int i = 0; i < y; i++) {
row = mysql_fetch_row(res);
v8::Handle<v8::Array> item = v8::Array::New(x);
result->Set(JS_INT(i), item);
for (int j=0; j<x; j++) {
if (row[j] == NULL) {
item->Set(JS_INT(j), v8::Null());
} else {
item->Set(JS_INT(j), JS_STR(row[j]));
}
}
}
return result;
}
JS_METHOD(_fetchobjects) {
MYSQL_RES * res = LOAD_PTR(0, MYSQL_RES *);
mysql_data_seek(res, 0);
int x = mysql_num_fields(res);
int y = mysql_num_rows(res);
MYSQL_FIELD * fields = mysql_fetch_fields(res);
MYSQL_ROW row;
v8::Handle<v8::Array> result = v8::Array::New(y);
for (int i = 0; i < y; i++) {
row = mysql_fetch_row(res);
v8::Handle<v8::Object> item = v8::Object::New();
result->Set(JS_INT(i), item);
for (int j=0; j<x; j++) {
if (row[j] == NULL) {
item->Set(JS_STR(fields[j].name), v8::Null());
} else {
item->Set(JS_STR(fields[j].name), JS_STR(row[j]));
}
}
}
return result;
}
SHARED_INIT() {
v8::HandleScope handle_scope;
v8::Handle<v8::FunctionTemplate> ft = v8::FunctionTemplate::New(_mysql);
ft->SetClassName(JS_STR("MySQL"));
v8::Handle<v8::ObjectTemplate> ot = ft->InstanceTemplate();
ot->SetInternalFieldCount(1); /* connection */
ot->Set(JS_STR("queryCount"), JS_INT(0));
v8::Handle<v8::ObjectTemplate> pt = ft->PrototypeTemplate();
pt->Set(JS_STR("connect"), v8::FunctionTemplate::New(_connect));
pt->Set(JS_STR("query"), v8::FunctionTemplate::New(_query));
pt->Set(JS_STR("error"), v8::FunctionTemplate::New(_error));
pt->Set(JS_STR("errno"), v8::FunctionTemplate::New(_errno));
pt->Set(JS_STR("affectedRows"), v8::FunctionTemplate::New(_affectedrows));
pt->Set(JS_STR("escape"), v8::FunctionTemplate::New(_escape));
pt->Set(JS_STR("qualify"), v8::FunctionTemplate::New(_qualify));
pt->Set(JS_STR("insertId"), v8::FunctionTemplate::New(_insertid));
rest = v8::Persistent<v8::FunctionTemplate>::New(v8::FunctionTemplate::New(_result));
rest->SetClassName(JS_STR("Result"));
v8::Handle<v8::ObjectTemplate> resinst = rest->InstanceTemplate();
resinst->SetInternalFieldCount(1);
v8::Handle<v8::ObjectTemplate> resproto = rest->PrototypeTemplate();
resproto->Set(JS_STR("numRows"), v8::FunctionTemplate::New(_numrows));
resproto->Set(JS_STR("numFields"), v8::FunctionTemplate::New(_numfields));
resproto->Set(JS_STR("fetchNames"), v8::FunctionTemplate::New(_fetchnames));
resproto->Set(JS_STR("fetchArrays"), v8::FunctionTemplate::New(_fetcharrays));
resproto->Set(JS_STR("fetchObjects"), v8::FunctionTemplate::New(_fetchobjects));
exports->Set(JS_STR("MySQL"), ft->GetFunction());
}
<commit_msg>MySQL().close()<commit_after>#include <v8.h>
#include "js_macros.h"
#ifdef windows
# include <my_global.h>
#endif
#include <mysql.h>
#include <stdlib.h>
#include <string>
v8::Persistent<v8::FunctionTemplate> rest;
JS_METHOD(_mysql) {
if (args.This()->InternalFieldCount() == 0) {
return JS_EXCEPTION("Invalid call format. Use 'new MySQL()'");
}
SAVE_VALUE(0, JS_BOOL(false));
return args.This();
}
JS_METHOD(_close) {
MYSQL * conn = LOAD_PTR(0, MYSQL *);
mysql_close(conn);
SAVE_VALUE(0, JS_BOOL(false));
return args.This();
}
JS_METHOD(_connect) {
if (args.Length() < 4) {
return JS_EXCEPTION("Invalid call format. Use 'mysql.connect(host, user, pass, db)'");
}
MYSQL *conn;
v8::String::Utf8Value host(args[0]);
v8::String::Utf8Value user(args[1]);
v8::String::Utf8Value pass(args[2]);
v8::String::Utf8Value db(args[3]);
conn = mysql_init(NULL);
if (!mysql_real_connect(conn, *host, *user, *pass, *db, 0, NULL, 0)) {
return JS_BOOL(false);
} else {
mysql_query(conn, "SET NAMES 'utf8'");
SAVE_PTR(0, conn);
return args.This();
}
}
JS_METHOD(_query) {
v8::Handle<v8::Value> c = LOAD_VALUE(0);
if (c->IsFalse()) {
return JS_EXCEPTION("No connection established");
}
if (args.Length() < 1) {
return JS_EXCEPTION("No query specified");
}
v8::String::Utf8Value q(args[0]);
int qc = args.This()->Get(JS_STR("queryCount"))->ToInteger()->Int32Value();
args.This()->Set(JS_STR("queryCount"), JS_INT(qc+1));
MYSQL * conn = LOAD_PTR(0, MYSQL *);
MYSQL_RES *res;
int code = mysql_real_query(conn, *q, q.length());
if (code != 0) { return JS_BOOL(false); }
res = mysql_store_result(conn);
if (res) {
v8::Handle<v8::Value> resargs[] = { v8::External::New((void *) res) };
return rest->GetFunction()->NewInstance(1, resargs);
} else {
if (mysql_field_count(conn)) {
return JS_BOOL(false);
} else {
return JS_BOOL(true);
}
}
}
JS_METHOD(_error) {
v8::Handle<v8::Value> c = LOAD_VALUE(0);
if (c->IsFalse()) {
return JS_EXCEPTION("No connection established");
}
MYSQL * conn = LOAD_PTR(0, MYSQL *);
return JS_STR(mysql_error(conn));
}
JS_METHOD(_errno) {
v8::Handle<v8::Value> c = LOAD_VALUE(0);
if (c->IsFalse()) {
return JS_EXCEPTION("No connection established");
}
MYSQL * conn = LOAD_PTR(0, MYSQL *);
return JS_INT(mysql_errno(conn));
}
JS_METHOD(_affectedrows) {
v8::Handle<v8::Value> c = LOAD_VALUE(0);
if (c->IsFalse()) {
return JS_EXCEPTION("No connection established");
}
MYSQL * conn = LOAD_PTR(0, MYSQL *)
return JS_INT(mysql_affected_rows(conn));
}
JS_METHOD(_insertid) {
v8::Handle<v8::Value> c = LOAD_VALUE(0);
if (c->IsFalse()) {
return JS_EXCEPTION("No connection established");
}
MYSQL * conn = LOAD_PTR(0, MYSQL *);
return JS_INT(mysql_insert_id(conn));
}
JS_METHOD(_escape) {
v8::Handle<v8::Value> c = LOAD_VALUE(0);
if (c->IsFalse()) {
return JS_EXCEPTION("No connection established");
}
if (args.Length() < 1) {
return JS_EXCEPTION("Nothing to escape");
}
v8::String::Utf8Value str(args[0]);
int len = args[0]->ToString()->Utf8Length();
char * result = new char[2*len + 1];
MYSQL * conn = LOAD_PTR(0, MYSQL *);
int length = mysql_real_escape_string(conn, result, *str, len);
v8::Handle<v8::Value> output = JS_STR(result, length);
delete[] result;
return output;
}
JS_METHOD(_qualify) {
if (args.Length() < 1) {
return JS_EXCEPTION("Nothing to qualify");
}
v8::String::Utf8Value str(args[0]);
std::string result = "`";
result += *str;
result += "`";
v8::Handle<v8::Value> output = JS_STR(result.c_str());
return output;
}
JS_METHOD(_result) {
SAVE_VALUE(0, args[0]);
return args.This();
}
JS_METHOD(_numrows) {
MYSQL_RES * res = LOAD_PTR(0, MYSQL_RES *);
return JS_INT(mysql_num_rows(res));
}
JS_METHOD(_numfields) {
MYSQL_RES * res = LOAD_PTR(0, MYSQL_RES *);
return JS_INT(mysql_num_fields(res));
}
JS_METHOD(_fetchnames) {
MYSQL_RES * res = LOAD_PTR(0, MYSQL_RES *);
int cnt = mysql_num_fields(res);
MYSQL_FIELD * fields = mysql_fetch_fields(res);
v8::Handle<v8::Array> result = v8::Array::New(cnt);
for(int i = 0; i < cnt; i++) {
result->Set(JS_INT(i), JS_STR(fields[i].name));
}
return result;
}
JS_METHOD(_fetcharrays) {
MYSQL_RES * res = LOAD_PTR(0, MYSQL_RES *);
mysql_data_seek(res, 0);
int x = mysql_num_fields(res);
int y = mysql_num_rows(res);
MYSQL_ROW row;
v8::Handle<v8::Array> result = v8::Array::New(y);
for (int i = 0; i < y; i++) {
row = mysql_fetch_row(res);
v8::Handle<v8::Array> item = v8::Array::New(x);
result->Set(JS_INT(i), item);
for (int j=0; j<x; j++) {
if (row[j] == NULL) {
item->Set(JS_INT(j), v8::Null());
} else {
item->Set(JS_INT(j), JS_STR(row[j]));
}
}
}
return result;
}
JS_METHOD(_fetchobjects) {
MYSQL_RES * res = LOAD_PTR(0, MYSQL_RES *);
mysql_data_seek(res, 0);
int x = mysql_num_fields(res);
int y = mysql_num_rows(res);
MYSQL_FIELD * fields = mysql_fetch_fields(res);
MYSQL_ROW row;
v8::Handle<v8::Array> result = v8::Array::New(y);
for (int i = 0; i < y; i++) {
row = mysql_fetch_row(res);
v8::Handle<v8::Object> item = v8::Object::New();
result->Set(JS_INT(i), item);
for (int j=0; j<x; j++) {
if (row[j] == NULL) {
item->Set(JS_STR(fields[j].name), v8::Null());
} else {
item->Set(JS_STR(fields[j].name), JS_STR(row[j]));
}
}
}
return result;
}
SHARED_INIT() {
v8::HandleScope handle_scope;
v8::Handle<v8::FunctionTemplate> ft = v8::FunctionTemplate::New(_mysql);
ft->SetClassName(JS_STR("MySQL"));
v8::Handle<v8::ObjectTemplate> ot = ft->InstanceTemplate();
ot->SetInternalFieldCount(1); /* connection */
ot->Set(JS_STR("queryCount"), JS_INT(0));
v8::Handle<v8::ObjectTemplate> pt = ft->PrototypeTemplate();
pt->Set(JS_STR("connect"), v8::FunctionTemplate::New(_connect));
pt->Set(JS_STR("close"), v8::FunctionTemplate::New(_close));
pt->Set(JS_STR("query"), v8::FunctionTemplate::New(_query));
pt->Set(JS_STR("error"), v8::FunctionTemplate::New(_error));
pt->Set(JS_STR("errno"), v8::FunctionTemplate::New(_errno));
pt->Set(JS_STR("affectedRows"), v8::FunctionTemplate::New(_affectedrows));
pt->Set(JS_STR("escape"), v8::FunctionTemplate::New(_escape));
pt->Set(JS_STR("qualify"), v8::FunctionTemplate::New(_qualify));
pt->Set(JS_STR("insertId"), v8::FunctionTemplate::New(_insertid));
rest = v8::Persistent<v8::FunctionTemplate>::New(v8::FunctionTemplate::New(_result));
rest->SetClassName(JS_STR("Result"));
v8::Handle<v8::ObjectTemplate> resinst = rest->InstanceTemplate();
resinst->SetInternalFieldCount(1);
v8::Handle<v8::ObjectTemplate> resproto = rest->PrototypeTemplate();
resproto->Set(JS_STR("numRows"), v8::FunctionTemplate::New(_numrows));
resproto->Set(JS_STR("numFields"), v8::FunctionTemplate::New(_numfields));
resproto->Set(JS_STR("fetchNames"), v8::FunctionTemplate::New(_fetchnames));
resproto->Set(JS_STR("fetchArrays"), v8::FunctionTemplate::New(_fetcharrays));
resproto->Set(JS_STR("fetchObjects"), v8::FunctionTemplate::New(_fetchobjects));
exports->Set(JS_STR("MySQL"), ft->GetFunction());
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <sstream>
#include <fstream>
#include <fcntl.h>
#include <sys/stat.h>
namespace patch {
template<typename T> std::string to_string(const T& n) {
std::ostringstream stm;
stm << n;
return stm.str();
}
}
using namespace std;
const string ZIP = "zip";
const string UNZIP = "unzip";
const string TEXTBELT_URL = "http://textbelt.com/text";
const int MIN_ARG_COUNT = 4;//2fzip -d pwd zipfile
string theAuthCode;
bool generateZip(char** zipCmd);
bool generateText(string authCode, string phoneNum, string filename);
void undoGenerateZip(string zipName);
void helpMenu() {
cout << "2Factor Zip (c) 2014 Kyle Koceski" << endl;
cout << "Usage:" << endl;
cout << " 2fzip -e password [zip_parameters] zipfilename.2fz filelist" << endl;
// zip -P code:password [zip_parameters] zipfilename.2fz filelist
cout << " 2fzip -d password [unzip_parameters] zipfilename.2fz" << endl;
// unzip -P code:password [unzip_parameters] zipfilename.2fz filelist
cout << "Available zip/unzip parameters: " << endl;
cout << " -r recurse into directories -j junk (don't record) directory names" << endl <<
" -0 store only -l convert LF to CR LF (-ll CR LF to LF)" << endl <<
" -1 compress faster -9 compress better" << endl <<
" -q quiet operation -v verbose operation/print version info" << endl <<
" -c add one-line comments -z add zipfile comment" << endl;
}
//helper methods: authCode, mallocCopy, getZipFilename, isEncryption, isDecryption
string authCode() {
//Create the random 2-factor authentication code
srand (time(NULL));
int rndm = rand() % 10000;
string rStr = patch::to_string(rndm);
while(rStr.size() < 4) {
rStr.insert(0,"0");
}
//cout << "authCode: " << rStr << endl;
return rStr;
}
//pass a char* (ie character array) by reference to modify it
void mallocCopy(char* &s1, string value) {
s1 = (char*)malloc(value.length()+1);
strcpy(s1, value.c_str());
}
bool isSuccess(char* jsonReply) {
string success = "\"success\": true";
if(strstr(jsonReply, success.c_str())) return true;
else return false;
}
string getZipFilename(int argc, char** argv) {
if(argc < 4) {
return 0;
}
int i;
for(i = 3;i<argc;i++) {
if(argv[i][0] != '-') break;
}
return string(argv[i]);
}
bool isEncryption(int argc, char** argv) {
if(argc < 2) return false;
return (strcmp(argv[1], "-e") == 0);
}
bool isDecryption(int argc, char** argv) {//note: not necessarily !isEncryption
if(argc < 2) return false;
return (strcmp(argv[1], "-d") == 0);
}
//parses arguments, generating appropriate (un)zip command
//generates authCode to be used for encryption, if necessary
//returns array of character arrays to be exec()d
char** parseArgs(int argc, char** argv) {
if(argc < 4) {
return 0;
}
bool isEncr = isEncryption(argc, argv);
bool isDecr = isDecryption(argc, argv);
if(!isEncr && !isDecr) {
return 0;
}
int cmdSize = argc+1;//1 extra for the NULL terminator
char** zipCmd = new char*[cmdSize];
zipCmd[cmdSize-1] = NULL;
char* cmdType = (char*)malloc(6);
if(isEncr) {
strcpy(cmdType, ZIP.c_str());
}
else if(isDecr) {
strcpy(cmdType, UNZIP.c_str());
}
zipCmd[0] = cmdType;//zip or unzip
mallocCopy(zipCmd[1], "-P");
string pwd;
if(isEncr) {
theAuthCode = authCode();
pwd = theAuthCode + ":" + patch::to_string(argv[2]);
}
else if(isDecr) {
string theAuthCode;
cout << "Enter 2Factor Authentication Code: " << endl << " ";
cin >> theAuthCode;
pwd = theAuthCode + ":" + patch::to_string(argv[2]);
}
if(pwd.empty()) return 0;
mallocCopy(zipCmd[2], pwd);//authCode:password
for(int i = 3; i<argc; i++) {
zipCmd[i] = argv[i];
}
return zipCmd;
}
//main:
//parses arguments for a proper (un)zip command, generating an authCode
//zips file
//if zip successful, generates text
//and, if text fails, reverts zip
int main(int argc, char** argv) {
char** zipCmd = parseArgs(argc, argv);
if(zipCmd == 0) {
helpMenu();
return 0;
}
bool noErrors = generateZip(zipCmd);
if(noErrors && isEncryption(argc, argv)) {
string phoneNum;
cout << "Enter recipient's (10-digit) phone number (form: xxxxxxxxxx): " << endl;
cin >> phoneNum;
noErrors = generateText(theAuthCode, phoneNum, getZipFilename(argc, argv));
if(!noErrors) {
undoGenerateZip(getZipFilename(argc, argv));
cout << "Error sending authorization code to recipient" << endl;
}
}
return 0;
}
//generates zip file
//return true if successful
bool generateZip(char** zipCmd) {
//cout << "Original PID: " << getpid() << endl;
int n, fd[2], status; char buf[100];
pipe(fd);//generate pipe for communicating between main and child/text process
pid_t pid = fork();//create child process
switch(pid) {
case -1: {//ERROR
cerr << " ERROR: (un)zip fork() failed" << endl;
exit(1);
}
case 0: {//CHILD
close(fd[0]);//close read end of pipe
//Redirect stdout-stderr to parent to test for success
dup2(fd[1], STDOUT_FILENO);
dup2(fd[1], STDERR_FILENO);
execvp(zipCmd[0], zipCmd);//execute program
cerr << " ERROR: (un)compressing zip" << endl;//exec doesn't return unless there's an error
exit(1);
}
default: {//PARENT
close(fd[1]);
//cout << "(un)zip process created; PID: " << pid << endl;
while(true) {
n = read(fd[0], buf, 100);//Read from pipe
if(n <= 0) break;
write(STDOUT_FILENO,buf,n);//Write to standard output
}
do {
waitpid(pid, &status, 0);//wait for process to complete
} while(!WIFEXITED(status) && !WIFSIGNALED(status));
//cout << "(un)zip process exit status: " << WEXITSTATUS(status) << endl;
break;
}
}
close(fd[0]);
close(fd[1]);
return status == 0;
}
//generates a TextBelt text message for the authCode to the phoneNum
//returns true if text successful
//returns false if text unsuccessful
bool generateText(string authCode, string phoneNum, string filename) {
string number = "number=" + phoneNum;
string message = "message=2Factor Auth Code for " + filename + ": " + authCode;
char** textCmd = new char*[10];
mallocCopy(textCmd[0], "curl");
mallocCopy(textCmd[1], "--silent");
mallocCopy(textCmd[2], "-X");
mallocCopy(textCmd[3], "POST");
mallocCopy(textCmd[4], TEXTBELT_URL);
mallocCopy(textCmd[5], "-d");
mallocCopy(textCmd[6], number);
mallocCopy(textCmd[7], "-d");
mallocCopy(textCmd[8], message);
textCmd[9] = NULL;
int n, fd[2]; char buf[100];
pipe(fd);//generate pipe for communicating between main and child/text process
pid_t pid = fork();//create child process
switch(pid) {
case -1: {//ERROR
cerr << " ERROR: text fork() failed" << endl;
exit(1);
}
case 0: {//CHILD
close(fd[0]);//close read end of pipe
//Redirect stdout-stderr to parent to test for success
dup2(fd[1], STDOUT_FILENO);
dup2(fd[1], STDERR_FILENO);
execvp(textCmd[0], textCmd);//execute program
cerr << " ERROR: text generation failed!" << endl;//exec doesn't return unless there's an error
exit(1);
}
default: {//PARENT
close(fd[1]);//close write end of pipe
//cout << "Text process created; PID: " << pid << endl;
int status;
dup2(fd[0], STDIN_FILENO);
n = read(fd[0], buf, 100);//Read from pipe
//write(STDOUT_FILENO,buf,n);//Write to standard output
do {
waitpid(pid, &status, 0);//wait for process to complete
} while(!WIFEXITED(status) && !WIFSIGNALED(status));
//cout << "\nText process exit status: " << WEXITSTATUS(status) << "\n";
break;
}
}
close(fd[0]);
close(fd[1]);
return isSuccess(buf);
}
//reverts creation of zip
void undoGenerateZip(string zipName) {
char** undoCmd = new char*[3];
mallocCopy(undoCmd[0], "rm");
mallocCopy(undoCmd[1], zipName);
undoCmd[2] = NULL;
pid_t pid = fork();//create child process
switch(pid) {
case -1: {//ERROR
cerr << " ERROR: undo zip fork() failed" << endl;
exit(1);
}
case 0: {//CHILD
execvp(undoCmd[0], undoCmd);//execute program
cerr << " ERROR: undo zip failed!" << endl;//exec doesn't return unless there's an error
exit(1);
}
default: {//PARENT
//cout << "Undo zip process created; PID: " << pid << endl;
int status;
do {
waitpid(pid, &status, 0);//wait for process to complete
} while(!WIFEXITED(status) && !WIFSIGNALED(status));
//cout << "Undo zip process exit status: " << WEXITSTATUS(status) << "\n";
break;
}
}
}<commit_msg>'Copyright' and additional commenting<commit_after>/*
* 2Factor Zip Copyright (c) 2014 Kyle Koceski
* A program for providing 2-Factor authentication to *.zip files via SMS
* (via TextBelt API: http://www.textbelt.com) at compression time.
*/
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <sstream>
#include <fstream>
#include <fcntl.h>
#include <sys/stat.h>
//Patches a C++11 to_string()
namespace patch {
template<typename T> std::string to_string(const T& n) {
std::ostringstream stm;
stm << n;
return stm.str();
}
}
using namespace std;
//CONSTANTS
const string ZIP = "zip";
const string UNZIP = "unzip";
const string TEXTBELT_URL = "http://textbelt.com/text";
const int MIN_ARG_COUNT = 4;//2fzip -d pwd zipfile
//the authentication code, generated is parseArgs and used for the zipCmd and textCmd
string theAuthCode;
//Methods for fork()ing the process to generate the zip, text, and revert the zip-generation transaction
bool generateZip(char** zipCmd);
bool generateText(string authCode, string phoneNum, string filename);
void undoGenerateZip(string zipName);
//Prints the proper usage of 2fzip when improper command arguments are provided
void helpMenu() {
cout << "2Factor Zip Copyright (c) 2014 Kyle Koceski" << endl;
cout << "Usage:" << endl;
cout << " 2fzip -e password [zip_parameters] zipfilename.2fz filelist" << endl;
// zip -P code:password [zip_parameters] zipfilename.2fz filelist
cout << " 2fzip -d password [unzip_parameters] zipfilename.2fz" << endl;
// unzip -P code:password [unzip_parameters] zipfilename.2fz filelist
cout << "Available zip/unzip parameters: " << endl;
cout << " -r recurse into directories -j junk (don't record) directory names" << endl <<
" -0 store only -l convert LF to CR LF (-ll CR LF to LF)" << endl <<
" -1 compress faster -9 compress better" << endl <<
" -q quiet operation -v verbose operation/print version info" << endl <<
" -c add one-line comments -z add zipfile comment" << endl;
}
//HELPER METHODS:
//authCode, mallocCopy, getZipFilename, isEncryption, isDecryption
//generates and returns a random 4-character numeric authentication code
string authCode() {
//Create the random 2-factor authentication code
srand (time(NULL));
int rndm = rand() % 10000;
string rStr = patch::to_string(rndm);
while(rStr.size() < 4) {
rStr.insert(0,"0");
}
//cout << "authCode: " << rStr << endl;
return rStr;
}
//pass a char* (ie character array) by reference to modify it
//(useful for allocating space and assigning string values to command parameter array items)
void mallocCopy(char* &s1, string value) {
s1 = (char*)malloc(value.length()+1);
strcpy(s1, value.c_str());
}
//determines success of TextBelt text via JSON reply analysis of success item
bool isSuccess(char* jsonReply) {
string success = "\"success\": true";
if(strstr(jsonReply, success.c_str())) return true;
else return false;
}
//parses the provided argument list for the name of the created zip file
//useful for texting the name of the file which an authCode unlocks
string getZipFilename(int argc, char** argv) {
if(argc < 4) {
return 0;
}
int i;
for(i = 3;i<argc;i++) {
if(argv[i][0] != '-') break;
}
return string(argv[i]);
}
//Determine whether to follow:
//encryption path (gen auth, gen zip, send text, (revert))
//OR
//decryption path (get auth, unzip file)
bool isEncryption(int argc, char** argv) {
if(argc < 2) return false;
return (strcmp(argv[1], "-e") == 0);
}
bool isDecryption(int argc, char** argv) {//note: not necessarily !isEncryption
if(argc < 2) return false;
return (strcmp(argv[1], "-d") == 0);
}
//parses arguments, generating appropriate (un)zip command
//generates authCode to be used for encryption, if necessary
//returns array of character arrays to be exec()d
char** parseArgs(int argc, char** argv) {
if(argc < 4) {
return 0;
}
bool isEncr = isEncryption(argc, argv);
bool isDecr = isDecryption(argc, argv);
if(!isEncr && !isDecr) {
return 0;
}
int cmdSize = argc+1;//1 extra for the NULL terminator
char** zipCmd = new char*[cmdSize];
zipCmd[cmdSize-1] = NULL;
char* cmdType = (char*)malloc(6);
if(isEncr) {
strcpy(cmdType, ZIP.c_str());
}
else if(isDecr) {
strcpy(cmdType, UNZIP.c_str());
}
zipCmd[0] = cmdType;//zip or unzip
mallocCopy(zipCmd[1], "-P");//password parameter identifier
string pwd;
if(isEncr) {
theAuthCode = authCode();
pwd = theAuthCode + ":" + patch::to_string(argv[2]);
}
else if(isDecr) {
string theAuthCode;
cout << "Enter 2Factor Authentication Code: " << endl << " ";
cin >> theAuthCode;
pwd = theAuthCode + ":" + patch::to_string(argv[2]);
}
if(pwd.empty()) return 0;
mallocCopy(zipCmd[2], pwd);//authCode:password
for(int i = 3; i<argc; i++) {
zipCmd[i] = argv[i];//addition parameters (includes "... zipName [list of files]")
}
return zipCmd;
}
// 1. parses arguments for a proper (un)zip command, generating (or retrieving) an authCode
// 2. (un)zips file
//[3.] if zip successful, generates text
//[4.] if text fails, reverts zip]
int main(int argc, char** argv) {
char** zipCmd = parseArgs(argc, argv);
if(zipCmd == 0) {
helpMenu();
return 0;
}
bool noErrors = generateZip(zipCmd);
if(noErrors && isEncryption(argc, argv)) {
string phoneNum;
cout << "Enter recipient's (10-digit) phone number (form: xxxxxxxxxx): " << endl;
cin >> phoneNum;
noErrors = generateText(theAuthCode, phoneNum, getZipFilename(argc, argv));
if(!noErrors) {
undoGenerateZip(getZipFilename(argc, argv));
cout << "Error sending authorization code to recipient" << endl;
}
}
return 0;
}
//generates zip file
//return true if successful
bool generateZip(char** zipCmd) {
//cout << "Original PID: " << getpid() << endl;
int n, fd[2], status; char buf[100];
pipe(fd);//generate pipe for communicating between main and child/text process
pid_t pid = fork();//create child process
switch(pid) {
case -1: {//ERROR
cerr << " ERROR: (un)zip fork() failed" << endl;
exit(1);
}
case 0: {//CHILD
close(fd[0]);//close read end of pipe
//Redirect stdout-stderr to parent to test for success
dup2(fd[1], STDOUT_FILENO);
dup2(fd[1], STDERR_FILENO);
execvp(zipCmd[0], zipCmd);//execute program
cerr << " ERROR: (un)compressing zip" << endl;//exec doesn't return unless there's an error
exit(1);
}
default: {//PARENT
close(fd[1]);
//cout << "(un)zip process created; PID: " << pid << endl;
while(true) {
n = read(fd[0], buf, 100);//Read from pipe
if(n <= 0) break;
write(STDOUT_FILENO,buf,n);//Write to standard output
}
do {
waitpid(pid, &status, 0);//wait for process to complete
} while(!WIFEXITED(status) && !WIFSIGNALED(status));
//cout << "(un)zip process exit status: " << WEXITSTATUS(status) << endl;
break;
}
}
close(fd[0]);
close(fd[1]);
return status == 0;
}
//generates a TextBelt text message for the authCode to the phoneNum
//returns true if text successful
//returns false if text unsuccessful
bool generateText(string authCode, string phoneNum, string filename) {
string number = "number=" + phoneNum;
string message = "message=2Factor Auth Code for " + filename + ": " + authCode;
char** textCmd = new char*[10];
mallocCopy(textCmd[0], "curl");
mallocCopy(textCmd[1], "--silent");
mallocCopy(textCmd[2], "-X");
mallocCopy(textCmd[3], "POST");
mallocCopy(textCmd[4], TEXTBELT_URL);
mallocCopy(textCmd[5], "-d");
mallocCopy(textCmd[6], number);
mallocCopy(textCmd[7], "-d");
mallocCopy(textCmd[8], message);
textCmd[9] = NULL;
int n, fd[2]; char buf[100];
pipe(fd);//generate pipe for communicating between main and child/text process
pid_t pid = fork();//create child process
switch(pid) {
case -1: {//ERROR
cerr << " ERROR: text fork() failed" << endl;
exit(1);
}
case 0: {//CHILD
close(fd[0]);//close read end of pipe
//Redirect stdout-stderr to parent to test for success
dup2(fd[1], STDOUT_FILENO);
dup2(fd[1], STDERR_FILENO);
execvp(textCmd[0], textCmd);//execute program
cerr << " ERROR: text generation failed!" << endl;//exec doesn't return unless there's an error
exit(1);
}
default: {//PARENT
close(fd[1]);//close write end of pipe
//cout << "Text process created; PID: " << pid << endl;
int status;
dup2(fd[0], STDIN_FILENO);
n = read(fd[0], buf, 100);//Read from pipe
//write(STDOUT_FILENO,buf,n);//Write to standard output
do {
waitpid(pid, &status, 0);//wait for process to complete
} while(!WIFEXITED(status) && !WIFSIGNALED(status));
//cout << "\nText process exit status: " << WEXITSTATUS(status) << "\n";
break;
}
}
close(fd[0]);
close(fd[1]);
return isSuccess(buf);
}
//reverts creation of zip
void undoGenerateZip(string zipName) {
char** undoCmd = new char*[3];
mallocCopy(undoCmd[0], "rm");
mallocCopy(undoCmd[1], zipName);
undoCmd[2] = NULL;
pid_t pid = fork();//create child process
switch(pid) {
case -1: {//ERROR
cerr << " ERROR: undo zip fork() failed" << endl;
exit(1);
}
case 0: {//CHILD
execvp(undoCmd[0], undoCmd);//execute program
cerr << " ERROR: undo zip failed!" << endl;//exec doesn't return unless there's an error
exit(1);
}
default: {//PARENT
//cout << "Undo zip process created; PID: " << pid << endl;
int status;
do {
waitpid(pid, &status, 0);//wait for process to complete
} while(!WIFEXITED(status) && !WIFSIGNALED(status));
//cout << "Undo zip process exit status: " << WEXITSTATUS(status) << "\n";
break;
}
}
}<|endoftext|>
|
<commit_before><commit_msg>Relaxed file size check for DMK images<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright 2015 Cloudius Systems
*/
#pragma once
#include "disk_types.hh"
#include "core/enum.hh"
#include "bytes.hh"
#include "gc_clock.hh"
#include "tombstone.hh"
#include "streaming_histogram.hh"
#include "estimated_histogram.hh"
#include "column_name_helper.hh"
#include "sstables/key.hh"
#include <vector>
#include <unordered_map>
#include <type_traits>
namespace sstables {
struct option {
disk_string<uint16_t> key;
disk_string<uint16_t> value;
template <typename Describer>
auto describe_type(Describer f) { return f(key, value); }
};
struct filter {
uint32_t hashes;
disk_array<uint32_t, uint64_t> buckets;
template <typename Describer>
auto describe_type(Describer f) { return f(hashes, buckets); }
// Create an always positive filter if nothing else is specified.
filter() : hashes(0), buckets({}) {}
explicit filter(int hashes, std::vector<uint64_t> buckets) : hashes(hashes), buckets({std::move(buckets)}) {}
};
struct index_entry {
disk_string<uint16_t> key;
uint64_t position;
disk_string<uint32_t> promoted_index;
key_view get_key() const {
return { bytes_view(key) };
}
};
struct summary_entry {
bytes key;
uint64_t position;
key_view get_key() const {
return { key };
}
bool operator==(const summary_entry& x) const {
return position == x.position && key == x.key;
}
};
// Note: Sampling level is present in versions ka and higher. We ATM only support la,
// so it's always there. But we need to make this conditional if we ever want to support
// other formats (unlikely)
struct summary_la {
struct header {
// The minimum possible amount of indexes per group (sampling level)
uint32_t min_index_interval;
// The number of entries in the Summary File
uint32_t size;
// The memory to be consumed to map the whole Summary into memory.
uint64_t memory_size;
// The actual sampling level.
uint32_t sampling_level;
// The number of entries the Summary *would* have if the sampling
// level would be equal to min_index_interval.
uint32_t size_at_full_sampling;
} header;
// The position in the Summary file for each of the indexes.
// NOTE1 that its actual size is determined by the "size" parameter, not
// by its preceding size_at_full_sampling
// NOTE2: They are laid out in *MEMORY* order, not BE.
// NOTE3: The sizes in this array represent positions in the memory stream,
// not the file. The memory stream effectively begins after the header,
// so every position here has to be added of sizeof(header).
std::vector<uint32_t> positions;
std::vector<summary_entry> entries;
disk_string<uint32_t> first_key;
disk_string<uint32_t> last_key;
// Used to determine when a summary entry should be added based on min_index_interval.
// NOTE: keys_written isn't part of on-disk format of summary.
size_t keys_written;
// NOTE4: There is a structure written by Cassandra into the end of the Summary
// file, after the field last_key, that we haven't understand yet, but we know
// that its content isn't related to the summary itself.
// The structure is basically as follow:
// struct { disk_string<uint16_t>; uint32_t; uint64_t; disk_string<uint16_t>; }
// Another interesting fact about this structure is that it is apparently always
// filled with the same data. It's too early to judge that the data is useless.
// However, it was tested that Cassandra loads successfully a Summary file with
// this structure removed from it. Anyway, let's pay attention to it.
};
using summary = summary_la;
struct replay_position {
uint64_t segment;
uint32_t position;
replay_position() {}
replay_position(uint64_t seg, uint32_t pos) {
segment = seg;
position = pos;
}
template <typename Describer>
auto describe_type(Describer f) { return f(segment, position); }
};
struct metadata {
virtual ~metadata() {}
};
struct validation_metadata : public metadata {
disk_string<uint16_t> partitioner;
double filter_chance;
size_t serialized_size() {
return sizeof(uint16_t) + partitioner.value.size() + sizeof(filter_chance);
}
template <typename Describer>
auto describe_type(Describer f) { return f(partitioner, filter_chance); }
};
struct compaction_metadata : public metadata {
disk_array<uint32_t, uint32_t> ancestors;
disk_array<uint32_t, uint8_t> cardinality;
size_t serialized_size() {
return sizeof(uint32_t) + (ancestors.elements.size() * sizeof(uint32_t)) +
sizeof(uint32_t) + (cardinality.elements.size() * sizeof(uint8_t));
}
template <typename Describer>
auto describe_type(Describer f) { return f(ancestors, cardinality); }
};
struct ka_stats_metadata : public metadata {
estimated_histogram estimated_row_size;
estimated_histogram estimated_column_count;
replay_position position;
uint64_t min_timestamp;
uint64_t max_timestamp;
uint32_t max_local_deletion_time;
double compression_ratio;
streaming_histogram estimated_tombstone_drop_time;
uint32_t sstable_level;
uint64_t repaired_at;
disk_array<uint32_t, disk_string<uint16_t>> min_column_names;
disk_array<uint32_t, disk_string<uint16_t>> max_column_names;
bool has_legacy_counter_shards;
template <typename Describer>
auto describe_type(Describer f) {
return f(
estimated_row_size,
estimated_column_count,
position,
min_timestamp,
max_timestamp,
max_local_deletion_time,
compression_ratio,
estimated_tombstone_drop_time,
sstable_level,
repaired_at,
min_column_names,
max_column_names,
has_legacy_counter_shards
);
}
};
using stats_metadata = ka_stats_metadata;
// Numbers are found on disk, so they do matter. Also, setting their sizes of
// that of an uint32_t is a bit wasteful, but it simplifies the code a lot
// since we can now still use a strongly typed enum without introducing a
// notion of "disk-size" vs "memory-size".
enum class metadata_type : uint32_t {
Validation = 0,
Compaction = 1,
Stats = 2,
};
static constexpr int DEFAULT_CHUNK_SIZE = 65536;
// checksums are generated using adler32 algorithm.
struct checksum {
uint32_t chunk_size;
std::vector<uint32_t> checksums;
template <typename Describer>
auto describe_type(Describer f) { return f(chunk_size, checksums); }
};
}
namespace std {
template <>
struct hash<sstables::metadata_type> : enum_hash<sstables::metadata_type> {};
}
namespace sstables {
struct statistics {
disk_hash<uint32_t, metadata_type, uint32_t> hash;
std::unordered_map<metadata_type, std::unique_ptr<metadata>> contents;
};
struct deletion_time {
int32_t local_deletion_time;
int64_t marked_for_delete_at;
template <typename Describer>
auto describe_type(Describer f) { return f(local_deletion_time, marked_for_delete_at); }
bool live() const {
return (local_deletion_time == std::numeric_limits<int32_t>::max()) &&
(marked_for_delete_at == std::numeric_limits<int64_t>::min());
}
explicit operator tombstone() {
return tombstone(marked_for_delete_at, gc_clock::time_point(gc_clock::duration(local_deletion_time)));
}
};
enum class column_mask : uint8_t {
none = 0x0,
deletion = 0x01,
expiration = 0x02,
counter = 0x04,
counter_update = 0x08,
range_tombstone = 0x10,
};
inline column_mask operator&(column_mask m1, column_mask m2) {
return column_mask(static_cast<uint8_t>(m1) & static_cast<uint8_t>(m2));
}
inline column_mask operator|(column_mask m1, column_mask m2) {
return column_mask(static_cast<uint8_t>(m1) | static_cast<uint8_t>(m2));
}
}
<commit_msg>sstables: change summary_la to summary_ka<commit_after>/*
* Copyright 2015 Cloudius Systems
*/
#pragma once
#include "disk_types.hh"
#include "core/enum.hh"
#include "bytes.hh"
#include "gc_clock.hh"
#include "tombstone.hh"
#include "streaming_histogram.hh"
#include "estimated_histogram.hh"
#include "column_name_helper.hh"
#include "sstables/key.hh"
#include <vector>
#include <unordered_map>
#include <type_traits>
namespace sstables {
struct option {
disk_string<uint16_t> key;
disk_string<uint16_t> value;
template <typename Describer>
auto describe_type(Describer f) { return f(key, value); }
};
struct filter {
uint32_t hashes;
disk_array<uint32_t, uint64_t> buckets;
template <typename Describer>
auto describe_type(Describer f) { return f(hashes, buckets); }
// Create an always positive filter if nothing else is specified.
filter() : hashes(0), buckets({}) {}
explicit filter(int hashes, std::vector<uint64_t> buckets) : hashes(hashes), buckets({std::move(buckets)}) {}
};
struct index_entry {
disk_string<uint16_t> key;
uint64_t position;
disk_string<uint32_t> promoted_index;
key_view get_key() const {
return { bytes_view(key) };
}
};
struct summary_entry {
bytes key;
uint64_t position;
key_view get_key() const {
return { key };
}
bool operator==(const summary_entry& x) const {
return position == x.position && key == x.key;
}
};
// Note: Sampling level is present in versions ka and higher. We ATM only support ka,
// so it's always there. But we need to make this conditional if we ever want to support
// other formats.
struct summary_ka {
struct header {
// The minimum possible amount of indexes per group (sampling level)
uint32_t min_index_interval;
// The number of entries in the Summary File
uint32_t size;
// The memory to be consumed to map the whole Summary into memory.
uint64_t memory_size;
// The actual sampling level.
uint32_t sampling_level;
// The number of entries the Summary *would* have if the sampling
// level would be equal to min_index_interval.
uint32_t size_at_full_sampling;
} header;
// The position in the Summary file for each of the indexes.
// NOTE1 that its actual size is determined by the "size" parameter, not
// by its preceding size_at_full_sampling
// NOTE2: They are laid out in *MEMORY* order, not BE.
// NOTE3: The sizes in this array represent positions in the memory stream,
// not the file. The memory stream effectively begins after the header,
// so every position here has to be added of sizeof(header).
std::vector<uint32_t> positions;
std::vector<summary_entry> entries;
disk_string<uint32_t> first_key;
disk_string<uint32_t> last_key;
// Used to determine when a summary entry should be added based on min_index_interval.
// NOTE: keys_written isn't part of on-disk format of summary.
size_t keys_written;
// NOTE4: There is a structure written by Cassandra into the end of the Summary
// file, after the field last_key, that we haven't understand yet, but we know
// that its content isn't related to the summary itself.
// The structure is basically as follow:
// struct { disk_string<uint16_t>; uint32_t; uint64_t; disk_string<uint16_t>; }
// Another interesting fact about this structure is that it is apparently always
// filled with the same data. It's too early to judge that the data is useless.
// However, it was tested that Cassandra loads successfully a Summary file with
// this structure removed from it. Anyway, let's pay attention to it.
};
using summary = summary_ka;
struct replay_position {
uint64_t segment;
uint32_t position;
replay_position() {}
replay_position(uint64_t seg, uint32_t pos) {
segment = seg;
position = pos;
}
template <typename Describer>
auto describe_type(Describer f) { return f(segment, position); }
};
struct metadata {
virtual ~metadata() {}
};
struct validation_metadata : public metadata {
disk_string<uint16_t> partitioner;
double filter_chance;
size_t serialized_size() {
return sizeof(uint16_t) + partitioner.value.size() + sizeof(filter_chance);
}
template <typename Describer>
auto describe_type(Describer f) { return f(partitioner, filter_chance); }
};
struct compaction_metadata : public metadata {
disk_array<uint32_t, uint32_t> ancestors;
disk_array<uint32_t, uint8_t> cardinality;
size_t serialized_size() {
return sizeof(uint32_t) + (ancestors.elements.size() * sizeof(uint32_t)) +
sizeof(uint32_t) + (cardinality.elements.size() * sizeof(uint8_t));
}
template <typename Describer>
auto describe_type(Describer f) { return f(ancestors, cardinality); }
};
struct ka_stats_metadata : public metadata {
estimated_histogram estimated_row_size;
estimated_histogram estimated_column_count;
replay_position position;
uint64_t min_timestamp;
uint64_t max_timestamp;
uint32_t max_local_deletion_time;
double compression_ratio;
streaming_histogram estimated_tombstone_drop_time;
uint32_t sstable_level;
uint64_t repaired_at;
disk_array<uint32_t, disk_string<uint16_t>> min_column_names;
disk_array<uint32_t, disk_string<uint16_t>> max_column_names;
bool has_legacy_counter_shards;
template <typename Describer>
auto describe_type(Describer f) {
return f(
estimated_row_size,
estimated_column_count,
position,
min_timestamp,
max_timestamp,
max_local_deletion_time,
compression_ratio,
estimated_tombstone_drop_time,
sstable_level,
repaired_at,
min_column_names,
max_column_names,
has_legacy_counter_shards
);
}
};
using stats_metadata = ka_stats_metadata;
// Numbers are found on disk, so they do matter. Also, setting their sizes of
// that of an uint32_t is a bit wasteful, but it simplifies the code a lot
// since we can now still use a strongly typed enum without introducing a
// notion of "disk-size" vs "memory-size".
enum class metadata_type : uint32_t {
Validation = 0,
Compaction = 1,
Stats = 2,
};
static constexpr int DEFAULT_CHUNK_SIZE = 65536;
// checksums are generated using adler32 algorithm.
struct checksum {
uint32_t chunk_size;
std::vector<uint32_t> checksums;
template <typename Describer>
auto describe_type(Describer f) { return f(chunk_size, checksums); }
};
}
namespace std {
template <>
struct hash<sstables::metadata_type> : enum_hash<sstables::metadata_type> {};
}
namespace sstables {
struct statistics {
disk_hash<uint32_t, metadata_type, uint32_t> hash;
std::unordered_map<metadata_type, std::unique_ptr<metadata>> contents;
};
struct deletion_time {
int32_t local_deletion_time;
int64_t marked_for_delete_at;
template <typename Describer>
auto describe_type(Describer f) { return f(local_deletion_time, marked_for_delete_at); }
bool live() const {
return (local_deletion_time == std::numeric_limits<int32_t>::max()) &&
(marked_for_delete_at == std::numeric_limits<int64_t>::min());
}
explicit operator tombstone() {
return tombstone(marked_for_delete_at, gc_clock::time_point(gc_clock::duration(local_deletion_time)));
}
};
enum class column_mask : uint8_t {
none = 0x0,
deletion = 0x01,
expiration = 0x02,
counter = 0x04,
counter_update = 0x08,
range_tombstone = 0x10,
};
inline column_mask operator&(column_mask m1, column_mask m2) {
return column_mask(static_cast<uint8_t>(m1) & static_cast<uint8_t>(m2));
}
inline column_mask operator|(column_mask m1, column_mask m2) {
return column_mask(static_cast<uint8_t>(m1) | static_cast<uint8_t>(m2));
}
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/eff_config/timing.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file timing.H
/// @brief Determine effective config for mss settings
///
// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP FW Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP
#ifndef _MSS_TIMING_H_
#define _MSS_TIMING_H_
#include <cstdint>
#include <fapi2.H>
#include <mss.H>
#include <lib/utils/find.H>
using fapi2::TARGET_TYPE_DIMM;
namespace mss
{
// { density in GBs, tREFI(base) in picoseconds }
static const std::vector<std::pair<uint8_t, uint64_t> > TREFI_BASE =
{
{2, 7800},
{4, 7800},
{8, 7800},
// 16Gb - TBD
};
// { density in GBs, tRFC1(min) in picoseconds }
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC1_MIN =
{
{2, 160},
{4, 260},
{8, 350},
// 16Gb - TBD
};
// { density in GBs, tRFC2(min) in picoseconds }
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC2_MIN =
{
{2, 110},
{4, 160},
{8, 260},
// 16Gb - TBD
};
// { density in GBs, tRFC4(min) in picoseconds }
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC4_MIN =
{
{2, 90},
{4, 110},
{8, 160},
// 16Gb - TBD
};
enum GUARD_BAND
{
// Used for caclulating spd timing values - from JEDEC rounding algorithm
// Correction factor is 1% (for DDR3) or 2.5% (for DDR4)
// when doing integer math, we add-in the inverse correction factor
// Formula used for derivation:
// Guardband = 1000 * (1000* correction_factor) - 1
INVERSE_DDR3_CORRECTION_FACTOR = 989,
INVERSE_DDR4_CORRECTION_FACTOR = 974,
};
///
/// @brief Calculates timing value
/// @tparam T input and output type
/// @param[in] i_timing_mtb timing value in MTB units
/// @param[in] i_mtb_multiplier SPD medium timebase
/// @param[in] i_timing_ftb fine offset of timing value
/// @param[in] i_ftb_multiplier SPD fine timebase
/// @return the timing value in picoseconds
///
template<typename T>
inline T calc_timing_from_timebase(const T i_timing_mtb,
const T i_mtb_multiplier,
const T i_timing_ftb,
const T i_ftb_multiplier)
{
// JEDEC algorithm
T l_timing_val = i_timing_mtb * i_mtb_multiplier;
T l_fine_offset = i_timing_ftb * i_ftb_multiplier;
// Needed to do integer math but attribute is uint64
return l_timing_val + l_fine_offset;
}
///
/// @brief Returns clock cycles
/// @tparam T input and output type
/// @param[in] timing_in_ps timing parameter in ps
/// @param[in] tck_in_ps clock period in ps
/// @param[in] inverse_corr_factor inverse correction factor (defined by JEDEC)
/// @return the clock cycles of timing parameter (provided in ps)
/// @note DDR4 SPD Contents Rounding Algorithm
/// @note Item 2220.46
///
template<typename T>
inline T calc_nck(T timing_in_ps, T tck_in_ps, T inverse_corr_factor)
{
// Preliminary nCK calculation, scaled by 1000
T temp_nck = timing_in_ps * 1000 / tck_in_ps;
// Apply inverse of correction factor percentage
temp_nck += inverse_corr_factor;
return temp_nck / 1000;
}
//
// TK - AAM
// These are only used in eff_config, make them non-member non-friend functions in eff_config.C?
//
/// @brief Calculates refresh interval time 1 (tREFI 1)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
inline fapi2::ReturnCode calc_trefi1(const fapi2::Target<TARGET_TYPE_DIMM>& i_target, uint64_t& o_value)
{
uint8_t l_quotient = 0;
uint8_t l_remainder = 0;
uint64_t l_output = 0;
uint8_t l_temp_ref_range = 0;
uint8_t l_dram_density = 0;
FAPI_TRY(mss::eff_dram_density(i_target, l_dram_density));
switch(l_temp_ref_range)
{
case fapi2::ENUM_ATTR_EFF_TEMP_REF_RANGE_NORMAL:
mss::find_value_from_key(TREFI_BASE, l_dram_density, o_value);
break;
case fapi2::ENUM_ATTR_EFF_TEMP_REF_RANGE_EXTEND:
mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
l_quotient = l_output / 2;
l_remainder = l_output % 2;
o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
break;
default:
// l_temp_ref_range will be a platform attribute set by the MRW,
// which they "shouldn't" mess up as long as use "attribute" enums.
// if openpower messes this up we can at least catch it
FAPI_ASSERT(false,
fapi2::MSS_INVALID_TEMP_REF_RANGE().
set_TEMP_REF_RANGE(l_temp_ref_range),
"%s Incorrect Temperature Ref. Range received: %d ",
mss::c_str(i_target),
l_temp_ref_range);
break;
}
fapi_try_exit:
return fapi2::current_err;
}
/// @brief Calculates refresh interval time 2 (tREFI 2)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
inline fapi2::ReturnCode calc_trefi2(const fapi2::Target<TARGET_TYPE_DIMM>& i_target, uint64_t& o_value)
{
uint8_t l_quotient = 0;
uint8_t l_remainder = 0;
uint64_t l_output = 0;
uint8_t l_temp_ref_range = 0;
uint8_t l_dram_density = 0;
FAPI_TRY(mss::eff_temp_ref_range(i_target, l_temp_ref_range));
FAPI_TRY(mss::eff_dram_density(i_target, l_dram_density));
switch(l_temp_ref_range)
{
case fapi2::ENUM_ATTR_EFF_TEMP_REF_RANGE_NORMAL:
mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
l_quotient = l_output / 2;
l_remainder = l_output % 2;
o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
break;
case fapi2::ENUM_ATTR_EFF_TEMP_REF_RANGE_EXTEND:
mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
l_quotient = l_output / 4;
l_remainder = l_output % 4;
o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
break;
default:
// l_temp_ref_range will be a platform attribute set by the MRW,
// which they "shouldn't" mess up as long as use "attribute" enums.
// if openpower messes this up we can at least catch it
FAPI_ASSERT(false,
fapi2::MSS_INVALID_TEMP_REF_RANGE().
set_TEMP_REF_RANGE(l_temp_ref_range),
"%s Incorrect Temperature Ref. Range received: %d ",
mss::c_str(i_target),
l_temp_ref_range);
break;
}
fapi_try_exit:
return fapi2::current_err;
}
/// @brief Calculates refresh interval time 4 (tREFI 4)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
inline fapi2::ReturnCode calc_trefi4( const fapi2::Target<TARGET_TYPE_DIMM>& i_target, uint64_t& o_value)
{
uint8_t l_quotient = 0;
uint8_t l_remainder = 0;
uint64_t l_output = 0;
uint8_t l_temp_ref_range = 0;
uint8_t l_dram_density = 0;
FAPI_TRY(mss::eff_temp_ref_range(i_target, l_temp_ref_range));
FAPI_TRY(mss::eff_dram_density(i_target, l_dram_density));
switch(l_temp_ref_range)
{
case fapi2::ENUM_ATTR_EFF_TEMP_REF_RANGE_NORMAL:
mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
l_quotient = l_output / 4;
l_remainder = l_output % 4;
o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
break;
case fapi2::ENUM_ATTR_EFF_TEMP_REF_RANGE_EXTEND:
mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
l_quotient = l_output / 8;
l_remainder = l_output % 8;
o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
break;
default:
// l_temp_ref_range will be a platform attribute set by the MRW,
// which they "shouldn't" mess up as long as use "attribute" enums.
// if openpower messes this up we can at least catch it
FAPI_ASSERT(false,
fapi2::MSS_INVALID_TEMP_REF_RANGE().
set_TEMP_REF_RANGE(l_temp_ref_range),
"%s Incorrect Temperature Ref. Range received: %d ",
mss::c_str(i_target),
l_temp_ref_range);
break;
}
fapi_try_exit:
return fapi2::current_err;
}
} // mss
#endif
<commit_msg>Modify freq & dep. files. Add cas latency & unit tests<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/eff_config/timing.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file timing.H
/// @brief Determine effective config for mss settings
///
// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP FW Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP
#ifndef _MSS_TIMING_H_
#define _MSS_TIMING_H_
#include <cstdint>
#include <fapi2.H>
namespace mss
{
enum GUARD_BAND
{
// Used for caclulating spd timing values - from JEDEC rounding algorithm
// Correction factor is 1% (for DDR3) or 2.5% (for DDR4)
// when doing integer math, we add-in the inverse correction factor
// Formula used for derivation:
// Guardband = 1000 * (1000* correction_factor) - 1
INVERSE_DDR3_CORRECTION_FACTOR = 989,
INVERSE_DDR4_CORRECTION_FACTOR = 974,
};
///
/// @brief Calculates timing value
/// @tparam T input and output type
/// @param[in] i_timing_mtb timing value in MTB units
/// @param[in] i_mtb_multiplier SPD medium timebase
/// @param[in] i_timing_ftb fine offset of timing value
/// @param[in] i_ftb_multiplier SPD fine timebase
/// @return the timing value in picoseconds
///
template<typename T>
inline T calc_timing_from_timebase(const T i_timing_mtb,
const T i_mtb_multiplier,
const T i_timing_ftb,
const T i_ftb_multiplier)
{
// JEDEC algorithm
T l_timing_val = i_timing_mtb * i_mtb_multiplier;
T l_fine_offset = i_timing_ftb * i_ftb_multiplier;
return l_timing_val + l_fine_offset;
}
///
/// @brief Returns clock cycles
/// @tparam T input and output type
/// @param[in] timing_in_ps timing parameter in ps
/// @param[in] tck_in_ps clock period in ps
/// @param[in] inverse_corr_factor inverse correction factor (defined by JEDEC)
/// @return the clock cycles of timing parameter (provided in ps)
/// @note DDR4 SPD Contents Rounding Algorithm
/// @note Item 2220.46
///
template<typename T>
inline T calc_nck(T timing_in_ps, T tck_in_ps, T inverse_corr_factor)
{
// Preliminary nCK calculation, scaled by 1000
T temp_nck = timing_in_ps * 1000 / tck_in_ps;
// Apply inverse of correction factor percentage
temp_nck += inverse_corr_factor;
return temp_nck / 1000;
}
/// @brief Calculates refresh interval time 1 (tREFI 1)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode calc_trefi1(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
uint64_t& o_value);
/// @brief Calculates refresh interval time 2 (tREFI 2)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode calc_trefi2(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
uint64_t& o_value);
/// @brief Calculates refresh interval time 4 (tREFI 4)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode calc_trefi4( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
uint64_t& o_value);
} // mss
#endif
<|endoftext|>
|
<commit_before>/**
* create_cost_function main file. Reads a label.txt and several
* minimalImpactTEDcoefficients.txt to create a single const_function.txt that
* can be used with sbmrm.
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <sopnet/segments/SegmentHash.h>
#include <util/exceptions.h>
#include <util/ProgramOptions.h>
#include <util/Logger.h>
util::ProgramOption optionLabels(
util::_long_name = "labels",
util::_description_text = "The gold standard label file.",
util::_default_value = "labels.txt");
util::ProgramOption optionTedCoefficientFile(
util::_long_name = "coefficients",
util::_description_text = "A file that contains TED coefficients, one per line: [varnum] [coeff] # [hash] [misc]. The important pieces for this script are [coeff] and [hash].",
util::_default_value = "ted_coefficients.txt");
util::ProgramOption optionCostFunctionFile(
util::_long_name = "out",
util::_description_text = "The file to store the coefficients in.",
util::_default_value = "cost_function.txt");
/**
* Read the coefficients of each segment from the given file.
*/
std::map<SegmentHash, double>
readCoefficients(const std::string& filename) {
std::map<SegmentHash, double> coefficients;
std::ifstream coefsfile(filename.c_str());
while (coefsfile.good()) {
std::string line;
std::getline(coefsfile, line);
std::stringstream linestream(line);
std::string varname;
linestream >> varname;
// first line or comment or empty or constant
if (varname == "numVar" || varname == "constant" || varname.find_first_of('#') == 0 || varname.empty())
continue;
double coef;
linestream >> coef;
char hashSymbol;
linestream >> hashSymbol;
if (hashSymbol != '#')
UTIL_THROW_EXCEPTION(
IOError,
"line '" << line << "' does not have valid syntax (expected '#', got '" << hashSymbol << "'");
SegmentHash hash;
linestream >> hash;
coefficients[hash] = coef;
}
return coefficients;
}
/**
* Read the variables and their corresponding segment hashes from the given
* file.
*/
std::vector<SegmentHash>
readVariables(const std::string& filename) {
std::vector<SegmentHash> hashes;
std::ifstream labelsfile(filename.c_str());
while (labelsfile.good()) {
std::string line;
std::getline(labelsfile, line);
std::stringstream linestream(line);
bool defaultValue;
linestream >> defaultValue;
char hashSymbol;
linestream >> hashSymbol;
if (hashSymbol != '#')
UTIL_THROW_EXCEPTION(
IOError,
"line '" << line << "' does not have valid syntax (expected '#', got '" << hashSymbol << "'");
SegmentHash hash;
linestream >> hash;
hashes.push_back(hash);
}
return hashes;
}
int main(int optionc, char** optionv) {
try {
/********
* INIT *
********/
// init command line parser
util::ProgramOptions::init(optionc, optionv);
// init logger
logger::LogManager::init();
LOG_USER(logger::out) << "[main] starting..." << std::endl;
// read hashes and their coefs
std::vector<SegmentHash> hashes = readVariables(optionLabels.as<std::string>());
std::map<SegmentHash, double> coefs = readCoefficients(optionTedCoefficientFile.as<std::string>());
// assemble cost_function.txt
std::ofstream costFunctionFile(optionCostFunctionFile.as<std::string>());
double constant = 0;
costFunctionFile << "varNum " << hashes.size() << std::endl;
for (unsigned int i = 0; i < hashes.size(); i++) {
double coef = coefs[hashes[i]];
costFunctionFile << "c" << i << " " << coef << std::endl;
if (coef < 0)
constant += -coef;
}
costFunctionFile << "constant " << constant << std::endl;
/*********
* SETUP *
*********/
} catch (Exception& e) {
handleException(e, std::cerr);
}
}
<commit_msg>Changed varNum in first line of output of create_cost_function to numVar<commit_after>/**
* create_cost_function main file. Reads a label.txt and several
* minimalImpactTEDcoefficients.txt to create a single const_function.txt that
* can be used with sbmrm.
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <sopnet/segments/SegmentHash.h>
#include <util/exceptions.h>
#include <util/ProgramOptions.h>
#include <util/Logger.h>
util::ProgramOption optionLabels(
util::_long_name = "labels",
util::_description_text = "The gold standard label file.",
util::_default_value = "labels.txt");
util::ProgramOption optionTedCoefficientFile(
util::_long_name = "coefficients",
util::_description_text = "A file that contains TED coefficients, one per line: [varnum] [coeff] # [hash] [misc]. The important pieces for this script are [coeff] and [hash].",
util::_default_value = "ted_coefficients.txt");
util::ProgramOption optionCostFunctionFile(
util::_long_name = "out",
util::_description_text = "The file to store the coefficients in.",
util::_default_value = "cost_function.txt");
/**
* Read the coefficients of each segment from the given file.
*/
std::map<SegmentHash, double>
readCoefficients(const std::string& filename) {
std::map<SegmentHash, double> coefficients;
std::ifstream coefsfile(filename.c_str());
while (coefsfile.good()) {
std::string line;
std::getline(coefsfile, line);
std::stringstream linestream(line);
std::string varname;
linestream >> varname;
// first line or comment or empty or constant
if (varname == "numVar" || varname == "constant" || varname.find_first_of('#') == 0 || varname.empty())
continue;
double coef;
linestream >> coef;
char hashSymbol;
linestream >> hashSymbol;
if (hashSymbol != '#')
UTIL_THROW_EXCEPTION(
IOError,
"line '" << line << "' does not have valid syntax (expected '#', got '" << hashSymbol << "'");
SegmentHash hash;
linestream >> hash;
coefficients[hash] = coef;
}
return coefficients;
}
/**
* Read the variables and their corresponding segment hashes from the given
* file.
*/
std::vector<SegmentHash>
readVariables(const std::string& filename) {
std::vector<SegmentHash> hashes;
std::ifstream labelsfile(filename.c_str());
while (labelsfile.good()) {
std::string line;
std::getline(labelsfile, line);
std::stringstream linestream(line);
bool defaultValue;
linestream >> defaultValue;
char hashSymbol;
linestream >> hashSymbol;
if (hashSymbol != '#')
UTIL_THROW_EXCEPTION(
IOError,
"line '" << line << "' does not have valid syntax (expected '#', got '" << hashSymbol << "'");
SegmentHash hash;
linestream >> hash;
hashes.push_back(hash);
}
return hashes;
}
int main(int optionc, char** optionv) {
try {
/********
* INIT *
********/
// init command line parser
util::ProgramOptions::init(optionc, optionv);
// init logger
logger::LogManager::init();
LOG_USER(logger::out) << "[main] starting..." << std::endl;
// read hashes and their coefs
std::vector<SegmentHash> hashes = readVariables(optionLabels.as<std::string>());
std::map<SegmentHash, double> coefs = readCoefficients(optionTedCoefficientFile.as<std::string>());
// assemble cost_function.txt
std::ofstream costFunctionFile(optionCostFunctionFile.as<std::string>());
double constant = 0;
costFunctionFile << "numVar " << hashes.size() << std::endl;
for (unsigned int i = 0; i < hashes.size(); i++) {
double coef = coefs[hashes[i]];
costFunctionFile << "c" << i << " " << coef << std::endl;
if (coef < 0)
constant += -coef;
}
costFunctionFile << "constant " << constant << std::endl;
/*********
* SETUP *
*********/
} catch (Exception& e) {
handleException(e, std::cerr);
}
}
<|endoftext|>
|
<commit_before>#pragma once
#include "constants.hpp"
#include "types.hpp"
#include <fstream>
#include <json/json.hpp>
#include <spdlog/spdlog.h>
// Example:
//
// {
// "global": {
// "check_for_updates_on_startup": true,
// "show_in_menu_bar": true
// },
// "profiles": [
// {
// "name": "Default profile",
// "selected": true,
// "simple_modifications": {
// "caps_lock": "delete_or_backspace",
// "escape": "spacebar"
// },
// "fn_function_keys": {
// "f1": "display_brightness_decrement",
// "f2": "display_brightness_increment",
// "f3": "mission_control",
// "f4": "launchpad",
// "f5": "illumination_decrement",
// "f6": "illumination_increment",
// "f7": "rewind",
// "f8": "play_or_pause",
// "f9": "fastforward",
// "f10": "mute",
// "f11": "volume_decrement",
// "f12": "volume_increment"
// },
// "virtual_hid_keyboard": {
// "keyboard_type": "ansi",
// "caps_lock_delay_milliseconds": 100
// },
// "devices": [
// {
// "identifiers": {
// "vendor_id": 1133,
// "product_id": 50475,
// "is_keyboard": true,
// "is_pointing_device": false
// },
// "ignore": false
// },
// {
// "identifiers": {
// "vendor_id": 1452,
// "product_id": 610,
// "is_keyboard": true,
// "is_pointing_device": false
// },
// "ignore": true,
// "disable_built_in_keyboard_if_exists": true
// }
// ]
// },
// {
// "name": "Empty",
// "selected": false
// }
// ]
// }
class core_configuration final {
public:
core_configuration(const core_configuration&) = delete;
core_configuration(spdlog::logger& logger, const std::string& file_path) : logger_(logger), file_path_(file_path), loaded_(false) {
std::ifstream input(file_path_);
if (input) {
try {
json_ = nlohmann::json::parse(input);
loaded_ = true;
} catch (std::exception& e) {
logger_.warn("parse error in {0}: {1}", file_path_, e.what());
}
}
}
std::string to_json_string(void) const {
return json_.dump();
}
bool is_loaded(void) const { return loaded_; }
// std::vector<from,to>
std::vector<std::pair<krbn::key_code, krbn::key_code>> get_current_profile_simple_modifications(void) {
auto profile = get_current_profile();
return get_key_code_pair_from_json_object(profile["simple_modifications"]);
}
// std::vector<f1,display_brightness_decrement>
std::vector<std::pair<krbn::key_code, krbn::key_code>> get_current_profile_fn_function_keys(void) {
auto profile = get_current_profile();
return get_key_code_pair_from_json_object(profile["fn_function_keys"]);
}
krbn::virtual_hid_keyboard_configuration_struct get_current_profile_virtual_hid_keyboard(void) {
krbn::virtual_hid_keyboard_configuration_struct virtual_hid_keyboard_configuration_struct;
auto profile = get_current_profile();
if (profile["virtual_hid_keyboard"].is_object()) {
std::string keyboard_type_name = profile["virtual_hid_keyboard"]["keyboard_type"];
if (auto keyboard_type = krbn::types::get_keyboard_type(keyboard_type_name)) {
virtual_hid_keyboard_configuration_struct.keyboard_type = *keyboard_type;
}
if (profile["virtual_hid_keyboard"]["caps_lock_delay_milliseconds"].is_number()) {
virtual_hid_keyboard_configuration_struct.caps_lock_delay_milliseconds = profile["virtual_hid_keyboard"]["caps_lock_delay_milliseconds"];
}
}
return virtual_hid_keyboard_configuration_struct;
}
std::vector<std::pair<krbn::device_identifiers_struct, krbn::device_configuration_struct>> get_current_profile_devices(void) {
std::vector<std::pair<krbn::device_identifiers_struct, krbn::device_configuration_struct>> v;
auto profile = get_current_profile();
if (profile["devices"].is_array()) {
for (auto&& device : profile["devices"]) {
if (device["identifiers"].is_object() &&
device["identifiers"]["vendor_id"].is_number() &&
device["identifiers"]["product_id"].is_number() &&
device["identifiers"]["is_keyboard"].is_boolean() &&
device["identifiers"]["is_pointing_device"].is_boolean() &&
device["ignore"].is_boolean()) {
krbn::device_identifiers_struct device_identifiers_struct;
device_identifiers_struct.vendor_id = krbn::vendor_id(static_cast<uint32_t>(device["identifiers"]["vendor_id"]));
device_identifiers_struct.product_id = krbn::product_id(static_cast<uint32_t>(device["identifiers"]["product_id"]));
device_identifiers_struct.is_keyboard = device["identifiers"]["is_keyboard"];
device_identifiers_struct.is_pointing_device = device["identifiers"]["is_pointing_device"];
krbn::device_configuration_struct device_configuration_struct;
device_configuration_struct.ignore = device["ignore"];
device_configuration_struct.disable_built_in_keyboard_if_exists = false;
// disable_built_in_keyboard_if_exists is optional
if (device["disable_built_in_keyboard_if_exists"].is_boolean()) {
device_configuration_struct.disable_built_in_keyboard_if_exists = static_cast<bool>(device["disable_built_in_keyboard_if_exists"]);
}
v.push_back(std::make_pair(device_identifiers_struct, device_configuration_struct));
}
}
}
return v;
}
std::string get_current_profile_json(void) {
return get_current_profile().dump();
}
bool get_global_check_for_updates_on_startup(void) {
if (json_["global"]["check_for_updates_on_startup"].is_boolean()) {
return json_["global"]["check_for_updates_on_startup"];
}
return true;
}
bool get_global_show_in_menu_bar(void) {
auto value = json_["global"]["show_in_menu_bar"];
if (value.is_boolean()) {
return value;
}
return true;
}
// Note:
// Be careful calling `save` method.
// If the configuration file is corrupted temporarily (user editing the configuration file in editor),
// the user data will be lost by the `save` method.
// Thus, we should call the `save` method only when it is neccessary.
bool save(void) {
std::ofstream output(file_path_);
if (!output) {
return false;
}
output << std::setw(4) << json_ << std::endl;
return true;
}
private:
nlohmann::json get_default_profile(void) const {
nlohmann::json json;
json["name"] = "Default profile";
json["selected"] = true;
json["simple_modifications"] = nlohmann::json::object();
json["fn_function_keys"]["f1"] = "display_brightness_decrement";
json["fn_function_keys"]["f2"] = "display_brightness_increment";
json["fn_function_keys"]["f3"] = "mission_control";
json["fn_function_keys"]["f4"] = "launchpad";
json["fn_function_keys"]["f5"] = "illumination_decrement";
json["fn_function_keys"]["f6"] = "illumination_increment";
json["fn_function_keys"]["f7"] = "rewind";
json["fn_function_keys"]["f8"] = "play_or_pause";
json["fn_function_keys"]["f9"] = "fastforward";
json["fn_function_keys"]["f10"] = "mute";
json["fn_function_keys"]["f11"] = "volume_decrement";
json["fn_function_keys"]["f12"] = "volume_increment";
json["devices"] = nlohmann::json::array();
return json;
}
nlohmann::json get_current_profile(void) {
if (json_.is_object() && json_["profiles"].is_array()) {
for (auto&& profile : json_["profiles"]) {
if (profile.is_object() && profile["selected"]) {
// Use default value if fn_function_keys is not set.
if (!profile["fn_function_keys"].is_object()) {
auto default_profile = get_default_profile();
profile["fn_function_keys"] = default_profile["fn_function_keys"];
}
return profile;
}
}
}
return get_default_profile();
}
std::vector<std::pair<krbn::key_code, krbn::key_code>> get_key_code_pair_from_json_object(const nlohmann::json& json) {
std::vector<std::pair<krbn::key_code, krbn::key_code>> v;
if (json.is_object()) {
for (auto it = json.begin(); it != json.end(); ++it) {
std::string from = it.key();
std::string to = it.value();
auto from_key_code = krbn::types::get_key_code(from);
if (!from_key_code) {
logger_.warn("unknown key_code:{0} in {1}", from, file_path_);
continue;
}
auto to_key_code = krbn::types::get_key_code(to);
if (!to_key_code) {
logger_.warn("unknown key_code:{0} in {1}", to, file_path_);
continue;
}
v.push_back(std::make_pair(*from_key_code, *to_key_code));
}
}
return v;
}
spdlog::logger& logger_;
std::string file_path_;
bool loaded_;
nlohmann::json json_;
};
<commit_msg>set default values in core_configuration<commit_after>#pragma once
#include "constants.hpp"
#include "types.hpp"
#include <fstream>
#include <json/json.hpp>
#include <spdlog/spdlog.h>
// Example:
//
// {
// "global": {
// "check_for_updates_on_startup": true,
// "show_in_menu_bar": true
// },
// "profiles": [
// {
// "name": "Default profile",
// "selected": true,
// "simple_modifications": {
// "caps_lock": "delete_or_backspace",
// "escape": "spacebar"
// },
// "fn_function_keys": {
// "f1": "display_brightness_decrement",
// "f2": "display_brightness_increment",
// "f3": "mission_control",
// "f4": "launchpad",
// "f5": "illumination_decrement",
// "f6": "illumination_increment",
// "f7": "rewind",
// "f8": "play_or_pause",
// "f9": "fastforward",
// "f10": "mute",
// "f11": "volume_decrement",
// "f12": "volume_increment"
// },
// "virtual_hid_keyboard": {
// "keyboard_type": "ansi",
// "caps_lock_delay_milliseconds": 100
// },
// "devices": [
// {
// "identifiers": {
// "vendor_id": 1133,
// "product_id": 50475,
// "is_keyboard": true,
// "is_pointing_device": false
// },
// "ignore": false
// },
// {
// "identifiers": {
// "vendor_id": 1452,
// "product_id": 610,
// "is_keyboard": true,
// "is_pointing_device": false
// },
// "ignore": true,
// "disable_built_in_keyboard_if_exists": true
// }
// ]
// },
// {
// "name": "Empty",
// "selected": false
// }
// ]
// }
class core_configuration final {
public:
core_configuration(const core_configuration&) = delete;
core_configuration(spdlog::logger& logger, const std::string& file_path) : logger_(logger), file_path_(file_path), loaded_(false) {
std::ifstream input(file_path_);
if (input) {
try {
json_ = nlohmann::json::parse(input);
// ----------------------------------------
// Add default values if needed.
if (!json_["profiles"].is_array()) {
json_["profiles"] = nlohmann::json::array();
}
if (json_["profiles"].empty()) {
json_["profiles"].push_back(get_default_profile());
}
for (auto&& profile : json_["profiles"]) {
// Use default value if fn_function_keys is not set.
if (!profile["fn_function_keys"].is_object() || profile["fn_function_keys"].empty()) {
auto default_profile = get_default_profile();
profile["fn_function_keys"] = default_profile["fn_function_keys"];
}
}
// ----------------------------------------
loaded_ = true;
} catch (std::exception& e) {
logger_.warn("parse error in {0}: {1}", file_path_, e.what());
}
}
}
std::string to_json_string(void) const {
return json_.dump();
}
bool is_loaded(void) const { return loaded_; }
// std::vector<from,to>
std::vector<std::pair<krbn::key_code, krbn::key_code>> get_current_profile_simple_modifications(void) {
auto profile = get_current_profile();
return get_key_code_pair_from_json_object(profile["simple_modifications"]);
}
// std::vector<f1,display_brightness_decrement>
std::vector<std::pair<krbn::key_code, krbn::key_code>> get_current_profile_fn_function_keys(void) {
auto profile = get_current_profile();
return get_key_code_pair_from_json_object(profile["fn_function_keys"]);
}
krbn::virtual_hid_keyboard_configuration_struct get_current_profile_virtual_hid_keyboard(void) {
krbn::virtual_hid_keyboard_configuration_struct virtual_hid_keyboard_configuration_struct;
auto profile = get_current_profile();
if (profile["virtual_hid_keyboard"].is_object()) {
std::string keyboard_type_name = profile["virtual_hid_keyboard"]["keyboard_type"];
if (auto keyboard_type = krbn::types::get_keyboard_type(keyboard_type_name)) {
virtual_hid_keyboard_configuration_struct.keyboard_type = *keyboard_type;
}
if (profile["virtual_hid_keyboard"]["caps_lock_delay_milliseconds"].is_number()) {
virtual_hid_keyboard_configuration_struct.caps_lock_delay_milliseconds = profile["virtual_hid_keyboard"]["caps_lock_delay_milliseconds"];
}
}
return virtual_hid_keyboard_configuration_struct;
}
std::vector<std::pair<krbn::device_identifiers_struct, krbn::device_configuration_struct>> get_current_profile_devices(void) {
std::vector<std::pair<krbn::device_identifiers_struct, krbn::device_configuration_struct>> v;
auto profile = get_current_profile();
if (profile["devices"].is_array()) {
for (auto&& device : profile["devices"]) {
if (device["identifiers"].is_object() &&
device["identifiers"]["vendor_id"].is_number() &&
device["identifiers"]["product_id"].is_number() &&
device["identifiers"]["is_keyboard"].is_boolean() &&
device["identifiers"]["is_pointing_device"].is_boolean() &&
device["ignore"].is_boolean()) {
krbn::device_identifiers_struct device_identifiers_struct;
device_identifiers_struct.vendor_id = krbn::vendor_id(static_cast<uint32_t>(device["identifiers"]["vendor_id"]));
device_identifiers_struct.product_id = krbn::product_id(static_cast<uint32_t>(device["identifiers"]["product_id"]));
device_identifiers_struct.is_keyboard = device["identifiers"]["is_keyboard"];
device_identifiers_struct.is_pointing_device = device["identifiers"]["is_pointing_device"];
krbn::device_configuration_struct device_configuration_struct;
device_configuration_struct.ignore = device["ignore"];
device_configuration_struct.disable_built_in_keyboard_if_exists = false;
// disable_built_in_keyboard_if_exists is optional
if (device["disable_built_in_keyboard_if_exists"].is_boolean()) {
device_configuration_struct.disable_built_in_keyboard_if_exists = static_cast<bool>(device["disable_built_in_keyboard_if_exists"]);
}
v.push_back(std::make_pair(device_identifiers_struct, device_configuration_struct));
}
}
}
return v;
}
std::string get_current_profile_json(void) {
return get_current_profile().dump();
}
bool get_global_check_for_updates_on_startup(void) {
if (json_["global"]["check_for_updates_on_startup"].is_boolean()) {
return json_["global"]["check_for_updates_on_startup"];
}
return true;
}
bool get_global_show_in_menu_bar(void) {
auto value = json_["global"]["show_in_menu_bar"];
if (value.is_boolean()) {
return value;
}
return true;
}
// Note:
// Be careful calling `save` method.
// If the configuration file is corrupted temporarily (user editing the configuration file in editor),
// the user data will be lost by the `save` method.
// Thus, we should call the `save` method only when it is neccessary.
bool save(void) {
std::ofstream output(file_path_);
if (!output) {
return false;
}
output << std::setw(4) << json_ << std::endl;
return true;
}
private:
nlohmann::json get_default_profile(void) const {
nlohmann::json json;
json["name"] = "Default profile";
json["selected"] = true;
json["simple_modifications"] = nlohmann::json::object();
json["fn_function_keys"]["f1"] = "display_brightness_decrement";
json["fn_function_keys"]["f2"] = "display_brightness_increment";
json["fn_function_keys"]["f3"] = "mission_control";
json["fn_function_keys"]["f4"] = "launchpad";
json["fn_function_keys"]["f5"] = "illumination_decrement";
json["fn_function_keys"]["f6"] = "illumination_increment";
json["fn_function_keys"]["f7"] = "rewind";
json["fn_function_keys"]["f8"] = "play_or_pause";
json["fn_function_keys"]["f9"] = "fastforward";
json["fn_function_keys"]["f10"] = "mute";
json["fn_function_keys"]["f11"] = "volume_decrement";
json["fn_function_keys"]["f12"] = "volume_increment";
json["devices"] = nlohmann::json::array();
return json;
}
nlohmann::json get_current_profile(void) {
if (json_.is_object() && json_["profiles"].is_array()) {
for (auto&& profile : json_["profiles"]) {
if (profile.is_object() && profile["selected"]) {
return profile;
}
}
}
return get_default_profile();
}
std::vector<std::pair<krbn::key_code, krbn::key_code>> get_key_code_pair_from_json_object(const nlohmann::json& json) {
std::vector<std::pair<krbn::key_code, krbn::key_code>> v;
if (json.is_object()) {
for (auto it = json.begin(); it != json.end(); ++it) {
std::string from = it.key();
std::string to = it.value();
auto from_key_code = krbn::types::get_key_code(from);
if (!from_key_code) {
logger_.warn("unknown key_code:{0} in {1}", from, file_path_);
continue;
}
auto to_key_code = krbn::types::get_key_code(to);
if (!to_key_code) {
logger_.warn("unknown key_code:{0} in {1}", to, file_path_);
continue;
}
v.push_back(std::make_pair(*from_key_code, *to_key_code));
}
}
return v;
}
spdlog::logger& logger_;
std::string file_path_;
bool loaded_;
nlohmann::json json_;
};
<|endoftext|>
|
<commit_before>/**********************************************************************************************/
/* Abstract class for matrix used for millepede2 operation. */
/* Author: ruben.shahoyan@cern.ch */
/* */
/**********************************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
//
#include "TClass.h"
#include "TMath.h"
#include "AliMatrixSq.h"
//
using namespace std;
ClassImp(AliMatrixSq)
AliMatrixSq & AliMatrixSq::operator=(const AliMatrixSq &src)
{
// = operator
if (this == &src) return *this;
TMatrixDBase::operator=(src);
fSymmetric = src.fSymmetric;
}
//___________________________________________________________
void AliMatrixSq::MultiplyByVec(const Double_t *vecIn,Double_t *vecOut) const
{
// fill vecOut by matrix*vecIn
// vector should be of the same size as the matrix
for (int i=GetSize();i--;) {
vecOut[i] = 0.0;
for (int j=GetSize();j--;) vecOut[i] += vecIn[j]*(*this)(i,j);
}
//
}
//___________________________________________________________
void AliMatrixSq::PrintCOO() const
{
// print matrix in COO sparse format
//
// get number of non-zero elements
int nnz = 0;
int sz = GetSize();
for (int ir=0;ir<sz;ir++) for (int ic=0;ic<sz;ic++) if (Query(ir,ic)!=0) nnz++;
//
printf("%d %d %d\n",sz,sz,nnz);
double vl;
for (int ir=0;ir<sz;ir++) for (int ic=0;ic<sz;ic++) if ((vl=Query(ir,ic))!=0) printf("%d %d %f\n",ir,ic,vl);
//
}
<commit_msg>Coverity fix<commit_after>/**********************************************************************************************/
/* Abstract class for matrix used for millepede2 operation. */
/* Author: ruben.shahoyan@cern.ch */
/* */
/**********************************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
//
#include "TClass.h"
#include "TMath.h"
#include "AliMatrixSq.h"
//
using namespace std;
ClassImp(AliMatrixSq)
AliMatrixSq & AliMatrixSq::operator=(const AliMatrixSq &src)
{
// = operator
if (this == &src) return *this;
TMatrixDBase::operator=(src);
fSymmetric = src.fSymmetric;
return *this;
}
//___________________________________________________________
void AliMatrixSq::MultiplyByVec(const Double_t *vecIn,Double_t *vecOut) const
{
// fill vecOut by matrix*vecIn
// vector should be of the same size as the matrix
for (int i=GetSize();i--;) {
vecOut[i] = 0.0;
for (int j=GetSize();j--;) vecOut[i] += vecIn[j]*(*this)(i,j);
}
//
}
//___________________________________________________________
void AliMatrixSq::PrintCOO() const
{
// print matrix in COO sparse format
//
// get number of non-zero elements
int nnz = 0;
int sz = GetSize();
for (int ir=0;ir<sz;ir++) for (int ic=0;ic<sz;ic++) if (Query(ir,ic)!=0) nnz++;
//
printf("%d %d %d\n",sz,sz,nnz);
double vl;
for (int ir=0;ir<sz;ir++) for (int ic=0;ic<sz;ic++) if ((vl=Query(ir,ic))!=0) printf("%d %d %f\n",ir,ic,vl);
//
}
<|endoftext|>
|
<commit_before>/*
* (C) 2017 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/mem_ops.h>
#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
#include <botan/locking_allocator.h>
#endif
namespace Botan {
void* allocate_memory(size_t elems, size_t elem_size)
{
#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
if(void* p = mlock_allocator::instance().allocate(elems, elem_size))
return p;
#endif
void* ptr = std::calloc(elems, elem_size);
if(!ptr)
throw std::bad_alloc();
return ptr;
}
void deallocate_memory(void* p, size_t elems, size_t elem_size)
{
if(p == nullptr)
return;
secure_scrub_memory(p, elems * elem_size);
#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
if(mlock_allocator::instance().deallocate(p, elems, elem_size))
return;
#endif
std::free(p);
}
bool constant_time_compare(const uint8_t x[],
const uint8_t y[],
size_t len)
{
volatile uint8_t difference = 0;
for(size_t i = 0; i != len; ++i)
difference |= (x[i] ^ y[i]);
return difference == 0;
}
void xor_buf(uint8_t x[],
const uint8_t y[],
size_t len)
{
while(len >= 16)
{
x[0] ^= y[0];
x[1] ^= y[1];
x[2] ^= y[2];
x[3] ^= y[3];
x[4] ^= y[4];
x[5] ^= y[5];
x[6] ^= y[6];
x[7] ^= y[7];
x[8] ^= y[8];
x[9] ^= y[9];
x[10] ^= y[10];
x[11] ^= y[11];
x[12] ^= y[12];
x[13] ^= y[13];
x[14] ^= y[14];
x[15] ^= y[15];
x += 16; y += 16; len -= 16;
}
for(size_t i = 0; i != len; ++i)
{
x[i] ^= y[i];
}
}
void xor_buf(uint8_t out[],
const uint8_t in[],
const uint8_t in2[],
size_t length)
{
while(length >= 16)
{
out[0] = in[0] ^ in2[0];
out[1] = in[1] ^ in2[1];
out[2] = in[2] ^ in2[2];
out[3] = in[3] ^ in2[3];
out[4] = in[4] ^ in2[4];
out[5] = in[5] ^ in2[5];
out[6] = in[6] ^ in2[6];
out[7] = in[7] ^ in2[7];
out[8] = in[8] ^ in2[8];
out[9] = in[9] ^ in2[9];
out[10] = in[10] ^ in2[10];
out[11] = in[11] ^ in2[11];
out[12] = in[12] ^ in2[12];
out[13] = in[13] ^ in2[13];
out[14] = in[14] ^ in2[14];
out[15] = in[15] ^ in2[15];
in += 16; in2 += 16; out += 16; length -= 16;
}
for(size_t i = 0; i != length; ++i)
out[i] = in[i] ^ in2[i];
}
}
<commit_msg>Missing include, noticed by OS X<commit_after>/*
* (C) 2017 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/mem_ops.h>
#include <cstdlib>
#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
#include <botan/locking_allocator.h>
#endif
namespace Botan {
void* allocate_memory(size_t elems, size_t elem_size)
{
#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
if(void* p = mlock_allocator::instance().allocate(elems, elem_size))
return p;
#endif
void* ptr = std::calloc(elems, elem_size);
if(!ptr)
throw std::bad_alloc();
return ptr;
}
void deallocate_memory(void* p, size_t elems, size_t elem_size)
{
if(p == nullptr)
return;
secure_scrub_memory(p, elems * elem_size);
#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
if(mlock_allocator::instance().deallocate(p, elems, elem_size))
return;
#endif
std::free(p);
}
bool constant_time_compare(const uint8_t x[],
const uint8_t y[],
size_t len)
{
volatile uint8_t difference = 0;
for(size_t i = 0; i != len; ++i)
difference |= (x[i] ^ y[i]);
return difference == 0;
}
void xor_buf(uint8_t x[],
const uint8_t y[],
size_t len)
{
while(len >= 16)
{
x[0] ^= y[0];
x[1] ^= y[1];
x[2] ^= y[2];
x[3] ^= y[3];
x[4] ^= y[4];
x[5] ^= y[5];
x[6] ^= y[6];
x[7] ^= y[7];
x[8] ^= y[8];
x[9] ^= y[9];
x[10] ^= y[10];
x[11] ^= y[11];
x[12] ^= y[12];
x[13] ^= y[13];
x[14] ^= y[14];
x[15] ^= y[15];
x += 16; y += 16; len -= 16;
}
for(size_t i = 0; i != len; ++i)
{
x[i] ^= y[i];
}
}
void xor_buf(uint8_t out[],
const uint8_t in[],
const uint8_t in2[],
size_t length)
{
while(length >= 16)
{
out[0] = in[0] ^ in2[0];
out[1] = in[1] ^ in2[1];
out[2] = in[2] ^ in2[2];
out[3] = in[3] ^ in2[3];
out[4] = in[4] ^ in2[4];
out[5] = in[5] ^ in2[5];
out[6] = in[6] ^ in2[6];
out[7] = in[7] ^ in2[7];
out[8] = in[8] ^ in2[8];
out[9] = in[9] ^ in2[9];
out[10] = in[10] ^ in2[10];
out[11] = in[11] ^ in2[11];
out[12] = in[12] ^ in2[12];
out[13] = in[13] ^ in2[13];
out[14] = in[14] ^ in2[14];
out[15] = in[15] ^ in2[15];
in += 16; in2 += 16; out += 16; length -= 16;
}
for(size_t i = 0; i != length; ++i)
out[i] = in[i] ^ in2[i];
}
}
<|endoftext|>
|
<commit_before>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2011 Heiko Strathmann
* Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
*/
#include <shogun/base/ParameterMap.h>
#include <shogun/base/Parameter.h>
#include <shogun/mathematics/Math.h>
using namespace shogun;
SGParamInfo::SGParamInfo()
{
init();
}
SGParamInfo::SGParamInfo(const SGParamInfo& orig)
{
init();
/* copy name */
m_name=strdup(orig.m_name);
m_ctype=orig.m_ctype;
m_stype=orig.m_stype;
m_ptype=orig.m_ptype;
m_param_version=orig.m_param_version;
}
SGParamInfo::SGParamInfo(const char* name, EContainerType ctype,
EStructType stype, EPrimitiveType ptype, int32_t param_version)
{
init();
/* copy name */
m_name=strdup(name);
m_ctype=ctype;
m_stype=stype;
m_ptype=ptype;
m_param_version=param_version;
}
SGParamInfo::SGParamInfo(const TParameter* param, int32_t param_version)
{
init();
/* copy name */
m_name=strdup(param->m_name);
TSGDataType type=param->m_datatype;
m_ctype=type.m_ctype;
m_stype=type.m_stype;
m_ptype=type.m_ptype;
m_param_version=param_version;
}
SGParamInfo::~SGParamInfo()
{
SG_FREE(m_name);
}
char* SGParamInfo::to_string() const
{
char* buffer=SG_MALLOC(char, 200);
strcpy(buffer, "SGParamInfo with: ");
strcat(buffer, "name=\"");
strcat(buffer, m_name);
strcat(buffer, "\", type=");
TSGDataType t(m_ctype, m_stype, m_ptype);
index_t l=100;
char* b=SG_MALLOC(char, l);
t.to_string(b, l);
strcat(buffer, b);
SG_FREE(b);
b=SG_MALLOC(char, 10);
sprintf(b, "%d", m_param_version);
strcat(buffer, ", version=");
strcat(buffer, b);
SG_FREE(b);
return buffer;
}
void SGParamInfo::print_param_info()
{
char* s=to_string();
SG_SPRINT("%s\n", s);
SG_FREE(s);
}
SGParamInfo* SGParamInfo::duplicate() const
{
return new SGParamInfo(m_name, m_ctype, m_stype, m_ptype, m_param_version);
}
void SGParamInfo::init()
{
m_name=NULL;
m_ctype=(EContainerType) -1;
m_stype=(EStructType) -1;
m_ptype=(EPrimitiveType) -1;
m_param_version=-1;
}
bool SGParamInfo::operator==(const SGParamInfo& other) const
{
bool result=true;
result&=!strcmp(m_name, other.m_name);
result&=m_ctype==other.m_ctype;
result&=m_stype==other.m_stype;
result&=m_ptype==other.m_ptype;
result&=m_param_version==other.m_param_version;
return result;
}
bool SGParamInfo::operator<(const SGParamInfo& other) const
{
int32_t result=strcmp(m_name, other.m_name);
if (result==0)
{
if (m_param_version==other.m_param_version)
{
if (m_ctype==other.m_ctype)
{
if (m_stype==other.m_stype)
{
if (m_ptype==other.m_ptype)
{
return false;
}
else
return m_ptype<other.m_ptype;
}
else
return m_stype<other.m_stype;
}
else
return m_ctype<other.m_ctype;
}
else
return m_param_version<other.m_param_version;
}
else
return result<0;
}
bool SGParamInfo::operator>(const SGParamInfo& other) const
{
int32_t result=strcmp(m_name, other.m_name);
if (result==0)
{
if (m_param_version==other.m_param_version)
{
if (m_ctype==other.m_ctype)
{
if (m_stype==other.m_stype)
{
if (m_ptype==other.m_ptype)
{
return false;
}
else
return m_ptype>other.m_ptype;
}
else
return m_stype>other.m_stype;
}
else
return m_ctype>other.m_ctype;
}
else
return m_param_version>other.m_param_version;
}
else
return result>0;
}
ParameterMapElement::ParameterMapElement()
{
init();
}
ParameterMapElement::ParameterMapElement(SGParamInfo* key,
SGParamInfo* value)
{
init();
m_key=key;
m_value=value;
}
ParameterMapElement::~ParameterMapElement()
{
delete m_key;
delete m_value;
}
bool ParameterMapElement::operator==(const ParameterMapElement& other) const
{
return *m_key==*other.m_key;
}
bool ParameterMapElement::operator<(const ParameterMapElement& other) const
{
return *m_key<*other.m_key;
}
bool ParameterMapElement::operator>(const ParameterMapElement& other) const
{
return *m_key>*other.m_key;
}
void ParameterMapElement::init()
{
m_key=NULL;
m_value=NULL;
}
ParameterMap::ParameterMap()
{
init();
}
void ParameterMap::init()
{
m_finalized=false;
}
ParameterMap::~ParameterMap()
{
for (index_t i=0; i<m_map_elements.get_num_elements(); ++i)
delete m_map_elements[i];
}
void ParameterMap::put(SGParamInfo* key, SGParamInfo* value)
{
// if (key->m_ptype==PT_SGOBJECT || value->m_ptype==PT_SGOBJECT)
// {
// SG_SPRINT("Parameter maps for CSGObjects are not yet supported\n");
// SG_SNOTIMPLEMENTED;
// }
/* assert that versions do differ exactly one */
if(key->m_param_version-value->m_param_version!=1)
{
char* s=key->to_string();
char* t=value->to_string();
SG_SERROR("Versions of parameter mappings from \"%s\" to \"%s\" have to"
" differ exactly one\n", s, t);
SG_FREE(s);
SG_FREE(t);
}
m_map_elements.append_element(new ParameterMapElement(key, value));
m_finalized=false;
}
SGParamInfo* ParameterMap::get(SGParamInfo* key) const
{
index_t num_elements=m_map_elements.get_num_elements();
/* check if underlying array is sorted */
if (!m_finalized && num_elements>1)
SG_SERROR("Call finalize_map() before calling get()\n");
/* do binary search in array of pointers */
/* dummy element for searching */
ParameterMapElement* dummy=new ParameterMapElement(key->duplicate(),
key->duplicate());
index_t index=CMath::binary_search<ParameterMapElement> (
m_map_elements.get_array(), num_elements, dummy);
delete dummy;
if (index==-1)
return NULL;
ParameterMapElement* element=m_map_elements.get_element(index);
SGParamInfo* value=element->m_value;
return value;
}
void ParameterMap::finalize_map()
{
/* sort underlying array */
CMath::qsort<ParameterMapElement> (m_map_elements.get_array(),
m_map_elements.get_num_elements());
/* ensure that there are no duplicate keys */
if (m_map_elements.get_num_elements()>1)
{
for (index_t i=1; i<m_map_elements.get_num_elements(); ++i)
{
SGParamInfo* key1=m_map_elements.get_element(i-1)->m_key;
SGParamInfo* key2=m_map_elements.get_element(i)->m_key;
if (*key1==*key2)
SG_SERROR("ParameterMap::finalize_map(): duplicate key!\n");
}
}
m_finalized=true;
}
void ParameterMap::print_map()
{
for (index_t i=0; i< m_map_elements.get_num_elements(); ++i)
{
ParameterMapElement* current=m_map_elements[i];
SG_SPRINT("%d\n", i);
SG_SPRINT("key: ");
current->m_key->print_param_info();
SG_SPRINT("value: ");
current->m_value->print_param_info();
}
}
<commit_msg>white space changes<commit_after>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2011 Heiko Strathmann
* Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
*/
#include <shogun/base/ParameterMap.h>
#include <shogun/base/Parameter.h>
#include <shogun/mathematics/Math.h>
using namespace shogun;
SGParamInfo::SGParamInfo()
{
init();
}
SGParamInfo::SGParamInfo(const SGParamInfo& orig)
{
init();
/* copy name */
m_name=strdup(orig.m_name);
m_ctype=orig.m_ctype;
m_stype=orig.m_stype;
m_ptype=orig.m_ptype;
m_param_version=orig.m_param_version;
}
SGParamInfo::SGParamInfo(const char* name, EContainerType ctype,
EStructType stype, EPrimitiveType ptype, int32_t param_version)
{
init();
/* copy name */
m_name=strdup(name);
m_ctype=ctype;
m_stype=stype;
m_ptype=ptype;
m_param_version=param_version;
}
SGParamInfo::SGParamInfo(const TParameter* param, int32_t param_version)
{
init();
/* copy name */
m_name=strdup(param->m_name);
TSGDataType type=param->m_datatype;
m_ctype=type.m_ctype;
m_stype=type.m_stype;
m_ptype=type.m_ptype;
m_param_version=param_version;
}
SGParamInfo::~SGParamInfo()
{
SG_FREE(m_name);
}
char* SGParamInfo::to_string() const
{
char* buffer=SG_MALLOC(char, 200);
strcpy(buffer, "SGParamInfo with: ");
strcat(buffer, "name=\"");
strcat(buffer, m_name);
strcat(buffer, "\", type=");
TSGDataType t(m_ctype, m_stype, m_ptype);
index_t l=100;
char* b=SG_MALLOC(char, l);
t.to_string(b, l);
strcat(buffer, b);
SG_FREE(b);
b=SG_MALLOC(char, 10);
sprintf(b, "%d", m_param_version);
strcat(buffer, ", version=");
strcat(buffer, b);
SG_FREE(b);
return buffer;
}
void SGParamInfo::print_param_info()
{
char* s=to_string();
SG_SPRINT("%s\n", s);
SG_FREE(s);
}
SGParamInfo* SGParamInfo::duplicate() const
{
return new SGParamInfo(m_name, m_ctype, m_stype, m_ptype, m_param_version);
}
void SGParamInfo::init()
{
m_name=NULL;
m_ctype=(EContainerType) -1;
m_stype=(EStructType) -1;
m_ptype=(EPrimitiveType) -1;
m_param_version=-1;
}
bool SGParamInfo::operator==(const SGParamInfo& other) const
{
bool result=true;
result&=!strcmp(m_name, other.m_name);
result&=m_ctype==other.m_ctype;
result&=m_stype==other.m_stype;
result&=m_ptype==other.m_ptype;
result&=m_param_version==other.m_param_version;
return result;
}
bool SGParamInfo::operator<(const SGParamInfo& other) const
{
int32_t result=strcmp(m_name, other.m_name);
if (result==0)
{
if (m_param_version==other.m_param_version)
{
if (m_ctype==other.m_ctype)
{
if (m_stype==other.m_stype)
{
if (m_ptype==other.m_ptype)
{
return false;
}
else
return m_ptype<other.m_ptype;
}
else
return m_stype<other.m_stype;
}
else
return m_ctype<other.m_ctype;
}
else
return m_param_version<other.m_param_version;
}
else
return result<0;
}
bool SGParamInfo::operator>(const SGParamInfo& other) const
{
int32_t result=strcmp(m_name, other.m_name);
if (result==0)
{
if (m_param_version==other.m_param_version)
{
if (m_ctype==other.m_ctype)
{
if (m_stype==other.m_stype)
{
if (m_ptype==other.m_ptype)
{
return false;
}
else
return m_ptype>other.m_ptype;
}
else
return m_stype>other.m_stype;
}
else
return m_ctype>other.m_ctype;
}
else
return m_param_version>other.m_param_version;
}
else
return result>0;
}
ParameterMapElement::ParameterMapElement()
{
init();
}
ParameterMapElement::ParameterMapElement(SGParamInfo* key,
SGParamInfo* value)
{
init();
m_key=key;
m_value=value;
}
ParameterMapElement::~ParameterMapElement()
{
delete m_key;
delete m_value;
}
bool ParameterMapElement::operator==(const ParameterMapElement& other) const
{
return *m_key==*other.m_key;
}
bool ParameterMapElement::operator<(const ParameterMapElement& other) const
{
return *m_key<*other.m_key;
}
bool ParameterMapElement::operator>(const ParameterMapElement& other) const
{
return *m_key>*other.m_key;
}
void ParameterMapElement::init()
{
m_key=NULL;
m_value=NULL;
}
ParameterMap::ParameterMap()
{
init();
}
void ParameterMap::init()
{
m_finalized=false;
}
ParameterMap::~ParameterMap()
{
for (index_t i=0; i<m_map_elements.get_num_elements(); ++i)
delete m_map_elements[i];
}
void ParameterMap::put(SGParamInfo* key, SGParamInfo* value)
{
// if (key->m_ptype==PT_SGOBJECT || value->m_ptype==PT_SGOBJECT)
// {
// SG_SPRINT("Parameter maps for CSGObjects are not yet supported\n");
// SG_SNOTIMPLEMENTED;
// }
/* assert that versions do differ exactly one */
if(key->m_param_version-value->m_param_version!=1)
{
char* s=key->to_string();
char* t=value->to_string();
SG_SERROR("Versions of parameter mappings from \"%s\" to \"%s\" have to"
" differ exactly one\n", s, t);
SG_FREE(s);
SG_FREE(t);
}
m_map_elements.append_element(new ParameterMapElement(key, value));
m_finalized=false;
}
SGParamInfo* ParameterMap::get(SGParamInfo* key) const
{
index_t num_elements=m_map_elements.get_num_elements();
/* check if underlying array is sorted */
if (!m_finalized && num_elements>1)
SG_SERROR("Call finalize_map() before calling get()\n");
/* do binary search in array of pointers */
/* dummy element for searching */
ParameterMapElement* dummy=new ParameterMapElement(key->duplicate(),
key->duplicate());
index_t index=CMath::binary_search<ParameterMapElement> (
m_map_elements.get_array(), num_elements, dummy);
delete dummy;
if (index==-1)
return NULL;
ParameterMapElement* element=m_map_elements.get_element(index);
SGParamInfo* value=element->m_value;
return value;
}
void ParameterMap::finalize_map()
{
/* sort underlying array */
CMath::qsort<ParameterMapElement> (m_map_elements.get_array(),
m_map_elements.get_num_elements());
/* ensure that there are no duplicate keys */
if (m_map_elements.get_num_elements()>1)
{
for (index_t i=1; i<m_map_elements.get_num_elements(); ++i)
{
SGParamInfo* key1=m_map_elements.get_element(i-1)->m_key;
SGParamInfo* key2=m_map_elements.get_element(i)->m_key;
if (*key1==*key2)
SG_SERROR("ParameterMap::finalize_map(): duplicate key!\n");
}
}
m_finalized=true;
}
void ParameterMap::print_map()
{
for (index_t i=0; i< m_map_elements.get_num_elements(); ++i)
{
ParameterMapElement* current=m_map_elements[i];
SG_SPRINT("%d\n", i);
SG_SPRINT("key: ");
current->m_key->print_param_info();
SG_SPRINT("value: ");
current->m_value->print_param_info();
}
}
<|endoftext|>
|
<commit_before>/*
* X.509 SIGNED Object
* (C) 1999-2007 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/x509_obj.h>
#include <botan/pubkey.h>
#include <botan/oids.h>
#include <botan/der_enc.h>
#include <botan/ber_dec.h>
#include <botan/parsing.h>
#include <botan/pem.h>
#include <algorithm>
namespace Botan {
namespace {
struct Pss_params
{
AlgorithmIdentifier hash_algo;
AlgorithmIdentifier mask_gen_algo;
AlgorithmIdentifier mask_gen_hash; // redundant: decoded mask_gen_algo.parameters
size_t salt_len;
size_t trailer_field;
};
Pss_params decode_pss_params(const std::vector<uint8_t>& encoded_pss_params)
{
Pss_params pss_parameter;
BER_Decoder(encoded_pss_params)
.start_cons(SEQUENCE)
.decode_optional(pss_parameter.hash_algo, ASN1_Tag(0), PRIVATE, AlgorithmIdentifier("SHA-160",
AlgorithmIdentifier::USE_NULL_PARAM))
.decode_optional(pss_parameter.mask_gen_algo, ASN1_Tag(1), PRIVATE,
AlgorithmIdentifier("MGF1", DER_Encoder().encode(AlgorithmIdentifier("SHA-160",
AlgorithmIdentifier::USE_NULL_PARAM)).get_contents_unlocked()))
.decode_optional(pss_parameter.salt_len, ASN1_Tag(2), PRIVATE, size_t(20))
.decode_optional(pss_parameter.trailer_field, ASN1_Tag(3), PRIVATE, size_t(1))
.end_cons();
BER_Decoder(pss_parameter.mask_gen_algo.parameters).decode(pss_parameter.mask_gen_hash);
return pss_parameter;
}
}
/*
* Create a generic X.509 object
*/
X509_Object::X509_Object(DataSource& stream, const std::string& labels)
{
init(stream, labels);
}
#if defined(BOTAN_TARGET_OS_HAS_FILESYSTEM)
/*
* Create a generic X.509 object
*/
X509_Object::X509_Object(const std::string& file, const std::string& labels)
{
DataSource_Stream stream(file, true);
init(stream, labels);
}
#endif
/*
* Create a generic X.509 object
*/
X509_Object::X509_Object(const std::vector<uint8_t>& vec, const std::string& labels)
{
DataSource_Memory stream(vec.data(), vec.size());
init(stream, labels);
}
/*
* Read a PEM or BER X.509 object
*/
void X509_Object::init(DataSource& in, const std::string& labels)
{
m_PEM_labels_allowed = split_on(labels, '/');
if(m_PEM_labels_allowed.size() < 1)
throw Invalid_Argument("Bad labels argument to X509_Object");
m_PEM_label_pref = m_PEM_labels_allowed[0];
std::sort(m_PEM_labels_allowed.begin(), m_PEM_labels_allowed.end());
try {
if(ASN1::maybe_BER(in) && !PEM_Code::matches(in))
{
BER_Decoder dec(in);
decode_from(dec);
}
else
{
std::string got_label;
DataSource_Memory ber(PEM_Code::decode(in, got_label));
if(!std::binary_search(m_PEM_labels_allowed.begin(),
m_PEM_labels_allowed.end(), got_label))
throw Decoding_Error("Invalid PEM label: " + got_label);
BER_Decoder dec(ber);
decode_from(dec);
}
}
catch(Decoding_Error& e)
{
throw Decoding_Error(m_PEM_label_pref + " decoding failed: " + e.what());
}
}
void X509_Object::encode_into(DER_Encoder& to) const
{
to.start_cons(SEQUENCE)
.start_cons(SEQUENCE)
.raw_bytes(signed_body())
.end_cons()
.encode(signature_algorithm())
.encode(signature(), BIT_STRING)
.end_cons();
}
/*
* Read a BER encoded X.509 object
*/
void X509_Object::decode_from(BER_Decoder& from)
{
from.start_cons(SEQUENCE)
.start_cons(SEQUENCE)
.raw_bytes(m_tbs_bits)
.end_cons()
.decode(m_sig_algo)
.decode(m_sig, BIT_STRING)
.end_cons();
}
/*
* Return a BER encoded X.509 object
*/
std::vector<uint8_t> X509_Object::BER_encode() const
{
DER_Encoder der;
encode_into(der);
return der.get_contents_unlocked();
}
/*
* Return a PEM encoded X.509 object
*/
std::string X509_Object::PEM_encode() const
{
return PEM_Code::encode(BER_encode(), m_PEM_label_pref);
}
/*
* Return the TBS data
*/
std::vector<uint8_t> X509_Object::tbs_data() const
{
return ASN1::put_in_sequence(m_tbs_bits);
}
/*
* Return the hash used in generating the signature
*/
std::string X509_Object::hash_used_for_signature() const
{
const OID oid = m_sig_algo.oid;
std::vector<std::string> sig_info = split_on(OIDS::lookup(oid), '/');
if(sig_info.size() != 2)
throw Internal_Error("Invalid name format found for " +
oid.as_string());
if(sig_info[1] == "EMSA4")
{
return OIDS::lookup(decode_pss_params(signature_algorithm().parameters).hash_algo.oid);
}
else
{
std::vector<std::string> pad_and_hash =
parse_algorithm_name(sig_info[1]);
if(pad_and_hash.size() != 2)
{
throw Internal_Error("Invalid name format " + sig_info[1]);
}
return pad_and_hash[1];
}
}
/*
* Check the signature on an object
*/
bool X509_Object::check_signature(const Public_Key* pub_key) const
{
if(!pub_key)
throw Exception("No key provided for " + m_PEM_label_pref + " signature check");
std::unique_ptr<const Public_Key> key(pub_key);
return check_signature(*key);
}
/*
* Check the signature on an object
*/
bool X509_Object::check_signature(const Public_Key& pub_key) const
{
try {
std::vector<std::string> sig_info =
split_on(OIDS::lookup(m_sig_algo.oid), '/');
if(sig_info.size() != 2 || sig_info[0] != pub_key.algo_name())
return false;
std::string padding = sig_info[1];
Signature_Format format =
(pub_key.message_parts() >= 2) ? DER_SEQUENCE : IEEE_1363;
if(padding == "EMSA4")
{
// "MUST contain RSASSA-PSS-params"
if(signature_algorithm().parameters.empty())
{
return false;
}
Pss_params pss_parameter = decode_pss_params(signature_algorithm().parameters);
// hash_algo must be SHA1, SHA2-224, SHA2-256, SHA2-384 or SHA2-512
std::string hash_algo = OIDS::lookup(pss_parameter.hash_algo.oid);
if(hash_algo != "SHA-160" && hash_algo != "SHA-224" && hash_algo != "SHA-256" && hash_algo != "SHA-384"
&& hash_algo != "SHA-512")
{
return false;
}
std::string mgf_algo = OIDS::lookup(pss_parameter.mask_gen_algo.oid);
if(mgf_algo != "MGF1")
{
return false;
}
// For MGF1, it is strongly RECOMMENDED that the underlying hash function be the same as the one identified by hashAlgorithm
// Must be SHA1, SHA2-224, SHA2-256, SHA2-384 or SHA2-512
if(pss_parameter.mask_gen_hash.oid != pss_parameter.hash_algo.oid)
{
return false;
}
if(pss_parameter.trailer_field != 1)
{
return false;
}
padding += "(" + hash_algo;
padding += "," + mgf_algo;
padding += "," + std::to_string(pss_parameter.salt_len) +
")"; // salt_len is actually not used for verification. Length is inferred from the signature
}
PK_Verifier verifier(pub_key, padding, format);
return verifier.verify_message(tbs_data(), signature());
}
catch(std::exception&)
{
return false;
}
}
/*
* Apply the X.509 SIGNED macro
*/
std::vector<uint8_t> X509_Object::make_signed(PK_Signer* signer,
RandomNumberGenerator& rng,
const AlgorithmIdentifier& algo,
const secure_vector<uint8_t>& tbs_bits)
{
return DER_Encoder()
.start_cons(SEQUENCE)
.raw_bytes(tbs_bits)
.encode(algo)
.encode(signer->sign_message(tbs_bits, rng), BIT_STRING)
.end_cons()
.get_contents_unlocked();
}
/*
* Try to decode the actual information
*/
void X509_Object::do_decode()
{
try {
force_decode();
}
catch(Decoding_Error& e)
{
throw Decoding_Error(m_PEM_label_pref + " decoding failed (" +
e.what() + ")");
}
catch(Invalid_Argument& e)
{
throw Decoding_Error(m_PEM_label_pref + " decoding failed (" +
e.what() + ")");
}
}
}
<commit_msg>Use new Decoding_Error constructor<commit_after>/*
* X.509 SIGNED Object
* (C) 1999-2007 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/x509_obj.h>
#include <botan/pubkey.h>
#include <botan/oids.h>
#include <botan/der_enc.h>
#include <botan/ber_dec.h>
#include <botan/parsing.h>
#include <botan/pem.h>
#include <algorithm>
namespace Botan {
namespace {
struct Pss_params
{
AlgorithmIdentifier hash_algo;
AlgorithmIdentifier mask_gen_algo;
AlgorithmIdentifier mask_gen_hash; // redundant: decoded mask_gen_algo.parameters
size_t salt_len;
size_t trailer_field;
};
Pss_params decode_pss_params(const std::vector<uint8_t>& encoded_pss_params)
{
Pss_params pss_parameter;
BER_Decoder(encoded_pss_params)
.start_cons(SEQUENCE)
.decode_optional(pss_parameter.hash_algo, ASN1_Tag(0), PRIVATE, AlgorithmIdentifier("SHA-160",
AlgorithmIdentifier::USE_NULL_PARAM))
.decode_optional(pss_parameter.mask_gen_algo, ASN1_Tag(1), PRIVATE,
AlgorithmIdentifier("MGF1", DER_Encoder().encode(AlgorithmIdentifier("SHA-160",
AlgorithmIdentifier::USE_NULL_PARAM)).get_contents_unlocked()))
.decode_optional(pss_parameter.salt_len, ASN1_Tag(2), PRIVATE, size_t(20))
.decode_optional(pss_parameter.trailer_field, ASN1_Tag(3), PRIVATE, size_t(1))
.end_cons();
BER_Decoder(pss_parameter.mask_gen_algo.parameters).decode(pss_parameter.mask_gen_hash);
return pss_parameter;
}
}
/*
* Create a generic X.509 object
*/
X509_Object::X509_Object(DataSource& stream, const std::string& labels)
{
init(stream, labels);
}
#if defined(BOTAN_TARGET_OS_HAS_FILESYSTEM)
/*
* Create a generic X.509 object
*/
X509_Object::X509_Object(const std::string& file, const std::string& labels)
{
DataSource_Stream stream(file, true);
init(stream, labels);
}
#endif
/*
* Create a generic X.509 object
*/
X509_Object::X509_Object(const std::vector<uint8_t>& vec, const std::string& labels)
{
DataSource_Memory stream(vec.data(), vec.size());
init(stream, labels);
}
/*
* Read a PEM or BER X.509 object
*/
void X509_Object::init(DataSource& in, const std::string& labels)
{
m_PEM_labels_allowed = split_on(labels, '/');
if(m_PEM_labels_allowed.size() < 1)
throw Invalid_Argument("Bad labels argument to X509_Object");
m_PEM_label_pref = m_PEM_labels_allowed[0];
std::sort(m_PEM_labels_allowed.begin(), m_PEM_labels_allowed.end());
try {
if(ASN1::maybe_BER(in) && !PEM_Code::matches(in))
{
BER_Decoder dec(in);
decode_from(dec);
}
else
{
std::string got_label;
DataSource_Memory ber(PEM_Code::decode(in, got_label));
if(!std::binary_search(m_PEM_labels_allowed.begin(),
m_PEM_labels_allowed.end(), got_label))
throw Decoding_Error("Invalid PEM label: " + got_label);
BER_Decoder dec(ber);
decode_from(dec);
}
}
catch(Decoding_Error& e)
{
throw Decoding_Error(m_PEM_label_pref + " decoding failed: " + e.what());
}
}
void X509_Object::encode_into(DER_Encoder& to) const
{
to.start_cons(SEQUENCE)
.start_cons(SEQUENCE)
.raw_bytes(signed_body())
.end_cons()
.encode(signature_algorithm())
.encode(signature(), BIT_STRING)
.end_cons();
}
/*
* Read a BER encoded X.509 object
*/
void X509_Object::decode_from(BER_Decoder& from)
{
from.start_cons(SEQUENCE)
.start_cons(SEQUENCE)
.raw_bytes(m_tbs_bits)
.end_cons()
.decode(m_sig_algo)
.decode(m_sig, BIT_STRING)
.end_cons();
}
/*
* Return a BER encoded X.509 object
*/
std::vector<uint8_t> X509_Object::BER_encode() const
{
DER_Encoder der;
encode_into(der);
return der.get_contents_unlocked();
}
/*
* Return a PEM encoded X.509 object
*/
std::string X509_Object::PEM_encode() const
{
return PEM_Code::encode(BER_encode(), m_PEM_label_pref);
}
/*
* Return the TBS data
*/
std::vector<uint8_t> X509_Object::tbs_data() const
{
return ASN1::put_in_sequence(m_tbs_bits);
}
/*
* Return the hash used in generating the signature
*/
std::string X509_Object::hash_used_for_signature() const
{
const OID oid = m_sig_algo.oid;
std::vector<std::string> sig_info = split_on(OIDS::lookup(oid), '/');
if(sig_info.size() != 2)
throw Internal_Error("Invalid name format found for " +
oid.as_string());
if(sig_info[1] == "EMSA4")
{
return OIDS::lookup(decode_pss_params(signature_algorithm().parameters).hash_algo.oid);
}
else
{
std::vector<std::string> pad_and_hash =
parse_algorithm_name(sig_info[1]);
if(pad_and_hash.size() != 2)
{
throw Internal_Error("Invalid name format " + sig_info[1]);
}
return pad_and_hash[1];
}
}
/*
* Check the signature on an object
*/
bool X509_Object::check_signature(const Public_Key* pub_key) const
{
if(!pub_key)
throw Exception("No key provided for " + m_PEM_label_pref + " signature check");
std::unique_ptr<const Public_Key> key(pub_key);
return check_signature(*key);
}
/*
* Check the signature on an object
*/
bool X509_Object::check_signature(const Public_Key& pub_key) const
{
try {
std::vector<std::string> sig_info =
split_on(OIDS::lookup(m_sig_algo.oid), '/');
if(sig_info.size() != 2 || sig_info[0] != pub_key.algo_name())
return false;
std::string padding = sig_info[1];
Signature_Format format =
(pub_key.message_parts() >= 2) ? DER_SEQUENCE : IEEE_1363;
if(padding == "EMSA4")
{
// "MUST contain RSASSA-PSS-params"
if(signature_algorithm().parameters.empty())
{
return false;
}
Pss_params pss_parameter = decode_pss_params(signature_algorithm().parameters);
// hash_algo must be SHA1, SHA2-224, SHA2-256, SHA2-384 or SHA2-512
std::string hash_algo = OIDS::lookup(pss_parameter.hash_algo.oid);
if(hash_algo != "SHA-160" && hash_algo != "SHA-224" && hash_algo != "SHA-256" && hash_algo != "SHA-384"
&& hash_algo != "SHA-512")
{
return false;
}
std::string mgf_algo = OIDS::lookup(pss_parameter.mask_gen_algo.oid);
if(mgf_algo != "MGF1")
{
return false;
}
// For MGF1, it is strongly RECOMMENDED that the underlying hash function be the same as the one identified by hashAlgorithm
// Must be SHA1, SHA2-224, SHA2-256, SHA2-384 or SHA2-512
if(pss_parameter.mask_gen_hash.oid != pss_parameter.hash_algo.oid)
{
return false;
}
if(pss_parameter.trailer_field != 1)
{
return false;
}
padding += "(" + hash_algo;
padding += "," + mgf_algo;
padding += "," + std::to_string(pss_parameter.salt_len) +
")"; // salt_len is actually not used for verification. Length is inferred from the signature
}
PK_Verifier verifier(pub_key, padding, format);
return verifier.verify_message(tbs_data(), signature());
}
catch(std::exception&)
{
return false;
}
}
/*
* Apply the X.509 SIGNED macro
*/
std::vector<uint8_t> X509_Object::make_signed(PK_Signer* signer,
RandomNumberGenerator& rng,
const AlgorithmIdentifier& algo,
const secure_vector<uint8_t>& tbs_bits)
{
return DER_Encoder()
.start_cons(SEQUENCE)
.raw_bytes(tbs_bits)
.encode(algo)
.encode(signer->sign_message(tbs_bits, rng), BIT_STRING)
.end_cons()
.get_contents_unlocked();
}
/*
* Try to decode the actual information
*/
void X509_Object::do_decode()
{
try {
force_decode();
}
catch(Decoding_Error& e)
{
throw Decoding_Error(m_PEM_label_pref + " decoding failed", e.what());
}
catch(Invalid_Argument& e)
{
throw Decoding_Error(m_PEM_label_pref + " decoding failed", e.what());
}
}
}
<|endoftext|>
|
<commit_before>#include "Board.h"
Board::Board() {
m_Board.reserve(9);
m_Board.assign(9,PlayerOptions::EMPTY);
}
std::vector<PlayerOptions>& Board::getBoard() {
return m_Board;
}
bool Board::isValidMove(int move) const {
if(m_Board[move] == PlayerOptions::EMPTY) {
return true;
}
return false;
}
bool Board::makeMove(GenericPlayer & player, int move) {
if(isValidMove(move)) {
m_Board[move] = player.getCallSign();
return true;
}
return false;
}
GameResults Board::Winner() {
// Michael Dawson : Begining C++ Through Game Programming
const int WINNING_ROWS[8][3] = {{0,1,2},
{3,4,5},
{6,7,8},
{0,3,6},
{1,4,7},
{2,5,8},
{0,4,8},
{2,4,6}};
for(int row=0; row < 8 ; row++) {
if ((m_Board[WINNING_ROWS[row][0]] == m_Board[WINNING_ROWS[row][1]]) &&
(m_Board[WINNING_ROWS[row][1]] == m_Board[WINNING_ROWS[row][2]])) {
if(m_Board[WINNING_ROWS[row][0]] == PlayerOptions::X)
return GameResults::X_WINS;
if(m_Board[WINNING_ROWS[row][0]] == PlayerOptions::O)
return GameResults::O_WINS;
}
}
if(std::count(m_Board.begin(),m_Board.end(),PlayerOptions::EMPTY) == 0) {
return GameResults::TIE;
}
return GameResults::NO_ONE_IS_WINNING_YET;
}
<commit_msg>alignment<commit_after>#include "Board.h"
Board::Board() {
m_Board.reserve(9);
m_Board.assign(9,PlayerOptions::EMPTY);
}
std::vector<PlayerOptions>& Board::getBoard() {
return m_Board;
}
bool Board::isValidMove(int move) const {
if(m_Board[move] == PlayerOptions::EMPTY) {
return true;
}
return false;
}
bool Board::makeMove(GenericPlayer & player, int move) {
if(isValidMove(move)) {
m_Board[move] = player.getCallSign();
return true;
}
return false;
}
GameResults Board::Winner() {
// Michael Dawson : Begining C++ Through Game Programming
const int WINNING_ROWS[8][3] = {{0,1,2},
{3,4,5},
{6,7,8},
{0,3,6},
{1,4,7},
{2,5,8},
{0,4,8},
{2,4,6}};
for(int row=0; row < 8 ; row++) {
if ((m_Board[WINNING_ROWS[row][0]] == m_Board[WINNING_ROWS[row][1]]) &&
(m_Board[WINNING_ROWS[row][1]] == m_Board[WINNING_ROWS[row][2]])) {
if(m_Board[WINNING_ROWS[row][0]] == PlayerOptions::X)
return GameResults::X_WINS;
if(m_Board[WINNING_ROWS[row][0]] == PlayerOptions::O)
return GameResults::O_WINS;
}
}
if(std::count(m_Board.begin(),m_Board.end(),PlayerOptions::EMPTY) == 0) {
return GameResults::TIE;
}
return GameResults::NO_ONE_IS_WINNING_YET;
}
<|endoftext|>
|
<commit_before>#include "cpuid.h"
#include "sanitizer_common/sanitizer_common.h"
#include "xray_defs.h"
#include "xray_interface_internal.h"
#include <atomic>
#include <cstdint>
#include <errno.h>
#include <fcntl.h>
#include <iterator>
#include <limits>
#include <tuple>
#include <unistd.h>
namespace __xray {
static std::pair<ssize_t, bool>
retryingReadSome(int Fd, char *Begin, char *End) XRAY_NEVER_INSTRUMENT {
auto BytesToRead = std::distance(Begin, End);
ssize_t BytesRead;
ssize_t TotalBytesRead = 0;
while (BytesToRead && (BytesRead = read(Fd, Begin, BytesToRead))) {
if (BytesRead == -1) {
if (errno == EINTR)
continue;
Report("Read error; errno = %d\n", errno);
return std::make_pair(TotalBytesRead, false);
}
TotalBytesRead += BytesRead;
BytesToRead -= BytesRead;
Begin += BytesRead;
}
return std::make_pair(TotalBytesRead, true);
}
static bool readValueFromFile(const char *Filename,
long long *Value) XRAY_NEVER_INSTRUMENT {
int Fd = open(Filename, O_RDONLY | O_CLOEXEC);
if (Fd == -1)
return false;
static constexpr size_t BufSize = 256;
char Line[BufSize] = {};
ssize_t BytesRead;
bool Success;
std::tie(BytesRead, Success) = retryingReadSome(Fd, Line, Line + BufSize);
if (!Success)
return false;
close(Fd);
char *End = nullptr;
long long Tmp = internal_simple_strtoll(Line, &End, 10);
bool Result = false;
if (Line[0] != '\0' && (*End == '\n' || *End == '\0')) {
*Value = Tmp;
Result = true;
}
return Result;
}
uint64_t getTSCFrequency() XRAY_NEVER_INSTRUMENT {
long long TSCFrequency = -1;
if (readValueFromFile("/sys/devices/system/cpu/cpu0/tsc_freq_khz",
&TSCFrequency)) {
TSCFrequency *= 1000;
} else if (readValueFromFile(
"/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq",
&TSCFrequency)) {
TSCFrequency *= 1000;
} else {
Report("Unable to determine CPU frequency for TSC accounting.\n");
}
return TSCFrequency == -1 ? 0 : static_cast<uint64_t>(TSCFrequency);
}
static constexpr uint8_t CallOpCode = 0xe8;
static constexpr uint16_t MovR10Seq = 0xba41;
static constexpr uint16_t Jmp9Seq = 0x09eb;
static constexpr uint8_t JmpOpCode = 0xe9;
static constexpr uint8_t RetOpCode = 0xc3;
static constexpr int64_t MinOffset{std::numeric_limits<int32_t>::min()};
static constexpr int64_t MaxOffset{std::numeric_limits<int32_t>::max()};
bool patchFunctionEntry(const bool Enable, const uint32_t FuncId,
const XRaySledEntry &Sled,
void (*Trampoline)()) XRAY_NEVER_INSTRUMENT {
// Here we do the dance of replacing the following sled:
//
// xray_sled_n:
// jmp +9
// <9 byte nop>
//
// With the following:
//
// mov r10d, <function id>
// call <relative 32bit offset to entry trampoline>
//
// We need to do this in the following order:
//
// 1. Put the function id first, 2 bytes from the start of the sled (just
// after the 2-byte jmp instruction).
// 2. Put the call opcode 6 bytes from the start of the sled.
// 3. Put the relative offset 7 bytes from the start of the sled.
// 4. Do an atomic write over the jmp instruction for the "mov r10d"
// opcode and first operand.
//
// Prerequisite is to compute the relative offset to the trampoline's address.
int64_t TrampolineOffset = reinterpret_cast<int64_t>(Trampoline) -
(static_cast<int64_t>(Sled.Address) + 11);
if (TrampolineOffset < MinOffset || TrampolineOffset > MaxOffset) {
Report("XRay Entry trampoline (%p) too far from sled (%p)\n",
Trampoline, reinterpret_cast<void *>(Sled.Address));
return false;
}
if (Enable) {
*reinterpret_cast<uint32_t *>(Sled.Address + 2) = FuncId;
*reinterpret_cast<uint8_t *>(Sled.Address + 6) = CallOpCode;
*reinterpret_cast<uint32_t *>(Sled.Address + 7) = TrampolineOffset;
std::atomic_store_explicit(
reinterpret_cast<std::atomic<uint16_t> *>(Sled.Address), MovR10Seq,
std::memory_order_release);
} else {
std::atomic_store_explicit(
reinterpret_cast<std::atomic<uint16_t> *>(Sled.Address), Jmp9Seq,
std::memory_order_release);
// FIXME: Write out the nops still?
}
return true;
}
bool patchFunctionExit(const bool Enable, const uint32_t FuncId,
const XRaySledEntry &Sled) XRAY_NEVER_INSTRUMENT {
// Here we do the dance of replacing the following sled:
//
// xray_sled_n:
// ret
// <10 byte nop>
//
// With the following:
//
// mov r10d, <function id>
// jmp <relative 32bit offset to exit trampoline>
//
// 1. Put the function id first, 2 bytes from the start of the sled (just
// after the 1-byte ret instruction).
// 2. Put the jmp opcode 6 bytes from the start of the sled.
// 3. Put the relative offset 7 bytes from the start of the sled.
// 4. Do an atomic write over the jmp instruction for the "mov r10d"
// opcode and first operand.
//
// Prerequisite is to compute the relative offset fo the
// __xray_FunctionExit function's address.
int64_t TrampolineOffset = reinterpret_cast<int64_t>(__xray_FunctionExit) -
(static_cast<int64_t>(Sled.Address) + 11);
if (TrampolineOffset < MinOffset || TrampolineOffset > MaxOffset) {
Report("XRay Exit trampoline (%p) too far from sled (%p)\n",
__xray_FunctionExit, reinterpret_cast<void *>(Sled.Address));
return false;
}
if (Enable) {
*reinterpret_cast<uint32_t *>(Sled.Address + 2) = FuncId;
*reinterpret_cast<uint8_t *>(Sled.Address + 6) = JmpOpCode;
*reinterpret_cast<uint32_t *>(Sled.Address + 7) = TrampolineOffset;
std::atomic_store_explicit(
reinterpret_cast<std::atomic<uint16_t> *>(Sled.Address), MovR10Seq,
std::memory_order_release);
} else {
std::atomic_store_explicit(
reinterpret_cast<std::atomic<uint8_t> *>(Sled.Address), RetOpCode,
std::memory_order_release);
// FIXME: Write out the nops still?
}
return true;
}
bool patchFunctionTailExit(const bool Enable, const uint32_t FuncId,
const XRaySledEntry &Sled) XRAY_NEVER_INSTRUMENT {
// Here we do the dance of replacing the tail call sled with a similar
// sequence as the entry sled, but calls the tail exit sled instead.
int64_t TrampolineOffset =
reinterpret_cast<int64_t>(__xray_FunctionTailExit) -
(static_cast<int64_t>(Sled.Address) + 11);
if (TrampolineOffset < MinOffset || TrampolineOffset > MaxOffset) {
Report("XRay Exit trampoline (%p) too far from sled (%p)\n",
__xray_FunctionExit, reinterpret_cast<void *>(Sled.Address));
return false;
}
if (Enable) {
*reinterpret_cast<uint32_t *>(Sled.Address + 2) = FuncId;
*reinterpret_cast<uint8_t *>(Sled.Address + 6) = CallOpCode;
*reinterpret_cast<uint32_t *>(Sled.Address + 7) = TrampolineOffset;
std::atomic_store_explicit(
reinterpret_cast<std::atomic<uint16_t> *>(Sled.Address), MovR10Seq,
std::memory_order_release);
} else {
std::atomic_store_explicit(
reinterpret_cast<std::atomic<uint16_t> *>(Sled.Address), Jmp9Seq,
std::memory_order_release);
// FIXME: Write out the nops still?
}
return true;
}
// We determine whether the CPU we're running on has the correct features we
// need. In x86_64 this will be rdtscp support.
bool probeRequiredCPUFeatures() XRAY_NEVER_INSTRUMENT {
unsigned int EAX, EBX, ECX, EDX;
// We check whether rdtscp support is enabled. According to the x86_64 manual,
// level should be set at 0x80000001, and we should have a look at bit 27 in
// EDX. That's 0x8000000 (or 1u << 26).
__get_cpuid(0x80000001, &EAX, &EBX, &ECX, &EDX);
if (!(EDX & (1u << 26))) {
Report("Missing rdtscp support.\n");
return false;
}
return true;
}
} // namespace __xray
<commit_msg>[XRay] [compiler-rt] Plug a file descriptor leak in a failure case.<commit_after>#include "cpuid.h"
#include "sanitizer_common/sanitizer_common.h"
#include "xray_defs.h"
#include "xray_interface_internal.h"
#include <atomic>
#include <cstdint>
#include <errno.h>
#include <fcntl.h>
#include <iterator>
#include <limits>
#include <tuple>
#include <unistd.h>
namespace __xray {
static std::pair<ssize_t, bool>
retryingReadSome(int Fd, char *Begin, char *End) XRAY_NEVER_INSTRUMENT {
auto BytesToRead = std::distance(Begin, End);
ssize_t BytesRead;
ssize_t TotalBytesRead = 0;
while (BytesToRead && (BytesRead = read(Fd, Begin, BytesToRead))) {
if (BytesRead == -1) {
if (errno == EINTR)
continue;
Report("Read error; errno = %d\n", errno);
return std::make_pair(TotalBytesRead, false);
}
TotalBytesRead += BytesRead;
BytesToRead -= BytesRead;
Begin += BytesRead;
}
return std::make_pair(TotalBytesRead, true);
}
static bool readValueFromFile(const char *Filename,
long long *Value) XRAY_NEVER_INSTRUMENT {
int Fd = open(Filename, O_RDONLY | O_CLOEXEC);
if (Fd == -1)
return false;
static constexpr size_t BufSize = 256;
char Line[BufSize] = {};
ssize_t BytesRead;
bool Success;
std::tie(BytesRead, Success) = retryingReadSome(Fd, Line, Line + BufSize);
close(Fd);
if (!Success)
return false;
char *End = nullptr;
long long Tmp = internal_simple_strtoll(Line, &End, 10);
bool Result = false;
if (Line[0] != '\0' && (*End == '\n' || *End == '\0')) {
*Value = Tmp;
Result = true;
}
return Result;
}
uint64_t getTSCFrequency() XRAY_NEVER_INSTRUMENT {
long long TSCFrequency = -1;
if (readValueFromFile("/sys/devices/system/cpu/cpu0/tsc_freq_khz",
&TSCFrequency)) {
TSCFrequency *= 1000;
} else if (readValueFromFile(
"/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq",
&TSCFrequency)) {
TSCFrequency *= 1000;
} else {
Report("Unable to determine CPU frequency for TSC accounting.\n");
}
return TSCFrequency == -1 ? 0 : static_cast<uint64_t>(TSCFrequency);
}
static constexpr uint8_t CallOpCode = 0xe8;
static constexpr uint16_t MovR10Seq = 0xba41;
static constexpr uint16_t Jmp9Seq = 0x09eb;
static constexpr uint8_t JmpOpCode = 0xe9;
static constexpr uint8_t RetOpCode = 0xc3;
static constexpr int64_t MinOffset{std::numeric_limits<int32_t>::min()};
static constexpr int64_t MaxOffset{std::numeric_limits<int32_t>::max()};
bool patchFunctionEntry(const bool Enable, const uint32_t FuncId,
const XRaySledEntry &Sled,
void (*Trampoline)()) XRAY_NEVER_INSTRUMENT {
// Here we do the dance of replacing the following sled:
//
// xray_sled_n:
// jmp +9
// <9 byte nop>
//
// With the following:
//
// mov r10d, <function id>
// call <relative 32bit offset to entry trampoline>
//
// We need to do this in the following order:
//
// 1. Put the function id first, 2 bytes from the start of the sled (just
// after the 2-byte jmp instruction).
// 2. Put the call opcode 6 bytes from the start of the sled.
// 3. Put the relative offset 7 bytes from the start of the sled.
// 4. Do an atomic write over the jmp instruction for the "mov r10d"
// opcode and first operand.
//
// Prerequisite is to compute the relative offset to the trampoline's address.
int64_t TrampolineOffset = reinterpret_cast<int64_t>(Trampoline) -
(static_cast<int64_t>(Sled.Address) + 11);
if (TrampolineOffset < MinOffset || TrampolineOffset > MaxOffset) {
Report("XRay Entry trampoline (%p) too far from sled (%p)\n",
Trampoline, reinterpret_cast<void *>(Sled.Address));
return false;
}
if (Enable) {
*reinterpret_cast<uint32_t *>(Sled.Address + 2) = FuncId;
*reinterpret_cast<uint8_t *>(Sled.Address + 6) = CallOpCode;
*reinterpret_cast<uint32_t *>(Sled.Address + 7) = TrampolineOffset;
std::atomic_store_explicit(
reinterpret_cast<std::atomic<uint16_t> *>(Sled.Address), MovR10Seq,
std::memory_order_release);
} else {
std::atomic_store_explicit(
reinterpret_cast<std::atomic<uint16_t> *>(Sled.Address), Jmp9Seq,
std::memory_order_release);
// FIXME: Write out the nops still?
}
return true;
}
bool patchFunctionExit(const bool Enable, const uint32_t FuncId,
const XRaySledEntry &Sled) XRAY_NEVER_INSTRUMENT {
// Here we do the dance of replacing the following sled:
//
// xray_sled_n:
// ret
// <10 byte nop>
//
// With the following:
//
// mov r10d, <function id>
// jmp <relative 32bit offset to exit trampoline>
//
// 1. Put the function id first, 2 bytes from the start of the sled (just
// after the 1-byte ret instruction).
// 2. Put the jmp opcode 6 bytes from the start of the sled.
// 3. Put the relative offset 7 bytes from the start of the sled.
// 4. Do an atomic write over the jmp instruction for the "mov r10d"
// opcode and first operand.
//
// Prerequisite is to compute the relative offset fo the
// __xray_FunctionExit function's address.
int64_t TrampolineOffset = reinterpret_cast<int64_t>(__xray_FunctionExit) -
(static_cast<int64_t>(Sled.Address) + 11);
if (TrampolineOffset < MinOffset || TrampolineOffset > MaxOffset) {
Report("XRay Exit trampoline (%p) too far from sled (%p)\n",
__xray_FunctionExit, reinterpret_cast<void *>(Sled.Address));
return false;
}
if (Enable) {
*reinterpret_cast<uint32_t *>(Sled.Address + 2) = FuncId;
*reinterpret_cast<uint8_t *>(Sled.Address + 6) = JmpOpCode;
*reinterpret_cast<uint32_t *>(Sled.Address + 7) = TrampolineOffset;
std::atomic_store_explicit(
reinterpret_cast<std::atomic<uint16_t> *>(Sled.Address), MovR10Seq,
std::memory_order_release);
} else {
std::atomic_store_explicit(
reinterpret_cast<std::atomic<uint8_t> *>(Sled.Address), RetOpCode,
std::memory_order_release);
// FIXME: Write out the nops still?
}
return true;
}
bool patchFunctionTailExit(const bool Enable, const uint32_t FuncId,
const XRaySledEntry &Sled) XRAY_NEVER_INSTRUMENT {
// Here we do the dance of replacing the tail call sled with a similar
// sequence as the entry sled, but calls the tail exit sled instead.
int64_t TrampolineOffset =
reinterpret_cast<int64_t>(__xray_FunctionTailExit) -
(static_cast<int64_t>(Sled.Address) + 11);
if (TrampolineOffset < MinOffset || TrampolineOffset > MaxOffset) {
Report("XRay Exit trampoline (%p) too far from sled (%p)\n",
__xray_FunctionExit, reinterpret_cast<void *>(Sled.Address));
return false;
}
if (Enable) {
*reinterpret_cast<uint32_t *>(Sled.Address + 2) = FuncId;
*reinterpret_cast<uint8_t *>(Sled.Address + 6) = CallOpCode;
*reinterpret_cast<uint32_t *>(Sled.Address + 7) = TrampolineOffset;
std::atomic_store_explicit(
reinterpret_cast<std::atomic<uint16_t> *>(Sled.Address), MovR10Seq,
std::memory_order_release);
} else {
std::atomic_store_explicit(
reinterpret_cast<std::atomic<uint16_t> *>(Sled.Address), Jmp9Seq,
std::memory_order_release);
// FIXME: Write out the nops still?
}
return true;
}
// We determine whether the CPU we're running on has the correct features we
// need. In x86_64 this will be rdtscp support.
bool probeRequiredCPUFeatures() XRAY_NEVER_INSTRUMENT {
unsigned int EAX, EBX, ECX, EDX;
// We check whether rdtscp support is enabled. According to the x86_64 manual,
// level should be set at 0x80000001, and we should have a look at bit 27 in
// EDX. That's 0x8000000 (or 1u << 26).
__get_cpuid(0x80000001, &EAX, &EBX, &ECX, &EDX);
if (!(EDX & (1u << 26))) {
Report("Missing rdtscp support.\n");
return false;
}
return true;
}
} // namespace __xray
<|endoftext|>
|
<commit_before>/*
* ti-pga2310
* github.com/kashev/ti-pga2310
*
* An Arduino / Energia Library for control of a Texas Instruments
* PGA2310 Stereo Volume Control.
*
* Kashev Dalmia - kashev.dalmia@gmail.com
*
* PGA2310.cpp
*/
#include "PGA2310.h"
PGA2310::PGA2310 (uint8_t pinCS, uint8_t pinSDATA, uint8_t pinSCLK, uint8_t pinZCEN, uint8_t pinMUTE)
{
_pinCS = pinCS;
_pinSDATA = pinSDATA;
_pinSCLK = pinSCLK;
_pinZCEN = pinZCEN;
_pinMUTE = pinMUTE;
_hard_mute = 1;
_muted = 0;
_v_left = _v_right = _pv_left = _pv_right = 0;
}
PGA2310::PGA2310 (uint8_t pinCS, uint8_t pinSDATA, uint8_t pinSCLK, uint8_t pinZCEN)
{
_pinCS = pinCS;
_pinSDATA = pinSDATA;
_pinSCLK = pinSCLK;
_pinZCEN = pinZCEN;
_hard_mute = 0;
_muted = 0;
_v_left = _v_right = _pv_left = _pv_right = 0;
}
void
PGA2310::begin (void)
{
begin(1); /* By Default, Enable Zero Crossing Detection */
}
void
begin (uint8_t zcen_enable)
{
pinMode(_pinCS, OUTPUT);
pinMode(_pinSDATA, OUTPUT);
pinMode(_pinSCLK, OUTPUT);
pinMode(_pinZCEN, OUTPUT);
if (_hard_mute)
pinMode(_pinMUTE, OUTPUT);
if (zcen_enable)
digitalWrite(_pinZCEN, HIGH);
else
digitalWrite(_pinZCEN, LOW);
}
uint8_t
PGA2310::getLeftVolume (void)
{
return _v_left;
}
uint8_t
PGA2310::getRightVolume (void)
{
return _v_right;
}
boolean
PGA2310::isMuted (void)
{
return (boolean)_muted;
}
void
PGA2310::SPIWrite (uint8_t byte)
{
for (uint8_t i = 0; i < 8; i++, byte <<= 1)
{
digitalWrite(_pinSCLK, LOW);
if (0x80 & byte)
digitalWrite(_pinSDATA, HIGH);
else
digitalWrite(_pinSDATA, LOW);
digitalWrite(_pinSCLK, HIGH);
}
}
void
PGA2310::setVolume (uint8_t left, uint8_t right)
{
if ((left > MAX_GAIN) || (right > MAX_GAIN))
return; /* don't allow gains above MAX_GAIN */
digitalWrite(_pinCS, LOW);
SPIWrite(right);
SPIWrite(left);
digitalWrite(_pinCS, HIGH);
_pv_left = _v_left; _pv_right = _v_right;
_v_left = left; _v_right = right;
if (!(_hard_mute) && (_v_left == 0) && (_v_right == 0))
_muted = 1;
}
void
PGA2310::setVolume (uint8_t vol)
{
setVolume(vol, vol);
}
void
PGA2310::restoreVolume (void)
{
uint8_t tr, tl;
digitalWrite(_pinCS, LOW);
SPIWrite(_pv_right);
SPIWrite(_pv_left);
digitalWrite(_pinCS, HIGH);
tr = _v_right; tl = _v_left;
_v_right = _pv_right; _v_left = _pv_left;
_pv_right = tr; _pv_left = pl;
}
void
PGA2310::mute (void)
{
if(_hard_mute)
digitalWrite(_pinMUTE, LOW);
else
setVolume(0, 0);
_muted = 1;
}
void
PGA2310::toggleMute (void)
{
if (_muted)
{
/* unmute */
if(_hard_mute)
digitalWrite(_pinMUTE, HIGH);
else
restoreVolume();
_muted = 0;
}
else
{
/* mute */
if(_hard_mute)
digitalWrite(_pinMUTE, LOW);
else
setVolume(0, 0);
_muted = 1;
}
}
void
PGA2310::incVolume (void)
{
uint8_t nl, nr;
if(_muted)
{
if (_hard_mute)
{
digitalWrite(_pinMUTE, HIGH);
}
_muted = 0;
}
nl = _v_left == MAX_GAIN ? MAX_GAIN : _v_left + 1;
nr = _v_right == MAX_GAIN ? MAX_GAIN : _v_right + 1;
if ((nl != _v_left) && (nr != _v_right))
{
/* minimize writes to device */
setVolume(nl, nr);
}
}
void
PGA2310::decVolume (void)
{
uint8_t nl, nr;
if(_muted)
{
if (_hard_mute)
{
digitalWrite(_pinMUTE, HIGH);
}
_muted = 0;
}
nl = _v_left == 0 ? 0 : _v_left - 1;
nr = _v_right == 0 ? 0 : _v_right - 1;
if ((nl != _v_left) && (nr != _v_right))
{
/* minimize writes to device */
setVolume(nl, nr);
}
}
<commit_msg>fixed compilation errors due to typos.<commit_after>/*
* ti-pga2310
* github.com/kashev/ti-pga2310
*
* An Arduino / Energia Library for control of a Texas Instruments
* PGA2310 Stereo Volume Control.
*
* Kashev Dalmia - kashev.dalmia@gmail.com
*
* PGA2310.cpp
*/
#include "PGA2310.h"
PGA2310::PGA2310 (uint8_t pinCS, uint8_t pinSDATA, uint8_t pinSCLK, uint8_t pinZCEN, uint8_t pinMUTE)
{
_pinCS = pinCS;
_pinSDATA = pinSDATA;
_pinSCLK = pinSCLK;
_pinZCEN = pinZCEN;
_pinMUTE = pinMUTE;
_hard_mute = 1;
_muted = 0;
_v_left = _v_right = _pv_left = _pv_right = 0;
}
PGA2310::PGA2310 (uint8_t pinCS, uint8_t pinSDATA, uint8_t pinSCLK, uint8_t pinZCEN)
{
_pinCS = pinCS;
_pinSDATA = pinSDATA;
_pinSCLK = pinSCLK;
_pinZCEN = pinZCEN;
_hard_mute = 0;
_muted = 0;
_v_left = _v_right = _pv_left = _pv_right = 0;
}
void
PGA2310::begin (void)
{
begin(1); /* By Default, Enable Zero Crossing Detection */
}
void
PGA2310::begin (uint8_t zcen_enable)
{
pinMode(_pinCS, OUTPUT);
pinMode(_pinSDATA, OUTPUT);
pinMode(_pinSCLK, OUTPUT);
pinMode(_pinZCEN, OUTPUT);
if (_hard_mute)
pinMode(_pinMUTE, OUTPUT);
if (zcen_enable)
digitalWrite(_pinZCEN, HIGH);
else
digitalWrite(_pinZCEN, LOW);
}
uint8_t
PGA2310::getLeftVolume (void)
{
return _v_left;
}
uint8_t
PGA2310::getRightVolume (void)
{
return _v_right;
}
boolean
PGA2310::isMuted (void)
{
return (boolean)_muted;
}
void
PGA2310::SPIWrite (uint8_t byte)
{
for (uint8_t i = 0; i < 8; i++, byte <<= 1)
{
digitalWrite(_pinSCLK, LOW);
if (0x80 & byte)
digitalWrite(_pinSDATA, HIGH);
else
digitalWrite(_pinSDATA, LOW);
digitalWrite(_pinSCLK, HIGH);
}
}
void
PGA2310::setVolume (uint8_t left, uint8_t right)
{
if ((left > MAX_GAIN) || (right > MAX_GAIN))
return; /* don't allow gains above MAX_GAIN */
digitalWrite(_pinCS, LOW);
SPIWrite(right);
SPIWrite(left);
digitalWrite(_pinCS, HIGH);
_pv_left = _v_left; _pv_right = _v_right;
_v_left = left; _v_right = right;
if (!(_hard_mute) && (_v_left == 0) && (_v_right == 0))
_muted = 1;
}
void
PGA2310::setVolume (uint8_t vol)
{
setVolume(vol, vol);
}
void
PGA2310::restoreVolume (void)
{
uint8_t tr, tl;
digitalWrite(_pinCS, LOW);
SPIWrite(_pv_right);
SPIWrite(_pv_left);
digitalWrite(_pinCS, HIGH);
tr = _v_right; tl = _v_left;
_v_right = _pv_right; _v_left = _pv_left;
_pv_right = tr; _pv_left = tl;
}
void
PGA2310::mute (void)
{
if(_hard_mute)
digitalWrite(_pinMUTE, LOW);
else
setVolume(0, 0);
_muted = 1;
}
void
PGA2310::toggleMute (void)
{
if (_muted)
{
/* unmute */
if(_hard_mute)
digitalWrite(_pinMUTE, HIGH);
else
restoreVolume();
_muted = 0;
}
else
{
/* mute */
if(_hard_mute)
digitalWrite(_pinMUTE, LOW);
else
setVolume(0, 0);
_muted = 1;
}
}
void
PGA2310::incVolume (void)
{
uint8_t nl, nr;
if(_muted)
{
if (_hard_mute)
{
digitalWrite(_pinMUTE, HIGH);
}
_muted = 0;
}
nl = _v_left == MAX_GAIN ? MAX_GAIN : _v_left + 1;
nr = _v_right == MAX_GAIN ? MAX_GAIN : _v_right + 1;
if ((nl != _v_left) && (nr != _v_right))
{
/* minimize writes to device */
setVolume(nl, nr);
}
}
void
PGA2310::decVolume (void)
{
uint8_t nl, nr;
if(_muted)
{
if (_hard_mute)
{
digitalWrite(_pinMUTE, HIGH);
}
_muted = 0;
}
nl = _v_left == 0 ? 0 : _v_left - 1;
nr = _v_right == 0 ? 0 : _v_right - 1;
if ((nl != _v_left) && (nr != _v_right))
{
/* minimize writes to device */
setVolume(nl, nr);
}
}
<|endoftext|>
|
<commit_before>#include <cstring>
#include <iostream>
#include <UnitTest++.h>
#include <TestReporter.h> // Part of UnitTest++
#include <tightdb.hpp>
#include <tightdb/column.hpp>
#include <tightdb/utilities.hpp>
#include <tightdb/query_engine.hpp>
#include <assert.h>
#define USE_VLD
#if defined(_MSC_VER) && defined(_DEBUG) && defined(USE_VLD)
#include "C:\\Program Files (x86)\\Visual Leak Detector\\include\\vld.h"
#endif
using namespace std;
using namespace UnitTest;
using namespace tightdb;
namespace {
struct CustomTestReporter: TestReporter {
void ReportTestStart(TestDetails const& test)
{
static_cast<void>(test);
// cerr << test.filename << ":" << test.lineNumber << ": Begin " << test.testName << "\n";
}
void ReportFailure(TestDetails const& test, char const* failure)
{
cerr << test.filename << ":" << test.lineNumber << ": error: "
"Failure in " << test.testName << ": " << failure << "\n";
}
void ReportTestFinish(TestDetails const& test, float seconds_elapsed)
{
static_cast<void>(test);
static_cast<void>(seconds_elapsed);
// cerr << test.filename << ":" << test.lineNumber << ": End\n";
}
void ReportSummary(int total_test_count, int failed_test_count, int failure_count, float seconds_elapsed)
{
if (0 < failure_count)
cerr << "FAILURE: " << failed_test_count << " "
"out of " << total_test_count << " tests failed "
"(" << failure_count << " failures).\n";
else
cerr << "Success: " << total_test_count << " tests passed.\n";
const streamsize orig_prec = cerr.precision();
cerr.precision(2);
cerr << "Test time: " << seconds_elapsed << " seconds.\n";
cerr.precision(orig_prec);
}
};
} // anonymous namespace
TIGHTDB_TABLE_3(ThreeColTable,
first, Int,
second, Float,
third, Double)
int main(int argc, char* argv[])
{
size_t match;
// Setup untyped table
Table untyped;
untyped.add_column(type_Int, "firs1");
untyped.add_column(type_Float, "second");
untyped.add_column(type_Double, "third");
untyped.add_empty_row(2);
untyped.set_int(0, 0, 20);
untyped.set_float(1, 0, 19.9f);
untyped.set_double(2, 0, 3.0);
untyped.set_int(0, 1, 20);
untyped.set_float(1, 1, 20.1f);
untyped.set_double(2, 1, 4.0);
// Setup typed table, same contents as untyped
ThreeColTable typed;
typed.add(20, 19.9f, 3.0);
typed.add(20, 20.1f, 4.0);
// Testing &&
// Left condition makes first row non-match
match = (untyped.column<float>(1) + 1 > 21 && untyped.column<double>(2) > 2).find_next();
assert(match == 1);
// Right condition makes first row a non-match
match = (untyped.column<float>(1) > 10 && untyped.column<double>(2) > 3.5).find_next();
assert(match == 1);
// Both make first row match
match = (untyped.column<float>(1) < 20 && untyped.column<double>(2) > 2).find_next();
assert(match == 0);
// Both make first row non-match
match = (untyped.column<float>(1) > 20 && untyped.column<double>(2) > 3.5).find_next();
assert(match == 1);
// Left cond match 0, right match 1
match = (untyped.column<float>(1) < 20 && untyped.column<double>(2) > 3.5).find_next();
assert(match == not_found);
// Left match 1, right match 0
match = (untyped.column<float>(1) > 20 && untyped.column<double>(2) < 3.5).find_next();
assert(match == not_found);
// Testing ||
// Left match 0
match = (untyped.column<float>(1) < 20 || untyped.column<double>(2) < 3.5).find_next();
assert(match == 0);
// Right match 0
match = (untyped.column<float>(1) > 20 || untyped.column<double>(2) < 3.5).find_next();
assert(match == 0);
// Left match 1
match = (untyped.column<float>(1) > 20 || untyped.column<double>(2) > 9.5).find_next();
assert(match == 1);
// Tons of other tests. More in test_query.cpp
Query q4 = untyped.column<float>(1) + untyped.column<int64_t>(0) > 40;
Query q5 = 20 < untyped.column<float>(1);
match = q4.expression( q5.get_expression() ).find_next();
assert(match == 1);
// Untyped, direct column addressing
Value<int64_t> uv1(1);
Columns<float> uc1 = untyped.column<float>(1);
Query q2 = uv1 <= uc1;
match = q2.find_next();
assert(match == 0);
Query q0 = uv1 <= uc1;
match = q0.find_next();
assert(match == 0);
Query q99 = uv1 <= untyped.column<float>(1);
match = q99.find_next();
assert(match == 0);
Query q8 = 1 > untyped.column<float>(1) + 5;
match = q8.find_next();
assert(match == not_found);
Query q3 = untyped.column<float>(1) + untyped.column<int64_t>(0) > 10 + untyped.column<int64_t>(0);
match = q3.find_next();
match = q2.find_next();
assert(match == 0);
// Typed, direct column addressing
Query q1 = typed.column().second + typed.column().first > 40;
match = q1.find_next();
assert(match == 1);
match = (typed.column().first + typed.column().second > 40).find_next();
assert(match == 1);
Query tq1 = typed.column().first + typed.column().second >= typed.column().first + typed.column().second;
match = tq1.find_next();
assert(match == 0);
// Typed, column objects
Columns<int64_t> t0 = typed.column().first;
Columns<float> t1 = typed.column().second;
match = (t0 + t1 > 40).find_next();
assert(match == 1);
match = q1.find_next();
assert(match == 1);
match = (untyped.column<int64_t>(0) + untyped.column<float>(1) > 40).find_next();
assert(match == 1);
match = (untyped.column<int64_t>(0) + untyped.column<float>(1) < 40).find_next();
assert(match == 0);
match = (untyped.column<float>(1) <= untyped.column<int64_t>(0)).find_next();
assert(match == 0);
match = (untyped.column<int64_t>(0) + untyped.column<float>(1) >= untyped.column<int64_t>(0) + untyped.column<float>(1)).find_next();
assert(match == 0);
// Untyped, column objects
Columns<int64_t> u0 = untyped.column<int64_t>(0);
Columns<float> u1 = untyped.column<float>(1);
match = (u0 + u1 > 40).find_next();
assert(match == 1);
// Flexible language binding style
Subexpr* first = new Columns<int64_t>(0);
Subexpr* second = new Columns<float>(1);
Subexpr* third = new Columns<double>(2);
Subexpr* constant = new Value<int64_t>(40);
Subexpr* plus = new Operator<Plus<float> >(*first, *second);
Expression *e = new Compare<Greater, float>(*plus, *constant);
// Bind table and do search
match = untyped.where().expression(e).find_next();
assert(match == 1);
Query q9 = untyped.where().expression(e);
match = q9.find_next();
assert(match == 1);
Subexpr* first2 = new Columns<int64_t>(0);
Subexpr* second2 = new Columns<float>(1);
Subexpr* third2 = new Columns<double>(2);
Subexpr* constant2 = new Value<int64_t>(40);
Subexpr* plus2 = new Operator<Plus<float> >(*first, *second);
Expression *e2 = new Compare<Greater, float>(*plus, *constant);
match = untyped.where().expression(e).expression(e2).find_next();
assert(match == 1);
Query q10 = untyped.where().expression(q9.get_expression()).expression(e2);
match = q10.find_next();
assert(match == 1);
Query tq3 = tq1;
match = tq3.find_next();
assert(match == 0);
delete e;
delete plus;
delete constant;
delete third;
delete second;
delete first;
delete e2;
delete plus2;
delete constant2;
delete third2;
delete second2;
delete first2;
CustomTestReporter reporter;
TestRunner runner(reporter);
const int res = runner.RunTestsIf(Test::GetTestList(), 0, True(), 0);
return 0;
}
// 638
// 545 568<commit_msg>main.cpp demo<commit_after>#include <cstring>
#include <iostream>
#include <UnitTest++.h>
#include <TestReporter.h> // Part of UnitTest++
#include <tightdb.hpp>
#include <tightdb/column.hpp>
#include <tightdb/utilities.hpp>
#include <tightdb/query_engine.hpp>
#include <assert.h>
#define USE_VLD
#if defined(_MSC_VER) && defined(_DEBUG) && defined(USE_VLD)
#include "C:\\Program Files (x86)\\Visual Leak Detector\\include\\vld.h"
#endif
using namespace std;
using namespace UnitTest;
using namespace tightdb;
namespace {
struct CustomTestReporter: TestReporter {
void ReportTestStart(TestDetails const& test)
{
static_cast<void>(test);
// cerr << test.filename << ":" << test.lineNumber << ": Begin " << test.testName << "\n";
}
void ReportFailure(TestDetails const& test, char const* failure)
{
cerr << test.filename << ":" << test.lineNumber << ": error: "
"Failure in " << test.testName << ": " << failure << "\n";
}
void ReportTestFinish(TestDetails const& test, float seconds_elapsed)
{
static_cast<void>(test);
static_cast<void>(seconds_elapsed);
// cerr << test.filename << ":" << test.lineNumber << ": End\n";
}
void ReportSummary(int total_test_count, int failed_test_count, int failure_count, float seconds_elapsed)
{
if (0 < failure_count)
cerr << "FAILURE: " << failed_test_count << " "
"out of " << total_test_count << " tests failed "
"(" << failure_count << " failures).\n";
else
cerr << "Success: " << total_test_count << " tests passed.\n";
const streamsize orig_prec = cerr.precision();
cerr.precision(2);
cerr << "Test time: " << seconds_elapsed << " seconds.\n";
cerr.precision(orig_prec);
}
};
} // anonymous namespace
TIGHTDB_TABLE_3(ThreeColTable,
first, Int,
second, Float,
third, Double)
int main(int argc, char* argv[])
{
size_t match;
// Setup untyped table
Table untyped;
untyped.add_column(type_Int, "firs1");
untyped.add_column(type_Float, "second");
untyped.add_column(type_Double, "third");
untyped.add_empty_row(2);
untyped.set_int(0, 0, 20);
untyped.set_float(1, 0, 19.9f);
untyped.set_double(2, 0, 3.0);
untyped.set_int(0, 1, 20);
untyped.set_float(1, 1, 20.1f);
untyped.set_double(2, 1, 4.0);
// Setup typed table, same contents as untyped
ThreeColTable typed;
typed.add(20, 19.9f, 3.0);
typed.add(20, 20.1f, 4.0);
// Small typed table test:
match = (typed.column().second + 100 > 120 && typed.column().first > 2).find_next();
assert(match == 1);
// Untyped &&
// Left condition makes first row non-match
match = (untyped.column<float>(1) + 1 > 21 && untyped.column<double>(2) > 2).find_next();
assert(match == 1);
// Right condition makes first row a non-match
match = (untyped.column<float>(1) > 10 && untyped.column<double>(2) > 3.5).find_next();
assert(match == 1);
// Both make first row match
match = (untyped.column<float>(1) < 20 && untyped.column<double>(2) > 2).find_next();
assert(match == 0);
// Both make first row non-match
match = (untyped.column<float>(1) > 20 && untyped.column<double>(2) > 3.5).find_next();
assert(match == 1);
// Left cond match 0, right match 1
match = (untyped.column<float>(1) < 20 && untyped.column<double>(2) > 3.5).find_next();
assert(match == not_found);
// Left match 1, right match 0
match = (untyped.column<float>(1) > 20 && untyped.column<double>(2) < 3.5).find_next();
assert(match == not_found);
// Untyped ||
// Left match 0
match = (untyped.column<float>(1) < 20 || untyped.column<double>(2) < 3.5).find_next();
assert(match == 0);
// Right match 0
match = (untyped.column<float>(1) > 20 || untyped.column<double>(2) < 3.5).find_next();
assert(match == 0);
// Left match 1
match = (untyped.column<float>(1) > 20 || untyped.column<double>(2) > 9.5).find_next();
assert(match == 1);
// Tons of other tests. More in test_query.cpp
Query q4 = untyped.column<float>(1) + untyped.column<int64_t>(0) > 40;
Query q5 = 20 < untyped.column<float>(1);
match = q4.expression( q5.get_expression() ).find_next();
assert(match == 1);
// Untyped, direct column addressing
Value<int64_t> uv1(1);
Columns<float> uc1 = untyped.column<float>(1);
Query q2 = uv1 <= uc1;
match = q2.find_next();
assert(match == 0);
Query q0 = uv1 <= uc1;
match = q0.find_next();
assert(match == 0);
Query q99 = uv1 <= untyped.column<float>(1);
match = q99.find_next();
assert(match == 0);
Query q8 = 1 > untyped.column<float>(1) + 5;
match = q8.find_next();
assert(match == not_found);
Query q3 = untyped.column<float>(1) + untyped.column<int64_t>(0) > 10 + untyped.column<int64_t>(0);
match = q3.find_next();
match = q2.find_next();
assert(match == 0);
// Typed, direct column addressing
Query q1 = typed.column().second + typed.column().first > 40;
match = q1.find_next();
assert(match == 1);
match = (typed.column().first + typed.column().second > 40).find_next();
assert(match == 1);
Query tq1 = typed.column().first + typed.column().second >= typed.column().first + typed.column().second;
match = tq1.find_next();
assert(match == 0);
// Typed, column objects
Columns<int64_t> t0 = typed.column().first;
Columns<float> t1 = typed.column().second;
match = (t0 + t1 > 40).find_next();
assert(match == 1);
match = q1.find_next();
assert(match == 1);
match = (untyped.column<int64_t>(0) + untyped.column<float>(1) > 40).find_next();
assert(match == 1);
match = (untyped.column<int64_t>(0) + untyped.column<float>(1) < 40).find_next();
assert(match == 0);
match = (untyped.column<float>(1) <= untyped.column<int64_t>(0)).find_next();
assert(match == 0);
match = (untyped.column<int64_t>(0) + untyped.column<float>(1) >= untyped.column<int64_t>(0) + untyped.column<float>(1)).find_next();
assert(match == 0);
// Untyped, column objects
Columns<int64_t> u0 = untyped.column<int64_t>(0);
Columns<float> u1 = untyped.column<float>(1);
match = (u0 + u1 > 40).find_next();
assert(match == 1);
// Flexible language binding style
Subexpr* first = new Columns<int64_t>(0);
Subexpr* second = new Columns<float>(1);
Subexpr* third = new Columns<double>(2);
Subexpr* constant = new Value<int64_t>(40);
Subexpr* plus = new Operator<Plus<float> >(*first, *second);
Expression *e = new Compare<Greater, float>(*plus, *constant);
// Bind table and do search
match = untyped.where().expression(e).find_next();
assert(match == 1);
Query q9 = untyped.where().expression(e);
match = q9.find_next();
assert(match == 1);
Subexpr* first2 = new Columns<int64_t>(0);
Subexpr* second2 = new Columns<float>(1);
Subexpr* third2 = new Columns<double>(2);
Subexpr* constant2 = new Value<int64_t>(40);
Subexpr* plus2 = new Operator<Plus<float> >(*first, *second);
Expression *e2 = new Compare<Greater, float>(*plus, *constant);
match = untyped.where().expression(e).expression(e2).find_next();
assert(match == 1);
Query q10 = untyped.where().expression(q9.get_expression()).expression(e2);
match = q10.find_next();
assert(match == 1);
Query tq3 = tq1;
match = tq3.find_next();
assert(match == 0);
delete e;
delete plus;
delete constant;
delete third;
delete second;
delete first;
delete e2;
delete plus2;
delete constant2;
delete third2;
delete second2;
delete first2;
CustomTestReporter reporter;
TestRunner runner(reporter);
const int res = runner.RunTestsIf(Test::GetTestList(), 0, True(), 0);
return 0;
}
// 638
// 545 568<|endoftext|>
|
<commit_before>//
// Created by Martin Miralles-Cordal on 5/16/2018.
//
#pragma once
#include <util/TypeTraits.hpp>
#include <util/Void.hpp>
#include <concepts>
#include <cstdint>
#include <functional>
#include <iterator>
namespace sys {
template <typename T>
class Maybe
{
public:
// our custom types
using RegularType = regular_t<T>;
template <bool Const> struct BasicIterator;
using RawType = typename std::decay<RegularType>::type;
using MutableType = typename std::remove_const<RegularType>::type;
// std container member types
using iterator = BasicIterator<false>;
using const_iterator = BasicIterator<true>;
using value_type = std::remove_reference_t<RegularType>;
using reference = lvref_t<value_type>;
using const_reference = cref_t<value_type>;
using rvalue_reference = rvref_t<value_type>;
using pointer = value_type *;
using const_pointer = value_type const *;
using difference_type = int64_t;
using size_type = size_t;
constexpr Maybe() = default;
constexpr Maybe(Void) : Maybe() {}
template <std::copy_constructible U = T>
constexpr Maybe(T const &v) : _store(v), _set(true) {}
template <std::move_constructible U = T>
constexpr Maybe(T &&v) : _store(std::move(v)), _set(true) {}
constexpr Maybe(Maybe const &other) : _store{}, _set(other._set) { if (_set) { _store.init(other.ref_()); } }
constexpr Maybe& operator=(Maybe const &other) = delete;
/** Move constructor. */
constexpr Maybe(Maybe&& other) : _store{}, _set(other._set)
{
if (_set) { _store.init(std::move(other.takeValue_())); other.clear(); }
}
constexpr Maybe& operator=(Maybe &&other) = delete;
/** Clears the stored value. */
constexpr void clear() { _store.destroy(_set); _set = false; }
/** Returns whether this contains a value. */
constexpr operator bool() const noexcept { return _set; }
/** Returns whether this contains a value. */
constexpr bool isPresent() const noexcept { return _set; }
/**
* Accesses the contained value.
* @return A const pointer to the value if set, nullptr otherwise.
*/
constexpr value_type const * operator->() const { return _set ? &ref_() : nullptr; }
/**
* Accesses the contained value.
* @return A pointer to the value if set, nullptr otherwise.
*/
constexpr value_type * operator->() { return _set ? &ref_() : nullptr; }
/**
* Accesses the contained value.
* @return A const ref to the value. Return value is undefined if not set.
*/
constexpr value_type const & operator*() const { return ref_(); }
/**
* Accesses the contained value.
* @return A reference to the value. Return value is undefined if not set.
*/
constexpr value_type & operator*() { return ref_(); }
/**
* Returns the contained value.
* @return A const ref to the value. Return value is undefined if not set.
*/
constexpr value_type const & get() const { return ref_(); }
/**
* Returns the contained value.
* @return A reference to the value. Return value is undefined if not set.
*/
constexpr value_type & get() { return ref_(); }
/**
* Returns a copy of the contained value, or a default value if not set.
* @param other The value to default to.
* @return A copy of the value, or the default value if this is not set.
*/
constexpr value_type getOr(T &&other) const &
{
return _set ? ref_() : std::forward<T>(other);
}
/**
* Moves out the contained value or returns a default value if not set.
* @param other The value to default to.
* @return A copy of the value, or the default value if this is not set.
*/
constexpr value_type getOr(T &&other) &&
{
return _set ? std::move(takeValue_()) : std::forward<T>(other);
}
/** @name STL container interface */
/** @{ */
constexpr bool empty() const { return empty(); }
constexpr size_type size() const { return isPresent() ? 1 : 0; }
constexpr size_type max_size() const { return 1; }
constexpr const_iterator cbegin() const { return isPresent() ? const_iterator{this} : cend(); }
constexpr const_iterator cend() const { return const_iterator{this, const_iterator::kEndIterator}; }
constexpr const_iterator begin() const { return cbegin(); }
constexpr const_iterator end() const { return cend(); }
constexpr iterator begin() { return isPresent() ? iterator{this} : end(); }
constexpr iterator end() { return iterator{this, iterator::kEndIterator}; }
constexpr reference front() { return get(); }
constexpr const_reference front() const { return get(); }
constexpr reference back() { return get(); }
constexpr const_reference back() const { return get(); }
/** @} */
private:
inline constexpr decltype(auto) takeValue_() noexcept { return _store.rvRef(); }
inline constexpr decltype(auto) ref_() noexcept { return _store.ref(); }
inline constexpr decltype(auto) ref_() const noexcept { return _store.ref(); }
template<typename Ts>
union Storage
{
constexpr Storage() : _nothing() {}
constexpr Storage(Ts const &aValue) : _value(aValue) {}
constexpr Storage(Ts &&aValue) : _value(std::move(aValue)) {}
~Storage() {}
constexpr void destroy(bool isSet) { if (isSet) { _value.~Ts(); } }
constexpr void init(const Ts &val) { new (&_value) Ts{val}; }
constexpr void init(Ts &&val) { new (&_value) Ts{std::move(val)}; }
constexpr value_type&& rvRef() noexcept { return std::move(_value); }
constexpr value_type& ref() noexcept { return _value; }
constexpr value_type const & ref() const noexcept { return _value; }
private:
Void _nothing;
Ts _value;
};
template<typename Ts>
union Storage<Ts &>
{
constexpr Storage() noexcept : _nothing() {}
constexpr Storage(reference aValue) noexcept : _value(&aValue) {}
constexpr void destroy(bool) noexcept {}
constexpr void init(reference val) noexcept { _value = val; }
constexpr auto rvRef() noexcept { return _value.get(); }
constexpr value_type& ref() const noexcept { return _value.get(); }
private:
Void _nothing;
std::reference_wrapper<value_type> _value;
};
Storage<MutableType> _store{};
bool _set{false};
public:
template <bool Const>
struct BasicIterator
{
static constexpr const bool kValueIterator = false;
static constexpr const bool kEndIterator = true;
using iterator_category = std::bidirectional_iterator_tag;
using value_type = RegularType;
using difference_type = Maybe::difference_type;
using reference = const_t<RegularType, Const>;
using pointer = typename std::conditional<Const, RegularType const *, RegularType *>::type;
// maintain is_trivially_copy_constructible by defining the Iterator->ConstIterator constructor as a template.
template <bool OtherConst, typename = typename std::enable_if<Const || !OtherConst>::type>
constexpr BasicIterator(const BasicIterator<OtherConst> &other) : parent_(other.parent_), end_(other.end_) {}
explicit BasicIterator(const_ptr_t<Maybe, Const> parent) : parent_(parent), end_(kValueIterator) {}
constexpr BasicIterator(const_ptr_t<Maybe, Const> parent, bool end) : parent_(parent), end_(end) {}
constexpr reference operator*() const { return parent_->GetValue(); }
constexpr BasicIterator& operator++() { end_ = true; return *this; }
constexpr BasicIterator operator++(int) { auto copy = *this; operator++(); return copy; }
constexpr BasicIterator& operator--() { end_ = false; return *this; }
constexpr BasicIterator operator--(int) { auto copy = *this; operator--(); return copy; }
constexpr bool operator==(BasicIterator const &rhs) const { return parent_ == rhs.parent_ && end_ == rhs.end_; }
constexpr bool operator!=(BasicIterator const &rhs) const { return !(rhs == *this); }
constexpr bool end() const { return end_; }
private:
const_ptr_t<Maybe, Const> parent_;
bool end_;
};
};
template <typename T> Maybe(T const &) -> Maybe<T>;
template <typename T> Maybe(T &&) -> Maybe<T>;
/**
* Constructs and "promotes" an object to a Maybe<T>.
* @tparam T The type of Maybe.
* @tparam Args The types for one of T's constructors. (deducible)
* @param args The arguments for one of T's constructors.
* @return The Maybe.
*/
template <typename T, typename... Args>
constexpr static Maybe<T> AsMaybe(Args && ...args)
{
return Maybe<T>(T(std::forward<Args>(args)...));
}
} // libsys namespace
<commit_msg>Maybe<T> support for reassignment.<commit_after>//
// Created by Martin Miralles-Cordal on 5/16/2018.
//
#pragma once
#include <util/TypeTraits.hpp>
#include <util/Void.hpp>
#include <concepts>
#include <cstdint>
#include <functional>
#include <iterator>
namespace sys {
template <typename T>
class Maybe
{
public:
// our custom types
using RegularType = regular_t<T>;
template <bool Const> struct BasicIterator;
using RawType = typename std::decay<RegularType>::type;
using MutableType = typename std::remove_const<RegularType>::type;
// std container member types
using iterator = BasicIterator<false>;
using const_iterator = BasicIterator<true>;
using value_type = std::remove_reference_t<RegularType>;
using reference = lvref_t<value_type>;
using const_reference = cref_t<value_type>;
using rvalue_reference = rvref_t<value_type>;
using pointer = value_type *;
using const_pointer = value_type const *;
using difference_type = int64_t;
using size_type = size_t;
constexpr Maybe() = default;
constexpr Maybe(Void) : Maybe() {}
template <std::copy_constructible U = T>
constexpr Maybe(T const &v) : _store(v), _set(true) {}
template <std::move_constructible U = T>
constexpr Maybe(T &&v) : _store(std::move(v)), _set(true) {}
constexpr Maybe(Maybe const &other) : _store{}, _set(other._set) { if (_set) { _store.init(other.ref_()); } }
/** Copy assignment operator */
Maybe& operator=(Maybe const &other)
{
if (other._set) { set(other.ref_()); }
else { clear(); }
return *this;
}
/** Move constructor. */
constexpr Maybe(Maybe&& other) : _store{}, _set(other._set)
{
if (_set) { _store.init(std::move(other).ref_()); other.clear(); }
}
/** Move assignment operator */
Maybe& operator=(Maybe &&other)
{
if (other._set) { set(std::move(other).ref_()); other.clear(); }
else { clear(); }
return *this;
}
/** Clears the stored value. */
constexpr void clear() { _store.destroy(_set); _set = false; }
/** Returns whether this contains a value. */
constexpr operator bool() const noexcept { return _set; }
/** Returns whether this contains a value. */
constexpr bool isPresent() const noexcept { return _set; }
/**
* Accesses the contained value.
* @return A const pointer to the value if set, nullptr otherwise.
*/
constexpr value_type const * operator->() const { return _set ? &ref_() : nullptr; }
/**
* Accesses the contained value.
* @return A pointer to the value if set, nullptr otherwise.
*/
constexpr value_type * operator->() { return _set ? &ref_() : nullptr; }
/**
* Accesses the contained value.
* @return A const ref to the value. Return value is undefined if not set.
*/
constexpr value_type const & operator*() const { return ref_(); }
/**
* Accesses the contained value.
* @return A reference to the value. Return value is undefined if not set.
*/
constexpr value_type & operator*() { return ref_(); }
/**
* Returns the contained value.
* @return A const ref to the value. Return value is undefined if not set.
*/
constexpr value_type const & get() const { return ref_(); }
/**
* Returns the contained value.
* @return A reference to the value. Return value is undefined if not set.
*/
constexpr value_type & get() { return ref_(); }
/**
* Returns a copy of the contained value, or a default value if not set.
* @param other The value to default to.
* @return A copy of the value, or the default value if this is not set.
*/
constexpr value_type getOr(T &&other) const &
{
return _set ? ref_() : std::forward<T>(other);
}
/**
* Moves out the contained value or returns a default value if not set.
* @param other The value to default to.
* @return A copy of the value, or the default value if this is not set.
*/
constexpr value_type getOr(T &&other) &&
{
return _set ? std::move(*this).ref_() : std::forward<T>(other);
}
/** Sets the Maybe to a copy of the given value. */
constexpr void set(const_reference value)
{
if (_set) { _store.reassign(value); }
else { _store.init(value); }
_set = true;
}
/** Sets the Maybe by moving the given value into the storage. */
constexpr void set(rvalue_reference value)
{
if (_set) { _store.reassign(std::move(value)); }
else { _store.init(std::move(value)); }
_set = true;
}
/** @name STL container interface */
/** @{ */
constexpr bool empty() const { return empty(); }
constexpr size_type size() const { return isPresent() ? 1 : 0; }
constexpr size_type max_size() const { return 1; }
constexpr const_iterator cbegin() const { return isPresent() ? const_iterator{this} : cend(); }
constexpr const_iterator cend() const { return const_iterator{this, const_iterator::kEndIterator}; }
constexpr const_iterator begin() const { return cbegin(); }
constexpr const_iterator end() const { return cend(); }
constexpr iterator begin() { return isPresent() ? iterator{this} : end(); }
constexpr iterator end() { return iterator{this, iterator::kEndIterator}; }
constexpr reference front() { return get(); }
constexpr const_reference front() const { return get(); }
constexpr reference back() { return get(); }
constexpr const_reference back() const { return get(); }
/** @} */
private:
inline constexpr decltype(auto) ref_() && noexcept { return std::move(_store).ref(); }
inline constexpr decltype(auto) ref_() const && noexcept { return std::move(_store).ref(); }
inline constexpr decltype(auto) ref_() & noexcept{ return _store.ref(); }
inline constexpr decltype(auto) ref_() const & noexcept{ return _store.ref(); }
template<typename Ts>
union Storage
{
constexpr Storage() : _nothing() {}
constexpr Storage(Ts const &aValue) : _value(aValue) {}
constexpr Storage(Ts &&aValue) : _value(std::move(aValue)) {}
~Storage() {}
constexpr void destroy(bool isSet) { if (isSet) { _value.~Ts(); } }
constexpr void init(const Ts &val) { new (&_value) Ts{val}; }
constexpr void init(Ts &&val) { new (&_value) Ts{std::move(val)}; }
template <std::same_as<Ts> Us = Ts> requires std::copy_assignable<Us>
constexpr void reassign(const Ts &val) { _value = val; }
template <std::same_as<Ts> Us = Ts> requires (!std::copy_assignable<Us> && std::copy_constructible<Us>)
constexpr void reassign(const Ts &val) { destroy(true); init(val); }
template <std::same_as<Ts> Us = Ts> requires std::move_assignable<Us>
constexpr void reassign(Ts &&val) { _value = std::move(val); }
template <std::same_as<Ts> Us = Ts> requires (std::move_constructible<Us> && !std::move_assignable<Us>)
constexpr void reassign(Ts &&val) { destroy(true); init(std::move(val)); }
constexpr value_type&& ref() && noexcept { return std::move(_value); }
constexpr value_type&& ref() const && noexcept { return std::move(_value); }
constexpr value_type& ref() & noexcept { return _value; }
constexpr value_type const & ref() const & noexcept { return _value; }
private:
Void _nothing;
Ts _value;
};
template<typename Ts>
union Storage<Ts &>
{
constexpr Storage() noexcept : _nothing() {}
constexpr Storage(reference aValue) noexcept : _value(&aValue) {}
constexpr void destroy(bool) noexcept {}
constexpr void init(reference val) noexcept { _value = val; }
void reassign(reference val) noexcept { _value = val; }
constexpr value_type& ref() const && noexcept { return _value.get(); }
constexpr value_type& ref() const & noexcept { return _value.get(); }
private:
Void _nothing;
std::reference_wrapper<value_type> _value;
};
Storage<MutableType> _store{};
bool _set{false};
public:
template <bool Const>
struct BasicIterator
{
static constexpr const bool kValueIterator = false;
static constexpr const bool kEndIterator = true;
using iterator_category = std::bidirectional_iterator_tag;
using value_type = RegularType;
using difference_type = Maybe::difference_type;
using reference = const_t<RegularType, Const>;
using pointer = typename std::conditional<Const, RegularType const *, RegularType *>::type;
// maintain is_trivially_copy_constructible by defining the Iterator->ConstIterator constructor as a template.
template <bool OtherConst, typename = typename std::enable_if<Const || !OtherConst>::type>
constexpr BasicIterator(const BasicIterator<OtherConst> &other) : parent_(other.parent_), end_(other.end_) {}
explicit BasicIterator(const_ptr_t<Maybe, Const> parent) : parent_(parent), end_(kValueIterator) {}
constexpr BasicIterator(const_ptr_t<Maybe, Const> parent, bool end) : parent_(parent), end_(end) {}
constexpr reference operator*() const { return parent_->GetValue(); }
constexpr BasicIterator& operator++() { end_ = true; return *this; }
constexpr BasicIterator operator++(int) { auto copy = *this; operator++(); return copy; }
constexpr BasicIterator& operator--() { end_ = false; return *this; }
constexpr BasicIterator operator--(int) { auto copy = *this; operator--(); return copy; }
constexpr bool operator==(BasicIterator const &rhs) const { return parent_ == rhs.parent_ && end_ == rhs.end_; }
constexpr bool operator!=(BasicIterator const &rhs) const { return !(rhs == *this); }
constexpr bool end() const { return end_; }
private:
const_ptr_t<Maybe, Const> parent_;
bool end_;
};
};
template <typename T> Maybe(T const &) -> Maybe<T>;
template <typename T> Maybe(T &&) -> Maybe<T>;
/**
* Constructs and "promotes" an object to a Maybe<T>.
* @tparam T The type of Maybe.
* @tparam Args The types for one of T's constructors. (deducible)
* @param args The arguments for one of T's constructors.
* @return The Maybe.
*/
template <typename T, typename... Args>
constexpr static Maybe<T> AsMaybe(Args && ...args)
{
return Maybe<T>(T(std::forward<Args>(args)...));
}
} // libsys namespace
<|endoftext|>
|
<commit_before>/**
* @file Singleton.hpp
* @brief Singleton class prototype.
* @author zer0
* @date 2016-04-04
*/
#ifndef __INCLUDE_LIBTBAG__LIBTBAG_PATTERN_SINGLETON_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_PATTERN_SINGLETON_HPP__
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#include <libtbag/config.h>
#include <atomic>
#include <mutex>
#ifndef SINGLETON_PROTOTYPE
#define SINGLETON_PROTOTYPE(base_class) \
protected: \
base_class(); \
public: \
~base_class(); \
private: \
static std::atomic<base_class*> __instance; \
static std::mutex __instance_lock; \
public: \
static base_class * getInstance();
#endif
#ifndef SINGLETON_IMPLEMENT
#define SINGLETON_IMPLEMENT(base_class) \
std::atomic<base_class*> base_class::__instance(nullptr); \
std::mutex base_class::__instance_lock; \
\
base_class * base_class::getInstance() \
{ \
base_class * temp = __instance.load(); \
if (temp == nullptr) { \
std::lock_guard<std::mutex> guard(__instance_lock); \
temp = __instance.load(); \
if (temp == nullptr) { \
temp = new base_class(); \
__instance.store(temp); \
} \
} \
return temp; \
}
#endif
#endif // __INCLUDE_LIBTBAG__LIBTBAG_PATTERN_SINGLETON_HPP__
<commit_msg>Create SingletonLifeManager class.<commit_after>/**
* @file Singleton.hpp
* @brief Singleton class prototype.
* @author zer0
* @date 2016-04-04
*/
#ifndef __INCLUDE_LIBTBAG__LIBTBAG_PATTERN_SINGLETON_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_PATTERN_SINGLETON_HPP__
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#include <libtbag/config.h>
#include <libtbag/Noncopyable.hpp>
#include <libtbag/pattern/Observer.hpp>
#include <cstdlib>
#include <atomic>
#include <mutex>
/**
* Don't use @c std::atexit function.
*
* @remarks
* Default variable is true.
*/
constexpr bool isManualRelease() noexcept
{
return false;
}
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace pattern {
/**
* SingletonLifeManager class prototype.
*
* @author zer0
* @date 2016-04-11
*
* @remarks
* Management of Singleton classes.
*/
class SingletonLifeManager : public Noncopyable
{
public:
UnorderedObservable _observable;
protected:
SingletonLifeManager() {
__EMPTY_BLOCK__
}
public:
~SingletonLifeManager() {
this->_observable.notify();
}
public:
void add(std::function<void(void)> const & observer) {
this->_observable.add(observer);
}
// Singleton section.
private:
static std::atomic<SingletonLifeManager*> __instance;
static std::mutex __instance_lock;
public:
static void releaseInstance() {
SingletonLifeManager * temp = __instance.load();
if (temp != nullptr) {
std::lock_guard<std::mutex> guard(__instance_lock);
temp = __instance.load();
if (temp != nullptr) {
delete temp; // Release, all singleton objects.
__instance.store(nullptr);
}
}
}
public:
static SingletonLifeManager * getInstance() {
SingletonLifeManager * temp = __instance.load();
if (temp == nullptr) {
std::lock_guard<std::mutex> guard(__instance_lock);
temp = __instance.load();
if (temp == nullptr) {
temp = new SingletonLifeManager();
__instance.store(temp);
if (!isManualRelease()) {
// Register release method.
std::atexit(&SingletonLifeManager::releaseInstance);
}
}
}
return temp;
}
};
std::atomic<SingletonLifeManager*> SingletonLifeManager::__instance(nullptr);
std::mutex SingletonLifeManager::__instance_lock;
} // namespace pattern
#ifndef SINGLETON_PROTOTYPE
#define SINGLETON_PROTOTYPE(base_class) \
protected: \
base_class(); \
public: \
~base_class(); \
private: \
static std::atomic<base_class*> __instance; \
static std::mutex __instance_lock; \
private: \
static void releaseInstance(); \
public: \
static base_class * getInstance(); \
private: // default access modifier of class.
#endif
#ifndef SINGLETON_IMPLEMENT
#define SINGLETON_IMPLEMENT(base_class) \
std::atomic<base_class*> base_class::__instance(nullptr); \
std::mutex base_class::__instance_lock; \
\
void base_class::releaseInstance() { \
base_class * temp = __instance.load(); \
if (temp != nullptr) { \
std::lock_guard<std::mutex> guard(__instance_lock); \
temp = __instance.load(); \
if (temp != nullptr) { \
delete temp; \
__instance.store(nullptr); \
} \
} \
} \
\
base_class * base_class::getInstance() \
{ \
base_class * temp = __instance.load(); \
if (temp == nullptr) { \
std::lock_guard<std::mutex> guard(__instance_lock); \
temp = __instance.load(); \
if (temp == nullptr) { \
temp = new base_class(); \
__instance.store(temp); \
using namespace libtbag; \
using namespace libtbag::pattern; \
SingletonLifeManager::getInstance()->add([](){ \
base_class::releaseInstance(); \
}); \
} \
} \
return temp; \
}
#endif
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
#endif // __INCLUDE_LIBTBAG__LIBTBAG_PATTERN_SINGLETON_HPP__
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: repainttarget.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-03-30 07:38:40 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _VCLCANVAS_REPAINTTARGET_HXX
#define _VCLCANVAS_REPAINTTARGET_HXX
#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif
#include "cachedbitmap.hxx"
class Point;
class Size;
class GraphicAttr;
namespace vclcanvas
{
/* Definition of RepaintTarget interface */
/** Target interface for XCachedPrimitive implementations
This interface must be implemented on all canvas
implementations that hand out XCachedPrimitives
*/
class RepaintTarget
{
public:
virtual ~RepaintTarget() {}
// call this when a bitmap is repainted
virtual bool repaint( const GraphicObjectSharedPtr& rGrf,
const ::Point& rPt,
const ::Size& rSz,
const GraphicAttr& rAttr ) const = 0;
};
}
#endif /* _VCLCANVAS_REPAINTTARGET_HXX */
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.20); FILE MERGED 2005/09/05 17:27:16 rt 1.2.20.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: repainttarget.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-07 23:22:47 $
*
* 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 _VCLCANVAS_REPAINTTARGET_HXX
#define _VCLCANVAS_REPAINTTARGET_HXX
#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif
#include "cachedbitmap.hxx"
class Point;
class Size;
class GraphicAttr;
namespace vclcanvas
{
/* Definition of RepaintTarget interface */
/** Target interface for XCachedPrimitive implementations
This interface must be implemented on all canvas
implementations that hand out XCachedPrimitives
*/
class RepaintTarget
{
public:
virtual ~RepaintTarget() {}
// call this when a bitmap is repainted
virtual bool repaint( const GraphicObjectSharedPtr& rGrf,
const ::Point& rPt,
const ::Size& rSz,
const GraphicAttr& rAttr ) const = 0;
};
}
#endif /* _VCLCANVAS_REPAINTTARGET_HXX */
<|endoftext|>
|
<commit_before>#include <cstdlib>
#include "connection.hpp"
#include "../common/assert.hpp"
#include "../common/message.hpp"
#include "../common/network/tcp_socket.hpp"
#include "rsg.pb.h"
namespace rsg
{
thread_local Connection* connection = nullptr;
}
static void retrieve_rsg_connection_params_from_env(std::string & server_hostname, uint16_t & port, int & actor_id)
{
const char * c_server_hostname = std::getenv("RSG_SERVER_HOSTNAME");
RSG_ENFORCE(c_server_hostname != nullptr, "Invalid RSG connection initialization: RSG_SERVER_HOSTNAME is not set.");
server_hostname = std::string(c_server_hostname);
const char * server_port = std::getenv("RSG_SERVER_PORT");
RSG_ENFORCE(server_port != nullptr, "Invalid RSG connection initialization: RSG_SERVER_PORT is not set.");
try
{
port = std::stoi(std::string(server_port));
}
catch (const rsg::Error & e)
{
throw rsg::Error("Invalid RSG connection initialization: RSG_SERVER_PORT ('%s') is not a valid port", server_port);
}
const char * initial_actor_id = std::getenv("RSG_INITIAL_ACTOR_ID");
RSG_ENFORCE(initial_actor_id != nullptr, "Invalid RSG connection initialization: RSG_INITIAL_ACTOR_ID is not set.");
try
{
actor_id = std::stoi(std::string(initial_actor_id));
}
catch(const std::exception & e)
{
throw rsg::Error("Invalid RSG connection initialization: RSG_INITIAL_ACTOR_ID ('%s') is not a valid actor id", initial_actor_id);
}
}
rsg::Connection::Connection(const std::string & server_hostname, uint16_t port, int actor_id) : _actor_id(actor_id)
{
// Connect to the server.
_socket = new TcpSocket();
_socket->connect(server_hostname, port);
_socket->disable_nagle_algorithm();
// Generate command.
rsg::pb::Command command;
auto actor = new rsg::pb::Actor();
actor->set_id(_actor_id);
command.set_allocated_connect(actor);
// Write message on socket.
write_message(command, *_socket);
// Read acknowledment.
rsg::pb::CommandAck command_ack;
read_message(command_ack, *_socket);
if (!command_ack.success())
printf("connect failed\n");
}
rsg::Connection::~Connection()
{
// Wait for the termination of all children threads.
for (pthread_t child : _children)
{
int ret = pthread_join(child, nullptr);
RSG_ENFORCE(ret == 0, "Error while joining thread");
}
try
{
rsg::pb::Decision decision;
decision.set_quit(true);
rsg::pb::DecisionAck ack;
write_message(decision, *_socket);
}
catch (const rsg::Error & e)
{
printf("Could not tell server that I want to quit: %s\n", e.what());
}
delete _socket;
_socket = nullptr;
}
void rsg::Connection::send_decision(const rsg::pb::Decision & decision, rsg::pb::DecisionAck & decision_ack)
{
write_message(decision, *_socket);
read_message(decision_ack, *_socket);
}
void rsg::Connection::add_child_thread(pthread_t child)
{
_children.push_back(child);
}
int rsg::Connection::actor_id() const
{
return _actor_id;
}
void rsg::connect(int actor_id)
{
RSG_ENFORCE(connection == nullptr, "Invalid rsg::connect() call: Already connected!");
std::string server_hostname;
uint16_t port = 0;
int env_actor_id;
try {
retrieve_rsg_connection_params_from_env(server_hostname, port, env_actor_id);
} catch (const rsg::Error & e) {
if (strstr(e.what(), "RSG_INITIAL_ACTOR_ID") != nullptr)
{
fprintf(stdout, "Killing the server, as this process had no/invalid actor_id.\n");
fflush(stdout);
char kill_command[128];
snprintf(kill_command, 128,
"rsg kill --reason=\"could not connect: invalid actor_id '%s'\" -h %s -p %d",
std::getenv("RSG_INITIAL_ACTOR_ID"), server_hostname.c_str(), port);
int ret = system(kill_command);
RSG_ENFORCE(ret != -1, "Could not kill server: Could not execute a `rsg` process.");
RSG_ENFORCE(ret == 0 || ret == 1, "Could not kill server: `rsg kill` returned %d", ret);
}
throw;
}
if (actor_id == -1)
actor_id = env_actor_id;
connection = new Connection(server_hostname, port, actor_id);
}
void rsg::connect()
{
connect(-1);
}
static void autoconnect(void) __attribute__((constructor));
void autoconnect(void)
{
if (std::getenv("RSG_AUTOCONNECT") != nullptr)
rsg::connect();
}
void rsg::disconnect()
{
delete rsg::connection;
rsg::connection = nullptr;
}
static void autodisconnect(void) __attribute__((destructor));
void autodisconnect(void)
{
rsg::disconnect();
}
<commit_msg>[code] fix warning<commit_after>#include <cstdlib>
#include "connection.hpp"
#include "../common/assert.hpp"
#include "../common/message.hpp"
#include "../common/network/tcp_socket.hpp"
#include "rsg.pb.h"
namespace rsg
{
thread_local Connection* connection = nullptr;
}
static void retrieve_rsg_connection_params_from_env(std::string & server_hostname, uint16_t & port, int & actor_id)
{
const char * c_server_hostname = std::getenv("RSG_SERVER_HOSTNAME");
RSG_ENFORCE(c_server_hostname != nullptr, "Invalid RSG connection initialization: RSG_SERVER_HOSTNAME is not set.");
server_hostname = std::string(c_server_hostname);
const char * server_port = std::getenv("RSG_SERVER_PORT");
RSG_ENFORCE(server_port != nullptr, "Invalid RSG connection initialization: RSG_SERVER_PORT is not set.");
try
{
port = std::stoi(std::string(server_port));
}
catch (const rsg::Error & e)
{
throw rsg::Error("Invalid RSG connection initialization: RSG_SERVER_PORT ('%s') is not a valid port", server_port);
}
const char * initial_actor_id = std::getenv("RSG_INITIAL_ACTOR_ID");
RSG_ENFORCE(initial_actor_id != nullptr, "Invalid RSG connection initialization: RSG_INITIAL_ACTOR_ID is not set.");
try
{
actor_id = std::stoi(std::string(initial_actor_id));
}
catch(const std::exception & e)
{
throw rsg::Error("Invalid RSG connection initialization: RSG_INITIAL_ACTOR_ID ('%s') is not a valid actor id", initial_actor_id);
}
}
rsg::Connection::Connection(const std::string & server_hostname, uint16_t port, int actor_id) : _actor_id(actor_id)
{
// Connect to the server.
_socket = new TcpSocket();
_socket->connect(server_hostname, port);
_socket->disable_nagle_algorithm();
// Generate command.
rsg::pb::Command command;
auto actor = new rsg::pb::Actor();
actor->set_id(_actor_id);
command.set_allocated_connect(actor);
// Write message on socket.
write_message(command, *_socket);
// Read acknowledment.
rsg::pb::CommandAck command_ack;
read_message(command_ack, *_socket);
if (!command_ack.success())
printf("connect failed\n");
}
rsg::Connection::~Connection()
{
// Wait for the termination of all children threads.
for (pthread_t child : _children)
{
int ret = pthread_join(child, nullptr);
if (ret != 0)
{
printf("Error while joining thread\n");
}
}
try
{
rsg::pb::Decision decision;
decision.set_quit(true);
rsg::pb::DecisionAck ack;
write_message(decision, *_socket);
}
catch (const rsg::Error & e)
{
printf("Could not tell server that I want to quit: %s\n", e.what());
}
delete _socket;
_socket = nullptr;
}
void rsg::Connection::send_decision(const rsg::pb::Decision & decision, rsg::pb::DecisionAck & decision_ack)
{
write_message(decision, *_socket);
read_message(decision_ack, *_socket);
}
void rsg::Connection::add_child_thread(pthread_t child)
{
_children.push_back(child);
}
int rsg::Connection::actor_id() const
{
return _actor_id;
}
void rsg::connect(int actor_id)
{
RSG_ENFORCE(connection == nullptr, "Invalid rsg::connect() call: Already connected!");
std::string server_hostname;
uint16_t port = 0;
int env_actor_id;
try {
retrieve_rsg_connection_params_from_env(server_hostname, port, env_actor_id);
} catch (const rsg::Error & e) {
if (strstr(e.what(), "RSG_INITIAL_ACTOR_ID") != nullptr)
{
fprintf(stdout, "Killing the server, as this process had no/invalid actor_id.\n");
fflush(stdout);
char kill_command[128];
snprintf(kill_command, 128,
"rsg kill --reason=\"could not connect: invalid actor_id '%s'\" -h %s -p %d",
std::getenv("RSG_INITIAL_ACTOR_ID"), server_hostname.c_str(), port);
int ret = system(kill_command);
RSG_ENFORCE(ret != -1, "Could not kill server: Could not execute a `rsg` process.");
RSG_ENFORCE(ret == 0 || ret == 1, "Could not kill server: `rsg kill` returned %d", ret);
}
throw;
}
if (actor_id == -1)
actor_id = env_actor_id;
connection = new Connection(server_hostname, port, actor_id);
}
void rsg::connect()
{
connect(-1);
}
static void autoconnect(void) __attribute__((constructor));
void autoconnect(void)
{
if (std::getenv("RSG_AUTOCONNECT") != nullptr)
rsg::connect();
}
void rsg::disconnect()
{
delete rsg::connection;
rsg::connection = nullptr;
}
static void autodisconnect(void) __attribute__((destructor));
void autodisconnect(void)
{
rsg::disconnect();
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2018 Google, Inc.
*
* 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 copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __SYSTEMC_CORE_SCHEDULER_HH__
#define __SYSTEMC_CORE_SCHEDULER_HH__
#include <functional>
#include <map>
#include <mutex>
#include <set>
#include <vector>
#include "base/logging.hh"
#include "sim/core.hh"
#include "sim/eventq_impl.hh"
#include "systemc/core/channel.hh"
#include "systemc/core/list.hh"
#include "systemc/core/process.hh"
#include "systemc/core/sched_event.hh"
class Fiber;
namespace sc_gem5
{
class TraceFile;
typedef NodeList<Process> ProcessList;
typedef NodeList<Channel> ChannelList;
/*
* The scheduler supports three different mechanisms, the initialization phase,
* delta cycles, and timed notifications.
*
* INITIALIZATION PHASE
*
* The initialization phase has three parts:
* 1. Run requested channel updates.
* 2. Make processes which need to initialize runnable (methods and threads
* which didn't have dont_initialize called on them).
* 3. Process delta notifications.
*
* First, the Kernel SimObject calls the update() method during its startup()
* callback which handles the requested channel updates. The Kernel also
* schedules an event to be run at time 0 with a slightly elevated priority
* so that it happens before any "normal" event.
*
* When that t0 event happens, it calls the schedulers prepareForInit method
* which performs step 2 above. That indirectly causes the scheduler's
* readyEvent to be scheduled with slightly lowered priority, ensuring it
* happens after any "normal" event.
*
* Because delta notifications are scheduled at the standard priority, all
* of those events will happen next, performing step 3 above. Once they finish,
* if the readyEvent was scheduled above, there shouldn't be any higher
* priority events in front of it. When it runs, it will start the first
* evaluate phase of the first delta cycle.
*
* DELTA CYCLE
*
* A delta cycle has three phases within it.
* 1. The evaluate phase where runnable processes are allowed to run.
* 2. The update phase where requested channel updates hapen.
* 3. The delta notification phase where delta notifications happen.
*
* The readyEvent runs all three steps of the delta cycle. It first goes
* through the list of runnable processes and executes them until the set is
* empty, and then immediately runs the update phase. Since these are all part
* of the same event, there's no chance for other events to intervene and
* break the required order above.
*
* During the update phase above, the spec forbids any action which would make
* a process runnable. That means that once the update phase finishes, the set
* of runnable processes will be empty. There may, however, have been some
* delta notifications/timeouts which will have been scheduled during either
* the evaluate or update phase above. Those will have been accumulated in the
* scheduler, and are now all executed.
*
* If any processes became runnable during the delta notification phase, the
* readyEvent will have been scheduled and will be waiting and ready to run
* again, effectively starting the next delta cycle.
*
* TIMED NOTIFICATION PHASE
*
* If no processes became runnable, the event queue will continue to process
* events until it comes across an event which represents all the timed
* notifications which are supposed to happen at a particular time. The object
* which tracks them will execute all those notifications, and then destroy
* itself. If the readyEvent is now ready to run, the next delta cycle will
* start.
*
* PAUSE/STOP
*
* To inject a pause from sc_pause which should happen after the current delta
* cycle's delta notification phase, an event is scheduled with a lower than
* normal priority, but higher than the readyEvent. That ensures that any
* delta notifications which are scheduled with normal priority will happen
* first, since those are part of the current delta cycle. Then the pause
* event will happen before the next readyEvent which would start the next
* delta cycle. All of these events are scheduled for the current time, and so
* would happen before any timed notifications went off.
*
* To inject a stop from sc_stop, the delta cycles should stop before even the
* delta notifications have happened, but after the evaluate and update phases.
* For that, a stop event with slightly higher than normal priority will be
* scheduled so that it happens before any of the delta notification events
* which are at normal priority.
*
* MAX RUN TIME
*
* When sc_start is called, it's possible to pass in a maximum time the
* simulation should run to, at which point sc_pause is implicitly called. The
* simulation is supposed to run up to the latest timed notification phase
* which is less than or equal to the maximum time. In other words it should
* run timed notifications at the maximum time, but not the subsequent evaluate
* phase. That's implemented by scheduling an event at the max time with a
* priority which is lower than all the others except the ready event. Timed
* notifications will happen before it fires, but it will override any ready
* event and prevent the evaluate phase from starting.
*/
class Scheduler
{
public:
typedef std::list<ScEvent *> ScEvents;
class TimeSlot : public ::Event
{
public:
TimeSlot() : ::Event(Default_Pri, AutoDelete) {}
ScEvents events;
void process();
};
typedef std::map<Tick, TimeSlot *> TimeSlots;
Scheduler();
~Scheduler();
void clear();
const std::string name() const { return "systemc_scheduler"; }
uint64_t numCycles() { return _numCycles; }
Process *current() { return _current; }
void initPhase();
// Register a process with the scheduler.
void reg(Process *p);
// Run the next process, if there is one.
void yield();
// Put a process on the ready list.
void ready(Process *p);
// Mark a process as ready if init is finished, or put it on the list of
// processes to be initialized.
void resume(Process *p);
// Remove a process from the ready/init list if it was on one of them, and
// return if it was.
bool suspend(Process *p);
// Schedule an update for a given channel.
void requestUpdate(Channel *c);
// Same as above, but may be called from a different thread.
void asyncRequestUpdate(Channel *c);
// Run the given process immediately, preempting whatever may be running.
void
runNow(Process *p)
{
// This function may put a process on the wrong list, ie a thread
// the method list. That's fine since that's just a performance
// optimization, and the important thing here is how the processes are
// ordered.
// If a process is running, schedule it/us to run again.
if (_current)
readyListMethods.pushFirst(_current);
// Schedule p to run first.
readyListMethods.pushFirst(p);
yield();
}
// Run this process at the next opportunity.
void
runNext(Process *p)
{
// Like above, it's ok if this isn't a method. Putting it on this list
// just gives it priority.
readyListMethods.pushFirst(p);
if (!inEvaluate())
scheduleReadyEvent();
}
// Set an event queue for scheduling events.
void setEventQueue(EventQueue *_eq) { eq = _eq; }
// Get the current time according to gem5.
Tick getCurTick() { return eq ? eq->getCurTick() : 0; }
Tick
delayed(const ::sc_core::sc_time &delay)
{
return getCurTick() + delay.value();
}
// For scheduling delayed/timed notifications/timeouts.
void
schedule(ScEvent *event, const ::sc_core::sc_time &delay)
{
Tick tick = delayed(delay);
if (tick < getCurTick())
tick = getCurTick();
// Delta notification/timeout.
if (delay.value() == 0) {
event->schedule(deltas, tick);
if (!inEvaluate() && !inUpdate())
scheduleReadyEvent();
return;
}
// Timed notification/timeout.
TimeSlot *&ts = timeSlots[tick];
if (!ts) {
ts = new TimeSlot;
schedule(ts, tick);
}
event->schedule(ts->events, tick);
}
// For descheduling delayed/timed notifications/timeouts.
void
deschedule(ScEvent *event)
{
ScEvents *on = event->scheduledOn();
if (on == &deltas) {
event->deschedule();
return;
}
// Timed notification/timeout.
auto tsit = timeSlots.find(event->when());
panic_if(tsit == timeSlots.end(),
"Descheduling event at time with no events.");
TimeSlot *ts = tsit->second;
ScEvents &events = ts->events;
assert(on == &events);
event->deschedule();
// If no more events are happening at this time slot, get rid of it.
if (events.empty()) {
deschedule(ts);
timeSlots.erase(tsit);
}
}
void
completeTimeSlot(TimeSlot *ts)
{
assert(ts == timeSlots.begin()->second);
timeSlots.erase(timeSlots.begin());
if (!runToTime && starved())
scheduleStarvationEvent();
scheduleTimeAdvancesEvent();
}
// Pending activity ignores gem5 activity, much like how a systemc
// simulation wouldn't know about asynchronous external events (socket IO
// for instance) that might happen before time advances in a pure
// systemc simulation. Also the spec lists what specific types of pending
// activity needs to be counted, which obviously doesn't include gem5
// events.
// Return whether there's pending systemc activity at this time.
bool
pendingCurr()
{
return !readyListMethods.empty() || !readyListThreads.empty() ||
!updateList.empty() || !deltas.empty();
}
// Return whether there are pending timed notifications or timeouts.
bool
pendingFuture()
{
return !timeSlots.empty();
}
// Return how many ticks there are until the first pending event, if any.
Tick
timeToPending()
{
if (pendingCurr())
return 0;
if (pendingFuture())
return timeSlots.begin()->first - getCurTick();
return MaxTick - getCurTick();
}
// Run scheduled channel updates.
void runUpdate();
// Run delta events.
void runDelta();
void start(Tick max_tick, bool run_to_time);
void oneCycle();
void schedulePause();
void scheduleStop(bool finish_delta);
enum Status
{
StatusOther = 0,
StatusEvaluate,
StatusUpdate,
StatusDelta,
StatusTiming,
StatusPaused,
StatusStopped
};
bool elaborationDone() { return _elaborationDone; }
void elaborationDone(bool b) { _elaborationDone = b; }
bool paused() { return status() == StatusPaused; }
bool stopped() { return status() == StatusStopped; }
bool inEvaluate() { return status() == StatusEvaluate; }
bool inUpdate() { return status() == StatusUpdate; }
bool inDelta() { return status() == StatusDelta; }
bool inTiming() { return status() == StatusTiming; }
uint64_t changeStamp() { return _changeStamp; }
void stepChangeStamp() { _changeStamp++; }
// Throw upwards, either to sc_main or to the report handler if sc_main
// isn't running.
void throwUp();
Status status() { return _status; }
void status(Status s) { _status = s; }
void registerTraceFile(TraceFile *tf) { traceFiles.insert(tf); }
void unregisterTraceFile(TraceFile *tf) { traceFiles.erase(tf); }
private:
typedef const EventBase::Priority Priority;
static Priority DefaultPriority = EventBase::Default_Pri;
static Priority StopPriority = DefaultPriority - 1;
static Priority PausePriority = DefaultPriority + 1;
static Priority MaxTickPriority = DefaultPriority + 2;
static Priority ReadyPriority = DefaultPriority + 3;
static Priority StarvationPriority = ReadyPriority;
static Priority TimeAdvancesPriority = EventBase::Maximum_Pri;
EventQueue *eq;
// For gem5 style events.
void
schedule(::Event *event, Tick tick)
{
if (initDone)
eq->schedule(event, tick);
else
eventsToSchedule[event] = tick;
}
void schedule(::Event *event) { schedule(event, getCurTick()); }
void
deschedule(::Event *event)
{
if (initDone)
eq->deschedule(event);
else
eventsToSchedule.erase(event);
}
ScEvents deltas;
TimeSlots timeSlots;
Process *
getNextReady()
{
Process *p = readyListMethods.getNext();
return p ? p : readyListThreads.getNext();
}
void runReady();
EventWrapper<Scheduler, &Scheduler::runReady> readyEvent;
void scheduleReadyEvent();
void pause();
void stop();
EventWrapper<Scheduler, &Scheduler::pause> pauseEvent;
EventWrapper<Scheduler, &Scheduler::stop> stopEvent;
const ::sc_core::sc_report *_throwUp;
bool
starved()
{
return (readyListMethods.empty() && readyListThreads.empty() &&
updateList.empty() && deltas.empty() &&
(timeSlots.empty() || timeSlots.begin()->first > maxTick) &&
initList.empty());
}
EventWrapper<Scheduler, &Scheduler::pause> starvationEvent;
void scheduleStarvationEvent();
bool _elaborationDone;
bool _started;
bool _stopNow;
Status _status;
Tick maxTick;
Tick lastReadyTick;
void
maxTickFunc()
{
if (lastReadyTick != getCurTick())
_changeStamp++;
pause();
}
EventWrapper<Scheduler, &Scheduler::maxTickFunc> maxTickEvent;
void timeAdvances() { trace(false); }
EventWrapper<Scheduler, &Scheduler::timeAdvances> timeAdvancesEvent;
void
scheduleTimeAdvancesEvent()
{
if (!traceFiles.empty() && !timeAdvancesEvent.scheduled())
schedule(&timeAdvancesEvent);
}
uint64_t _numCycles;
uint64_t _changeStamp;
Process *_current;
bool initDone;
bool runToTime;
bool runOnce;
ProcessList initList;
ProcessList readyListMethods;
ProcessList readyListThreads;
ChannelList updateList;
ChannelList asyncUpdateList;
std::mutex asyncListMutex;
std::map<::Event *, Tick> eventsToSchedule;
std::set<TraceFile *> traceFiles;
void trace(bool delta);
};
extern Scheduler scheduler;
// A proxy function to avoid having to expose the scheduler in header files.
Process *getCurrentProcess();
inline void
Scheduler::TimeSlot::process()
{
scheduler.stepChangeStamp();
scheduler.status(StatusTiming);
try {
while (!events.empty())
events.front()->run();
} catch (...) {
if (events.empty())
scheduler.completeTimeSlot(this);
else
scheduler.schedule(this);
scheduler.throwUp();
}
scheduler.status(StatusOther);
scheduler.completeTimeSlot(this);
}
const ::sc_core::sc_report reportifyException();
} // namespace sc_gem5
#endif // __SYSTEMC_CORE_SCHEDULER_H__
<commit_msg>systemc: Replace include of eventq_impl.hh with eventq.hh.<commit_after>/*
* Copyright 2018 Google, Inc.
*
* 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 copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __SYSTEMC_CORE_SCHEDULER_HH__
#define __SYSTEMC_CORE_SCHEDULER_HH__
#include <functional>
#include <map>
#include <mutex>
#include <set>
#include <vector>
#include "base/logging.hh"
#include "sim/core.hh"
#include "sim/eventq.hh"
#include "systemc/core/channel.hh"
#include "systemc/core/list.hh"
#include "systemc/core/process.hh"
#include "systemc/core/sched_event.hh"
class Fiber;
namespace sc_gem5
{
class TraceFile;
typedef NodeList<Process> ProcessList;
typedef NodeList<Channel> ChannelList;
/*
* The scheduler supports three different mechanisms, the initialization phase,
* delta cycles, and timed notifications.
*
* INITIALIZATION PHASE
*
* The initialization phase has three parts:
* 1. Run requested channel updates.
* 2. Make processes which need to initialize runnable (methods and threads
* which didn't have dont_initialize called on them).
* 3. Process delta notifications.
*
* First, the Kernel SimObject calls the update() method during its startup()
* callback which handles the requested channel updates. The Kernel also
* schedules an event to be run at time 0 with a slightly elevated priority
* so that it happens before any "normal" event.
*
* When that t0 event happens, it calls the schedulers prepareForInit method
* which performs step 2 above. That indirectly causes the scheduler's
* readyEvent to be scheduled with slightly lowered priority, ensuring it
* happens after any "normal" event.
*
* Because delta notifications are scheduled at the standard priority, all
* of those events will happen next, performing step 3 above. Once they finish,
* if the readyEvent was scheduled above, there shouldn't be any higher
* priority events in front of it. When it runs, it will start the first
* evaluate phase of the first delta cycle.
*
* DELTA CYCLE
*
* A delta cycle has three phases within it.
* 1. The evaluate phase where runnable processes are allowed to run.
* 2. The update phase where requested channel updates hapen.
* 3. The delta notification phase where delta notifications happen.
*
* The readyEvent runs all three steps of the delta cycle. It first goes
* through the list of runnable processes and executes them until the set is
* empty, and then immediately runs the update phase. Since these are all part
* of the same event, there's no chance for other events to intervene and
* break the required order above.
*
* During the update phase above, the spec forbids any action which would make
* a process runnable. That means that once the update phase finishes, the set
* of runnable processes will be empty. There may, however, have been some
* delta notifications/timeouts which will have been scheduled during either
* the evaluate or update phase above. Those will have been accumulated in the
* scheduler, and are now all executed.
*
* If any processes became runnable during the delta notification phase, the
* readyEvent will have been scheduled and will be waiting and ready to run
* again, effectively starting the next delta cycle.
*
* TIMED NOTIFICATION PHASE
*
* If no processes became runnable, the event queue will continue to process
* events until it comes across an event which represents all the timed
* notifications which are supposed to happen at a particular time. The object
* which tracks them will execute all those notifications, and then destroy
* itself. If the readyEvent is now ready to run, the next delta cycle will
* start.
*
* PAUSE/STOP
*
* To inject a pause from sc_pause which should happen after the current delta
* cycle's delta notification phase, an event is scheduled with a lower than
* normal priority, but higher than the readyEvent. That ensures that any
* delta notifications which are scheduled with normal priority will happen
* first, since those are part of the current delta cycle. Then the pause
* event will happen before the next readyEvent which would start the next
* delta cycle. All of these events are scheduled for the current time, and so
* would happen before any timed notifications went off.
*
* To inject a stop from sc_stop, the delta cycles should stop before even the
* delta notifications have happened, but after the evaluate and update phases.
* For that, a stop event with slightly higher than normal priority will be
* scheduled so that it happens before any of the delta notification events
* which are at normal priority.
*
* MAX RUN TIME
*
* When sc_start is called, it's possible to pass in a maximum time the
* simulation should run to, at which point sc_pause is implicitly called. The
* simulation is supposed to run up to the latest timed notification phase
* which is less than or equal to the maximum time. In other words it should
* run timed notifications at the maximum time, but not the subsequent evaluate
* phase. That's implemented by scheduling an event at the max time with a
* priority which is lower than all the others except the ready event. Timed
* notifications will happen before it fires, but it will override any ready
* event and prevent the evaluate phase from starting.
*/
class Scheduler
{
public:
typedef std::list<ScEvent *> ScEvents;
class TimeSlot : public ::Event
{
public:
TimeSlot() : ::Event(Default_Pri, AutoDelete) {}
ScEvents events;
void process();
};
typedef std::map<Tick, TimeSlot *> TimeSlots;
Scheduler();
~Scheduler();
void clear();
const std::string name() const { return "systemc_scheduler"; }
uint64_t numCycles() { return _numCycles; }
Process *current() { return _current; }
void initPhase();
// Register a process with the scheduler.
void reg(Process *p);
// Run the next process, if there is one.
void yield();
// Put a process on the ready list.
void ready(Process *p);
// Mark a process as ready if init is finished, or put it on the list of
// processes to be initialized.
void resume(Process *p);
// Remove a process from the ready/init list if it was on one of them, and
// return if it was.
bool suspend(Process *p);
// Schedule an update for a given channel.
void requestUpdate(Channel *c);
// Same as above, but may be called from a different thread.
void asyncRequestUpdate(Channel *c);
// Run the given process immediately, preempting whatever may be running.
void
runNow(Process *p)
{
// This function may put a process on the wrong list, ie a thread
// the method list. That's fine since that's just a performance
// optimization, and the important thing here is how the processes are
// ordered.
// If a process is running, schedule it/us to run again.
if (_current)
readyListMethods.pushFirst(_current);
// Schedule p to run first.
readyListMethods.pushFirst(p);
yield();
}
// Run this process at the next opportunity.
void
runNext(Process *p)
{
// Like above, it's ok if this isn't a method. Putting it on this list
// just gives it priority.
readyListMethods.pushFirst(p);
if (!inEvaluate())
scheduleReadyEvent();
}
// Set an event queue for scheduling events.
void setEventQueue(EventQueue *_eq) { eq = _eq; }
// Get the current time according to gem5.
Tick getCurTick() { return eq ? eq->getCurTick() : 0; }
Tick
delayed(const ::sc_core::sc_time &delay)
{
return getCurTick() + delay.value();
}
// For scheduling delayed/timed notifications/timeouts.
void
schedule(ScEvent *event, const ::sc_core::sc_time &delay)
{
Tick tick = delayed(delay);
if (tick < getCurTick())
tick = getCurTick();
// Delta notification/timeout.
if (delay.value() == 0) {
event->schedule(deltas, tick);
if (!inEvaluate() && !inUpdate())
scheduleReadyEvent();
return;
}
// Timed notification/timeout.
TimeSlot *&ts = timeSlots[tick];
if (!ts) {
ts = new TimeSlot;
schedule(ts, tick);
}
event->schedule(ts->events, tick);
}
// For descheduling delayed/timed notifications/timeouts.
void
deschedule(ScEvent *event)
{
ScEvents *on = event->scheduledOn();
if (on == &deltas) {
event->deschedule();
return;
}
// Timed notification/timeout.
auto tsit = timeSlots.find(event->when());
panic_if(tsit == timeSlots.end(),
"Descheduling event at time with no events.");
TimeSlot *ts = tsit->second;
ScEvents &events = ts->events;
assert(on == &events);
event->deschedule();
// If no more events are happening at this time slot, get rid of it.
if (events.empty()) {
deschedule(ts);
timeSlots.erase(tsit);
}
}
void
completeTimeSlot(TimeSlot *ts)
{
assert(ts == timeSlots.begin()->second);
timeSlots.erase(timeSlots.begin());
if (!runToTime && starved())
scheduleStarvationEvent();
scheduleTimeAdvancesEvent();
}
// Pending activity ignores gem5 activity, much like how a systemc
// simulation wouldn't know about asynchronous external events (socket IO
// for instance) that might happen before time advances in a pure
// systemc simulation. Also the spec lists what specific types of pending
// activity needs to be counted, which obviously doesn't include gem5
// events.
// Return whether there's pending systemc activity at this time.
bool
pendingCurr()
{
return !readyListMethods.empty() || !readyListThreads.empty() ||
!updateList.empty() || !deltas.empty();
}
// Return whether there are pending timed notifications or timeouts.
bool
pendingFuture()
{
return !timeSlots.empty();
}
// Return how many ticks there are until the first pending event, if any.
Tick
timeToPending()
{
if (pendingCurr())
return 0;
if (pendingFuture())
return timeSlots.begin()->first - getCurTick();
return MaxTick - getCurTick();
}
// Run scheduled channel updates.
void runUpdate();
// Run delta events.
void runDelta();
void start(Tick max_tick, bool run_to_time);
void oneCycle();
void schedulePause();
void scheduleStop(bool finish_delta);
enum Status
{
StatusOther = 0,
StatusEvaluate,
StatusUpdate,
StatusDelta,
StatusTiming,
StatusPaused,
StatusStopped
};
bool elaborationDone() { return _elaborationDone; }
void elaborationDone(bool b) { _elaborationDone = b; }
bool paused() { return status() == StatusPaused; }
bool stopped() { return status() == StatusStopped; }
bool inEvaluate() { return status() == StatusEvaluate; }
bool inUpdate() { return status() == StatusUpdate; }
bool inDelta() { return status() == StatusDelta; }
bool inTiming() { return status() == StatusTiming; }
uint64_t changeStamp() { return _changeStamp; }
void stepChangeStamp() { _changeStamp++; }
// Throw upwards, either to sc_main or to the report handler if sc_main
// isn't running.
void throwUp();
Status status() { return _status; }
void status(Status s) { _status = s; }
void registerTraceFile(TraceFile *tf) { traceFiles.insert(tf); }
void unregisterTraceFile(TraceFile *tf) { traceFiles.erase(tf); }
private:
typedef const EventBase::Priority Priority;
static Priority DefaultPriority = EventBase::Default_Pri;
static Priority StopPriority = DefaultPriority - 1;
static Priority PausePriority = DefaultPriority + 1;
static Priority MaxTickPriority = DefaultPriority + 2;
static Priority ReadyPriority = DefaultPriority + 3;
static Priority StarvationPriority = ReadyPriority;
static Priority TimeAdvancesPriority = EventBase::Maximum_Pri;
EventQueue *eq;
// For gem5 style events.
void
schedule(::Event *event, Tick tick)
{
if (initDone)
eq->schedule(event, tick);
else
eventsToSchedule[event] = tick;
}
void schedule(::Event *event) { schedule(event, getCurTick()); }
void
deschedule(::Event *event)
{
if (initDone)
eq->deschedule(event);
else
eventsToSchedule.erase(event);
}
ScEvents deltas;
TimeSlots timeSlots;
Process *
getNextReady()
{
Process *p = readyListMethods.getNext();
return p ? p : readyListThreads.getNext();
}
void runReady();
EventWrapper<Scheduler, &Scheduler::runReady> readyEvent;
void scheduleReadyEvent();
void pause();
void stop();
EventWrapper<Scheduler, &Scheduler::pause> pauseEvent;
EventWrapper<Scheduler, &Scheduler::stop> stopEvent;
const ::sc_core::sc_report *_throwUp;
bool
starved()
{
return (readyListMethods.empty() && readyListThreads.empty() &&
updateList.empty() && deltas.empty() &&
(timeSlots.empty() || timeSlots.begin()->first > maxTick) &&
initList.empty());
}
EventWrapper<Scheduler, &Scheduler::pause> starvationEvent;
void scheduleStarvationEvent();
bool _elaborationDone;
bool _started;
bool _stopNow;
Status _status;
Tick maxTick;
Tick lastReadyTick;
void
maxTickFunc()
{
if (lastReadyTick != getCurTick())
_changeStamp++;
pause();
}
EventWrapper<Scheduler, &Scheduler::maxTickFunc> maxTickEvent;
void timeAdvances() { trace(false); }
EventWrapper<Scheduler, &Scheduler::timeAdvances> timeAdvancesEvent;
void
scheduleTimeAdvancesEvent()
{
if (!traceFiles.empty() && !timeAdvancesEvent.scheduled())
schedule(&timeAdvancesEvent);
}
uint64_t _numCycles;
uint64_t _changeStamp;
Process *_current;
bool initDone;
bool runToTime;
bool runOnce;
ProcessList initList;
ProcessList readyListMethods;
ProcessList readyListThreads;
ChannelList updateList;
ChannelList asyncUpdateList;
std::mutex asyncListMutex;
std::map<::Event *, Tick> eventsToSchedule;
std::set<TraceFile *> traceFiles;
void trace(bool delta);
};
extern Scheduler scheduler;
// A proxy function to avoid having to expose the scheduler in header files.
Process *getCurrentProcess();
inline void
Scheduler::TimeSlot::process()
{
scheduler.stepChangeStamp();
scheduler.status(StatusTiming);
try {
while (!events.empty())
events.front()->run();
} catch (...) {
if (events.empty())
scheduler.completeTimeSlot(this);
else
scheduler.schedule(this);
scheduler.throwUp();
}
scheduler.status(StatusOther);
scheduler.completeTimeSlot(this);
}
const ::sc_core::sc_report reportifyException();
} // namespace sc_gem5
#endif // __SYSTEMC_CORE_SCHEDULER_H__
<|endoftext|>
|
<commit_before>#include "openmc/tallies/filter_energy.h"
#include "openmc/capi.h"
#include "openmc/constants.h" // For F90_NONE
#include "openmc/mgxs_interface.h"
#include "openmc/search.h"
#include "openmc/settings.h"
#include "openmc/xml_interface.h"
namespace openmc {
//==============================================================================
// EnergyFilter implementation
//==============================================================================
void
EnergyFilter::from_xml(pugi::xml_node node)
{
bins_ = get_node_array<double>(node, "bins");
n_bins_ = bins_.size() - 1;
// In MG mode, check if the filter bins match the transport bins.
// We can save tallying time if we know that the tally bins match the energy
// group structure. In that case, the matching bin index is simply the group
// (after flipping for the different ordering of the library and tallying
// systems).
if (!settings::run_CE) {
if (n_bins_ == num_energy_groups) {
matches_transport_groups_ = true;
for (auto i = 0; i < n_bins_ + 1; i++) {
if (rev_energy_bins[i] != bins_[i]) {
matches_transport_groups_ = false;
break;
}
}
}
}
}
void
EnergyFilter::get_all_bins(const Particle* p, int estimator, FilterMatch& match)
const
{
if (p->g != F90_NONE && matches_transport_groups_) {
if (estimator == ESTIMATOR_TRACKLENGTH) {
//TODO: off-by-one
match.bins_.push_back(num_energy_groups - p->g + 1);
} else {
//TODO: off-by-one
match.bins_.push_back(num_energy_groups - p->last_g + 1);
}
match.weights_.push_back(1.0);
} else {
// Get the pre-collision energy of the particle.
auto E = p->last_E;
// Bin the energy.
if (E >= bins_.front() && E <= bins_.back()) {
//TODO: off-by-one
auto bin = lower_bound_index(bins_.begin(), bins_.end(), E) + 1;
match.bins_.push_back(bin);
match.weights_.push_back(1.0);
}
}
}
void
EnergyFilter::to_statepoint(hid_t filter_group) const
{
Filter::to_statepoint(filter_group);
write_dataset(filter_group, "bins", bins_);
}
std::string
EnergyFilter::text_label(int bin) const
{
std::stringstream out;
//TODO: off-by-one
out << "Incoming Energy [" << bins_[bin-1] << ", " << bins_[bin] << ")";
return out.str();
}
//==============================================================================
// EnergyoutFilter implementation
//==============================================================================
void
EnergyoutFilter::get_all_bins(const Particle* p, int estimator,
FilterMatch& match) const
{
if (p->g != F90_NONE && matches_transport_groups_) {
match.bins_.push_back(num_energy_groups - p->g + 1);
match.weights_.push_back(1.0);
} else {
if (p->E >= bins_.front() && p->E <= bins_.back()) {
//TODO: off-by-one
auto bin = lower_bound_index(bins_.begin(), bins_.end(), p->E) + 1;
match.bins_.push_back(bin);
match.weights_.push_back(1.0);
}
}
}
std::string
EnergyoutFilter::text_label(int bin) const
{
std::stringstream out;
//TODO: off-by-one
out << "Outgoing Energy [" << bins_[bin-1] << ", " << bins_[bin] << ")";
return out.str();
}
//==============================================================================
// Fortran interoperability
//==============================================================================
extern "C" bool energy_filter_matches_transport_groups(EnergyFilter* filt)
{return filt->matches_transport_groups_;}
extern "C" int
energy_filter_search(EnergyFilter* filt, double val)
{
if (val < filt->bins_.front() || val > filt->bins_.back()) {
return -1;
} else {
//TODO: off-by-one
return lower_bound_index(filt->bins_.begin(), filt->bins_.end(), val) + 1;
}
}
//==============================================================================
// C-API functions
//==============================================================================
extern"C" int
openmc_energy_filter_get_bins(int32_t index, double** energies, int32_t* n)
{
// Make sure this is a valid index to an allocated filter.
int err = verify_filter(index);
if (err) return err;
// Get a pointer to the filter and downcast.
auto* filt_base = filter_from_f(index);
auto* filt = dynamic_cast<EnergyFilter*>(filt_base);
// Check the filter type.
if (!filt) {
set_errmsg("Tried to get energy bins on a non-energy filter.");
return OPENMC_E_INVALID_TYPE;
}
// Output the bins.
*energies = filt->bins_.data();
*n = filt->bins_.size();
return 0;
}
extern "C" int
openmc_energy_filter_set_bins(int32_t index, int32_t n, const double* energies)
{
// Make sure this is a valid index to an allocated filter.
int err = verify_filter(index);
if (err) return err;
// Get a pointer to the filter and downcast.
auto* filt_base = filter_from_f(index);
auto* filt = dynamic_cast<EnergyFilter*>(filt_base);
// Check the filter type.
if (!filt) {
set_errmsg("Tried to set energy bins on a non-energy filter.");
return OPENMC_E_INVALID_TYPE;
}
// Update the filter.
filt->bins_.clear();
filt->bins_.resize(n);
for (int i = 0; i < n; i++) filt->bins_[i] = energies[i];
filt->n_bins_ = n - 1;
filter_update_n_bins(index);
}
}// namespace openmc
<commit_msg>Make sure openmc_energy_filter_set_bins returns an int<commit_after>#include "openmc/tallies/filter_energy.h"
#include "openmc/capi.h"
#include "openmc/constants.h" // For F90_NONE
#include "openmc/mgxs_interface.h"
#include "openmc/search.h"
#include "openmc/settings.h"
#include "openmc/xml_interface.h"
namespace openmc {
//==============================================================================
// EnergyFilter implementation
//==============================================================================
void
EnergyFilter::from_xml(pugi::xml_node node)
{
bins_ = get_node_array<double>(node, "bins");
n_bins_ = bins_.size() - 1;
// In MG mode, check if the filter bins match the transport bins.
// We can save tallying time if we know that the tally bins match the energy
// group structure. In that case, the matching bin index is simply the group
// (after flipping for the different ordering of the library and tallying
// systems).
if (!settings::run_CE) {
if (n_bins_ == num_energy_groups) {
matches_transport_groups_ = true;
for (auto i = 0; i < n_bins_ + 1; i++) {
if (rev_energy_bins[i] != bins_[i]) {
matches_transport_groups_ = false;
break;
}
}
}
}
}
void
EnergyFilter::get_all_bins(const Particle* p, int estimator, FilterMatch& match)
const
{
if (p->g != F90_NONE && matches_transport_groups_) {
if (estimator == ESTIMATOR_TRACKLENGTH) {
//TODO: off-by-one
match.bins_.push_back(num_energy_groups - p->g + 1);
} else {
//TODO: off-by-one
match.bins_.push_back(num_energy_groups - p->last_g + 1);
}
match.weights_.push_back(1.0);
} else {
// Get the pre-collision energy of the particle.
auto E = p->last_E;
// Bin the energy.
if (E >= bins_.front() && E <= bins_.back()) {
//TODO: off-by-one
auto bin = lower_bound_index(bins_.begin(), bins_.end(), E) + 1;
match.bins_.push_back(bin);
match.weights_.push_back(1.0);
}
}
}
void
EnergyFilter::to_statepoint(hid_t filter_group) const
{
Filter::to_statepoint(filter_group);
write_dataset(filter_group, "bins", bins_);
}
std::string
EnergyFilter::text_label(int bin) const
{
std::stringstream out;
//TODO: off-by-one
out << "Incoming Energy [" << bins_[bin-1] << ", " << bins_[bin] << ")";
return out.str();
}
//==============================================================================
// EnergyoutFilter implementation
//==============================================================================
void
EnergyoutFilter::get_all_bins(const Particle* p, int estimator,
FilterMatch& match) const
{
if (p->g != F90_NONE && matches_transport_groups_) {
match.bins_.push_back(num_energy_groups - p->g + 1);
match.weights_.push_back(1.0);
} else {
if (p->E >= bins_.front() && p->E <= bins_.back()) {
//TODO: off-by-one
auto bin = lower_bound_index(bins_.begin(), bins_.end(), p->E) + 1;
match.bins_.push_back(bin);
match.weights_.push_back(1.0);
}
}
}
std::string
EnergyoutFilter::text_label(int bin) const
{
std::stringstream out;
//TODO: off-by-one
out << "Outgoing Energy [" << bins_[bin-1] << ", " << bins_[bin] << ")";
return out.str();
}
//==============================================================================
// Fortran interoperability
//==============================================================================
extern "C" bool energy_filter_matches_transport_groups(EnergyFilter* filt)
{return filt->matches_transport_groups_;}
extern "C" int
energy_filter_search(EnergyFilter* filt, double val)
{
if (val < filt->bins_.front() || val > filt->bins_.back()) {
return -1;
} else {
//TODO: off-by-one
return lower_bound_index(filt->bins_.begin(), filt->bins_.end(), val) + 1;
}
}
//==============================================================================
// C-API functions
//==============================================================================
extern"C" int
openmc_energy_filter_get_bins(int32_t index, double** energies, int32_t* n)
{
// Make sure this is a valid index to an allocated filter.
int err = verify_filter(index);
if (err) return err;
// Get a pointer to the filter and downcast.
auto* filt_base = filter_from_f(index);
auto* filt = dynamic_cast<EnergyFilter*>(filt_base);
// Check the filter type.
if (!filt) {
set_errmsg("Tried to get energy bins on a non-energy filter.");
return OPENMC_E_INVALID_TYPE;
}
// Output the bins.
*energies = filt->bins_.data();
*n = filt->bins_.size();
return 0;
}
extern "C" int
openmc_energy_filter_set_bins(int32_t index, int32_t n, const double* energies)
{
// Make sure this is a valid index to an allocated filter.
int err = verify_filter(index);
if (err) return err;
// Get a pointer to the filter and downcast.
auto* filt_base = filter_from_f(index);
auto* filt = dynamic_cast<EnergyFilter*>(filt_base);
// Check the filter type.
if (!filt) {
set_errmsg("Tried to set energy bins on a non-energy filter.");
return OPENMC_E_INVALID_TYPE;
}
// Update the filter.
filt->bins_.clear();
filt->bins_.resize(n);
for (int i = 0; i < n; i++) filt->bins_[i] = energies[i];
filt->n_bins_ = n - 1;
filter_update_n_bins(index);
return 0;
}
}// namespace openmc
<|endoftext|>
|
<commit_before>#include "ExecStats.h"
#include <iostream>
#include <iomanip>
#include <cassert>
namespace dev
{
namespace eth
{
namespace jit
{
void ExecStats::stateChanged(ExecState _state)
{
if (!CHECK(m_state != ExecState::Finished))
return;
auto now = clock::now();
if (_state != ExecState::Started)
{
assert(time[(int)m_state] == ExecStats::duration::zero());
time[(int)m_state] = now - m_tp;
}
m_state = _state;
m_tp = now;
}
namespace
{
struct StatsAgg
{
using unit = std::chrono::microseconds;
ExecStats::duration tot = ExecStats::duration::zero();
ExecStats::duration min = ExecStats::duration::max();
ExecStats::duration max = ExecStats::duration::zero();
size_t count = 0;
void update(ExecStats::duration _d)
{
++count;
tot += _d;
min = _d < min ? _d : min;
max = _d > max ? _d : max;
}
void output(char const* _name, std::ostream& _os)
{
auto avg = tot / count;
_os << std::setfill(' ')
<< std::setw(12) << std::left << _name
<< std::setw(10) << std::right << std::chrono::duration_cast<unit>(tot).count()
<< std::setw(10) << std::right << std::chrono::duration_cast<unit>(avg).count()
<< std::setw(10) << std::right << std::chrono::duration_cast<unit>(min).count()
<< std::setw(10) << std::right << std::chrono::duration_cast<unit>(max).count()
<< std::endl;
}
};
char const* getExecStateName(ExecState _state)
{
switch (_state)
{
case ExecState::Started: return "Start";
case ExecState::CacheLoad: return "CacheLoad";
case ExecState::CacheWrite: return "CacheWrite";
case ExecState::Compilation: return "Compilation";
case ExecState::CodeGen: return "CodeGen";
case ExecState::Execution: return "Execution";
case ExecState::Return: return "Return";
case ExecState::Finished: return "Finish";
}
return nullptr;
}
}
StatsCollector::~StatsCollector()
{
if (stats.empty())
return;
std::cout << " [us] total avg min max\n";
for (int i = 0; i < (int)ExecState::Finished; ++i)
{
StatsAgg agg;
for (auto&& s : stats)
agg.update(s->time[i]);
agg.output(getExecStateName(ExecState(i)), std::cout);
}
}
}
}
}
<commit_msg>Build fix<commit_after>#include "ExecStats.h"
#include <iostream>
#include <iomanip>
#include <cassert>
#include "Utils.h"
namespace dev
{
namespace eth
{
namespace jit
{
void ExecStats::stateChanged(ExecState _state)
{
if (!CHECK(m_state != ExecState::Finished))
return;
auto now = clock::now();
if (_state != ExecState::Started)
{
assert(time[(int)m_state] == ExecStats::duration::zero());
time[(int)m_state] = now - m_tp;
}
m_state = _state;
m_tp = now;
}
namespace
{
struct StatsAgg
{
using unit = std::chrono::microseconds;
ExecStats::duration tot = ExecStats::duration::zero();
ExecStats::duration min = ExecStats::duration::max();
ExecStats::duration max = ExecStats::duration::zero();
size_t count = 0;
void update(ExecStats::duration _d)
{
++count;
tot += _d;
min = _d < min ? _d : min;
max = _d > max ? _d : max;
}
void output(char const* _name, std::ostream& _os)
{
auto avg = tot / count;
_os << std::setfill(' ')
<< std::setw(12) << std::left << _name
<< std::setw(10) << std::right << std::chrono::duration_cast<unit>(tot).count()
<< std::setw(10) << std::right << std::chrono::duration_cast<unit>(avg).count()
<< std::setw(10) << std::right << std::chrono::duration_cast<unit>(min).count()
<< std::setw(10) << std::right << std::chrono::duration_cast<unit>(max).count()
<< std::endl;
}
};
char const* getExecStateName(ExecState _state)
{
switch (_state)
{
case ExecState::Started: return "Start";
case ExecState::CacheLoad: return "CacheLoad";
case ExecState::CacheWrite: return "CacheWrite";
case ExecState::Compilation: return "Compilation";
case ExecState::CodeGen: return "CodeGen";
case ExecState::Execution: return "Execution";
case ExecState::Return: return "Return";
case ExecState::Finished: return "Finish";
}
return nullptr;
}
}
StatsCollector::~StatsCollector()
{
if (stats.empty())
return;
std::cout << " [us] total avg min max\n";
for (int i = 0; i < (int)ExecState::Finished; ++i)
{
StatsAgg agg;
for (auto&& s : stats)
agg.update(s->time[i]);
agg.output(getExecStateName(ExecState(i)), std::cout);
}
}
}
}
}
<|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 "webkit/appcache/appcache_group.h"
#include <algorithm>
#include "base/logging.h"
#include "base/message_loop.h"
#include "webkit/appcache/appcache.h"
#include "webkit/appcache/appcache_host.h"
#include "webkit/appcache/appcache_service.h"
#include "webkit/appcache/appcache_storage.h"
#include "webkit/appcache/appcache_update_job.h"
namespace appcache {
class AppCacheGroup;
// Use this helper class because we cannot make AppCacheGroup a derived class
// of AppCacheHost::Observer as it would create a circular dependency between
// AppCacheHost and AppCacheGroup.
class AppCacheGroup::HostObserver : public AppCacheHost::Observer {
public:
explicit HostObserver(AppCacheGroup* group) : group_(group) {}
// Methods for AppCacheHost::Observer.
void OnCacheSelectionComplete(AppCacheHost* host) {} // N/A
void OnDestructionImminent(AppCacheHost* host) {
group_->HostDestructionImminent(host);
}
private:
AppCacheGroup* group_;
};
AppCacheGroup::AppCacheGroup(AppCacheService* service,
const GURL& manifest_url,
int64 group_id)
: group_id_(group_id),
manifest_url_(manifest_url),
update_status_(IDLE),
is_obsolete_(false),
newest_complete_cache_(NULL),
update_job_(NULL),
service_(service),
restart_update_task_(NULL) {
service_->storage()->working_set()->AddGroup(this);
host_observer_.reset(new HostObserver(this));
}
AppCacheGroup::~AppCacheGroup() {
DCHECK(old_caches_.empty());
DCHECK(!newest_complete_cache_);
DCHECK(!restart_update_task_);
DCHECK(queued_updates_.empty());
if (update_job_)
delete update_job_;
DCHECK_EQ(IDLE, update_status_);
service_->storage()->working_set()->RemoveGroup(this);
service_->storage()->DeleteResponses(
manifest_url_, newly_deletable_response_ids_);
}
void AppCacheGroup::AddUpdateObserver(UpdateObserver* observer) {
// If observer being added is a host that has been queued for later update,
// add observer to a different observer list.
AppCacheHost* host = static_cast<AppCacheHost*>(observer);
if (queued_updates_.find(host) != queued_updates_.end())
queued_observers_.AddObserver(observer);
else
observers_.AddObserver(observer);
}
void AppCacheGroup::RemoveUpdateObserver(UpdateObserver* observer) {
observers_.RemoveObserver(observer);
queued_observers_.RemoveObserver(observer);
}
void AppCacheGroup::AddCache(AppCache* complete_cache) {
DCHECK(complete_cache->is_complete());
complete_cache->set_owning_group(this);
if (!newest_complete_cache_) {
newest_complete_cache_ = complete_cache;
return;
}
if (complete_cache->IsNewerThan(newest_complete_cache_)) {
old_caches_.push_back(newest_complete_cache_);
newest_complete_cache_ = complete_cache;
// Update hosts of older caches to add a reference to the newest cache.
for (Caches::iterator it = old_caches_.begin();
it != old_caches_.end(); ++it) {
AppCache::AppCacheHosts& hosts = (*it)->associated_hosts();
for (AppCache::AppCacheHosts::iterator host_it = hosts.begin();
host_it != hosts.end(); ++host_it) {
(*host_it)->SetSwappableCache(this);
}
}
} else {
old_caches_.push_back(complete_cache);
}
}
void AppCacheGroup::RemoveCache(AppCache* cache) {
DCHECK(cache->associated_hosts().empty());
if (cache == newest_complete_cache_) {
AppCache* tmp_cache = newest_complete_cache_;
newest_complete_cache_ = NULL;
tmp_cache->set_owning_group(NULL); // may cause this group to be deleted
} else {
scoped_refptr<AppCacheGroup> protect(this);
Caches::iterator it =
std::find(old_caches_.begin(), old_caches_.end(), cache);
if (it != old_caches_.end()) {
AppCache* tmp_cache = *it;
old_caches_.erase(it);
tmp_cache->set_owning_group(NULL); // may cause group to be released
}
if (!is_obsolete() && old_caches_.empty() &&
!newly_deletable_response_ids_.empty()) {
service_->storage()->DeleteResponses(
manifest_url_, newly_deletable_response_ids_);
newly_deletable_response_ids_.clear();
}
}
}
void AppCacheGroup::AddNewlyDeletableResponseIds(
std::vector<int64>* response_ids) {
if (!is_obsolete() && old_caches_.empty()) {
service_->storage()->DeleteResponses(
manifest_url_, *response_ids);
response_ids->clear();
return;
}
if (newly_deletable_response_ids_.empty()) {
newly_deletable_response_ids_.swap(*response_ids);
return;
}
newly_deletable_response_ids_.insert(
newly_deletable_response_ids_.end(),
response_ids->begin(), response_ids->end());
response_ids->clear();
}
void AppCacheGroup::StartUpdateWithNewMasterEntry(
AppCacheHost* host, const GURL& new_master_resource) {
if (!update_job_)
update_job_ = new AppCacheUpdateJob(service_, this);
update_job_->StartUpdate(host, new_master_resource);
// Run queued update immediately as an update has been started manually.
if (restart_update_task_) {
restart_update_task_->Cancel();
restart_update_task_ = NULL;
RunQueuedUpdates();
}
}
void AppCacheGroup::QueueUpdate(AppCacheHost* host,
const GURL& new_master_resource) {
DCHECK(update_job_ && host && !new_master_resource.is_empty());
queued_updates_.insert(QueuedUpdates::value_type(host, new_master_resource));
// Need to know when host is destroyed.
host->AddObserver(host_observer_.get());
// If host is already observing for updates, move host to queued observers
// list so that host is not notified when the current update completes.
if (FindObserver(host, observers_)) {
observers_.RemoveObserver(host);
queued_observers_.AddObserver(host);
}
}
void AppCacheGroup::RunQueuedUpdates() {
if (restart_update_task_)
restart_update_task_ = NULL;
if (queued_updates_.empty())
return;
QueuedUpdates updates_to_run;
queued_updates_.swap(updates_to_run);
DCHECK(queued_updates_.empty());
for (QueuedUpdates::iterator it = updates_to_run.begin();
it != updates_to_run.end(); ++it) {
AppCacheHost* host = it->first;
host->RemoveObserver(host_observer_.get());
if (FindObserver(host, queued_observers_)) {
queued_observers_.RemoveObserver(host);
observers_.AddObserver(host);
}
if (!is_obsolete())
StartUpdateWithNewMasterEntry(host, it->second);
}
}
bool AppCacheGroup::FindObserver(UpdateObserver* find_me,
const ObserverList<UpdateObserver>& observer_list) {
ObserverList<UpdateObserver>::Iterator it(observer_list);
UpdateObserver* obs;
while ((obs = it.GetNext()) != NULL) {
if (obs == find_me)
return true;
}
return false;
}
void AppCacheGroup::ScheduleUpdateRestart(int delay_ms) {
DCHECK(!restart_update_task_);
restart_update_task_ =
NewRunnableMethod(this, &AppCacheGroup::RunQueuedUpdates);
MessageLoop::current()->PostDelayedTask(FROM_HERE, restart_update_task_,
delay_ms);
}
void AppCacheGroup::HostDestructionImminent(AppCacheHost* host) {
queued_updates_.erase(host);
if (queued_updates_.empty() && restart_update_task_) {
restart_update_task_->Cancel();
restart_update_task_ = NULL;
}
}
void AppCacheGroup::SetUpdateStatus(UpdateStatus status) {
if (status == update_status_)
return;
update_status_ = status;
if (status != IDLE) {
DCHECK(update_job_);
} else {
update_job_ = NULL;
// Note, this method may be called from within our destructor so we have
// to be careful about calling addref and release in here. If there are
// any observers, this will not be the case since each observer will have
// a reference to us.
if (observers_.size() || queued_observers_.size()) {
// Observers may release us in these callbacks, so we protect against
// deletion by adding an extra ref in this scope.
scoped_refptr<AppCacheGroup> protect(this);
FOR_EACH_OBSERVER(UpdateObserver, observers_, OnUpdateComplete(this));
if (!queued_updates_.empty())
ScheduleUpdateRestart(kUpdateRestartDelayMs);
}
}
}
} // namespace appcache
<commit_msg>Revert 37466 - Fix a refcounting memory bug.<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 "webkit/appcache/appcache_group.h"
#include <algorithm>
#include "base/logging.h"
#include "base/message_loop.h"
#include "webkit/appcache/appcache.h"
#include "webkit/appcache/appcache_host.h"
#include "webkit/appcache/appcache_service.h"
#include "webkit/appcache/appcache_storage.h"
#include "webkit/appcache/appcache_update_job.h"
namespace appcache {
class AppCacheGroup;
// Use this helper class because we cannot make AppCacheGroup a derived class
// of AppCacheHost::Observer as it would create a circular dependency between
// AppCacheHost and AppCacheGroup.
class AppCacheGroup::HostObserver : public AppCacheHost::Observer {
public:
explicit HostObserver(AppCacheGroup* group) : group_(group) {}
// Methods for AppCacheHost::Observer.
void OnCacheSelectionComplete(AppCacheHost* host) {} // N/A
void OnDestructionImminent(AppCacheHost* host) {
group_->HostDestructionImminent(host);
}
private:
AppCacheGroup* group_;
};
AppCacheGroup::AppCacheGroup(AppCacheService* service,
const GURL& manifest_url,
int64 group_id)
: group_id_(group_id),
manifest_url_(manifest_url),
update_status_(IDLE),
is_obsolete_(false),
newest_complete_cache_(NULL),
update_job_(NULL),
service_(service),
restart_update_task_(NULL) {
service_->storage()->working_set()->AddGroup(this);
host_observer_.reset(new HostObserver(this));
}
AppCacheGroup::~AppCacheGroup() {
DCHECK(old_caches_.empty());
DCHECK(!newest_complete_cache_);
DCHECK(!restart_update_task_);
DCHECK(queued_updates_.empty());
if (update_job_)
delete update_job_;
DCHECK_EQ(IDLE, update_status_);
service_->storage()->working_set()->RemoveGroup(this);
service_->storage()->DeleteResponses(
manifest_url_, newly_deletable_response_ids_);
}
void AppCacheGroup::AddUpdateObserver(UpdateObserver* observer) {
// If observer being added is a host that has been queued for later update,
// add observer to a different observer list.
AppCacheHost* host = static_cast<AppCacheHost*>(observer);
if (queued_updates_.find(host) != queued_updates_.end())
queued_observers_.AddObserver(observer);
else
observers_.AddObserver(observer);
}
void AppCacheGroup::RemoveUpdateObserver(UpdateObserver* observer) {
observers_.RemoveObserver(observer);
queued_observers_.RemoveObserver(observer);
}
void AppCacheGroup::AddCache(AppCache* complete_cache) {
DCHECK(complete_cache->is_complete());
complete_cache->set_owning_group(this);
if (!newest_complete_cache_) {
newest_complete_cache_ = complete_cache;
return;
}
if (complete_cache->IsNewerThan(newest_complete_cache_)) {
old_caches_.push_back(newest_complete_cache_);
newest_complete_cache_ = complete_cache;
// Update hosts of older caches to add a reference to the newest cache.
for (Caches::iterator it = old_caches_.begin();
it != old_caches_.end(); ++it) {
AppCache::AppCacheHosts& hosts = (*it)->associated_hosts();
for (AppCache::AppCacheHosts::iterator host_it = hosts.begin();
host_it != hosts.end(); ++host_it) {
(*host_it)->SetSwappableCache(this);
}
}
} else {
old_caches_.push_back(complete_cache);
}
}
void AppCacheGroup::RemoveCache(AppCache* cache) {
DCHECK(cache->associated_hosts().empty());
if (cache == newest_complete_cache_) {
AppCache* tmp_cache = newest_complete_cache_;
newest_complete_cache_ = NULL;
tmp_cache->set_owning_group(NULL); // may cause this group to be deleted
} else {
scoped_refptr<AppCacheGroup> protect(this);
Caches::iterator it =
std::find(old_caches_.begin(), old_caches_.end(), cache);
if (it != old_caches_.end()) {
AppCache* tmp_cache = *it;
old_caches_.erase(it);
tmp_cache->set_owning_group(NULL); // may cause group to be released
}
if (!is_obsolete() && old_caches_.empty() &&
!newly_deletable_response_ids_.empty()) {
service_->storage()->DeleteResponses(
manifest_url_, newly_deletable_response_ids_);
newly_deletable_response_ids_.clear();
}
}
}
void AppCacheGroup::AddNewlyDeletableResponseIds(
std::vector<int64>* response_ids) {
if (!is_obsolete() && old_caches_.empty()) {
service_->storage()->DeleteResponses(
manifest_url_, *response_ids);
response_ids->clear();
return;
}
if (newly_deletable_response_ids_.empty()) {
newly_deletable_response_ids_.swap(*response_ids);
return;
}
newly_deletable_response_ids_.insert(
newly_deletable_response_ids_.end(),
response_ids->begin(), response_ids->end());
response_ids->clear();
}
void AppCacheGroup::StartUpdateWithNewMasterEntry(
AppCacheHost* host, const GURL& new_master_resource) {
if (!update_job_)
update_job_ = new AppCacheUpdateJob(service_, this);
update_job_->StartUpdate(host, new_master_resource);
// Run queued update immediately as an update has been started manually.
if (restart_update_task_) {
restart_update_task_->Cancel();
restart_update_task_ = NULL;
RunQueuedUpdates();
}
}
void AppCacheGroup::QueueUpdate(AppCacheHost* host,
const GURL& new_master_resource) {
DCHECK(update_job_ && host && !new_master_resource.is_empty());
queued_updates_.insert(QueuedUpdates::value_type(host, new_master_resource));
// Need to know when host is destroyed.
host->AddObserver(host_observer_.get());
// If host is already observing for updates, move host to queued observers
// list so that host is not notified when the current update completes.
if (FindObserver(host, observers_)) {
observers_.RemoveObserver(host);
queued_observers_.AddObserver(host);
}
}
void AppCacheGroup::RunQueuedUpdates() {
if (restart_update_task_)
restart_update_task_ = NULL;
if (queued_updates_.empty())
return;
QueuedUpdates updates_to_run;
queued_updates_.swap(updates_to_run);
DCHECK(queued_updates_.empty());
for (QueuedUpdates::iterator it = updates_to_run.begin();
it != updates_to_run.end(); ++it) {
AppCacheHost* host = it->first;
host->RemoveObserver(host_observer_.get());
if (FindObserver(host, queued_observers_)) {
queued_observers_.RemoveObserver(host);
observers_.AddObserver(host);
}
if (!is_obsolete())
StartUpdateWithNewMasterEntry(host, it->second);
}
}
bool AppCacheGroup::FindObserver(UpdateObserver* find_me,
const ObserverList<UpdateObserver>& observer_list) {
ObserverList<UpdateObserver>::Iterator it(observer_list);
UpdateObserver* obs;
while ((obs = it.GetNext()) != NULL) {
if (obs == find_me)
return true;
}
return false;
}
void AppCacheGroup::ScheduleUpdateRestart(int delay_ms) {
DCHECK(!restart_update_task_);
restart_update_task_ =
NewRunnableMethod(this, &AppCacheGroup::RunQueuedUpdates);
MessageLoop::current()->PostDelayedTask(FROM_HERE, restart_update_task_,
delay_ms);
}
void AppCacheGroup::HostDestructionImminent(AppCacheHost* host) {
queued_updates_.erase(host);
if (queued_updates_.empty() && restart_update_task_) {
restart_update_task_->Cancel();
restart_update_task_ = NULL;
}
}
void AppCacheGroup::SetUpdateStatus(UpdateStatus status) {
if (status == update_status_)
return;
update_status_ = status;
if (status != IDLE) {
DCHECK(update_job_);
} else {
update_job_ = NULL;
// Check member variable before notifying observers about update finishing.
// Observers may remove reference to group, causing group to be deleted
// after the notifications. If there are queued updates, then the group
// will continue to exist.
bool restart_update = !queued_updates_.empty();
FOR_EACH_OBSERVER(UpdateObserver, observers_, OnUpdateComplete(this));
if (restart_update)
ScheduleUpdateRestart(kUpdateRestartDelayMs);
}
}
} // namespace appcache
<|endoftext|>
|
<commit_before>/*++
Copyright (c) 2012 Microsoft Corporation
Module Name:
fpa2bv_tactic.cpp
Abstract:
Tactic that converts floating points to bit-vectors
Author:
Christoph (cwinter) 2012-02-09
Notes:
--*/
#include"tactical.h"
#include"fpa2bv_rewriter.h"
#include"simplify_tactic.h"
#include"fpa2bv_tactic.h"
#include"fpa2bv_model_converter.h"
class fpa2bv_tactic : public tactic {
struct imp {
ast_manager & m;
fpa2bv_converter m_conv;
fpa2bv_rewriter m_rw;
unsigned m_num_steps;
bool m_proofs_enabled;
bool m_produce_models;
bool m_produce_unsat_cores;
imp(ast_manager & _m, params_ref const & p):
m(_m),
m_conv(m),
m_rw(m, m_conv, p),
m_proofs_enabled(false),
m_produce_models(false),
m_produce_unsat_cores(false) {
}
void updt_params(params_ref const & p) {
m_rw.cfg().updt_params(p);
}
virtual void operator()(goal_ref const & g,
goal_ref_buffer & result,
model_converter_ref & mc,
proof_converter_ref & pc,
expr_dependency_ref & core) {
SASSERT(g->is_well_sorted());
m_proofs_enabled = g->proofs_enabled();
m_produce_models = g->models_enabled();
m_produce_unsat_cores = g->unsat_core_enabled();
mc = 0; pc = 0; core = 0; result.reset();
tactic_report report("fpa2bv", *g);
m_rw.reset();
TRACE("fpa2bv", tout << "BEFORE: " << std::endl; g->display(tout););
if (g->inconsistent()) {
result.push_back(g.get());
return;
}
m_num_steps = 0;
expr_ref new_curr(m);
proof_ref new_pr(m);
unsigned size = g->size();
for (unsigned idx = 0; idx < size; idx++) {
if (g->inconsistent())
break;
expr * curr = g->form(idx);
m_rw(curr, new_curr, new_pr);
m_num_steps += m_rw.get_num_steps();
if (m_proofs_enabled) {
proof * pr = g->pr(idx);
new_pr = m.mk_modus_ponens(pr, new_pr);
}
g->update(idx, new_curr, new_pr, g->dep(idx));
if (is_app(new_curr)) {
const app * a = to_app(new_curr.get());
if (a->get_family_id() == m_conv.fu().get_family_id() &&
a->get_decl_kind() == OP_FPA_IS_NAN) {
// Inject auxiliary lemmas that fix e to the one and only NaN value,
// that is (= e (fp #b0 #b1...1 #b0...01)), so that the value propagation
// has a value to propagate.
expr * sgn, *sig, *exp;
expr_ref top_exp(m);
m_conv.split_fp(new_curr, sgn, exp, sig);
m.mk_eq(sgn, m_conv.bu().mk_numeral(0, 1));
m.mk_eq(exp, m_conv.bu().mk_numeral(-1, m_conv.bu().get_bv_size(exp)));
m.mk_eq(sig, m_conv.bu().mk_numeral(1, m_conv.bu().get_bv_size(sig)));
}
}
}
if (g->models_enabled())
mc = mk_fpa2bv_model_converter(m, m_conv);
g->inc_depth();
result.push_back(g.get());
for (unsigned i = 0; i < m_conv.m_extra_assertions.size(); i++)
result.back()->assert_expr(m_conv.m_extra_assertions[i].get());
SASSERT(g->is_well_sorted());
TRACE("fpa2bv", tout << "AFTER: " << std::endl; g->display(tout);
if (mc) mc->display(tout); tout << std::endl; );
}
};
imp * m_imp;
params_ref m_params;
public:
fpa2bv_tactic(ast_manager & m, params_ref const & p):
m_params(p) {
m_imp = alloc(imp, m, p);
}
virtual tactic * translate(ast_manager & m) {
return alloc(fpa2bv_tactic, m, m_params);
}
virtual ~fpa2bv_tactic() {
dealloc(m_imp);
}
virtual void updt_params(params_ref const & p) {
m_params = p;
m_imp->updt_params(p);
}
virtual void collect_param_descrs(param_descrs & r) {
}
virtual void operator()(goal_ref const & in,
goal_ref_buffer & result,
model_converter_ref & mc,
proof_converter_ref & pc,
expr_dependency_ref & core) {
try {
(*m_imp)(in, result, mc, pc, core);
}
catch (rewriter_exception & ex) {
throw tactic_exception(ex.msg());
}
}
virtual void cleanup() {
imp * d = alloc(imp, m_imp->m, m_params);
std::swap(d, m_imp);
dealloc(d);
}
};
tactic * mk_fpa2bv_tactic(ast_manager & m, params_ref const & p) {
return clean(alloc(fpa2bv_tactic, m, p));
}
<commit_msg>Fixed memory leak in fpa2bv tactic.<commit_after>/*++
Copyright (c) 2012 Microsoft Corporation
Module Name:
fpa2bv_tactic.cpp
Abstract:
Tactic that converts floating points to bit-vectors
Author:
Christoph (cwinter) 2012-02-09
Notes:
--*/
#include"tactical.h"
#include"fpa2bv_rewriter.h"
#include"simplify_tactic.h"
#include"fpa2bv_tactic.h"
#include"fpa2bv_model_converter.h"
class fpa2bv_tactic : public tactic {
struct imp {
ast_manager & m;
fpa2bv_converter m_conv;
fpa2bv_rewriter m_rw;
unsigned m_num_steps;
bool m_proofs_enabled;
bool m_produce_models;
bool m_produce_unsat_cores;
imp(ast_manager & _m, params_ref const & p):
m(_m),
m_conv(m),
m_rw(m, m_conv, p),
m_proofs_enabled(false),
m_produce_models(false),
m_produce_unsat_cores(false) {
}
void updt_params(params_ref const & p) {
m_rw.cfg().updt_params(p);
}
virtual void operator()(goal_ref const & g,
goal_ref_buffer & result,
model_converter_ref & mc,
proof_converter_ref & pc,
expr_dependency_ref & core) {
SASSERT(g->is_well_sorted());
m_proofs_enabled = g->proofs_enabled();
m_produce_models = g->models_enabled();
m_produce_unsat_cores = g->unsat_core_enabled();
mc = 0; pc = 0; core = 0; result.reset();
tactic_report report("fpa2bv", *g);
m_rw.reset();
TRACE("fpa2bv", tout << "BEFORE: " << std::endl; g->display(tout););
if (g->inconsistent()) {
result.push_back(g.get());
return;
}
m_num_steps = 0;
expr_ref new_curr(m);
proof_ref new_pr(m);
unsigned size = g->size();
for (unsigned idx = 0; idx < size; idx++) {
if (g->inconsistent())
break;
expr * curr = g->form(idx);
m_rw(curr, new_curr, new_pr);
m_num_steps += m_rw.get_num_steps();
if (m_proofs_enabled) {
proof * pr = g->pr(idx);
new_pr = m.mk_modus_ponens(pr, new_pr);
}
g->update(idx, new_curr, new_pr, g->dep(idx));
if (is_app(new_curr)) {
const app * a = to_app(new_curr.get());
if (a->get_family_id() == m_conv.fu().get_family_id() &&
a->get_decl_kind() == OP_FPA_IS_NAN) {
// Inject auxiliary lemmas that fix e to the one and only NaN value,
// that is (= e (fp #b0 #b1...1 #b0...01)), so that the value propagation
// has a value to propagate.
expr * sgn, *sig, *exp;
expr_ref top_exp(m);
m_conv.split_fp(new_curr, sgn, exp, sig);
result.back()->assert_expr(m.mk_eq(sgn, m_conv.bu().mk_numeral(0, 1)));
result.back()->assert_expr(m.mk_eq(exp, m_conv.bu().mk_numeral(-1, m_conv.bu().get_bv_size(exp))));
result.back()->assert_expr(m.mk_eq(sig, m_conv.bu().mk_numeral(1, m_conv.bu().get_bv_size(sig))));
}
}
}
if (g->models_enabled())
mc = mk_fpa2bv_model_converter(m, m_conv);
g->inc_depth();
result.push_back(g.get());
for (unsigned i = 0; i < m_conv.m_extra_assertions.size(); i++)
result.back()->assert_expr(m_conv.m_extra_assertions[i].get());
SASSERT(g->is_well_sorted());
TRACE("fpa2bv", tout << "AFTER: " << std::endl; g->display(tout);
if (mc) mc->display(tout); tout << std::endl; );
}
};
imp * m_imp;
params_ref m_params;
public:
fpa2bv_tactic(ast_manager & m, params_ref const & p):
m_params(p) {
m_imp = alloc(imp, m, p);
}
virtual tactic * translate(ast_manager & m) {
return alloc(fpa2bv_tactic, m, m_params);
}
virtual ~fpa2bv_tactic() {
dealloc(m_imp);
}
virtual void updt_params(params_ref const & p) {
m_params = p;
m_imp->updt_params(p);
}
virtual void collect_param_descrs(param_descrs & r) {
}
virtual void operator()(goal_ref const & in,
goal_ref_buffer & result,
model_converter_ref & mc,
proof_converter_ref & pc,
expr_dependency_ref & core) {
try {
(*m_imp)(in, result, mc, pc, core);
}
catch (rewriter_exception & ex) {
throw tactic_exception(ex.msg());
}
}
virtual void cleanup() {
imp * d = alloc(imp, m_imp->m, m_params);
std::swap(d, m_imp);
dealloc(d);
}
};
tactic * mk_fpa2bv_tactic(ast_manager & m, params_ref const & p) {
return clean(alloc(fpa2bv_tactic, m, p));
}
<|endoftext|>
|
<commit_before>// Copyright 2015 Adam Grandquist
#include "./catch.hpp"
#include "./test.hpp"
#include "./reql/types.h"
void
reql_test_cur_end_cb(void *data) {
*static_cast<int*>(data) = 0;
}
void
reql_test_cur_error_cb(void *res, void *data) {
if (res != nullptr) {
*static_cast<int*>(data) = 0;
}
}
int
reql_test_cur_each_cb(void *res, void *data) {
if (res != nullptr) {
++(*static_cast<int*>(data));
}
return res == nullptr;
}
int
reql_test_cur_each_inf_cb(void *res, void *data) {
int *num = static_cast<int*>(data);
if (res != nullptr) {
++(*num);
}
if (*num > 99) {
return 1;
}
return 0;
}
template <typename type>
int
_add(ReQL_Parse_t *, type, size_t);
template <typename type>
int
_add(ReQL_Parse_t *, type);
int
_add(ReQL_Parse_t *);
int
_end_array(ReQL_Parse_t *);
int
_end_element(ReQL_Parse_t *);
int
_end_key_value(ReQL_Parse_t *, const char *, size_t);
int
_end_object(ReQL_Parse_t *);
int
_end_parse(ReQL_Parse_t *);
void
_error(ReQL_Parse_t *);
int
_start_array(ReQL_Parse_t *);
int
_start_element(ReQL_Parse_t *);
int
_start_key_value(ReQL_Parse_t *);
int
_start_object(ReQL_Parse_t *);
int
_start_parse(ReQL_Parse_t *);
Event::Event(std::string name) : p_name(name) {}
Event::Event(std::string name, bool val) : p_bool(val), p_name(name) {}
Event::Event(std::string name, std::string val) : p_name(name), p_str(val) {}
Event::Event(std::string name, double val) : p_name(name), p_num(val) {}
bool Event::operator==(const Event &other) const {
return p_bool == other.p_bool &&
p_name == other.p_name &&
p_num == Approx(other.p_num) &&
p_str == other.p_str;
}
Parser::Parser() : p_events(), p_parser(new ReQL_Parse_t()) {
p_parser->add_bool = _add;
p_parser->add_null = _add;
p_parser->add_number = _add;
p_parser->add_string = _add;
p_parser->data = this;
p_parser->end_array = _end_array;
p_parser->end_element = _end_element;
p_parser->end_key_value = _end_key_value;
p_parser->end_object = _end_object;
p_parser->end_parse = _end_parse;
p_parser->error = _error;
p_parser->start_array = _start_array;
p_parser->start_element = _start_element;
p_parser->start_key_value = _start_key_value;
p_parser->start_object = _start_object;
p_parser->start_parse = _start_parse;
}
Parser::~Parser() {
delete p_parser;
}
ReQL_Parse_t *Parser::get_parser() {
return p_parser;
}
void Parser::add() {
p_events.push_back(Event("add"));
}
void Parser::end_array() {
p_events.push_back(Event("end_array"));
}
void Parser::end_element() {
p_events.push_back(Event("end_element"));
}
void Parser::end_key_value(std::string key) {
p_events.push_back(Event("end_key_value", key));
}
void Parser::end_object() {
p_events.push_back(Event("end_object"));
}
void Parser::end_parse() {
p_events.push_back(Event("end_parse"));
}
void Parser::error() {
p_events.push_back(Event("error"));
}
void Parser::start_array() {
p_events.push_back(Event("start_array"));
}
void Parser::start_element() {
p_events.push_back(Event("start_element"));
}
void Parser::start_key_value() {
p_events.push_back(Event("start_key_value"));
}
void Parser::start_object() {
p_events.push_back(Event("start_object"));
}
void Parser::start_parse() {
p_events.push_back(Event("start_parse"));
}
int
_add(ReQL_Parse_t *p) {
try {
reinterpret_cast<Parser *>(p->data)->add();
} catch (std::exception) {
return -1;
}
return 0;
}
int
_end_array(ReQL_Parse_t *p) {
try {
reinterpret_cast<Parser *>(p->data)->end_array();
} catch (std::exception) {
return -1;
}
return 0;
}
int
_end_element(ReQL_Parse_t *p) {
try {
reinterpret_cast<Parser *>(p->data)->end_element();
} catch (std::exception) {
return -1;
}
return 0;
}
int
_end_key_value(ReQL_Parse_t *p, const char *key, size_t length) {
try {
reinterpret_cast<Parser *>(p->data)->end_key_value(std::string(key, length));
} catch (std::exception) {
return -1;
}
return 0;
}
int
_end_object(ReQL_Parse_t *p) {
try {
reinterpret_cast<Parser *>(p->data)->end_object();
} catch (std::exception) {
return -1;
}
return 0;
}
int
_end_parse(ReQL_Parse_t *p) {
try {
reinterpret_cast<Parser *>(p->data)->end_parse();
} catch (std::exception) {
return -1;
}
return 0;
}
void
_error(ReQL_Parse_t *p) {
try {
reinterpret_cast<Parser *>(p->data)->error();
} catch (std::exception) {
}
}
int
_start_array(ReQL_Parse_t *p) {
try {
reinterpret_cast<Parser *>(p->data)->start_array();
} catch (std::exception) {
return -1;
}
return 0;
}
int
_start_element(ReQL_Parse_t *p) {
try {
reinterpret_cast<Parser *>(p->data)->start_element();
} catch (std::exception) {
return -1;
}
return 0;
}
int
_start_key_value(ReQL_Parse_t *p) {
try {
reinterpret_cast<Parser *>(p->data)->start_key_value();
} catch (std::exception) {
return -1;
}
return 0;
}
int
_start_object(ReQL_Parse_t *p) {
try {
reinterpret_cast<Parser *>(p->data)->start_object();
} catch (std::exception) {
return -1;
}
return 0;
}
int
_start_parse(ReQL_Parse_t *p) {
try {
reinterpret_cast<Parser *>(p->data)->start_parse();
} catch (std::exception) {
return -1;
}
return 0;
}
<commit_msg>Don't declare twice.<commit_after>// Copyright 2015 Adam Grandquist
#include "./catch.hpp"
#include "./test.hpp"
#include "./reql/types.h"
void
reql_test_cur_end_cb(void *data) {
*static_cast<int*>(data) = 0;
}
void
reql_test_cur_error_cb(void *res, void *data) {
if (res != nullptr) {
*static_cast<int*>(data) = 0;
}
}
int
reql_test_cur_each_cb(void *res, void *data) {
if (res != nullptr) {
++(*static_cast<int*>(data));
}
return res == nullptr;
}
int
reql_test_cur_each_inf_cb(void *res, void *data) {
int *num = static_cast<int*>(data);
if (res != nullptr) {
++(*num);
}
if (*num > 99) {
return 1;
}
return 0;
}
Event::Event(std::string name) : p_name(name) {}
Event::Event(std::string name, bool val) : p_bool(val), p_name(name) {}
Event::Event(std::string name, std::string val) : p_name(name), p_str(val) {}
Event::Event(std::string name, double val) : p_name(name), p_num(val) {}
bool Event::operator==(const Event &other) const {
return p_bool == other.p_bool &&
p_name == other.p_name &&
p_num == Approx(other.p_num) &&
p_str == other.p_str;
}
Parser::Parser() : p_events(), p_parser(new ReQL_Parse_t()) {
p_parser->add_bool = _add;
p_parser->add_null = _add;
p_parser->add_number = _add;
p_parser->add_string = _add;
p_parser->data = this;
p_parser->end_array = _end_array;
p_parser->end_element = _end_element;
p_parser->end_key_value = _end_key_value;
p_parser->end_object = _end_object;
p_parser->end_parse = _end_parse;
p_parser->error = _error;
p_parser->start_array = _start_array;
p_parser->start_element = _start_element;
p_parser->start_key_value = _start_key_value;
p_parser->start_object = _start_object;
p_parser->start_parse = _start_parse;
}
Parser::~Parser() {
delete p_parser;
}
ReQL_Parse_t *Parser::get_parser() {
return p_parser;
}
void Parser::add() {
p_events.push_back(Event("add"));
}
void Parser::end_array() {
p_events.push_back(Event("end_array"));
}
void Parser::end_element() {
p_events.push_back(Event("end_element"));
}
void Parser::end_key_value(std::string key) {
p_events.push_back(Event("end_key_value", key));
}
void Parser::end_object() {
p_events.push_back(Event("end_object"));
}
void Parser::end_parse() {
p_events.push_back(Event("end_parse"));
}
void Parser::error() {
p_events.push_back(Event("error"));
}
void Parser::start_array() {
p_events.push_back(Event("start_array"));
}
void Parser::start_element() {
p_events.push_back(Event("start_element"));
}
void Parser::start_key_value() {
p_events.push_back(Event("start_key_value"));
}
void Parser::start_object() {
p_events.push_back(Event("start_object"));
}
void Parser::start_parse() {
p_events.push_back(Event("start_parse"));
}
int
_add(ReQL_Parse_t *p) {
try {
reinterpret_cast<Parser *>(p->data)->add();
} catch (std::exception) {
return -1;
}
return 0;
}
int
_end_array(ReQL_Parse_t *p) {
try {
reinterpret_cast<Parser *>(p->data)->end_array();
} catch (std::exception) {
return -1;
}
return 0;
}
int
_end_element(ReQL_Parse_t *p) {
try {
reinterpret_cast<Parser *>(p->data)->end_element();
} catch (std::exception) {
return -1;
}
return 0;
}
int
_end_key_value(ReQL_Parse_t *p, const char *key, size_t length) {
try {
reinterpret_cast<Parser *>(p->data)->end_key_value(std::string(key, length));
} catch (std::exception) {
return -1;
}
return 0;
}
int
_end_object(ReQL_Parse_t *p) {
try {
reinterpret_cast<Parser *>(p->data)->end_object();
} catch (std::exception) {
return -1;
}
return 0;
}
int
_end_parse(ReQL_Parse_t *p) {
try {
reinterpret_cast<Parser *>(p->data)->end_parse();
} catch (std::exception) {
return -1;
}
return 0;
}
void
_error(ReQL_Parse_t *p) {
try {
reinterpret_cast<Parser *>(p->data)->error();
} catch (std::exception) {
}
}
int
_start_array(ReQL_Parse_t *p) {
try {
reinterpret_cast<Parser *>(p->data)->start_array();
} catch (std::exception) {
return -1;
}
return 0;
}
int
_start_element(ReQL_Parse_t *p) {
try {
reinterpret_cast<Parser *>(p->data)->start_element();
} catch (std::exception) {
return -1;
}
return 0;
}
int
_start_key_value(ReQL_Parse_t *p) {
try {
reinterpret_cast<Parser *>(p->data)->start_key_value();
} catch (std::exception) {
return -1;
}
return 0;
}
int
_start_object(ReQL_Parse_t *p) {
try {
reinterpret_cast<Parser *>(p->data)->start_object();
} catch (std::exception) {
return -1;
}
return 0;
}
int
_start_parse(ReQL_Parse_t *p) {
try {
reinterpret_cast<Parser *>(p->data)->start_parse();
} catch (std::exception) {
return -1;
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TEST_HPP
#define TEST_HPP
#include <boost/config.hpp>
#include <exception>
#include <sstream>
#include "libtorrent/config.hpp"
#ifdef TORRENT_BUILDING_TEST_SHARED
#define EXPORT BOOST_SYMBOL_EXPORT
#else
#define EXPORT BOOST_SYMBOL_IMPORT
#endif
// the unit tests need access to these.
// they are built into the unit test library as well.
// not exported from libtorrent itself
extern "C"
{
int EXPORT ed25519_create_seed(unsigned char *seed);
void EXPORT ed25519_create_keypair(unsigned char *public_key, unsigned char *private_key, const unsigned char *seed);
void EXPORT ed25519_sign(unsigned char *signature, const unsigned char *message, size_t message_len, const unsigned char *public_key, const unsigned char *private_key);
int EXPORT ed25519_verify(const unsigned char *signature, const unsigned char *message, size_t message_len, const unsigned char *private_key);
void EXPORT ed25519_add_scalar(unsigned char *public_key, unsigned char *private_key, const unsigned char *scalar);
void EXPORT ed25519_key_exchange(unsigned char *shared_secret, const unsigned char *public_key, const unsigned char *private_key);
}
void EXPORT report_failure(char const* err, char const* file, int line);
#if defined(_MSC_VER)
#define COUNTER_GUARD(x)
#else
#define COUNTER_GUARD(type) \
struct BOOST_PP_CAT(type, _counter_guard) \
{ \
~BOOST_PP_CAT(type, _counter_guard()) \
{ \
TEST_CHECK(counted_type<type>::count == 0); \
} \
} BOOST_PP_CAT(type, _guard)
#endif
#define TEST_REPORT_AUX(x, line, file) \
report_failure(x, line, file)
#ifdef BOOST_NO_EXCEPTIONS
#define TEST_CHECK(x) \
if (!(x)) \
TEST_REPORT_AUX("TEST_CHECK failed: \"" #x "\"", __FILE__, __LINE__);
#define TEST_EQUAL(x, y) \
if (x != y) { \
std::stringstream s__; \
s__ << "TEST_EQUAL_ERROR:\n" #x ": " << x << "\nexpected: " << y << std::endl; \
TEST_REPORT_AUX(s__.str().c_str(), __FILE__, __LINE__); \
}
#else
#define TEST_CHECK(x) \
try \
{ \
if (!(x)) \
TEST_REPORT_AUX("TEST_CHECK failed: \"" #x "\"", __FILE__, __LINE__); \
} \
catch (std::exception& e) \
{ \
TEST_ERROR("Exception thrown: " #x " :" + std::string(e.what())); \
} \
catch (...) \
{ \
TEST_ERROR("Exception thrown: " #x); \
}
#define TEST_EQUAL(x, y) \
try { \
if (x != y) { \
std::stringstream s__; \
s__ << "TEST_EQUAL_ERROR: " #x ": " << x << " expected: " << y << std::endl; \
TEST_REPORT_AUX(s__.str().c_str(), __FILE__, __LINE__); \
} \
} \
catch (std::exception& e) \
{ \
TEST_ERROR("Exception thrown: " #x " :" + std::string(e.what())); \
} \
catch (...) \
{ \
TEST_ERROR("Exception thrown: " #x); \
}
#endif
#define TEST_ERROR(x) \
TEST_REPORT_AUX((std::string("ERROR: \"") + x + "\"").c_str(), __FILE__, __LINE__)
#define TEST_NOTHROW(x) \
try \
{ \
x; \
} \
catch (...) \
{ \
TEST_ERROR("Exception thrown: " #x); \
}
#endif // TEST_HPP
<commit_msg>one more attempt at fixing windows linking of test<commit_after>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TEST_HPP
#define TEST_HPP
#include <boost/config.hpp>
#include <exception>
#include <sstream>
#include "libtorrent/config.hpp"
#ifdef TORRENT_BUILDING_TEST_SHARED
#define EXPORT BOOST_SYMBOL_EXPORT
#else
#define EXPORT BOOST_SYMBOL_IMPORT
#endif
// the unit tests need access to these.
// they are built into the unit test library as well.
// not exported from libtorrent itself
extern "C"
{
int EXPORT ed25519_create_seed(unsigned char *seed);
void EXPORT ed25519_create_keypair(unsigned char *public_key, unsigned char *private_key, const unsigned char *seed);
void EXPORT ed25519_sign(unsigned char *signature, const unsigned char *message, size_t message_len, const unsigned char *public_key, const unsigned char *private_key);
int EXPORT ed25519_verify(const unsigned char *signature, const unsigned char *message, size_t message_len, const unsigned char *private_key);
void EXPORT ed25519_add_scalar(unsigned char *public_key, unsigned char *private_key, const unsigned char *scalar);
void EXPORT ed25519_key_exchange(unsigned char *shared_secret, const unsigned char *public_key, const unsigned char *private_key);
}
void EXPORT report_failure(char const* err, char const* file, int line);
int EXPORT print_failures();
#if defined(_MSC_VER)
#define COUNTER_GUARD(x)
#else
#define COUNTER_GUARD(type) \
struct BOOST_PP_CAT(type, _counter_guard) \
{ \
~BOOST_PP_CAT(type, _counter_guard()) \
{ \
TEST_CHECK(counted_type<type>::count == 0); \
} \
} BOOST_PP_CAT(type, _guard)
#endif
#define TEST_REPORT_AUX(x, line, file) \
report_failure(x, line, file)
#ifdef BOOST_NO_EXCEPTIONS
#define TEST_CHECK(x) \
if (!(x)) \
TEST_REPORT_AUX("TEST_CHECK failed: \"" #x "\"", __FILE__, __LINE__);
#define TEST_EQUAL(x, y) \
if (x != y) { \
std::stringstream s__; \
s__ << "TEST_EQUAL_ERROR:\n" #x ": " << x << "\nexpected: " << y << std::endl; \
TEST_REPORT_AUX(s__.str().c_str(), __FILE__, __LINE__); \
}
#else
#define TEST_CHECK(x) \
try \
{ \
if (!(x)) \
TEST_REPORT_AUX("TEST_CHECK failed: \"" #x "\"", __FILE__, __LINE__); \
} \
catch (std::exception& e) \
{ \
TEST_ERROR("Exception thrown: " #x " :" + std::string(e.what())); \
} \
catch (...) \
{ \
TEST_ERROR("Exception thrown: " #x); \
}
#define TEST_EQUAL(x, y) \
try { \
if (x != y) { \
std::stringstream s__; \
s__ << "TEST_EQUAL_ERROR: " #x ": " << x << " expected: " << y << std::endl; \
TEST_REPORT_AUX(s__.str().c_str(), __FILE__, __LINE__); \
} \
} \
catch (std::exception& e) \
{ \
TEST_ERROR("Exception thrown: " #x " :" + std::string(e.what())); \
} \
catch (...) \
{ \
TEST_ERROR("Exception thrown: " #x); \
}
#endif
#define TEST_ERROR(x) \
TEST_REPORT_AUX((std::string("ERROR: \"") + x + "\"").c_str(), __FILE__, __LINE__)
#define TEST_NOTHROW(x) \
try \
{ \
x; \
} \
catch (...) \
{ \
TEST_ERROR("Exception thrown: " #x); \
}
#endif // TEST_HPP
<|endoftext|>
|
<commit_before>#include <iostream>
#include <cstdint>
#include <random>
#include <chrono>
#include <vector>
#include <boost/dynamic_bitset.hpp>
#include <bitset>
#include <numeric>
/**
* Lessons learned so far:
* - SIMD registers are used as soon as we compile with -03
* - If we want to get the real speed up (and use all SIMD registers by unfolding both loops,
* we have to know both, input-size and number of comparisons, at compile time.
* - Otherwise, only some of the SIMD registers are used, and speedup is 0, compared to
* code optimized with 02.
* - Example compile command: g++ -std=c++11 -march=native -O3 simd.cpp -o simd
* - Command for getting assembly code: g++ -std=c++11 -march=native -O3 -S simd.cpp
*/
typedef std::mt19937 Engine;
typedef std::uniform_int_distribution<unsigned> Intdistr;
template <typename T, typename U>
void smaller (const T *input, U outputs, const T *comparison_values, const unsigned array_size, const unsigned comparisons) {
for (unsigned i = 0; i < array_size; ++i)
{
for (unsigned m = 0; m < comparisons; ++m) {
outputs[m*array_size+i] = (float) (input[i] < comparison_values[m]);
}
}
}
template <typename T>
void pretty_print (T *arr, unsigned size, std::string s = "Pretty Print") {
std::cout << s << ":" << std::endl;
for (auto r = arr; r < arr+size; ++r ) {
std::cout << *r << std::endl;
}
}
template <typename T>
void compute_stats(const std::vector<T> stats, double &mean, double &stdev) {
double sum = std::accumulate(stats.begin(), stats.end(), 0.0);
mean = sum / stats.size();
std::vector<double> diff(stats.size());
std::transform(stats.begin(), stats.end(), diff.begin(),
std::bind2nd(std::minus<double>(), mean));
double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);
stdev = std::sqrt(sq_sum / stats.size());
}
template <typename T>
void fill (T *arr, unsigned size) {
Engine engine (0);
Intdistr distr (0, 100000);
for (auto r = arr; r < arr+size; ++r ) {
*r = distr(engine);
}
}
int main (int argc, char *argv[]) {
//**** PARAMS ****/
typedef unsigned TestType;
static constexpr unsigned repetitions = 10000;
constexpr unsigned input_size = 2000000;
constexpr unsigned comparisons = 17; // 17 seems to be a magic number...
// if (argc != 3)
// {
// std::cout << "Usage: ./simd <input-size> <comparisons>" << std::endl;
// return -1;
// }
// unsigned long input_size = std::stoi(argv[1]);
// unsigned comparisons = std::stoi(argv[2]);
std::cout << "input size: " << input_size << std::endl;
std::cout << "comparisons: " << comparisons<< std::endl;
//**** INPUT ****/
TestType test_input [input_size];
fill(test_input, input_size);
// pretty_print(test_input, input_size, "Input");
TestType comparison_values [comparisons];
for (unsigned c = 0; c < comparisons; ++c) {
comparison_values[c] = test_input[c];
}
// pretty_print(comparison_values, comparisons, "Comparison values");
//**** COMPUTE ****/
std::vector<unsigned long> stats (repetitions);
// bool results [comparisons * input_size];
std::bitset<comparisons*input_size> results;
// std::vector<bool> results (comparisons * input_size);
// boost::dynamic_bitset<> results(comparisons * input_size);
for (unsigned i = 0; i < repetitions; ++i) {
auto start = std::chrono::high_resolution_clock::now();
smaller(test_input, results, comparison_values, input_size, comparisons);
auto end = std::chrono::high_resolution_clock::now();
stats [i] =
std::chrono::duration_cast<std::chrono::microseconds>(end-start).count();
}
//**** REPORT ****/
double mean, stdev;
compute_stats(stats, mean, stdev);
std::cout
// << "Avg Time [microsecs]: "
<< mean
<< "\t"
// << "(+/- "
<< stdev
// << ")"
<< std::endl;
// pretty_print(stats.data(), repetitions, "Stats");
// for (unsigned c = 0; c < comparisons; ++c) {
// pretty_print(&results[c*input_size], input_size, "Result");
// }
return 0;
}
<commit_msg>templated comparisons seem to work fine<commit_after>#include <iostream>
#include <cstdint>
#include <random>
#include <chrono>
#include <vector>
#include <boost/dynamic_bitset.hpp>
#include <bitset>
#include <numeric>
#include <functional>
/**
* Lessons learned so far:
* - SIMD registers are used as soon as we compile with -03
* - If we want to get the real speed up (and use all SIMD registers by unfolding both loops,
* we have to know both, input-size and number of comparisons, at compile time.
* - Otherwise, only some of the SIMD registers are used, and speedup is 0, compared to
* code optimized with 02.
* - Example compile command: g++ -std=c++11 -march=native -O3 simd.cpp -o simd
* - Command for getting assembly code: g++ -std=c++11 -march=native -O3 -S simd.cpp
* - Function pointers (array of std::function) are very slow. On the other hand, templated functions seem promissing :-)
*/
typedef std::mt19937 Engine;
typedef std::uniform_int_distribution<unsigned> Intdistr;
/**
* takes a bunch of comparison values and an input array and compares each array value
* with each comparison value (with smaller), outputting an array of booleans
*/
template <typename T, typename U>
void smaller (const T *input, U &outputs, const T *comparison_values, const unsigned array_size, const unsigned comparisons) {
for (unsigned i = 0; i < array_size; ++i)
{
for (unsigned m = 0; m < comparisons; ++m) {
outputs[m*array_size+i] = (input[i] < comparison_values[m]);
}
}
}
/**
* takes a bunch of comparison values and an input array and compares each array value
* with each comparison value (alternating smaller and larger), outputting an array of booleans
*/
template <typename T, typename U>
void smaller_greater (const T *input, U &outputs, const T *comparison_values, const unsigned array_size, const unsigned comparisons) {
for (unsigned i = 0; i < array_size; ++i)
{
for (unsigned m = 0; m < comparisons; m+=2) {
outputs[m*array_size+i] = (input[i] < comparison_values[m]);
outputs[(m+1)*array_size+i] = (input[i] > comparison_values[m+1]);
}
}
}
template <typename T, typename U>
void general_compare (const T *input, U &outputs, const T *comparison_values,
const unsigned array_size, const unsigned comparisons,
std::function<bool(T,T)>* comparators) {
for (unsigned i = 0; i < array_size; ++i)
{
for (unsigned m = 0; m < comparisons; ++m) {
outputs[m*array_size+i] = comparators[m](input[i],comparison_values[m]);
}
}
}
template <typename T, typename U, typename Compare>
void templated_compare (const T *input, U &outputs, const T *comparison_values, const unsigned array_size, const unsigned comparisons) {
Compare comp;
for (unsigned i = 0; i < array_size; ++i)
{
for (unsigned m = 0; m < comparisons; ++m) {
outputs[m*array_size+i] = comp (input[i],comparison_values[m]);
}
}
}
template <typename T>
void pretty_print (T arr, unsigned size, std::string s = "Pretty Print", unsigned index = 0) {
// std::cout << s << ":" << std::endl;
// for (unsigned i = 0; i < size; ++i) {
// std::cout << arr[index*size + i] << std::endl;
// }
}
template <typename T>
void compute_stats(const std::vector<T> stats, double &mean, double &stdev) {
double sum = std::accumulate(stats.begin(), stats.end(), 0.0);
mean = sum / stats.size();
std::vector<double> diff(stats.size());
std::transform(stats.begin(), stats.end(), diff.begin(),
std::bind2nd(std::minus<double>(), mean));
double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);
stdev = std::sqrt(sq_sum / stats.size());
}
template <typename T>
void fill (T *arr, unsigned size) {
Engine engine (0);
Intdistr distr (0, 100000);
for (auto r = arr; r < arr+size; ++r ) {
*r = distr(engine);
}
}
template <typename T>
void fillRandomComparators(std::function<bool(T,T)> *comparators, unsigned size)
{
Engine engine (0);
Intdistr distr (0, 5);
unsigned comp;
for (unsigned i = 0; i < size; ++i) {
comp = distr(engine);
switch (comp) {
case 0:
comparators[i] = std::greater<T>();
break;
case 1:
comparators[i] = std::greater_equal<T>();
break;
case 2:
comparators[i] = std::equal_to<T>();
break;
case 3:
comparators[i] = std::not_equal_to<T>();
break;
case 4:
comparators[i] = std::less_equal<T>();
break;
case 5:
comparators[i] = std::less<T>();
break;
}
// std::cout << "Comparator: " << comp << std::endl;
}
}
int main (int argc, char *argv[]) {
//**** PARAMS ****/
typedef unsigned TestType;
static constexpr unsigned repetitions = 10000;
constexpr unsigned input_size = 500000;
constexpr unsigned comparisons = 1; // 17 seems to be a magic number...
// if (argc != 3)
// {
// std::cout << "Usage: ./simd <input-size> <comparisons>" << std::endl;
// return -1;
// }
// unsigned long input_size = std::stoi(argv[1]);
// unsigned comparisons = std::stoi(argv[2]);
std::cout << "input size: " << input_size << std::endl;
std::cout << "comparisons: " << comparisons<< std::endl;
//**** INPUT ****/
TestType test_input [input_size];
fill(test_input, input_size);
pretty_print(test_input, input_size, "Input");
TestType comparison_values [comparisons];
for (unsigned c = 0; c < comparisons; ++c) {
comparison_values[c] = test_input[c];
}
pretty_print(comparison_values, comparisons, "Comparison values");
std::function<bool(TestType,TestType)> comparators [comparisons];
fillRandomComparators(comparators, comparisons);
// std::function<bool(TestType,TestType)> comparators [] = {std::less_equal<TestType>()};
//**** COMPUTE ****/
std::vector<unsigned long> stats (repetitions);
// bool results [comparisons * input_size];
std::bitset<comparisons*input_size> results;
// std::vector<bool> results (comparisons * input_size);
// boost::dynamic_bitset<> results(comparisons * input_size);
for (unsigned i = 0; i < repetitions; ++i) {
auto start = std::chrono::high_resolution_clock::now();
// smaller(test_input, results, comparison_values, input_size, comparisons);
// smaller_greater(test_input, results, comparison_values, input_size, comparisons);
// general_compare(test_input, results, comparison_values, input_size, comparisons, comparators);
templated_compare<TestType, decltype(results), std::greater<TestType>>(test_input, results, comparison_values, input_size, comparisons);
auto end = std::chrono::high_resolution_clock::now();
stats [i] =
std::chrono::duration_cast<std::chrono::microseconds>(end-start).count();
}
//**** REPORT ****/
double mean, stdev;
compute_stats(stats, mean, stdev);
std::cout
// << "Avg Time [microsecs]: "
<< mean
<< "\t"
// << "(+/- "
<< stdev
// << ")"
<< std::endl;
// for (unsigned c = 0; c < comparisons; ++c) {
// pretty_print(results, input_size, std::string("Result"), c);
// }
// std::cout << "Result: " << results << std::endl;
return 0;
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.