text stringlengths 54 60.6k |
|---|
<commit_before>//---------------------------------------------------------- -*- Mode: C++ -*-
// $Id$
//
// Created 2014/01/21
//
// Author: Mike Ovsiannikov
//
// Copyright 2014 Quantcast Corp.
//
// This file is part of Kosmos File System (KFS).
//
// 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.
//
// \brief Meta server administration and monitoring utility.
//
//----------------------------------------------------------------------------
#include "tools/MonClient.h"
#include "common/MsgLogger.h"
#include "qcdio/QCUtils.h"
#include "libclient/KfsOps.h"
#include "libclient/KfsClient.h"
#include <iostream>
#include <sstream>
#include <string>
#include <map>
#include <algorithm>
#include <iomanip>
#include <ctype.h>
#include <unistd.h>
namespace KFS_MON
{
using namespace KFS;
using namespace KFS::client;
using std::map;
using std::make_pair;
using std::string;
using std::cerr;
using std::cout;
using std::setw;
using std::right;
using std::max;
using std::istringstream;
#define KfsForEachMetaOpId(f) \
f(CHECK_LEASES, "debug: run chunk leases check") \
f(RECOMPUTE_DIRSIZE, "debug: recompute directories sizes") \
f(DUMP_CHUNKTOSERVERMAP, "create chunk server to chunk id map" \
" file used by the off line" \
" re-balance utility and layout" \
" emulator" \
) \
f(DUMP_CHUNKREPLICATIONCANDIDATES, "debug: list content of the chunks" \
" re-replication and recovery queues" \
) \
f(OPEN_FILES, "debug: list all chunk leases") \
f(GET_CHUNK_SERVERS_COUNTERS, "stats: output chunk server counters") \
f(GET_CHUNK_SERVER_DIRS_COUNTERS, "stats: output chunk directories" \
" counters") \
f(GET_REQUEST_COUNTERS, "stats: get meta server request" \
" counters") \
f(PING, "stats: list current status counters") \
f(STATS, "stats: list RPC counters") \
f(FSCK, "debug: run fsck") \
f(FORCE_REPLICATION, "debug: force chunk replication or"\
" recovery" \
" Chunk=<id>" \
" [Recovery=1]" \
" [Host=<chunk server ip>]" \
" [Port=<chunk server port>]" \
) \
f(UPSERVERS, "debug: show connected chunk servers")
static string
ToLower(
const char* inStr)
{
string theRet;
const char* thePtr = inStr;
while (*thePtr) {
theRet.push_back((char)tolower(*thePtr++ & 0xFF));
}
return theRet;
}
typedef map<
string,
pair<const char*, pair<KfsOp_t, const char*> >
> MetaAdminOps;
static const pair<MetaAdminOps const*, size_t>&
MakeMetaAdminOpsMap()
{
static MetaAdminOps sOps;
static size_t sMaxCmdNameLen = 0;
if (sOps.empty()) {
sMaxCmdNameLen = 0;
#define InsertAdminOpEntry(name, comment) \
{ \
const string theName = ToLower(#name); \
sOps[theName] = make_pair(#name, \
make_pair(CMD_META_##name, comment)); \
sMaxCmdNameLen = max(sMaxCmdNameLen, theName.size()); \
}
KfsForEachMetaOpId(InsertAdminOpEntry)
#undef InsertAdminOpEntry
}
static const pair<MetaAdminOps const*, size_t> theRet(
&sOps, sMaxCmdNameLen);
return theRet;
}
const MetaAdminOps& sMetaAdminOpsMap = *MakeMetaAdminOpsMap().first;
const size_t sMetaAdminOpMaxLen = MakeMetaAdminOpsMap().second;
static void
CmdHelp(
const char* inNamePtr)
{
if (inNamePtr) {
MetaAdminOps::const_iterator const theIt =
sMetaAdminOpsMap.find(ToLower(inNamePtr));
if (theIt == sMetaAdminOpsMap.end()) {
KFS_LOG_STREAM_ERROR <<
"no such command: " << inNamePtr <<
KFS_LOG_EOM;
} else {
cout << theIt->first << " -- " <<
theIt->second.second.second << "\n";
}
} else {
for (MetaAdminOps::const_iterator theIt = sMetaAdminOpsMap.begin();
theIt != sMetaAdminOpsMap.end();
++theIt) {
cout << setw(sMetaAdminOpMaxLen) << theIt->first << " -- " <<
theIt->second.second.second << "\n";
}
}
}
static int
Main(
int inArgCount,
char** inArgsPtr)
{
bool theHelpFlag = false;
const char* theServerPtr = 0;
const char* theConfigFileNamePtr = 0;
int thePort = -1;
bool theVerboseLoggingFlag = false;
bool theShowHeadersFlag = false;
int theRetCode = 0;
string thePropsStr;
int theOptChar;
while ((theOptChar = getopt(inArgCount, inArgsPtr, "hm:s:p:vf:aF:")) != -1) {
switch (theOptChar) {
case 'm':
case 's':
theServerPtr = optarg;
break;
case 'p':
thePort = atoi(optarg);
break;
case 'h':
theHelpFlag = true;
break;
case 'v':
theVerboseLoggingFlag = true;
break;
case 'f':
theConfigFileNamePtr = optarg;
break;
case 'F':
thePropsStr += optarg;
thePropsStr += "\n";
break;
case 'a':
theShowHeadersFlag = true;
break;
default:
theRetCode = 1;
break;
}
}
if (theHelpFlag || ! theServerPtr || thePort < 0 || inArgCount <= optind) {
(theHelpFlag ? cout : cerr) <<
"Usage: " << inArgsPtr[0] << "\n"
" -m|-s <meta server host name>\n"
" -p <port>\n"
" [-f <config file name>]\n"
" [-a -- show response headers]\n"
" [-v -- verbose]\n"
" [-F <request field name>=<request field value>]\n"
" -- <cmd> <cmd> ...\n"
"Where cmd is one of the following:\n"
;
CmdHelp(0);
return (theHelpFlag ? theRetCode : 1);
}
MsgLogger::Init(0, theVerboseLoggingFlag ?
MsgLogger::kLogLevelDEBUG : MsgLogger::kLogLevelINFO);
const ServerLocation theLocation(theServerPtr, thePort);
MonClient theClient;
if (theClient.SetParameters(theLocation, theConfigFileNamePtr) < 0) {
return 1;
}
theClient.SetMaxContentLength(512 << 20);
Properties theReqProps;
theReqProps.loadProperties(
thePropsStr.data(), thePropsStr.size(), (char)'=');
for (int i = optind; i < inArgCount; i++) {
MetaAdminOps::const_iterator const theIt =
sMetaAdminOpsMap.find(ToLower(inArgsPtr[i]));
if (theIt == sMetaAdminOpsMap.end()) {
KFS_LOG_STREAM_ERROR <<
"no such command: " << inArgsPtr[i] <<
KFS_LOG_EOM;
theRetCode = 1;
} else {
MetaMonOp theOp(
theIt->second.second.first,
theIt->second.first
);
if (! theReqProps.empty()) {
theOp.requestProps = theReqProps;
} else if (theOp.op == CMD_META_FSCK) {
theOp.requestProps.setValue("Report-Abandoned-Files", "1");
}
theClient.SetMaxRpcHeaderLength(
theOp.op == CMD_META_PING ? 512 << 20 : MAX_RPC_HEADER_LEN);
const int theRet = theClient.Execute(theLocation, theOp);
if (theRet < 0) {
KFS_LOG_STREAM_ERROR << theOp.statusMsg <<
" error: " << ErrorCodeToStr(theRet) <<
KFS_LOG_EOM;
theRetCode = 1;
} else {
if (theShowHeadersFlag || theOp.contentLength <= 0) {
Properties::iterator theIt;
size_t theMaxLen = 0;
for (theIt = theOp.responseProps.begin();
theIt != theOp.responseProps.end();
++theIt) {
theMaxLen = max(theMaxLen, theIt->first.size());
}
for (theIt = theOp.responseProps.begin();
theIt != theOp.responseProps.end();
++theIt) {
cout << setw(theMaxLen) << right <<
theIt->first.GetPtr() << ": " <<
theIt->second.GetPtr() << "\n";
}
cout << "\n";
}
if (0 < theOp.contentLength) {
cout.write(theOp.contentBuf, theOp.contentLength);
}
}
}
}
return theRetCode;
}
}
int
main(
int inArgCount,
char** inArgsPtr)
{
return KFS_MON::Main(inArgCount, inArgsPtr);
}
<commit_msg>Tools: admin tool: use long RPC format for backward compatibility by default. Implement -S option to switch to short RPC format. This change makes chunk recovery unit test work again.<commit_after>//---------------------------------------------------------- -*- Mode: C++ -*-
// $Id$
//
// Created 2014/01/21
//
// Author: Mike Ovsiannikov
//
// Copyright 2014 Quantcast Corp.
//
// This file is part of Kosmos File System (KFS).
//
// 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.
//
// \brief Meta server administration and monitoring utility.
//
//----------------------------------------------------------------------------
#include "tools/MonClient.h"
#include "common/MsgLogger.h"
#include "qcdio/QCUtils.h"
#include "libclient/KfsOps.h"
#include "libclient/KfsClient.h"
#include <iostream>
#include <sstream>
#include <string>
#include <map>
#include <algorithm>
#include <iomanip>
#include <ctype.h>
#include <unistd.h>
namespace KFS_MON
{
using namespace KFS;
using namespace KFS::client;
using std::map;
using std::make_pair;
using std::string;
using std::cerr;
using std::cout;
using std::setw;
using std::right;
using std::max;
using std::istringstream;
#define KfsForEachMetaOpId(f) \
f(CHECK_LEASES, "debug: run chunk leases check") \
f(RECOMPUTE_DIRSIZE, "debug: recompute directories sizes") \
f(DUMP_CHUNKTOSERVERMAP, "create chunk server to chunk id map" \
" file used by the off line" \
" re-balance utility and layout" \
" emulator" \
) \
f(DUMP_CHUNKREPLICATIONCANDIDATES, "debug: list content of the chunks" \
" re-replication and recovery queues" \
) \
f(OPEN_FILES, "debug: list all chunk leases") \
f(GET_CHUNK_SERVERS_COUNTERS, "stats: output chunk server counters") \
f(GET_CHUNK_SERVER_DIRS_COUNTERS, "stats: output chunk directories" \
" counters") \
f(GET_REQUEST_COUNTERS, "stats: get meta server request" \
" counters") \
f(PING, "stats: list current status counters") \
f(STATS, "stats: list RPC counters") \
f(FSCK, "debug: run fsck") \
f(FORCE_REPLICATION, "debug: force chunk replication or"\
" recovery" \
" Chunk=<id>" \
" [Recovery=1]" \
" [Host=<chunk server ip>]" \
" [Port=<chunk server port>]" \
) \
f(UPSERVERS, "debug: show connected chunk servers")
static string
ToLower(
const char* inStr)
{
string theRet;
const char* thePtr = inStr;
while (*thePtr) {
theRet.push_back((char)tolower(*thePtr++ & 0xFF));
}
return theRet;
}
typedef map<
string,
pair<const char*, pair<KfsOp_t, const char*> >
> MetaAdminOps;
static const pair<MetaAdminOps const*, size_t>&
MakeMetaAdminOpsMap()
{
static MetaAdminOps sOps;
static size_t sMaxCmdNameLen = 0;
if (sOps.empty()) {
sMaxCmdNameLen = 0;
#define InsertAdminOpEntry(name, comment) \
{ \
const string theName = ToLower(#name); \
sOps[theName] = make_pair(#name, \
make_pair(CMD_META_##name, comment)); \
sMaxCmdNameLen = max(sMaxCmdNameLen, theName.size()); \
}
KfsForEachMetaOpId(InsertAdminOpEntry)
#undef InsertAdminOpEntry
}
static const pair<MetaAdminOps const*, size_t> theRet(
&sOps, sMaxCmdNameLen);
return theRet;
}
const MetaAdminOps& sMetaAdminOpsMap = *MakeMetaAdminOpsMap().first;
const size_t sMetaAdminOpMaxLen = MakeMetaAdminOpsMap().second;
static void
CmdHelp(
const char* inNamePtr)
{
if (inNamePtr) {
MetaAdminOps::const_iterator const theIt =
sMetaAdminOpsMap.find(ToLower(inNamePtr));
if (theIt == sMetaAdminOpsMap.end()) {
KFS_LOG_STREAM_ERROR <<
"no such command: " << inNamePtr <<
KFS_LOG_EOM;
} else {
cout << theIt->first << " -- " <<
theIt->second.second.second << "\n";
}
} else {
for (MetaAdminOps::const_iterator theIt = sMetaAdminOpsMap.begin();
theIt != sMetaAdminOpsMap.end();
++theIt) {
cout << setw(sMetaAdminOpMaxLen) << theIt->first << " -- " <<
theIt->second.second.second << "\n";
}
}
}
static int
Main(
int inArgCount,
char** inArgsPtr)
{
bool theHelpFlag = false;
const char* theServerPtr = 0;
const char* theConfigFileNamePtr = 0;
int thePort = -1;
bool theVerboseLoggingFlag = false;
bool theShowHeadersFlag = false;
bool theShortRpcFmtFlag = false;
int theRetCode = 0;
string thePropsStr;
int theOptChar;
while ((theOptChar = getopt(inArgCount, inArgsPtr, "hm:s:p:vf:aF:S")) != -1) {
switch (theOptChar) {
case 'm':
case 's':
theServerPtr = optarg;
break;
case 'p':
thePort = atoi(optarg);
break;
case 'h':
theHelpFlag = true;
break;
case 'v':
theVerboseLoggingFlag = true;
break;
case 'f':
theConfigFileNamePtr = optarg;
break;
case 'F':
thePropsStr += optarg;
thePropsStr += "\n";
break;
case 'S':
theShortRpcFmtFlag = true;
break;
case 'a':
theShowHeadersFlag = true;
break;
default:
theRetCode = 1;
break;
}
}
if (theHelpFlag || ! theServerPtr || thePort < 0 || inArgCount <= optind) {
(theHelpFlag ? cout : cerr) <<
"Usage: " << inArgsPtr[0] << "\n"
" -m|-s <meta server host name>\n"
" -p <port>\n"
" [-f <config file name>]\n"
" [-a -- show response headers]\n"
" [-v -- verbose]\n"
" [-F <request field name>=<request field value>]\n"
" [-S -- use short rpc format]\n"
" -- <cmd> <cmd> ...\n"
"Where cmd is one of the following:\n"
;
CmdHelp(0);
return (theHelpFlag ? theRetCode : 1);
}
MsgLogger::Init(0, theVerboseLoggingFlag ?
MsgLogger::kLogLevelDEBUG : MsgLogger::kLogLevelINFO);
const ServerLocation theLocation(theServerPtr, thePort);
MonClient theClient;
if (theClient.SetParameters(theLocation, theConfigFileNamePtr) < 0) {
return 1;
}
theClient.SetMaxContentLength(512 << 20);
theClient.SetRpcFormat(theShortRpcFmtFlag ?
MonClient::kRpcFormatShort : MonClient::kRpcFormatLong);
Properties theReqProps;
theReqProps.loadProperties(
thePropsStr.data(), thePropsStr.size(), (char)'=');
for (int i = optind; i < inArgCount; i++) {
MetaAdminOps::const_iterator const theIt =
sMetaAdminOpsMap.find(ToLower(inArgsPtr[i]));
if (theIt == sMetaAdminOpsMap.end()) {
KFS_LOG_STREAM_ERROR <<
"no such command: " << inArgsPtr[i] <<
KFS_LOG_EOM;
theRetCode = 1;
} else {
MetaMonOp theOp(
theIt->second.second.first,
theIt->second.first
);
if (! theReqProps.empty()) {
theOp.requestProps = theReqProps;
} else if (theOp.op == CMD_META_FSCK) {
theOp.requestProps.setValue("Report-Abandoned-Files", "1");
}
theClient.SetMaxRpcHeaderLength(
theOp.op == CMD_META_PING ? 512 << 20 : MAX_RPC_HEADER_LEN);
const int theRet = theClient.Execute(theLocation, theOp);
if (theRet < 0) {
KFS_LOG_STREAM_ERROR << theOp.statusMsg <<
" error: " << ErrorCodeToStr(theRet) <<
KFS_LOG_EOM;
theRetCode = 1;
} else {
if (theShowHeadersFlag || theOp.contentLength <= 0) {
Properties::iterator theIt;
size_t theMaxLen = 0;
for (theIt = theOp.responseProps.begin();
theIt != theOp.responseProps.end();
++theIt) {
theMaxLen = max(theMaxLen, theIt->first.size());
}
for (theIt = theOp.responseProps.begin();
theIt != theOp.responseProps.end();
++theIt) {
cout << setw(theMaxLen) << right <<
theIt->first.GetPtr() << ": " <<
theIt->second.GetPtr() << "\n";
}
cout << "\n";
}
if (0 < theOp.contentLength) {
cout.write(theOp.contentBuf, theOp.contentLength);
}
}
}
}
return theRetCode;
}
}
int
main(
int inArgCount,
char** inArgsPtr)
{
return KFS_MON::Main(inArgCount, inArgsPtr);
}
<|endoftext|> |
<commit_before><commit_msg>Fix typo in twoStageSynchronousLoopback test<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: grfitem.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: mba $ $Date: 2002-05-22 12:03:50 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#define ITEMID_GRF_CROP 0
#ifndef _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#ifndef _SVX_GRFCROP_HXX
#include <grfcrop.hxx>
#endif
#ifndef _SVX_ITEMTYPE_HXX //autogen
#include <itemtype.hxx>
#endif
#ifndef _COM_SUN_STAR_TEXT_GRAPHICCROP_HPP_
#include <com/sun/star/text/GraphicCrop.hpp>
#endif
using namespace ::com::sun::star;
#define TWIP_TO_MM100(TWIP) ((TWIP) >= 0 ? (((TWIP)*127L+36L)/72L) : (((TWIP)*127L-36L)/72L))
#define MM100_TO_TWIP(MM100) ((MM100) >= 0 ? (((MM100)*72L+63L)/127L) : (((MM100)*72L-63L)/127L))
//TYPEINIT1_AUTOFACTORY( SvxGrfCrop, SfxPoolItem )
/******************************************************************************
* Implementierung class SwCropGrf
******************************************************************************/
SvxGrfCrop::SvxGrfCrop( USHORT nItemId )
: SfxPoolItem( nItemId ),
nLeft( 0 ), nRight( 0 ), nTop( 0 ), nBottom( 0 )
{}
SvxGrfCrop::SvxGrfCrop( sal_Int32 nL, sal_Int32 nR,
sal_Int32 nT, sal_Int32 nB, USHORT nItemId )
: SfxPoolItem( nItemId ),
nLeft( nL ), nRight( nR ), nTop( nT ), nBottom( nB )
{}
SvxGrfCrop::~SvxGrfCrop()
{
}
int SvxGrfCrop::operator==( const SfxPoolItem& rAttr ) const
{
DBG_ASSERT( SfxPoolItem::operator==( rAttr ), "not equal attributes" );
return nLeft == ((const SvxGrfCrop&)rAttr).GetLeft() &&
nRight == ((const SvxGrfCrop&)rAttr).GetRight() &&
nTop == ((const SvxGrfCrop&)rAttr).GetTop() &&
nBottom == ((const SvxGrfCrop&)rAttr).GetBottom();
}
/*
SfxPoolItem* SvxGrfCrop::Clone( SfxItemPool* ) const
{
return new SvxGrfCrop( *this );
}
*/
/*
USHORT SvxGrfCrop::GetVersion( USHORT nFFVer ) const
{
DBG_ASSERT( SOFFICE_FILEFORMAT_31==nFFVer ||
SOFFICE_FILEFORMAT_40==nFFVer ||
SOFFICE_FILEFORMAT_NOW==nFFVer,
"SvxGrfCrop: exist a new fileformat?" );
return GRFCROP_VERSION_SWDEFAULT;
}
*/
SfxPoolItem* SvxGrfCrop::Create( SvStream& rStrm, USHORT nVersion ) const
{
INT32 top, left, right, bottom;
rStrm >> top >> left >> right >> bottom;
if( GRFCROP_VERSION_SWDEFAULT == nVersion )
top = -top, bottom = -bottom, left = -left, right = -right;
SvxGrfCrop* pNew = (SvxGrfCrop*)Clone();
pNew->SetLeft( left );
pNew->SetRight( right );
pNew->SetTop( top );
pNew->SetBottom( bottom );
return pNew;
}
SvStream& SvxGrfCrop::Store( SvStream& rStrm, USHORT nVersion ) const
{
INT32 left = GetLeft(), right = GetRight(),
top = GetTop(), bottom = GetBottom();
if( GRFCROP_VERSION_SWDEFAULT == nVersion )
top = -top, bottom = -bottom, left = -left, right = -right;
rStrm << top << left << right << bottom;
return rStrm;
}
BOOL SvxGrfCrop::QueryValue( uno::Any& rVal, BYTE nMemberId ) const
{
sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);
nMemberId &= ~CONVERT_TWIPS;
text::GraphicCrop aRet;
aRet.Left = nLeft;
aRet.Right = nRight;
aRet.Top = nTop;
aRet.Bottom = nBottom;
if( bConvert )
{
aRet.Right = TWIP_TO_MM100(aRet.Right );
aRet.Top = TWIP_TO_MM100(aRet.Top );
aRet.Left = TWIP_TO_MM100(aRet.Left );
aRet.Bottom = TWIP_TO_MM100(aRet.Bottom);
}
rVal <<= aRet;
return sal_True;
}
BOOL SvxGrfCrop::PutValue( const uno::Any& rVal, BYTE nMemberId )
{
sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);
nMemberId &= ~CONVERT_TWIPS;
text::GraphicCrop aVal;
if(!(rVal >>= aVal))
return sal_False;
if( bConvert )
{
aVal.Right = MM100_TO_TWIP(aVal.Right );
aVal.Top = MM100_TO_TWIP(aVal.Top );
aVal.Left = MM100_TO_TWIP(aVal.Left );
aVal.Bottom = MM100_TO_TWIP(aVal.Bottom);
}
nLeft = aVal.Left ;
nRight = aVal.Right ;
nTop = aVal.Top ;
nBottom = aVal.Bottom;
return sal_True;
}
SfxItemPresentation SvxGrfCrop::GetPresentation(
SfxItemPresentation ePres, SfxMapUnit eCoreUnit, SfxMapUnit ePresUnit,
String &rText, const IntlWrapper* pIntl ) const
{
rText.Erase();
switch( ePres )
{
case SFX_ITEM_PRESENTATION_NAMELESS:
case SFX_ITEM_PRESENTATION_COMPLETE:
if( SFX_ITEM_PRESENTATION_COMPLETE == ePres )
{
( rText.AssignAscii( "L: " )) += ::GetMetricText( GetLeft(),
eCoreUnit, SFX_MAPUNIT_MM );
( rText.AppendAscii( " R: " )) += ::GetMetricText( GetRight(),
eCoreUnit, SFX_MAPUNIT_MM );
( rText.AppendAscii( " T: " )) += ::GetMetricText( GetTop(),
eCoreUnit, SFX_MAPUNIT_MM );
( rText.AppendAscii( " B: " )) += ::GetMetricText( GetBottom(),
eCoreUnit, SFX_MAPUNIT_MM );
}
break;
default:
ePres = SFX_ITEM_PRESENTATION_NONE;
break;
}
return ePres;
}
<commit_msg>INTEGRATION: CWS os7 (1.5.150); FILE MERGED 2003/03/28 12:02:33 os 1.5.150.1: #108241# set decimal separator correctly in SfxPoolItem::GetPresentation() methods<commit_after>/*************************************************************************
*
* $RCSfile: grfitem.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2003-04-04 18:03:17 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#define ITEMID_GRF_CROP 0
#ifndef _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#ifndef _SVX_GRFCROP_HXX
#include <grfcrop.hxx>
#endif
#ifndef _SVX_ITEMTYPE_HXX //autogen
#include <itemtype.hxx>
#endif
#ifndef _COM_SUN_STAR_TEXT_GRAPHICCROP_HPP_
#include <com/sun/star/text/GraphicCrop.hpp>
#endif
using namespace ::com::sun::star;
#define TWIP_TO_MM100(TWIP) ((TWIP) >= 0 ? (((TWIP)*127L+36L)/72L) : (((TWIP)*127L-36L)/72L))
#define MM100_TO_TWIP(MM100) ((MM100) >= 0 ? (((MM100)*72L+63L)/127L) : (((MM100)*72L-63L)/127L))
//TYPEINIT1_AUTOFACTORY( SvxGrfCrop, SfxPoolItem )
/******************************************************************************
* Implementierung class SwCropGrf
******************************************************************************/
SvxGrfCrop::SvxGrfCrop( USHORT nItemId )
: SfxPoolItem( nItemId ),
nLeft( 0 ), nRight( 0 ), nTop( 0 ), nBottom( 0 )
{}
SvxGrfCrop::SvxGrfCrop( sal_Int32 nL, sal_Int32 nR,
sal_Int32 nT, sal_Int32 nB, USHORT nItemId )
: SfxPoolItem( nItemId ),
nLeft( nL ), nRight( nR ), nTop( nT ), nBottom( nB )
{}
SvxGrfCrop::~SvxGrfCrop()
{
}
int SvxGrfCrop::operator==( const SfxPoolItem& rAttr ) const
{
DBG_ASSERT( SfxPoolItem::operator==( rAttr ), "not equal attributes" );
return nLeft == ((const SvxGrfCrop&)rAttr).GetLeft() &&
nRight == ((const SvxGrfCrop&)rAttr).GetRight() &&
nTop == ((const SvxGrfCrop&)rAttr).GetTop() &&
nBottom == ((const SvxGrfCrop&)rAttr).GetBottom();
}
/*
SfxPoolItem* SvxGrfCrop::Clone( SfxItemPool* ) const
{
return new SvxGrfCrop( *this );
}
*/
/*
USHORT SvxGrfCrop::GetVersion( USHORT nFFVer ) const
{
DBG_ASSERT( SOFFICE_FILEFORMAT_31==nFFVer ||
SOFFICE_FILEFORMAT_40==nFFVer ||
SOFFICE_FILEFORMAT_NOW==nFFVer,
"SvxGrfCrop: exist a new fileformat?" );
return GRFCROP_VERSION_SWDEFAULT;
}
*/
SfxPoolItem* SvxGrfCrop::Create( SvStream& rStrm, USHORT nVersion ) const
{
INT32 top, left, right, bottom;
rStrm >> top >> left >> right >> bottom;
if( GRFCROP_VERSION_SWDEFAULT == nVersion )
top = -top, bottom = -bottom, left = -left, right = -right;
SvxGrfCrop* pNew = (SvxGrfCrop*)Clone();
pNew->SetLeft( left );
pNew->SetRight( right );
pNew->SetTop( top );
pNew->SetBottom( bottom );
return pNew;
}
SvStream& SvxGrfCrop::Store( SvStream& rStrm, USHORT nVersion ) const
{
INT32 left = GetLeft(), right = GetRight(),
top = GetTop(), bottom = GetBottom();
if( GRFCROP_VERSION_SWDEFAULT == nVersion )
top = -top, bottom = -bottom, left = -left, right = -right;
rStrm << top << left << right << bottom;
return rStrm;
}
BOOL SvxGrfCrop::QueryValue( uno::Any& rVal, BYTE nMemberId ) const
{
sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);
nMemberId &= ~CONVERT_TWIPS;
text::GraphicCrop aRet;
aRet.Left = nLeft;
aRet.Right = nRight;
aRet.Top = nTop;
aRet.Bottom = nBottom;
if( bConvert )
{
aRet.Right = TWIP_TO_MM100(aRet.Right );
aRet.Top = TWIP_TO_MM100(aRet.Top );
aRet.Left = TWIP_TO_MM100(aRet.Left );
aRet.Bottom = TWIP_TO_MM100(aRet.Bottom);
}
rVal <<= aRet;
return sal_True;
}
BOOL SvxGrfCrop::PutValue( const uno::Any& rVal, BYTE nMemberId )
{
sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);
nMemberId &= ~CONVERT_TWIPS;
text::GraphicCrop aVal;
if(!(rVal >>= aVal))
return sal_False;
if( bConvert )
{
aVal.Right = MM100_TO_TWIP(aVal.Right );
aVal.Top = MM100_TO_TWIP(aVal.Top );
aVal.Left = MM100_TO_TWIP(aVal.Left );
aVal.Bottom = MM100_TO_TWIP(aVal.Bottom);
}
nLeft = aVal.Left ;
nRight = aVal.Right ;
nTop = aVal.Top ;
nBottom = aVal.Bottom;
return sal_True;
}
SfxItemPresentation SvxGrfCrop::GetPresentation(
SfxItemPresentation ePres, SfxMapUnit eCoreUnit, SfxMapUnit ePresUnit,
String &rText, const IntlWrapper* pIntl ) const
{
rText.Erase();
switch( ePres )
{
case SFX_ITEM_PRESENTATION_NAMELESS:
case SFX_ITEM_PRESENTATION_COMPLETE:
if( SFX_ITEM_PRESENTATION_COMPLETE == ePres )
{
( rText.AssignAscii( "L: " )) += ::GetMetricText( GetLeft(),
eCoreUnit, SFX_MAPUNIT_MM, pIntl );
( rText.AppendAscii( " R: " )) += ::GetMetricText( GetRight(),
eCoreUnit, SFX_MAPUNIT_MM, pIntl );
( rText.AppendAscii( " T: " )) += ::GetMetricText( GetTop(),
eCoreUnit, SFX_MAPUNIT_MM, pIntl );
( rText.AppendAscii( " B: " )) += ::GetMetricText( GetBottom(),
eCoreUnit, SFX_MAPUNIT_MM, pIntl );
}
break;
default:
ePres = SFX_ITEM_PRESENTATION_NONE;
break;
}
return ePres;
}
<|endoftext|> |
<commit_before>// Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <base/gserrors.h>
#include <psi/iapi.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
static const unsigned char *g_data;
static size_t g_size;
#define min(x, y) ((x) < (y) ? (x) : (y))
static int gs_stdin(void *inst, char *buf, int len)
{
size_t to_copy = min(len, g_size);
to_copy = min(INT_MAX, to_copy);
memcpy(buf, g_data, to_copy);
g_data += to_copy;
g_size -= to_copy;
return to_copy;
}
static int gs_stdout(void *inst, const char *buf, int len)
{
/* Just discard everything. */
return len;
}
static int gs_to_raster_fuzz(const unsigned char *buf, size_t size)
{
int ret;
void *gs = NULL;
/* Mostly stolen from cups-filters gstoraster. */
char *args[] = {
"gs",
"-K1048576",
"-r200x200",
"-dMediaPosition=1",
"-dcupsColorSpace=1", /* RGB */
"-dQUIET",
"-dPARANOIDSAFER",
"-dNOPAUSE",
"-dBATCH",
"-dNOINTERPOLATE",
"-dNOMEDIAATTRS",
"-sstdout=%stderr",
"-sOutputFile=%stdout",
"-sDEVICE=cups",
"-_",
};
int argc = sizeof(args) / sizeof(args[0]);
/* Stash buffers globally, for gs_stdin(). */
g_data = buf;
g_size = size;
ret = gsapi_new_instance(&gs, NULL);
if (ret < 0) {
fprintf(stderr, "gsapi_new_instance: error %d\n", ret);
return ret;
}
gsapi_set_stdio(gs, gs_stdin, gs_stdout, NULL /* stderr */);
ret = gsapi_set_arg_encoding(gs, GS_ARG_ENCODING_UTF8);
if (ret < 0) {
fprintf(stderr, "gsapi_set_arg_encoding: error %d\n", ret);
gsapi_delete_instance(gs);
return ret;
}
ret = gsapi_init_with_args(gs, argc, args);
if (ret && ret != gs_error_Quit)
/* Just keep going, to cleanup. */
fprintf(stderr, "gsapi_init_with_args: error %d\n", ret);
ret = gsapi_exit(gs);
if (ret < 0 && ret != gs_error_Quit) {
fprintf(stderr, "gsapi_exit: error %d\n", ret);
return ret;
}
gsapi_delete_instance(gs);
return 0;
}
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
gs_to_raster_fuzz(data, size);
return 0;
}
<commit_msg>[ghostscript] Relicense target fuzzer under Apache 2.0 license. (#3440)<commit_after>/*
# Copyright 2019 The Chromium OS Authors.
#
# 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 <base/gserrors.h>
#include <psi/iapi.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
static const unsigned char *g_data;
static size_t g_size;
#define min(x, y) ((x) < (y) ? (x) : (y))
static int gs_stdin(void *inst, char *buf, int len)
{
size_t to_copy = min(len, g_size);
to_copy = min(INT_MAX, to_copy);
memcpy(buf, g_data, to_copy);
g_data += to_copy;
g_size -= to_copy;
return to_copy;
}
static int gs_stdout(void *inst, const char *buf, int len)
{
/* Just discard everything. */
return len;
}
static int gs_to_raster_fuzz(const unsigned char *buf, size_t size)
{
int ret;
void *gs = NULL;
/* Mostly stolen from cups-filters gstoraster. */
char *args[] = {
"gs",
"-K1048576",
"-r200x200",
"-dMediaPosition=1",
"-dcupsColorSpace=1", /* RGB */
"-dQUIET",
"-dPARANOIDSAFER",
"-dNOPAUSE",
"-dBATCH",
"-dNOINTERPOLATE",
"-dNOMEDIAATTRS",
"-sstdout=%stderr",
"-sOutputFile=%stdout",
"-sDEVICE=cups",
"-_",
};
int argc = sizeof(args) / sizeof(args[0]);
/* Stash buffers globally, for gs_stdin(). */
g_data = buf;
g_size = size;
ret = gsapi_new_instance(&gs, NULL);
if (ret < 0) {
fprintf(stderr, "gsapi_new_instance: error %d\n", ret);
return ret;
}
gsapi_set_stdio(gs, gs_stdin, gs_stdout, NULL /* stderr */);
ret = gsapi_set_arg_encoding(gs, GS_ARG_ENCODING_UTF8);
if (ret < 0) {
fprintf(stderr, "gsapi_set_arg_encoding: error %d\n", ret);
gsapi_delete_instance(gs);
return ret;
}
ret = gsapi_init_with_args(gs, argc, args);
if (ret && ret != gs_error_Quit)
/* Just keep going, to cleanup. */
fprintf(stderr, "gsapi_init_with_args: error %d\n", ret);
ret = gsapi_exit(gs);
if (ret < 0 && ret != gs_error_Quit) {
fprintf(stderr, "gsapi_exit: error %d\n", ret);
return ret;
}
gsapi_delete_instance(gs);
return 0;
}
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
gs_to_raster_fuzz(data, size);
return 0;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/
#include <pdal/FileUtils.hpp>
#include <pdal/drivers/las/Reader.hpp>
#include <pdal/drivers/las/Writer.hpp>
#ifdef PDAL_HAVE_ORACLE
#include <pdal/drivers/oci/Writer.hpp>
#include <pdal/drivers/oci/Reader.hpp>
#endif
#include <pdal/filters/Cache.hpp>
#include <pdal/filters/Chipper.hpp>
#include <pdal/Filters/Crop.hpp>
#include <pdal/filters/InPlaceReprojection.hpp>
#include <pdal/filters/Scaling.hpp>
#include <pdal/SpatialReference.hpp>
#include <pdal/Bounds.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include "AppSupport.hpp"
#include "Application.hpp"
using namespace pdal;
class Pc2Pc : public Application
{
public:
Pc2Pc(int argc, char* argv[]);
int execute();
private:
void addSwitches();
void validateSwitches();
std::string m_inputFile;
std::string m_outputFile;
bool m_bCompress;
boost::uint64_t m_numPointsToWrite;
boost::uint64_t m_numSkipPoints;
pdal::SpatialReference m_input_srs;
pdal::SpatialReference m_output_srs;
pdal::Bounds<double> m_bounds;
std::string m_wkt;
};
Pc2Pc::Pc2Pc(int argc, char* argv[])
: Application(argc, argv, "pc2pc")
, m_inputFile("")
, m_outputFile("")
, m_bCompress(false)
, m_numPointsToWrite(0)
, m_numSkipPoints(0)
, m_input_srs(pdal::SpatialReference())
, m_output_srs(pdal::SpatialReference())
, m_wkt("")
{
return;
}
void Pc2Pc::validateSwitches()
{
if (m_inputFile == "")
{
throw app_usage_error("--input/-i required");
}
if (m_outputFile == "")
{
throw app_usage_error("--output/-o required");
}
return;
}
void Pc2Pc::addSwitches()
{
namespace po = boost::program_options;
po::options_description* file_options = new po::options_description("file options");
file_options->add_options()
("input,i", po::value<std::string>(&m_inputFile)->default_value(""), "input file name")
("output,o", po::value<std::string>(&m_outputFile)->default_value(""), "output file name")
("a_srs", po::value<pdal::SpatialReference>(&m_input_srs), "Assign input coordinate system (if supported by output format)")
("t_srs", po::value<pdal::SpatialReference>(&m_output_srs), "Transform to output coordinate system (if supported by output format)")
("compress,z", po::value<bool>(&m_bCompress)->zero_tokens()->implicit_value(true), "Compress output data (if supported by output format)")
("count", po::value<boost::uint64_t>(&m_numPointsToWrite)->default_value(0), "How many points should we write?")
("skip", po::value<boost::uint64_t>(&m_numSkipPoints)->default_value(0), "How many points should we skip?")
("bounds", po::value<pdal::Bounds<double> >(&m_bounds), "Extent (in XYZ to clip output to)")
("polygon", po::value<std::string >(&m_wkt), "POLYGON WKT to use for precise crop of data (2d or 3d)")
;
addSwitchSet(file_options);
addPositionalSwitch("input", 1);
addPositionalSwitch("output", 1);
}
int Pc2Pc::execute()
{
Options readerOptions;
{
readerOptions.add<std::string>("filename", m_inputFile);
readerOptions.add<bool>("debug", isDebug());
readerOptions.add<boost::uint32_t>("verbose", getVerboseLevel());
if (!m_input_srs.empty())
{
readerOptions.add<std::string>("spatialreference", m_input_srs.getWKT());
}
}
Options writerOptions;
{
writerOptions.add<std::string>("filename", m_outputFile);
writerOptions.add<bool>("debug", isDebug());
writerOptions.add<boost::uint32_t>("verbose", getVerboseLevel());
if (!m_input_srs.empty())
{
writerOptions.add<std::string>("spatialreference", m_input_srs.getWKT());
}
if (m_bCompress)
{
writerOptions.add<bool>("compression", true);
}
if (m_chunkSize != 0)
{
writerOptions.add<boost::uint32_t>("chunk_size", m_chunkSize);
}
}
Stage* reader_stage = AppSupport::makeReader(readerOptions);
Stage* final_stage(0);
if (!m_bounds.empty() || !m_wkt.empty() || !m_output_srs.empty())
{
Stage* next_stage = reader_stage;
Stage* crop_stage(0);
Stage* reprojection_stage(0);
if (!m_output_srs.empty())
{
readerOptions.add<std::string >("out_srs", m_output_srs.getWKT());
if (m_output_srs.isGeographic())
{
readerOptions.add<double >("scale_x", 0.0000001);
readerOptions.add<double >("scale_y", 0.0000001);
} else
{
readerOptions.add<double >("scale_x", 0.01);
readerOptions.add<double >("scale_y", 0.01);
}
reprojection_stage = new pdal::filters::InPlaceReprojection(*next_stage, readerOptions);
next_stage = reprojection_stage;
}
if (!m_bounds.empty() && m_wkt.empty())
{
readerOptions.add<pdal::Bounds<double> >("bounds", m_bounds);
crop_stage = new pdal::filters::Crop(*next_stage, readerOptions);
next_stage = crop_stage;
}
else if (m_bounds.empty() && !m_wkt.empty())
{
std::istream* wkt_stream;
try
{
wkt_stream = FileUtils::openFile(m_wkt);
std::stringstream buffer;
buffer << wkt_stream->rdbuf();
m_wkt = buffer.str();
} catch (pdal::pdal_error const&)
{
// If we couldn't open the file given in m_wkt because it
// was likely actually wkt, leave it alone
}
readerOptions.add<std::string >("polygon", m_wkt);
crop_stage = new pdal::filters::Crop(*next_stage, readerOptions);
next_stage = crop_stage;
}
final_stage = next_stage;
}
if (final_stage == 0)
final_stage = reader_stage;
Writer* writer = AppSupport::makeWriter(writerOptions, *final_stage);
if (!m_output_srs.empty())
{
writer->setSpatialReference(m_output_srs);
}
writer->initialize();
const boost::uint64_t numPointsToRead = final_stage->getNumPoints();
boost::scoped_ptr<pdal::UserCallback> callback((numPointsToRead == 0) ?
(pdal::UserCallback*)(new HeartbeatCallback) :
(pdal::UserCallback*)(new PercentageCallback));
writer->setUserCallback(callback.get());
const boost::uint64_t numPointsRead = writer->write(m_numPointsToWrite, m_numSkipPoints);
std::cout << "Wrote " << numPointsRead << " points\n";
delete writer;
delete final_stage;
return 0;
}
int main(int argc, char* argv[])
{
Pc2Pc app(argc, argv);
return app.run();
}
<commit_msg>fix case-sensitive include<commit_after>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/
#include <pdal/FileUtils.hpp>
#include <pdal/drivers/las/Reader.hpp>
#include <pdal/drivers/las/Writer.hpp>
#ifdef PDAL_HAVE_ORACLE
#include <pdal/drivers/oci/Writer.hpp>
#include <pdal/drivers/oci/Reader.hpp>
#endif
#include <pdal/filters/Cache.hpp>
#include <pdal/filters/Chipper.hpp>
#include <pdal/filters/Crop.hpp>
#include <pdal/filters/InPlaceReprojection.hpp>
#include <pdal/filters/Scaling.hpp>
#include <pdal/SpatialReference.hpp>
#include <pdal/Bounds.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include "AppSupport.hpp"
#include "Application.hpp"
using namespace pdal;
class Pc2Pc : public Application
{
public:
Pc2Pc(int argc, char* argv[]);
int execute();
private:
void addSwitches();
void validateSwitches();
std::string m_inputFile;
std::string m_outputFile;
bool m_bCompress;
boost::uint64_t m_numPointsToWrite;
boost::uint64_t m_numSkipPoints;
pdal::SpatialReference m_input_srs;
pdal::SpatialReference m_output_srs;
pdal::Bounds<double> m_bounds;
std::string m_wkt;
};
Pc2Pc::Pc2Pc(int argc, char* argv[])
: Application(argc, argv, "pc2pc")
, m_inputFile("")
, m_outputFile("")
, m_bCompress(false)
, m_numPointsToWrite(0)
, m_numSkipPoints(0)
, m_input_srs(pdal::SpatialReference())
, m_output_srs(pdal::SpatialReference())
, m_wkt("")
{
return;
}
void Pc2Pc::validateSwitches()
{
if (m_inputFile == "")
{
throw app_usage_error("--input/-i required");
}
if (m_outputFile == "")
{
throw app_usage_error("--output/-o required");
}
return;
}
void Pc2Pc::addSwitches()
{
namespace po = boost::program_options;
po::options_description* file_options = new po::options_description("file options");
file_options->add_options()
("input,i", po::value<std::string>(&m_inputFile)->default_value(""), "input file name")
("output,o", po::value<std::string>(&m_outputFile)->default_value(""), "output file name")
("a_srs", po::value<pdal::SpatialReference>(&m_input_srs), "Assign input coordinate system (if supported by output format)")
("t_srs", po::value<pdal::SpatialReference>(&m_output_srs), "Transform to output coordinate system (if supported by output format)")
("compress,z", po::value<bool>(&m_bCompress)->zero_tokens()->implicit_value(true), "Compress output data (if supported by output format)")
("count", po::value<boost::uint64_t>(&m_numPointsToWrite)->default_value(0), "How many points should we write?")
("skip", po::value<boost::uint64_t>(&m_numSkipPoints)->default_value(0), "How many points should we skip?")
("bounds", po::value<pdal::Bounds<double> >(&m_bounds), "Extent (in XYZ to clip output to)")
("polygon", po::value<std::string >(&m_wkt), "POLYGON WKT to use for precise crop of data (2d or 3d)")
;
addSwitchSet(file_options);
addPositionalSwitch("input", 1);
addPositionalSwitch("output", 1);
}
int Pc2Pc::execute()
{
Options readerOptions;
{
readerOptions.add<std::string>("filename", m_inputFile);
readerOptions.add<bool>("debug", isDebug());
readerOptions.add<boost::uint32_t>("verbose", getVerboseLevel());
if (!m_input_srs.empty())
{
readerOptions.add<std::string>("spatialreference", m_input_srs.getWKT());
}
}
Options writerOptions;
{
writerOptions.add<std::string>("filename", m_outputFile);
writerOptions.add<bool>("debug", isDebug());
writerOptions.add<boost::uint32_t>("verbose", getVerboseLevel());
if (!m_input_srs.empty())
{
writerOptions.add<std::string>("spatialreference", m_input_srs.getWKT());
}
if (m_bCompress)
{
writerOptions.add<bool>("compression", true);
}
if (m_chunkSize != 0)
{
writerOptions.add<boost::uint32_t>("chunk_size", m_chunkSize);
}
}
Stage* reader_stage = AppSupport::makeReader(readerOptions);
Stage* final_stage(0);
if (!m_bounds.empty() || !m_wkt.empty() || !m_output_srs.empty())
{
Stage* next_stage = reader_stage;
Stage* crop_stage(0);
Stage* reprojection_stage(0);
if (!m_output_srs.empty())
{
readerOptions.add<std::string >("out_srs", m_output_srs.getWKT());
if (m_output_srs.isGeographic())
{
readerOptions.add<double >("scale_x", 0.0000001);
readerOptions.add<double >("scale_y", 0.0000001);
} else
{
readerOptions.add<double >("scale_x", 0.01);
readerOptions.add<double >("scale_y", 0.01);
}
reprojection_stage = new pdal::filters::InPlaceReprojection(*next_stage, readerOptions);
next_stage = reprojection_stage;
}
if (!m_bounds.empty() && m_wkt.empty())
{
readerOptions.add<pdal::Bounds<double> >("bounds", m_bounds);
crop_stage = new pdal::filters::Crop(*next_stage, readerOptions);
next_stage = crop_stage;
}
else if (m_bounds.empty() && !m_wkt.empty())
{
std::istream* wkt_stream;
try
{
wkt_stream = FileUtils::openFile(m_wkt);
std::stringstream buffer;
buffer << wkt_stream->rdbuf();
m_wkt = buffer.str();
} catch (pdal::pdal_error const&)
{
// If we couldn't open the file given in m_wkt because it
// was likely actually wkt, leave it alone
}
readerOptions.add<std::string >("polygon", m_wkt);
crop_stage = new pdal::filters::Crop(*next_stage, readerOptions);
next_stage = crop_stage;
}
final_stage = next_stage;
}
if (final_stage == 0)
final_stage = reader_stage;
Writer* writer = AppSupport::makeWriter(writerOptions, *final_stage);
if (!m_output_srs.empty())
{
writer->setSpatialReference(m_output_srs);
}
writer->initialize();
const boost::uint64_t numPointsToRead = final_stage->getNumPoints();
boost::scoped_ptr<pdal::UserCallback> callback((numPointsToRead == 0) ?
(pdal::UserCallback*)(new HeartbeatCallback) :
(pdal::UserCallback*)(new PercentageCallback));
writer->setUserCallback(callback.get());
const boost::uint64_t numPointsRead = writer->write(m_numPointsToWrite, m_numSkipPoints);
std::cout << "Wrote " << numPointsRead << " points\n";
delete writer;
delete final_stage;
return 0;
}
int main(int argc, char* argv[])
{
Pc2Pc app(argc, argv);
return app.run();
}
<|endoftext|> |
<commit_before><commit_msg>cppcheck: pColEntry has never been used since the initial import in 2000/09/18<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: optpage.hxx,v $
*
* $Revision: 1.21 $
*
* last change: $Author: hr $ $Date: 2007-09-27 12:06:42 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _OPTPAGE_HXX
#define _OPTPAGE_HXX
#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif
#ifndef _GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _CTRLBOX_HXX //autogen
#include <svtools/ctrlbox.hxx>
#endif
#ifndef _SVX_FNTCTRL_HXX //autogen
#include <svx/fntctrl.hxx>
#endif
#ifndef _FONTCFG_HXX
#include <fontcfg.hxx>
#endif
class SvStringsDtor;
class SfxPrinter;
class SwStdFontConfig;
class SwWrtShell;
class FontList;
/*-----------------31.08.96 10.09-------------------
--------------------------------------------------*/
class SwContentOptPage : public SfxTabPage
{
//visual aids
FixedLine aLineFL;
CheckBox aCrossCB;
CheckBox aSolidHandleCB;
CheckBox aBigHandleCB;
//view
FixedLine aWindowFL;
CheckBox aHScrollBox;
CheckBox aVScrollBox;
CheckBox aAnyRulerCB;
CheckBox aHRulerCBox;
ListBox aHMetric;
CheckBox aVRulerCBox;
CheckBox aVRulerRightCBox;
ListBox aVMetric;
CheckBox aSmoothCBox;
//display
FixedLine aDispFL;
CheckBox aGrfCB;
CheckBox aTblCB;
CheckBox aDrwCB;
CheckBox aFldNameCB;
CheckBox aPostItCB;
FixedLine aSettingsFL;
FixedText aMetricFT;
ListBox aMetricLB;
DECL_LINK(VertRulerHdl, CheckBox*);
DECL_LINK(AnyRulerHdl, CheckBox*);
public:
SwContentOptPage( Window* pParent,
const SfxItemSet& rSet );
~SwContentOptPage();
static SfxTabPage* Create( Window* pParent,
const SfxItemSet& rAttrSet);
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
};
/*-------- OS 27.01.95 -----------------------------------
TabPage Druckereinstellungen Zusaetze
--------------------------------------------------------- */
class SwAddPrinterTabPage : public SfxTabPage
{
FixedLine aFL1;
CheckBox aGrfCB;
CheckBox aTabCB;
CheckBox aDrawCB;
CheckBox aCtrlFldCB;
CheckBox aBackgroundCB;
CheckBox aBlackFontCB;
FixedLine aSeparatorLFL;
FixedLine aFL2;
CheckBox aLeftPageCB;
CheckBox aRightPageCB;
CheckBox aReverseCB;
CheckBox aProspectCB;
CheckBox aProspectCB_RTL;
FixedLine aSeparatorRFL;
RadioButton aNoRB;
RadioButton aOnlyRB;
RadioButton aEndRB;
RadioButton aEndPageRB;
FixedLine aFL3;
FixedLine aFL4;
CheckBox aPrintEmptyPagesCB;
CheckBox aSingleJobsCB;
CheckBox aPaperFromSetupCB;
FixedText aFaxFT;
ListBox aFaxLB;
String sNone;
BOOL bAttrModified;
BOOL bPreview;
void Init();
DECL_LINK( AutoClickHdl, CheckBox * );
DECL_LINK( SelectHdl, ListBox * );
SwAddPrinterTabPage( Window* pParent,
const SfxItemSet& rSet );
public:
static SfxTabPage* Create( Window* pParent,
const SfxItemSet& rAttrSet );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
void SetFax( const SvStringsDtor& );
void SelectFax( const String& );
void SetPreview(BOOL bPrev);
virtual void PageCreated (SfxAllItemSet aSet);
};
/*-----------------03.09.96 11.50-------------------
--------------------------------------------------*/
class SwStdFontTabPage : public SfxTabPage
{
FixedLine aStdChrFL ;
FixedText aTypeFT;
FixedText aStandardLbl;
ComboBox aStandardBox;
FixedText aHeightFT;
FontSizeBox aStandardHeightLB;
FixedText aTitleLbl ;
ComboBox aTitleBox ;
FontSizeBox aTitleHeightLB;
FixedText aListLbl ;
ComboBox aListBox ;
FontSizeBox aListHeightLB;
FixedText aLabelLbl ;
ComboBox aLabelBox ;
FontSizeBox aLabelHeightLB;
FixedText aIdxLbl ;
ComboBox aIdxBox ;
FontSizeBox aIndexHeightLB;
CheckBox aDocOnlyCB ;
PushButton aStandardPB;
String sShellStd;
String sShellTitle;
String sShellList;
String sShellLabel;
String sShellIndex;
SfxPrinter* pPrt;
FontList* pFontList;
SwStdFontConfig* pFontConfig;
SwWrtShell* pWrtShell;
LanguageType eLanguage;
// waren nur defaults vorhanden? wurden sie mit den Boxen ueberschrieben
BOOL bListDefault :1;
BOOL bSetListDefault :1;
BOOL bLabelDefault :1;
BOOL bSetLabelDefault :1;
BOOL bIdxDefault :1;
BOOL bSetIdxDefault :1;
BOOL bDeletePrinter :1;
BOOL bListHeightDefault :1;
BOOL bSetListHeightDefault :1;
BOOL bLabelHeightDefault :1;
BOOL bSetLabelHeightDefault :1;
BOOL bIndexHeightDefault :1;
BOOL bSetIndexHeightDefault :1;
sal_uInt8 nFontGroup; //fontcfg.hxx: FONT_GROUP_[STANDARD|CJK|CTL]
String sScriptWestern;
String sScriptAsian;
String sScriptComplex;
DECL_LINK( StandardHdl, PushButton * );
DECL_LINK( ModifyHdl, ComboBox * );
DECL_LINK( ModifyHeightHdl, FontSizeBox * );
DECL_LINK( LoseFocusHdl, ComboBox * );
SwStdFontTabPage( Window* pParent,
const SfxItemSet& rSet );
~SwStdFontTabPage();
public:
static SfxTabPage* Create( Window* pParent,
const SfxItemSet& rAttrSet );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
void SetFontMode(sal_uInt8 nGroup) {nFontGroup = nGroup;}
virtual void PageCreated (SfxAllItemSet aSet);
};
/*-----------------18.01.97 12.10-------------------
--------------------------------------------------*/
class SwTableOptionsTabPage : public SfxTabPage
{
FixedLine aTableFL;
CheckBox aHeaderCB;
CheckBox aRepeatHeaderCB;
CheckBox aDontSplitCB;
CheckBox aBorderCB;
FixedLine aSeparatorFL;
FixedLine aTableInsertFL;
CheckBox aNumFormattingCB;
CheckBox aNumFmtFormattingCB;
CheckBox aNumAlignmentCB;
FixedLine aMoveFL;
FixedText aMoveFT;
FixedText aRowMoveFT;
MetricField aRowMoveMF;
FixedText aColMoveFT;
MetricField aColMoveMF;
FixedText aInsertFT;
FixedText aRowInsertFT;
MetricField aRowInsertMF;
FixedText aColInsertFT;
MetricField aColInsertMF;
FixedText aHandlingFT;
RadioButton aFixRB;
RadioButton aFixPropRB;
RadioButton aVarRB;
FixedText aFixFT;
FixedText aFixPropFT;
FixedText aVarFT;
SwWrtShell* pWrtShell;
BOOL bHTMLMode;
DECL_LINK(CheckBoxHdl, CheckBox *pCB);
SwTableOptionsTabPage( Window* pParent,
const SfxItemSet& rSet );
~SwTableOptionsTabPage();
public:
static SfxTabPage* Create( Window* pParent,
const SfxItemSet& rAttrSet );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
void SetWrtShell(SwWrtShell* pSh) {pWrtShell = pSh;}
virtual void PageCreated (SfxAllItemSet aSet);
};
/*-----------------31.10.97 17:55-------------------
TabPage fuer ShadowCrsr
--------------------------------------------------*/
class SwShdwCrsrOptionsTabPage : public SfxTabPage
{
//nonprinting characters
FixedLine aUnprintFL;
CheckBox aParaCB;
CheckBox aSHyphCB;
CheckBox aSpacesCB;
CheckBox aHSpacesCB;
CheckBox aTabCB;
CheckBox aBreakCB;
CheckBox aCharHiddenCB;
CheckBox aFldHiddenCB;
CheckBox aFldHiddenParaCB;
FixedLine aSeparatorFL;
FixedLine aFlagFL;
CheckBox aOnOffCB;
FixedText aFillModeFT;
RadioButton aFillMarginRB;
RadioButton aFillIndentRB;
RadioButton aFillTabRB;
RadioButton aFillSpaceRB;
FixedLine aCrsrOptFL;
CheckBox aCrsrInProtCB;
SwShdwCrsrOptionsTabPage( Window* pParent, const SfxItemSet& rSet );
~SwShdwCrsrOptionsTabPage();
public:
static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
};
/*-----------------------------------------------------------------------
Beschreibung: Markierungsvorschau
-----------------------------------------------------------------------*/
class SwMarkPreview : public Window
{
Color m_aBgCol; // background
Color m_aTransCol; // transparency
Color m_aMarkCol; // marks
Color m_aLineCol; // general lines
Color m_aShadowCol; // shadow
Color m_aTxtCol; // text
Color m_aPrintAreaCol; // frame for print area
Rectangle aPage;
Rectangle aLeftPagePrtArea;
Rectangle aRightPagePrtArea;
USHORT nMarkPos;
using OutputDevice::DrawRect;
void DrawRect(const Rectangle &rRect, const Color &rFillColor, const Color &rLineColor);
void Paint(const Rectangle&);
void PaintPage(const Rectangle &rRect);
void InitColors( void );
protected:
virtual void DataChanged( const DataChangedEvent& rDCEvt );
public:
SwMarkPreview(Window* pParent, const ResId& rResID);
virtual ~SwMarkPreview();
inline void SetColor(const Color& rCol) { m_aMarkCol = rCol; }
inline void SetMarkPos(USHORT nPos) { nMarkPos = nPos; }
};
/*-----------------------------------------------------------------------
Beschreibung: Redlining-Optionen
-----------------------------------------------------------------------*/
class SwRedlineOptionsTabPage : public SfxTabPage
{
FixedLine aInsertFL;
FixedText aInsertFT;
FixedText aInsertAttrFT;
ListBox aInsertLB;
FixedText aInsertColorFT;
ColorListBox aInsertColorLB;
SvxFontPrevWindow aInsertedPreviewWN;
FixedText aDeletedFT;
FixedText aDeletedAttrFT;
ListBox aDeletedLB;
FixedText aDeletedColorFT;
ColorListBox aDeletedColorLB;
SvxFontPrevWindow aDeletedPreviewWN;
FixedText aChangedFT;
FixedText aChangedAttrFT;
ListBox aChangedLB;
FixedText aChangedColorFT;
ColorListBox aChangedColorLB;
SvxFontPrevWindow aChangedPreviewWN;
FixedLine aChangedFL;
FixedText aMarkPosFT;
ListBox aMarkPosLB;
FixedText aMarkColorFT;
ColorListBox aMarkColorLB;
SwMarkPreview aMarkPreviewWN;
String sAuthor;
String sNone;
SwRedlineOptionsTabPage( Window* pParent, const SfxItemSet& rSet );
~SwRedlineOptionsTabPage();
DECL_LINK( AttribHdl, ListBox *pLB );
DECL_LINK( ChangedMaskPrevHdl, ListBox *pLB = 0 );
DECL_LINK( ColorHdl, ColorListBox *pColorLB );
void InitFontStyle(SvxFontPrevWindow& rExampleWin);
public:
static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
};
/*--------OS 11.01.95 -----------------------------------
TabPage Testeinstellungen fuer SW
--------------------------------------------------------- */
#ifndef PRODUCT
class SwTestTabPage : public SfxTabPage
{
public:
SwTestTabPage( Window* pParent,
const SfxItemSet& rSet );
static SfxTabPage* Create( Window* pParent,
const SfxItemSet& rAttrSet );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
private:
FixedLine aTestFL;
CheckBox aTest1CBox;
CheckBox aTest2CBox;
CheckBox aTest3CBox;
CheckBox aTest4CBox;
CheckBox aTest5CBox;
CheckBox aTest6CBox;
CheckBox aTest7CBox;
CheckBox aTest8CBox;
CheckBox aTest9CBox;
CheckBox aTest10CBox;
BOOL bAttrModified;
void Init();
DECL_LINK( AutoClickHdl, CheckBox * );
};
#endif //PRODUCT
#endif
<commit_msg>INTEGRATION: CWS swusing (1.21.36); FILE MERGED 2007/10/10 14:15:11 tl 1.21.36.1: #i82476# make newly added 'using' declarations private<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: optpage.hxx,v $
*
* $Revision: 1.22 $
*
* last change: $Author: vg $ $Date: 2007-10-22 15:21:12 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _OPTPAGE_HXX
#define _OPTPAGE_HXX
#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif
#ifndef _GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _CTRLBOX_HXX //autogen
#include <svtools/ctrlbox.hxx>
#endif
#ifndef _SVX_FNTCTRL_HXX //autogen
#include <svx/fntctrl.hxx>
#endif
#ifndef _FONTCFG_HXX
#include <fontcfg.hxx>
#endif
class SvStringsDtor;
class SfxPrinter;
class SwStdFontConfig;
class SwWrtShell;
class FontList;
/*-----------------31.08.96 10.09-------------------
--------------------------------------------------*/
class SwContentOptPage : public SfxTabPage
{
//visual aids
FixedLine aLineFL;
CheckBox aCrossCB;
CheckBox aSolidHandleCB;
CheckBox aBigHandleCB;
//view
FixedLine aWindowFL;
CheckBox aHScrollBox;
CheckBox aVScrollBox;
CheckBox aAnyRulerCB;
CheckBox aHRulerCBox;
ListBox aHMetric;
CheckBox aVRulerCBox;
CheckBox aVRulerRightCBox;
ListBox aVMetric;
CheckBox aSmoothCBox;
//display
FixedLine aDispFL;
CheckBox aGrfCB;
CheckBox aTblCB;
CheckBox aDrwCB;
CheckBox aFldNameCB;
CheckBox aPostItCB;
FixedLine aSettingsFL;
FixedText aMetricFT;
ListBox aMetricLB;
DECL_LINK(VertRulerHdl, CheckBox*);
DECL_LINK(AnyRulerHdl, CheckBox*);
public:
SwContentOptPage( Window* pParent,
const SfxItemSet& rSet );
~SwContentOptPage();
static SfxTabPage* Create( Window* pParent,
const SfxItemSet& rAttrSet);
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
};
/*-------- OS 27.01.95 -----------------------------------
TabPage Druckereinstellungen Zusaetze
--------------------------------------------------------- */
class SwAddPrinterTabPage : public SfxTabPage
{
FixedLine aFL1;
CheckBox aGrfCB;
CheckBox aTabCB;
CheckBox aDrawCB;
CheckBox aCtrlFldCB;
CheckBox aBackgroundCB;
CheckBox aBlackFontCB;
FixedLine aSeparatorLFL;
FixedLine aFL2;
CheckBox aLeftPageCB;
CheckBox aRightPageCB;
CheckBox aReverseCB;
CheckBox aProspectCB;
CheckBox aProspectCB_RTL;
FixedLine aSeparatorRFL;
RadioButton aNoRB;
RadioButton aOnlyRB;
RadioButton aEndRB;
RadioButton aEndPageRB;
FixedLine aFL3;
FixedLine aFL4;
CheckBox aPrintEmptyPagesCB;
CheckBox aSingleJobsCB;
CheckBox aPaperFromSetupCB;
FixedText aFaxFT;
ListBox aFaxLB;
String sNone;
BOOL bAttrModified;
BOOL bPreview;
void Init();
DECL_LINK( AutoClickHdl, CheckBox * );
DECL_LINK( SelectHdl, ListBox * );
SwAddPrinterTabPage( Window* pParent,
const SfxItemSet& rSet );
public:
static SfxTabPage* Create( Window* pParent,
const SfxItemSet& rAttrSet );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
void SetFax( const SvStringsDtor& );
void SelectFax( const String& );
void SetPreview(BOOL bPrev);
virtual void PageCreated (SfxAllItemSet aSet);
};
/*-----------------03.09.96 11.50-------------------
--------------------------------------------------*/
class SwStdFontTabPage : public SfxTabPage
{
FixedLine aStdChrFL ;
FixedText aTypeFT;
FixedText aStandardLbl;
ComboBox aStandardBox;
FixedText aHeightFT;
FontSizeBox aStandardHeightLB;
FixedText aTitleLbl ;
ComboBox aTitleBox ;
FontSizeBox aTitleHeightLB;
FixedText aListLbl ;
ComboBox aListBox ;
FontSizeBox aListHeightLB;
FixedText aLabelLbl ;
ComboBox aLabelBox ;
FontSizeBox aLabelHeightLB;
FixedText aIdxLbl ;
ComboBox aIdxBox ;
FontSizeBox aIndexHeightLB;
CheckBox aDocOnlyCB ;
PushButton aStandardPB;
String sShellStd;
String sShellTitle;
String sShellList;
String sShellLabel;
String sShellIndex;
SfxPrinter* pPrt;
FontList* pFontList;
SwStdFontConfig* pFontConfig;
SwWrtShell* pWrtShell;
LanguageType eLanguage;
// waren nur defaults vorhanden? wurden sie mit den Boxen ueberschrieben
BOOL bListDefault :1;
BOOL bSetListDefault :1;
BOOL bLabelDefault :1;
BOOL bSetLabelDefault :1;
BOOL bIdxDefault :1;
BOOL bSetIdxDefault :1;
BOOL bDeletePrinter :1;
BOOL bListHeightDefault :1;
BOOL bSetListHeightDefault :1;
BOOL bLabelHeightDefault :1;
BOOL bSetLabelHeightDefault :1;
BOOL bIndexHeightDefault :1;
BOOL bSetIndexHeightDefault :1;
sal_uInt8 nFontGroup; //fontcfg.hxx: FONT_GROUP_[STANDARD|CJK|CTL]
String sScriptWestern;
String sScriptAsian;
String sScriptComplex;
DECL_LINK( StandardHdl, PushButton * );
DECL_LINK( ModifyHdl, ComboBox * );
DECL_LINK( ModifyHeightHdl, FontSizeBox * );
DECL_LINK( LoseFocusHdl, ComboBox * );
SwStdFontTabPage( Window* pParent,
const SfxItemSet& rSet );
~SwStdFontTabPage();
public:
static SfxTabPage* Create( Window* pParent,
const SfxItemSet& rAttrSet );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
void SetFontMode(sal_uInt8 nGroup) {nFontGroup = nGroup;}
virtual void PageCreated (SfxAllItemSet aSet);
};
/*-----------------18.01.97 12.10-------------------
--------------------------------------------------*/
class SwTableOptionsTabPage : public SfxTabPage
{
FixedLine aTableFL;
CheckBox aHeaderCB;
CheckBox aRepeatHeaderCB;
CheckBox aDontSplitCB;
CheckBox aBorderCB;
FixedLine aSeparatorFL;
FixedLine aTableInsertFL;
CheckBox aNumFormattingCB;
CheckBox aNumFmtFormattingCB;
CheckBox aNumAlignmentCB;
FixedLine aMoveFL;
FixedText aMoveFT;
FixedText aRowMoveFT;
MetricField aRowMoveMF;
FixedText aColMoveFT;
MetricField aColMoveMF;
FixedText aInsertFT;
FixedText aRowInsertFT;
MetricField aRowInsertMF;
FixedText aColInsertFT;
MetricField aColInsertMF;
FixedText aHandlingFT;
RadioButton aFixRB;
RadioButton aFixPropRB;
RadioButton aVarRB;
FixedText aFixFT;
FixedText aFixPropFT;
FixedText aVarFT;
SwWrtShell* pWrtShell;
BOOL bHTMLMode;
DECL_LINK(CheckBoxHdl, CheckBox *pCB);
SwTableOptionsTabPage( Window* pParent,
const SfxItemSet& rSet );
~SwTableOptionsTabPage();
public:
static SfxTabPage* Create( Window* pParent,
const SfxItemSet& rAttrSet );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
void SetWrtShell(SwWrtShell* pSh) {pWrtShell = pSh;}
virtual void PageCreated (SfxAllItemSet aSet);
};
/*-----------------31.10.97 17:55-------------------
TabPage fuer ShadowCrsr
--------------------------------------------------*/
class SwShdwCrsrOptionsTabPage : public SfxTabPage
{
//nonprinting characters
FixedLine aUnprintFL;
CheckBox aParaCB;
CheckBox aSHyphCB;
CheckBox aSpacesCB;
CheckBox aHSpacesCB;
CheckBox aTabCB;
CheckBox aBreakCB;
CheckBox aCharHiddenCB;
CheckBox aFldHiddenCB;
CheckBox aFldHiddenParaCB;
FixedLine aSeparatorFL;
FixedLine aFlagFL;
CheckBox aOnOffCB;
FixedText aFillModeFT;
RadioButton aFillMarginRB;
RadioButton aFillIndentRB;
RadioButton aFillTabRB;
RadioButton aFillSpaceRB;
FixedLine aCrsrOptFL;
CheckBox aCrsrInProtCB;
SwShdwCrsrOptionsTabPage( Window* pParent, const SfxItemSet& rSet );
~SwShdwCrsrOptionsTabPage();
public:
static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
};
/*-----------------------------------------------------------------------
Beschreibung: Markierungsvorschau
-----------------------------------------------------------------------*/
class SwMarkPreview : public Window
{
Color m_aBgCol; // background
Color m_aTransCol; // transparency
Color m_aMarkCol; // marks
Color m_aLineCol; // general lines
Color m_aShadowCol; // shadow
Color m_aTxtCol; // text
Color m_aPrintAreaCol; // frame for print area
Rectangle aPage;
Rectangle aLeftPagePrtArea;
Rectangle aRightPagePrtArea;
USHORT nMarkPos;
using OutputDevice::DrawRect;
void DrawRect(const Rectangle &rRect, const Color &rFillColor, const Color &rLineColor);
void Paint(const Rectangle&);
void PaintPage(const Rectangle &rRect);
void InitColors( void );
protected:
virtual void DataChanged( const DataChangedEvent& rDCEvt );
public:
SwMarkPreview(Window* pParent, const ResId& rResID);
virtual ~SwMarkPreview();
inline void SetColor(const Color& rCol) { m_aMarkCol = rCol; }
inline void SetMarkPos(USHORT nPos) { nMarkPos = nPos; }
};
/*-----------------------------------------------------------------------
Beschreibung: Redlining-Optionen
-----------------------------------------------------------------------*/
class SwRedlineOptionsTabPage : public SfxTabPage
{
FixedLine aInsertFL;
FixedText aInsertFT;
FixedText aInsertAttrFT;
ListBox aInsertLB;
FixedText aInsertColorFT;
ColorListBox aInsertColorLB;
SvxFontPrevWindow aInsertedPreviewWN;
FixedText aDeletedFT;
FixedText aDeletedAttrFT;
ListBox aDeletedLB;
FixedText aDeletedColorFT;
ColorListBox aDeletedColorLB;
SvxFontPrevWindow aDeletedPreviewWN;
FixedText aChangedFT;
FixedText aChangedAttrFT;
ListBox aChangedLB;
FixedText aChangedColorFT;
ColorListBox aChangedColorLB;
SvxFontPrevWindow aChangedPreviewWN;
FixedLine aChangedFL;
FixedText aMarkPosFT;
ListBox aMarkPosLB;
FixedText aMarkColorFT;
ColorListBox aMarkColorLB;
SwMarkPreview aMarkPreviewWN;
String sAuthor;
String sNone;
SwRedlineOptionsTabPage( Window* pParent, const SfxItemSet& rSet );
~SwRedlineOptionsTabPage();
DECL_LINK( AttribHdl, ListBox *pLB );
DECL_LINK( ChangedMaskPrevHdl, ListBox *pLB = 0 );
DECL_LINK( ColorHdl, ColorListBox *pColorLB );
void InitFontStyle(SvxFontPrevWindow& rExampleWin);
public:
static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
};
/*--------OS 11.01.95 -----------------------------------
TabPage Testeinstellungen fuer SW
--------------------------------------------------------- */
#ifndef PRODUCT
class SwTestTabPage : public SfxTabPage
{
public:
SwTestTabPage( Window* pParent,
const SfxItemSet& rSet );
static SfxTabPage* Create( Window* pParent,
const SfxItemSet& rAttrSet );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
private:
FixedLine aTestFL;
CheckBox aTest1CBox;
CheckBox aTest2CBox;
CheckBox aTest3CBox;
CheckBox aTest4CBox;
CheckBox aTest5CBox;
CheckBox aTest6CBox;
CheckBox aTest7CBox;
CheckBox aTest8CBox;
CheckBox aTest9CBox;
CheckBox aTest10CBox;
BOOL bAttrModified;
void Init();
DECL_LINK( AutoClickHdl, CheckBox * );
};
#endif //PRODUCT
#endif
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestLabeledGeoView2D.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.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
// .SECTION Description
#include "vtkCamera.h"
#include "vtkGeoAlignedImageSource.h"
#include "vtkGeoAlignedImageRepresentation.h"
#include "vtkGeoFileImageSource.h"
#include "vtkGeoFileTerrainSource.h"
#include "vtkGeoGraphRepresentation2D.h"
#include "vtkGeoProjectionSource.h"
#include "vtkGeoRandomGraphSource.h"
#include "vtkGeoTerrain2D.h"
#include "vtkGeoTerrainNode.h"
#include "vtkGeoView2D.h"
#include "vtkJPEGReader.h"
#include "vtkPolyData.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkSmartPointer.h"
#include "vtkStdString.h"
#include "vtkTestUtilities.h"
#include <vtksys/ios/sstream>
int TestLabeledGeoView2D(int argc, char* argv[])
{
int proj = 40;
char* fname = vtkTestUtilities::ExpandDataFileName(
argc, argv, "Data/NE2_ps_bath_small.jpg");
vtkStdString imageFile = fname;
// Create the view
vtkSmartPointer<vtkRenderWindow> win = vtkSmartPointer<vtkRenderWindow>::New();
vtkSmartPointer<vtkGeoView2D> view = vtkSmartPointer<vtkGeoView2D>::New();
view->SetupRenderWindow(win);
// Create the terrain
vtkSmartPointer<vtkGeoTerrain2D> terrain =
vtkSmartPointer<vtkGeoTerrain2D>::New();
vtkSmartPointer<vtkGeoSource> terrainSource;
vtkGeoProjectionSource* projSource = vtkGeoProjectionSource::New();
projSource->SetProjection(proj);
terrainSource.TakeReference(projSource);
terrain->SetSource(terrainSource);
view->SetSurface(terrain);
// Create background image
vtkSmartPointer<vtkGeoAlignedImageRepresentation> imageRep =
vtkSmartPointer<vtkGeoAlignedImageRepresentation>::New();
vtkSmartPointer<vtkGeoSource> imageSource;
vtkGeoAlignedImageSource* alignedSource = vtkGeoAlignedImageSource::New();
vtkSmartPointer<vtkJPEGReader> reader =
vtkSmartPointer<vtkJPEGReader>::New();
reader->SetFileName(imageFile.c_str());
reader->Update();
alignedSource->SetImage(reader->GetOutput());
imageSource.TakeReference(alignedSource);
imageRep->SetSource(imageSource);
view->AddRepresentation(imageRep);
vtkSmartPointer<vtkGeoRandomGraphSource> graphSource =
vtkSmartPointer<vtkGeoRandomGraphSource>::New();
graphSource->SetNumberOfVertices(1000);
vtkSmartPointer<vtkGeoGraphRepresentation2D> graphRep =
vtkSmartPointer<vtkGeoGraphRepresentation2D>::New();
graphRep->SetInputConnection(graphSource->GetOutputPort());
graphRep->SetVertexLabelArrayName("latitude");
graphRep->SetUseLabelHierarchy(false);
graphRep->SetVertexLabelVisibility(true);
view->AddRepresentation(graphRep);
// Set up the viewport
win->SetSize(600, 600);
vtkSmartPointer<vtkGeoTerrainNode> root =
vtkSmartPointer<vtkGeoTerrainNode>::New();
terrainSource->FetchRoot(root);
double bounds[6];
root->GetModel()->GetBounds(bounds);
bounds[0] = bounds[0] - (bounds[1] - bounds[0])*0.01;
bounds[1] = bounds[1] + (bounds[1] - bounds[0])*0.01;
bounds[2] = bounds[2] - (bounds[3] - bounds[2])*0.01;
bounds[3] = bounds[3] + (bounds[3] - bounds[2])*0.01;
double scalex = (bounds[1] - bounds[0])/2.0;
double scaley = (bounds[3] - bounds[2])/2.0;
double scale = (scalex > scaley) ? scalex : scaley;
view->GetRenderer()->ResetCamera();
view->GetRenderer()->GetActiveCamera()->SetParallelScale(scale);
view->Update();
int retVal = vtkRegressionTestImage(win);
if (retVal == vtkRegressionTester::DO_INTERACTOR)
{
win->GetInteractor()->Initialize();
win->GetInteractor()->Start();
}
terrainSource->ShutDown();
imageSource->ShutDown();
delete [] fname;
return !retVal;
}
<commit_msg>ENH: adjust test to use less graph vertices.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestLabeledGeoView2D.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.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
// .SECTION Description
#include "vtkCamera.h"
#include "vtkGeoAlignedImageSource.h"
#include "vtkGeoAlignedImageRepresentation.h"
#include "vtkGeoFileImageSource.h"
#include "vtkGeoFileTerrainSource.h"
#include "vtkGeoGraphRepresentation2D.h"
#include "vtkGeoProjectionSource.h"
#include "vtkGeoRandomGraphSource.h"
#include "vtkGeoTerrain2D.h"
#include "vtkGeoTerrainNode.h"
#include "vtkGeoView2D.h"
#include "vtkJPEGReader.h"
#include "vtkPolyData.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkSmartPointer.h"
#include "vtkStdString.h"
#include "vtkTestUtilities.h"
#include <vtksys/ios/sstream>
int TestLabeledGeoView2D(int argc, char* argv[])
{
int proj = 40;
char* fname = vtkTestUtilities::ExpandDataFileName(
argc, argv, "Data/NE2_ps_bath_small.jpg");
vtkStdString imageFile = fname;
// Create the view
vtkSmartPointer<vtkRenderWindow> win = vtkSmartPointer<vtkRenderWindow>::New();
vtkSmartPointer<vtkGeoView2D> view = vtkSmartPointer<vtkGeoView2D>::New();
view->SetupRenderWindow(win);
// Create the terrain
vtkSmartPointer<vtkGeoTerrain2D> terrain =
vtkSmartPointer<vtkGeoTerrain2D>::New();
vtkSmartPointer<vtkGeoSource> terrainSource;
vtkGeoProjectionSource* projSource = vtkGeoProjectionSource::New();
projSource->SetProjection(proj);
terrainSource.TakeReference(projSource);
terrain->SetSource(terrainSource);
view->SetSurface(terrain);
// Create background image
vtkSmartPointer<vtkGeoAlignedImageRepresentation> imageRep =
vtkSmartPointer<vtkGeoAlignedImageRepresentation>::New();
vtkSmartPointer<vtkGeoSource> imageSource;
vtkGeoAlignedImageSource* alignedSource = vtkGeoAlignedImageSource::New();
vtkSmartPointer<vtkJPEGReader> reader =
vtkSmartPointer<vtkJPEGReader>::New();
reader->SetFileName(imageFile.c_str());
reader->Update();
alignedSource->SetImage(reader->GetOutput());
imageSource.TakeReference(alignedSource);
imageRep->SetSource(imageSource);
view->AddRepresentation(imageRep);
vtkSmartPointer<vtkGeoRandomGraphSource> graphSource =
vtkSmartPointer<vtkGeoRandomGraphSource>::New();
graphSource->SetNumberOfVertices(500);
vtkSmartPointer<vtkGeoGraphRepresentation2D> graphRep =
vtkSmartPointer<vtkGeoGraphRepresentation2D>::New();
graphRep->SetInputConnection(graphSource->GetOutputPort());
graphRep->SetVertexLabelArrayName("latitude");
graphRep->SetUseLabelHierarchy(true);
graphRep->SetVertexLabelVisibility(true);
view->AddRepresentation(graphRep);
// Set up the viewport
win->SetSize(600, 600);
vtkSmartPointer<vtkGeoTerrainNode> root =
vtkSmartPointer<vtkGeoTerrainNode>::New();
terrainSource->FetchRoot(root);
double bounds[6];
root->GetModel()->GetBounds(bounds);
bounds[0] = bounds[0] - (bounds[1] - bounds[0])*0.01;
bounds[1] = bounds[1] + (bounds[1] - bounds[0])*0.01;
bounds[2] = bounds[2] - (bounds[3] - bounds[2])*0.01;
bounds[3] = bounds[3] + (bounds[3] - bounds[2])*0.01;
double scalex = (bounds[1] - bounds[0])/2.0;
double scaley = (bounds[3] - bounds[2])/2.0;
double scale = (scalex > scaley) ? scalex : scaley;
view->GetRenderer()->ResetCamera();
view->GetRenderer()->GetActiveCamera()->SetParallelScale(scale);
view->Update();
int retVal = vtkRegressionTestImage(win);
if (retVal == vtkRegressionTester::DO_INTERACTOR)
{
win->GetInteractor()->Initialize();
win->GetInteractor()->Start();
}
terrainSource->ShutDown();
imageSource->ShutDown();
delete [] fname;
return !retVal;
}
<|endoftext|> |
<commit_before>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "opt_status.h"
#include "kernel/register.h"
#include "kernel/sigtools.h"
#include "kernel/log.h"
#include "kernel/celltypes.h"
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <set>
using RTLIL::id2cstr;
static CellTypes ct;
static int count_rm_cells, count_rm_wires;
static void rmunused_module_cells(RTLIL::Module *module, bool verbose)
{
SigMap assign_map(module);
std::set<RTLIL::Cell*, RTLIL::sort_by_name<RTLIL::Cell>> queue, unused;
SigSet<RTLIL::Cell*> wire2driver;
for (auto &it : module->cells) {
RTLIL::Cell *cell = it.second;
for (auto &it2 : cell->connections) {
if (!ct.cell_input(cell->type, it2.first)) {
RTLIL::SigSpec sig = it2.second;
assign_map.apply(sig);
wire2driver.insert(sig, cell);
}
}
if (cell->type == "$memwr" || cell->attributes.count("\\keep"))
queue.insert(cell);
unused.insert(cell);
}
for (auto &it : module->wires) {
RTLIL::Wire *wire = it.second;
if (wire->port_output) {
std::set<RTLIL::Cell*> cell_list;
RTLIL::SigSpec sig = RTLIL::SigSpec(wire);
assign_map.apply(sig);
wire2driver.find(sig, cell_list);
for (auto cell : cell_list)
queue.insert(cell);
}
}
while (queue.size() > 0)
{
std::set<RTLIL::Cell*, RTLIL::sort_by_name<RTLIL::Cell>> new_queue;
for (auto cell : queue)
unused.erase(cell);
for (auto cell : queue) {
for (auto &it : cell->connections) {
if (!ct.cell_output(cell->type, it.first)) {
std::set<RTLIL::Cell*> cell_list;
RTLIL::SigSpec sig = it.second;
assign_map.apply(sig);
wire2driver.find(sig, cell_list);
for (auto cell : cell_list) {
if (unused.count(cell) > 0)
new_queue.insert(cell);
}
}
}
}
queue.swap(new_queue);
}
for (auto cell : unused) {
if (verbose)
log(" removing unused `%s' cell `%s'.\n", cell->type.c_str(), cell->name.c_str());
OPT_DID_SOMETHING = true;
module->cells.erase(cell->name);
count_rm_cells++;
delete cell;
}
}
static bool compare_signals(RTLIL::SigSpec &s1, RTLIL::SigSpec &s2)
{
assert(s1.width == 1);
assert(s2.width == 1);
assert(s1.chunks.size() == 1);
assert(s2.chunks.size() == 1);
RTLIL::Wire *w1 = s1.chunks[0].wire;
RTLIL::Wire *w2 = s2.chunks[0].wire;
if (w1 == NULL || w2 == NULL)
return w2 == NULL;
if (w1->port_input != w2->port_input)
return w2->port_input;
if (w1->port_output != w2->port_output)
return w2->port_output;
if (w1->name[0] != w2->name[0])
return w2->name[0] == '\\';
if (w1->attributes.size() != w2->attributes.size())
return w2->attributes.size() > w1->attributes.size();
return w2->name < w1->name;
}
static bool check_public_name(RTLIL::IdString id)
{
if (id[0] == '$')
return false;
if (id.substr(0, 2) == "\\_" && (id[id.size()-1] == '_' || id.find("_[") != std::string::npos))
return false;
if (id.find(".$") != std::string::npos)
return false;
return true;
}
static void rmunused_module_signals(RTLIL::Module *module, bool purge_mode, bool verbose)
{
SigMap assign_map(module);
for (auto &it : module->wires) {
RTLIL::Wire *wire = it.second;
for (int i = 0; i < wire->width; i++) {
RTLIL::SigSpec s1 = RTLIL::SigSpec(wire, 1, i), s2 = assign_map(s1);
if (!compare_signals(s1, s2))
assign_map.add(s1);
}
}
module->connections.clear();
SigPool used_signals;
SigPool used_signals_nodrivers;
for (auto &it : module->cells) {
RTLIL::Cell *cell = it.second;
for (auto &it2 : cell->connections) {
assign_map.apply(it2.second);
used_signals.add(it2.second);
if (!ct.cell_output(cell->type, it2.first))
used_signals_nodrivers.add(it2.second);
}
}
for (auto &it : module->wires) {
RTLIL::Wire *wire = it.second;
if (wire->port_id > 0) {
RTLIL::SigSpec sig = RTLIL::SigSpec(wire);
assign_map.apply(sig);
used_signals.add(sig);
if (!wire->port_input)
used_signals_nodrivers.add(sig);
}
}
std::vector<RTLIL::Wire*> del_wires;
for (auto &it : module->wires) {
RTLIL::Wire *wire = it.second;
if ((!purge_mode && check_public_name(wire->name)) || wire->port_id != 0) {
RTLIL::SigSpec s1 = RTLIL::SigSpec(wire), s2 = s1;
assign_map.apply(s2);
if (!used_signals.check_any(s2) && wire->port_id == 0) {
del_wires.push_back(wire);
} else {
s1.expand();
s2.expand();
assert(s1.chunks.size() == s2.chunks.size());
RTLIL::SigSig new_conn;
for (size_t i = 0; i < s1.chunks.size(); i++)
if (s1.chunks[i] != s2.chunks[i]) {
new_conn.first.append(s1.chunks[i]);
new_conn.second.append(s2.chunks[i]);
}
if (new_conn.first.width > 0) {
new_conn.first.optimize();
new_conn.second.optimize();
used_signals.add(new_conn.first);
used_signals.add(new_conn.second);
module->connections.push_back(new_conn);
}
}
} else {
if (!used_signals.check_any(RTLIL::SigSpec(wire)))
del_wires.push_back(wire);
}
RTLIL::SigSpec sig = assign_map(RTLIL::SigSpec(wire));
if (!used_signals_nodrivers.check_any(sig)) {
std::string unused_bits;
sig.expand();
for (size_t i = 0; i < sig.chunks.size(); i++) {
if (sig.chunks[i].wire == NULL)
continue;
if (!used_signals_nodrivers.check_any(sig)) {
if (!unused_bits.empty())
unused_bits += " ";
unused_bits += stringf("%zd", i);
}
}
if (unused_bits.empty() || wire->port_id != 0)
wire->attributes.erase("\\unused_bits");
else
wire->attributes["\\unused_bits"] = RTLIL::Const(unused_bits);
} else {
wire->attributes.erase("\\unused_bits");
}
}
int del_wires_count = 0;
for (auto wire : del_wires)
if (!used_signals.check_any(RTLIL::SigSpec(wire))) {
if (check_public_name(wire->name) && verbose) {
log(" removing unused non-port wire %s.\n", wire->name.c_str());
del_wires_count++;
}
module->wires.erase(wire->name);
count_rm_wires++;
delete wire;
}
if (del_wires_count > 0)
log(" removed %d unused temporary wires.\n", del_wires_count);
}
static void rmunused_module(RTLIL::Module *module, bool purge_mode, bool verbose)
{
if (verbose)
log("Finding unused cells or wires in module %s..\n", module->name.c_str());
rmunused_module_cells(module, verbose);
rmunused_module_signals(module, purge_mode, verbose);
}
struct OptCleanPass : public Pass {
OptCleanPass() : Pass("opt_clean", "remove unused cells and wires") { }
virtual void help()
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" opt_clean [options] [selection]\n");
log("\n");
log("This pass identifies wires and cells that are unused and removes them. Other\n");
log("passes often remove cells but leave the wires in the design or reconnect the\n");
log("wires but leave the old cells in the design. This pass can be used to clean up\n");
log("after the passes that do the actual work.\n");
log("\n");
log("This pass only operates on completely selected modules without processes.\n");
log("\n");
log(" -purge\n");
log(" also remove internal nets if they have a public name\n");
log("\n");
}
virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
{
bool purge_mode = false;
log_header("Executing OPT_CLEAN pass (remove unused cells and wires).\n");
log_push();
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-purge") {
purge_mode = true;
continue;
}
break;
}
extra_args(args, argidx, design);
ct.setup_internals();
ct.setup_internals_mem();
ct.setup_stdcells();
ct.setup_stdcells_mem();
for (auto &mod_it : design->modules) {
if (!design->selected_whole_module(mod_it.first)) {
if (design->selected(mod_it.second))
log("Skipping module %s as it is only partially selected.\n", id2cstr(mod_it.second->name));
continue;
}
if (mod_it.second->processes.size() > 0) {
log("Skipping module %s as it contains processes.\n", mod_it.second->name.c_str());
} else {
rmunused_module(mod_it.second, purge_mode, true);
}
}
ct.clear();
log_pop();
}
} OptCleanPass;
struct CleanPass : public Pass {
CleanPass() : Pass("clean", "remove unused cells and wires") { }
virtual void help()
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" clean [options] [selection]\n");
log("\n");
log("This is identical to 'opt_clean', but less verbose.\n");
log("\n");
log("When commands are seperated using the ';;' token, this command will be executed\n");
log("between the commands.\n");
log("\n");
log("When commands are seperated using the ';;;' token, this command will be executed\n");
log("in -purge mode between the commands.\n");
log("\n");
}
virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
{
bool purge_mode = false;
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-purge") {
purge_mode = true;
continue;
}
break;
}
if (argidx < args.size())
extra_args(args, argidx, design);
ct.setup_internals();
ct.setup_internals_mem();
ct.setup_stdcells();
ct.setup_stdcells_mem();
count_rm_cells = 0;
count_rm_wires = 0;
for (auto &mod_it : design->modules) {
if (design->selected_whole_module(mod_it.first) && mod_it.second->processes.size() == 0)
do {
OPT_DID_SOMETHING = false;
rmunused_module(mod_it.second, purge_mode, false);
} while (OPT_DID_SOMETHING);
}
if (count_rm_cells > 0 || count_rm_wires > 0)
log("Removed %d unused cells and %d unused wires.\n", count_rm_cells, count_rm_wires);
ct.clear();
}
} CleanPass;
<commit_msg>Avoid re-arranging signals on register outputs<commit_after>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "opt_status.h"
#include "kernel/register.h"
#include "kernel/sigtools.h"
#include "kernel/log.h"
#include "kernel/celltypes.h"
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <set>
using RTLIL::id2cstr;
static CellTypes ct, ct_reg;
static int count_rm_cells, count_rm_wires;
static void rmunused_module_cells(RTLIL::Module *module, bool verbose)
{
SigMap assign_map(module);
std::set<RTLIL::Cell*, RTLIL::sort_by_name<RTLIL::Cell>> queue, unused;
SigSet<RTLIL::Cell*> wire2driver;
for (auto &it : module->cells) {
RTLIL::Cell *cell = it.second;
for (auto &it2 : cell->connections) {
if (!ct.cell_input(cell->type, it2.first)) {
RTLIL::SigSpec sig = it2.second;
assign_map.apply(sig);
wire2driver.insert(sig, cell);
}
}
if (cell->type == "$memwr" || cell->attributes.count("\\keep"))
queue.insert(cell);
unused.insert(cell);
}
for (auto &it : module->wires) {
RTLIL::Wire *wire = it.second;
if (wire->port_output) {
std::set<RTLIL::Cell*> cell_list;
RTLIL::SigSpec sig = RTLIL::SigSpec(wire);
assign_map.apply(sig);
wire2driver.find(sig, cell_list);
for (auto cell : cell_list)
queue.insert(cell);
}
}
while (queue.size() > 0)
{
std::set<RTLIL::Cell*, RTLIL::sort_by_name<RTLIL::Cell>> new_queue;
for (auto cell : queue)
unused.erase(cell);
for (auto cell : queue) {
for (auto &it : cell->connections) {
if (!ct.cell_output(cell->type, it.first)) {
std::set<RTLIL::Cell*> cell_list;
RTLIL::SigSpec sig = it.second;
assign_map.apply(sig);
wire2driver.find(sig, cell_list);
for (auto cell : cell_list) {
if (unused.count(cell) > 0)
new_queue.insert(cell);
}
}
}
}
queue.swap(new_queue);
}
for (auto cell : unused) {
if (verbose)
log(" removing unused `%s' cell `%s'.\n", cell->type.c_str(), cell->name.c_str());
OPT_DID_SOMETHING = true;
module->cells.erase(cell->name);
count_rm_cells++;
delete cell;
}
}
static bool compare_signals(RTLIL::SigSpec &s1, RTLIL::SigSpec &s2, SigPool ®s, SigPool &conns)
{
assert(s1.width == 1);
assert(s2.width == 1);
assert(s1.chunks.size() == 1);
assert(s2.chunks.size() == 1);
RTLIL::Wire *w1 = s1.chunks[0].wire;
RTLIL::Wire *w2 = s2.chunks[0].wire;
if (w1 == NULL || w2 == NULL)
return w2 == NULL;
if (w1->port_input != w2->port_input)
return w2->port_input;
if (regs.check_any(s1) != regs.check_any(s2))
return regs.check_any(s2);
if (conns.check_any(s1) != conns.check_any(s2))
return conns.check_any(s2);
if (w1->port_output != w2->port_output)
return w2->port_output;
if (w1->name[0] != w2->name[0])
return w2->name[0] == '\\';
if (w1->attributes.size() != w2->attributes.size())
return w2->attributes.size() > w1->attributes.size();
return w2->name < w1->name;
}
static bool check_public_name(RTLIL::IdString id)
{
if (id[0] == '$')
return false;
if (id.substr(0, 2) == "\\_" && (id[id.size()-1] == '_' || id.find("_[") != std::string::npos))
return false;
if (id.find(".$") != std::string::npos)
return false;
return true;
}
static void rmunused_module_signals(RTLIL::Module *module, bool purge_mode, bool verbose)
{
SigPool register_signals;
SigPool connected_signals;
if (!purge_mode)
for (auto &it : module->cells) {
RTLIL::Cell *cell = it.second;
if (ct_reg.cell_known(cell->type))
for (auto &it2 : cell->connections)
if (ct_reg.cell_output(cell->type, it2.first))
register_signals.add(it2.second);
for (auto &it2 : cell->connections)
connected_signals.add(it2.second);
}
SigMap assign_map(module);
for (auto &it : module->wires) {
RTLIL::Wire *wire = it.second;
for (int i = 0; i < wire->width; i++) {
RTLIL::SigSpec s1 = RTLIL::SigSpec(wire, 1, i), s2 = assign_map(s1);
if (!compare_signals(s1, s2, register_signals, connected_signals))
assign_map.add(s1);
}
}
module->connections.clear();
SigPool used_signals;
SigPool used_signals_nodrivers;
for (auto &it : module->cells) {
RTLIL::Cell *cell = it.second;
for (auto &it2 : cell->connections) {
assign_map.apply(it2.second);
used_signals.add(it2.second);
if (!ct.cell_output(cell->type, it2.first))
used_signals_nodrivers.add(it2.second);
}
}
for (auto &it : module->wires) {
RTLIL::Wire *wire = it.second;
if (wire->port_id > 0) {
RTLIL::SigSpec sig = RTLIL::SigSpec(wire);
assign_map.apply(sig);
used_signals.add(sig);
if (!wire->port_input)
used_signals_nodrivers.add(sig);
}
}
std::vector<RTLIL::Wire*> del_wires;
for (auto &it : module->wires) {
RTLIL::Wire *wire = it.second;
if ((!purge_mode && check_public_name(wire->name)) || wire->port_id != 0) {
RTLIL::SigSpec s1 = RTLIL::SigSpec(wire), s2 = s1;
assign_map.apply(s2);
if (!used_signals.check_any(s2) && wire->port_id == 0) {
del_wires.push_back(wire);
} else {
s1.expand();
s2.expand();
assert(s1.chunks.size() == s2.chunks.size());
RTLIL::SigSig new_conn;
for (size_t i = 0; i < s1.chunks.size(); i++)
if (s1.chunks[i] != s2.chunks[i]) {
new_conn.first.append(s1.chunks[i]);
new_conn.second.append(s2.chunks[i]);
}
if (new_conn.first.width > 0) {
new_conn.first.optimize();
new_conn.second.optimize();
used_signals.add(new_conn.first);
used_signals.add(new_conn.second);
module->connections.push_back(new_conn);
}
}
} else {
if (!used_signals.check_any(RTLIL::SigSpec(wire)))
del_wires.push_back(wire);
}
RTLIL::SigSpec sig = assign_map(RTLIL::SigSpec(wire));
if (!used_signals_nodrivers.check_any(sig)) {
std::string unused_bits;
sig.expand();
for (size_t i = 0; i < sig.chunks.size(); i++) {
if (sig.chunks[i].wire == NULL)
continue;
if (!used_signals_nodrivers.check_any(sig)) {
if (!unused_bits.empty())
unused_bits += " ";
unused_bits += stringf("%zd", i);
}
}
if (unused_bits.empty() || wire->port_id != 0)
wire->attributes.erase("\\unused_bits");
else
wire->attributes["\\unused_bits"] = RTLIL::Const(unused_bits);
} else {
wire->attributes.erase("\\unused_bits");
}
}
int del_wires_count = 0;
for (auto wire : del_wires)
if (!used_signals.check_any(RTLIL::SigSpec(wire))) {
if (check_public_name(wire->name) && verbose) {
log(" removing unused non-port wire %s.\n", wire->name.c_str());
del_wires_count++;
}
module->wires.erase(wire->name);
count_rm_wires++;
delete wire;
}
if (del_wires_count > 0)
log(" removed %d unused temporary wires.\n", del_wires_count);
}
static void rmunused_module(RTLIL::Module *module, bool purge_mode, bool verbose)
{
if (verbose)
log("Finding unused cells or wires in module %s..\n", module->name.c_str());
rmunused_module_cells(module, verbose);
rmunused_module_signals(module, purge_mode, verbose);
}
struct OptCleanPass : public Pass {
OptCleanPass() : Pass("opt_clean", "remove unused cells and wires") { }
virtual void help()
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" opt_clean [options] [selection]\n");
log("\n");
log("This pass identifies wires and cells that are unused and removes them. Other\n");
log("passes often remove cells but leave the wires in the design or reconnect the\n");
log("wires but leave the old cells in the design. This pass can be used to clean up\n");
log("after the passes that do the actual work.\n");
log("\n");
log("This pass only operates on completely selected modules without processes.\n");
log("\n");
log(" -purge\n");
log(" also remove internal nets if they have a public name\n");
log("\n");
}
virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
{
bool purge_mode = false;
log_header("Executing OPT_CLEAN pass (remove unused cells and wires).\n");
log_push();
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-purge") {
purge_mode = true;
continue;
}
break;
}
extra_args(args, argidx, design);
ct.setup_internals();
ct.setup_internals_mem();
ct.setup_stdcells();
ct.setup_stdcells_mem();
ct_reg.setup_internals_mem();
ct_reg.setup_stdcells_mem();
for (auto &mod_it : design->modules) {
if (!design->selected_whole_module(mod_it.first)) {
if (design->selected(mod_it.second))
log("Skipping module %s as it is only partially selected.\n", id2cstr(mod_it.second->name));
continue;
}
if (mod_it.second->processes.size() > 0) {
log("Skipping module %s as it contains processes.\n", mod_it.second->name.c_str());
} else {
rmunused_module(mod_it.second, purge_mode, true);
}
}
ct.clear();
ct_reg.clear();
log_pop();
}
} OptCleanPass;
struct CleanPass : public Pass {
CleanPass() : Pass("clean", "remove unused cells and wires") { }
virtual void help()
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" clean [options] [selection]\n");
log("\n");
log("This is identical to 'opt_clean', but less verbose.\n");
log("\n");
log("When commands are seperated using the ';;' token, this command will be executed\n");
log("between the commands.\n");
log("\n");
log("When commands are seperated using the ';;;' token, this command will be executed\n");
log("in -purge mode between the commands.\n");
log("\n");
}
virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
{
bool purge_mode = false;
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-purge") {
purge_mode = true;
continue;
}
break;
}
if (argidx < args.size())
extra_args(args, argidx, design);
ct.setup_internals();
ct.setup_internals_mem();
ct.setup_stdcells();
ct.setup_stdcells_mem();
ct_reg.setup_internals_mem();
ct_reg.setup_stdcells_mem();
count_rm_cells = 0;
count_rm_wires = 0;
for (auto &mod_it : design->modules) {
if (design->selected_whole_module(mod_it.first) && mod_it.second->processes.size() == 0)
do {
OPT_DID_SOMETHING = false;
rmunused_module(mod_it.second, purge_mode, false);
} while (OPT_DID_SOMETHING);
}
if (count_rm_cells > 0 || count_rm_wires > 0)
log("Removed %d unused cells and %d unused wires.\n", count_rm_cells, count_rm_wires);
ct.clear();
ct_reg.clear();
}
} CleanPass;
<|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS oj30 (1.18.114); FILE MERGED 2008/01/09 09:43:56 oj 1.18.114.1: #i85085# add std namespace<commit_after><|endoftext|> |
<commit_before>#include "compare.h"
#include <cassert>
int remove_single_exon_transcripts(genome &gm)
{
for(int i = 0; i < gm.genes.size(); i++)
{
gm.genes[i].remove_single_exon_transcripts();
}
return 0;
}
bool compare_structure(const transcript &x, const transcript &y)
{
if(x.exons.size() != y.exons.size()) return false;
for(int i = 0; i < x.exons.size(); i++)
{
if(x.exons[i].first != y.exons[i].first) return false;
if(x.exons[i].second != y.exons[i].second) return false;
}
return true;
}
bool compare_intron_chain(const transcript &x, const transcript &y)
{
if(x.exons.size() != y.exons.size()) return false;
for(int i = 0; i < x.exons.size(); i++)
{
if(i >= 1 && x.exons[i].first != y.exons[i].first) return false;
if(i < x.exons.size() - 1 && x.exons[i].second != y.exons[i].second) return false;
}
return true;
}
bool compare_expression(const transcript &x, const transcript &y)
{
if(x.expression == y.expression) return true;
else return false;
}
int compare_gene(const gene &x, const gene &y, int mode)
{
return compare_transcripts(x.transcripts, y.transcripts, mode);
}
int compare_transcripts(const vector<transcript> &y, const vector<transcript> &x, int mode)
{
int cnt = 0;
vector<bool> v;
v.assign(y.size(), false);
for(int i = 0; i < x.size(); i++)
{
const transcript &t1 = x[i];
bool flag = false;
for(int j = 0; j < y.size(); j++)
{
if(v[j] == true) continue;
const transcript &t2 = y[j];
bool b = false;
if(mode == 1)
{
if(compare_structure(t1, t2) == false) b = false;
if(compare_expression(t1, t2) == false) b = false;
}
if(mode == 2)
{
b = compare_intron_chain(t1, t2);
//if(t1.strand != t2.strand) b = false;
}
if(b == false) continue;
//printf("%s %s matched, reference expression = %d predicted expression = %d, strands = (%c, %c)\n",
// t1.transcript_id.c_str(), t2.transcript_id.c_str(), t1.expression, t2.expression, t1.strand, t2.strand);
printf("TRUE %s %s\n", t1.transcript_id.c_str(), t2.transcript_id.c_str());
flag = true;
v[j] = true;
cnt++;
break;
}
if(flag == false) printf("FALSE %s\n", t1.transcript_id.c_str());
}
return cnt;
}
int compare_genome1(const genome &x, const genome &y)
{
int gequal = 0;
int tequal = 0;
int gtotal = x.genes.size();
int ttotal = 0;
for(int i = 0; i < x.genes.size(); i++)
{
const gene* gx = &(x.genes[i]);
const gene* gy = y.get_gene(x.genes[i].get_gene_id());
if(gx == NULL || gy == NULL) continue;
int tx = gx->transcripts.size();
int ty = gy->transcripts.size();
int t0 = compare_gene(*gx, *gy, 1);
assert(t0 <= tx);
assert(t0 <= ty);
ttotal += tx;
tequal += t0;
if(t0 == tx) gequal++;
string s;
if(tx == ty) s = "EQUAL";
else if(tx > ty) s = "GREATER";
else s = "LESS";
printf("%s %d and %d transcripts, %d are equal, %s, %s\n", gx->get_gene_id().c_str(), tx, ty, t0, (t0 == tx) ? "TRUE" : "FALSE", s.c_str());
}
printf("summary: %d out of %d genes are equal, %d out of %d transcripts are equal\n",
gequal, gtotal, tequal, ttotal);
return 0;
}
int compare_genome2(const genome &x, const genome &y)
{
typedef pair< string, vector<transcript> > PSVT;
typedef map< string, vector<transcript> > MSVT;
MSVT m1;
MSVT m2;
int xtotal = 0;
int ytotal = 0;
for(int i = 0; i < x.genes.size(); i++)
{
string chrm = x.genes[i].get_seqname();
const vector<transcript> &v = x.genes[i].transcripts;
xtotal += v.size();
if(m1.find(chrm) == m1.end())
{
m1.insert(PSVT(chrm, v));
}
else
{
m1[chrm].insert(m1[chrm].end(), v.begin(), v.end());
}
}
for(int i = 0; i < y.genes.size(); i++)
{
string chrm = y.genes[i].get_seqname();
const vector<transcript> &v = y.genes[i].transcripts;
ytotal += v.size();
if(m2.find(chrm) == m2.end())
{
m2.insert(PSVT(chrm, v));
}
else
{
m2[chrm].insert(m2[chrm].end(), v.begin(), v.end());
}
}
int correct = 0;
for(MSVT::iterator it = m1.begin(); it != m1.end(); it++)
{
const vector<transcript> &v1 = it->second;
if(m2.find(it->first) == m2.end()) continue;
const vector<transcript> &v2 = m2[it->first];
correct += compare_transcripts(v1, v2, 2);
}
double s = (xtotal == 0) ? 0 : correct * 100.0 / xtotal;
double p = (ytotal == 0) ? 0 : correct * 100.0 / ytotal;
printf("reference = %d prediction = %d correct = %d sensitivity = %.2lf precision = %.2lf\n", xtotal, ytotal, correct, s, p);
return 0;
}
<commit_msg>print label<commit_after>#include "compare.h"
#include <cassert>
int remove_single_exon_transcripts(genome &gm)
{
for(int i = 0; i < gm.genes.size(); i++)
{
gm.genes[i].remove_single_exon_transcripts();
}
return 0;
}
bool compare_structure(const transcript &x, const transcript &y)
{
if(x.exons.size() != y.exons.size()) return false;
for(int i = 0; i < x.exons.size(); i++)
{
if(x.exons[i].first != y.exons[i].first) return false;
if(x.exons[i].second != y.exons[i].second) return false;
}
return true;
}
bool compare_intron_chain(const transcript &x, const transcript &y)
{
if(x.exons.size() != y.exons.size()) return false;
for(int i = 0; i < x.exons.size(); i++)
{
if(i >= 1 && x.exons[i].first != y.exons[i].first) return false;
if(i < x.exons.size() - 1 && x.exons[i].second != y.exons[i].second) return false;
}
return true;
}
bool compare_expression(const transcript &x, const transcript &y)
{
if(x.expression == y.expression) return true;
else return false;
}
int compare_gene(const gene &x, const gene &y, int mode)
{
return compare_transcripts(x.transcripts, y.transcripts, mode);
}
int compare_transcripts(const vector<transcript> &y, const vector<transcript> &x, int mode)
{
int cnt = 0;
vector<bool> v;
v.assign(y.size(), false);
for(int i = 0; i < x.size(); i++)
{
const transcript &t1 = x[i];
bool flag = false;
for(int j = 0; j < y.size(); j++)
{
if(v[j] == true) continue;
const transcript &t2 = y[j];
bool b = false;
if(mode == 1)
{
if(compare_structure(t1, t2) == false) b = false;
if(compare_expression(t1, t2) == false) b = false;
}
if(mode == 2)
{
b = compare_intron_chain(t1, t2);
//if(t1.strand != t2.strand) b = false;
}
if(b == false) continue;
//printf("%s %s matched, reference expression = %d predicted expression = %d, strands = (%c, %c)\n",
// t1.transcript_id.c_str(), t2.transcript_id.c_str(), t1.expression, t2.expression, t1.strand, t2.strand);
printf("TRUE %s %s %s\n", t1.transcript_id.c_str(), t1.label().c_str(), t2.transcript_id.c_str());
flag = true;
v[j] = true;
cnt++;
break;
}
if(flag == false) printf("FALSE %s %s\n", t1.transcript_id.c_str(), t1.label().c_str());
}
return cnt;
}
int compare_genome1(const genome &x, const genome &y)
{
int gequal = 0;
int tequal = 0;
int gtotal = x.genes.size();
int ttotal = 0;
for(int i = 0; i < x.genes.size(); i++)
{
const gene* gx = &(x.genes[i]);
const gene* gy = y.get_gene(x.genes[i].get_gene_id());
if(gx == NULL || gy == NULL) continue;
int tx = gx->transcripts.size();
int ty = gy->transcripts.size();
int t0 = compare_gene(*gx, *gy, 1);
assert(t0 <= tx);
assert(t0 <= ty);
ttotal += tx;
tequal += t0;
if(t0 == tx) gequal++;
string s;
if(tx == ty) s = "EQUAL";
else if(tx > ty) s = "GREATER";
else s = "LESS";
printf("%s %d and %d transcripts, %d are equal, %s, %s\n", gx->get_gene_id().c_str(), tx, ty, t0, (t0 == tx) ? "TRUE" : "FALSE", s.c_str());
}
printf("summary: %d out of %d genes are equal, %d out of %d transcripts are equal\n",
gequal, gtotal, tequal, ttotal);
return 0;
}
int compare_genome2(const genome &x, const genome &y)
{
typedef pair< string, vector<transcript> > PSVT;
typedef map< string, vector<transcript> > MSVT;
MSVT m1;
MSVT m2;
int xtotal = 0;
int ytotal = 0;
for(int i = 0; i < x.genes.size(); i++)
{
string chrm = x.genes[i].get_seqname();
const vector<transcript> &v = x.genes[i].transcripts;
xtotal += v.size();
if(m1.find(chrm) == m1.end())
{
m1.insert(PSVT(chrm, v));
}
else
{
m1[chrm].insert(m1[chrm].end(), v.begin(), v.end());
}
}
for(int i = 0; i < y.genes.size(); i++)
{
string chrm = y.genes[i].get_seqname();
const vector<transcript> &v = y.genes[i].transcripts;
ytotal += v.size();
if(m2.find(chrm) == m2.end())
{
m2.insert(PSVT(chrm, v));
}
else
{
m2[chrm].insert(m2[chrm].end(), v.begin(), v.end());
}
}
int correct = 0;
for(MSVT::iterator it = m1.begin(); it != m1.end(); it++)
{
const vector<transcript> &v1 = it->second;
if(m2.find(it->first) == m2.end()) continue;
const vector<transcript> &v2 = m2[it->first];
correct += compare_transcripts(v1, v2, 2);
}
double s = (xtotal == 0) ? 0 : correct * 100.0 / xtotal;
double p = (ytotal == 0) ? 0 : correct * 100.0 / ytotal;
printf("reference = %d prediction = %d correct = %d sensitivity = %.2lf precision = %.2lf\n", xtotal, ytotal, correct, s, p);
return 0;
}
<|endoftext|> |
<commit_before>/*
* ProbeHullRenderTasks.cpp
*
* Copyright (C) 2020 by Universitaet Stuttgart (VISUS).
* All rights reserved.
*/
#include "stdafx.h"
#include "mmcore/EventCall.h"
#include "mmcore/param/EnumParam.h"
#include "ProbeCalls.h"
#include "ProbeEvents.h"
#include "ProbeGlCalls.h"
#include "ProbeHUllRenderTasks.h"
#include "mesh/MeshCalls.h"
bool megamol::probe_gl::ProbeHullRenderTasks::create() {
m_rendertask_collection.first = std::make_shared<mesh::GPURenderTaskCollection>();
struct PerFrameData {
int shading_mode;
};
std::array<PerFrameData, 1> per_frame_data;
per_frame_data[0].shading_mode = m_shading_mode_slot.Param<core::param::EnumParam>()->Value();
m_rendertask_collection.first->addPerFrameDataBuffer("", per_frame_data, 1);
m_material_collection = std::make_shared<mesh::GPUMaterialCollection>();
m_material_collection->addMaterial(this->instance(), "ProbeHull", "ProbeHull");
m_material_collection->addMaterial(this->instance(), "ProbeTriangleHull", "ProbeTriangleHull");
//TODO add other shader for e.g. triangle-based meshes ? switch automatically of course
return true;
}
megamol::probe_gl::ProbeHullRenderTasks::ProbeHullRenderTasks()
: m_version(0)
, m_show_hull(true)
//, m_probes_slot("probes","")
, m_event_slot("GetEvents", "")
, m_shading_mode_slot("ShadingMode","") {
//this->m_probes_slot.SetCompatibleCall<megamol::probe::CallProbesDescription>();
//this->MakeSlotAvailable(&this->m_probes_slot);
this->m_event_slot.SetCompatibleCall<core::CallEventDescription>();
this->MakeSlotAvailable(&this->m_event_slot);
this->m_shading_mode_slot << new megamol::core::param::EnumParam(0);
this->m_shading_mode_slot.Param<megamol::core::param::EnumParam>()->SetTypePair(0, "Grey");
this->m_shading_mode_slot.Param<megamol::core::param::EnumParam>()->SetTypePair(1, "ClusterID");
this->MakeSlotAvailable(&this->m_shading_mode_slot);
}
megamol::probe_gl::ProbeHullRenderTasks::~ProbeHullRenderTasks() {}
bool megamol::probe_gl::ProbeHullRenderTasks::getDataCallback(core::Call& caller) {
mesh::CallGPURenderTaskData* lhs_rtc = dynamic_cast<mesh::CallGPURenderTaskData*>(&caller);
if (lhs_rtc == NULL)
return false;
mesh::CallGPURenderTaskData* rhs_rtc = this->m_renderTask_rhs_slot.CallAs<mesh::CallGPURenderTaskData>();
std::vector<std::shared_ptr<mesh::GPURenderTaskCollection>> gpu_render_tasks;
if (rhs_rtc != nullptr) {
if (!(*rhs_rtc)(0)) {
return false;
}
if (rhs_rtc->hasUpdate()) {
++m_version;
}
gpu_render_tasks = rhs_rtc->getData();
}
gpu_render_tasks.push_back(m_rendertask_collection.first);
mesh::CallGPUMeshData* mc = this->m_mesh_slot.CallAs<mesh::CallGPUMeshData>();
if (mc != nullptr) {
if (!(*mc)(0))
return false;
if (m_shading_mode_slot.IsDirty()) {
m_shading_mode_slot.ResetDirty();
struct PerFrameData {
int shading_mode;
};
std::array<PerFrameData, 1> per_frame_data;
per_frame_data[0].shading_mode = m_shading_mode_slot.Param<core::param::EnumParam>()->Value();
m_rendertask_collection.first->updatePerFrameDataBuffer("", per_frame_data, 1);
}
bool something_has_changed = mc->hasUpdate();
if (something_has_changed) {
++m_version;
for (auto& identifier : m_rendertask_collection.second) {
m_rendertask_collection.first->deleteRenderTask(identifier);
}
m_rendertask_collection.second.clear();
m_identifiers.clear();
m_draw_commands.clear();
m_object_transforms.clear();
m_batch_meshes.clear();
auto gpu_mesh_storage = mc->getData();
for (auto& mesh_collection : gpu_mesh_storage) {
std::shared_ptr<glowl::Mesh> prev_mesh(nullptr);
for (auto& sub_mesh : mesh_collection->getSubMeshData()) {
auto const& gpu_batch_mesh = sub_mesh.second.mesh->mesh;
if (gpu_batch_mesh != prev_mesh) {
m_draw_commands.emplace_back(std::vector<glowl::DrawElementsCommand>());
m_object_transforms.emplace_back(std::vector<std::array<float, 16>>());
m_batch_meshes.push_back(gpu_batch_mesh);
prev_mesh = gpu_batch_mesh;
}
float scale = 1.0f;
std::array<float, 16> obj_xform = {scale, 0.0f, 0.0f, 0.0f, 0.0f, scale, 0.0f, 0.0f, 0.0f, 0.0f,
scale, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
m_identifiers.emplace_back(std::string(FullName()) + "_" + sub_mesh.first);
m_draw_commands.back().push_back(sub_mesh.second.sub_mesh_draw_command);
m_object_transforms.back().push_back(obj_xform);
}
}
if (m_show_hull) {
auto patch_shader = m_material_collection->getMaterial("ProbeHull").shader_program;
auto tri_shader = m_material_collection->getMaterial("ProbeTriangleHull").shader_program;
for (int i = 0; i < m_batch_meshes.size(); ++i) {
if (m_batch_meshes[i]->getPrimitiveType() == GL_TRIANGLES) {
m_rendertask_collection.first->addRenderTasks(
m_identifiers, tri_shader, m_batch_meshes[i], m_draw_commands[i], m_object_transforms[i]);
m_rendertask_collection.second.insert(
m_rendertask_collection.second.end(), m_identifiers.begin(), m_identifiers.end());
} else if (m_batch_meshes[i]->getPrimitiveType() == GL_PATCHES) {
m_rendertask_collection.first->addRenderTasks(
m_identifiers, patch_shader, m_batch_meshes[i], m_draw_commands[i], m_object_transforms[i]);
m_rendertask_collection.second.insert(
m_rendertask_collection.second.end(), m_identifiers.begin(), m_identifiers.end());
} else {
//TODO print warning
}
}
}
}
// check for pending events
auto call_event_storage = this->m_event_slot.CallAs<core::CallEvent>();
if (call_event_storage != NULL) {
if ((!(*call_event_storage)(0)))
return false;
auto event_collection = call_event_storage->getData();
// process toggle show glyph events
{
auto pending_deselect_events = event_collection->get<ToggleShowHull>();
for (auto& evt : pending_deselect_events) {
m_show_hull = !m_show_hull;
if (m_show_hull) {
auto const& shader = m_material_collection->getMaterial("ProbeHull").shader_program;
for (int i = 0; i < m_batch_meshes.size(); ++i) {
m_rendertask_collection.first->addRenderTasks(
m_identifiers, shader, m_batch_meshes[i], m_draw_commands[i], m_object_transforms[i]);
m_rendertask_collection.second.insert(
m_rendertask_collection.second.end(), m_identifiers.begin(), m_identifiers.end());
}
} else {
for (auto& identifier : m_rendertask_collection.second) {
m_rendertask_collection.first->deleteRenderTask(identifier);
}
m_rendertask_collection.second.clear();
}
}
}
}
// TODO merge meta data stuff, i.e. bounding box
auto mesh_meta_data = mc->getMetaData();
}
// set data if necessary
lhs_rtc->setData(gpu_render_tasks, m_version);
return true;
}
bool megamol::probe_gl::ProbeHullRenderTasks::getMetaDataCallback(core::Call& caller) {
if (!AbstractGPURenderTaskDataSource::getMetaDataCallback(caller))
return false;
mesh::CallGPURenderTaskData* lhs_rt_call = dynamic_cast<mesh::CallGPURenderTaskData*>(&caller);
mesh::CallGPUMeshData* mesh_call = this->m_mesh_slot.CallAs<mesh::CallGPUMeshData>();
auto lhs_meta_data = lhs_rt_call->getMetaData();
if (mesh_call != NULL) {
auto mesh_meta_data = mesh_call->getMetaData();
mesh_meta_data.m_frame_ID = lhs_meta_data.m_frame_ID;
mesh_call->setMetaData(mesh_meta_data);
if (!(*mesh_call)(1))
return false;
mesh_meta_data = mesh_call->getMetaData();
auto bbox = lhs_meta_data.m_bboxs.BoundingBox();
auto cbbox = lhs_meta_data.m_bboxs.ClipBox();
auto mesh_bbox = mesh_meta_data.m_bboxs.BoundingBox();
auto mesh_cbbox = mesh_meta_data.m_bboxs.ClipBox();
// mesh_bbox.SetSize(vislib::math::Dimension<float, 3>(
// 2.1f * mesh_bbox.GetSize()[0], 2.1f * mesh_bbox.GetSize()[1], 2.1f * mesh_bbox.GetSize()[2]));
mesh_cbbox.SetSize(vislib::math::Dimension<float, 3>(
2.1f * mesh_cbbox.GetSize()[0], 2.1f * mesh_cbbox.GetSize()[1], 2.1f * mesh_cbbox.GetSize()[2]));
bbox.Union(mesh_bbox);
cbbox.Union(mesh_cbbox);
lhs_meta_data.m_bboxs.SetBoundingBox(bbox);
lhs_meta_data.m_bboxs.SetClipBox(cbbox);
}
lhs_rt_call->setMetaData(lhs_meta_data);
return true;
}
<commit_msg>Bugfix for show hull event<commit_after>/*
* ProbeHullRenderTasks.cpp
*
* Copyright (C) 2020 by Universitaet Stuttgart (VISUS).
* All rights reserved.
*/
#include "stdafx.h"
#include "mmcore/EventCall.h"
#include "mmcore/param/EnumParam.h"
#include "ProbeCalls.h"
#include "ProbeEvents.h"
#include "ProbeGlCalls.h"
#include "ProbeHUllRenderTasks.h"
#include "mesh/MeshCalls.h"
bool megamol::probe_gl::ProbeHullRenderTasks::create() {
m_rendertask_collection.first = std::make_shared<mesh::GPURenderTaskCollection>();
struct PerFrameData {
int shading_mode;
};
std::array<PerFrameData, 1> per_frame_data;
per_frame_data[0].shading_mode = m_shading_mode_slot.Param<core::param::EnumParam>()->Value();
m_rendertask_collection.first->addPerFrameDataBuffer("", per_frame_data, 1);
m_material_collection = std::make_shared<mesh::GPUMaterialCollection>();
m_material_collection->addMaterial(this->instance(), "ProbeHull", "ProbeHull");
m_material_collection->addMaterial(this->instance(), "ProbeTriangleHull", "ProbeTriangleHull");
//TODO add other shader for e.g. triangle-based meshes ? switch automatically of course
return true;
}
megamol::probe_gl::ProbeHullRenderTasks::ProbeHullRenderTasks()
: m_version(0)
, m_show_hull(true)
//, m_probes_slot("probes","")
, m_event_slot("GetEvents", "")
, m_shading_mode_slot("ShadingMode","") {
//this->m_probes_slot.SetCompatibleCall<megamol::probe::CallProbesDescription>();
//this->MakeSlotAvailable(&this->m_probes_slot);
this->m_event_slot.SetCompatibleCall<core::CallEventDescription>();
this->MakeSlotAvailable(&this->m_event_slot);
this->m_shading_mode_slot << new megamol::core::param::EnumParam(0);
this->m_shading_mode_slot.Param<megamol::core::param::EnumParam>()->SetTypePair(0, "Grey");
this->m_shading_mode_slot.Param<megamol::core::param::EnumParam>()->SetTypePair(1, "ClusterID");
this->MakeSlotAvailable(&this->m_shading_mode_slot);
}
megamol::probe_gl::ProbeHullRenderTasks::~ProbeHullRenderTasks() {}
bool megamol::probe_gl::ProbeHullRenderTasks::getDataCallback(core::Call& caller) {
mesh::CallGPURenderTaskData* lhs_rtc = dynamic_cast<mesh::CallGPURenderTaskData*>(&caller);
if (lhs_rtc == NULL)
return false;
mesh::CallGPURenderTaskData* rhs_rtc = this->m_renderTask_rhs_slot.CallAs<mesh::CallGPURenderTaskData>();
std::vector<std::shared_ptr<mesh::GPURenderTaskCollection>> gpu_render_tasks;
if (rhs_rtc != nullptr) {
if (!(*rhs_rtc)(0)) {
return false;
}
if (rhs_rtc->hasUpdate()) {
++m_version;
}
gpu_render_tasks = rhs_rtc->getData();
}
gpu_render_tasks.push_back(m_rendertask_collection.first);
mesh::CallGPUMeshData* mc = this->m_mesh_slot.CallAs<mesh::CallGPUMeshData>();
if (mc != nullptr) {
if (!(*mc)(0))
return false;
if (m_shading_mode_slot.IsDirty()) {
m_shading_mode_slot.ResetDirty();
struct PerFrameData {
int shading_mode;
};
std::array<PerFrameData, 1> per_frame_data;
per_frame_data[0].shading_mode = m_shading_mode_slot.Param<core::param::EnumParam>()->Value();
m_rendertask_collection.first->updatePerFrameDataBuffer("", per_frame_data, 1);
}
bool something_has_changed = mc->hasUpdate();
if (something_has_changed) {
++m_version;
for (auto& identifier : m_rendertask_collection.second) {
m_rendertask_collection.first->deleteRenderTask(identifier);
}
m_rendertask_collection.second.clear();
m_identifiers.clear();
m_draw_commands.clear();
m_object_transforms.clear();
m_batch_meshes.clear();
auto gpu_mesh_storage = mc->getData();
for (auto& mesh_collection : gpu_mesh_storage) {
std::shared_ptr<glowl::Mesh> prev_mesh(nullptr);
for (auto& sub_mesh : mesh_collection->getSubMeshData()) {
auto const& gpu_batch_mesh = sub_mesh.second.mesh->mesh;
if (gpu_batch_mesh != prev_mesh) {
m_draw_commands.emplace_back(std::vector<glowl::DrawElementsCommand>());
m_object_transforms.emplace_back(std::vector<std::array<float, 16>>());
m_batch_meshes.push_back(gpu_batch_mesh);
prev_mesh = gpu_batch_mesh;
}
float scale = 1.0f;
std::array<float, 16> obj_xform = {scale, 0.0f, 0.0f, 0.0f, 0.0f, scale, 0.0f, 0.0f, 0.0f, 0.0f,
scale, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
m_identifiers.emplace_back(std::string(FullName()) + "_" + sub_mesh.first);
m_draw_commands.back().push_back(sub_mesh.second.sub_mesh_draw_command);
m_object_transforms.back().push_back(obj_xform);
}
}
if (m_show_hull) {
auto patch_shader = m_material_collection->getMaterial("ProbeHull").shader_program;
auto tri_shader = m_material_collection->getMaterial("ProbeTriangleHull").shader_program;
for (int i = 0; i < m_batch_meshes.size(); ++i) {
if (m_batch_meshes[i]->getPrimitiveType() == GL_TRIANGLES) {
m_rendertask_collection.first->addRenderTasks(
m_identifiers, tri_shader, m_batch_meshes[i], m_draw_commands[i], m_object_transforms[i]);
m_rendertask_collection.second.insert(
m_rendertask_collection.second.end(), m_identifiers.begin(), m_identifiers.end());
} else if (m_batch_meshes[i]->getPrimitiveType() == GL_PATCHES) {
m_rendertask_collection.first->addRenderTasks(
m_identifiers, patch_shader, m_batch_meshes[i], m_draw_commands[i], m_object_transforms[i]);
m_rendertask_collection.second.insert(
m_rendertask_collection.second.end(), m_identifiers.begin(), m_identifiers.end());
} else {
//TODO print warning
}
}
}
}
// check for pending events
auto call_event_storage = this->m_event_slot.CallAs<core::CallEvent>();
if (call_event_storage != NULL) {
if ((!(*call_event_storage)(0)))
return false;
auto event_collection = call_event_storage->getData();
// process toggle show glyph events
{
auto pending_deselect_events = event_collection->get<ToggleShowHull>();
for (auto& evt : pending_deselect_events) {
m_show_hull = !m_show_hull;
if (m_show_hull) {
//TODO get rid of code copy-pasting...
auto patch_shader = m_material_collection->getMaterial("ProbeHull").shader_program;
auto tri_shader = m_material_collection->getMaterial("ProbeTriangleHull").shader_program;
for (int i = 0; i < m_batch_meshes.size(); ++i) {
if (m_batch_meshes[i]->getPrimitiveType() == GL_TRIANGLES) {
m_rendertask_collection.first->addRenderTasks(m_identifiers, tri_shader,
m_batch_meshes[i], m_draw_commands[i], m_object_transforms[i]);
m_rendertask_collection.second.insert(
m_rendertask_collection.second.end(), m_identifiers.begin(), m_identifiers.end());
} else if (m_batch_meshes[i]->getPrimitiveType() == GL_PATCHES) {
m_rendertask_collection.first->addRenderTasks(m_identifiers, patch_shader,
m_batch_meshes[i], m_draw_commands[i], m_object_transforms[i]);
m_rendertask_collection.second.insert(
m_rendertask_collection.second.end(), m_identifiers.begin(), m_identifiers.end());
} else {
// TODO print warning
}
}
} else {
for (auto& identifier : m_rendertask_collection.second) {
m_rendertask_collection.first->deleteRenderTask(identifier);
}
m_rendertask_collection.second.clear();
}
}
}
}
// TODO merge meta data stuff, i.e. bounding box
auto mesh_meta_data = mc->getMetaData();
}
// set data if necessary
lhs_rtc->setData(gpu_render_tasks, m_version);
return true;
}
bool megamol::probe_gl::ProbeHullRenderTasks::getMetaDataCallback(core::Call& caller) {
if (!AbstractGPURenderTaskDataSource::getMetaDataCallback(caller))
return false;
mesh::CallGPURenderTaskData* lhs_rt_call = dynamic_cast<mesh::CallGPURenderTaskData*>(&caller);
mesh::CallGPUMeshData* mesh_call = this->m_mesh_slot.CallAs<mesh::CallGPUMeshData>();
auto lhs_meta_data = lhs_rt_call->getMetaData();
if (mesh_call != NULL) {
auto mesh_meta_data = mesh_call->getMetaData();
mesh_meta_data.m_frame_ID = lhs_meta_data.m_frame_ID;
mesh_call->setMetaData(mesh_meta_data);
if (!(*mesh_call)(1))
return false;
mesh_meta_data = mesh_call->getMetaData();
auto bbox = lhs_meta_data.m_bboxs.BoundingBox();
auto cbbox = lhs_meta_data.m_bboxs.ClipBox();
auto mesh_bbox = mesh_meta_data.m_bboxs.BoundingBox();
auto mesh_cbbox = mesh_meta_data.m_bboxs.ClipBox();
// mesh_bbox.SetSize(vislib::math::Dimension<float, 3>(
// 2.1f * mesh_bbox.GetSize()[0], 2.1f * mesh_bbox.GetSize()[1], 2.1f * mesh_bbox.GetSize()[2]));
mesh_cbbox.SetSize(vislib::math::Dimension<float, 3>(
2.1f * mesh_cbbox.GetSize()[0], 2.1f * mesh_cbbox.GetSize()[1], 2.1f * mesh_cbbox.GetSize()[2]));
bbox.Union(mesh_bbox);
cbbox.Union(mesh_cbbox);
lhs_meta_data.m_bboxs.SetBoundingBox(bbox);
lhs_meta_data.m_bboxs.SetClipBox(cbbox);
}
lhs_rt_call->setMetaData(lhs_meta_data);
return true;
}
<|endoftext|> |
<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include <cstring>
#include <typeinfo>
#include <pficommon/lang/shared_ptr.h>
#include <pficommon/lang/cast.h>
namespace jubatus {
namespace exception {
namespace detail {
std::string demangle_symbol(const char *symbol);
}
class error_info_base {
public:
virtual bool splitter() const
{
return false;
}
virtual std::string tag_typeid_name() const = 0;
virtual std::string as_string() const = 0;
virtual ~error_info_base() throw()
{}
};
template <class Tag, class V>
class error_info;
template <class Tag, class V>
inline std::string to_string(const error_info<Tag, V>& info)
{
return pfi::lang::lexical_cast<std::string, V>(info.value());
}
template<>
class error_info<struct error_splitter_, void> : public error_info_base {
public:
bool splitter() const
{
return true;
}
std::string tag_typeid_name() const
{
return jubatus::exception::detail::demangle_symbol(typeid(struct error_splitter_*).name());
}
std::string as_string() const
{
// USE splitter or tag_typeid_name
return "-splitter-";
}
};
template <class Tag, class V>
class error_info : public error_info_base {
public:
typedef V value_type;
error_info(value_type v);
~error_info() throw();
std::string tag_typeid_name() const;
std::string as_string() const;
value_type value() const
{
return value_;
}
private:
value_type value_;
};
template <class Tag, class V>
inline error_info<Tag, V>::error_info(value_type v)
: value_(v)
{
}
template <class Tag, class V>
inline error_info<Tag, V>::~error_info() throw()
{
}
template <class Tag, class V>
inline std::string error_info<Tag, V>::tag_typeid_name() const
{
return jubatus::exception::detail::demangle_symbol(typeid(Tag*).name());
}
template <class Tag, class V>
inline std::string error_info<Tag, V>::as_string() const
{
return to_string(*this);
}
} // exception
} // jubatus
<commit_msg>Add pragma_once to common/exception_info.hpp<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#pragma once
#include <cstring>
#include <typeinfo>
#include <pficommon/lang/shared_ptr.h>
#include <pficommon/lang/cast.h>
namespace jubatus {
namespace exception {
namespace detail {
std::string demangle_symbol(const char *symbol);
}
class error_info_base {
public:
virtual bool splitter() const
{
return false;
}
virtual std::string tag_typeid_name() const = 0;
virtual std::string as_string() const = 0;
virtual ~error_info_base() throw()
{}
};
template <class Tag, class V>
class error_info;
template <class Tag, class V>
inline std::string to_string(const error_info<Tag, V>& info)
{
return pfi::lang::lexical_cast<std::string, V>(info.value());
}
template<>
class error_info<struct error_splitter_, void> : public error_info_base {
public:
bool splitter() const
{
return true;
}
std::string tag_typeid_name() const
{
return jubatus::exception::detail::demangle_symbol(typeid(struct error_splitter_*).name());
}
std::string as_string() const
{
// USE splitter or tag_typeid_name
return "-splitter-";
}
};
template <class Tag, class V>
class error_info : public error_info_base {
public:
typedef V value_type;
error_info(value_type v);
~error_info() throw();
std::string tag_typeid_name() const;
std::string as_string() const;
value_type value() const
{
return value_;
}
private:
value_type value_;
};
template <class Tag, class V>
inline error_info<Tag, V>::error_info(value_type v)
: value_(v)
{
}
template <class Tag, class V>
inline error_info<Tag, V>::~error_info() throw()
{
}
template <class Tag, class V>
inline std::string error_info<Tag, V>::tag_typeid_name() const
{
return jubatus::exception::detail::demangle_symbol(typeid(Tag*).name());
}
template <class Tag, class V>
inline std::string error_info<Tag, V>::as_string() const
{
return to_string(*this);
}
} // exception
} // jubatus
<|endoftext|> |
<commit_before>/*********************************************************************
*
* Condor ClassAd library
* Copyright (C) 1990-2003, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI and Rajesh Raman.
*
* This source code is covered by the Condor Public License, which can
* be found in the accompanying LICENSE file, or online at
* www.condorproject.org.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* AND THE UNIVERSITY OF WISCONSIN-MADISON "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, OF SATISFACTORY QUALITY, AND FITNESS
* FOR A PARTICULAR PURPOSE OR USE ARE DISCLAIMED. THE COPYRIGHT
* HOLDERS AND CONTRIBUTORS AND THE UNIVERSITY OF WISCONSIN-MADISON
* MAKE NO MAKE NO REPRESENTATION THAT THE SOFTWARE, MODIFICATIONS,
* ENHANCEMENTS OR DERIVATIVE WORKS THEREOF, WILL NOT INFRINGE ANY
* PATENT, COPYRIGHT, TRADEMARK, TRADE SECRET OR OTHER PROPRIETARY
* RIGHT.
*
*********************************************************************/
#include "common.h"
#include "operators.h"
#include "sink.h"
#include "value.h"
#include <iostream>
using namespace std;
BEGIN_NAMESPACE( classad )
const double Value::ScaleFactor[] = {
1.0, // none
1.0, // B
1024.0, // Kilo
1024.0*1024.0, // Mega
1024.0*1024.0*1024.0, // Giga
1024.0*1024.0*1024.0*1024.0 // Terra
};
Value::
Value( )
{
valueType = UNDEFINED_VALUE;
booleanValue = false;
integerValue = 0;
realValue = 0.0;
listValue = NULL;
classadValue = NULL;
relTimeValueSecs = 0;
absTimeValueSecs.secs = 0;
absTimeValueSecs.offset = 0;
}
Value::
Value(const Value &value)
{
CopyFrom(value);
return;
}
Value::
~Value()
{
}
Value& Value::
operator=(const Value &value)
{
if (this != &value) {
CopyFrom(value);
}
return *this;
}
void Value::
Clear()
{
switch( valueType ) {
case LIST_VALUE:
// list values live in the evaluation environment, so they must
// never be explicitly destroyed
listValue = NULL;
break;
case CLASSAD_VALUE:
// classad values live in the evaluation environment, so they must
// never be explicitly destroyed
classadValue = NULL;
break;
case STRING_VALUE:
strValue = "";
break;
default:
valueType = UNDEFINED_VALUE;
}
valueType = UNDEFINED_VALUE;
}
bool Value::
IsNumber (int &i) const
{
switch (valueType) {
case INTEGER_VALUE:
i = integerValue;
return true;
case REAL_VALUE:
i = (int) realValue; // truncation
return true;
default:
return false;
}
}
bool Value::
IsNumber (double &r) const
{
switch (valueType) {
case INTEGER_VALUE:
r = (double) integerValue;
return true;
case REAL_VALUE:
r = realValue;
return true;
default:
return false;
}
}
void Value::
CopyFrom( const Value &val )
{
valueType = val.valueType;
switch (val.valueType) {
case STRING_VALUE:
strValue = val.strValue;
return;
case BOOLEAN_VALUE:
booleanValue = val.booleanValue;
return;
case INTEGER_VALUE:
integerValue = val.integerValue;
return;
case REAL_VALUE:
realValue = val.realValue;
return;
case UNDEFINED_VALUE:
case ERROR_VALUE:
return;
case LIST_VALUE:
listValue = val.listValue;
return;
case CLASSAD_VALUE:
classadValue = val.classadValue;
return;
case ABSOLUTE_TIME_VALUE:
absTimeValueSecs = val.absTimeValueSecs;
return;
case RELATIVE_TIME_VALUE:
relTimeValueSecs = val.relTimeValueSecs;
return;
default:
SetUndefinedValue ();
}
}
void Value::
SetRealValue (double r)
{
valueType=REAL_VALUE;
realValue = r;
}
void Value::
SetBooleanValue( bool b )
{
valueType = BOOLEAN_VALUE;
booleanValue = b;
}
void Value::
SetIntegerValue (int i)
{
valueType=INTEGER_VALUE;
integerValue = i;
}
void Value::
SetUndefinedValue (void)
{
valueType=UNDEFINED_VALUE;
}
void Value::
SetErrorValue (void)
{
valueType=ERROR_VALUE;
}
void Value::
SetStringValue( const string &s )
{
valueType = STRING_VALUE;
strValue = s;
}
void Value::
SetStringValue( const char *s )
{
valueType = STRING_VALUE;
strValue = s;
}
void Value::
SetListValue( ExprList *l)
{
valueType = LIST_VALUE;
listValue = l;
}
void Value::
SetClassAdValue( ClassAd *ad )
{
valueType = CLASSAD_VALUE;
classadValue = ad;
}
void Value::
SetRelativeTimeValue( time_t rsecs )
{
valueType = RELATIVE_TIME_VALUE;
relTimeValueSecs = (double) rsecs;
}
void Value::
SetRelativeTimeValue( double rsecs )
{
valueType = RELATIVE_TIME_VALUE;
relTimeValueSecs = rsecs;
}
void Value::
SetAbsoluteTimeValue( abstime_t asecs )
{
valueType = ABSOLUTE_TIME_VALUE;
absTimeValueSecs = asecs;
}
bool Value::
SameAs(const Value &otherValue) const
{
bool is_same;
if (valueType != otherValue.valueType) {
is_same = false;
} else {
switch (valueType) {
case Value::NULL_VALUE:
case Value::ERROR_VALUE:
case Value::UNDEFINED_VALUE:
is_same = true;
break;
case Value::BOOLEAN_VALUE:
is_same = (booleanValue == otherValue.booleanValue);
break;
case Value::INTEGER_VALUE:
is_same = (integerValue == otherValue.integerValue);
break;
case Value::REAL_VALUE:
is_same = (realValue == otherValue.realValue);
break;
case Value::LIST_VALUE:
// To do!
break;
case Value::CLASSAD_VALUE:
// To do!
break;
case Value::RELATIVE_TIME_VALUE:
is_same = (relTimeValueSecs == otherValue.relTimeValueSecs);
break;
case Value::ABSOLUTE_TIME_VALUE:
is_same = ( absTimeValueSecs.secs == otherValue.absTimeValueSecs.secs
&& absTimeValueSecs.offset == otherValue.absTimeValueSecs.offset);
break;
case Value::STRING_VALUE:
is_same = (strValue == otherValue.strValue);
break;
}
}
return is_same;
}
bool operator==(const Value &value1, const Value &value2)
{
return value1.SameAs(value2);
}
ostream& operator<<(ostream &stream, Value &value)
{
ClassAdUnParser unparser;
string unparsed_text;
switch (value.valueType) {
case Value::NULL_VALUE:
stream << "(null)";
break;
case Value::ERROR_VALUE:
stream << "error";
break;
case Value::UNDEFINED_VALUE:
stream << "undefined";
break;
case Value::BOOLEAN_VALUE:
if (value.booleanValue) {
stream << "true";
} else {
stream << "false";
}
break;
case Value::INTEGER_VALUE:
stream << value.integerValue;
break;
case Value::REAL_VALUE:
stream << value.realValue;
break;
case Value::LIST_VALUE:
case Value::CLASSAD_VALUE:
case Value::RELATIVE_TIME_VALUE:
case Value::ABSOLUTE_TIME_VALUE: {
unparser.Unparse(unparsed_text, value);
stream << unparsed_text;
break;
}
case Value::STRING_VALUE:
stream << value.strValue;
break;
}
return stream;
}
bool convertValueToRealValue(const Value value, Value &realValue)
{
bool could_convert;
string buf;
char *end;
int ivalue;
time_t rtvalue;
abstime_t atvalue;
bool bvalue;
double rvalue;
Value::NumberFactor nf;
switch(value.GetType()) {
case Value::UNDEFINED_VALUE:
realValue.SetUndefinedValue();
could_convert = false;
break;
case Value::ERROR_VALUE:
case Value::CLASSAD_VALUE:
case Value::LIST_VALUE:
realValue.SetErrorValue();
could_convert = false;
break;
case Value::STRING_VALUE:
value.IsStringValue(buf);
rvalue = strtod(buf.c_str(), (char**) &end);
if (end == buf && rvalue == 0.0) {
// strtod() returned an error
realValue.SetErrorValue();
could_convert = false;
}
switch (toupper( *end )) {
case 'B': nf = Value::B_FACTOR; break;
case 'K': nf = Value::K_FACTOR; break;
case 'M': nf = Value::M_FACTOR; break;
case 'G': nf = Value::G_FACTOR; break;
case 'T': nf = Value::T_FACTOR; break;
case '\0': nf = Value::NO_FACTOR; break;
default:
realValue.SetErrorValue();
could_convert = false;
break;
}
could_convert = true;
realValue.SetRealValue(rvalue*Value::ScaleFactor[nf]);
break;
case Value::BOOLEAN_VALUE:
value.IsBooleanValue(bvalue);
realValue.SetRealValue(bvalue ? 1.0 : 0.0);
could_convert = true;
break;
case Value::INTEGER_VALUE:
value.IsIntegerValue(ivalue);
realValue.SetRealValue((double)ivalue);
could_convert = true;
break;
case Value::REAL_VALUE:
realValue.CopyFrom(value);
could_convert = true;
break;
case Value::ABSOLUTE_TIME_VALUE:
value.IsAbsoluteTimeValue(atvalue);
realValue.SetRealValue(atvalue.secs);
could_convert = true;
break;
case Value::RELATIVE_TIME_VALUE:
value.IsRelativeTimeValue(rtvalue);
realValue.SetRealValue(rtvalue);
could_convert = true;
break;
default:
CLASSAD_EXCEPT( "Should not reach here" );
}
return could_convert;
}
bool convertValueToIntegerValue(const Value value, Value &integerValue)
{
bool could_convert;
string buf;
char *end;
int ivalue;
time_t rtvalue;
abstime_t atvalue;
bool bvalue;
double rvalue;
Value::NumberFactor nf;
switch(value.GetType()) {
case Value::UNDEFINED_VALUE:
integerValue.SetUndefinedValue();
could_convert = false;
break;
case Value::ERROR_VALUE:
case Value::CLASSAD_VALUE:
case Value::LIST_VALUE:
integerValue.SetErrorValue();
could_convert = false;
break;
case Value::STRING_VALUE:
value.IsStringValue( buf );
ivalue = (int) strtod( buf.c_str( ), (char**) &end);
if( end == buf && ivalue == 0 ) {
// strtol() returned an error
integerValue.SetErrorValue( );
return( true );
}
switch( toupper( *end ) ) {
case 'B': nf = Value::B_FACTOR; break;
case 'K': nf = Value::K_FACTOR; break;
case 'M': nf = Value::M_FACTOR; break;
case 'G': nf = Value::G_FACTOR; break;
case 'T': nf = Value::T_FACTOR; break;
case '\0': nf = Value::NO_FACTOR; break;
default:
integerValue.SetErrorValue( );
return( true );
}
integerValue.SetIntegerValue((int) (ivalue*Value::ScaleFactor[nf]));
break;
case Value::BOOLEAN_VALUE:
value.IsBooleanValue(bvalue);
integerValue.SetIntegerValue(bvalue ? 1 : 0);
could_convert = true;
break;
case Value::INTEGER_VALUE:
integerValue.CopyFrom(value);
could_convert = true;
break;
case Value::REAL_VALUE:
value.IsRealValue(rvalue);
integerValue.SetIntegerValue((int) rvalue);
could_convert = true;
break;
case Value::ABSOLUTE_TIME_VALUE:
value.IsAbsoluteTimeValue(atvalue);
integerValue.SetIntegerValue(atvalue.secs);
could_convert = true;
break;
case Value::RELATIVE_TIME_VALUE:
value.IsRelativeTimeValue(rtvalue);
integerValue.SetIntegerValue((int) rtvalue);
could_convert = true;
break;
default:
CLASSAD_EXCEPT( "Should not reach here" );
}
return could_convert;
}
bool convertValueToStringValue(const Value value, Value &stringValue)
{
bool could_convert;
time_t rtvalue;
abstime_t atvalue;
string string_representation;
ClassAdUnParser unparser;
switch(value.GetType()) {
case Value::UNDEFINED_VALUE:
stringValue.SetUndefinedValue();
could_convert = false;
break;
case Value::ERROR_VALUE:
stringValue.SetErrorValue();
could_convert = false;
break;
case Value::STRING_VALUE:
stringValue.CopyFrom(value);
could_convert = true;
break;
case Value::CLASSAD_VALUE:
case Value::LIST_VALUE:
case Value::BOOLEAN_VALUE:
case Value::INTEGER_VALUE:
case Value::REAL_VALUE:
unparser.Unparse(string_representation, value);
stringValue.SetStringValue(string_representation);
break;
case Value::ABSOLUTE_TIME_VALUE:
value.IsAbsoluteTimeValue(atvalue);
absTimeToString(atvalue, string_representation);
stringValue.SetStringValue(string_representation);
could_convert = true;
break;
case Value::RELATIVE_TIME_VALUE:
value.IsRelativeTimeValue(rtvalue);
relTimeToString(rtvalue, string_representation);
stringValue.SetStringValue(string_representation);
could_convert = true;
break;
default:
CLASSAD_EXCEPT( "Should not reach here" );
}
return could_convert;
}
END_NAMESPACE // classad
<commit_msg>Eliminated segmentation fault. Oops.<commit_after>/*********************************************************************
*
* Condor ClassAd library
* Copyright (C) 1990-2003, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI and Rajesh Raman.
*
* This source code is covered by the Condor Public License, which can
* be found in the accompanying LICENSE file, or online at
* www.condorproject.org.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* AND THE UNIVERSITY OF WISCONSIN-MADISON "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, OF SATISFACTORY QUALITY, AND FITNESS
* FOR A PARTICULAR PURPOSE OR USE ARE DISCLAIMED. THE COPYRIGHT
* HOLDERS AND CONTRIBUTORS AND THE UNIVERSITY OF WISCONSIN-MADISON
* MAKE NO MAKE NO REPRESENTATION THAT THE SOFTWARE, MODIFICATIONS,
* ENHANCEMENTS OR DERIVATIVE WORKS THEREOF, WILL NOT INFRINGE ANY
* PATENT, COPYRIGHT, TRADEMARK, TRADE SECRET OR OTHER PROPRIETARY
* RIGHT.
*
*********************************************************************/
#include "common.h"
#include "operators.h"
#include "sink.h"
#include "value.h"
#include <iostream>
using namespace std;
BEGIN_NAMESPACE( classad )
const double Value::ScaleFactor[] = {
1.0, // none
1.0, // B
1024.0, // Kilo
1024.0*1024.0, // Mega
1024.0*1024.0*1024.0, // Giga
1024.0*1024.0*1024.0*1024.0 // Terra
};
Value::
Value( )
{
valueType = UNDEFINED_VALUE;
booleanValue = false;
integerValue = 0;
realValue = 0.0;
listValue = NULL;
classadValue = NULL;
relTimeValueSecs = 0;
absTimeValueSecs.secs = 0;
absTimeValueSecs.offset = 0;
}
Value::
Value(const Value &value)
{
CopyFrom(value);
return;
}
Value::
~Value()
{
}
Value& Value::
operator=(const Value &value)
{
if (this != &value) {
CopyFrom(value);
}
return *this;
}
void Value::
Clear()
{
switch( valueType ) {
case LIST_VALUE:
// list values live in the evaluation environment, so they must
// never be explicitly destroyed
listValue = NULL;
break;
case CLASSAD_VALUE:
// classad values live in the evaluation environment, so they must
// never be explicitly destroyed
classadValue = NULL;
break;
case STRING_VALUE:
strValue = "";
break;
default:
valueType = UNDEFINED_VALUE;
}
valueType = UNDEFINED_VALUE;
}
bool Value::
IsNumber (int &i) const
{
switch (valueType) {
case INTEGER_VALUE:
i = integerValue;
return true;
case REAL_VALUE:
i = (int) realValue; // truncation
return true;
default:
return false;
}
}
bool Value::
IsNumber (double &r) const
{
switch (valueType) {
case INTEGER_VALUE:
r = (double) integerValue;
return true;
case REAL_VALUE:
r = realValue;
return true;
default:
return false;
}
}
void Value::
CopyFrom( const Value &val )
{
valueType = val.valueType;
switch (val.valueType) {
case STRING_VALUE:
strValue = val.strValue;
return;
case BOOLEAN_VALUE:
booleanValue = val.booleanValue;
return;
case INTEGER_VALUE:
integerValue = val.integerValue;
return;
case REAL_VALUE:
realValue = val.realValue;
return;
case UNDEFINED_VALUE:
case ERROR_VALUE:
return;
case LIST_VALUE:
listValue = val.listValue;
return;
case CLASSAD_VALUE:
classadValue = val.classadValue;
return;
case ABSOLUTE_TIME_VALUE:
absTimeValueSecs = val.absTimeValueSecs;
return;
case RELATIVE_TIME_VALUE:
relTimeValueSecs = val.relTimeValueSecs;
return;
default:
SetUndefinedValue ();
}
}
void Value::
SetRealValue (double r)
{
valueType=REAL_VALUE;
realValue = r;
}
void Value::
SetBooleanValue( bool b )
{
valueType = BOOLEAN_VALUE;
booleanValue = b;
}
void Value::
SetIntegerValue (int i)
{
valueType=INTEGER_VALUE;
integerValue = i;
}
void Value::
SetUndefinedValue (void)
{
valueType=UNDEFINED_VALUE;
}
void Value::
SetErrorValue (void)
{
valueType=ERROR_VALUE;
}
void Value::
SetStringValue( const string &s )
{
valueType = STRING_VALUE;
strValue = s;
}
void Value::
SetStringValue( const char *s )
{
valueType = STRING_VALUE;
strValue = s;
}
void Value::
SetListValue( ExprList *l)
{
valueType = LIST_VALUE;
listValue = l;
}
void Value::
SetClassAdValue( ClassAd *ad )
{
valueType = CLASSAD_VALUE;
classadValue = ad;
}
void Value::
SetRelativeTimeValue( time_t rsecs )
{
valueType = RELATIVE_TIME_VALUE;
relTimeValueSecs = (double) rsecs;
}
void Value::
SetRelativeTimeValue( double rsecs )
{
valueType = RELATIVE_TIME_VALUE;
relTimeValueSecs = rsecs;
}
void Value::
SetAbsoluteTimeValue( abstime_t asecs )
{
valueType = ABSOLUTE_TIME_VALUE;
absTimeValueSecs = asecs;
}
bool Value::
SameAs(const Value &otherValue) const
{
bool is_same;
if (valueType != otherValue.valueType) {
is_same = false;
} else {
switch (valueType) {
case Value::NULL_VALUE:
case Value::ERROR_VALUE:
case Value::UNDEFINED_VALUE:
is_same = true;
break;
case Value::BOOLEAN_VALUE:
is_same = (booleanValue == otherValue.booleanValue);
break;
case Value::INTEGER_VALUE:
is_same = (integerValue == otherValue.integerValue);
break;
case Value::REAL_VALUE:
is_same = (realValue == otherValue.realValue);
break;
case Value::LIST_VALUE:
// To do!
break;
case Value::CLASSAD_VALUE:
// To do!
break;
case Value::RELATIVE_TIME_VALUE:
is_same = (relTimeValueSecs == otherValue.relTimeValueSecs);
break;
case Value::ABSOLUTE_TIME_VALUE:
is_same = ( absTimeValueSecs.secs == otherValue.absTimeValueSecs.secs
&& absTimeValueSecs.offset == otherValue.absTimeValueSecs.offset);
break;
case Value::STRING_VALUE:
is_same = (strValue == otherValue.strValue);
break;
}
}
return is_same;
}
bool operator==(const Value &value1, const Value &value2)
{
return value1.SameAs(value2);
}
ostream& operator<<(ostream &stream, Value &value)
{
ClassAdUnParser unparser;
string unparsed_text;
switch (value.valueType) {
case Value::NULL_VALUE:
stream << "(null)";
break;
case Value::ERROR_VALUE:
stream << "error";
break;
case Value::UNDEFINED_VALUE:
stream << "undefined";
break;
case Value::BOOLEAN_VALUE:
if (value.booleanValue) {
stream << "true";
} else {
stream << "false";
}
break;
case Value::INTEGER_VALUE:
stream << value.integerValue;
break;
case Value::REAL_VALUE:
stream << value.realValue;
break;
case Value::LIST_VALUE:
case Value::CLASSAD_VALUE:
case Value::RELATIVE_TIME_VALUE:
case Value::ABSOLUTE_TIME_VALUE: {
unparser.Unparse(unparsed_text, value);
stream << unparsed_text;
break;
}
case Value::STRING_VALUE:
stream << value.strValue;
break;
}
return stream;
}
bool convertValueToRealValue(const Value value, Value &realValue)
{
bool could_convert;
string buf;
char *end;
int ivalue;
time_t rtvalue;
abstime_t atvalue;
bool bvalue;
double rvalue;
Value::NumberFactor nf;
switch(value.GetType()) {
case Value::UNDEFINED_VALUE:
realValue.SetUndefinedValue();
could_convert = false;
break;
case Value::ERROR_VALUE:
case Value::CLASSAD_VALUE:
case Value::LIST_VALUE:
realValue.SetErrorValue();
could_convert = false;
break;
case Value::STRING_VALUE:
could_convert = true;
value.IsStringValue(buf);
rvalue = strtod(buf.c_str(), (char**) &end);
if (end == buf && rvalue == 0.0) {
// strtod() returned an error
realValue.SetErrorValue();
could_convert = false;
}
switch (toupper( *end )) {
case 'B': nf = Value::B_FACTOR; break;
case 'K': nf = Value::K_FACTOR; break;
case 'M': nf = Value::M_FACTOR; break;
case 'G': nf = Value::G_FACTOR; break;
case 'T': nf = Value::T_FACTOR; break;
case '\0': nf = Value::NO_FACTOR; break;
default:
realValue.SetErrorValue();
could_convert = false;
break;
}
if (could_convert) {
realValue.SetRealValue(rvalue*Value::ScaleFactor[nf]);
}
break;
case Value::BOOLEAN_VALUE:
value.IsBooleanValue(bvalue);
realValue.SetRealValue(bvalue ? 1.0 : 0.0);
could_convert = true;
break;
case Value::INTEGER_VALUE:
value.IsIntegerValue(ivalue);
realValue.SetRealValue((double)ivalue);
could_convert = true;
break;
case Value::REAL_VALUE:
realValue.CopyFrom(value);
could_convert = true;
break;
case Value::ABSOLUTE_TIME_VALUE:
value.IsAbsoluteTimeValue(atvalue);
realValue.SetRealValue(atvalue.secs);
could_convert = true;
break;
case Value::RELATIVE_TIME_VALUE:
value.IsRelativeTimeValue(rtvalue);
realValue.SetRealValue(rtvalue);
could_convert = true;
break;
default:
CLASSAD_EXCEPT( "Should not reach here" );
}
return could_convert;
}
bool convertValueToIntegerValue(const Value value, Value &integerValue)
{
bool could_convert;
string buf;
char *end;
int ivalue;
time_t rtvalue;
abstime_t atvalue;
bool bvalue;
double rvalue;
Value::NumberFactor nf;
switch(value.GetType()) {
case Value::UNDEFINED_VALUE:
integerValue.SetUndefinedValue();
could_convert = false;
break;
case Value::ERROR_VALUE:
case Value::CLASSAD_VALUE:
case Value::LIST_VALUE:
integerValue.SetErrorValue();
could_convert = false;
break;
case Value::STRING_VALUE:
value.IsStringValue( buf );
ivalue = (int) strtod( buf.c_str( ), (char**) &end);
if( end == buf && ivalue == 0 ) {
// strtol() returned an error
integerValue.SetErrorValue( );
return( true );
}
switch( toupper( *end ) ) {
case 'B': nf = Value::B_FACTOR; break;
case 'K': nf = Value::K_FACTOR; break;
case 'M': nf = Value::M_FACTOR; break;
case 'G': nf = Value::G_FACTOR; break;
case 'T': nf = Value::T_FACTOR; break;
case '\0': nf = Value::NO_FACTOR; break;
default:
integerValue.SetErrorValue( );
return( true );
}
integerValue.SetIntegerValue((int) (ivalue*Value::ScaleFactor[nf]));
break;
case Value::BOOLEAN_VALUE:
value.IsBooleanValue(bvalue);
integerValue.SetIntegerValue(bvalue ? 1 : 0);
could_convert = true;
break;
case Value::INTEGER_VALUE:
integerValue.CopyFrom(value);
could_convert = true;
break;
case Value::REAL_VALUE:
value.IsRealValue(rvalue);
integerValue.SetIntegerValue((int) rvalue);
could_convert = true;
break;
case Value::ABSOLUTE_TIME_VALUE:
value.IsAbsoluteTimeValue(atvalue);
integerValue.SetIntegerValue(atvalue.secs);
could_convert = true;
break;
case Value::RELATIVE_TIME_VALUE:
value.IsRelativeTimeValue(rtvalue);
integerValue.SetIntegerValue((int) rtvalue);
could_convert = true;
break;
default:
CLASSAD_EXCEPT( "Should not reach here" );
}
return could_convert;
}
bool convertValueToStringValue(const Value value, Value &stringValue)
{
bool could_convert;
time_t rtvalue;
abstime_t atvalue;
string string_representation;
ClassAdUnParser unparser;
switch(value.GetType()) {
case Value::UNDEFINED_VALUE:
stringValue.SetUndefinedValue();
could_convert = false;
break;
case Value::ERROR_VALUE:
stringValue.SetErrorValue();
could_convert = false;
break;
case Value::STRING_VALUE:
stringValue.CopyFrom(value);
could_convert = true;
break;
case Value::CLASSAD_VALUE:
case Value::LIST_VALUE:
case Value::BOOLEAN_VALUE:
case Value::INTEGER_VALUE:
case Value::REAL_VALUE:
unparser.Unparse(string_representation, value);
stringValue.SetStringValue(string_representation);
break;
case Value::ABSOLUTE_TIME_VALUE:
value.IsAbsoluteTimeValue(atvalue);
absTimeToString(atvalue, string_representation);
stringValue.SetStringValue(string_representation);
could_convert = true;
break;
case Value::RELATIVE_TIME_VALUE:
value.IsRelativeTimeValue(rtvalue);
relTimeToString(rtvalue, string_representation);
stringValue.SetStringValue(string_representation);
could_convert = true;
break;
default:
CLASSAD_EXCEPT( "Should not reach here" );
}
return could_convert;
}
END_NAMESPACE // classad
<|endoftext|> |
<commit_before>
#include "GasMeter.h"
#include <llvm/IR/GlobalVariable.h>
#include <llvm/IR/Function.h>
#include <libevmface/Instruction.h>
#include <libevm/FeeStructure.h>
#include "Type.h"
#include "Utils.h"
#include "Ext.h"
namespace evmcc
{
using namespace dev::eth; // We should move all the JIT code into dev::eth namespace
namespace // Helper functions
{
uint64_t getStepCost(dev::eth::Instruction inst) // TODO: Add this function to FeeSructure
{
switch (inst)
{
case Instruction::STOP:
case Instruction::SUICIDE:
return 0;
case Instruction::SSTORE:
return static_cast<uint64_t>(c_sstoreGas);
case Instruction::SLOAD:
return static_cast<uint64_t>(c_sloadGas);
case Instruction::SHA3:
return static_cast<uint64_t>(c_sha3Gas);
case Instruction::BALANCE:
return static_cast<uint64_t>(c_sha3Gas);
case Instruction::CALL:
case Instruction::CALLCODE:
return static_cast<uint64_t>(c_callGas);
case Instruction::CREATE:
return static_cast<uint64_t>(c_createGas);
default: // Assumes instruction code is valid
return static_cast<uint64_t>(c_stepGas);
}
}
bool isCostBlockEnd(Instruction _inst)
{
// Basic block terminators like STOP are not needed on the list
// as cost will be commited at the end of basic block
// CALL & CALLCODE are commited manually
switch (_inst)
{
case Instruction::CALLDATACOPY:
case Instruction::CODECOPY:
case Instruction::MLOAD:
case Instruction::MSTORE:
case Instruction::MSTORE8:
case Instruction::SSTORE:
case Instruction::GAS:
case Instruction::CREATE:
return true;
default:
return false;
}
}
}
GasMeter::GasMeter(llvm::IRBuilder<>& _builder, llvm::Module* _module):
m_builder(_builder)
{
m_gas = new llvm::GlobalVariable(*_module, Type::i256, false, llvm::GlobalVariable::ExternalLinkage, nullptr, "gas");
m_gas->setUnnamedAddr(true); // Address is not important
m_gasCheckFunc = llvm::Function::Create(llvm::FunctionType::get(Type::Void, Type::i256, false), llvm::Function::PrivateLinkage, "gas.check", _module);
InsertPointGuard guard(m_builder);
m_builder.SetInsertPoint(llvm::BasicBlock::Create(_builder.getContext(), {}, m_gasCheckFunc));
llvm::Value* cost = m_gasCheckFunc->arg_begin();
llvm::Value* gas = m_builder.CreateLoad(m_gas);
gas = m_builder.CreateSub(gas, cost);
m_builder.CreateStore(gas, m_gas);
m_builder.CreateRetVoid();
}
void GasMeter::count(Instruction _inst)
{
if (!m_checkCall)
{
// Create gas check call with mocked block cost at begining of current cost-block
m_checkCall = m_builder.CreateCall(m_gasCheckFunc, llvm::UndefValue::get(Type::i256));
}
if (_inst != Instruction::SSTORE) // Handle cost of SSTORE separately in countSStore()
m_blockCost += getStepCost(_inst);
if (isCostBlockEnd(_inst))
commitCostBlock();
}
void GasMeter::countSStore(Ext& _ext, llvm::Value* _index, llvm::Value* _newValue)
{
assert(!m_checkCall); // Everything should've been commited before
static const auto sstoreCost = static_cast<uint64_t>(c_sstoreGas);
// [ADD] if oldValue == 0 and newValue != 0 => 2*cost
// [DEL] if oldValue != 0 and newValue == 0 => 0
auto oldValue = _ext.store(_index);
auto oldValueIsZero = m_builder.CreateICmpEQ(oldValue, Constant::get(0), "oldValueIsZero");
auto newValueIsZero = m_builder.CreateICmpEQ(_newValue, Constant::get(0), "newValueIsZero");
auto oldValueIsntZero = m_builder.CreateICmpNE(oldValue, Constant::get(0), "oldValueIsntZero");
auto newValueIsntZero = m_builder.CreateICmpNE(_newValue, Constant::get(0), "newValueIsntZero");
auto isAdd = m_builder.CreateAnd(oldValueIsZero, newValueIsntZero, "isAdd");
auto isDel = m_builder.CreateAnd(oldValueIsntZero, newValueIsZero, "isDel");
auto cost = m_builder.CreateSelect(isAdd, Constant::get(2 * sstoreCost), Constant::get(sstoreCost), "cost");
cost = m_builder.CreateSelect(isDel, Constant::get(0), cost, "cost");
m_builder.CreateCall(m_gasCheckFunc, cost);
}
void GasMeter::giveBack(llvm::Value* _gas)
{
llvm::Value* gasCounter = m_builder.CreateLoad(m_gas, "gas");
gasCounter = m_builder.CreateAdd(gasCounter, _gas);
m_builder.CreateStore(gasCounter, m_gas);
}
void GasMeter::commitCostBlock(llvm::Value* _additionalCost)
{
assert(!_additionalCost || m_checkCall); // _additionalCost => m_checkCall; Must be inside cost-block
// If any uncommited block
if (m_checkCall)
{
if (m_blockCost == 0 && !_additionalCost) // Do not check 0
{
m_checkCall->eraseFromParent(); // Remove the gas check call
return;
}
llvm::Value* cost = Constant::get(m_blockCost);
if (_additionalCost)
cost = m_builder.CreateAdd(cost, _additionalCost);
m_checkCall->setArgOperand(0, cost); // Update block cost in gas check call
m_checkCall = nullptr; // End cost-block
m_blockCost = 0;
}
assert(m_blockCost == 0);
}
void GasMeter::checkMemory(llvm::Value* _additionalMemoryInWords, llvm::IRBuilder<>& _builder)
{
// Memory uses other builder, but that can be changes later
auto cost = _builder.CreateMul(_additionalMemoryInWords, Constant::get(static_cast<uint64_t>(c_memoryGas)), "memcost");
_builder.CreateCall(m_gasCheckFunc, cost);
}
llvm::Value* GasMeter::getGas()
{
m_builder.CreateLoad(m_gas, "gas");
}
}
<commit_msg>Change a bit the implementation of GAS instruction (fix)<commit_after>
#include "GasMeter.h"
#include <llvm/IR/GlobalVariable.h>
#include <llvm/IR/Function.h>
#include <libevmface/Instruction.h>
#include <libevm/FeeStructure.h>
#include "Type.h"
#include "Utils.h"
#include "Ext.h"
namespace evmcc
{
using namespace dev::eth; // We should move all the JIT code into dev::eth namespace
namespace // Helper functions
{
uint64_t getStepCost(dev::eth::Instruction inst) // TODO: Add this function to FeeSructure
{
switch (inst)
{
case Instruction::STOP:
case Instruction::SUICIDE:
return 0;
case Instruction::SSTORE:
return static_cast<uint64_t>(c_sstoreGas);
case Instruction::SLOAD:
return static_cast<uint64_t>(c_sloadGas);
case Instruction::SHA3:
return static_cast<uint64_t>(c_sha3Gas);
case Instruction::BALANCE:
return static_cast<uint64_t>(c_sha3Gas);
case Instruction::CALL:
case Instruction::CALLCODE:
return static_cast<uint64_t>(c_callGas);
case Instruction::CREATE:
return static_cast<uint64_t>(c_createGas);
default: // Assumes instruction code is valid
return static_cast<uint64_t>(c_stepGas);
}
}
bool isCostBlockEnd(Instruction _inst)
{
// Basic block terminators like STOP are not needed on the list
// as cost will be commited at the end of basic block
// CALL & CALLCODE are commited manually
switch (_inst)
{
case Instruction::CALLDATACOPY:
case Instruction::CODECOPY:
case Instruction::MLOAD:
case Instruction::MSTORE:
case Instruction::MSTORE8:
case Instruction::SSTORE:
case Instruction::GAS:
case Instruction::CREATE:
return true;
default:
return false;
}
}
}
GasMeter::GasMeter(llvm::IRBuilder<>& _builder, llvm::Module* _module):
m_builder(_builder)
{
m_gas = new llvm::GlobalVariable(*_module, Type::i256, false, llvm::GlobalVariable::ExternalLinkage, nullptr, "gas");
m_gas->setUnnamedAddr(true); // Address is not important
m_gasCheckFunc = llvm::Function::Create(llvm::FunctionType::get(Type::Void, Type::i256, false), llvm::Function::PrivateLinkage, "gas.check", _module);
InsertPointGuard guard(m_builder);
m_builder.SetInsertPoint(llvm::BasicBlock::Create(_builder.getContext(), {}, m_gasCheckFunc));
llvm::Value* cost = m_gasCheckFunc->arg_begin();
llvm::Value* gas = m_builder.CreateLoad(m_gas);
gas = m_builder.CreateSub(gas, cost);
m_builder.CreateStore(gas, m_gas);
m_builder.CreateRetVoid();
}
void GasMeter::count(Instruction _inst)
{
if (!m_checkCall)
{
// Create gas check call with mocked block cost at begining of current cost-block
m_checkCall = m_builder.CreateCall(m_gasCheckFunc, llvm::UndefValue::get(Type::i256));
}
if (_inst != Instruction::SSTORE) // Handle cost of SSTORE separately in countSStore()
m_blockCost += getStepCost(_inst);
if (isCostBlockEnd(_inst))
commitCostBlock();
}
void GasMeter::countSStore(Ext& _ext, llvm::Value* _index, llvm::Value* _newValue)
{
assert(!m_checkCall); // Everything should've been commited before
static const auto sstoreCost = static_cast<uint64_t>(c_sstoreGas);
// [ADD] if oldValue == 0 and newValue != 0 => 2*cost
// [DEL] if oldValue != 0 and newValue == 0 => 0
auto oldValue = _ext.store(_index);
auto oldValueIsZero = m_builder.CreateICmpEQ(oldValue, Constant::get(0), "oldValueIsZero");
auto newValueIsZero = m_builder.CreateICmpEQ(_newValue, Constant::get(0), "newValueIsZero");
auto oldValueIsntZero = m_builder.CreateICmpNE(oldValue, Constant::get(0), "oldValueIsntZero");
auto newValueIsntZero = m_builder.CreateICmpNE(_newValue, Constant::get(0), "newValueIsntZero");
auto isAdd = m_builder.CreateAnd(oldValueIsZero, newValueIsntZero, "isAdd");
auto isDel = m_builder.CreateAnd(oldValueIsntZero, newValueIsZero, "isDel");
auto cost = m_builder.CreateSelect(isAdd, Constant::get(2 * sstoreCost), Constant::get(sstoreCost), "cost");
cost = m_builder.CreateSelect(isDel, Constant::get(0), cost, "cost");
m_builder.CreateCall(m_gasCheckFunc, cost);
}
void GasMeter::giveBack(llvm::Value* _gas)
{
llvm::Value* gasCounter = m_builder.CreateLoad(m_gas, "gas");
gasCounter = m_builder.CreateAdd(gasCounter, _gas);
m_builder.CreateStore(gasCounter, m_gas);
}
void GasMeter::commitCostBlock(llvm::Value* _additionalCost)
{
assert(!_additionalCost || m_checkCall); // _additionalCost => m_checkCall; Must be inside cost-block
// If any uncommited block
if (m_checkCall)
{
if (m_blockCost == 0 && !_additionalCost) // Do not check 0
{
m_checkCall->eraseFromParent(); // Remove the gas check call
return;
}
llvm::Value* cost = Constant::get(m_blockCost);
if (_additionalCost)
cost = m_builder.CreateAdd(cost, _additionalCost);
m_checkCall->setArgOperand(0, cost); // Update block cost in gas check call
m_checkCall = nullptr; // End cost-block
m_blockCost = 0;
}
assert(m_blockCost == 0);
}
void GasMeter::checkMemory(llvm::Value* _additionalMemoryInWords, llvm::IRBuilder<>& _builder)
{
// Memory uses other builder, but that can be changes later
auto cost = _builder.CreateMul(_additionalMemoryInWords, Constant::get(static_cast<uint64_t>(c_memoryGas)), "memcost");
_builder.CreateCall(m_gasCheckFunc, cost);
}
llvm::Value* GasMeter::getGas()
{
return m_builder.CreateLoad(m_gas, "gas");
}
}
<|endoftext|> |
<commit_before>#include "mediamodel.h"
#include "mediascanner.h"
#include "dbreader.h"
#include "backend.h"
#define DEBUG if (1) qDebug() << __PRETTY_FUNCTION__
MediaModel::MediaModel(QObject *parent)
: QAbstractItemModel(parent), m_depth(0), m_loading(false), m_loaded(false), m_reader(0), m_readerThread(0)
{
}
MediaModel::~MediaModel()
{
}
QString MediaModel::mediaType() const
{
return m_mediaType;
}
void MediaModel::setMediaType(const QString &type)
{
m_mediaType = type;
emit mediaTypeChanged();
beginResetModel();
initialize();
endResetModel();
QSqlDriver *driver = Backend::instance()->mediaDatabase().driver();
QSqlRecord record = driver->record(m_mediaType);
if (record.isEmpty())
qWarning() << "Table " << type << " is not valid it seems";
QHash<int, QByteArray> hash = roleNames();
for (int i = 0; i < record.count(); i++) {
hash.insert(Qt::UserRole + i, record.fieldName(i).toUtf8());
}
setRoleNames(hash);
}
void MediaModel::addSearchPath(const QString &path, const QString &name)
{
QMetaObject::invokeMethod(MediaScanner::instance(), "addSearchPath", Qt::QueuedConnection, Q_ARG(QString, "picture"), Q_ARG(QString, path), Q_ARG(QString, name));
}
void MediaModel::removeSearchPath(int index)
{
Q_UNUSED(index);
}
QString MediaModel::structure() const
{
return m_structure;
}
void MediaModel::setStructure(const QString &str)
{
m_structure = str;
m_depth = 0; // reset depth
emit structureChanged();
beginResetModel();
initialize();
endResetModel();
}
int MediaModel::depth() const
{
return m_depth;
}
void MediaModel::enter(int index)
{
Q_UNUSED(index);
if (m_cursor.count() + 1 == m_structure.split("|").count()) {
DEBUG << "Refusing to enter leaf node";
return;
}
if (index == 0 && !m_cursor.isEmpty()) {
back();
return;
}
DEBUG << "Entering " << index;
m_cursor.append(m_data[index]);
beginResetModel();
initialize();
endResetModel();
// fetchMore(QModelIndex());
}
void MediaModel::back()
{
beginResetModel();
m_cursor.removeLast();
initialize();
endResetModel();
}
QVariant MediaModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
const QHash<QString, QVariant> &data = m_data[index.row()];
const QHash<int, QByteArray> hash = roleNames();
return data.value(hash.value(role));
}
QModelIndex MediaModel::index(int row, int col, const QModelIndex &parent) const
{
if (parent.isValid())
return QModelIndex();
return createIndex(row, col);
}
QModelIndex MediaModel::parent(const QModelIndex &idx) const
{
Q_UNUSED(idx);
return QModelIndex();
}
int MediaModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;
return m_data.count();
}
int MediaModel::columnCount(const QModelIndex &idx) const
{
Q_UNUSED(idx);
return 1;
}
bool MediaModel::hasChildren(const QModelIndex &parent) const
{
return !parent.isValid();
}
bool MediaModel::canFetchMore(const QModelIndex &parent) const
{
if (parent.isValid() || m_mediaType.isEmpty() || m_structure.isEmpty())
return false;
return !m_loading && !m_loaded;
}
void MediaModel::fetchMore(const QModelIndex &parent)
{
if (!canFetchMore(parent))
return;
initialize();
QSqlQuery q = query();
DEBUG << q.lastQuery();
QMetaObject::invokeMethod(m_reader, "execute", Qt::QueuedConnection, Q_ARG(QSqlQuery, q));
}
void MediaModel::initialize()
{
m_data.clear();
DbReader *newReader = new DbReader;
if (m_reader) {
disconnect(m_reader, 0, this, 0);
m_reader->stop();
m_reader->deleteLater();
}
m_reader = newReader;
if (!m_readerThread) {
m_readerThread = new QThread(this);
m_readerThread->start();
}
m_reader->moveToThread(m_readerThread);
QMetaObject::invokeMethod(m_reader, "initialize", Q_ARG(QSqlDatabase, Backend::instance()->mediaDatabase()));
connect(m_reader, SIGNAL(dataReady(DbReader *, QList<QSqlRecord>, void *)),
this, SLOT(handleDataReady(DbReader *, QList<QSqlRecord>, void *)));
m_loading = m_loaded = false;
}
void MediaModel::handleDataReady(DbReader *reader, const QList<QSqlRecord> &records, void *node)
{
Q_ASSERT(reader == m_reader);
Q_UNUSED(reader);
Q_UNUSED(node);
DEBUG << "Received response from db of size " << records.size();
if (!m_cursor.isEmpty()) {
beginInsertRows(QModelIndex(), 0, records.count());
QHash<QString, QVariant> data;
data.insert("display", tr(".."));
m_data.append(data);
} else {
beginInsertRows(QModelIndex(), 0, records.count() - 1);
}
for (int i = 0; i < records.count(); i++) {
QHash<QString, QVariant> data;
for (int j = 0; j < records[i].count(); j++) {
data.insert(records[i].fieldName(j), records[i].value(j));
}
QStringList cols = m_structure.split("|").value(m_cursor.count()).split(",");
QStringList displayString;
for (int j = 0; j < cols.count(); j++) {
displayString << records[i].value(cols[j]).toString();
}
data.insert("display", displayString.join(", "));
m_data.append(data);
}
m_loading = false;
m_loaded = true;
endInsertRows();
}
void MediaModel::handleDatabaseUpdated(const QList<QSqlRecord> &records)
{
Q_UNUSED(records);
// not implemented yet
}
// ## BIG FAT FIXME: Fix the string escaping to prevent sql injection!
QSqlQuery MediaModel::query()
{
QString q;
QStringList parts = m_structure.split("|");
QString curPart = parts[m_cursor.count()];
QSqlQuery query(Backend::instance()->mediaDatabase());
query.setForwardOnly(true);
if (parts.count() == 1) {
query.prepare(QString("SELECT * FROM %1").arg(m_mediaType));
return query;
}
QStringList where;
for (int i = 0; i < m_cursor.count(); i++) {
where.append(parts[i] + " = '" + m_cursor[i].value(parts[i]).toString() + "'");
}
QString conditions = where.join(" AND ");
if (conditions.isEmpty()) {
query.prepare(QString("SELECT * FROM %1 GROUP BY %2").arg(m_mediaType).arg(curPart));
} else {
query.prepare(QString("SELECT DISTINCT %1 FROM %2 WHERE %3").arg(curPart).arg(m_mediaType).arg(conditions));
}
return query;
}
<commit_msg>subpart hack<commit_after>#include "mediamodel.h"
#include "mediascanner.h"
#include "dbreader.h"
#include "backend.h"
#define DEBUG if (1) qDebug() << __PRETTY_FUNCTION__
MediaModel::MediaModel(QObject *parent)
: QAbstractItemModel(parent), m_depth(0), m_loading(false), m_loaded(false), m_reader(0), m_readerThread(0)
{
}
MediaModel::~MediaModel()
{
}
QString MediaModel::mediaType() const
{
return m_mediaType;
}
void MediaModel::setMediaType(const QString &type)
{
m_mediaType = type;
emit mediaTypeChanged();
beginResetModel();
initialize();
endResetModel();
QSqlDriver *driver = Backend::instance()->mediaDatabase().driver();
QSqlRecord record = driver->record(m_mediaType);
if (record.isEmpty())
qWarning() << "Table " << type << " is not valid it seems";
QHash<int, QByteArray> hash = roleNames();
for (int i = 0; i < record.count(); i++) {
hash.insert(Qt::UserRole + i, record.fieldName(i).toUtf8());
}
setRoleNames(hash);
}
void MediaModel::addSearchPath(const QString &path, const QString &name)
{
QMetaObject::invokeMethod(MediaScanner::instance(), "addSearchPath", Qt::QueuedConnection, Q_ARG(QString, "picture"), Q_ARG(QString, path), Q_ARG(QString, name));
}
void MediaModel::removeSearchPath(int index)
{
Q_UNUSED(index);
}
QString MediaModel::structure() const
{
return m_structure;
}
void MediaModel::setStructure(const QString &str)
{
m_structure = str;
m_depth = 0; // reset depth
emit structureChanged();
beginResetModel();
initialize();
endResetModel();
}
int MediaModel::depth() const
{
return m_depth;
}
void MediaModel::enter(int index)
{
Q_UNUSED(index);
if (m_cursor.count() + 1 == m_structure.split("|").count()) {
DEBUG << "Refusing to enter leaf node";
return;
}
if (index == 0 && !m_cursor.isEmpty()) {
back();
return;
}
DEBUG << "Entering " << index;
m_cursor.append(m_data[index]);
beginResetModel();
initialize();
endResetModel();
// fetchMore(QModelIndex());
}
void MediaModel::back()
{
beginResetModel();
m_cursor.removeLast();
initialize();
endResetModel();
}
QVariant MediaModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
const QHash<QString, QVariant> &data = m_data[index.row()];
const QHash<int, QByteArray> hash = roleNames();
return data.value(hash.value(role));
}
QModelIndex MediaModel::index(int row, int col, const QModelIndex &parent) const
{
if (parent.isValid())
return QModelIndex();
return createIndex(row, col);
}
QModelIndex MediaModel::parent(const QModelIndex &idx) const
{
Q_UNUSED(idx);
return QModelIndex();
}
int MediaModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;
return m_data.count();
}
int MediaModel::columnCount(const QModelIndex &idx) const
{
Q_UNUSED(idx);
return 1;
}
bool MediaModel::hasChildren(const QModelIndex &parent) const
{
return !parent.isValid();
}
bool MediaModel::canFetchMore(const QModelIndex &parent) const
{
if (parent.isValid() || m_mediaType.isEmpty() || m_structure.isEmpty())
return false;
return !m_loading && !m_loaded;
}
void MediaModel::fetchMore(const QModelIndex &parent)
{
if (!canFetchMore(parent))
return;
initialize();
QSqlQuery q = query();
DEBUG << q.lastQuery();
QMetaObject::invokeMethod(m_reader, "execute", Qt::QueuedConnection, Q_ARG(QSqlQuery, q));
}
void MediaModel::initialize()
{
m_data.clear();
DbReader *newReader = new DbReader;
if (m_reader) {
disconnect(m_reader, 0, this, 0);
m_reader->stop();
m_reader->deleteLater();
}
m_reader = newReader;
if (!m_readerThread) {
m_readerThread = new QThread(this);
m_readerThread->start();
}
m_reader->moveToThread(m_readerThread);
QMetaObject::invokeMethod(m_reader, "initialize", Q_ARG(QSqlDatabase, Backend::instance()->mediaDatabase()));
connect(m_reader, SIGNAL(dataReady(DbReader *, QList<QSqlRecord>, void *)),
this, SLOT(handleDataReady(DbReader *, QList<QSqlRecord>, void *)));
m_loading = m_loaded = false;
}
void MediaModel::handleDataReady(DbReader *reader, const QList<QSqlRecord> &records, void *node)
{
Q_ASSERT(reader == m_reader);
Q_UNUSED(reader);
Q_UNUSED(node);
DEBUG << "Received response from db of size " << records.size();
if (!m_cursor.isEmpty()) {
beginInsertRows(QModelIndex(), 0, records.count());
QHash<QString, QVariant> data;
data.insert("display", tr(".."));
m_data.append(data);
} else {
beginInsertRows(QModelIndex(), 0, records.count() - 1);
}
for (int i = 0; i < records.count(); i++) {
QHash<QString, QVariant> data;
for (int j = 0; j < records[i].count(); j++) {
data.insert(records[i].fieldName(j), records[i].value(j));
}
QStringList cols = m_structure.split("|").value(m_cursor.count()).split(",");
QStringList displayString;
for (int j = 0; j < cols.count(); j++) {
displayString << records[i].value(cols[j]).toString();
}
data.insert("display", displayString.join(", "));
m_data.append(data);
}
m_loading = false;
m_loaded = true;
endInsertRows();
}
void MediaModel::handleDatabaseUpdated(const QList<QSqlRecord> &records)
{
Q_UNUSED(records);
// not implemented yet
}
// ## BIG FAT FIXME: Fix the string escaping to prevent sql injection!
QSqlQuery MediaModel::query()
{
QString q;
QStringList parts = m_structure.split("|");
QString curPart = parts[m_cursor.count()];
QSqlQuery query(Backend::instance()->mediaDatabase());
query.setForwardOnly(true);
if (parts.count() == 1) {
query.prepare(QString("SELECT * FROM %1").arg(m_mediaType));
return query;
}
QStringList where;
for (int i = 0; i < m_cursor.count(); i++) {
QString part = parts[i];
QStringList subParts = part.split(",");
for (int j = 0; j < subParts.count(); j++)
where.append(subParts[j] + " = '" + m_cursor[i].value(subParts[j]).toString() + "'");
}
QString conditions = where.join(" AND ");
if (conditions.isEmpty()) {
query.prepare(QString("SELECT * FROM %1 GROUP BY %2").arg(m_mediaType).arg(curPart));
} else {
query.prepare(QString("SELECT DISTINCT %1 FROM %2 WHERE %3").arg(curPart).arg(m_mediaType).arg(conditions));
}
return query;
}
<|endoftext|> |
<commit_before>/** \brief Tool for title, author and full-text extraction from XMl files corresponding to the Journal Publishing DTD.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2018 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <stdexcept>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include "FileUtil.h"
#include "FullTextImport.h"
#include "StringUtil.h"
#include "util.h"
#include "XMLParser.h"
namespace {
[[noreturn]] void Usage() {
std::cerr << "Usage: " << ::progname << " [--min-log-level=min_verbosity] [--normalise-only] xml_input full_text_output\n"
<< " When specifying --normalise-only we only require the input filename!\n\n";
std::exit(EXIT_FAILURE);
}
struct Metadata {
std::string title_;
std::set<std::string> authors_;
std::string publication_year_;
};
std::string ReadCharactersUntilNextClosingTag(XMLParser * const xml_parser, const std::string &closing_tag = "") {
XMLParser::XMLPart xml_part;
std::string extracted_data;
while (xml_parser->getNext(&xml_part)) {
if (xml_part.isClosingTag() and (closing_tag.empty() or xml_part.data_ == closing_tag))
break;
else if (xml_part.type_ == XMLParser::XMLPart::CHARACTERS)
extracted_data += xml_part.data_;
}
return extracted_data;
}
void ExtractAuthor(XMLParser * const xml_parser, std::set<std::string> * const article_authors) {
if (not xml_parser->skipTo(XMLParser::XMLPart::OPENING_TAG, "surname"))
return;
XMLParser::XMLPart xml_part;
if (not xml_parser->getNext(&xml_part) or xml_part.type_ != XMLParser::XMLPart::CHARACTERS)
return;
std::string surname(xml_part.data_);
while (xml_parser->getNext(&xml_part)) {
if (xml_part.type_ == XMLParser::XMLPart::CLOSING_TAG and xml_part.data_ == "contrib") {
article_authors->insert(surname);
return;
} else if (xml_part.type_ == XMLParser::XMLPart::OPENING_TAG and xml_part.data_ == "given-names") {
if (not xml_parser->getNext(&xml_part) or xml_part.type_ != XMLParser::XMLPart::CHARACTERS)
return;
article_authors->insert(xml_part.data_ + " " + surname);
return;
}
}
}
void ExtractMetadata(XMLParser * const xml_parser, Metadata * const metadata) {
XMLParser::XMLPart xml_part;
while (xml_parser->getNext(&xml_part)) {
if (xml_part.isOpeningTag("article-title"))
metadata->title_ = ReadCharactersUntilNextClosingTag(xml_parser);
else if (xml_part.isOpeningTag("contrib")) {
const auto contrib_type_and_value(xml_part.attributes_.find("contrib-type"));
if (contrib_type_and_value != xml_part.attributes_.cend() and contrib_type_and_value->second == "author")
ExtractAuthor(xml_parser, &metadata->authors_);
} else if (xml_part.isOpeningTag("pub-date")) {
if (xml_parser->skipTo(XMLParser::XMLPart::OPENING_TAG, "year"))
metadata->publication_year_ = ReadCharactersUntilNextClosingTag(xml_parser);
}
}
}
bool ExtractText(XMLParser * const xml_parser, const std::string &text_opening_tag, std::string * const text) {
xml_parser->rewind();
XMLParser::XMLPart xml_part;
if (not xml_parser->skipTo(XMLParser::XMLPart::OPENING_TAG, { text_opening_tag }, &xml_part))
return false;
do {
if (xml_part.isClosingTag(text_opening_tag))
break;
// format the text as it's read in
if (xml_part.isClosingTag("sec"))
*text += FullTextImport::CHUNK_DELIMITER;
else if (xml_part.isClosingTag("label"))
*text += ": ";
else if (xml_part.isClosingTag("title") or xml_part.isClosingTag("p"))
*text += FullTextImport::PARAGRAPH_DELIMITER;
else if (xml_part.isCharacters())
*text += xml_part.data_;
} while (xml_parser->getNext(&xml_part));
return not text->empty();
}
void ProcessDocument(const bool normalise_only, const std::string &input_file_path, XMLParser * const xml_parser, File * const plain_text_output) {
Metadata full_text_metadata;
ExtractMetadata(xml_parser, &full_text_metadata);
if (full_text_metadata.title_.empty())
LOG_ERROR("no article title found in file '" + input_file_path + "'");
if (full_text_metadata.authors_.empty())
LOG_ERROR("no article authors found in file '" + input_file_path + "'");
if (normalise_only) {
std::cout << ControlNumberGuesser::NormaliseTitle(full_text_metadata.title_) << '\n';
for (const auto &article_author : full_text_metadata.authors_)
std::cout << ControlNumberGuesser::NormaliseAuthorName(article_author) << '\n';
return;
}
std::string full_text, abstract;
if (not ExtractText(xml_parser, "body", &full_text))
ExtractText(xml_parser, "abstract", &abstract);
if (full_text.empty() and abstract.empty())
LOG_ERROR("Neither full-text nor abstract text was found in file '" + input_file_path + "'");
FullTextImport::WriteExtractedTextToDisk(not full_text.empty() ? full_text : abstract,
full_text_metadata.title_, full_text_metadata.authors_, full_text_metadata.publication_year_,
plain_text_output);
}
} // unnamed namespace
int Main(int argc, char *argv[]) {
if (argc < 3)
Usage();
bool normalise_only(false);
if (std::strcmp(argv[1], "--normalise-only") == 0) {
normalise_only = true;
++argc, ++argv;
}
if (argc != 3)
Usage();
XMLParser xml_parser (argv[1], XMLParser::XML_FILE);
auto plain_text_output(normalise_only ? nullptr : FileUtil::OpenOutputFileOrDie(argv[2]));
ProcessDocument(normalise_only, argv[1], &xml_parser, plain_text_output.get());
return EXIT_SUCCESS;
}
<commit_msg>Minor changes<commit_after>/** \brief Tool for title, author and full-text extraction from XMl files corresponding to the Journal Publishing DTD.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2018 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <stdexcept>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include "FileUtil.h"
#include "FullTextImport.h"
#include "StringUtil.h"
#include "util.h"
#include "XMLParser.h"
namespace {
[[noreturn]] void Usage() {
std::cerr << "Usage: " << ::progname << " [--min-log-level=min_verbosity] [--normalise-only] xml_input full_text_output\n"
<< " When specifying --normalise-only we only require the input filename!\n\n";
std::exit(EXIT_FAILURE);
}
struct Metadata {
std::string title_;
std::set<std::string> authors_;
std::string publication_year_;
};
std::string ReadCharactersUntilNextClosingTag(XMLParser * const xml_parser) {
XMLParser::XMLPart xml_part;
std::string extracted_data;
while (xml_parser->getNext(&xml_part)) {
if (xml_part.isClosingTag())
break;
else if (xml_part.type_ == XMLParser::XMLPart::CHARACTERS)
extracted_data += xml_part.data_;
}
return extracted_data;
}
void ExtractAuthor(XMLParser * const xml_parser, std::set<std::string> * const article_authors) {
if (not xml_parser->skipTo(XMLParser::XMLPart::OPENING_TAG, "surname"))
return;
XMLParser::XMLPart xml_part;
if (not xml_parser->getNext(&xml_part) or xml_part.type_ != XMLParser::XMLPart::CHARACTERS)
return;
const std::string surname(xml_part.data_);
while (xml_parser->getNext(&xml_part)) {
if (xml_part.type_ == XMLParser::XMLPart::CLOSING_TAG and xml_part.data_ == "contrib") {
article_authors->insert(surname);
return;
} else if (xml_part.type_ == XMLParser::XMLPart::OPENING_TAG and xml_part.data_ == "given-names") {
if (not xml_parser->getNext(&xml_part) or xml_part.type_ != XMLParser::XMLPart::CHARACTERS)
return;
article_authors->insert(xml_part.data_ + " " + surname);
return;
}
}
}
void ExtractMetadata(XMLParser * const xml_parser, Metadata * const metadata) {
XMLParser::XMLPart xml_part;
while (xml_parser->getNext(&xml_part)) {
if (xml_part.isOpeningTag("article-title"))
metadata->title_ = ReadCharactersUntilNextClosingTag(xml_parser);
else if (xml_part.isOpeningTag("contrib")) {
const auto contrib_type_and_value(xml_part.attributes_.find("contrib-type"));
if (contrib_type_and_value != xml_part.attributes_.cend() and contrib_type_and_value->second == "author")
ExtractAuthor(xml_parser, &metadata->authors_);
} else if (xml_part.isOpeningTag("pub-date")) {
if (xml_parser->skipTo(XMLParser::XMLPart::OPENING_TAG, "year"))
metadata->publication_year_ = ReadCharactersUntilNextClosingTag(xml_parser);
}
}
}
bool ExtractText(XMLParser * const xml_parser, const std::string &text_opening_tag, std::string * const text) {
xml_parser->rewind();
XMLParser::XMLPart xml_part;
if (not xml_parser->skipTo(XMLParser::XMLPart::OPENING_TAG, { text_opening_tag }, &xml_part))
return false;
do {
if (xml_part.isClosingTag(text_opening_tag))
break;
// format the text as it's read in
if (xml_part.isClosingTag("sec"))
*text += FullTextImport::CHUNK_DELIMITER;
else if (xml_part.isClosingTag("label"))
*text += ": ";
else if (xml_part.isClosingTag("title") or xml_part.isClosingTag("p"))
*text += FullTextImport::PARAGRAPH_DELIMITER;
else if (xml_part.isCharacters())
*text += xml_part.data_;
} while (xml_parser->getNext(&xml_part));
return not text->empty();
}
void ProcessDocument(const bool normalise_only, const std::string &input_file_path, XMLParser * const xml_parser, File * const plain_text_output) {
Metadata full_text_metadata;
ExtractMetadata(xml_parser, &full_text_metadata);
if (full_text_metadata.title_.empty())
LOG_ERROR("no article title found in file '" + input_file_path + "'");
if (full_text_metadata.authors_.empty())
LOG_ERROR("no article authors found in file '" + input_file_path + "'");
if (full_text_metadata.publication_year_.empty())
LOG_ERROR("no publication year found in file '" + input_file_path + "'");
if (normalise_only) {
std::cout << ControlNumberGuesser::NormaliseTitle(full_text_metadata.title_) << '\n';
for (const auto &article_author : full_text_metadata.authors_)
std::cout << ControlNumberGuesser::NormaliseAuthorName(article_author) << '\n';
return;
}
std::string full_text, abstract;
if (not ExtractText(xml_parser, "body", &full_text))
ExtractText(xml_parser, "abstract", &abstract);
if (full_text.empty() and abstract.empty())
LOG_ERROR("neither full-text nor abstract text was found in file '" + input_file_path + "'");
FullTextImport::WriteExtractedTextToDisk(not full_text.empty() ? full_text : abstract,
full_text_metadata.title_, full_text_metadata.authors_, full_text_metadata.publication_year_,
plain_text_output);
}
} // unnamed namespace
int Main(int argc, char *argv[]) {
if (argc < 3)
Usage();
bool normalise_only(false);
if (std::strcmp(argv[1], "--normalise-only") == 0) {
normalise_only = true;
++argc, ++argv;
}
if (argc != 3)
Usage();
XMLParser xml_parser (argv[1], XMLParser::XML_FILE);
auto plain_text_output(normalise_only ? nullptr : FileUtil::OpenOutputFileOrDie(argv[2]));
ProcessDocument(normalise_only, argv[1], &xml_parser, plain_text_output.get());
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before><commit_msg>change of opinion here: there's no point in breaking backwards compatibility with the old (to be retired) fp algorithm<commit_after><|endoftext|> |
<commit_before>//
// DataPointerResolver.hpp
// Clock Signal
//
// Created by Thomas Harte on 24/02/2022.
// Copyright © 2022 Thomas Harte. All rights reserved.
//
#ifndef DataPointerResolver_hpp
#define DataPointerResolver_hpp
#include "Instruction.hpp"
#include "Model.hpp"
#include <cassert>
namespace InstructionSet {
namespace x86 {
/// Unlike source, describes only registers, and breaks
/// them down by conventional name — so AL, AH, AX and EAX are all
/// listed separately and uniquely, rather than being eAX+size or
/// eSPorAH with a size of 1.
enum class Register: uint8_t {
// 8-bit registers.
AL, AH,
CL, CH,
DL, DH,
BL, BH,
// 16-bit registers.
AX, CX, DX, BX,
SP, BP, SI, DI,
ES, CS, SS, DS,
FS, GS,
// 32-bit registers.
EAX, ECX, EDX, EBX,
ESP, EBP, ESI, EDI,
//
None
};
/// @returns @c true if @c r is the same size as @c DataT; @c false otherwise.
/// @discussion Provided primarily to aid in asserts; if the decoder and resolver are both
/// working then it shouldn't be necessary to test this in register files.
template <typename DataT> constexpr bool is_sized(Register r) {
static_assert(sizeof(DataT) == 4 || sizeof(DataT) == 2 || sizeof(DataT) == 1);
if constexpr (sizeof(DataT) == 4) {
return r >= Register::EAX && r < Register::None;
}
if constexpr (sizeof(DataT) == 2) {
return r >= Register::AX && r < Register::EAX;
}
if constexpr (sizeof(DataT) == 1) {
return r >= Register::AL && r < Register::AX;
}
return false;
}
/// @returns the proper @c Register given @c source and data of size @c sizeof(DataT),
/// or Register::None if no such register exists (e.g. asking for a 32-bit version of CS).
template <typename DataT> constexpr Register register_for_source(Source source) {
static_assert(sizeof(DataT) == 4 || sizeof(DataT) == 2 || sizeof(DataT) == 1);
if constexpr (sizeof(DataT) == 4) {
switch(source) {
case Source::eAX: return Register::EAX;
case Source::eCX: return Register::ECX;
case Source::eDX: return Register::EDX;
case Source::eBX: return Register::EBX;
case Source::eSPorAH: return Register::ESP;
case Source::eBPorCH: return Register::EBP;
case Source::eSIorDH: return Register::ESI;
case Source::eDIorBH: return Register::EDI;
default: break;
}
}
if constexpr (sizeof(DataT) == 2) {
switch(source) {
case Source::eAX: return Register::AX;
case Source::eCX: return Register::CX;
case Source::eDX: return Register::DX;
case Source::eBX: return Register::BX;
case Source::eSPorAH: return Register::SP;
case Source::eBPorCH: return Register::BP;
case Source::eSIorDH: return Register::SI;
case Source::eDIorBH: return Register::DI;
case Source::ES: return Register::ES;
case Source::CS: return Register::CS;
case Source::SS: return Register::SS;
case Source::DS: return Register::DS;
case Source::FS: return Register::FS;
case Source::GS: return Register::GS;
default: break;
}
}
if constexpr (sizeof(DataT) == 1) {
switch(source) {
case Source::eAX: return Register::AL;
case Source::eCX: return Register::CL;
case Source::eDX: return Register::DL;
case Source::eBX: return Register::BL;
case Source::eSPorAH: return Register::AH;
case Source::eBPorCH: return Register::CH;
case Source::eSIorDH: return Register::DH;
case Source::eDIorBH: return Register::BH;
default: break;
}
}
return Register::None;
}
/// Reads from or writes to the source or target identified by a DataPointer, relying upon two user-supplied classes:
///
/// * a register bank; and
/// * a memory pool.
///
/// The register bank should implement `template<typename DataT, Register> DataT read()` and `template<typename DataT, Register> void write(DataT)`.
/// Those functions will be called only with registers and data types that are appropriate to the @c model.
///
/// The memory pool should implement `template<typename DataT> DataT read(Source segment, uint32_t address)` and
/// `template<typename DataT> void write(Source segment, uint32_t address, DataT value)`.
template <Model model, typename RegistersT, typename MemoryT> class DataPointerResolver {
public:
public:
/// Reads the data pointed to by @c pointer, referencing @c instruction, @c memory and @c registers as necessary.
template <typename DataT> static DataT read(
RegistersT ®isters,
MemoryT &memory,
const Instruction<is_32bit(model)> &instruction,
DataPointer pointer);
/// Writes @c value to the data pointed to by @c pointer, referencing @c instruction, @c memory and @c registers as necessary.
template <typename DataT> static void write(
RegistersT ®isters,
MemoryT &memory,
const Instruction<is_32bit(model)> &instruction,
DataPointer pointer,
DataT value);
/// Computes the effective address of @c pointer including any displacement applied by @c instruction.
/// @c pointer must be of type Source::Indirect.
static uint32_t effective_address(
RegistersT ®isters,
const Instruction<is_32bit(model)> &instruction,
DataPointer pointer);
private:
template <bool is_write, typename DataT> static void access(
RegistersT ®isters,
MemoryT &memory,
const Instruction<is_32bit(model)> &instruction,
DataPointer pointer,
DataT &value);
};
//
// Implementation begins here.
//
template <Model model, typename RegistersT, typename MemoryT>
template <typename DataT> DataT DataPointerResolver<model, RegistersT, MemoryT>::read(
RegistersT ®isters,
MemoryT &memory,
const Instruction<is_32bit(model)> &instruction,
DataPointer pointer) {
DataT result;
access<false>(registers, memory, instruction, pointer, result);
return result;
}
template <Model model, typename RegistersT, typename MemoryT>
template <typename DataT> void DataPointerResolver<model, RegistersT, MemoryT>::write(
RegistersT ®isters,
MemoryT &memory,
const Instruction<is_32bit(model)> &instruction,
DataPointer pointer,
DataT value) {
access<true>(registers, memory, instruction, pointer, value);
}
#define rw(v, r, is_write) \
case Source::r: \
using VType = typename std::remove_reference<decltype(v)>::type; \
if constexpr (is_write) { \
registers.template write<VType, register_for_source<VType>(Source::r)>(v); \
} else { \
v = registers.template read<VType, register_for_source<VType>(Source::r)>(); \
} \
break;
#define ALLREGS(v, i) rw(v, eAX, i); rw(v, eCX, i); \
rw(v, eDX, i); rw(v, eBX, i); \
rw(v, eSPorAH, i); rw(v, eBPorCH, i); \
rw(v, eSIorDH, i); rw(v, eDIorBH, i); \
rw(v, ES, i); rw(v, CS, i); \
rw(v, SS, i); rw(v, DS, i); \
rw(v, FS, i); rw(v, GS, i);
template <Model model, typename RegistersT, typename MemoryT>
uint32_t DataPointerResolver<model, RegistersT, MemoryT>::effective_address(
RegistersT ®isters,
const Instruction<is_32bit(model)> &instruction,
DataPointer pointer) {
using AddressT = typename Instruction<is_32bit(model)>::AddressT;
AddressT base = 0, index = 0;
switch(pointer.base()) {
default: break;
ALLREGS(base, false);
}
switch(pointer.index()) {
default: break;
ALLREGS(index, false);
}
uint32_t address = index;
if constexpr (model >= Model::i80386) {
address <<= pointer.scale();
} else {
assert(!pointer.scale());
}
// Always compute address as 32-bit.
// TODO: verify use of memory_mask around here.
// Also I think possibly an exception is supposed to be generated
// if the programmer is in 32-bit mode and has asked for 16-bit
// address computation but generated e.g. a 17-bit result. Look into
// that when working on execution. For now the goal is merely decoding
// and this code exists both to verify the presence of all necessary
// fields and to help to explore the best breakdown of storage
// within Instruction.
constexpr uint32_t memory_masks[] = {0x0000'ffff, 0xffff'ffff};
const uint32_t memory_mask = memory_masks[int(instruction.address_size())];
address = (address & memory_mask) + (base & memory_mask) + instruction.displacement();
return address;
}
template <Model model, typename RegistersT, typename MemoryT>
template <bool is_write, typename DataT> void DataPointerResolver<model, RegistersT, MemoryT>::access(
RegistersT ®isters,
MemoryT &memory,
const Instruction<is_32bit(model)> &instruction,
DataPointer pointer,
DataT &value) {
const Source source = pointer.source();
switch(source) {
default:
if constexpr (!is_write) {
value = 0;
}
return;
ALLREGS(value, is_write);
case Source::DirectAddress:
if constexpr(is_write) {
memory.template write(instruction.data_segment(), instruction.displacement(), value);
} else {
value = memory.template read<DataT>(instruction.data_segment(), instruction.displacement());
}
break;
case Source::Immediate:
value = DataT(instruction.operand());
break;
case Source::Indirect: {
const auto address = effective_address(registers, instruction, pointer);
if constexpr (is_write) {
memory.template write(
instruction.data_segment(),
address,
value
);
} else {
value = memory.template read<DataT>(
instruction.data_segment(),
address
);
}
}
}
}
#undef ALLREGS
#undef rw
}
}
#endif /* DataPointerResolver_hpp */
<commit_msg>Handle no-base case directly in existing switch.<commit_after>//
// DataPointerResolver.hpp
// Clock Signal
//
// Created by Thomas Harte on 24/02/2022.
// Copyright © 2022 Thomas Harte. All rights reserved.
//
#ifndef DataPointerResolver_hpp
#define DataPointerResolver_hpp
#include "Instruction.hpp"
#include "Model.hpp"
#include <cassert>
namespace InstructionSet {
namespace x86 {
/// Unlike source, describes only registers, and breaks
/// them down by conventional name — so AL, AH, AX and EAX are all
/// listed separately and uniquely, rather than being eAX+size or
/// eSPorAH with a size of 1.
enum class Register: uint8_t {
// 8-bit registers.
AL, AH,
CL, CH,
DL, DH,
BL, BH,
// 16-bit registers.
AX, CX, DX, BX,
SP, BP, SI, DI,
ES, CS, SS, DS,
FS, GS,
// 32-bit registers.
EAX, ECX, EDX, EBX,
ESP, EBP, ESI, EDI,
//
None
};
/// @returns @c true if @c r is the same size as @c DataT; @c false otherwise.
/// @discussion Provided primarily to aid in asserts; if the decoder and resolver are both
/// working then it shouldn't be necessary to test this in register files.
template <typename DataT> constexpr bool is_sized(Register r) {
static_assert(sizeof(DataT) == 4 || sizeof(DataT) == 2 || sizeof(DataT) == 1);
if constexpr (sizeof(DataT) == 4) {
return r >= Register::EAX && r < Register::None;
}
if constexpr (sizeof(DataT) == 2) {
return r >= Register::AX && r < Register::EAX;
}
if constexpr (sizeof(DataT) == 1) {
return r >= Register::AL && r < Register::AX;
}
return false;
}
/// @returns the proper @c Register given @c source and data of size @c sizeof(DataT),
/// or Register::None if no such register exists (e.g. asking for a 32-bit version of CS).
template <typename DataT> constexpr Register register_for_source(Source source) {
static_assert(sizeof(DataT) == 4 || sizeof(DataT) == 2 || sizeof(DataT) == 1);
if constexpr (sizeof(DataT) == 4) {
switch(source) {
case Source::eAX: return Register::EAX;
case Source::eCX: return Register::ECX;
case Source::eDX: return Register::EDX;
case Source::eBX: return Register::EBX;
case Source::eSPorAH: return Register::ESP;
case Source::eBPorCH: return Register::EBP;
case Source::eSIorDH: return Register::ESI;
case Source::eDIorBH: return Register::EDI;
default: break;
}
}
if constexpr (sizeof(DataT) == 2) {
switch(source) {
case Source::eAX: return Register::AX;
case Source::eCX: return Register::CX;
case Source::eDX: return Register::DX;
case Source::eBX: return Register::BX;
case Source::eSPorAH: return Register::SP;
case Source::eBPorCH: return Register::BP;
case Source::eSIorDH: return Register::SI;
case Source::eDIorBH: return Register::DI;
case Source::ES: return Register::ES;
case Source::CS: return Register::CS;
case Source::SS: return Register::SS;
case Source::DS: return Register::DS;
case Source::FS: return Register::FS;
case Source::GS: return Register::GS;
default: break;
}
}
if constexpr (sizeof(DataT) == 1) {
switch(source) {
case Source::eAX: return Register::AL;
case Source::eCX: return Register::CL;
case Source::eDX: return Register::DL;
case Source::eBX: return Register::BL;
case Source::eSPorAH: return Register::AH;
case Source::eBPorCH: return Register::CH;
case Source::eSIorDH: return Register::DH;
case Source::eDIorBH: return Register::BH;
default: break;
}
}
return Register::None;
}
/// Reads from or writes to the source or target identified by a DataPointer, relying upon two user-supplied classes:
///
/// * a register bank; and
/// * a memory pool.
///
/// The register bank should implement `template<typename DataT, Register> DataT read()` and `template<typename DataT, Register> void write(DataT)`.
/// Those functions will be called only with registers and data types that are appropriate to the @c model.
///
/// The memory pool should implement `template<typename DataT> DataT read(Source segment, uint32_t address)` and
/// `template<typename DataT> void write(Source segment, uint32_t address, DataT value)`.
template <Model model, typename RegistersT, typename MemoryT> class DataPointerResolver {
public:
public:
/// Reads the data pointed to by @c pointer, referencing @c instruction, @c memory and @c registers as necessary.
template <typename DataT> static DataT read(
RegistersT ®isters,
MemoryT &memory,
const Instruction<is_32bit(model)> &instruction,
DataPointer pointer);
/// Writes @c value to the data pointed to by @c pointer, referencing @c instruction, @c memory and @c registers as necessary.
template <typename DataT> static void write(
RegistersT ®isters,
MemoryT &memory,
const Instruction<is_32bit(model)> &instruction,
DataPointer pointer,
DataT value);
/// Computes the effective address of @c pointer including any displacement applied by @c instruction.
/// @c pointer must be of type Source::Indirect.
template <bool obscured_indirectNoBase = true, bool has_base = true>
static uint32_t effective_address(
RegistersT ®isters,
const Instruction<is_32bit(model)> &instruction,
DataPointer pointer);
private:
template <bool is_write, typename DataT> static void access(
RegistersT ®isters,
MemoryT &memory,
const Instruction<is_32bit(model)> &instruction,
DataPointer pointer,
DataT &value);
};
//
// Implementation begins here.
//
template <Model model, typename RegistersT, typename MemoryT>
template <typename DataT> DataT DataPointerResolver<model, RegistersT, MemoryT>::read(
RegistersT ®isters,
MemoryT &memory,
const Instruction<is_32bit(model)> &instruction,
DataPointer pointer) {
DataT result;
access<false>(registers, memory, instruction, pointer, result);
return result;
}
template <Model model, typename RegistersT, typename MemoryT>
template <typename DataT> void DataPointerResolver<model, RegistersT, MemoryT>::write(
RegistersT ®isters,
MemoryT &memory,
const Instruction<is_32bit(model)> &instruction,
DataPointer pointer,
DataT value) {
access<true>(registers, memory, instruction, pointer, value);
}
#define rw(v, r, is_write) \
case Source::r: \
using VType = typename std::remove_reference<decltype(v)>::type; \
if constexpr (is_write) { \
registers.template write<VType, register_for_source<VType>(Source::r)>(v); \
} else { \
v = registers.template read<VType, register_for_source<VType>(Source::r)>(); \
} \
break;
#define ALLREGS(v, i) rw(v, eAX, i); rw(v, eCX, i); \
rw(v, eDX, i); rw(v, eBX, i); \
rw(v, eSPorAH, i); rw(v, eBPorCH, i); \
rw(v, eSIorDH, i); rw(v, eDIorBH, i); \
rw(v, ES, i); rw(v, CS, i); \
rw(v, SS, i); rw(v, DS, i); \
rw(v, FS, i); rw(v, GS, i);
template <Model model, typename RegistersT, typename MemoryT>
template <bool obscured_indirectNoBase, bool has_base>
uint32_t DataPointerResolver<model, RegistersT, MemoryT>::effective_address(
RegistersT ®isters,
const Instruction<is_32bit(model)> &instruction,
DataPointer pointer) {
using AddressT = typename Instruction<is_32bit(model)>::AddressT;
AddressT base = 0, index = 0;
if constexpr (has_base) {
switch(pointer.base<obscured_indirectNoBase>()) {
default: break;
ALLREGS(base, false);
}
}
switch(pointer.index()) {
default: break;
ALLREGS(index, false);
}
uint32_t address = index;
if constexpr (model >= Model::i80386) {
address <<= pointer.scale();
} else {
assert(!pointer.scale());
}
// Always compute address as 32-bit.
// TODO: verify use of memory_mask around here.
// Also I think possibly an exception is supposed to be generated
// if the programmer is in 32-bit mode and has asked for 16-bit
// address computation but generated e.g. a 17-bit result. Look into
// that when working on execution. For now the goal is merely decoding
// and this code exists both to verify the presence of all necessary
// fields and to help to explore the best breakdown of storage
// within Instruction.
constexpr uint32_t memory_masks[] = {0x0000'ffff, 0xffff'ffff};
const uint32_t memory_mask = memory_masks[int(instruction.address_size())];
address = (address & memory_mask) + (base & memory_mask) + instruction.displacement();
return address;
}
template <Model model, typename RegistersT, typename MemoryT>
template <bool is_write, typename DataT> void DataPointerResolver<model, RegistersT, MemoryT>::access(
RegistersT ®isters,
MemoryT &memory,
const Instruction<is_32bit(model)> &instruction,
DataPointer pointer,
DataT &value) {
const Source source = pointer.source<false>();
switch(source) {
default:
if constexpr (!is_write) {
value = 0;
}
return;
ALLREGS(value, is_write);
case Source::DirectAddress:
if constexpr(is_write) {
memory.template write(instruction.data_segment(), instruction.displacement(), value);
} else {
value = memory.template read<DataT>(instruction.data_segment(), instruction.displacement());
}
break;
case Source::Immediate:
value = DataT(instruction.operand());
break;
#define indirect(has_base) { \
const auto address = effective_address<false, has_base> \
(registers, instruction, pointer); \
\
if constexpr (is_write) { \
memory.template write( \
instruction.data_segment(), \
address, \
value \
); \
} else { \
value = memory.template read<DataT>( \
instruction.data_segment(), \
address \
); \
} \
}
case Source::IndirectNoBase:
indirect(false);
break;
case Source::Indirect:
indirect(true);
break;
#undef indirect
}
}
#undef ALLREGS
#undef rw
}
}
#endif /* DataPointerResolver_hpp */
<|endoftext|> |
<commit_before><commit_msg>ASACORE-788 Fix memory leak due to m_mdnsPacketTracker.<commit_after><|endoftext|> |
<commit_before>#pragma once
#include <iostream>
#include <blitz/array.h>
#include "blitz_typedefs.hpp"
#include "eigen_interface.hpp"
#include "global_config.hpp"
#include "xs_mesh.hpp"
namespace mocc {
class Source {
public:
Source( int nreg, const XSMesh* xs_mesh, const ArrayB2& flux );
virtual ~Source(){
}
/**
* \brief Initialize the group source.
*
* If there is an external source specified, initialize to that.
* Otherwise, initialize the external source.
*/
virtual void initialize_group( int ig );
/**
* \brief Add the group's contribution from the multi-group fission
* source.
*/
virtual void fission( const ArrayF& fs, int ig );
/**
* Add the contribution from in-scattering from other groups. At some
* point, ill play with upscattering iterations, but for now KISS.
*/
virtual void in_scatter( size_t ig );
/**
* \brief Add a one-group auxiliary source
* This adds some arbitrary source to the current group. Bear in mind
* that the source definitiion starts with the MG fission source, then
* contributions get tacked on from there.
*/
void auxiliary( const ArrayB1 &aux );
/**
* \brief Add self-scatter source
* Add a contribution due to self-scatter within the current group,
* returning the final source. This is usually called several times by a
* sweeper in its "inner" iterations, and therefore does not mutate the
* interal representation of the source, but instead returns the result
* to the caller through the qbar argument.
*
* Have to pass flux_1g in for now, because it is assumed to be updated
* in the sweeper inner iterations outside of the MG flux array. At some
* point, it might be prudent to update it in-place, at which point,
* this flux_1g argument here would be superfluous.
*/
virtual void self_scatter( size_t ig, const ArrayB1& flux_1g,
ArrayF& qbar ) const;
/**
* \brief Return the number of regions for which the Source is defined.
*/
size_t n_reg() const {
return n_reg_;
}
/**
* \brief Add an external source from an XML node.
*/
void add_external( const pugi::xml_node &input );
/**
* \brief Scale the source by some weighting values.
*
* Use this if the client code desires a total source [n] for each
* region, rather than a specific source [nn/cm-3]. Make sure to use
* this right before using the source, after adding all contributions.
*/
void scale( const VecF &v ) {
assert( v.size() == n_reg_ );
for( int i=0; i<(int)n_reg_; i++ ) {
source_1g_(i) *= v[i];
}
}
/**
* \brief Return the source for the indexed cell for the current state
* of the source.
*
* This will never include self-scatter. It will only have contributions
* that have been added thus far.
*/
real_t operator[]( size_t i ) const {
return source_1g_[i];
}
/**
* \copydoc Source::operator[]
*/
real_t& operator[]( size_t i ) {
return source_1g_[i];
}
/**
* \brief Return a const reference to the actual 1G source.
*/
const VectorX& get() const {
return source_1g_;
}
friend std::ostream& operator<<(std::ostream &os, const Source &src) {
std::cout << src.source_1g_ << std::endl;
return os;
}
protected:
const XSMesh *xs_mesh_;
size_t n_group_;
// This is true if an external source has been specified. For now it's
// initialized false.
bool has_external_;
// The external source, if set
ArrayB2 external_source_;
// Single-group source. We use the Eigen storage class so that it can be
// used directly as a source vector in a linear system.
VectorX source_1g_;
// Reference to the MG flux variable. Need this to do scattering
// contributions, etc.
const ArrayB2& flux_;
size_t n_reg_;
};
typedef std::shared_ptr<Source> SP_Source_t;
typedef std::unique_ptr<Source> UP_Source_t;
}
<commit_msg>Actually do the below<commit_after>#pragma once
#include <iostream>
#include <blitz/array.h>
#include "blitz_typedefs.hpp"
#include "eigen_interface.hpp"
#include "global_config.hpp"
#include "xs_mesh.hpp"
namespace mocc {
/**
* The \ref Source class provides functionality for defining a particle
* source, accumulated from commonly-used origins (in-scattering, fission,
* self-scatter, etc.). A \ref Source object can be thought of as a simple
* state machine, in which source contributions for a single group (and
* potentially, angle) are added one-at-a-time. The "state" is reset with a
* call to \ref Source::initialize_group(), which clears all contributions
* to the internally-stored single-group source by initializing it to a
* prescribed external source (if one is defined), or to zero. Following
* group initialization, the other methods can be invoked by the client code
* to add other contributions as needed. When all contributions have been
* added, the client can then request a source for the current group and
* desired angle.
*
* \note At some point, it may be nice to incorporate Pn scattering. Most of
* the functionality for Pn scattering would end up in the Source class
* hierarchy (probably by introducing a Pn variant of the \ref Source base
* class). How the implementation will occur is somewhat up in the air.
* Simplest approach would be to add a new virtual method (which just
* returns on non-Pn sources), which accepts angular flux as input somehow.
* This could be done by passing in an FSR-dependent angular flux after each
* angle sweep and have the \ref Source maintain angular flux moments
* internally. This probably isn't the most computationally efficient method
* though. Ultimately, flux moments need to be stored somewhere, and the
* \ref Source is a great candidate; perhaps exposing a reference to those
* moments to the \ref TransportSweeper and coming up with a slick way for
* the \ref TransportSweeper to interact with those moments in an as-needed
* way would work better. Cross that river when we get to it, I suppose...
*/
class Source {
public:
Source( int nreg, const XSMesh* xs_mesh, const ArrayB2& flux );
virtual ~Source(){
}
/**
* \brief Initialize the group source.
*
* If there is an external source specified, initialize to that.
* Otherwise, initialize the external source.
*/
virtual void initialize_group( int ig );
/**
* \brief Add the group's contribution from the multi-group fission
* source.
*/
virtual void fission( const ArrayF& fs, int ig );
/**
* Add the contribution from in-scattering from other groups. At some
* point, ill play with upscattering iterations, but for now KISS.
*/
virtual void in_scatter( size_t ig );
/**
* \brief Add a one-group auxiliary source
* This adds some arbitrary source to the current group. Bear in mind
* that the source definitiion starts with the MG fission source, then
* contributions get tacked on from there.
*/
void auxiliary( const ArrayB1 &aux );
/**
* \brief Add self-scatter source
* Add a contribution due to self-scatter within the current group,
* returning the final source. This is usually called several times by a
* sweeper in its "inner" iterations, and therefore does not mutate the
* interal representation of the source, but instead returns the result
* to the caller through the qbar argument.
*
* Have to pass flux_1g in for now, because it is assumed to be updated
* in the sweeper inner iterations outside of the MG flux array. At some
* point, it might be prudent to update it in-place, at which point,
* this flux_1g argument here would be superfluous.
*/
virtual void self_scatter( size_t ig, const ArrayB1& flux_1g,
ArrayF& qbar ) const;
/**
* \brief Return the number of regions for which the Source is defined.
*/
size_t n_reg() const {
return n_reg_;
}
/**
* \brief Add an external source from an XML node.
*/
void add_external( const pugi::xml_node &input );
/**
* \brief Scale the source by some weighting values.
*
* Use this if the client code desires a total source [n] for each
* region, rather than a specific source [nn/cm-3]. Make sure to use
* this right before using the source, after adding all contributions.
*/
void scale( const VecF &v ) {
assert( v.size() == n_reg_ );
for( int i=0; i<(int)n_reg_; i++ ) {
source_1g_(i) *= v[i];
}
}
/**
* \brief Return the source for the indexed cell for the current state
* of the source.
*
* This will never include self-scatter. It will only have contributions
* that have been added thus far.
*/
real_t operator[]( size_t i ) const {
return source_1g_[i];
}
/**
* \copydoc Source::operator[]
*/
real_t& operator[]( size_t i ) {
return source_1g_[i];
}
/**
* \brief Return a const reference to the actual 1G source.
*/
const VectorX& get() const {
return source_1g_;
}
friend std::ostream& operator<<(std::ostream &os, const Source &src) {
std::cout << src.source_1g_ << std::endl;
return os;
}
protected:
const XSMesh *xs_mesh_;
size_t n_group_;
// This is true if an external source has been specified. For now it's
// initialized false.
bool has_external_;
// The external source, if set
ArrayB2 external_source_;
// Single-group source. We use the Eigen storage class so that it can be
// used directly as a source vector in a linear system.
VectorX source_1g_;
// Reference to the MG flux variable. Need this to do scattering
// contributions, etc.
const ArrayB2& flux_;
size_t n_reg_;
};
typedef std::shared_ptr<Source> SP_Source_t;
typedef std::unique_ptr<Source> UP_Source_t;
}
<|endoftext|> |
<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
*
* This 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. See file COPYING.
*
*/
#include "ClientMonitor.h"
#include "Monitor.h"
#include "MDSMonitor.h"
#include "OSDMonitor.h"
#include "MonitorStore.h"
#include "messages/MMonMap.h"
#include "messages/MClientMount.h"
#include "messages/MClientMountAck.h"
#include "messages/MClientUnmount.h"
#include "messages/MMonCommand.h"
#include "common/Timer.h"
#include "auth/ExportControl.h"
#include <sstream>
#include "config.h"
#define DOUT_SUBSYS mon
#undef dout_prefix
#define dout_prefix _prefix(mon, client_map)
static ostream& _prefix(Monitor *mon, ClientMap& client_map) {
return *_dout << dbeginl
<< "mon" << mon->whoami
<< (mon->is_starting() ? (const char*)"(starting)":(mon->is_leader() ? (const char*)"(leader)":(mon->is_peon() ? (const char*)"(peon)":(const char*)"(?\?)")))
<< ".client v" << client_map.version << " ";
}
bool ClientMonitor::update_from_paxos()
{
assert(paxos->is_active());
version_t paxosv = paxos->get_version();
if (paxosv == client_map.version) return true;
assert(paxosv >= client_map.version);
dout(10) << "update_from_paxos paxosv " << paxosv
<< ", my v " << client_map.version << dendl;
if (client_map.version == 0 && paxosv > 1) {
// starting up: load latest
bufferlist latest;
version_t v = paxos->get_latest(latest);
if (v) {
dout(7) << "update_from_paxos startup: loaded latest full clientmap" << dendl;
bufferlist::iterator p = latest.begin();
client_map.decode(p);
}
}
// walk through incrementals
while (paxosv > client_map.version) {
bufferlist bl;
bool success = paxos->read(client_map.version+1, bl);
assert(success);
dout(7) << "update_from_paxos applying incremental " << client_map.version+1 << dendl;
ClientMap::Incremental inc;
bufferlist::iterator p = bl.begin();
inc.decode(p);
client_map.apply_incremental(inc);
dout(1) << client_map.client_info.size() << " clients (+"
<< inc.mount.size() << " -" << inc.unmount.size() << ")"
<< dendl;
}
assert(paxosv == client_map.version);
// save latest
bufferlist bl;
client_map.encode(bl);
paxos->stash_latest(paxosv, bl);
mon->store->put_int(paxosv, "clientmap", "last_consumed");
return true;
}
void ClientMonitor::create_pending()
{
pending_inc = ClientMap::Incremental();
pending_inc.version = client_map.version + 1;
pending_inc.next_client = client_map.next_client;
dout(10) << "create_pending v " << pending_inc.version
<< ", next is " << pending_inc.next_client
<< dendl;
}
void ClientMonitor::create_initial(bufferlist& bl)
{
dout(10) << "create_initial -- creating initial map" << dendl;
}
void ClientMonitor::committed()
{
}
void ClientMonitor::encode_pending(bufferlist &bl)
{
dout(10) << "encode_pending v " << pending_inc.version
<< ", next is " << pending_inc.next_client
<< dendl;
assert(paxos->get_version() + 1 == pending_inc.version);
pending_inc.encode(bl);
}
// -------
bool ClientMonitor::check_mount(MClientMount *m)
{
stringstream ss;
// already mounted?
entity_addr_t addr = m->get_orig_source_addr();
ExportControl *ec = conf_get_export_control();
if (ec && (!ec->is_authorized(&addr, "/"))) {
dout(0) << "client is not authorized to mount" << dendl;
ss << "addr " << addr << "is not authorized to mount";
mon->get_logclient()->log(LOG_SEC, ss);
mon->get_logclient()->send_log();
return true;
}
if (client_map.addr_client.count(addr)) {
int client = client_map.addr_client[addr];
dout(7) << " client" << client << " already mounted" << dendl;
ss << "client " << client << "is already mounted";
mon->get_logclient()->log(LOG_INFO, ss);
mon->get_logclient()->send_log();
_mounted(client, m);
return true;
}
return false;
}
bool ClientMonitor::preprocess_query(Message *m)
{
dout(10) << "preprocess_query " << *m << " from " << m->get_orig_source_inst() << dendl;
switch (m->get_type()) {
case CEPH_MSG_CLIENT_MOUNT:
return check_mount((MClientMount *)m);
case CEPH_MSG_CLIENT_UNMOUNT:
{
// already unmounted?
int client = m->get_orig_source().num();
if (client_map.client_info.count(client) == 0) {
dout(7) << " client" << client << " not mounted" << dendl;
_unmounted((MClientUnmount*)m);
return true;
}
}
return false;
case MSG_MON_COMMAND:
return preprocess_command((MMonCommand*)m);
default:
assert(0);
delete m;
return true;
}
}
bool ClientMonitor::prepare_update(Message *m)
{
stringstream ss;
dout(10) << "prepare_update " << *m << " from " << m->get_orig_source_inst() << dendl;
switch (m->get_type()) {
case CEPH_MSG_CLIENT_MOUNT:
{
entity_addr_t addr = m->get_orig_source_addr();
int client = -1;
if (m->get_orig_source().is_client())
client = m->get_orig_source().num();
// choose a client id
if (client < 0) {
client = pending_inc.next_client;
dout(10) << "mount: assigned client" << client << " to " << addr << dendl;
} else {
dout(10) << "mount: client" << client << " requested by " << addr << dendl;
if (client_map.client_info.count(client)) {
assert(client_map.client_info[client].addr() != addr);
dout(0) << "mount: WARNING: client" << client << " requested by " << addr
<< ", which used to be " << client_map.client_info[client].addr() << dendl;
}
}
client_info_t info;
info.ticket.client = client;
info.ticket.addr = addr;
info.ticket.created = g_clock.now();
info.ticket.expires = utime_t();
::encode(info.ticket, info.signed_ticket);
pending_inc.add_mount(client, info);
paxos->wait_for_commit(new C_Mounted(this, client, (MClientMount*)m));
ss << "client " << client << " mounted";
mon->get_logclient()->log(LOG_INFO, ss);
mon->get_logclient()->send_log();
}
return true;
case CEPH_MSG_CLIENT_UNMOUNT:
{
assert(m->get_orig_source().is_client());
int client = m->get_orig_source().num();
assert(client_map.client_info.count(client));
pending_inc.add_unmount(client);
paxos->wait_for_commit(new C_Unmounted(this, (MClientUnmount*)m));
ss << "client " << client << " unmounted";
mon->get_logclient()->log(LOG_INFO, ss);
mon->get_logclient()->send_log();
}
return true;
case MSG_MON_COMMAND:
return prepare_command((MMonCommand*)m);
default:
assert(0);
delete m;
return false;
}
}
// COMMAND
bool ClientMonitor::preprocess_command(MMonCommand *m)
{
int r = -1;
bufferlist rdata;
stringstream ss;
if (m->cmd.size() > 1) {
if (m->cmd[1] == "stat") {
ss << client_map;
r = 0;
}
else if (m->cmd[1] == "getmap") {
client_map.encode(rdata);
ss << "got clientmap version " << client_map.version;
r = 0;
}
else if (m->cmd[1] == "dump") {
ss << "version " << client_map.version << std::endl;
ss << "next_client " << client_map.next_client << std::endl;
for (map<uint32_t, client_info_t>::iterator p = client_map.client_info.begin();
p != client_map.client_info.end();
p++) {
ss << "client" << p->first
<< "\t" << p->second.addr()
<< "\t" << p->second.created()
<< std::endl;
}
while (!ss.eof()) {
string s;
getline(ss, s);
rdata.append(s.c_str(), s.length());
rdata.append("\n", 1);
}
ss << "ok";
r = 0;
}
}
if (r != -1) {
string rs;
getline(ss, rs);
mon->reply_command(m, r, rs, rdata);
return true;
} else
return false;
}
bool ClientMonitor::prepare_command(MMonCommand *m)
{
stringstream ss;
string rs;
int err = -EINVAL;
// nothing here yet
ss << "unrecognized command";
getline(ss, rs);
mon->reply_command(m, err, rs);
return false;
}
// MOUNT
void ClientMonitor::_mounted(int client, MClientMount *m)
{
entity_inst_t to;
to.addr = m->get_orig_source_addr();
to.name = entity_name_t::CLIENT(client);
dout(10) << "_mounted client" << client << " at " << to << dendl;
// reply with client ticket
MClientMountAck *ack = new MClientMountAck;
mon->monmap->encode(ack->monmap_bl);
ack->signed_ticket = client_map.client_info[client].signed_ticket;
mon->messenger->send_message(ack, to);
// also send latest mds and osd maps
mon->mdsmon()->send_latest(to);
mon->osdmon()->send_latest(to);
delete m;
}
void ClientMonitor::_unmounted(MClientUnmount *m)
{
dout(10) << "_unmounted " << m->get_orig_source_inst() << dendl;
// reply with (same) unmount message
mon->messenger->send_message(m, m->get_orig_source_inst());
// auto-shutdown?
// (hack for fakesyn/newsyn, mostly)
if (mon->is_leader() &&
client_map.version > 1 &&
client_map.client_info.empty() &&
g_conf.mon_stop_on_last_unmount &&
!mon->is_stopping()) {
dout(1) << "last client unmounted" << dendl;
mon->stop_cluster();
}
}
void ClientMonitor::tick()
{
if (!paxos->is_active()) return;
update_from_paxos();
dout(10) << client_map << dendl;
if (!mon->is_leader()) return;
// ...
}
<commit_msg>mon: clean up client mount/unmount messages a bit<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
*
* This 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. See file COPYING.
*
*/
#include "ClientMonitor.h"
#include "Monitor.h"
#include "MDSMonitor.h"
#include "OSDMonitor.h"
#include "MonitorStore.h"
#include "messages/MMonMap.h"
#include "messages/MClientMount.h"
#include "messages/MClientMountAck.h"
#include "messages/MClientUnmount.h"
#include "messages/MMonCommand.h"
#include "common/Timer.h"
#include "auth/ExportControl.h"
#include <sstream>
#include "config.h"
#define DOUT_SUBSYS mon
#undef dout_prefix
#define dout_prefix _prefix(mon, client_map)
static ostream& _prefix(Monitor *mon, ClientMap& client_map) {
return *_dout << dbeginl
<< "mon" << mon->whoami
<< (mon->is_starting() ? (const char*)"(starting)":(mon->is_leader() ? (const char*)"(leader)":(mon->is_peon() ? (const char*)"(peon)":(const char*)"(?\?)")))
<< ".client v" << client_map.version << " ";
}
bool ClientMonitor::update_from_paxos()
{
assert(paxos->is_active());
version_t paxosv = paxos->get_version();
if (paxosv == client_map.version) return true;
assert(paxosv >= client_map.version);
dout(10) << "update_from_paxos paxosv " << paxosv
<< ", my v " << client_map.version << dendl;
if (client_map.version == 0 && paxosv > 1) {
// starting up: load latest
bufferlist latest;
version_t v = paxos->get_latest(latest);
if (v) {
dout(7) << "update_from_paxos startup: loaded latest full clientmap" << dendl;
bufferlist::iterator p = latest.begin();
client_map.decode(p);
}
}
// walk through incrementals
while (paxosv > client_map.version) {
bufferlist bl;
bool success = paxos->read(client_map.version+1, bl);
assert(success);
dout(7) << "update_from_paxos applying incremental " << client_map.version+1 << dendl;
ClientMap::Incremental inc;
bufferlist::iterator p = bl.begin();
inc.decode(p);
client_map.apply_incremental(inc);
dout(1) << client_map.client_info.size() << " clients (+"
<< inc.mount.size() << " -" << inc.unmount.size() << ")"
<< dendl;
}
assert(paxosv == client_map.version);
// save latest
bufferlist bl;
client_map.encode(bl);
paxos->stash_latest(paxosv, bl);
mon->store->put_int(paxosv, "clientmap", "last_consumed");
return true;
}
void ClientMonitor::create_pending()
{
pending_inc = ClientMap::Incremental();
pending_inc.version = client_map.version + 1;
pending_inc.next_client = client_map.next_client;
dout(10) << "create_pending v " << pending_inc.version
<< ", next is " << pending_inc.next_client
<< dendl;
}
void ClientMonitor::create_initial(bufferlist& bl)
{
dout(10) << "create_initial -- creating initial map" << dendl;
}
void ClientMonitor::committed()
{
}
void ClientMonitor::encode_pending(bufferlist &bl)
{
dout(10) << "encode_pending v " << pending_inc.version
<< ", next is " << pending_inc.next_client
<< dendl;
assert(paxos->get_version() + 1 == pending_inc.version);
pending_inc.encode(bl);
}
// -------
bool ClientMonitor::check_mount(MClientMount *m)
{
stringstream ss;
// already mounted?
entity_addr_t addr = m->get_orig_source_addr();
ExportControl *ec = conf_get_export_control();
if (ec && (!ec->is_authorized(&addr, "/"))) {
dout(0) << "client is not authorized to mount" << dendl;
ss << "client addr " << addr << " is not authorized to mount";
mon->get_logclient()->log(LOG_SEC, ss);
mon->get_logclient()->send_log();
return true;
}
if (client_map.addr_client.count(addr)) {
int client = client_map.addr_client[addr];
dout(7) << " client" << client << " already mounted" << dendl;
ss << "client" << client << " " << addr << " is already mounted";
mon->get_logclient()->log(LOG_INFO, ss);
mon->get_logclient()->send_log();
_mounted(client, m);
return true;
}
return false;
}
bool ClientMonitor::preprocess_query(Message *m)
{
dout(10) << "preprocess_query " << *m << " from " << m->get_orig_source_inst() << dendl;
switch (m->get_type()) {
case CEPH_MSG_CLIENT_MOUNT:
return check_mount((MClientMount *)m);
case CEPH_MSG_CLIENT_UNMOUNT:
{
// already unmounted?
int client = m->get_orig_source().num();
if (client_map.client_info.count(client) == 0) {
dout(7) << " client" << client << " not mounted" << dendl;
_unmounted((MClientUnmount*)m);
return true;
}
}
return false;
case MSG_MON_COMMAND:
return preprocess_command((MMonCommand*)m);
default:
assert(0);
delete m;
return true;
}
}
bool ClientMonitor::prepare_update(Message *m)
{
stringstream ss;
dout(10) << "prepare_update " << *m << " from " << m->get_orig_source_inst() << dendl;
switch (m->get_type()) {
case CEPH_MSG_CLIENT_MOUNT:
{
entity_addr_t addr = m->get_orig_source_addr();
int client = -1;
if (m->get_orig_source().is_client())
client = m->get_orig_source().num();
// choose a client id
if (client < 0) {
client = pending_inc.next_client;
dout(10) << "mount: assigned client" << client << " to " << addr << dendl;
} else {
dout(10) << "mount: client" << client << " requested by " << addr << dendl;
if (client_map.client_info.count(client)) {
assert(client_map.client_info[client].addr() != addr);
dout(0) << "mount: WARNING: client" << client << " requested by " << addr
<< ", which used to be " << client_map.client_info[client].addr() << dendl;
}
}
client_info_t info;
info.ticket.client = client;
info.ticket.addr = addr;
info.ticket.created = g_clock.now();
info.ticket.expires = utime_t();
::encode(info.ticket, info.signed_ticket);
pending_inc.add_mount(client, info);
paxos->wait_for_commit(new C_Mounted(this, client, (MClientMount*)m));
ss << "client" << client << " " << addr << " mounted";
mon->get_logclient()->log(LOG_INFO, ss);
mon->get_logclient()->send_log();
}
return true;
case CEPH_MSG_CLIENT_UNMOUNT:
{
assert(m->get_orig_source().is_client());
int client = m->get_orig_source().num();
assert(client_map.client_info.count(client));
pending_inc.add_unmount(client);
paxos->wait_for_commit(new C_Unmounted(this, (MClientUnmount*)m));
ss << "client" << client << " " << client_map.client_info[client].addr() << " unmounted";
mon->get_logclient()->log(LOG_INFO, ss);
mon->get_logclient()->send_log();
}
return true;
case MSG_MON_COMMAND:
return prepare_command((MMonCommand*)m);
default:
assert(0);
delete m;
return false;
}
}
// COMMAND
bool ClientMonitor::preprocess_command(MMonCommand *m)
{
int r = -1;
bufferlist rdata;
stringstream ss;
if (m->cmd.size() > 1) {
if (m->cmd[1] == "stat") {
ss << client_map;
r = 0;
}
else if (m->cmd[1] == "getmap") {
client_map.encode(rdata);
ss << "got clientmap version " << client_map.version;
r = 0;
}
else if (m->cmd[1] == "dump") {
ss << "version " << client_map.version << std::endl;
ss << "next_client " << client_map.next_client << std::endl;
for (map<uint32_t, client_info_t>::iterator p = client_map.client_info.begin();
p != client_map.client_info.end();
p++) {
ss << "client" << p->first
<< "\t" << p->second.addr()
<< "\t" << p->second.created()
<< std::endl;
}
while (!ss.eof()) {
string s;
getline(ss, s);
rdata.append(s.c_str(), s.length());
rdata.append("\n", 1);
}
ss << "ok";
r = 0;
}
}
if (r != -1) {
string rs;
getline(ss, rs);
mon->reply_command(m, r, rs, rdata);
return true;
} else
return false;
}
bool ClientMonitor::prepare_command(MMonCommand *m)
{
stringstream ss;
string rs;
int err = -EINVAL;
// nothing here yet
ss << "unrecognized command";
getline(ss, rs);
mon->reply_command(m, err, rs);
return false;
}
// MOUNT
void ClientMonitor::_mounted(int client, MClientMount *m)
{
entity_inst_t to;
to.addr = m->get_orig_source_addr();
to.name = entity_name_t::CLIENT(client);
dout(10) << "_mounted client" << client << " at " << to << dendl;
// reply with client ticket
MClientMountAck *ack = new MClientMountAck;
mon->monmap->encode(ack->monmap_bl);
ack->signed_ticket = client_map.client_info[client].signed_ticket;
mon->messenger->send_message(ack, to);
// also send latest mds and osd maps
mon->mdsmon()->send_latest(to);
mon->osdmon()->send_latest(to);
delete m;
}
void ClientMonitor::_unmounted(MClientUnmount *m)
{
dout(10) << "_unmounted " << m->get_orig_source_inst() << dendl;
// reply with (same) unmount message
mon->messenger->send_message(m, m->get_orig_source_inst());
// auto-shutdown?
// (hack for fakesyn/newsyn, mostly)
if (mon->is_leader() &&
client_map.version > 1 &&
client_map.client_info.empty() &&
g_conf.mon_stop_on_last_unmount &&
!mon->is_stopping()) {
dout(1) << "last client unmounted" << dendl;
mon->stop_cluster();
}
}
void ClientMonitor::tick()
{
if (!paxos->is_active()) return;
update_from_paxos();
dout(10) << client_map << dendl;
if (!mon->is_leader()) return;
// ...
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2010, Dan Bethell, Johannes Saam.
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 RenderConnect nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <time.h>
#include <stdio.h>
#include <vector>
#include <string>
#include <sstream>
#include "DDImage/Iop.h"
#include "DDImage/Row.h"
#include "DDImage/Thread.h"
#include "DDImage/Knobs.h"
#include "DDImage/DDMath.h"
using namespace DD::Image;
#include "Data.h"
#include "Server.h"
// class name
static const char* const CLASS = "RenderConnect";
// help
static const char* const HELP =
"Listens for renders coming from the RenderConnect display driver.";
// our default port
const int renderconnect_default_port = 9201;
// our listener method
static void renderConnectListen(unsigned index, unsigned nthreads, void* data);
// lightweight pixel class
class RenderColour
{
public:
RenderColour()
{
_val[0] = _val[1] = _val[2] = 0.f;
_val[3] = 1.f;
}
float& operator[](int i){ return _val[i]; }
const float& operator[](int i) const { return _val[i]; }
// data
float _val[4];
};
// our image buffer class
class RenderBuffer
{
public:
RenderBuffer() :
_width(0),
_height(0)
{
}
void init(const unsigned int width, const unsigned int height)
{
_width = width;
_height = height;
_data.resize(_width * _height);
}
RenderColour& get(unsigned int x, unsigned int y)
{
unsigned int index = (_width * y) + x;
return _data[index];
}
const RenderColour& get(unsigned int x, unsigned int y) const
{
unsigned int index = (_width * y) + x;
return _data[index];
}
const unsigned int size() const
{
return _data.size();
}
// data
std::vector<RenderColour> _data;
unsigned int _width;
unsigned int _height;
};
// our nuke node
class RenderConnect: public Iop
{
public:
FormatPair m_fmtp; // our buffer format (knob)
Format m_fmt; // The nuke display format
int m_port; // the port we're listening on (knob)
RenderBuffer m_buffer; // our pixel buffer
Lock m_mutex; // mutex for locking the pixel buffer
unsigned int hash_counter; // our refresh hash counter
renderconnect::Server m_server; // our renderconnect::Server
bool m_inError; // some error handling
std::string m_connectionError;
bool m_legit;
RenderConnect(Node* node) :
Iop(node),
m_port(renderconnect_default_port),
m_fmt(Format(0, 0, 1.0)),
m_inError(false),
m_connectionError(""),
m_legit(false)
{
inputs(0);
}
~RenderConnect()
{
disconnect();
}
// It seems additional instances of a node get copied/constructed upon
// very frequent calls to asapUpdate() and this causes us a few
// problems - we don't want new sockets getting opened etc.
// Fortunately attach() only gets called for nodes in the dag so we can
// use this to mark the DAG node as 'legit' and open the port accordingly.
void attach()
{
m_legit = true;
knob("m_formats_knob")->hide(); // We don't need to see the format knob
// Running python code to check if we've already our format in the script
this->script_command("bool([i.name() for i in nuke.formats() if i.name()=='Render_Connect'])");
const char * result = this->script_result();
this->script_unlock();
if (strcmp(result, "True"))
{
m_fmt.add("Render_Connect");
}
}
void detach()
{
// even though a node still exists once removed from a scene (in the
// undo stack) we should close the port and reopen if attach() gets
// called.
m_legit = false;
disconnect();
}
void flagForUpdate()
{
if ( hash_counter==UINT_MAX )
hash_counter=0;
else
hash_counter++;
asapUpdate();
}
// we can use this to change our tcp port
void changePort( int port )
{
m_inError = false;
m_connectionError = "";
// try to reconnect
disconnect();
try
{
m_server.connect( m_port );
}
catch ( ... )
{
std::stringstream ss;
ss << "Could not connect to port: " << port;
m_connectionError = ss.str();
m_inError = true;
print_name( std::cerr );
std::cerr << ": " << ss.str() << std::endl;
return;
}
// success
if ( m_server.isConnected() )
{
Thread::spawn(::renderConnectListen, 1, this);
print_name( std::cout );
std::cout << ": Connected to port " << m_server.getPort() << std::endl;
}
}
// disconnect the server for it's port
void disconnect()
{
if ( m_server.isConnected() )
{
m_server.quit();
Thread::wait(this);
print_name( std::cout );
std::cout << ": Disconnected from port " << m_server.getPort() << std::endl;
}
}
void append(Hash& hash)
{
hash.append(hash_counter);
}
void _validate(bool for_real)
{
// do we need to open a port?
if ( m_server.isConnected()==false && !m_inError && m_legit )
changePort(m_port);
// handle any connection error
if ( m_inError )
error(m_connectionError.c_str());
// setup format etc
info_.format(*m_fmtp.fullSizeFormat());
info_.full_size_format(*m_fmtp.format());
info_.channels(Mask_RGBA);
info_.set(info().format());
}
void engine(int y, int xx, int r, ChannelMask channels, Row& out)
{
float *rOut = out.writable(Chan_Red) + xx;
float *gOut = out.writable(Chan_Green) + xx;
float *bOut = out.writable(Chan_Blue) + xx;
float *aOut = out.writable(Chan_Alpha) + xx;
const float *END = rOut + (r - xx);
unsigned int xxx = static_cast<unsigned int> (xx);
unsigned int yyy = static_cast<unsigned int> (y);
// don't have a buffer yet
m_mutex.lock();
if ( m_buffer._width==0 && m_buffer._height==0 )
{
while (rOut < END)
{
*rOut = *gOut = *bOut = *aOut = 0.f;
++rOut;
++gOut;
++bOut;
++aOut;
++xxx;
}
}
else
{
while (rOut < END)
{
if ( xxx >= m_buffer._width || yyy >= m_buffer._height )
{
*rOut = *gOut = *bOut = *aOut = 0.f;
}
else
{
*rOut = m_buffer.get(xxx, yyy)[0];
*gOut = m_buffer.get(xxx, yyy)[1];
*bOut = m_buffer.get(xxx, yyy)[2];
*aOut = m_buffer.get(xxx, yyy)[3];
}
++rOut;
++gOut;
++bOut;
++aOut;
++xxx;
}
}
m_mutex.unlock();
}
void knobs(Knob_Callback f)
{
Format_knob(f, &m_fmtp, "m_formats_knob", "format");
Int_knob(f, &m_port, "port_number", "port");
}
int knob_changed(Knob* knob)
{
if (knob->is("port_number"))
{
changePort(m_port);
return 1;
}
return 0;
}
const char* Class() const { return CLASS; }
const char* displayName() const { return CLASS; }
const char* node_help() const { return HELP; }
static const Iop::Description desc;
};
//=====
//=====
// @brief our listening thread method
static void renderConnectListen(unsigned index, unsigned nthreads, void* data)
{
bool killThread = false;
RenderConnect * node = reinterpret_cast<RenderConnect*> (data);
while (!killThread)
{
// accept incoming connections!
node->m_server.accept();
// our incoming data object
renderconnect::Data d;
// loop over incoming data
while ((d.type()==2||d.type()==9)==false)
{
// listen for some data
try
{
d = node->m_server.listen();
}
catch( ... )
{
break;
}
// handle the data we received
switch (d.type())
{
case 0: // open a new image
{
node->m_mutex.lock();
node->m_buffer.init(d.width(), d.height());
node->m_mutex.unlock();
// Set the nuke display format
node->m_fmt.set(0, 0, d.width(), d.height());
node->m_fmt.width(d.width());
node->m_fmt.height(d.height());
// Automatically set the knob to the right format
node->knob("m_formats_knob")->set_text("Render_Connect");
break;
}
case 1: // image data
{
// lock buffer
node->m_mutex.lock();
// copy data from d into node->m_buffer
int _w = node->m_buffer._width;
int _h = node->m_buffer._height;
unsigned int _x, _x0, _y, _y0, _s, offset;
_x = _x0 = _y = _y0 = _s = 0;
int _xorigin = d.x();
int _yorigin = d.y();
int _width = d.width();
int _height = d.height();
int _spp = d.spp();
const float* pixel_data = d.pixels();
for (_x = 0; _x < _width; ++_x)
for (_y = 0; _y < _height; ++_y)
{
RenderColour &pix = node->m_buffer.get(_x
+ _xorigin, _h - (_y + _yorigin + 1));
offset = (_width * _y * _spp) + (_x * _spp);
for (_s = 0; _s < _spp; ++_s)
pix[_s] = pixel_data[offset+_s];
}
// release lock
node->m_mutex.unlock();
// update the image
node->flagForUpdate();
break;
}
case 2: // close image
{
// update the image
node->flagForUpdate();
// Debug image finished
//std::cout << "Finish image" << std::endl;
break;
}
case 9: // this is sent when the parent process want to kill
// the listening thread
{
killThread = true;
std::cout << "Kill listen thread" << std::endl;
break;
}
}
}
}
}
//=====
// nuke builder stuff
static Iop* constructor(Node* node){ return new RenderConnect(node); }
const Iop::Description RenderConnect::desc(CLASS, 0, constructor);
<commit_msg>fixed popup issue on windows<commit_after>/*
Copyright (c) 2010, Dan Bethell, Johannes Saam.
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 RenderConnect nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <time.h>
#include <stdio.h>
#include <vector>
#include <string>
#include <sstream>
#include "DDImage/Iop.h"
#include "DDImage/Row.h"
#include "DDImage/Thread.h"
#include "DDImage/Knobs.h"
#include "DDImage/DDMath.h"
using namespace DD::Image;
#include "Data.h"
#include "Server.h"
// class name
static const char* const CLASS = "RenderConnect";
// help
static const char* const HELP =
"Listens for renders coming from the RenderConnect display driver.";
// our default port
const int renderconnect_default_port = 9201;
// our listener method
static void renderConnectListen(unsigned index, unsigned nthreads, void* data);
// lightweight pixel class
class RenderColour
{
public:
RenderColour()
{
_val[0] = _val[1] = _val[2] = 0.f;
_val[3] = 1.f;
}
float& operator[](int i){ return _val[i]; }
const float& operator[](int i) const { return _val[i]; }
// data
float _val[4];
};
// our image buffer class
class RenderBuffer
{
public:
RenderBuffer() :
_width(0),
_height(0)
{
}
void init(const unsigned int width, const unsigned int height)
{
_width = width;
_height = height;
_data.resize(_width * _height);
}
RenderColour& get(unsigned int x, unsigned int y)
{
unsigned int index = (_width * y) + x;
return _data[index];
}
const RenderColour& get(unsigned int x, unsigned int y) const
{
unsigned int index = (_width * y) + x;
return _data[index];
}
const unsigned int size() const
{
return _data.size();
}
// data
std::vector<RenderColour> _data;
unsigned int _width;
unsigned int _height;
};
// our nuke node
class RenderConnect: public Iop
{
public:
FormatPair m_fmtp; // our buffer format (knob)
Format m_fmt; // The nuke display format
int m_port; // the port we're listening on (knob)
RenderBuffer m_buffer; // our pixel buffer
Lock m_mutex; // mutex for locking the pixel buffer
unsigned int hash_counter; // our refresh hash counter
renderconnect::Server m_server; // our renderconnect::Server
bool m_inError; // some error handling
std::string m_connectionError;
bool m_legit;
RenderConnect(Node* node) :
Iop(node),
m_port(renderconnect_default_port),
m_fmt(Format(0, 0, 1.0)),
m_inError(false),
m_connectionError(""),
m_legit(false)
{
inputs(0);
}
~RenderConnect()
{
disconnect();
}
// It seems additional instances of a node get copied/constructed upon
// very frequent calls to asapUpdate() and this causes us a few
// problems - we don't want new sockets getting opened etc.
// Fortunately attach() only gets called for nodes in the dag so we can
// use this to mark the DAG node as 'legit' and open the port accordingly.
void attach()
{
m_legit = true;
knob("m_formats_knob")->hide(); // We don't need to see the format knob
// Running python code to check if we've already our format in the script
this->script_command("bool([i.name() for i in nuke.formats() if i.name()=='Render_Connect'])", true, false);
const char * result = this->script_result();
this->script_unlock();
if (strcmp(result, "True"))
{
m_fmt.add("Render_Connect");
}
}
void detach()
{
// even though a node still exists once removed from a scene (in the
// undo stack) we should close the port and reopen if attach() gets
// called.
m_legit = false;
disconnect();
}
void flagForUpdate()
{
if ( hash_counter==UINT_MAX )
hash_counter=0;
else
hash_counter++;
asapUpdate();
}
// we can use this to change our tcp port
void changePort( int port )
{
m_inError = false;
m_connectionError = "";
// try to reconnect
disconnect();
try
{
m_server.connect( m_port );
}
catch ( ... )
{
std::stringstream ss;
ss << "Could not connect to port: " << port;
m_connectionError = ss.str();
m_inError = true;
print_name( std::cerr );
std::cerr << ": " << ss.str() << std::endl;
return;
}
// success
if ( m_server.isConnected() )
{
Thread::spawn(::renderConnectListen, 1, this);
print_name( std::cout );
std::cout << ": Connected to port " << m_server.getPort() << std::endl;
}
}
// disconnect the server for it's port
void disconnect()
{
if ( m_server.isConnected() )
{
m_server.quit();
Thread::wait(this);
print_name( std::cout );
std::cout << ": Disconnected from port " << m_server.getPort() << std::endl;
}
}
void append(Hash& hash)
{
hash.append(hash_counter);
}
void _validate(bool for_real)
{
// do we need to open a port?
if ( m_server.isConnected()==false && !m_inError && m_legit )
changePort(m_port);
// handle any connection error
if ( m_inError )
error(m_connectionError.c_str());
// setup format etc
info_.format(*m_fmtp.fullSizeFormat());
info_.full_size_format(*m_fmtp.format());
info_.channels(Mask_RGBA);
info_.set(info().format());
}
void engine(int y, int xx, int r, ChannelMask channels, Row& out)
{
float *rOut = out.writable(Chan_Red) + xx;
float *gOut = out.writable(Chan_Green) + xx;
float *bOut = out.writable(Chan_Blue) + xx;
float *aOut = out.writable(Chan_Alpha) + xx;
const float *END = rOut + (r - xx);
unsigned int xxx = static_cast<unsigned int> (xx);
unsigned int yyy = static_cast<unsigned int> (y);
// don't have a buffer yet
m_mutex.lock();
if ( m_buffer._width==0 && m_buffer._height==0 )
{
while (rOut < END)
{
*rOut = *gOut = *bOut = *aOut = 0.f;
++rOut;
++gOut;
++bOut;
++aOut;
++xxx;
}
}
else
{
while (rOut < END)
{
if ( xxx >= m_buffer._width || yyy >= m_buffer._height )
{
*rOut = *gOut = *bOut = *aOut = 0.f;
}
else
{
*rOut = m_buffer.get(xxx, yyy)[0];
*gOut = m_buffer.get(xxx, yyy)[1];
*bOut = m_buffer.get(xxx, yyy)[2];
*aOut = m_buffer.get(xxx, yyy)[3];
}
++rOut;
++gOut;
++bOut;
++aOut;
++xxx;
}
}
m_mutex.unlock();
}
void knobs(Knob_Callback f)
{
Format_knob(f, &m_fmtp, "m_formats_knob", "format");
Int_knob(f, &m_port, "port_number", "port");
}
int knob_changed(Knob* knob)
{
if (knob->is("port_number"))
{
changePort(m_port);
return 1;
}
return 0;
}
const char* Class() const { return CLASS; }
const char* displayName() const { return CLASS; }
const char* node_help() const { return HELP; }
static const Iop::Description desc;
};
//=====
//=====
// @brief our listening thread method
static void renderConnectListen(unsigned index, unsigned nthreads, void* data)
{
bool killThread = false;
RenderConnect * node = reinterpret_cast<RenderConnect*> (data);
while (!killThread)
{
// accept incoming connections!
node->m_server.accept();
// our incoming data object
renderconnect::Data d;
// loop over incoming data
while ((d.type()==2||d.type()==9)==false)
{
// listen for some data
try
{
d = node->m_server.listen();
}
catch( ... )
{
break;
}
// handle the data we received
switch (d.type())
{
case 0: // open a new image
{
node->m_mutex.lock();
node->m_buffer.init(d.width(), d.height());
node->m_mutex.unlock();
// Set the nuke display format
node->m_fmt.set(0, 0, d.width(), d.height());
node->m_fmt.width(d.width());
node->m_fmt.height(d.height());
// Automatically set the knob to the right format
node->knob("m_formats_knob")->set_text("Render_Connect");
break;
}
case 1: // image data
{
// lock buffer
node->m_mutex.lock();
// copy data from d into node->m_buffer
int _w = node->m_buffer._width;
int _h = node->m_buffer._height;
unsigned int _x, _x0, _y, _y0, _s, offset;
_x = _x0 = _y = _y0 = _s = 0;
int _xorigin = d.x();
int _yorigin = d.y();
int _width = d.width();
int _height = d.height();
int _spp = d.spp();
const float* pixel_data = d.pixels();
for (_x = 0; _x < _width; ++_x)
for (_y = 0; _y < _height; ++_y)
{
RenderColour &pix = node->m_buffer.get(_x
+ _xorigin, _h - (_y + _yorigin + 1));
offset = (_width * _y * _spp) + (_x * _spp);
for (_s = 0; _s < _spp; ++_s)
pix[_s] = pixel_data[offset+_s];
}
// release lock
node->m_mutex.unlock();
// update the image
node->flagForUpdate();
break;
}
case 2: // close image
{
// update the image
node->flagForUpdate();
// Debug image finished
//std::cout << "Finish image" << std::endl;
break;
}
case 9: // this is sent when the parent process want to kill
// the listening thread
{
killThread = true;
std::cout << "Kill listen thread" << std::endl;
break;
}
}
}
}
}
//=====
// nuke builder stuff
static Iop* constructor(Node* node){ return new RenderConnect(node); }
const Iop::Description RenderConnect::desc(CLASS, 0, constructor);
<|endoftext|> |
<commit_before>// $Id: ex1.C,v 1.3 2003-03-26 13:55:21 benkirk Exp $
// The Next Great Finite Element Library.
// Copyright (C) 2003 Benjamin S. Kirk
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
/**
* C++ include files that we need
*/
#include <iostream>
/**
* Functions to initialize the library.
*/
#include "libmesh.h"
/**
* Basic include files needed for the mesh functionality.
*/
#include "mesh.h"
/**
* \mainpage Example 1
*
* \section Introduction
*
* This is the first example program. It simply demonstrates
* how to create a mesh object. A mesh is read from file,
* information is printed to the screen, and the mesh is then
* written
*/
int main (int argc, char** argv)
{
/**
* Initialize the library. This is necessary because the library
* may depend on a number of other libraries (i.e. MPI and Petsc)
* that require initialization before use.
*/
libMesh::init (argc, argv);
/**
* Force all our objects to have local scope. By declaring
* libMesh objects in the next pair of braces we can assert
* that they will go out of scope (and should have been deleted)
* before we return from main. This allows the library to do
* internal reference counting and assure memory is not leaked.
*/
{
/**
* Check for proper usage. The program is designed to be run
* as follows:
*
* ./ex1 -d DIM input_mesh_name [output_mesh_name]
*
* where [output_mesh_name] is an optional parameter giving
* a filename to write the mesh into.
*/
if (argc < 4)
{
std::cerr << "Usage: " << argv[0] << " -d 2 in.mesh [out.mesh]"
<< std::endl;
/**
* This handy function will print the file name, line number,
* and then abort. Currrently the library does not use C++
* exception handling.
*/
error();
}
/**
* Get the dimensionality of the mesh from argv[2]
*/
const unsigned int dim = atoi(argv[2]);
/**
* Create a mesh with the requested dimension.
*/
Mesh mesh(dim);
/**
* Read the input mesh.
*/
mesh.read (argv[3]);
/**
* Print information about the mesh to the screen.
*/
mesh.print_info();
/**
* Write the output mesh if the user specified an
* output file name.
*/
if (argc == 5)
mesh.write (argv[4]);
/**
* At this closing brace all of our objects will be forced
* out of scope and will get deconstructed.
*/
}
/**
* All done. Call the libMesh::close() function to close any
* external libraries and check for leaked memory. To be absolutey
* certain this is called last we will return its value. This
* also allows main to return nonzero if memory is leaked, which
* can be useful for testing purposes.
*/
return libMesh::close();
}
<commit_msg>Moved ex1.C over to the new commenting style for automatic output to html.<commit_after>/* $Id: ex1.C,v 1.4 2003-11-06 05:49:23 jwpeterson Exp $ */
/* The Next Great Finite Element Library. */
/* Copyright (C) 2003 Benjamin S. Kirk */
/* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
// C++ include files that we need
#include <iostream>
// Functions to initialize the library.
#include "libmesh.h"
// Basic include files needed for the mesh functionality.
#include "mesh.h"
// Example 1
// Introduction
// This is the first example program. It simply demonstrates
// how to create a mesh object. A mesh is read from file,
// information is printed to the screen, and the mesh is then
// written
int main (int argc, char** argv)
{
// Initialize the library. This is necessary because the library
// may depend on a number of other libraries (i.e. MPI and Petsc)
// that require initialization before use.
libMesh::init (argc, argv);
// Force all our objects to have local scope. By declaring
// libMesh objects in the next pair of braces we can assert
// that they will go out of scope (and should have been deleted)
// before we return from main. This allows the library to do
// internal reference counting and assure memory is not leaked.
{
// Check for proper usage. The program is designed to be run
// as follows:
// ./ex1 -d DIM input_mesh_name [output_mesh_name]
// where [output_mesh_name] is an optional parameter giving
// a filename to write the mesh into.
if (argc < 4)
{
std::cerr << "Usage: " << argv[0] << " -d 2 in.mesh [out.mesh]"
<< std::endl;
// This handy function will print the file name, line number,
// and then abort. Currrently the library does not use C++
// exception handling.
error();
}
// Get the dimensionality of the mesh from argv[2]
const unsigned int dim = atoi(argv[2]);
// Create a mesh with the requested dimension.
Mesh mesh(dim);
// Read the input mesh.
mesh.read (argv[3]);
// Print information about the mesh to the screen.
mesh.print_info();
// Write the output mesh if the user specified an
// output file name.
if (argc == 5)
mesh.write (argv[4]);
// At this closing brace all of our objects will be forced
// out of scope and will get deconstructed.
}
// All done. Call the libMesh::close() function to close any
// external libraries and check for leaked memory. To be absolutey
// certain this is called last we will return its value. This
// also allows main to return nonzero if memory is leaked, which
// can be useful for testing purposes.
return libMesh::close();
}
<|endoftext|> |
<commit_before>/*
* ParseRank.cc
*
* Place-holder -- does nothing except return the top-ranked parse,
* as previously ranked by relex.
*
* Copyright (c) 2008 Linas Vepstas <linas@linas.org>
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "ForeachWord.h"
#include "ParseRank.h"
#include "Node.h"
#include "SimpleTruthValue.h"
#include "TruthValue.h"
using namespace opencog;
ParseRank::ParseRank(void)
{
}
ParseRank::~ParseRank()
{
}
/**
* For each parse of the sentence, perform the ranking algo.
* The input handle is assumed to point to a sentence.
* The returned value is the highest-ranked parse of the
* bunch.
*/
Handle ParseRank::get_top_ranked_parse(Handle h)
{
top = UNDEFINED_HANDLE;
top_rank = -123456.0;
foreach_parse(h, &ParseRank::lookat_parse, this);
return top;
}
/**
*/
bool ParseRank::lookat_parse(Handle h)
{
Node *n = dynamic_cast<Node *>(TLB::getAtom(h));
double rank = n->getTruthValue().getConfidence();
if (top_rank < rank)
{
top_rank = rank;
top = h;
}
printf ("duuude r= %g %g\n", top_rank, rank);
return false;
}
/* ============================== END OF FILE ====================== */
<commit_msg>remove debugging print<commit_after>/*
* ParseRank.cc
*
* Place-holder -- does nothing except return the top-ranked parse,
* as previously ranked by relex.
*
* Copyright (c) 2008 Linas Vepstas <linas@linas.org>
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "ForeachWord.h"
#include "ParseRank.h"
#include "Node.h"
#include "SimpleTruthValue.h"
#include "TruthValue.h"
using namespace opencog;
ParseRank::ParseRank(void)
{
}
ParseRank::~ParseRank()
{
}
/**
* For each parse of the sentence, perform the ranking algo.
* The input handle is assumed to point to a sentence.
* The returned value is the highest-ranked parse of the
* bunch.
*/
Handle ParseRank::get_top_ranked_parse(Handle h)
{
top = UNDEFINED_HANDLE;
top_rank = -123456.0;
foreach_parse(h, &ParseRank::lookat_parse, this);
return top;
}
/**
*/
bool ParseRank::lookat_parse(Handle h)
{
Node *n = dynamic_cast<Node *>(TLB::getAtom(h));
double rank = n->getTruthValue().getConfidence();
if (top_rank < rank)
{
top_rank = rank;
top = h;
}
return false;
}
/* ============================== END OF FILE ====================== */
<|endoftext|> |
<commit_before>/**
** \file object/list-class.cc
** \brief Creation of the URBI object list.
*/
#include <boost/bind.hpp>
#include <libport/foreach.hh>
#include <libport/ufloat.hh>
#include "kernel/userver.hh"
#include "object/float-class.hh"
#include "object/list-class.hh"
#include "object/atom.hh"
#include "object/object.hh"
#include "primitives.hh"
#include "runner/runner.hh"
namespace object
{
rObject list_class;
/*----------------------------.
| Primitives implementation. |
`----------------------------*/
namespace
{
/// Concatenate two lists in place.
/**
* @return \a lhs
*/
static rList
PLUS_EQ(rList lhs, rList rhs)
{
// FIXME: If we use the following code, then a += a does not
// end.
//
// lhs->value_get().insert(lhs->value_get().end(),
// rhs->value_get().begin(),
// rhs->value_get().end());
foreach (const rObject& o, rhs->value_get())
lhs->value_get().push_back(o);
return lhs;
}
/// Concatenate two lists.
/**
* @return A fresh list, concatenation of \a lhs and \a rhs
*/
static rList
PLUS(rList lhs, rList rhs)
{
// Copy lhs
list_traits::type l(lhs->value_get());
rList res = List::fresh(l);
// Append rhs
PLUS_EQ(res, rhs);
return res;
}
#define CHECK_NON_EMPTY \
List::value_type& ul = l->value_get(); \
if (ul.empty ()) \
throw PrimitiveError \
(__FUNCTION__, "operation cannot be applied onto empty list")
/// Give the first element of \a l.
static rObject
front(rList l)
{
CHECK_NON_EMPTY;
return ul.front();
}
/// Give the last element of \a l.
static rObject
back(rList l)
{
CHECK_NON_EMPTY;
return ul.back();
}
/// Give \a l without the first element.
static rList
tail(rList l)
{
CHECK_NON_EMPTY;
List::value_type res = ul;
res.pop_front();
return List::fresh(res);
}
/// Insert \a elt at the end of \a l
static rList
push_back(rList l, rObject elt)
{
l->value_get().push_back(elt);
return l;
}
/// Insert \a elt at the front of \a l
static rList
push_front(rList l, rObject elt)
{
l->value_get().push_front(elt);
return l;
}
/// Remove first element from \a l
static rList
pop_front(rList l)
{
CHECK_NON_EMPTY;
ul.pop_front();
return l;
}
static rList
removeById(rList l, rObject elt)
{
List::value_type under = l->value_get();
List::value_type::iterator i = under.begin();
while (i != under.end())
if (*i == elt)
i = under.erase(i);
else
++i;
l->value_set(under);
return l;
}
#undef CHECK_NON_EMPTY
/// Clear \l
static rList
clear(rList l)
{
l->value_get().clear();
return l;
}
/// Binary predicate used to sort lists.
static bool
compareListItems (runner::Runner&, rObject a, rObject b)
{
objects_type args;
args.push_back(b);
return is_true(urbi_call(::urbiserver->getCurrentRunner(),
a, SYMBOL(LT), args));
}
/// \brief Sort a list.
/// If the list contains different kinds of elements,
/// the order is not defined.
/// \return New sorted list
static rObject
list_class_sort (runner::Runner& r, objects_type args)
{
CHECK_ARG_COUNT(1);
FETCH_ARG(0, List);
std::list<rObject> s;
foreach(const rObject& o, arg0->value_get())
s.push_back(o);
s.sort(boost::bind(compareListItems, boost::ref(r), _1, _2));
List::value_type res;
foreach(const rObject& o, s)
res.push_back(o);
return List::fresh(res);
}
/// Its size.
static rFloat
size (rList l)
{
return Float::fresh(l->value_get().size());
}
}
static rObject
list_class_nth(runner::Runner&, objects_type args)
{
CHECK_ARG_COUNT(2);
FETCH_ARG(0, List);
FETCH_ARG(1, Float);
int index = ufloat_to_int(arg1->value_get(), "nth");
if (index < 0 || index > static_cast<int>(arg0->value_get().size()))
throw PrimitiveError("nth", "invalid index");
return arg0->value_get().at(index);
}
/*-------------------------.
| Primitives declaration. |
`-------------------------*/
#define PRIMITIVE_1_LIST(Name) \
PRIMITIVE_1(list, Name, List)
#define PRIMITIVE_2_LIST(Name) \
PRIMITIVE_2(list, Name, List, List)
PRIMITIVE_1_LIST(back);
PRIMITIVE_1_LIST(clear);
PRIMITIVE_1_LIST(front);
PRIMITIVE_1_LIST(pop_front);
PRIMITIVE_1_LIST(size);
PRIMITIVE_1_LIST(tail);
PRIMITIVE_2_LIST(PLUS);
PRIMITIVE_2_LIST(PLUS_EQ);
PRIMITIVE_2_OBJECT(list, push_back, List);
PRIMITIVE_2_OBJECT(list, push_front, List);
PRIMITIVE_2_OBJECT(list, removeById, List);
void
list_class_initialize ()
{
#define DECLARE(Name) \
DECLARE_PRIMITIVE(list, Name)
DECLARE(PLUS);
DECLARE(PLUS_EQ);
DECLARE(back);
DECLARE(clear);
DECLARE(front);
DECLARE(nth);
DECLARE(pop_front);
DECLARE(push_back);
DECLARE(push_front);
DECLARE(removeById);
DECLARE(size);
DECLARE(sort);
DECLARE(tail);
#undef DECLARE
}
} // namespace object
<commit_msg>Fix an off-by-one error in List.nth.<commit_after>/**
** \file object/list-class.cc
** \brief Creation of the URBI object list.
*/
#include <boost/bind.hpp>
#include <libport/foreach.hh>
#include <libport/ufloat.hh>
#include "kernel/userver.hh"
#include "object/float-class.hh"
#include "object/list-class.hh"
#include "object/atom.hh"
#include "object/object.hh"
#include "primitives.hh"
#include "runner/runner.hh"
namespace object
{
rObject list_class;
/*----------------------------.
| Primitives implementation. |
`----------------------------*/
namespace
{
/// Concatenate two lists in place.
/**
* @return \a lhs
*/
static rList
PLUS_EQ(rList lhs, rList rhs)
{
// FIXME: If we use the following code, then a += a does not
// end.
//
// lhs->value_get().insert(lhs->value_get().end(),
// rhs->value_get().begin(),
// rhs->value_get().end());
foreach (const rObject& o, rhs->value_get())
lhs->value_get().push_back(o);
return lhs;
}
/// Concatenate two lists.
/**
* @return A fresh list, concatenation of \a lhs and \a rhs
*/
static rList
PLUS(rList lhs, rList rhs)
{
// Copy lhs
list_traits::type l(lhs->value_get());
rList res = List::fresh(l);
// Append rhs
PLUS_EQ(res, rhs);
return res;
}
#define CHECK_NON_EMPTY \
List::value_type& ul = l->value_get(); \
if (ul.empty ()) \
throw PrimitiveError \
(__FUNCTION__, "operation cannot be applied onto empty list")
/// Give the first element of \a l.
static rObject
front(rList l)
{
CHECK_NON_EMPTY;
return ul.front();
}
/// Give the last element of \a l.
static rObject
back(rList l)
{
CHECK_NON_EMPTY;
return ul.back();
}
/// Give \a l without the first element.
static rList
tail(rList l)
{
CHECK_NON_EMPTY;
List::value_type res = ul;
res.pop_front();
return List::fresh(res);
}
/// Insert \a elt at the end of \a l
static rList
push_back(rList l, rObject elt)
{
l->value_get().push_back(elt);
return l;
}
/// Insert \a elt at the front of \a l
static rList
push_front(rList l, rObject elt)
{
l->value_get().push_front(elt);
return l;
}
/// Remove first element from \a l
static rList
pop_front(rList l)
{
CHECK_NON_EMPTY;
ul.pop_front();
return l;
}
static rList
removeById(rList l, rObject elt)
{
List::value_type under = l->value_get();
List::value_type::iterator i = under.begin();
while (i != under.end())
if (*i == elt)
i = under.erase(i);
else
++i;
l->value_set(under);
return l;
}
#undef CHECK_NON_EMPTY
/// Clear \l
static rList
clear(rList l)
{
l->value_get().clear();
return l;
}
/// Binary predicate used to sort lists.
static bool
compareListItems (runner::Runner&, rObject a, rObject b)
{
objects_type args;
args.push_back(b);
return is_true(urbi_call(::urbiserver->getCurrentRunner(),
a, SYMBOL(LT), args));
}
/// \brief Sort a list.
/// If the list contains different kinds of elements,
/// the order is not defined.
/// \return New sorted list
static rObject
list_class_sort (runner::Runner& r, objects_type args)
{
CHECK_ARG_COUNT(1);
FETCH_ARG(0, List);
std::list<rObject> s;
foreach(const rObject& o, arg0->value_get())
s.push_back(o);
s.sort(boost::bind(compareListItems, boost::ref(r), _1, _2));
List::value_type res;
foreach(const rObject& o, s)
res.push_back(o);
return List::fresh(res);
}
/// Its size.
static rFloat
size (rList l)
{
return Float::fresh(l->value_get().size());
}
}
static rObject
list_class_nth(runner::Runner&, objects_type args)
{
CHECK_ARG_COUNT(2);
FETCH_ARG(0, List);
FETCH_ARG(1, Float);
int index = ufloat_to_int(arg1->value_get(), "nth");
if (index < 0 || index >= static_cast<int>(arg0->value_get().size()))
throw PrimitiveError("nth", "invalid index");
return arg0->value_get().at(index);
}
/*-------------------------.
| Primitives declaration. |
`-------------------------*/
#define PRIMITIVE_1_LIST(Name) \
PRIMITIVE_1(list, Name, List)
#define PRIMITIVE_2_LIST(Name) \
PRIMITIVE_2(list, Name, List, List)
PRIMITIVE_1_LIST(back);
PRIMITIVE_1_LIST(clear);
PRIMITIVE_1_LIST(front);
PRIMITIVE_1_LIST(pop_front);
PRIMITIVE_1_LIST(size);
PRIMITIVE_1_LIST(tail);
PRIMITIVE_2_LIST(PLUS);
PRIMITIVE_2_LIST(PLUS_EQ);
PRIMITIVE_2_OBJECT(list, push_back, List);
PRIMITIVE_2_OBJECT(list, push_front, List);
PRIMITIVE_2_OBJECT(list, removeById, List);
void
list_class_initialize ()
{
#define DECLARE(Name) \
DECLARE_PRIMITIVE(list, Name)
DECLARE(PLUS);
DECLARE(PLUS_EQ);
DECLARE(back);
DECLARE(clear);
DECLARE(front);
DECLARE(nth);
DECLARE(pop_front);
DECLARE(push_back);
DECLARE(push_front);
DECLARE(removeById);
DECLARE(size);
DECLARE(sort);
DECLARE(tail);
#undef DECLARE
}
} // namespace object
<|endoftext|> |
<commit_before>/*
* Copyright 2007-2015 The OpenMx Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <ctype.h>
#define R_NO_REMAP
#include <R.h>
#include <Rinternals.h>
#include "omxState.h"
#include "omxNPSOLSpecific.h"
#include "omxMatrix.h"
#include "glue.h"
#include "omxImportFrontendState.h"
#include "Compute.h"
#include "npsolswitch.h"
#include "omxBuffer.h"
template <typename T1>
void GradientOptimizerContext::allConstraintsFun(Eigen::MatrixBase<T1> &constraintOut)
{
omxState *globalState = fc->state;
int l=0;
for(int j = 0; j < (int) globalState->conList.size(); j++) {
omxConstraint &cs = *globalState->conList[j];
cs.refreshAndGrab(fc, omxConstraint::LESS_THAN, &constraintOut(l));
l += cs.size;
}
}
#ifdef __cplusplus
extern "C" {
#endif
/* NPSOL-related functions */
extern void F77_SUB(npsol)(int *n, int *nclin, int *ncnln, int *ldA, int *ldJ, int *ldR, double *A,
double *bl, double *bu, void* funcon, void* funobj, int *inform, int *iter,
int *istate, double *c, double *cJac, double *clambda, double *f, double *g, double *R,
double *x, int *iw, int *leniw, double *w, int *lenw);
extern void F77_SUB(npoptn)(char* string, int Rf_length);
#ifdef __cplusplus
}
#endif
#if HAS_NPSOL
static struct GradientOptimizerContext *NPSOL_GOpt;
void F77_SUB(npsolObjectiveFunction)(int* mode, int* n, double* x,
double* f, double* g, int* nstate)
{
if (x != NPSOL_GOpt->fc->est) return; // this is strange but necessary
double fit = NPSOL_GOpt->recordFit(x, mode);
*f = fit;
}
/* (Non)Linear Constraint Functions */
void F77_SUB(npsolConstraintFunction)
( int *mode, int *ncnln, int *n,
int *ldJ, int *needc, double *x,
double *c, double *cJac, int *nstate)
{
if(*mode==1) return;
// "Note that if there are any nonlinear constraints then the
// first call to CONFUN will precede the first call to
// OBJFUN." Hence, we must copyParamToModel here.
NPSOL_GOpt->fc->copyParamToModel();
Eigen::Map< Eigen::VectorXd > cE(c, *ncnln);
NPSOL_GOpt->allConstraintsFun(cE);
}
void omxNPSOL(double *est, GradientOptimizerContext &rf)
{
rf.optName = "NPSOL";
rf.setupAllBounds();
if (std::isfinite(rf.ControlTolerance)) {
std::string opt = string_snprintf("Optimality tolerance %.8g", rf.ControlTolerance);
F77_CALL(npoptn)((char*) opt.c_str(), opt.size());
}
if (rf.warmStart) {
std::string opt = string_snprintf("Warm start");
F77_CALL(npoptn)((char*) opt.c_str(), opt.size());
} else {
std::string opt = string_snprintf("Cold start");
F77_CALL(npoptn)((char*) opt.c_str(), opt.size());
}
// Will fail if we re-enter after an exception
//if (NPSOL_fitMatrix) Rf_error("NPSOL is not reentrant");
FitContext *fc = rf.fc;
NPSOL_GOpt = &rf;
if (ncnln == 0) {
// ensure we never move to a worse point
int mode = 0;
double fit = rf.recordFit(fc->est, &mode);
if (!std::isfinite(fit)) {
rf.informOut = INFORM_STARTING_VALUES_INFEASIBLE;
NPSOL_GOpt = NULL;
return;
}
if (mode == -1) {
NPSOL_GOpt = NULL;
return;
}
}
fc->grad.resize(fc->numParam); // ensure memory is allocated
omxState *globalState = fc->state;
int nclin = 0;
int nlinwid = std::max(1, nclin);
int equality, inequality;
globalState->countNonlinearConstraints(equality, inequality);
int ncnln = equality + inequality;
int nlnwid = std::max(1, ncnln);
int n = int(fc->numParam);
int nctotl = n + nlinwid + nlnwid;
int leniw = 3 * n + nclin + 2 * ncnln;
int lenw = 2 * n * n + n * nclin + 2 * n * ncnln + 20 * n + 11 * nclin + 21 * ncnln;
int ldA = nlinwid; // NPSOL specifies this should be either 1 or nclin, whichever is greater
int ldJ = nlnwid; // NPSOL specifies this should be either 1 or nclin, whichever is greater
int ldR = n; // TODO: Test alternative versions of the size of R to see what's best.
/* Allocate arrays */
Eigen::ArrayXXd A(ldA, n); // maybe transposed?
Eigen::VectorXd c(nlnwid);
Eigen::MatrixXd cJac(ldJ, n); // maybe transposed?
Eigen::VectorXd clambda(nctotl);
Eigen::VectorXd w(lenw);
Eigen::VectorXi istate(nctotl);
Eigen::VectorXi iw(leniw);
if (rf.warmStart) {
istate.setZero();
clambda.setZero();
}
/* F77_CALL(npsol)
( int *n, -- Number of variables
int *nclin, -- Number of linear constraints
int *ncnln, -- Number of nonlinear constraints
int *ldA, -- Row dimension of A (Linear Constraints)
int *ldJ, -- Row dimension of cJac (Jacobian)
int *ldR, -- Row dimension of R (Hessian)
double *A, -- Linear Constraints Array A (in Column-major order)
double *bl, -- Lower Bounds Array (at least n + nclin + ncnln long)
double *bu, -- Upper Bounds Array (at least n + nclin + ncnln long)
function funcon, -- Nonlinear constraint function
function funobj, -- Objective function
int *inform, -- Used to report state. Need not be initialized.
int *iter, -- Used to report number of major iterations performed. Need not be initialized.
int *istate, -- Initial State. Need not be initialized unless using Warm Start.
double *c, -- Array of length ncnln. Need not be initialized. Reports nonlinear constraints at final iteration.
double *cJac, -- Array of Row-length ldJ. Unused if ncnln = 0. Generally need not be initialized.
double *clambda, -- Array of length n+nclin+ncnln. Need not be initialized unless using Warm Start. Reports final QP multipliers.
double *f, -- Used to report final objective value. Need not be initialized.
double *g, -- Array of length n. Used to report final objective gradient. Need not be initialized.
double *R, -- Array of length ldR. Need not be intialized unless using Warm Start.
double *x, -- Array of length n. Contains initial solution estimate.
int *iw, -- Array of length leniw. Need not be initialized. Provides workspace.
int *leniw, -- Length of iw. Must be at least 3n + nclin + ncnln.
double *w, -- Array of length lenw. Need not be initialized. Provides workspace.
int *lenw -- Length of w. Must be at least 2n^2 + n*nclin + 2*n*ncnln + 20*n + 11*nclin +21*ncnln
)
bl, bu, istate, and clambda are all length n+nclin+ncnln.
First n elements refer to the vars, in order.
Next nclin elements refer to bounds on Ax
Last ncnln elements refer to bounds on c(x)
All arrays must be in column-major order.
*/
fc->grad.resize(n);
rf.hessOut.resize(n, n);
double fit; // do not pass in &fc->fit
int iter_out; // ignored
F77_CALL(npsol)(&n, &nclin, &ncnln, &ldA, &ldJ, &ldR, A.data(),
rf.solLB.data(), rf.solUB.data(), (void*)F77_SUB(npsolConstraintFunction),
(void*) F77_SUB(npsolObjectiveFunction), &rf.informOut, &iter_out,
istate.data(), c.data(), cJac.data(),
clambda.data(), &fit, fc->grad.data(), rf.hessOut.data(), fc->est, iw.data(), &leniw, w.data(), &lenw);
// NPSOL can return the wrong fit and estimates, but hard to
// know what to do if there are constraints.
if (rf.bestEst.size() && ncnln == 0) {
fc->fit = rf.bestFit;
memcpy(fc->est, rf.bestEst.data(), sizeof(double) * fc->numParam);
}
NPSOL_GOpt = NULL;
}
void omxSetNPSOLOpts(SEXP options)
{
omxManageProtectInsanity mpi;
static const char *whitelist[] = {
"Central Difference Interval",
"Crash Tolerance",
"Derivative level",
"Difference interval",
"Feasibility tolerance",
"Function precision",
"Hessian",
"Infinite bound size",
"Infinite step size",
"Iteration limit",
"Iters",
"Line search tolerance",
"Major iteration limit",
"Major iterations",
"Print level",
"Print file",
"Minor iteration limit",
"Minor print level",
"Nolist",
"Optimality tolerance",
"Step limit",
"Summary file",
"Verify level",
0
};
const int opBufLen = 250;
char optionCharArray[opBufLen];
int numOptions = Rf_length(options);
SEXP optionNames;
Rf_protect(optionNames = Rf_getAttrib(options, R_NamesSymbol));
for(int i = 0; i < numOptions; i++) {
const char *nextOptionName = CHAR(STRING_ELT(optionNames, i));
const char *nextOptionValue = CHAR(Rf_asChar(VECTOR_ELT(options, i)));
bool ok=false;
for (int wx=0; whitelist[wx]; ++wx) {
if (matchCaseInsensitive(nextOptionName, whitelist[wx])) {
ok=true;
break;
}
}
if (!ok) continue;
snprintf(optionCharArray, opBufLen, "%s %s", nextOptionName, nextOptionValue);
F77_CALL(npoptn)(optionCharArray, strlen(optionCharArray));
if(OMX_DEBUG) { mxLog("Option %s ", optionCharArray);}
}
}
#endif
<commit_msg>Clarify that NPSOL best fit enforcement only works without constraints (try#2)<commit_after>/*
* Copyright 2007-2015 The OpenMx Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <ctype.h>
#define R_NO_REMAP
#include <R.h>
#include <Rinternals.h>
#include "omxState.h"
#include "omxNPSOLSpecific.h"
#include "omxMatrix.h"
#include "glue.h"
#include "omxImportFrontendState.h"
#include "Compute.h"
#include "npsolswitch.h"
#include "omxBuffer.h"
template <typename T1>
void GradientOptimizerContext::allConstraintsFun(Eigen::MatrixBase<T1> &constraintOut)
{
omxState *globalState = fc->state;
int l=0;
for(int j = 0; j < (int) globalState->conList.size(); j++) {
omxConstraint &cs = *globalState->conList[j];
cs.refreshAndGrab(fc, omxConstraint::LESS_THAN, &constraintOut(l));
l += cs.size;
}
}
#ifdef __cplusplus
extern "C" {
#endif
/* NPSOL-related functions */
extern void F77_SUB(npsol)(int *n, int *nclin, int *ncnln, int *ldA, int *ldJ, int *ldR, double *A,
double *bl, double *bu, void* funcon, void* funobj, int *inform, int *iter,
int *istate, double *c, double *cJac, double *clambda, double *f, double *g, double *R,
double *x, int *iw, int *leniw, double *w, int *lenw);
extern void F77_SUB(npoptn)(char* string, int Rf_length);
#ifdef __cplusplus
}
#endif
#if HAS_NPSOL
static struct GradientOptimizerContext *NPSOL_GOpt;
void F77_SUB(npsolObjectiveFunction)(int* mode, int* n, double* x,
double* f, double* g, int* nstate)
{
if (x != NPSOL_GOpt->fc->est) return; // this is strange but necessary
double fit = NPSOL_GOpt->recordFit(x, mode);
*f = fit;
}
/* (Non)Linear Constraint Functions */
void F77_SUB(npsolConstraintFunction)
( int *mode, int *ncnln, int *n,
int *ldJ, int *needc, double *x,
double *c, double *cJac, int *nstate)
{
if(*mode==1) return;
// "Note that if there are any nonlinear constraints then the
// first call to CONFUN will precede the first call to
// OBJFUN." Hence, we must copyParamToModel here.
NPSOL_GOpt->fc->copyParamToModel();
Eigen::Map< Eigen::VectorXd > cE(c, *ncnln);
NPSOL_GOpt->allConstraintsFun(cE);
}
void omxNPSOL(double *est, GradientOptimizerContext &rf)
{
rf.optName = "NPSOL";
rf.setupAllBounds();
if (std::isfinite(rf.ControlTolerance)) {
std::string opt = string_snprintf("Optimality tolerance %.8g", rf.ControlTolerance);
F77_CALL(npoptn)((char*) opt.c_str(), opt.size());
}
if (rf.warmStart) {
std::string opt = string_snprintf("Warm start");
F77_CALL(npoptn)((char*) opt.c_str(), opt.size());
} else {
std::string opt = string_snprintf("Cold start");
F77_CALL(npoptn)((char*) opt.c_str(), opt.size());
}
// Will fail if we re-enter after an exception
//if (NPSOL_fitMatrix) Rf_error("NPSOL is not reentrant");
FitContext *fc = rf.fc;
NPSOL_GOpt = &rf;
omxState *globalState = fc->state;
int nclin = 0;
int nlinwid = std::max(1, nclin);
int equality, inequality;
globalState->countNonlinearConstraints(equality, inequality);
int ncnln = equality + inequality;
int nlnwid = std::max(1, ncnln);
if (ncnln == 0) {
// ensure we never move to a worse point
int mode = 0;
double fit = rf.recordFit(fc->est, &mode);
if (!std::isfinite(fit)) {
rf.informOut = INFORM_STARTING_VALUES_INFEASIBLE;
NPSOL_GOpt = NULL;
return;
}
if (mode == -1) {
NPSOL_GOpt = NULL;
return;
}
}
fc->grad.resize(fc->numParam); // ensure memory is allocated
int n = int(fc->numParam);
int nctotl = n + nlinwid + nlnwid;
int leniw = 3 * n + nclin + 2 * ncnln;
int lenw = 2 * n * n + n * nclin + 2 * n * ncnln + 20 * n + 11 * nclin + 21 * ncnln;
int ldA = nlinwid; // NPSOL specifies this should be either 1 or nclin, whichever is greater
int ldJ = nlnwid; // NPSOL specifies this should be either 1 or nclin, whichever is greater
int ldR = n; // TODO: Test alternative versions of the size of R to see what's best.
/* Allocate arrays */
Eigen::ArrayXXd A(ldA, n); // maybe transposed?
Eigen::VectorXd c(nlnwid);
Eigen::MatrixXd cJac(ldJ, n); // maybe transposed?
Eigen::VectorXd clambda(nctotl);
Eigen::VectorXd w(lenw);
Eigen::VectorXi istate(nctotl);
Eigen::VectorXi iw(leniw);
if (rf.warmStart) {
istate.setZero();
clambda.setZero();
}
/* F77_CALL(npsol)
( int *n, -- Number of variables
int *nclin, -- Number of linear constraints
int *ncnln, -- Number of nonlinear constraints
int *ldA, -- Row dimension of A (Linear Constraints)
int *ldJ, -- Row dimension of cJac (Jacobian)
int *ldR, -- Row dimension of R (Hessian)
double *A, -- Linear Constraints Array A (in Column-major order)
double *bl, -- Lower Bounds Array (at least n + nclin + ncnln long)
double *bu, -- Upper Bounds Array (at least n + nclin + ncnln long)
function funcon, -- Nonlinear constraint function
function funobj, -- Objective function
int *inform, -- Used to report state. Need not be initialized.
int *iter, -- Used to report number of major iterations performed. Need not be initialized.
int *istate, -- Initial State. Need not be initialized unless using Warm Start.
double *c, -- Array of length ncnln. Need not be initialized. Reports nonlinear constraints at final iteration.
double *cJac, -- Array of Row-length ldJ. Unused if ncnln = 0. Generally need not be initialized.
double *clambda, -- Array of length n+nclin+ncnln. Need not be initialized unless using Warm Start. Reports final QP multipliers.
double *f, -- Used to report final objective value. Need not be initialized.
double *g, -- Array of length n. Used to report final objective gradient. Need not be initialized.
double *R, -- Array of length ldR. Need not be intialized unless using Warm Start.
double *x, -- Array of length n. Contains initial solution estimate.
int *iw, -- Array of length leniw. Need not be initialized. Provides workspace.
int *leniw, -- Length of iw. Must be at least 3n + nclin + ncnln.
double *w, -- Array of length lenw. Need not be initialized. Provides workspace.
int *lenw -- Length of w. Must be at least 2n^2 + n*nclin + 2*n*ncnln + 20*n + 11*nclin +21*ncnln
)
bl, bu, istate, and clambda are all length n+nclin+ncnln.
First n elements refer to the vars, in order.
Next nclin elements refer to bounds on Ax
Last ncnln elements refer to bounds on c(x)
All arrays must be in column-major order.
*/
fc->grad.resize(n);
rf.hessOut.resize(n, n);
double fit; // do not pass in &fc->fit
int iter_out; // ignored
F77_CALL(npsol)(&n, &nclin, &ncnln, &ldA, &ldJ, &ldR, A.data(),
rf.solLB.data(), rf.solUB.data(), (void*)F77_SUB(npsolConstraintFunction),
(void*) F77_SUB(npsolObjectiveFunction), &rf.informOut, &iter_out,
istate.data(), c.data(), cJac.data(),
clambda.data(), &fit, fc->grad.data(), rf.hessOut.data(), fc->est, iw.data(), &leniw, w.data(), &lenw);
// NPSOL can return the wrong fit and estimates, but hard to
// know what to do if there are constraints.
if (rf.bestEst.size() && ncnln == 0) {
fc->fit = rf.bestFit;
memcpy(fc->est, rf.bestEst.data(), sizeof(double) * fc->numParam);
}
NPSOL_GOpt = NULL;
}
void omxSetNPSOLOpts(SEXP options)
{
omxManageProtectInsanity mpi;
static const char *whitelist[] = {
"Central Difference Interval",
"Crash Tolerance",
"Derivative level",
"Difference interval",
"Feasibility tolerance",
"Function precision",
"Hessian",
"Infinite bound size",
"Infinite step size",
"Iteration limit",
"Iters",
"Line search tolerance",
"Major iteration limit",
"Major iterations",
"Print level",
"Print file",
"Minor iteration limit",
"Minor print level",
"Nolist",
"Optimality tolerance",
"Step limit",
"Summary file",
"Verify level",
0
};
const int opBufLen = 250;
char optionCharArray[opBufLen];
int numOptions = Rf_length(options);
SEXP optionNames;
Rf_protect(optionNames = Rf_getAttrib(options, R_NamesSymbol));
for(int i = 0; i < numOptions; i++) {
const char *nextOptionName = CHAR(STRING_ELT(optionNames, i));
const char *nextOptionValue = CHAR(Rf_asChar(VECTOR_ELT(options, i)));
bool ok=false;
for (int wx=0; whitelist[wx]; ++wx) {
if (matchCaseInsensitive(nextOptionName, whitelist[wx])) {
ok=true;
break;
}
}
if (!ok) continue;
snprintf(optionCharArray, opBufLen, "%s %s", nextOptionName, nextOptionValue);
F77_CALL(npoptn)(optionCharArray, strlen(optionCharArray));
if(OMX_DEBUG) { mxLog("Option %s ", optionCharArray);}
}
}
#endif
<|endoftext|> |
<commit_before>
// CUDA utilities and system includes
#include <cuda_runtime.h>
#include "device_launch_parameters.h"
// Helper functions
#include <helper_functions.h> // CUDA SDK Helper functions
#include <helper_cuda.h> // CUDA device initialization helper functions
#include <helper_cuda_gl.h> // CUDA device + OpenGL initialization functions
#include <stdlib.h>
#include <stdio.h>
#include <png.h>
#include "imageio.h"
#include "histogram_gpu.h"
#include "histogram_cpu.h"
void probe_image(PixelType* image, png_infop info) {
/**
* Debug: print every 10th pixel.
*/
PixelType pixel;
for (uint y = 0; y < info->height; y+=10){
for (uint x = 0; x < info->width; x+=10){
pixel = image[y * info->width + x];
unsigned char* samples = reinterpret_cast<unsigned char*>(&pixel);
printf("[");
#pragma unroll
for (int CHANNEL = 0; CHANNEL < ACTIVE_CHANNELS; ++CHANNEL) {
printf("%4u", (unsigned int) (samples[CHANNEL]));
}
printf("]");
}
printf("\n");
}
}
void print_histogram(unsigned int* hist) {
/**
* Print histogram to the stdout.
*/
printf("Histogram:\n");
printf("########### ");
for (uint bin = 0; bin < NUM_BINS; bin++) {
printf("[%3u-%3u]", bin * K_BIN, (bin + 1) * K_BIN - 1);
}
printf("\n");
for (uint ch = 0; ch < ACTIVE_CHANNELS; ch++) {
printf("Channel %u: ", ch + 1);
for (uint bin = 0; bin < NUM_BINS; bin++) {
printf("%8u ", hist[ch * NUM_BINS + bin]);
}
printf("\n");
}
}
int main (int argc, char* argv[]) {
PixelType* h_pixels;
PixelType* d_pixels;
unsigned int* d_hist;
unsigned int* h_hist;
unsigned int* cpu_hist;
png_infop info;
if(argc < 2) {
printf("Must include file name to process. `%s <file_name>`\n", argv[0]);
return -1;
}
// Read image.
if(read_png(argv[1], &info, &h_pixels) == PNG_FAILURE) {
printf("Error reading file (%s).\n", argv[1]);
return -1;
}
size_t number_of_bytes = sizeof(uchar4) * info->width * info->height;
printf("Image has height %lu and width %lu\n", info->width, info->width);
// CPU
printf("CPU: \n");
cpu_hist = (uint* )calloc(ACTIVE_CHANNELS * NUM_BINS * sizeof(uint), sizeof(uint));
run_cpu(h_pixels, info->width, info->width, cpu_hist);
print_histogram(cpu_hist);
// Copy data to GPU
printf("GPU: \n");
printf("Allocating GPU memory and copying input data\n");
checkCudaErrors(cudaMalloc((void **)&d_pixels, number_of_bytes));
checkCudaErrors(cudaMalloc((void **)&d_hist, ACTIVE_CHANNELS * NUM_BINS * sizeof(uint)));
checkCudaErrors(cudaMemcpy(d_pixels, h_pixels, number_of_bytes, cudaMemcpyHostToDevice));
// Run histogram computing
printf("Computing histogram\n");
run_gmem_atomics(d_pixels, info->width, info->width, d_hist);
// Copy result back to CPU
printf("Copying result to CPU\n");
h_hist = (uint* )malloc(ACTIVE_CHANNELS * NUM_BINS * sizeof(uint));
checkCudaErrors(cudaMemcpy(h_hist, d_hist, ACTIVE_CHANNELS * NUM_BINS * sizeof(uint), cudaMemcpyDeviceToHost));
// Print results.
print_histogram(h_hist);
checkCudaErrors(cudaFree(d_pixels));
checkCudaErrors(cudaFree(d_hist));
free(h_pixels);
free(h_hist);
free(cpu_hist);
return 0;
}
<commit_msg>Copyright notice.<commit_after>/**
* Copyright 2017 Maria Glukhova
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
// CUDA utilities and system includes
#include <cuda_runtime.h>
#include "device_launch_parameters.h"
// Helper functions
#include <helper_functions.h> // CUDA SDK Helper functions
#include <helper_cuda.h> // CUDA device initialization helper functions
#include <helper_cuda_gl.h> // CUDA device + OpenGL initialization functions
#include <stdlib.h>
#include <stdio.h>
#include <png.h>
#include "imageio.h"
#include "histogram_gpu.h"
#include "histogram_cpu.h"
void probe_image(PixelType* image, png_infop info) {
/**
* Debug: print every 10th pixel.
*/
PixelType pixel;
for (uint y = 0; y < info->height; y+=10){
for (uint x = 0; x < info->width; x+=10){
pixel = image[y * info->width + x];
unsigned char* samples = reinterpret_cast<unsigned char*>(&pixel);
printf("[");
#pragma unroll
for (int CHANNEL = 0; CHANNEL < ACTIVE_CHANNELS; ++CHANNEL) {
printf("%4u", (unsigned int) (samples[CHANNEL]));
}
printf("]");
}
printf("\n");
}
}
void print_histogram(unsigned int* hist) {
/**
* Print histogram to the stdout.
*/
printf("Histogram:\n");
printf("########### ");
for (uint bin = 0; bin < NUM_BINS; bin++) {
printf("[%3u-%3u]", bin * K_BIN, (bin + 1) * K_BIN - 1);
}
printf("\n");
for (uint ch = 0; ch < ACTIVE_CHANNELS; ch++) {
printf("Channel %u: ", ch + 1);
for (uint bin = 0; bin < NUM_BINS; bin++) {
printf("%8u ", hist[ch * NUM_BINS + bin]);
}
printf("\n");
}
}
int main (int argc, char* argv[]) {
PixelType* h_pixels;
PixelType* d_pixels;
unsigned int* d_hist;
unsigned int* h_hist;
unsigned int* cpu_hist;
png_infop info;
if(argc < 2) {
printf("Must include file name to process. `%s <file_name>`\n", argv[0]);
return -1;
}
// Read image.
if(read_png(argv[1], &info, &h_pixels) == PNG_FAILURE) {
printf("Error reading file (%s).\n", argv[1]);
return -1;
}
size_t number_of_bytes = sizeof(uchar4) * info->width * info->height;
printf("Image has height %lu and width %lu\n", info->width, info->width);
// CPU
printf("CPU: \n");
cpu_hist = (uint* )calloc(ACTIVE_CHANNELS * NUM_BINS * sizeof(uint), sizeof(uint));
run_cpu(h_pixels, info->width, info->width, cpu_hist);
print_histogram(cpu_hist);
// Copy data to GPU
printf("GPU: \n");
printf("Allocating GPU memory and copying input data\n");
checkCudaErrors(cudaMalloc((void **)&d_pixels, number_of_bytes));
checkCudaErrors(cudaMalloc((void **)&d_hist, ACTIVE_CHANNELS * NUM_BINS * sizeof(uint)));
checkCudaErrors(cudaMemcpy(d_pixels, h_pixels, number_of_bytes, cudaMemcpyHostToDevice));
// Run histogram computing
printf("Computing histogram\n");
run_gmem_atomics(d_pixels, info->width, info->width, d_hist);
// Copy result back to CPU
printf("Copying result to CPU\n");
h_hist = (uint* )malloc(ACTIVE_CHANNELS * NUM_BINS * sizeof(uint));
checkCudaErrors(cudaMemcpy(h_hist, d_hist, ACTIVE_CHANNELS * NUM_BINS * sizeof(uint), cudaMemcpyDeviceToHost));
// Print results.
print_histogram(h_hist);
checkCudaErrors(cudaFree(d_pixels));
checkCudaErrors(cudaFree(d_hist));
free(h_pixels);
free(h_hist);
free(cpu_hist);
return 0;
}
<|endoftext|> |
<commit_before>#include "Messaging/RequestHandler.hpp"
#include "Messaging/RpcHandler.hpp"
#include "Transports/AddressFactory.hpp"
#include "Connection.hpp"
#include "ConnectionManager.hpp"
using Dissent::Transports::AddressFactory;
using Dissent::Messaging::RequestHandler;
namespace Dissent {
namespace Connections {
ConnectionManager::ConnectionManager(const Id &local_id,
const QSharedPointer<RpcHandler> &rpc) :
_inquired(new ResponseHandler(this, "Inquired")),
_con_tab(local_id),
_local_id(local_id),
_rpc(rpc)
{
QSharedPointer<RequestHandler> inquire(
new RequestHandler(this, "Inquire"));
_rpc->Register("CM::Inquire", inquire);
QSharedPointer<RequestHandler> close(
new RequestHandler(this, "Close"));
_rpc->Register("CM::Close", close);
QSharedPointer<RequestHandler> connect(
new RequestHandler(this, "Connect"));
_rpc->Register("CM::Connect", connect);
QSharedPointer<RequestHandler> disconnect(
new RequestHandler(this, "Disconnect"));
_rpc->Register("CM::Disconnect", disconnect);
QSharedPointer<Connection> con = _con_tab.GetConnection(_local_id);
con->SetSink(_rpc.data());
QObject::connect(con->GetEdge().data(), SIGNAL(StoppedSignal()),
this, SLOT(HandleEdgeClose()));
QObject::connect(con.data(), SIGNAL(CalledDisconnect()),
this, SLOT(HandleDisconnect()));
QObject::connect(con.data(), SIGNAL(Disconnected(const QString &)),
this, SLOT(HandleDisconnected(const QString &)));
}
ConnectionManager::~ConnectionManager()
{
_rpc->Unregister("CM::Inquire");
_rpc->Unregister("CM::Close");
_rpc->Unregister("CM::Connect");
_rpc->Unregister("CM::Disconnect");
}
void ConnectionManager::AddEdgeListener(const QSharedPointer<EdgeListener> &el)
{
if(Stopped()) {
qWarning() << "Attempting to add an EdgeListener after calling Disconnect.";
return;
}
_edge_factory.AddEdgeListener(el);
QObject::connect(el.data(), SIGNAL(NewEdge(const QSharedPointer<Edge> &)),
this, SLOT(HandleNewEdge(const QSharedPointer<Edge> &)));
QObject::connect(el.data(),
SIGNAL(EdgeCreationFailure(const Address &, const QString &)),
this,
SLOT(HandleEdgeCreationFailure(const Address &, const QString&)));
}
void ConnectionManager::ConnectTo(const Address &addr)
{
if(Stopped()) {
qWarning() << "Attempting to connect to a remote node after calling Disconnect.";
return;
}
if(_active_addrs.contains(addr)) {
qDebug() << "Attempting to connect multiple times to the same address:"
<< addr.ToString();
return;
}
_active_addrs[addr] = true;
_outstanding_con_attempts[addr] = true;
if(!_edge_factory.CreateEdgeTo(addr)) {
_outstanding_con_attempts.remove(addr);
_active_addrs.remove(addr);
emit ConnectionAttemptFailure(addr,
"No EdgeListener to handle request");
}
}
void ConnectionManager::OnStop()
{
bool emit_dis = (_con_tab.GetEdges().count() == 0);
foreach(const QSharedPointer<Connection> &con, _con_tab.GetConnections()) {
con->Disconnect();
}
foreach(const QSharedPointer<Edge> &edge, _con_tab.GetEdges()) {
edge->Stop("Disconnecting");
}
_edge_factory.Stop();
if(emit_dis) {
emit Disconnected();
}
}
void ConnectionManager::HandleNewEdge(const QSharedPointer<Edge> &edge)
{
_con_tab.AddEdge(edge);
edge->SetSink(_rpc.data());
QObject::connect(edge.data(), SIGNAL(StoppedSignal()),
this, SLOT(HandleEdgeClose()));
if(!edge->Outbound()) {
return;
}
_outstanding_con_attempts.remove(edge->GetRemoteAddress());
if(!_active_addrs.contains(edge->GetRemoteAddress())) {
qDebug() << "No record of attempting connection to" <<
edge->GetRemoteAddress().ToString();
}
QVariantHash request;
request["peer_id"] = _local_id.GetByteArray();
QString type = edge->GetLocalAddress().GetType();
QSharedPointer<EdgeListener> el = _edge_factory.GetEdgeListener(type);
request["persistent"] = el->GetAddress().ToString();
_rpc->SendRequest(edge, "CM::Inquire", request, _inquired);
}
void ConnectionManager::HandleEdgeCreationFailure(const Address &to,
const QString &reason)
{
_active_addrs.remove(to);
_outstanding_con_attempts.remove(to);
emit ConnectionAttemptFailure(to, reason);
}
void ConnectionManager::Inquire(const Request &request)
{
QSharedPointer<Edge> edge = request.GetFrom().dynamicCast<Edge>();
if(!edge) {
qWarning() << "Received an inquired from a non-Edge: " <<
request.GetFrom()->ToString();
return;
} else if(edge->Outbound()) {
qWarning() << "We should never receive an inquire call on an" <<
"outbound edge: " << request.GetFrom()->ToString();
return;
}
QVariantHash data = request.GetData().toHash();
QByteArray brem_id = data.value("peer_id").toByteArray();
if(brem_id.isEmpty()) {
qWarning() << "Invalid Inqiure, no id";
return;
}
Id rem_id(brem_id);
request.Respond(_local_id.GetByteArray());
QString saddr = data.value("persistent").toString();
Address addr = AddressFactory::GetInstance().CreateAddress(saddr);
edge->SetRemotePersistentAddress(addr);
if(_local_id < rem_id) {
BindEdge(edge, rem_id);
} else if(_local_id == rem_id) {
edge->Stop("Attempting to connect to ourself");
}
}
void ConnectionManager::Inquired(const Response &response)
{
QSharedPointer<Edge> edge = response.GetFrom().dynamicCast<Edge>();
if(!edge) {
qWarning() << "Received an inquired from a non-Edge: " <<
response.GetFrom()->ToString();
return;
} else if(!edge->Outbound()) {
qWarning() << "We would never make an inquire call on an" <<
"incoming edge: " << response.GetFrom()->ToString();
return;
}
QByteArray brem_id = response.GetData().toByteArray();
if(brem_id.isEmpty()) {
qWarning() << "Invalid ConnectionEstablished, no id";
return;
}
Id rem_id(brem_id);
if(_local_id < rem_id) {
BindEdge(edge, rem_id);
} else if(rem_id == _local_id) {
Address addr = edge->GetRemoteAddress();
qDebug() << "Attempting to connect to ourself";
edge->Stop("Attempting to connect to ourself");
emit ConnectionAttemptFailure(addr, "Attempting to connect to ourself");
}
}
void ConnectionManager::BindEdge(const QSharedPointer<Edge> &edge,
const Id &rem_id)
{
/// @TODO add an extra variable to the connection message such as a session
///token so that quick reconnects can be enabled.
if(_con_tab.GetConnection(rem_id) != 0) {
qDebug() << "Already have a connection to: " << rem_id.ToString() <<
" closing Edge: " << edge->ToString();
_rpc->SendNotification(edge, "CM::Close", QVariant());
Address addr = edge->GetRemoteAddress();
edge->Stop("Duplicate connection");
emit ConnectionAttemptFailure(addr, "Duplicate connection");
return;
}
_rpc->SendNotification(edge, "CM::Connect", _local_id.GetByteArray());
CreateConnection(edge, rem_id);
}
void ConnectionManager::Connect(const Request ¬ification)
{
QSharedPointer<Edge> edge = notification.GetFrom().dynamicCast<Edge>();
if(!edge) {
qWarning() << "Connection attempt not from an Edge: " <<
notification.GetFrom()->ToString();
return;
}
QByteArray brem_id = notification.GetData().toByteArray();
if(brem_id.isEmpty()) {
qWarning() << "Invalid ConnectionEstablished, no id";
return;
}
Id rem_id(brem_id);
if(_local_id < rem_id) {
qWarning() << "We should be sending CM::Connect, not the remote side.";
return;
}
QSharedPointer<Connection> old_con = _con_tab.GetConnection(rem_id);
// XXX if there is an old connection and the node doesn't want it, we need
// to close it
if(old_con) {
qDebug() << "Disconnecting old connection";
old_con->Disconnect();
}
CreateConnection(edge, rem_id);
}
void ConnectionManager::CreateConnection(const QSharedPointer<Edge> &pedge,
const Id &rem_id)
{
QSharedPointer<Connection> con(new Connection(pedge, _local_id, rem_id));
con->SetSharedPointer(con);
_con_tab.AddConnection(con);
qDebug() << "Handle new connection:" << con->ToString();
QObject::connect(con.data(), SIGNAL(CalledDisconnect()),
this, SLOT(HandleDisconnect()));
QObject::connect(con.data(), SIGNAL(Disconnected(const QString &)),
this, SLOT(HandleDisconnected(const QString &)));
emit NewConnection(con);
}
void ConnectionManager::Close(const Request ¬ification)
{
QSharedPointer<Edge> edge = notification.GetFrom().dynamicCast<Edge>();
if(!edge) {
qWarning() << "Connection attempt Edge close not from an Edge: " <<
notification.GetFrom()->ToString();
return;
}
edge->Stop("Closed from remote peer");
}
void ConnectionManager::HandleDisconnect()
{
Connection *con = qobject_cast<Connection *>(sender());
if(con == 0) {
return;
}
qDebug() << "Handle disconnect on: " << con->ToString();
_con_tab.Disconnect(con);
if(!con->GetEdge()->Stopped()) {
if(con->GetLocalId() != con->GetRemoteId()) {
_rpc->SendNotification(con->GetSharedPointer(),
"CM::Disconnect", QVariant());
}
con->GetEdge()->Stop("Local disconnect request");
}
}
void ConnectionManager::HandleDisconnected(const QString &reason)
{
Connection *con = qobject_cast<Connection *>(sender());
qDebug() << "Edge disconnected now removing Connection: " << con->ToString()
<< ", because: " << reason;
_con_tab.RemoveConnection(con);
}
void ConnectionManager::Disconnect(const Request ¬ification)
{
QSharedPointer<Connection> con =
notification.GetFrom().dynamicCast<Connection>();
if(!con) {
qWarning() << "Received DisconnectResponse from a non-connection: " <<
notification.GetFrom()->ToString();
return;
}
qDebug() << "Received disconnect for: " << con->ToString();
_con_tab.Disconnect(con.data());
con->GetEdge()->Stop("Remote disconnect");
}
void ConnectionManager::HandleEdgeClose()
{
Edge *edge = qobject_cast<Edge *>(sender());
_active_addrs.remove(edge->GetRemoteAddress());
qDebug() << "Edge closed: " << edge->ToString() << edge->GetStopReason();
if(!_con_tab.RemoveEdge(edge)) {
qWarning() << "Edge closed but no Edge found in CT:" << edge->ToString();
}
QSharedPointer<Connection> con = _con_tab.GetConnection(edge);
if(con) {
con = _con_tab.GetConnection(con->GetRemoteId());
if(con) {
con->Disconnect();
}
}
if(!Stopped()) {
return;
}
if(_con_tab.GetEdges().count() == 0) {
emit Disconnected();
}
}
}
}
<commit_msg>[Connections] Need to delete connections later or potentially not retrieve all of its signals (issue in session)<commit_after>#include "Messaging/RequestHandler.hpp"
#include "Messaging/RpcHandler.hpp"
#include "Transports/AddressFactory.hpp"
#include "Connection.hpp"
#include "ConnectionManager.hpp"
using Dissent::Transports::AddressFactory;
using Dissent::Messaging::RequestHandler;
namespace Dissent {
namespace Connections {
ConnectionManager::ConnectionManager(const Id &local_id,
const QSharedPointer<RpcHandler> &rpc) :
_inquired(new ResponseHandler(this, "Inquired")),
_con_tab(local_id),
_local_id(local_id),
_rpc(rpc)
{
QSharedPointer<RequestHandler> inquire(
new RequestHandler(this, "Inquire"));
_rpc->Register("CM::Inquire", inquire);
QSharedPointer<RequestHandler> close(
new RequestHandler(this, "Close"));
_rpc->Register("CM::Close", close);
QSharedPointer<RequestHandler> connect(
new RequestHandler(this, "Connect"));
_rpc->Register("CM::Connect", connect);
QSharedPointer<RequestHandler> disconnect(
new RequestHandler(this, "Disconnect"));
_rpc->Register("CM::Disconnect", disconnect);
QSharedPointer<Connection> con = _con_tab.GetConnection(_local_id);
con->SetSink(_rpc.data());
QObject::connect(con->GetEdge().data(), SIGNAL(StoppedSignal()),
this, SLOT(HandleEdgeClose()));
QObject::connect(con.data(), SIGNAL(CalledDisconnect()),
this, SLOT(HandleDisconnect()));
QObject::connect(con.data(), SIGNAL(Disconnected(const QString &)),
this, SLOT(HandleDisconnected(const QString &)));
}
ConnectionManager::~ConnectionManager()
{
_rpc->Unregister("CM::Inquire");
_rpc->Unregister("CM::Close");
_rpc->Unregister("CM::Connect");
_rpc->Unregister("CM::Disconnect");
}
void ConnectionManager::AddEdgeListener(const QSharedPointer<EdgeListener> &el)
{
if(Stopped()) {
qWarning() << "Attempting to add an EdgeListener after calling Disconnect.";
return;
}
_edge_factory.AddEdgeListener(el);
QObject::connect(el.data(), SIGNAL(NewEdge(const QSharedPointer<Edge> &)),
this, SLOT(HandleNewEdge(const QSharedPointer<Edge> &)));
QObject::connect(el.data(),
SIGNAL(EdgeCreationFailure(const Address &, const QString &)),
this,
SLOT(HandleEdgeCreationFailure(const Address &, const QString&)));
}
void ConnectionManager::ConnectTo(const Address &addr)
{
if(Stopped()) {
qWarning() << "Attempting to connect to a remote node after calling Disconnect.";
return;
}
if(_active_addrs.contains(addr)) {
qDebug() << "Attempting to connect multiple times to the same address:"
<< addr.ToString();
return;
}
_active_addrs[addr] = true;
_outstanding_con_attempts[addr] = true;
if(!_edge_factory.CreateEdgeTo(addr)) {
_outstanding_con_attempts.remove(addr);
_active_addrs.remove(addr);
emit ConnectionAttemptFailure(addr,
"No EdgeListener to handle request");
}
}
void ConnectionManager::OnStop()
{
bool emit_dis = (_con_tab.GetEdges().count() == 0);
foreach(const QSharedPointer<Connection> &con, _con_tab.GetConnections()) {
con->Disconnect();
}
foreach(const QSharedPointer<Edge> &edge, _con_tab.GetEdges()) {
edge->Stop("Disconnecting");
}
_edge_factory.Stop();
if(emit_dis) {
emit Disconnected();
}
}
void ConnectionManager::HandleNewEdge(const QSharedPointer<Edge> &edge)
{
_con_tab.AddEdge(edge);
edge->SetSink(_rpc.data());
QObject::connect(edge.data(), SIGNAL(StoppedSignal()),
this, SLOT(HandleEdgeClose()));
if(!edge->Outbound()) {
return;
}
_outstanding_con_attempts.remove(edge->GetRemoteAddress());
if(!_active_addrs.contains(edge->GetRemoteAddress())) {
qDebug() << "No record of attempting connection to" <<
edge->GetRemoteAddress().ToString();
}
QVariantHash request;
request["peer_id"] = _local_id.GetByteArray();
QString type = edge->GetLocalAddress().GetType();
QSharedPointer<EdgeListener> el = _edge_factory.GetEdgeListener(type);
request["persistent"] = el->GetAddress().ToString();
_rpc->SendRequest(edge, "CM::Inquire", request, _inquired);
}
void ConnectionManager::HandleEdgeCreationFailure(const Address &to,
const QString &reason)
{
_active_addrs.remove(to);
_outstanding_con_attempts.remove(to);
emit ConnectionAttemptFailure(to, reason);
}
void ConnectionManager::Inquire(const Request &request)
{
QSharedPointer<Edge> edge = request.GetFrom().dynamicCast<Edge>();
if(!edge) {
qWarning() << "Received an inquired from a non-Edge: " <<
request.GetFrom()->ToString();
return;
} else if(edge->Outbound()) {
qWarning() << "We should never receive an inquire call on an" <<
"outbound edge: " << request.GetFrom()->ToString();
return;
}
QVariantHash data = request.GetData().toHash();
QByteArray brem_id = data.value("peer_id").toByteArray();
if(brem_id.isEmpty()) {
qWarning() << "Invalid Inqiure, no id";
return;
}
Id rem_id(brem_id);
request.Respond(_local_id.GetByteArray());
QString saddr = data.value("persistent").toString();
Address addr = AddressFactory::GetInstance().CreateAddress(saddr);
edge->SetRemotePersistentAddress(addr);
if(_local_id < rem_id) {
BindEdge(edge, rem_id);
} else if(_local_id == rem_id) {
edge->Stop("Attempting to connect to ourself");
}
}
void ConnectionManager::Inquired(const Response &response)
{
QSharedPointer<Edge> edge = response.GetFrom().dynamicCast<Edge>();
if(!edge) {
qWarning() << "Received an inquired from a non-Edge: " <<
response.GetFrom()->ToString();
return;
} else if(!edge->Outbound()) {
qWarning() << "We would never make an inquire call on an" <<
"incoming edge: " << response.GetFrom()->ToString();
return;
}
QByteArray brem_id = response.GetData().toByteArray();
if(brem_id.isEmpty()) {
qWarning() << "Invalid ConnectionEstablished, no id";
return;
}
Id rem_id(brem_id);
if(_local_id < rem_id) {
BindEdge(edge, rem_id);
} else if(rem_id == _local_id) {
Address addr = edge->GetRemoteAddress();
qDebug() << "Attempting to connect to ourself";
edge->Stop("Attempting to connect to ourself");
emit ConnectionAttemptFailure(addr, "Attempting to connect to ourself");
}
}
void ConnectionManager::BindEdge(const QSharedPointer<Edge> &edge,
const Id &rem_id)
{
/// @TODO add an extra variable to the connection message such as a session
///token so that quick reconnects can be enabled.
if(_con_tab.GetConnection(rem_id) != 0) {
qDebug() << "Already have a connection to: " << rem_id.ToString() <<
" closing Edge: " << edge->ToString();
_rpc->SendNotification(edge, "CM::Close", QVariant());
Address addr = edge->GetRemoteAddress();
edge->Stop("Duplicate connection");
emit ConnectionAttemptFailure(addr, "Duplicate connection");
return;
}
_rpc->SendNotification(edge, "CM::Connect", _local_id.GetByteArray());
CreateConnection(edge, rem_id);
}
void ConnectionManager::Connect(const Request ¬ification)
{
QSharedPointer<Edge> edge = notification.GetFrom().dynamicCast<Edge>();
if(!edge) {
qWarning() << "Connection attempt not from an Edge: " <<
notification.GetFrom()->ToString();
return;
}
QByteArray brem_id = notification.GetData().toByteArray();
if(brem_id.isEmpty()) {
qWarning() << "Invalid ConnectionEstablished, no id";
return;
}
Id rem_id(brem_id);
if(_local_id < rem_id) {
qWarning() << "We should be sending CM::Connect, not the remote side.";
return;
}
QSharedPointer<Connection> old_con = _con_tab.GetConnection(rem_id);
// XXX if there is an old connection and the node doesn't want it, we need
// to close it
if(old_con) {
qDebug() << "Disconnecting old connection";
old_con->Disconnect();
}
CreateConnection(edge, rem_id);
}
void ConnectionManager::CreateConnection(const QSharedPointer<Edge> &pedge,
const Id &rem_id)
{
QSharedPointer<Connection> con(new Connection(pedge, _local_id, rem_id),
&QObject::deleteLater);
con->SetSharedPointer(con);
_con_tab.AddConnection(con);
qDebug() << "Handle new connection:" << con->ToString();
QObject::connect(con.data(), SIGNAL(CalledDisconnect()),
this, SLOT(HandleDisconnect()));
QObject::connect(con.data(), SIGNAL(Disconnected(const QString &)),
this, SLOT(HandleDisconnected(const QString &)));
emit NewConnection(con);
}
void ConnectionManager::Close(const Request ¬ification)
{
QSharedPointer<Edge> edge = notification.GetFrom().dynamicCast<Edge>();
if(!edge) {
qWarning() << "Connection attempt Edge close not from an Edge: " <<
notification.GetFrom()->ToString();
return;
}
edge->Stop("Closed from remote peer");
}
void ConnectionManager::HandleDisconnect()
{
Connection *con = qobject_cast<Connection *>(sender());
if(con == 0) {
return;
}
qDebug() << "Handle disconnect on: " << con->ToString();
_con_tab.Disconnect(con);
if(!con->GetEdge()->Stopped()) {
if(con->GetLocalId() != con->GetRemoteId()) {
_rpc->SendNotification(con->GetSharedPointer(),
"CM::Disconnect", QVariant());
}
con->GetEdge()->Stop("Local disconnect request");
}
}
void ConnectionManager::HandleDisconnected(const QString &reason)
{
Connection *con = qobject_cast<Connection *>(sender());
qDebug() << "Edge disconnected now removing Connection: " << con->ToString()
<< ", because: " << reason;
_con_tab.RemoveConnection(con);
}
void ConnectionManager::Disconnect(const Request ¬ification)
{
QSharedPointer<Connection> con =
notification.GetFrom().dynamicCast<Connection>();
if(!con) {
qWarning() << "Received DisconnectResponse from a non-connection: " <<
notification.GetFrom()->ToString();
return;
}
qDebug() << "Received disconnect for: " << con->ToString();
_con_tab.Disconnect(con.data());
con->GetEdge()->Stop("Remote disconnect");
}
void ConnectionManager::HandleEdgeClose()
{
Edge *edge = qobject_cast<Edge *>(sender());
_active_addrs.remove(edge->GetRemoteAddress());
qDebug() << "Edge closed: " << edge->ToString() << edge->GetStopReason();
if(!_con_tab.RemoveEdge(edge)) {
qWarning() << "Edge closed but no Edge found in CT:" << edge->ToString();
}
QSharedPointer<Connection> con = _con_tab.GetConnection(edge);
if(con) {
con = _con_tab.GetConnection(con->GetRemoteId());
if(con) {
con->Disconnect();
}
}
if(!Stopped()) {
return;
}
if(_con_tab.GetEdges().count() == 0) {
emit Disconnected();
}
}
}
}
<|endoftext|> |
<commit_before>// -*-c++-*-
#include <osg/Group>
#include <osg/Sequence>
#include <osg/Transform>
#include <osgDB/ReadFile>
#include <osgGA/TrackballManipulator>
#include <osgGLUT/Viewer>
#include <osgGLUT/glut>
//
// A simple demo demonstrating usage of osg::Sequence.
//
// simple event handler to start/stop sequences
class MyEventHandler : public osgGA::GUIEventHandler {
public:
/// Constructor.
MyEventHandler(std::vector<osg::Sequence*>* seq) : GUIEventHandler() {
_seq = seq;
}
/// Handle events.
virtual bool handle(const osgGA::GUIEventAdapter& ea,
osgGA::GUIActionAdapter&) {
bool handled = false;
if (ea.getEventType() == osgGA::GUIEventAdapter::KEYBOARD) {
const char keys[] = "!@#$%^&*()";
for (unsigned int i = 0; i < (sizeof(keys) / sizeof(keys[0])); i++) {
if (i < _seq->size() && ea.getKey() == keys[i]) {
// toggle sequence
osg::Sequence* seq = (*_seq)[i];
osg::Sequence::SequenceMode mode = seq->getMode();
switch (mode) {
case osg::Sequence::START:
seq->setMode(osg::Sequence::PAUSE);
break;
case osg::Sequence::STOP:
seq->setMode(osg::Sequence::START);
break;
case osg::Sequence::PAUSE:
seq->setMode(osg::Sequence::RESUME);
break;
default:
break;
}
cerr << "Toggled sequence " << i << endl;
handled = true;
}
}
}
return handled;
}
/// accept visits.
virtual void accept(osgGA::GUIEventHandlerVisitor&) { }
private:
std::vector<osg::Sequence*>* _seq;
};
void write_usage(std::ostream& out, const std::string& name)
{
out << std::endl;
out <<"usage:"<< std::endl;
out <<" "<<name<<" [options] infile1 [infile2 ...]"<< std::endl;
out << std::endl;
out <<"options:"<< std::endl;
out <<" -l libraryName - load plugin of name libraryName"<< std::endl;
out <<" i.e. -l osgdb_pfb"<< std::endl;
out <<" Useful for loading reader/writers which can load"<< std::endl;
out <<" other file formats in addition to its extension."<< std::endl;
out <<" -e extensionName - load reader/wrter plugin for file extension"<< std::endl;
out <<" i.e. -e pfb"<< std::endl;
out <<" Useful short hand for specifying full library name as"<< std::endl;
out <<" done with -l above, as it automatically expands to"<< std::endl;
out <<" the full library name appropriate for each platform."<< std::endl;
out<<std::endl;
}
osg::Sequence* generateSeq(osg::Sequence::LoopMode mode,
float speed, int nreps,
std::vector<osg::Node*>& model)
{
osg::Sequence* seqNode = osgNew osg::Sequence;
// add children, show each child for 1.0 seconds
for (unsigned int i = 0; i < model.size(); i++) {
seqNode->addChild(model[i]);
seqNode->setTime(i, 1.0f);
}
// interval
seqNode->setInterval(mode, 0, -1);
// speed-up factor and number of repeats for entire sequence
seqNode->setDuration(speed, nreps);
// stopped
seqNode->setMode(osg::Sequence::STOP);
return seqNode;
}
int main( int argc, char **argv )
{
// initialize the GLUT
glutInit( &argc, argv );
if (argc < 2)
{
write_usage(osg::notify(osg::NOTICE), argv[0]);
return 0;
}
// create commandline args
std::vector<std::string> commandLine;
for (int i = 1; i < argc; i++)
commandLine.push_back(argv[i]);
// initialize the viewer
osgGLUT::Viewer viewer;
viewer.setWindowTitle(argv[0]);
// configure the viewer from the commandline arguments, and eat any
// parameters that have been matched.
viewer.readCommandLine(commandLine);
// assumes any remaining parameters are models
std::vector<osg::Node*> model;
for (unsigned int i = 0; i < commandLine.size(); i++) {
cerr << "Loading " << commandLine[i] << endl;
osg::Node* node = osgDB::readNodeFile(commandLine[i]);
if (node)
model.push_back(node);
}
if (model.empty()) {
write_usage(osg::notify(osg::NOTICE),argv[0]);
return -1;
}
// root
osg::Group* rootNode = osgNew osg::Group;
// create sequences
std::vector<osg::Sequence*> seq;
const osg::Sequence::LoopMode mode[] = { osg::Sequence::LOOP,
osg::Sequence::SWING,
osg::Sequence::LOOP };
const float speed[] = { 0.5f, 1.0f, 1.5f };
const int nreps[] = { -1, 5, 1 };
float x = 0.0f;
for (unsigned int i = 0; i < (sizeof(speed) / sizeof(speed[0])); i++) {
osg::Sequence* seqNode = generateSeq(mode[i], speed[i], nreps[i],
model);
if (!seqNode)
continue;
seq.push_back(seqNode);
// position sequence
osg::Matrix matrix;
matrix.makeTranslate(x, 0.0, 0.0);
osg::Transform* xform = osgNew osg::Transform;
xform->setMatrix(matrix);
xform->addChild(seqNode);
rootNode->addChild(xform);
x += seqNode->getBound()._radius * 1.5f;
}
// add model to viewer.
viewer.addViewport(rootNode);
// register additional event handler
viewer.setEventHandler(osgNew MyEventHandler(&seq), 0);
// register trackball, flight and drive.
viewer.registerCameraManipulator(new osgGA::TrackballManipulator);
viewer.open();
viewer.run();
return 0;
}
<commit_msg>Fixed compile errors under IRIX.<commit_after>// -*-c++-*-
#include <osg/Group>
#include <osg/Sequence>
#include <osg/Transform>
#include <osgDB/ReadFile>
#include <osgGA/TrackballManipulator>
#include <osgGLUT/Viewer>
#include <osgGLUT/glut>
//
// A simple demo demonstrating usage of osg::Sequence.
//
// simple event handler to start/stop sequences
class MyEventHandler : public osgGA::GUIEventHandler {
public:
/// Constructor.
MyEventHandler(std::vector<osg::Sequence*>* seq)
{
_seq = seq;
}
/// Handle events.
virtual bool handle(const osgGA::GUIEventAdapter& ea,
osgGA::GUIActionAdapter&)
{
bool handled = false;
if (ea.getEventType() == osgGA::GUIEventAdapter::KEYBOARD)
{
const char keys[] = "!@#$%^&*()";
for (unsigned int i = 0; i < (sizeof(keys) / sizeof(keys[0])); i++) {
if (i < _seq->size() && ea.getKey() == keys[i])
{
// toggle sequence
osg::Sequence* seq = (*_seq)[i];
osg::Sequence::SequenceMode mode = seq->getMode();
switch (mode) {
case osg::Sequence::START:
seq->setMode(osg::Sequence::PAUSE);
break;
case osg::Sequence::STOP:
seq->setMode(osg::Sequence::START);
break;
case osg::Sequence::PAUSE:
seq->setMode(osg::Sequence::RESUME);
break;
default:
break;
}
std::cerr << "Toggled sequence " << i << std::endl;
handled = true;
}
}
}
return handled;
}
/// accept visits.
virtual void accept(osgGA::GUIEventHandlerVisitor&) {}
private:
std::vector<osg::Sequence*>* _seq;
};
void write_usage(std::ostream& out, const std::string& name)
{
out << std::endl;
out <<"usage:"<< std::endl;
out <<" "<<name<<" [options] infile1 [infile2 ...]"<< std::endl;
out << std::endl;
out <<"options:"<< std::endl;
out <<" -l libraryName - load plugin of name libraryName"<< std::endl;
out <<" i.e. -l osgdb_pfb"<< std::endl;
out <<" Useful for loading reader/writers which can load"<< std::endl;
out <<" other file formats in addition to its extension."<< std::endl;
out <<" -e extensionName - load reader/wrter plugin for file extension"<< std::endl;
out <<" i.e. -e pfb"<< std::endl;
out <<" Useful short hand for specifying full library name as"<< std::endl;
out <<" done with -l above, as it automatically expands to"<< std::endl;
out <<" the full library name appropriate for each platform."<< std::endl;
out<<std::endl;
}
osg::Sequence* generateSeq(osg::Sequence::LoopMode mode,
float speed, int nreps,
std::vector<osg::Node*>& model)
{
osg::Sequence* seqNode = osgNew osg::Sequence;
// add children, show each child for 1.0 seconds
for (unsigned int i = 0; i < model.size(); i++) {
seqNode->addChild(model[i]);
seqNode->setTime(i, 1.0f);
}
// interval
seqNode->setInterval(mode, 0, -1);
// speed-up factor and number of repeats for entire sequence
seqNode->setDuration(speed, nreps);
// stopped
seqNode->setMode(osg::Sequence::STOP);
return seqNode;
}
int main( int argc, char **argv )
{
// initialize the GLUT
glutInit( &argc, argv );
if (argc < 2)
{
write_usage(osg::notify(osg::NOTICE), argv[0]);
return 0;
}
// create commandline args
std::vector<std::string> commandLine;
for (int i = 1; i < argc; i++)
commandLine.push_back(argv[i]);
// initialize the viewer
osgGLUT::Viewer viewer;
viewer.setWindowTitle(argv[0]);
// configure the viewer from the commandline arguments, and eat any
// parameters that have been matched.
viewer.readCommandLine(commandLine);
// assumes any remaining parameters are models
std::vector<osg::Node*> model;
for (unsigned int i = 0; i < commandLine.size(); i++) {
std::cerr << "Loading " << commandLine[i] << std::endl;
osg::Node* node = osgDB::readNodeFile(commandLine[i]);
if (node)
model.push_back(node);
}
if (model.empty()) {
write_usage(osg::notify(osg::NOTICE),argv[0]);
return -1;
}
// root
osg::Group* rootNode = osgNew osg::Group;
// create sequences
std::vector<osg::Sequence*> seq;
const osg::Sequence::LoopMode mode[] = { osg::Sequence::LOOP,
osg::Sequence::SWING,
osg::Sequence::LOOP };
const float speed[] = { 0.5f, 1.0f, 1.5f };
const int nreps[] = { -1, 5, 1 };
float x = 0.0f;
for (unsigned int i = 0; i < (sizeof(speed) / sizeof(speed[0])); i++) {
osg::Sequence* seqNode = generateSeq(mode[i], speed[i], nreps[i],
model);
if (!seqNode)
continue;
seq.push_back(seqNode);
// position sequence
osg::Matrix matrix;
matrix.makeTranslate(x, 0.0, 0.0);
osg::Transform* xform = osgNew osg::Transform;
xform->setMatrix(matrix);
xform->addChild(seqNode);
rootNode->addChild(xform);
x += seqNode->getBound()._radius * 1.5f;
}
// add model to viewer.
viewer.addViewport(rootNode);
// register additional event handler
viewer.setEventHandler(osgNew MyEventHandler(&seq), 0);
// register trackball, flight and drive.
viewer.registerCameraManipulator(new osgGA::TrackballManipulator);
viewer.open();
viewer.run();
return 0;
}
<|endoftext|> |
<commit_before>#include "PhysicsManager.hpp"
#include <btBulletDynamicsCommon.h>
#include <glm/gtx/quaternion.hpp>
#include "../Component/RigidBody.hpp"
#include "../Component/Shape.hpp"
#include "../Entity/Entity.hpp"
#include "../Physics/GlmConversion.hpp"
#include "../Physics/Shape.hpp"
#include "../Physics/Trigger.hpp"
#include "../Physics/TriggerObserver.hpp"
#include "../Util/Json.hpp"
PhysicsManager::PhysicsManager() {
// The broadphase is used to quickly cull bodies that will not collide with
// each other, normally by leveraging some simpler (and rough) test such as
// bounding boxes.
broadphase = new btDbvtBroadphase;
// With the collision configuration one can configure collision detection
// algorithms.
collisionConfiguration = new btDefaultCollisionConfiguration;
dispatcher = new btCollisionDispatcher(collisionConfiguration);
// The solver makes objects interact by making use of gravity, collisions,
// game logic supplied forces, and constraints.
solver = new btSequentialImpulseConstraintSolver;
// The dynamics world encompasses objects included in the simulation.
dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
// Y axis up
dynamicsWorld->setGravity(btVector3(0, -9.82, 0));
// Set the lockbox key we will use for lockboxes created in here.
triggerLockBoxKey.reset(new Utility::LockBox<Physics::Trigger>::Key());
}
PhysicsManager::~PhysicsManager() {
delete dynamicsWorld;
delete solver;
delete dispatcher;
delete collisionConfiguration;
delete broadphase;
for (auto t : triggers)
delete t;
}
void PhysicsManager::Update(float deltaTime) {
for (auto rigidBodyComp : rigidBodyComponents.GetAll()) {
if (rigidBodyComp->IsKilled() || !rigidBodyComp->entity->enabled) {
continue;
}
dynamicsWorld->removeRigidBody(rigidBodyComp->GetBulletRigidBody());
rigidBodyComp->SetPosition(rigidBodyComp->entity->GetWorldPosition());
rigidBodyComp->SetOrientation(rigidBodyComp->entity->GetWorldOrientation());
rigidBodyComp->SetMass(rigidBodyComp->GetMass());
dynamicsWorld->addRigidBody(rigidBodyComp->GetBulletRigidBody());
}
dynamicsWorld->stepSimulation(deltaTime, 10);
for (auto trigger : triggers) {
trigger->Process(*dynamicsWorld);
}
}
void PhysicsManager::UpdateEntityTransforms() {
for (auto rigidBodyComp : rigidBodyComponents.GetAll()) {
if (rigidBodyComp->IsKilled() || !rigidBodyComp->entity->enabled)
continue;
Entity* entity = rigidBodyComp->entity;
auto trans = rigidBodyComp->GetBulletRigidBody()->getWorldTransform();
entity->SetWorldPosition(Physics::btToGlm(trans.getOrigin()));
entity->SetWorldOrientation(Physics::btToGlm(trans.getRotation()));
}
}
void PhysicsManager::OnTriggerEnter(Component::RigidBody* trigger, Component::RigidBody* object, std::function<void()> callback) {
auto t = CreateTrigger(trigger);
// Add the callback to the trigger observer
t.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) {
trigger.ForObserver(object->GetBulletRigidBody(), [&callback](Physics::TriggerObserver& observer) {
observer.OnEnter(callback);
});
});
}
void PhysicsManager::OnTriggerRetain(Component::RigidBody* trigger, Component::RigidBody* object, std::function<void()> callback) {
auto t = CreateTrigger(trigger);
// Add the callback to the trigger observer
t.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) {
trigger.ForObserver(object->GetBulletRigidBody(), [&callback](::Physics::TriggerObserver& observer) {
observer.OnRetain(callback);
});
});
}
void PhysicsManager::OnTriggerLeave(Component::RigidBody* trigger, Component::RigidBody* object, std::function<void()> callback) {
auto t = CreateTrigger(trigger);
// Add the callback to the trigger observer
t.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) {
trigger.ForObserver(object->GetBulletRigidBody(), [&callback](::Physics::TriggerObserver& observer) {
observer.OnLeave(callback);
});
});
}
Component::RigidBody* PhysicsManager::CreateRigidBody(Entity* owner) {
auto comp = rigidBodyComponents.Create();
comp->entity = owner;
comp->NewBulletRigidBody(1.0f);
auto shapeComp = comp->entity->GetComponent<Component::Shape>();
if (shapeComp) {
comp->GetBulletRigidBody()->setCollisionShape(shapeComp->GetShape()->GetShape());
}
return comp;
}
Component::RigidBody* PhysicsManager::CreateRigidBody(Entity* owner, const Json::Value& node) {
auto comp = rigidBodyComponents.Create();
comp->entity = owner;
auto mass = node.get("mass", 1.0f).asFloat();
comp->NewBulletRigidBody(mass);
auto shapeComp = comp->entity->GetComponent<Component::Shape>();
if (shapeComp) {
comp->GetBulletRigidBody()->setCollisionShape(shapeComp->GetShape()->GetShape());
}
return comp;
}
Component::Shape* PhysicsManager::CreateShape(Entity* owner) {
auto comp = shapeComponents.Create();
comp->entity = owner;
auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Sphere(1.0f)));
comp->SetShape(shape);
auto rigidBodyComp = comp->entity->GetComponent<Component::RigidBody>();
if (rigidBodyComp) {
rigidBodyComp->GetBulletRigidBody()->setCollisionShape(comp->GetShape()->GetShape());
}
return comp;
}
Component::Shape* PhysicsManager::CreateShape(Entity* owner, const Json::Value& node) {
auto comp = shapeComponents.Create();
comp->entity = owner;
if (node.isMember("sphere")) {
auto sphere = node.get("sphere", {});
auto radius = sphere.get("radius", 1.0f).asFloat();
auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Sphere(radius)));
comp->SetShape(shape);
} else if (node.isMember("plane")) {
auto plane = node.get("plane", {});
auto normal = Json::LoadVec3(plane.get("normal", {}));
auto planeCoeff = plane.get("planeCoeff", 0.0f).asFloat();
auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Plane(normal, planeCoeff)));
comp->SetShape(shape);
} else if (node.isMember("box")) {
auto box = node.get("box", {});
auto width = box.get("width", 1.0f).asFloat();
auto height = box.get("height", 1.0f).asFloat();
auto depth = box.get("depth", 1.0f).asFloat();
auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Box(width, height, depth)));
comp->SetShape(shape);
} else if (node.isMember("cylinder")) {
auto cylinder = node.get("cylinder", {});
auto radius = cylinder.get("radius", 1.0f).asFloat();
auto length = cylinder.get("length", 1.0f).asFloat();
auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Cylinder(radius, length)));
comp->SetShape(shape);
}
auto rigidBodyComp = comp->entity->GetComponent<Component::RigidBody>();
if (rigidBodyComp) {
rigidBodyComp->GetBulletRigidBody()->setCollisionShape(comp->GetShape()->GetShape());
}
return comp;
}
Utility::LockBox<Physics::Trigger> PhysicsManager::CreateTrigger(Component::RigidBody* comp) {
btTransform trans(btQuaternion(0, 0, 0, 1), ::Physics::glmToBt(comp->entity->position));
Physics::Trigger* trigger = new Physics::Trigger(trans);
auto shapeComp = comp->entity->GetComponent<Component::Shape>();
trigger->SetCollisionShape(shapeComp ? shapeComp->GetShape() : nullptr);
triggers.push_back(trigger);
return Utility::LockBox<Physics::Trigger>(triggerLockBoxKey, trigger);
}
void PhysicsManager::SetShape(Component::Shape* comp, std::shared_ptr<::Physics::Shape> shape) {
comp->SetShape(shape);
}
float PhysicsManager::GetMass(Component::RigidBody* comp) {
return comp->GetMass();
}
void PhysicsManager::SetMass(Component::RigidBody* comp, float mass) {
// Setting mass is only valid with a shape because it also sets inertia.
auto shapeComp = comp->entity->GetComponent<Component::Shape>();
if (shapeComp)
comp->SetMass(mass);
}
const std::vector<Component::Shape*>& PhysicsManager::GetShapeComponents() const {
return shapeComponents.GetAll();
}
void PhysicsManager::ClearKilledComponents() {
rigidBodyComponents.ClearKilled(
[this](Component::RigidBody* body) {
dynamicsWorld->removeRigidBody(body->GetBulletRigidBody());
});
shapeComponents.ClearKilled();
}
<commit_msg>Create cone shape from JSON definition.<commit_after>#include "PhysicsManager.hpp"
#include <btBulletDynamicsCommon.h>
#include <glm/gtx/quaternion.hpp>
#include "../Component/RigidBody.hpp"
#include "../Component/Shape.hpp"
#include "../Entity/Entity.hpp"
#include "../Physics/GlmConversion.hpp"
#include "../Physics/Shape.hpp"
#include "../Physics/Trigger.hpp"
#include "../Physics/TriggerObserver.hpp"
#include "../Util/Json.hpp"
PhysicsManager::PhysicsManager() {
// The broadphase is used to quickly cull bodies that will not collide with
// each other, normally by leveraging some simpler (and rough) test such as
// bounding boxes.
broadphase = new btDbvtBroadphase;
// With the collision configuration one can configure collision detection
// algorithms.
collisionConfiguration = new btDefaultCollisionConfiguration;
dispatcher = new btCollisionDispatcher(collisionConfiguration);
// The solver makes objects interact by making use of gravity, collisions,
// game logic supplied forces, and constraints.
solver = new btSequentialImpulseConstraintSolver;
// The dynamics world encompasses objects included in the simulation.
dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
// Y axis up
dynamicsWorld->setGravity(btVector3(0, -9.82, 0));
// Set the lockbox key we will use for lockboxes created in here.
triggerLockBoxKey.reset(new Utility::LockBox<Physics::Trigger>::Key());
}
PhysicsManager::~PhysicsManager() {
delete dynamicsWorld;
delete solver;
delete dispatcher;
delete collisionConfiguration;
delete broadphase;
for (auto t : triggers)
delete t;
}
void PhysicsManager::Update(float deltaTime) {
for (auto rigidBodyComp : rigidBodyComponents.GetAll()) {
if (rigidBodyComp->IsKilled() || !rigidBodyComp->entity->enabled) {
continue;
}
dynamicsWorld->removeRigidBody(rigidBodyComp->GetBulletRigidBody());
rigidBodyComp->SetPosition(rigidBodyComp->entity->GetWorldPosition());
rigidBodyComp->SetOrientation(rigidBodyComp->entity->GetWorldOrientation());
rigidBodyComp->SetMass(rigidBodyComp->GetMass());
dynamicsWorld->addRigidBody(rigidBodyComp->GetBulletRigidBody());
}
dynamicsWorld->stepSimulation(deltaTime, 10);
for (auto trigger : triggers) {
trigger->Process(*dynamicsWorld);
}
}
void PhysicsManager::UpdateEntityTransforms() {
for (auto rigidBodyComp : rigidBodyComponents.GetAll()) {
if (rigidBodyComp->IsKilled() || !rigidBodyComp->entity->enabled)
continue;
Entity* entity = rigidBodyComp->entity;
auto trans = rigidBodyComp->GetBulletRigidBody()->getWorldTransform();
entity->SetWorldPosition(Physics::btToGlm(trans.getOrigin()));
entity->SetWorldOrientation(Physics::btToGlm(trans.getRotation()));
}
}
void PhysicsManager::OnTriggerEnter(Component::RigidBody* trigger, Component::RigidBody* object, std::function<void()> callback) {
auto t = CreateTrigger(trigger);
// Add the callback to the trigger observer
t.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) {
trigger.ForObserver(object->GetBulletRigidBody(), [&callback](Physics::TriggerObserver& observer) {
observer.OnEnter(callback);
});
});
}
void PhysicsManager::OnTriggerRetain(Component::RigidBody* trigger, Component::RigidBody* object, std::function<void()> callback) {
auto t = CreateTrigger(trigger);
// Add the callback to the trigger observer
t.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) {
trigger.ForObserver(object->GetBulletRigidBody(), [&callback](::Physics::TriggerObserver& observer) {
observer.OnRetain(callback);
});
});
}
void PhysicsManager::OnTriggerLeave(Component::RigidBody* trigger, Component::RigidBody* object, std::function<void()> callback) {
auto t = CreateTrigger(trigger);
// Add the callback to the trigger observer
t.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) {
trigger.ForObserver(object->GetBulletRigidBody(), [&callback](::Physics::TriggerObserver& observer) {
observer.OnLeave(callback);
});
});
}
Component::RigidBody* PhysicsManager::CreateRigidBody(Entity* owner) {
auto comp = rigidBodyComponents.Create();
comp->entity = owner;
comp->NewBulletRigidBody(1.0f);
auto shapeComp = comp->entity->GetComponent<Component::Shape>();
if (shapeComp) {
comp->GetBulletRigidBody()->setCollisionShape(shapeComp->GetShape()->GetShape());
}
return comp;
}
Component::RigidBody* PhysicsManager::CreateRigidBody(Entity* owner, const Json::Value& node) {
auto comp = rigidBodyComponents.Create();
comp->entity = owner;
auto mass = node.get("mass", 1.0f).asFloat();
comp->NewBulletRigidBody(mass);
auto shapeComp = comp->entity->GetComponent<Component::Shape>();
if (shapeComp) {
comp->GetBulletRigidBody()->setCollisionShape(shapeComp->GetShape()->GetShape());
}
return comp;
}
Component::Shape* PhysicsManager::CreateShape(Entity* owner) {
auto comp = shapeComponents.Create();
comp->entity = owner;
auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Sphere(1.0f)));
comp->SetShape(shape);
auto rigidBodyComp = comp->entity->GetComponent<Component::RigidBody>();
if (rigidBodyComp) {
rigidBodyComp->GetBulletRigidBody()->setCollisionShape(comp->GetShape()->GetShape());
}
return comp;
}
Component::Shape* PhysicsManager::CreateShape(Entity* owner, const Json::Value& node) {
auto comp = shapeComponents.Create();
comp->entity = owner;
if (node.isMember("sphere")) {
auto sphere = node.get("sphere", {});
auto radius = sphere.get("radius", 1.0f).asFloat();
auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Sphere(radius)));
comp->SetShape(shape);
} else if (node.isMember("plane")) {
auto plane = node.get("plane", {});
auto normal = Json::LoadVec3(plane.get("normal", {}));
auto planeCoeff = plane.get("planeCoeff", 0.0f).asFloat();
auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Plane(normal, planeCoeff)));
comp->SetShape(shape);
} else if (node.isMember("box")) {
auto box = node.get("box", {});
auto width = box.get("width", 1.0f).asFloat();
auto height = box.get("height", 1.0f).asFloat();
auto depth = box.get("depth", 1.0f).asFloat();
auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Box(width, height, depth)));
comp->SetShape(shape);
} else if (node.isMember("cylinder")) {
auto cylinder = node.get("cylinder", {});
auto radius = cylinder.get("radius", 1.0f).asFloat();
auto length = cylinder.get("length", 1.0f).asFloat();
auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Cylinder(radius, length)));
comp->SetShape(shape);
} else if (node.isMember("cone")) {
auto cone = node.get("cone", {});
auto radius = cone.get("radius", 1.0f).asFloat();
auto height = cone.get("height", 1.0f).asFloat();
auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Cone(radius, height)));
comp->SetShape(shape);
}
auto rigidBodyComp = comp->entity->GetComponent<Component::RigidBody>();
if (rigidBodyComp) {
rigidBodyComp->GetBulletRigidBody()->setCollisionShape(comp->GetShape()->GetShape());
}
return comp;
}
Utility::LockBox<Physics::Trigger> PhysicsManager::CreateTrigger(Component::RigidBody* comp) {
btTransform trans(btQuaternion(0, 0, 0, 1), ::Physics::glmToBt(comp->entity->position));
Physics::Trigger* trigger = new Physics::Trigger(trans);
auto shapeComp = comp->entity->GetComponent<Component::Shape>();
trigger->SetCollisionShape(shapeComp ? shapeComp->GetShape() : nullptr);
triggers.push_back(trigger);
return Utility::LockBox<Physics::Trigger>(triggerLockBoxKey, trigger);
}
void PhysicsManager::SetShape(Component::Shape* comp, std::shared_ptr<::Physics::Shape> shape) {
comp->SetShape(shape);
}
float PhysicsManager::GetMass(Component::RigidBody* comp) {
return comp->GetMass();
}
void PhysicsManager::SetMass(Component::RigidBody* comp, float mass) {
// Setting mass is only valid with a shape because it also sets inertia.
auto shapeComp = comp->entity->GetComponent<Component::Shape>();
if (shapeComp)
comp->SetMass(mass);
}
const std::vector<Component::Shape*>& PhysicsManager::GetShapeComponents() const {
return shapeComponents.GetAll();
}
void PhysicsManager::ClearKilledComponents() {
rigidBodyComponents.ClearKilled(
[this](Component::RigidBody* body) {
dynamicsWorld->removeRigidBody(body->GetBulletRigidBody());
});
shapeComponents.ClearKilled();
}
<|endoftext|> |
<commit_before><commit_msg>loplugin:implicitboolconversion<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (c) 2011, Peter Thorson. 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 WebSocket++ Project 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 PETER THORSON BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "../../src/sockets/tls.hpp"
#include "../../src/websocketpp.hpp"
#include <cstring>
//typedef websocketpp::endpoint<websocketpp::role::server,websocketpp::socket::plain> plain_endpoint_type;
//typedef websocketpp::endpoint<websocketpp::role::server,websocketpp::socket::ssl> tls_endpoint_type;
//typedef plain_endpoint_type::handler_ptr plain_handler_ptr;
//typedef tls_endpoint_type::handler_ptr tls_handler_ptr;
using websocketpp::server;
using websocketpp::server_tls;
template <typename endpoint_type>
class echo_server_handler : public endpoint_type::handler {
public:
typedef echo_server_handler<endpoint_type> type;
typedef typename endpoint_type::handler::connection_ptr connection_ptr;
typedef typename endpoint_type::handler::message_ptr message_ptr;
std::string get_password() const {
return "test";
}
boost::shared_ptr<boost::asio::ssl::context> on_tls_init() {
// create a tls context, init, and return.
boost::shared_ptr<boost::asio::ssl::context> context(new boost::asio::ssl::context(boost::asio::ssl::context::tlsv1));
try {
context->set_options(boost::asio::ssl::context::default_workarounds |
boost::asio::ssl::context::no_sslv2 |
boost::asio::ssl::context::single_dh_use);
context->set_password_callback(boost::bind(&type::get_password, this));
context->use_certificate_chain_file("../../src/ssl/server.pem");
context->use_private_key_file("../../src/ssl/server.pem", boost::asio::ssl::context::pem);
context->use_tmp_dh_file("../../src/ssl/dh512.pem");
} catch (std::exception& e) {
std::cout << e.what() << std::endl;
}
return context;
}
void on_message(connection_ptr con,message_ptr msg) {
con->send(msg->get_payload(),msg->get_opcode());
}
void http(connection_ptr con) {
con->set_body("<!DOCTYPE html><html><head><title>WebSocket++ TLS certificate test</title></head><body><h1>WebSocket++ TLS certificate test</h1><p>This is an HTTP(S) page served by a WebSocket++ server for the purposes of confirming that certificates are working since browsers normally silently ignore certificate issues.</p></body></html>");
}
};
int main(int argc, char* argv[]) {
unsigned short port = 9002;
bool tls = false;
if (argc >= 2) {
port = atoi(argv[1]);
if (port == 0) {
std::cout << "Unable to parse port input " << argv[1] << std::endl;
return 1;
}
}
if (argc == 3) {
tls = !strcmp(argv[2],"-tls");
}
try {
if (tls) {
server_tls::handler::ptr handler(new echo_server_handler<server_tls>());
server_tls endpoint(handler);
endpoint.alog().unset_level(websocketpp::log::alevel::ALL);
endpoint.elog().unset_level(websocketpp::log::elevel::ALL);
std::cout << "Starting Secure WebSocket echo server on port "
<< port << std::endl;
endpoint.listen(port);
} else {
server::handler::ptr handler(new echo_server_handler<server>());
server endpoint(handler);
endpoint.alog().unset_level(websocketpp::log::alevel::ALL);
endpoint.elog().unset_level(websocketpp::log::elevel::ALL);
std::cout << "Starting WebSocket echo server on port "
<< port << std::endl;
endpoint.listen(port);
}
} catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
return 0;
}
<commit_msg>removes old api code<commit_after>/*
* Copyright (c) 2011, Peter Thorson. 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 WebSocket++ Project 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 PETER THORSON BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "../../src/sockets/tls.hpp"
#include "../../src/websocketpp.hpp"
#include <cstring>
using websocketpp::server;
using websocketpp::server_tls;
template <typename endpoint_type>
class echo_server_handler : public endpoint_type::handler {
public:
typedef echo_server_handler<endpoint_type> type;
typedef typename endpoint_type::handler::connection_ptr connection_ptr;
typedef typename endpoint_type::handler::message_ptr message_ptr;
std::string get_password() const {
return "test";
}
boost::shared_ptr<boost::asio::ssl::context> on_tls_init() {
// create a tls context, init, and return.
boost::shared_ptr<boost::asio::ssl::context> context(new boost::asio::ssl::context(boost::asio::ssl::context::tlsv1));
try {
context->set_options(boost::asio::ssl::context::default_workarounds |
boost::asio::ssl::context::no_sslv2 |
boost::asio::ssl::context::single_dh_use);
context->set_password_callback(boost::bind(&type::get_password, this));
context->use_certificate_chain_file("../../src/ssl/server.pem");
context->use_private_key_file("../../src/ssl/server.pem", boost::asio::ssl::context::pem);
context->use_tmp_dh_file("../../src/ssl/dh512.pem");
} catch (std::exception& e) {
std::cout << e.what() << std::endl;
}
return context;
}
void on_message(connection_ptr con,message_ptr msg) {
con->send(msg->get_payload(),msg->get_opcode());
}
void http(connection_ptr con) {
con->set_body("<!DOCTYPE html><html><head><title>WebSocket++ TLS certificate test</title></head><body><h1>WebSocket++ TLS certificate test</h1><p>This is an HTTP(S) page served by a WebSocket++ server for the purposes of confirming that certificates are working since browsers normally silently ignore certificate issues.</p></body></html>");
}
};
int main(int argc, char* argv[]) {
unsigned short port = 9002;
bool tls = false;
if (argc >= 2) {
port = atoi(argv[1]);
if (port == 0) {
std::cout << "Unable to parse port input " << argv[1] << std::endl;
return 1;
}
}
if (argc == 3) {
tls = !strcmp(argv[2],"-tls");
}
try {
if (tls) {
server_tls::handler::ptr handler(new echo_server_handler<server_tls>());
server_tls endpoint(handler);
endpoint.alog().unset_level(websocketpp::log::alevel::ALL);
endpoint.elog().unset_level(websocketpp::log::elevel::ALL);
std::cout << "Starting Secure WebSocket echo server on port "
<< port << std::endl;
endpoint.listen(port);
} else {
server::handler::ptr handler(new echo_server_handler<server>());
server endpoint(handler);
endpoint.alog().unset_level(websocketpp::log::alevel::ALL);
endpoint.elog().unset_level(websocketpp::log::elevel::ALL);
std::cout << "Starting WebSocket echo server on port "
<< port << std::endl;
endpoint.listen(port);
}
} catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of meegotouch-controlpanelsoundsettingsapplet.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <QDebug>
#include <MLayout>
#include <MLinearLayoutPolicy>
#include <QGraphicsLinearLayout>
#include <MImageWidget>
#include <MLabel>
#include <MApplicationPage>
#include <QTimer>
#include "alerttoneappletwidget.h"
#include "alerttonewidget.h"
#include "gconfstringcombo.h"
#include "profileintcombo.h"
#include "alerttonevolume.h"
#define DEBUG
#define WARNING
#include "../debug.h"
/******************************************************************************
* Helper functions.
*/
static MContainer *
createEmptyContainer(
QGraphicsWidget *parent,
MLinearLayoutPolicy **p_policy,
QGraphicsWidget **p_centralWidget)
{
MContainer *container = new MContainer (parent);
MLayout *layout;
container->setContentsMargins (0., 0., 0., 0.);
container->setHeaderVisible (false);
(*p_centralWidget) = container->centralWidget();
layout = new MLayout((*p_centralWidget));
layout->setContentsMargins (0., 0., 0., 0.);
(*p_policy) = new MLinearLayoutPolicy(layout, Qt::Vertical);
layout->setLandscapePolicy((*p_policy));
layout->setPortraitPolicy((*p_policy));
return container;
}
MLabel *
addTitleLabel (
QGraphicsWidget *parent,
MLinearLayoutPolicy *targetPolicy,
const char *panelStyleName,
const char *labelStyleName)
{
MContainer *container;
QGraphicsLinearLayout *layout;
MLabel *label;
label = new MLabel;
label->setStyleName (labelStyleName);
container = new MContainer (parent);
container->setContentsMargins (0., 0., 0., 0.);
container->setStyleName (panelStyleName);
container->setHeaderVisible (false);
layout = new QGraphicsLinearLayout (Qt::Horizontal);
layout->setContentsMargins (0., 0., 0., 0.);
layout->addItem (label);
container->centralWidget()->setLayout (layout);
targetPolicy->addItem (container);
return label;
}
/******************************************************************************
* AlertToneAppletWidget implementation
*/
AlertToneAppletWidget::AlertToneAppletWidget(QList<AlertTone *>alertTones, QGraphicsWidget *parent):
AlertToneToplevel(parent),
m_alertTones(alertTones),
m_tones (0),
m_feedback (0),
m_Title (0),
m_EventTonesLabel (0),
m_FeedbackLabel (0)
{
/*
* This should be called later, not from the constructor.
*/
createContents ();
}
void
AlertToneAppletWidget::createContents()
{
QGraphicsWidget *centralWidget = this/*->centralWidget()*/;
MLayout *mainLayout;
MLinearLayoutPolicy *policy;
mainLayout = new MLayout (centralWidget);
policy = new MLinearLayoutPolicy(mainLayout, Qt::Vertical);
policy->setContentsMargins (0., 0., 0., 0.);
policy->setSpacing (0.);
mainLayout->setLandscapePolicy(policy);
mainLayout->setPortraitPolicy(policy);
/*
* The main title
*/
m_Title = addTitleLabel (
centralWidget, policy,
"CommonXLargeHeaderPanelInverted",
"CommonLargeHeaderInverted");
/*
* A secondary title
*/
m_EventTonesLabel = addTitleLabel (
centralWidget, policy,
"CommonHeaderPanelInverted",
"CommonpHeaderInverted");
/*
* A list with the sound file setting widgets.
*/
m_tones = createAlertTonesList(centralWidget);
policy->addItem(m_tones);
/*
* An other secondary title.
*/
m_FeedbackLabel = addTitleLabel (
centralWidget, policy,
"CommonHeaderPanelInverted",
"CommonHeaderInverted");
/*
* The list with the feedback setting widgets.
*/
m_feedback = createFeedbackList(centralWidget);
policy->addItem(m_feedback);
retranslateUi();
}
MContainer *
AlertToneAppletWidget::createFeedbackList(QGraphicsWidget *parent)
{
MContainer *container;
MLinearLayoutPolicy *policy;
QGraphicsWidget *centralWidget;
container = createEmptyContainer(parent, &policy, ¢ralWidget);
ProfileIntCombo *picombo = new ProfileIntCombo(
"keypad.sound.level", true,
centralWidget);
picombo->setObjectName("ProfileIntCombo_keypad.sound.level");
picombo->setStyleName ("CommonComboBoxInverted");
policy->addItem(picombo);
picombo = new ProfileIntCombo(
"system.sound.level", true,
centralWidget);
picombo->setObjectName("ProfileIntCombo_system.sound.level");
picombo->setStyleName ("CommonComboBoxInverted");
policy->addItem(picombo);
GConfStringCombo *combo = new GConfStringCombo(
"/meegotouch/input_feedback/volume/pulse",
QStringList() << "off" << "low" << "medium" << "high",
centralWidget);
combo->setObjectName("GConfStringCombo_pulse");
combo->setStyleName ("CommonComboBoxInverted");
policy->addItem(combo);
combo = new GConfStringCombo(
"/meegotouch/input_feedback/volume/vibra",
QStringList() << "off" << "low" << "medium" << "high",
centralWidget);
combo->setObjectName("GConfStringCombo_vibra");
combo->setStyleName ("CommonComboBoxInverted");
policy->addItem(combo);
container->setObjectName("MConcreateAlertTonePreviewtainer_feedback");
container->setStyleName ("CommonLargePanelInverted");
return container;
}
MContainer *
AlertToneAppletWidget::createAlertTonePreview(
QGraphicsWidget *parent)
{
MContainer *sliderContainer;
QGraphicsLinearLayout *sliderLayout;
AlertToneVolume *slider;
slider = new AlertToneVolume(parent);
sliderContainer = new MContainer;
sliderContainer->setStyleName ("CommonLargePanelInverted");
sliderContainer->setObjectName ("AlertTonePreview");
sliderContainer->setHeaderVisible (false);
sliderLayout = new QGraphicsLinearLayout (Qt::Horizontal);
sliderLayout->addStretch ();
sliderLayout->addItem (slider);
sliderLayout->addStretch ();
sliderLayout->setAlignment (slider, Qt::AlignHCenter);
sliderContainer->centralWidget()->setLayout (sliderLayout);
return sliderContainer;
}
MContainer *
AlertToneAppletWidget::createAlertTonesList(QGraphicsWidget *parent)
{
MContainer *container;
MLinearLayoutPolicy *policy;
QGraphicsWidget *centralWidget;
AlertToneWidget *alertToneWidget;
container = createEmptyContainer(parent, &policy, ¢ralWidget);
/*
* According to the UI spec and NB#189565 the slider goes into this
* container.
*/
policy->addItem(createAlertTonePreview(centralWidget));
/*
* And then the list...
*/
for (int Nix = 0; Nix < m_alertTones.size(); Nix++) {
alertToneWidget = new AlertToneWidget (
m_alertTones[Nix], Nix, this, centralWidget);
alertToneWidget->setObjectName (
"AlertToneWidget_" + m_alertTones[Nix]->key());
policy->addItem(alertToneWidget);
}
container->setObjectName("MContainer_tones");
container->setStyleName ("CommonLargePanelInverted");
return container;
}
void
AlertToneAppletWidget::retranslateUi()
{
if (m_EventTonesLabel)
//% "Event Tones"
m_EventTonesLabel->setText (qtTrId("qtn_sond_event_tones"));
if (m_FeedbackLabel)
//% "Feedback"
m_FeedbackLabel->setText(qtTrId("qtn_sond_feedback"));
if (m_Title)
//% "Sounds"
m_Title->setText(qtTrId("qtn_sond_sounds"));
}
/*
* This virtual method is called when the MApplicationPage for the widget is
* already there, so we can initialize it.
*/
void
AlertToneAppletWidget::polishEvent ()
{
QGraphicsWidget *parent;
MApplicationPage *page = 0;
/*
* We need to find the MApplicationPage among our parents.
*/
parent = parentWidget();
while (parent) {
page = qobject_cast <MApplicationPage *>(parent);
if (page)
break;
parent = parent->parentWidget();
}
if (!page)
return;
/*
* Hiding the home button.
*/
page->setComponentsDisplayMode (
MApplicationPage::HomeButton,
MApplicationPageModel::Hide);
}
<commit_msg>Fixes: NB#228429 (Unreadable lable ”Alert tones” in sounds settings)<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of meegotouch-controlpanelsoundsettingsapplet.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <QDebug>
#include <MLayout>
#include <MLinearLayoutPolicy>
#include <QGraphicsLinearLayout>
#include <MImageWidget>
#include <MLabel>
#include <MApplicationPage>
#include <QTimer>
#include "alerttoneappletwidget.h"
#include "alerttonewidget.h"
#include "gconfstringcombo.h"
#include "profileintcombo.h"
#include "alerttonevolume.h"
#define DEBUG
#define WARNING
#include "../debug.h"
/******************************************************************************
* Helper functions.
*/
static MContainer *
createEmptyContainer(
QGraphicsWidget *parent,
MLinearLayoutPolicy **p_policy,
QGraphicsWidget **p_centralWidget)
{
MContainer *container = new MContainer (parent);
MLayout *layout;
container->setContentsMargins (0., 0., 0., 0.);
container->setHeaderVisible (false);
(*p_centralWidget) = container->centralWidget();
layout = new MLayout((*p_centralWidget));
layout->setContentsMargins (0., 0., 0., 0.);
(*p_policy) = new MLinearLayoutPolicy(layout, Qt::Vertical);
layout->setLandscapePolicy((*p_policy));
layout->setPortraitPolicy((*p_policy));
return container;
}
MLabel *
addTitleLabel (
QGraphicsWidget *parent,
MLinearLayoutPolicy *targetPolicy,
const char *panelStyleName,
const char *labelStyleName)
{
MContainer *container;
QGraphicsLinearLayout *layout;
MLabel *label;
label = new MLabel;
label->setStyleName (labelStyleName);
container = new MContainer (parent);
container->setContentsMargins (0., 0., 0., 0.);
container->setStyleName (panelStyleName);
container->setHeaderVisible (false);
layout = new QGraphicsLinearLayout (Qt::Horizontal);
layout->setContentsMargins (0., 0., 0., 0.);
layout->addItem (label);
container->centralWidget()->setLayout (layout);
targetPolicy->addItem (container);
return label;
}
/******************************************************************************
* AlertToneAppletWidget implementation
*/
AlertToneAppletWidget::AlertToneAppletWidget(QList<AlertTone *>alertTones, QGraphicsWidget *parent):
AlertToneToplevel(parent),
m_alertTones(alertTones),
m_tones (0),
m_feedback (0),
m_Title (0),
m_EventTonesLabel (0),
m_FeedbackLabel (0)
{
/*
* This should be called later, not from the constructor.
*/
createContents ();
}
void
AlertToneAppletWidget::createContents()
{
QGraphicsWidget *centralWidget = this/*->centralWidget()*/;
MLayout *mainLayout;
MLinearLayoutPolicy *policy;
mainLayout = new MLayout (centralWidget);
policy = new MLinearLayoutPolicy(mainLayout, Qt::Vertical);
policy->setContentsMargins (0., 0., 0., 0.);
policy->setSpacing (0.);
mainLayout->setLandscapePolicy(policy);
mainLayout->setPortraitPolicy(policy);
/*
* The main title
*/
m_Title = addTitleLabel (
centralWidget, policy,
"CommonXLargeHeaderPanelInverted",
"CommonLargeHeaderInverted");
/*
* A secondary title
*/
m_EventTonesLabel = addTitleLabel (
centralWidget, policy,
"CommonHeaderPanelInverted",
"CommonHeaderInverted");
/*
* A list with the sound file setting widgets.
*/
m_tones = createAlertTonesList(centralWidget);
policy->addItem(m_tones);
/*
* An other secondary title.
*/
m_FeedbackLabel = addTitleLabel (
centralWidget, policy,
"CommonHeaderPanelInverted",
"CommonHeaderInverted");
/*
* The list with the feedback setting widgets.
*/
m_feedback = createFeedbackList(centralWidget);
policy->addItem(m_feedback);
retranslateUi();
}
MContainer *
AlertToneAppletWidget::createFeedbackList(QGraphicsWidget *parent)
{
MContainer *container;
MLinearLayoutPolicy *policy;
QGraphicsWidget *centralWidget;
container = createEmptyContainer(parent, &policy, ¢ralWidget);
ProfileIntCombo *picombo = new ProfileIntCombo(
"keypad.sound.level", true,
centralWidget);
picombo->setObjectName("ProfileIntCombo_keypad.sound.level");
picombo->setStyleName ("CommonComboBoxInverted");
policy->addItem(picombo);
picombo = new ProfileIntCombo(
"system.sound.level", true,
centralWidget);
picombo->setObjectName("ProfileIntCombo_system.sound.level");
picombo->setStyleName ("CommonComboBoxInverted");
policy->addItem(picombo);
GConfStringCombo *combo = new GConfStringCombo(
"/meegotouch/input_feedback/volume/pulse",
QStringList() << "off" << "low" << "medium" << "high",
centralWidget);
combo->setObjectName("GConfStringCombo_pulse");
combo->setStyleName ("CommonComboBoxInverted");
policy->addItem(combo);
combo = new GConfStringCombo(
"/meegotouch/input_feedback/volume/vibra",
QStringList() << "off" << "low" << "medium" << "high",
centralWidget);
combo->setObjectName("GConfStringCombo_vibra");
combo->setStyleName ("CommonComboBoxInverted");
policy->addItem(combo);
container->setObjectName("MConcreateAlertTonePreviewtainer_feedback");
container->setStyleName ("CommonLargePanelInverted");
return container;
}
MContainer *
AlertToneAppletWidget::createAlertTonePreview(
QGraphicsWidget *parent)
{
MContainer *sliderContainer;
QGraphicsLinearLayout *sliderLayout;
AlertToneVolume *slider;
slider = new AlertToneVolume(parent);
sliderContainer = new MContainer;
sliderContainer->setStyleName ("CommonLargePanelInverted");
sliderContainer->setObjectName ("AlertTonePreview");
sliderContainer->setHeaderVisible (false);
sliderLayout = new QGraphicsLinearLayout (Qt::Horizontal);
sliderLayout->addStretch ();
sliderLayout->addItem (slider);
sliderLayout->addStretch ();
sliderLayout->setAlignment (slider, Qt::AlignHCenter);
sliderContainer->centralWidget()->setLayout (sliderLayout);
return sliderContainer;
}
MContainer *
AlertToneAppletWidget::createAlertTonesList(QGraphicsWidget *parent)
{
MContainer *container;
MLinearLayoutPolicy *policy;
QGraphicsWidget *centralWidget;
AlertToneWidget *alertToneWidget;
container = createEmptyContainer(parent, &policy, ¢ralWidget);
/*
* According to the UI spec and NB#189565 the slider goes into this
* container.
*/
policy->addItem(createAlertTonePreview(centralWidget));
/*
* And then the list...
*/
for (int Nix = 0; Nix < m_alertTones.size(); Nix++) {
alertToneWidget = new AlertToneWidget (
m_alertTones[Nix], Nix, this, centralWidget);
alertToneWidget->setObjectName (
"AlertToneWidget_" + m_alertTones[Nix]->key());
policy->addItem(alertToneWidget);
}
container->setObjectName("MContainer_tones");
container->setStyleName ("CommonLargePanelInverted");
return container;
}
void
AlertToneAppletWidget::retranslateUi()
{
if (m_EventTonesLabel)
//% "Event Tones"
m_EventTonesLabel->setText (qtTrId("qtn_sond_event_tones"));
if (m_FeedbackLabel)
//% "Feedback"
m_FeedbackLabel->setText(qtTrId("qtn_sond_feedback"));
if (m_Title)
//% "Sounds"
m_Title->setText(qtTrId("qtn_sond_sounds"));
}
/*
* This virtual method is called when the MApplicationPage for the widget is
* already there, so we can initialize it.
*/
void
AlertToneAppletWidget::polishEvent ()
{
QGraphicsWidget *parent;
MApplicationPage *page = 0;
/*
* We need to find the MApplicationPage among our parents.
*/
parent = parentWidget();
while (parent) {
page = qobject_cast <MApplicationPage *>(parent);
if (page)
break;
parent = parent->parentWidget();
}
if (!page)
return;
/*
* Hiding the home button.
*/
page->setComponentsDisplayMode (
MApplicationPage::HomeButton,
MApplicationPageModel::Hide);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "primitives/block.h"
#include "hash.h"
#include "tinyformat.h"
#include "utilstrencodings.h"
#include "crypto/common.h"
#include "chainparams.h"
unsigned char GetNfactor(int64_t nTimestamp) {
int l = 0;
if (nTimestamp <= Params().GetConsensus().nChainStartTime)
return Params().GetConsensus().nMinNFactor;
int64_t s = nTimestamp - Params().GetConsensus().nChainStartTime;
while ((s >> 1) > 3) {
l += 1;
s >>= 1;
}
s &= 3;
int n = (l * 158 + s * 28 - 2670) / 100;
if (n < 0) n = 0;
if (n > 255)
printf( "GetNfactor(%lld) - something wrong(n == %d)\n", nTimestamp, n );
unsigned char N = (unsigned char) n;
//printf("GetNfactor: %d -> %d %d : %d / %d\n", nTimestamp - nChainStartTime, l, s, n, min(max(N, minNfactor), maxNfactor));
return std::min(std::max(N, Params().GetConsensus().nMinNFactor), Params().GetConsensus().nMaxNFactor);
}
uint256 CBlockHeader::GetHash() const
{
return SerializeHash(*this);
}
uint256 CBlockHeader::GetPoWHash(int nHeight) const
{
uint256 thash;
if((Params().NetworkIDString() == CBaseChainParams::TESTNET && nHeight >= 0) || nHeight >= 347000) // New Lyra2re2 Testnet
{
lyra2re2_hash(BEGIN(nVersion), BEGIN(thash));
}
else if(nHeight >= 208301)
{
lyra2re_hash(BEGIN(nVersion), BEGIN(thash));
}
else
{
scrypt_N_1_1_256(BEGIN(nVersion), BEGIN(thash), GetNfactor(nTime));
}
return thash;
}
std::string CBlock::ToString() const
{
std::stringstream s;
s << strprintf("CBlock(hash=%s, ver=0x%08x, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\n",
GetHash().ToString(),
nVersion,
hashPrevBlock.ToString(),
hashMerkleRoot.ToString(),
nTime, nBits, nNonce,
vtx.size());
for (unsigned int i = 0; i < vtx.size(); i++)
{
s << " " << vtx[i]->ToString() << "\n";
}
return s.str();
}
int64_t GetBlockWeight(const CBlock& block)
{
// This implements the weight = (stripped_size * 4) + witness_size formula,
// using only serialization with and without witness data. As witness_size
// is equal to total_size - stripped_size, this formula is identical to:
// weight = (stripped_size * 3) + total_size.
return ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) * (WITNESS_SCALE_FACTOR - 1) + ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION);
}
<commit_msg>Set to SHA256<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "primitives/block.h"
#include "hash.h"
#include "tinyformat.h"
#include "utilstrencodings.h"
#include "crypto/common.h"
#include "chainparams.h"
uint256 CBlockHeader::GetHash() const
{
return SerializeHash(*this);
}
uint256 CBlockHeader::GetPoWHash(int nHeight) const
{
return SerializeHash(*this);
}
std::string CBlock::ToString() const
{
std::stringstream s;
s << strprintf("CBlock(hash=%s, ver=0x%08x, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\n",
GetHash().ToString(),
nVersion,
hashPrevBlock.ToString(),
hashMerkleRoot.ToString(),
nTime, nBits, nNonce,
vtx.size());
for (unsigned int i = 0; i < vtx.size(); i++)
{
s << " " << vtx[i]->ToString() << "\n";
}
return s.str();
}
int64_t GetBlockWeight(const CBlock& block)
{
// This implements the weight = (stripped_size * 4) + witness_size formula,
// using only serialization with and without witness data. As witness_size
// is equal to total_size - stripped_size, this formula is identical to:
// weight = (stripped_size * 3) + total_size.
return ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) * (WITNESS_SCALE_FACTOR - 1) + ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2015-2019 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "primitives/block.h"
#include "hash.h"
#include "script/standard.h"
#include "script/sign.h"
#include "tinyformat.h"
#include "utilstrencodings.h"
#include "util.h"
uint256 CBlockHeader::GetHash() const
{
#if defined(WORDS_BIGENDIAN)
if (nVersion < 4) {
uint8_t data[80];
WriteLE32(&data[0], nVersion);
memcpy(&data[4], hashPrevBlock.begin(), hashPrevBlock.size());
memcpy(&data[36], hashMerkleRoot.begin(), hashMerkleRoot.size());
WriteLE32(&data[68], nTime);
WriteLE32(&data[72], nBits);
WriteLE32(&data[76], nNonce);
return HashQuark(data, data + 80);
} else if (nVersion < 7) {
uint8_t data[112];
WriteLE32(&data[0], nVersion);
memcpy(&data[4], hashPrevBlock.begin(), hashPrevBlock.size());
memcpy(&data[36], hashMerkleRoot.begin(), hashMerkleRoot.size());
WriteLE32(&data[68], nTime);
WriteLE32(&data[72], nBits);
WriteLE32(&data[76], nNonce);
memcpy(&data[80], hashMerkleRoot.begin(), hashMerkleRoot.size());
return Hash(data, data + 80);
} else {
uint8_t data[80];
WriteLE32(&data[0], nVersion);
memcpy(&data[4], hashPrevBlock.begin(), hashPrevBlock.size());
memcpy(&data[36], hashMerkleRoot.begin(), hashMerkleRoot.size());
WriteLE32(&data[68], nTime);
WriteLE32(&data[72], nBits);
WriteLE32(&data[76], nNonce);
return Hash(data, data + 80);
}
#else // Can take shortcut for little endian
if (nVersion < 4)
return HashQuark(BEGIN(nVersion), END(nNonce));
if (nVersion < 7)
return Hash(BEGIN(nVersion), END(nAccumulatorCheckpoint));
return Hash(BEGIN(nVersion), END(nNonce));
#endif
}
std::string CBlock::ToString() const
{
std::stringstream s;
s << strprintf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\n",
GetHash().ToString(),
nVersion,
hashPrevBlock.ToString(),
hashMerkleRoot.ToString(),
nTime, nBits, nNonce,
vtx.size());
for (unsigned int i = 0; i < vtx.size(); i++)
{
s << " " << vtx[i].ToString() << "\n";
}
return s.str();
}
void CBlock::print() const
{
LogPrintf("%s", ToString());
}
bool CBlock::IsZerocoinStake() const
{
return IsProofOfStake() && vtx[1].HasZerocoinSpendInputs();
}
<commit_msg>Replace CBlockHeader::GetHash with call to SerializeHash<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2015-2019 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "primitives/block.h"
#include "hash.h"
#include "script/standard.h"
#include "script/sign.h"
#include "tinyformat.h"
#include "utilstrencodings.h"
#include "util.h"
uint256 CBlockHeader::GetHash() const
{
if (nVersion < 4) {
#if defined(WORDS_BIGENDIAN)
uint8_t data[80];
WriteLE32(&data[0], nVersion);
memcpy(&data[4], hashPrevBlock.begin(), hashPrevBlock.size());
memcpy(&data[36], hashMerkleRoot.begin(), hashMerkleRoot.size());
WriteLE32(&data[68], nTime);
WriteLE32(&data[72], nBits);
WriteLE32(&data[76], nNonce);
return HashQuark(data, data + 80);
#else // Can take shortcut for little endian
return HashQuark(BEGIN(nVersion), END(nNonce));
#endif
}
// version >= 4
return SerializeHash(*this);
}
std::string CBlock::ToString() const
{
std::stringstream s;
s << strprintf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\n",
GetHash().ToString(),
nVersion,
hashPrevBlock.ToString(),
hashMerkleRoot.ToString(),
nTime, nBits, nNonce,
vtx.size());
for (unsigned int i = 0; i < vtx.size(); i++)
{
s << " " << vtx[i].ToString() << "\n";
}
return s.str();
}
void CBlock::print() const
{
LogPrintf("%s", ToString());
}
bool CBlock::IsZerocoinStake() const
{
return IsProofOfStake() && vtx[1].HasZerocoinSpendInputs();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014-2017 The Dash Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <privatesend-util.h>
#include <util.h>
CWallet *GetWalletForPSRequest()
{
// TODO: Some way to access secondary wallets
return vpwallets.empty() ? nullptr : vpwallets[0];
}
CKeyHolder::CKeyHolder(CWallet* pwallet) :
reserveKey(pwallet)
{
reserveKey.GetReservedKey(pubKey);
}
void CKeyHolder::KeepKey()
{
reserveKey.KeepKey();
}
void CKeyHolder::ReturnKey()
{
reserveKey.ReturnKey();
}
CScript CKeyHolder::GetScriptForDestination() const
{
return ::GetScriptForDestination(pubKey.GetID());
}
CScript CKeyHolderStorage::AddKey(CWallet* pwallet)
{
LOCK(cs_storage);
storage.emplace_back(std::unique_ptr<CKeyHolder>(new CKeyHolder(pwallet)));
LogPrintf("CKeyHolderStorage::%s -- storage size %lld\n", __func__, storage.size());
return storage.back()->GetScriptForDestination();
}
void CKeyHolderStorage::KeepAll(){
LOCK(cs_storage);
if (storage.size() > 0) {
for (auto &key : storage) {
key->KeepKey();
}
LogPrintf("CKeyHolderStorage::%s -- %lld keys kept\n", __func__, storage.size());
storage.clear();
}
}
void CKeyHolderStorage::ReturnAll()
{
LOCK(cs_storage);
if (storage.size() > 0) {
for (auto &key : storage) {
key->ReturnKey();
}
LogPrintf("CKeyHolderStorage::%s -- %lld keys returned\n", __func__, storage.size());
storage.clear();
}
}
<commit_msg>Don't hold cs_storage in CKeyHolderStorage while calling functions which might lock cs_wallet (#2000)<commit_after>// Copyright (c) 2014-2017 The Dash Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <privatesend-util.h>
#include <util.h>
CWallet *GetWalletForPSRequest()
{
// TODO: Some way to access secondary wallets
return vpwallets.empty() ? nullptr : vpwallets[0];
}
CKeyHolder::CKeyHolder(CWallet* pwallet) :
reserveKey(pwallet)
{
reserveKey.GetReservedKey(pubKey);
}
void CKeyHolder::KeepKey()
{
reserveKey.KeepKey();
}
void CKeyHolder::ReturnKey()
{
reserveKey.ReturnKey();
}
CScript CKeyHolder::GetScriptForDestination() const
{
return ::GetScriptForDestination(pubKey.GetID());
}
CScript CKeyHolderStorage::AddKey(CWallet* pwallet)
{
auto keyHolder = std::unique_ptr<CKeyHolder>(new CKeyHolder(pwallet));
auto script = keyHolder->GetScriptForDestination();
LOCK(cs_storage);
storage.emplace_back(std::move(keyHolder));
LogPrintf("CKeyHolderStorage::%s -- storage size %lld\n", __func__, storage.size());
return script;
}
void CKeyHolderStorage::KeepAll()
{
std::vector<std::unique_ptr<CKeyHolder>> tmp;
{
// don't hold cs_storage while calling KeepKey(), which might lock cs_wallet
LOCK(cs_storage);
std::swap(storage, tmp);
}
if (tmp.size() > 0) {
for (auto &key : tmp) {
key->KeepKey();
}
LogPrintf("CKeyHolderStorage::%s -- %lld keys kept\n", __func__, tmp.size());
}
}
void CKeyHolderStorage::ReturnAll()
{
std::vector<std::unique_ptr<CKeyHolder>> tmp;
{
// don't hold cs_storage while calling ReturnKey(), which might lock cs_wallet
LOCK(cs_storage);
std::swap(storage, tmp);
}
if (tmp.size() > 0) {
for (auto &key : tmp) {
key->ReturnKey();
}
LogPrintf("CKeyHolderStorage::%s -- %lld keys returned\n", __func__, tmp.size());
}
}
<|endoftext|> |
<commit_before>#include "plugin.h"
#include "api/include/pd_ui.h"
#include "api/include/pd_view.h"
#include "api/plugin_instance.h"
#include "core/alloc.h"
#include "core/log.h"
#include "core/math.h"
#include <imgui.h>
#include <string.h>
#include <stdio.h>
struct ImGuiWindow;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct PrivateData
{
ImGuiWindow* window;
const char* name;
bool showWindow;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void separator()
{
ImGui::Separator();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void sameLine(int columnX, int spacingW)
{
ImGui::SameLine(columnX, spacingW);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void spacing()
{
ImGui::Spacing();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void columns(int count, const char* id, int border)
{
ImGui::Columns(count, id, !!border);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void nextColumn()
{
ImGui::NextColumn();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static float getColumnOffset(int columnIndex)
{
return ImGui::GetColumnOffset(columnIndex);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void setColumnOffset(int columnIndex, float offset)
{
return ImGui::SetColumnOffset(columnIndex, offset);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static float getColumnWidth(int columnIndex)
{
return ImGui::GetColumnWidth(columnIndex);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static PDVec2 getCursorPos()
{
ImVec2 t = ImGui::GetCursorPos();
PDVec2 r = { t.x, t.y };
return r;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void setCursorPos(PDVec2 pos)
{
ImGui::SetCursorPos(ImVec2(pos.x, pos.y));
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void setCursorPosX(float x)
{
ImGui::SetCursorPosX(x);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void setCursorPosY(float y)
{
ImGui::SetCursorPosY(y);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static PDVec2 getCursorScreenPos()
{
ImVec2 t = ImGui::GetCursorScreenPos();
PDVec2 r = { t.x, t.y };
return r;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void alignFirstTextHeightToWidgets()
{
ImGui::AlignFirstTextHeightToWidgets();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static float getTextLineSpacing()
{
return ImGui::GetTextLineSpacing();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static float getTextLineHeight()
{
return ImGui::GetTextLineHeight();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static int button(const char* label)
{
return ImGui::Button(label);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void text(const char* format, ...)
{
va_list ap;
va_start(ap, format);
ImGui::TextV(format, ap);
va_end(ap);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static bool scEditText(const char* label, char* buf, int buf_size, float xSize, float ySize, int flags,
void (*callback)(void*), void* userData)
{
return ImGui::ScInputText(label, buf, (size_t)buf_size, xSize, ySize, flags, callback, userData);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static int buttonSize(const char* label, int width, int height, int repeatWhenHeld)
{
return ImGui::Button(label, ImVec2((float)width, (float)height), !!repeatWhenHeld);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void fillRect(PDRect rect, unsigned int color)
{
ImGui::FillRect(ImVec2(rect.x, rect.y), ImVec2(rect.width, rect.height), color);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static float getTextWidth(const char* text, const char* textEnd)
{
return ImGui::GetTextWidth(text, textEnd);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static PDVec2 getWindowSize()
{
ImVec2 size = ImGui::GetWindowSize();
PDVec2 r = { size.x, size.y };
return r;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static float getFontHeight()
{
return 12.0f; // TODO: Fix me
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static float getFontWidth()
{
return 12.0f; // TODO: Fix me
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static PDVec2 getMousePos()
{
ImVec2 pos = ImGui::GetRelativeMousePos();
PDVec2 r = { pos.x, pos.y };
return r;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static PDVec2 getMouseScreenPos()
{
ImVec2 pos = ImGui::GetMousePos();
PDVec2 r = { pos.x, pos.y };
return r;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static int isMouseClicked(int button, int repeat)
{
return ImGui::IsMouseClicked(button, !!repeat);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static int isMouseDoubleClicked(int button)
{
return ImGui::IsMouseDoubleClicked(button);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static int isMouseHoveringBox(PDVec2 boxMin, PDVec2 boxMax)
{
return ImGui::IsMouseHoveringBox(ImVec2(boxMin.x, boxMin.y), ImVec2(boxMax.x, boxMax.y));
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static int isKeyDown(int key, int repeat)
{
return ImGui::IsFocusWindowKeyDown(key, !!repeat);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static int getKeyModifier()
{
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
char* buildName(const char* pluginName, int id)
{
char idBuffer[32];
int nameLen = (int)strlen(pluginName);
sprintf(idBuffer, "%d", id);
char* name = (char*)alloc_zero(nameLen + (int)strlen(idBuffer) + 2); // + 2 for space and end marker
sprintf(name, "%s %s", pluginName, idBuffer);
return name;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void PluginUI_init(ViewPluginInstance* pluginInstance)
{
PrivateData* data = (PrivateData*)alloc_zero(sizeof(PrivateData));
PDUI* uiInstance = &pluginInstance->ui;
data->showWindow = true;
memset(uiInstance, 0, sizeof(PDUI));
// TODO: These functions are static, we shouldn't need to do it like this
uiInstance->columns = columns;
uiInstance->nextColumn = nextColumn;
uiInstance->sameLine = sameLine;
uiInstance->text = text;
uiInstance->scInputText = scEditText;
uiInstance->button = button;
uiInstance->buttonSize = buttonSize;
uiInstance->separator = separator;
uiInstance->sameLine = sameLine;
uiInstance->spacing = spacing;
uiInstance->columns = columns;
uiInstance->nextColumn = nextColumn;
uiInstance->getColumnOffset = getColumnOffset;
uiInstance->setColumnOffset = setColumnOffset;
uiInstance->getColumnWidth = getColumnWidth;
uiInstance->getCursorPos = getCursorPos;
uiInstance->setCursorPos = setCursorPos;
uiInstance->setCursorPosX = setCursorPosX;
uiInstance->setCursorPosY = setCursorPosY;
uiInstance->getCursorScreenPos = getCursorScreenPos;
uiInstance->alignFirstTextHeightToWidgets = alignFirstTextHeightToWidgets;
uiInstance->getTextLineSpacing = getTextLineSpacing;
uiInstance->getTextLineHeight = getTextLineHeight;
uiInstance->fillRect = fillRect;
uiInstance->getTextWidth = getTextWidth;
uiInstance->getWindowSize = getWindowSize;
uiInstance->getFontHeight = getFontHeight;
uiInstance->getFontWidth = getFontWidth;
uiInstance->getMousePos = getMousePos;
uiInstance->getMouseScreenPos = getMouseScreenPos;
uiInstance->isMouseClicked = isMouseClicked;
uiInstance->isMouseDoubleClicked = isMouseDoubleClicked;
uiInstance->isMouseHoveringBox = isMouseHoveringBox;
uiInstance->isKeyDown = isKeyDown;
uiInstance->getKeyModifier = getKeyModifier;
uiInstance->privateData = alloc_zero(sizeof(PrivateData));
data->name = buildName(pluginInstance->plugin->name, pluginInstance->count);
data->window = 0; //ImGui::FindOrCreateWindow(data->name, ImVec2(400, 400), 0);
uiInstance->privateData = data;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PluginUIState PluginUI_updateInstance(ViewPluginInstance* instance, PDReader* reader, PDWriter* writer)
{
PDUI* uiInstance = &instance->ui;
PrivateData* data = (PrivateData*)uiInstance->privateData;
ImGui::SetNextWindowPos(ImVec2((float)instance->rect.x, (float)instance->rect.y));
ImGui::SetNextWindowSize(ImVec2((float)instance->rect.width - 4, (float)instance->rect.height - 4));
ImGui::Begin(data->name, &data->showWindow, ImVec2(0, 0), true, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove);
instance->plugin->update(instance->userData, uiInstance, reader, writer);
ImGui::End();
if (!data->showWindow)
return PluginUIState_CloseView;
return PluginUIState_None;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void PluginUI_getWindowRect(ViewPluginInstance* instance, FloatRect* rect)
{
rect->x = (float)instance->rect.x;
rect->y = (float)instance->rect.y;
rect->width = (float)instance->rect.width;
rect->height = (float)instance->rect.height;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void PluginUI_setWindowRect(ViewPluginInstance* instance, FloatRect* rect)
{
instance->rect.x = (int)rect->x;
instance->rect.y = (int)rect->y;
instance->rect.width = (int)rect->width;
instance->rect.height = (int)rect->height;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
bool PluginUI_isActiveWindow(ViewPluginInstance* instance)
{
(void)instance;
PDUI* uiInstance = &instance->ui;
PrivateData* data = (PrivateData*)uiInstance->privateData;
return ImGui::IsActiveWindow(data->window);
}
*/
<commit_msg>Use NoCollapse flags for plugin windows<commit_after>#include "plugin.h"
#include "api/include/pd_ui.h"
#include "api/include/pd_view.h"
#include "api/plugin_instance.h"
#include "core/alloc.h"
#include "core/log.h"
#include "core/math.h"
#include <imgui.h>
#include <string.h>
#include <stdio.h>
struct ImGuiWindow;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct PrivateData
{
ImGuiWindow* window;
const char* name;
bool showWindow;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void separator()
{
ImGui::Separator();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void sameLine(int columnX, int spacingW)
{
ImGui::SameLine(columnX, spacingW);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void spacing()
{
ImGui::Spacing();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void columns(int count, const char* id, int border)
{
ImGui::Columns(count, id, !!border);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void nextColumn()
{
ImGui::NextColumn();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static float getColumnOffset(int columnIndex)
{
return ImGui::GetColumnOffset(columnIndex);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void setColumnOffset(int columnIndex, float offset)
{
return ImGui::SetColumnOffset(columnIndex, offset);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static float getColumnWidth(int columnIndex)
{
return ImGui::GetColumnWidth(columnIndex);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static PDVec2 getCursorPos()
{
ImVec2 t = ImGui::GetCursorPos();
PDVec2 r = { t.x, t.y };
return r;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void setCursorPos(PDVec2 pos)
{
ImGui::SetCursorPos(ImVec2(pos.x, pos.y));
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void setCursorPosX(float x)
{
ImGui::SetCursorPosX(x);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void setCursorPosY(float y)
{
ImGui::SetCursorPosY(y);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static PDVec2 getCursorScreenPos()
{
ImVec2 t = ImGui::GetCursorScreenPos();
PDVec2 r = { t.x, t.y };
return r;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void alignFirstTextHeightToWidgets()
{
ImGui::AlignFirstTextHeightToWidgets();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static float getTextLineSpacing()
{
return ImGui::GetTextLineSpacing();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static float getTextLineHeight()
{
return ImGui::GetTextLineHeight();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static int button(const char* label)
{
return ImGui::Button(label);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void text(const char* format, ...)
{
va_list ap;
va_start(ap, format);
ImGui::TextV(format, ap);
va_end(ap);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static bool scEditText(const char* label, char* buf, int buf_size, float xSize, float ySize, int flags,
void (*callback)(void*), void* userData)
{
return ImGui::ScInputText(label, buf, (size_t)buf_size, xSize, ySize, flags, callback, userData);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static int buttonSize(const char* label, int width, int height, int repeatWhenHeld)
{
return ImGui::Button(label, ImVec2((float)width, (float)height), !!repeatWhenHeld);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void fillRect(PDRect rect, unsigned int color)
{
ImGui::FillRect(ImVec2(rect.x, rect.y), ImVec2(rect.width, rect.height), color);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static float getTextWidth(const char* text, const char* textEnd)
{
return ImGui::GetTextWidth(text, textEnd);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static PDVec2 getWindowSize()
{
ImVec2 size = ImGui::GetWindowSize();
PDVec2 r = { size.x, size.y };
return r;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static float getFontHeight()
{
return 12.0f; // TODO: Fix me
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static float getFontWidth()
{
return 12.0f; // TODO: Fix me
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static PDVec2 getMousePos()
{
ImVec2 pos = ImGui::GetRelativeMousePos();
PDVec2 r = { pos.x, pos.y };
return r;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static PDVec2 getMouseScreenPos()
{
ImVec2 pos = ImGui::GetMousePos();
PDVec2 r = { pos.x, pos.y };
return r;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static int isMouseClicked(int button, int repeat)
{
return ImGui::IsMouseClicked(button, !!repeat);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static int isMouseDoubleClicked(int button)
{
return ImGui::IsMouseDoubleClicked(button);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static int isMouseHoveringBox(PDVec2 boxMin, PDVec2 boxMax)
{
return ImGui::IsMouseHoveringBox(ImVec2(boxMin.x, boxMin.y), ImVec2(boxMax.x, boxMax.y));
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static int isKeyDown(int key, int repeat)
{
return ImGui::IsFocusWindowKeyDown(key, !!repeat);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static int getKeyModifier()
{
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
char* buildName(const char* pluginName, int id)
{
char idBuffer[32];
int nameLen = (int)strlen(pluginName);
sprintf(idBuffer, "%d", id);
char* name = (char*)alloc_zero(nameLen + (int)strlen(idBuffer) + 2); // + 2 for space and end marker
sprintf(name, "%s %s", pluginName, idBuffer);
return name;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void PluginUI_init(ViewPluginInstance* pluginInstance)
{
PrivateData* data = (PrivateData*)alloc_zero(sizeof(PrivateData));
PDUI* uiInstance = &pluginInstance->ui;
data->showWindow = true;
memset(uiInstance, 0, sizeof(PDUI));
// TODO: These functions are static, we shouldn't need to do it like this
uiInstance->columns = columns;
uiInstance->nextColumn = nextColumn;
uiInstance->sameLine = sameLine;
uiInstance->text = text;
uiInstance->scInputText = scEditText;
uiInstance->button = button;
uiInstance->buttonSize = buttonSize;
uiInstance->separator = separator;
uiInstance->sameLine = sameLine;
uiInstance->spacing = spacing;
uiInstance->columns = columns;
uiInstance->nextColumn = nextColumn;
uiInstance->getColumnOffset = getColumnOffset;
uiInstance->setColumnOffset = setColumnOffset;
uiInstance->getColumnWidth = getColumnWidth;
uiInstance->getCursorPos = getCursorPos;
uiInstance->setCursorPos = setCursorPos;
uiInstance->setCursorPosX = setCursorPosX;
uiInstance->setCursorPosY = setCursorPosY;
uiInstance->getCursorScreenPos = getCursorScreenPos;
uiInstance->alignFirstTextHeightToWidgets = alignFirstTextHeightToWidgets;
uiInstance->getTextLineSpacing = getTextLineSpacing;
uiInstance->getTextLineHeight = getTextLineHeight;
uiInstance->fillRect = fillRect;
uiInstance->getTextWidth = getTextWidth;
uiInstance->getWindowSize = getWindowSize;
uiInstance->getFontHeight = getFontHeight;
uiInstance->getFontWidth = getFontWidth;
uiInstance->getMousePos = getMousePos;
uiInstance->getMouseScreenPos = getMouseScreenPos;
uiInstance->isMouseClicked = isMouseClicked;
uiInstance->isMouseDoubleClicked = isMouseDoubleClicked;
uiInstance->isMouseHoveringBox = isMouseHoveringBox;
uiInstance->isKeyDown = isKeyDown;
uiInstance->getKeyModifier = getKeyModifier;
uiInstance->privateData = alloc_zero(sizeof(PrivateData));
data->name = buildName(pluginInstance->plugin->name, pluginInstance->count);
data->window = 0; //ImGui::FindOrCreateWindow(data->name, ImVec2(400, 400), 0);
uiInstance->privateData = data;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PluginUIState PluginUI_updateInstance(ViewPluginInstance* instance, PDReader* reader, PDWriter* writer)
{
PDUI* uiInstance = &instance->ui;
PrivateData* data = (PrivateData*)uiInstance->privateData;
ImGui::SetNextWindowPos(ImVec2((float)instance->rect.x, (float)instance->rect.y));
ImGui::SetNextWindowSize(ImVec2((float)instance->rect.width - 4, (float)instance->rect.height - 4));
ImGui::Begin(data->name, &data->showWindow, ImVec2(0, 0), true, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove);
instance->plugin->update(instance->userData, uiInstance, reader, writer);
ImGui::End();
if (!data->showWindow)
return PluginUIState_CloseView;
return PluginUIState_None;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void PluginUI_getWindowRect(ViewPluginInstance* instance, FloatRect* rect)
{
rect->x = (float)instance->rect.x;
rect->y = (float)instance->rect.y;
rect->width = (float)instance->rect.width;
rect->height = (float)instance->rect.height;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void PluginUI_setWindowRect(ViewPluginInstance* instance, FloatRect* rect)
{
instance->rect.x = (int)rect->x;
instance->rect.y = (int)rect->y;
instance->rect.width = (int)rect->width;
instance->rect.height = (int)rect->height;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
bool PluginUI_isActiveWindow(ViewPluginInstance* instance)
{
(void)instance;
PDUI* uiInstance = &instance->ui;
PrivateData* data = (PrivateData*)uiInstance->privateData;
return ImGui::IsActiveWindow(data->window);
}
*/
<|endoftext|> |
<commit_before>#include "progress.hpp"
#include "errors.hpp"
#include "utils2.hpp"
progress_bar_t::progress_bar_t(std::string activity, int redraw_interval_ms = 100)
: repeating_timer_t(redraw_interval_ms, boost::bind(&progress_bar_t::refresh, this)),
activity(activity), redraw_interval_ms(redraw_interval_ms), start_time(get_ticks()),
total_refreshes(0)
{ }
void progress_bar_t::refresh() {
total_refreshes++;
reset_bar();
draw();
reset_bar();
}
void progress_bar_t::reset_bar() {
printf("\r");
fflush(stdout);
}
/* progress should be in [0.0,1.0] */
void progress_bar_t::draw_bar(float progress, int eta) {
int percent_done = int(progress * 100);
printf("%s: ", activity.c_str());
printf("[");
for (int i = 1; i < 49; i++) {
if (i % 5 == 0) printf("%d", 2 * i);
else if (i == percent_done / 2) printf(">");
else if (i < percent_done / 2) printf("=");
else printf(" ");
}
printf("] ");
if (eta == -1 && progress > 0) {
//Do automatic linear interpolation for eta
eta = ((1.0f / progress) - 1) * ticks_to_secs(get_ticks() - start_time);
}
if (eta == -1) printf("ETA: -");
else printf("ETA: %01d:%02d:%02d", (eta / 3600), (eta / 60) % 60, eta % 60);
printf(" "); //make sure we don't leave an characters behind
fflush(stdout);
}
counter_progress_bar_t::counter_progress_bar_t(std::string activity, int expected_count, int redraw_interval_ms)
: progress_bar_t(activity, redraw_interval_ms), count(0), expected_count(expected_count)
{ }
void counter_progress_bar_t::draw() {
progress_bar_t::draw_bar(float(count) / float(expected_count), -1);
}
void counter_progress_bar_t::operator++(int) {
count++;
}
file_progress_bar_t::file_progress_bar_t(std::string activity, FILE *file, int redraw_interval_ms)
: progress_bar_t(activity, redraw_interval_ms), file(file)
{
struct stat file_stats;
fstat(fileno(file), &file_stats);
file_size = file_stats.st_size;
}
void file_progress_bar_t::draw() {
progress_bar_t::draw_bar(float(ftell(file)) / float(file_size), -1);
}
<commit_msg>Include <sys/stat.h> in progress/progress.cc.<commit_after>#include "progress.hpp"
#include "errors.hpp"
#include "utils2.hpp"
#include <sys/stat.h>
progress_bar_t::progress_bar_t(std::string activity, int redraw_interval_ms = 100)
: repeating_timer_t(redraw_interval_ms, boost::bind(&progress_bar_t::refresh, this)),
activity(activity), redraw_interval_ms(redraw_interval_ms), start_time(get_ticks()),
total_refreshes(0)
{ }
void progress_bar_t::refresh() {
total_refreshes++;
reset_bar();
draw();
reset_bar();
}
void progress_bar_t::reset_bar() {
printf("\r");
fflush(stdout);
}
/* progress should be in [0.0,1.0] */
void progress_bar_t::draw_bar(float progress, int eta) {
int percent_done = int(progress * 100);
printf("%s: ", activity.c_str());
printf("[");
for (int i = 1; i < 49; i++) {
if (i % 5 == 0) printf("%d", 2 * i);
else if (i == percent_done / 2) printf(">");
else if (i < percent_done / 2) printf("=");
else printf(" ");
}
printf("] ");
if (eta == -1 && progress > 0) {
//Do automatic linear interpolation for eta
eta = ((1.0f / progress) - 1) * ticks_to_secs(get_ticks() - start_time);
}
if (eta == -1) printf("ETA: -");
else printf("ETA: %01d:%02d:%02d", (eta / 3600), (eta / 60) % 60, eta % 60);
printf(" "); //make sure we don't leave an characters behind
fflush(stdout);
}
counter_progress_bar_t::counter_progress_bar_t(std::string activity, int expected_count, int redraw_interval_ms)
: progress_bar_t(activity, redraw_interval_ms), count(0), expected_count(expected_count)
{ }
void counter_progress_bar_t::draw() {
progress_bar_t::draw_bar(float(count) / float(expected_count), -1);
}
void counter_progress_bar_t::operator++(int) {
count++;
}
file_progress_bar_t::file_progress_bar_t(std::string activity, FILE *file, int redraw_interval_ms)
: progress_bar_t(activity, redraw_interval_ms), file(file)
{
struct stat file_stats;
fstat(fileno(file), &file_stats);
file_size = file_stats.st_size;
}
void file_progress_bar_t::draw() {
progress_bar_t::draw_bar(float(ftell(file)) / float(file_size), -1);
}
<|endoftext|> |
<commit_before>// A work-in-progress llvm backend
#include <set>
#include <taichi/common/util.h>
#include <taichi/io/io.h>
#include "../ir.h"
#include "../program.h"
#include "../tlang_util.h"
#include "codegen_cuda.h"
#include "cuda_context.h"
#if defined(TLANG_WITH_CUDA)
#include "cuda_runtime.h"
#endif
#include "codegen_llvm.h"
TLANG_NAMESPACE_BEGIN
using namespace llvm;
// NVVM IR Spec:
// https://docs.nvidia.com/cuda/archive/10.0/pdf/NVVM_IR_Specification.pdf
class CodeGenLLVMGPU : public CodeGenLLVM {
public:
int kernel_grid_dim;
int kernel_block_dim;
CodeGenLLVMGPU(CodeGenBase *codegen_base, Kernel *kernel)
: CodeGenLLVM(codegen_base, kernel) {
}
void mark_function_as_cuda_kernel(llvm::Function *func) {
/*******************************************************************
Example annotation from llvm PTX doc:
define void @kernel(float addrspace(1)* %A,
float addrspace(1)* %B,
float addrspace(1)* %C);
!nvvm.annotations = !{!0}
!0 = !{void (float addrspace(1)*,
float addrspace(1)*,
float addrspace(1)*)* @kernel, !"kernel", i32 1}
*******************************************************************/
// Mark kernel function as a CUDA __global__ function
// Add the nvvm annotation that it is considered a kernel function.
llvm::Metadata *md_args[] = {
llvm::ValueAsMetadata::get(func),
MDString::get(*llvm_context, "kernel"),
llvm::ValueAsMetadata::get(tlctx->get_constant(1))};
MDNode *md_node = MDNode::get(*llvm_context, md_args);
module->getOrInsertNamedMetadata("nvvm.annotations")->addOperand(md_node);
}
FunctionType compile_module_to_executable() override {
#if defined(TLANG_WITH_CUDA)
auto offloaded_local = offloaded_tasks;
for (auto &task : offloaded_local) {
llvm::Function *func = module->getFunction(task.name);
TC_ASSERT(func);
mark_function_as_cuda_kernel(func);
}
if (get_current_program().config.print_kernel_llvm_ir) {
TC_INFO("IR before global optimization");
module->print(errs(), nullptr);
}
auto ptx = compile_module_to_ptx(module);
if (get_current_program().config.print_kernel_llvm_ir_optimized) {
TC_P(ptx);
}
auto cuda_module = cuda_context->compile(ptx);
for (auto &task : offloaded_local) {
task.cuda_func =
(void *)cuda_context->get_function(cuda_module, task.name);
}
return [offloaded_local](Context context) {
for (auto task : offloaded_local) {
if (get_current_program().config.verbose_kernel_launches)
TC_INFO("Launching kernel {}<<<{}, {}>>>", task.name, task.grid_dim,
task.block_dim);
if (get_current_program().config.enable_profiler) {
get_current_program().profiler_llvm->start(task.name);
}
cuda_context->launch((CUfunction)task.cuda_func, &context,
task.grid_dim, task.block_dim);
if (get_current_program().config.enable_profiler) {
get_current_program().profiler_llvm->stop();
}
}
};
#else
TC_NOT_IMPLEMENTED;
return nullptr;
#endif
}
void visit(PrintStmt *stmt) override {
TC_ASSERT(stmt->width() == 1);
auto value_type = tlctx->get_data_type(stmt->stmt->ret_type.data_type);
std::string format;
auto value = stmt->stmt->value;
if (stmt->stmt->ret_type.data_type == DataType::i32) {
format = "%d";
} else if (stmt->stmt->ret_type.data_type == DataType::i64) {
format = "%lld";
} else if (stmt->stmt->ret_type.data_type == DataType::f32) {
value_type = llvm::Type::getDoubleTy(*llvm_context);
value = builder->CreateFPExt(value, value_type);
format = "%f";
} else if (stmt->stmt->ret_type.data_type == DataType::f64) {
format = "%.12f";
} else {
TC_NOT_IMPLEMENTED
}
std::vector<llvm::Type *> types{value_type};
auto stype = llvm::StructType::get(*llvm_context, types, false);
auto values = builder->CreateAlloca(stype);
auto value_ptr = builder->CreateGEP(
values, {tlctx->get_constant(0), tlctx->get_constant(0)});
builder->CreateStore(value, value_ptr);
auto format_str = "[debug] " + stmt->str + " = " + format + "\n";
stmt->value = ModuleBuilder::call(
builder, "vprintf",
builder->CreateGlobalStringPtr(format_str, "format_string"),
builder->CreateBitCast(values,
llvm::Type::getInt8PtrTy(*llvm_context)));
}
void emit_extra_unary(UnaryOpStmt *stmt) override {
// functions from libdevice
auto input = stmt->operand->value;
auto input_taichi_type = stmt->operand->ret_type.data_type;
auto input_type = input->getType();
auto op = stmt->op_type;
#define UNARY_STD(x) \
else if (op == UnaryOpType::x) { \
if (input_taichi_type == DataType::f32) { \
stmt->value = \
builder->CreateCall(get_runtime_function("__nv_" #x "f"), input); \
} else if (input_taichi_type == DataType::f64) { \
stmt->value = \
builder->CreateCall(get_runtime_function("__nv_" #x), input); \
} else if (input_taichi_type == DataType::i32) { \
stmt->value = builder->CreateCall(get_runtime_function(#x), input); \
} else { \
TC_NOT_IMPLEMENTED \
} \
}
if (op == UnaryOpType::abs) {
if (input_taichi_type == DataType::f32) {
stmt->value =
builder->CreateCall(get_runtime_function("__nv_fabsf"), input);
} else if (input_taichi_type == DataType::f64) {
stmt->value =
builder->CreateCall(get_runtime_function("__nv_fabs"), input);
} else if (input_taichi_type == DataType::i32) {
stmt->value =
builder->CreateCall(get_runtime_function("__nv_abs"), input);
} else {
TC_NOT_IMPLEMENTED
}
} else if (op == UnaryOpType::sqrt) {
if (input_taichi_type == DataType::f32) {
stmt->value =
builder->CreateCall(get_runtime_function("__nv_sqrtf"), input);
} else if (input_taichi_type == DataType::f64) {
stmt->value =
builder->CreateCall(get_runtime_function("__nv_sqrt"), input);
} else {
TC_NOT_IMPLEMENTED
}
} else if (op == UnaryOpType::logic_not) {
if (input_taichi_type == DataType::i32) {
stmt->value =
builder->CreateCall(get_runtime_function("logic_not_i32"), input);
} else {
TC_NOT_IMPLEMENTED
}
}
UNARY_STD(exp)
UNARY_STD(log)
UNARY_STD(tan)
UNARY_STD(tanh)
UNARY_STD(sgn)
UNARY_STD(acos)
UNARY_STD(asin)
else {
TC_P(unary_op_type_name(op));
TC_NOT_IMPLEMENTED
}
#undef UNARY_STD
}
void visit(AtomicOpStmt *stmt) override {
TC_ASSERT(stmt->width() == 1);
// https://llvm.org/docs/NVPTXUsage.html#address-spaces
bool is_local = stmt->dest->is<AllocaStmt>();
if (is_local) {
TC_ERROR("Local atomics should have been demoted.");
} else {
for (int l = 0; l < stmt->width(); l++) {
TC_ASSERT(stmt->op_type == AtomicOpType::add);
if (is_integral(stmt->val->ret_type.data_type)) {
builder->CreateAtomicRMW(
llvm::AtomicRMWInst::BinOp::Add, stmt->dest->value,
stmt->val->value, llvm::AtomicOrdering::SequentiallyConsistent);
} else if (stmt->val->ret_type.data_type == DataType::f32) {
auto dt = tlctx->get_data_type(DataType::f32);
builder->CreateIntrinsic(Intrinsic::nvvm_atomic_load_add_f32,
{llvm::PointerType::get(dt, 0)},
{stmt->dest->value, stmt->val->value});
} else if (stmt->val->ret_type.data_type == DataType::f64) {
auto dt = tlctx->get_data_type(DataType::f64);
builder->CreateIntrinsic(Intrinsic::nvvm_atomic_load_add_f64,
{llvm::PointerType::get(dt, 0)},
{stmt->dest->value, stmt->val->value});
} else {
TC_NOT_IMPLEMENTED
}
}
}
}
void visit(RandStmt *stmt) override {
stmt->value =
create_call(fmt::format("cuda_rand_{}",
data_type_short_name(stmt->ret_type.data_type)),
{get_context()});
}
void visit(RangeForStmt *for_stmt) override {
create_naive_range_for(for_stmt);
}
void create_offload_range_for(OffloadedStmt *stmt) {
auto loop_var = create_entry_block_alloca(DataType::i32);
stmt->loop_vars_llvm.push_back(loop_var);
auto loop_begin = stmt->begin;
auto loop_end = stmt->end;
auto loop_block_dim = stmt->block_dim;
if (loop_block_dim == 0) {
loop_block_dim = get_current_program().config.default_gpu_block_dim;
}
kernel_grid_dim =
(loop_end - loop_begin + loop_block_dim - 1) / loop_block_dim;
kernel_block_dim = loop_block_dim;
BasicBlock *body = BasicBlock::Create(*llvm_context, "loop_body", func);
BasicBlock *after_loop = BasicBlock::Create(*llvm_context, "block", func);
auto threadIdx =
builder->CreateIntrinsic(Intrinsic::nvvm_read_ptx_sreg_tid_x, {}, {});
auto blockIdx =
builder->CreateIntrinsic(Intrinsic::nvvm_read_ptx_sreg_ctaid_x, {}, {});
auto blockDim =
builder->CreateIntrinsic(Intrinsic::nvvm_read_ptx_sreg_ntid_x, {}, {});
auto loop_id = builder->CreateAdd(
tlctx->get_constant(stmt->begin),
builder->CreateAdd(threadIdx, builder->CreateMul(blockIdx, blockDim)));
builder->CreateStore(loop_id, loop_var);
auto cond = builder->CreateICmp(llvm::CmpInst::Predicate::ICMP_SLT,
builder->CreateLoad(loop_var),
tlctx->get_constant(stmt->end));
builder->CreateCondBr(cond, body, after_loop);
{
// body cfg
builder->SetInsertPoint(body);
stmt->body->accept(this);
builder->CreateBr(after_loop);
}
builder->SetInsertPoint(after_loop);
}
void visit(OffloadedStmt *stmt) override {
#if defined(TLANG_WITH_CUDA)
int num_SMs;
cudaDeviceGetAttribute(&num_SMs, cudaDevAttrMultiProcessorCount, 0);
int max_block_dim;
cudaDeviceGetAttribute(&max_block_dim, cudaDevAttrMaxBlockDimX, 0);
using Type = OffloadedStmt::TaskType;
kernel_grid_dim = 1;
kernel_block_dim = 1;
init_offloaded_task_function(stmt);
if (stmt->task_type == Type::serial) {
stmt->body->accept(this);
} else if (stmt->task_type == Type::range_for) {
create_offload_range_for(stmt);
} else if (stmt->task_type == Type::struct_for) {
kernel_grid_dim = num_SMs * 32; // each SM can have 16-32 resident blocks
kernel_block_dim = stmt->block_dim;
if (kernel_block_dim == 0)
kernel_block_dim = get_current_program().config.default_gpu_block_dim;
kernel_block_dim =
std::min(stmt->snode->parent->max_num_elements(), kernel_block_dim);
stmt->block_dim = kernel_block_dim;
create_offload_struct_for(stmt, true);
} else if (stmt->task_type == Type::clear_list) {
emit_clear_list(stmt);
} else if (stmt->task_type == Type::listgen) {
int branching = stmt->snode->max_num_elements();
kernel_grid_dim = num_SMs * 32;
kernel_block_dim = std::min(branching, max_gpu_block_dim);
emit_list_gen(stmt);
} else {
TC_NOT_IMPLEMENTED
}
finalize_offloaded_task_function();
current_task->grid_dim = kernel_grid_dim;
current_task->block_dim = kernel_block_dim;
current_task->end();
current_task = nullptr;
#else
TC_NOT_IMPLEMENTED
#endif
}
};
FunctionType GPUCodeGen::codegen_llvm() {
TC_PROFILER("gpu codegen");
return CodeGenLLVMGPU(this, kernel).gen();
}
TLANG_NAMESPACE_END
<commit_msg>mpm99 7x faster on GPUs due to after listgen<commit_after>// A work-in-progress llvm backend
#include <set>
#include <taichi/common/util.h>
#include <taichi/io/io.h>
#include "../ir.h"
#include "../program.h"
#include "../tlang_util.h"
#include "codegen_cuda.h"
#include "cuda_context.h"
#if defined(TLANG_WITH_CUDA)
#include "cuda_runtime.h"
#endif
#include "codegen_llvm.h"
TLANG_NAMESPACE_BEGIN
using namespace llvm;
// NVVM IR Spec:
// https://docs.nvidia.com/cuda/archive/10.0/pdf/NVVM_IR_Specification.pdf
class CodeGenLLVMGPU : public CodeGenLLVM {
public:
int kernel_grid_dim;
int kernel_block_dim;
CodeGenLLVMGPU(CodeGenBase *codegen_base, Kernel *kernel)
: CodeGenLLVM(codegen_base, kernel) {
}
void mark_function_as_cuda_kernel(llvm::Function *func) {
/*******************************************************************
Example annotation from llvm PTX doc:
define void @kernel(float addrspace(1)* %A,
float addrspace(1)* %B,
float addrspace(1)* %C);
!nvvm.annotations = !{!0}
!0 = !{void (float addrspace(1)*,
float addrspace(1)*,
float addrspace(1)*)* @kernel, !"kernel", i32 1}
*******************************************************************/
// Mark kernel function as a CUDA __global__ function
// Add the nvvm annotation that it is considered a kernel function.
llvm::Metadata *md_args[] = {
llvm::ValueAsMetadata::get(func),
MDString::get(*llvm_context, "kernel"),
llvm::ValueAsMetadata::get(tlctx->get_constant(1))};
MDNode *md_node = MDNode::get(*llvm_context, md_args);
module->getOrInsertNamedMetadata("nvvm.annotations")->addOperand(md_node);
}
FunctionType compile_module_to_executable() override {
#if defined(TLANG_WITH_CUDA)
auto offloaded_local = offloaded_tasks;
for (auto &task : offloaded_local) {
llvm::Function *func = module->getFunction(task.name);
TC_ASSERT(func);
mark_function_as_cuda_kernel(func);
}
if (get_current_program().config.print_kernel_llvm_ir) {
TC_INFO("IR before global optimization");
module->print(errs(), nullptr);
}
auto ptx = compile_module_to_ptx(module);
if (get_current_program().config.print_kernel_llvm_ir_optimized) {
TC_P(ptx);
}
auto cuda_module = cuda_context->compile(ptx);
for (auto &task : offloaded_local) {
task.cuda_func =
(void *)cuda_context->get_function(cuda_module, task.name);
}
return [offloaded_local](Context context) {
for (auto task : offloaded_local) {
if (get_current_program().config.verbose_kernel_launches)
TC_INFO("Launching kernel {}<<<{}, {}>>>", task.name, task.grid_dim,
task.block_dim);
if (get_current_program().config.enable_profiler) {
get_current_program().profiler_llvm->start(task.name);
}
cuda_context->launch((CUfunction)task.cuda_func, &context,
task.grid_dim, task.block_dim);
if (get_current_program().config.enable_profiler) {
get_current_program().profiler_llvm->stop();
}
}
};
#else
TC_NOT_IMPLEMENTED;
return nullptr;
#endif
}
void visit(PrintStmt *stmt) override {
TC_ASSERT(stmt->width() == 1);
auto value_type = tlctx->get_data_type(stmt->stmt->ret_type.data_type);
std::string format;
auto value = stmt->stmt->value;
if (stmt->stmt->ret_type.data_type == DataType::i32) {
format = "%d";
} else if (stmt->stmt->ret_type.data_type == DataType::i64) {
format = "%lld";
} else if (stmt->stmt->ret_type.data_type == DataType::f32) {
value_type = llvm::Type::getDoubleTy(*llvm_context);
value = builder->CreateFPExt(value, value_type);
format = "%f";
} else if (stmt->stmt->ret_type.data_type == DataType::f64) {
format = "%.12f";
} else {
TC_NOT_IMPLEMENTED
}
std::vector<llvm::Type *> types{value_type};
auto stype = llvm::StructType::get(*llvm_context, types, false);
auto values = builder->CreateAlloca(stype);
auto value_ptr = builder->CreateGEP(
values, {tlctx->get_constant(0), tlctx->get_constant(0)});
builder->CreateStore(value, value_ptr);
auto format_str = "[debug] " + stmt->str + " = " + format + "\n";
stmt->value = ModuleBuilder::call(
builder, "vprintf",
builder->CreateGlobalStringPtr(format_str, "format_string"),
builder->CreateBitCast(values,
llvm::Type::getInt8PtrTy(*llvm_context)));
}
void emit_extra_unary(UnaryOpStmt *stmt) override {
// functions from libdevice
auto input = stmt->operand->value;
auto input_taichi_type = stmt->operand->ret_type.data_type;
auto input_type = input->getType();
auto op = stmt->op_type;
#define UNARY_STD(x) \
else if (op == UnaryOpType::x) { \
if (input_taichi_type == DataType::f32) { \
stmt->value = \
builder->CreateCall(get_runtime_function("__nv_" #x "f"), input); \
} else if (input_taichi_type == DataType::f64) { \
stmt->value = \
builder->CreateCall(get_runtime_function("__nv_" #x), input); \
} else if (input_taichi_type == DataType::i32) { \
stmt->value = builder->CreateCall(get_runtime_function(#x), input); \
} else { \
TC_NOT_IMPLEMENTED \
} \
}
if (op == UnaryOpType::abs) {
if (input_taichi_type == DataType::f32) {
stmt->value =
builder->CreateCall(get_runtime_function("__nv_fabsf"), input);
} else if (input_taichi_type == DataType::f64) {
stmt->value =
builder->CreateCall(get_runtime_function("__nv_fabs"), input);
} else if (input_taichi_type == DataType::i32) {
stmt->value =
builder->CreateCall(get_runtime_function("__nv_abs"), input);
} else {
TC_NOT_IMPLEMENTED
}
} else if (op == UnaryOpType::sqrt) {
if (input_taichi_type == DataType::f32) {
stmt->value =
builder->CreateCall(get_runtime_function("__nv_sqrtf"), input);
} else if (input_taichi_type == DataType::f64) {
stmt->value =
builder->CreateCall(get_runtime_function("__nv_sqrt"), input);
} else {
TC_NOT_IMPLEMENTED
}
} else if (op == UnaryOpType::logic_not) {
if (input_taichi_type == DataType::i32) {
stmt->value =
builder->CreateCall(get_runtime_function("logic_not_i32"), input);
} else {
TC_NOT_IMPLEMENTED
}
}
UNARY_STD(exp)
UNARY_STD(log)
UNARY_STD(tan)
UNARY_STD(tanh)
UNARY_STD(sgn)
UNARY_STD(acos)
UNARY_STD(asin)
else {
TC_P(unary_op_type_name(op));
TC_NOT_IMPLEMENTED
}
#undef UNARY_STD
}
void visit(AtomicOpStmt *stmt) override {
TC_ASSERT(stmt->width() == 1);
// https://llvm.org/docs/NVPTXUsage.html#address-spaces
bool is_local = stmt->dest->is<AllocaStmt>();
if (is_local) {
TC_ERROR("Local atomics should have been demoted.");
} else {
for (int l = 0; l < stmt->width(); l++) {
TC_ASSERT(stmt->op_type == AtomicOpType::add);
if (is_integral(stmt->val->ret_type.data_type)) {
builder->CreateAtomicRMW(
llvm::AtomicRMWInst::BinOp::Add, stmt->dest->value,
stmt->val->value, llvm::AtomicOrdering::SequentiallyConsistent);
} else if (stmt->val->ret_type.data_type == DataType::f32) {
auto dt = tlctx->get_data_type(DataType::f32);
builder->CreateIntrinsic(Intrinsic::nvvm_atomic_load_add_f32,
{llvm::PointerType::get(dt, 0)},
{stmt->dest->value, stmt->val->value});
} else if (stmt->val->ret_type.data_type == DataType::f64) {
auto dt = tlctx->get_data_type(DataType::f64);
builder->CreateIntrinsic(Intrinsic::nvvm_atomic_load_add_f64,
{llvm::PointerType::get(dt, 0)},
{stmt->dest->value, stmt->val->value});
} else {
TC_NOT_IMPLEMENTED
}
}
}
}
void visit(RandStmt *stmt) override {
stmt->value =
create_call(fmt::format("cuda_rand_{}",
data_type_short_name(stmt->ret_type.data_type)),
{get_context()});
}
void visit(RangeForStmt *for_stmt) override {
create_naive_range_for(for_stmt);
}
void create_offload_range_for(OffloadedStmt *stmt) {
auto loop_var = create_entry_block_alloca(DataType::i32);
stmt->loop_vars_llvm.push_back(loop_var);
auto loop_begin = stmt->begin;
auto loop_end = stmt->end;
auto loop_block_dim = stmt->block_dim;
if (loop_block_dim == 0) {
loop_block_dim = get_current_program().config.default_gpu_block_dim;
}
kernel_grid_dim =
(loop_end - loop_begin + loop_block_dim - 1) / loop_block_dim;
kernel_block_dim = loop_block_dim;
BasicBlock *body = BasicBlock::Create(*llvm_context, "loop_body", func);
BasicBlock *after_loop = BasicBlock::Create(*llvm_context, "block", func);
auto threadIdx =
builder->CreateIntrinsic(Intrinsic::nvvm_read_ptx_sreg_tid_x, {}, {});
auto blockIdx =
builder->CreateIntrinsic(Intrinsic::nvvm_read_ptx_sreg_ctaid_x, {}, {});
auto blockDim =
builder->CreateIntrinsic(Intrinsic::nvvm_read_ptx_sreg_ntid_x, {}, {});
auto loop_id = builder->CreateAdd(
tlctx->get_constant(stmt->begin),
builder->CreateAdd(threadIdx, builder->CreateMul(blockIdx, blockDim)));
builder->CreateStore(loop_id, loop_var);
auto cond = builder->CreateICmp(llvm::CmpInst::Predicate::ICMP_SLT,
builder->CreateLoad(loop_var),
tlctx->get_constant(stmt->end));
builder->CreateCondBr(cond, body, after_loop);
{
// body cfg
builder->SetInsertPoint(body);
stmt->body->accept(this);
builder->CreateBr(after_loop);
}
builder->SetInsertPoint(after_loop);
}
void visit(OffloadedStmt *stmt) override {
#if defined(TLANG_WITH_CUDA)
int num_SMs;
cudaDeviceGetAttribute(&num_SMs, cudaDevAttrMultiProcessorCount, 0);
int max_block_dim;
cudaDeviceGetAttribute(&max_block_dim, cudaDevAttrMaxBlockDimX, 0);
using Type = OffloadedStmt::TaskType;
kernel_grid_dim = 1;
kernel_block_dim = 1;
init_offloaded_task_function(stmt);
if (stmt->task_type == Type::serial) {
stmt->body->accept(this);
} else if (stmt->task_type == Type::range_for) {
create_offload_range_for(stmt);
} else if (stmt->task_type == Type::struct_for) {
kernel_grid_dim = num_SMs * 32; // each SM can have 16-32 resident blocks
kernel_block_dim = stmt->block_dim;
if (kernel_block_dim == 0)
kernel_block_dim = get_current_program().config.default_gpu_block_dim;
kernel_block_dim =
std::min(stmt->snode->parent->max_num_elements(), kernel_block_dim);
stmt->block_dim = kernel_block_dim;
create_offload_struct_for(stmt, true);
} else if (stmt->task_type == Type::clear_list) {
emit_clear_list(stmt);
} else if (stmt->task_type == Type::listgen) {
int branching = stmt->snode->max_num_elements();
kernel_grid_dim = num_SMs * 32;
kernel_block_dim = std::min(branching, 64);
emit_list_gen(stmt);
} else {
TC_NOT_IMPLEMENTED
}
finalize_offloaded_task_function();
current_task->grid_dim = kernel_grid_dim;
current_task->block_dim = kernel_block_dim;
current_task->end();
current_task = nullptr;
#else
TC_NOT_IMPLEMENTED
#endif
}
};
FunctionType GPUCodeGen::codegen_llvm() {
TC_PROFILER("gpu codegen");
return CodeGenLLVMGPU(this, kernel).gen();
}
TLANG_NAMESPACE_END
<|endoftext|> |
<commit_before>/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015
Vladimír Vondruš <mosra@centrum.cz>
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 <Corrade/TestSuite/Compare/Container.h>
#include "Magnum/BufferImage.h"
#include "Magnum/ColorFormat.h"
#include "Magnum/Test/AbstractOpenGLTester.h"
namespace Magnum { namespace Test {
struct BufferImageTest: AbstractOpenGLTester {
explicit BufferImageTest();
void construct();
void constructCopy();
void constructMove();
void setData();
};
BufferImageTest::BufferImageTest() {
addTests({&BufferImageTest::construct,
&BufferImageTest::constructCopy,
&BufferImageTest::constructMove,
&BufferImageTest::setData});
}
void BufferImageTest::construct() {
const char data[] = { 'a', 0, 0, 0, 'b', 0, 0, 0, 'c', 0, 0, 0 };
BufferImage2D a(ColorFormat::Red, ColorType::UnsignedByte, {1, 3}, data, BufferUsage::StaticDraw);
#ifndef MAGNUM_TARGET_GLES
const auto imageData = a.buffer().data();
#endif
MAGNUM_VERIFY_NO_ERROR();
CORRADE_COMPARE(a.format(), ColorFormat::Red);
CORRADE_COMPARE(a.type(), ColorType::UnsignedByte);
CORRADE_COMPARE(a.size(), Vector2i(1, 3));
/** @todo How to verify the contents in ES? */
#ifndef MAGNUM_TARGET_GLES
CORRADE_COMPARE_AS(std::vector<char>(imageData.begin(), imageData.end()),
std::vector<char>(data, data + 12),
TestSuite::Compare::Container);
#endif
}
void BufferImageTest::constructCopy() {
CORRADE_VERIFY(!(std::is_constructible<BufferImage2D, const BufferImage2D&>{}));
CORRADE_VERIFY(!(std::is_assignable<BufferImage2D, const BufferImage2D&>{}));
}
void BufferImageTest::constructMove() {
const char data[4] = { 'a', 'b', 'c', 'd' };
BufferImage2D a(ColorFormat::Red, ColorType::UnsignedByte, {4, 1}, data, BufferUsage::StaticDraw);
const Int id = a.buffer().id();
MAGNUM_VERIFY_NO_ERROR();
CORRADE_VERIFY(id > 0);
BufferImage2D b(std::move(a));
CORRADE_COMPARE(a.buffer().id(), 0);
CORRADE_COMPARE(a.size(), Vector2i());
CORRADE_COMPARE(b.format(), ColorFormat::Red);
CORRADE_COMPARE(b.type(), ColorType::UnsignedByte);
CORRADE_COMPARE(b.size(), Vector2i(4, 1));
CORRADE_COMPARE(b.buffer().id(), id);
const unsigned short data2[2*4] = { 1, 2, 3, 4, 5, 6, 7, 8 };
BufferImage2D c(ColorFormat::RGBA, ColorType::UnsignedShort, {1, 2}, data2, BufferUsage::StaticDraw);
const Int cId = c.buffer().id();
c = std::move(b);
MAGNUM_VERIFY_NO_ERROR();
CORRADE_VERIFY(cId > 0);
CORRADE_COMPARE(b.buffer().id(), cId);
CORRADE_COMPARE(b.size(), Vector2i(1, 2));
CORRADE_COMPARE(c.format(), ColorFormat::Red);
CORRADE_COMPARE(c.type(), ColorType::UnsignedByte);
CORRADE_COMPARE(c.size(), Vector2i(4, 1));
CORRADE_COMPARE(c.buffer().id(), id);
}
void BufferImageTest::setData() {
const char data[4] = { 'a', 'b', 'c', 'd' };
BufferImage2D a(ColorFormat::Red, ColorType::UnsignedByte, {4, 1}, data, BufferUsage::StaticDraw);
const UnsignedShort data2[2*4] = { 1, 2, 3, 4, 5, 6, 7, 8 };
a.setData(ColorFormat::RGBA, ColorType::UnsignedShort, {1, 2}, data2, BufferUsage::StaticDraw);
#ifndef MAGNUM_TARGET_GLES
const auto imageData = a.buffer().data<UnsignedShort>();
#endif
MAGNUM_VERIFY_NO_ERROR();
CORRADE_COMPARE(a.format(), ColorFormat::RGBA);
CORRADE_COMPARE(a.type(), ColorType::UnsignedShort);
CORRADE_COMPARE(a.size(), Vector2i(1, 2));
/** @todo How to verify the contents in ES? */
#ifndef MAGNUM_TARGET_GLES
CORRADE_COMPARE_AS(std::vector<UnsignedShort>(imageData.begin(), imageData.end()),
std::vector<UnsignedShort>(data2, data2 + 8),
TestSuite::Compare::Container);
#endif
}
}}
CORRADE_TEST_MAIN(Magnum::Test::BufferImageTest)
<commit_msg>Test cleanup.<commit_after>/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015
Vladimír Vondruš <mosra@centrum.cz>
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 <Corrade/TestSuite/Compare/Container.h>
#include "Magnum/BufferImage.h"
#include "Magnum/ColorFormat.h"
#include "Magnum/Test/AbstractOpenGLTester.h"
namespace Magnum { namespace Test {
struct BufferImageGLTest: AbstractOpenGLTester {
explicit BufferImageGLTest();
void construct();
void constructCopy();
void constructMove();
void setData();
};
BufferImageGLTest::BufferImageGLTest() {
addTests({&BufferImageGLTest::construct,
&BufferImageGLTest::constructCopy,
&BufferImageGLTest::constructMove,
&BufferImageGLTest::setData});
}
void BufferImageGLTest::construct() {
const char data[] = { 'a', 0, 0, 0, 'b', 0, 0, 0, 'c', 0, 0, 0 };
BufferImage2D a(ColorFormat::Red, ColorType::UnsignedByte, {1, 3}, data, BufferUsage::StaticDraw);
#ifndef MAGNUM_TARGET_GLES
const auto imageData = a.buffer().data();
#endif
MAGNUM_VERIFY_NO_ERROR();
CORRADE_COMPARE(a.format(), ColorFormat::Red);
CORRADE_COMPARE(a.type(), ColorType::UnsignedByte);
CORRADE_COMPARE(a.size(), Vector2i(1, 3));
/** @todo How to verify the contents in ES? */
#ifndef MAGNUM_TARGET_GLES
CORRADE_COMPARE_AS(std::vector<char>(imageData.begin(), imageData.end()),
std::vector<char>(data, data + 12),
TestSuite::Compare::Container);
#endif
}
void BufferImageGLTest::constructCopy() {
CORRADE_VERIFY(!(std::is_constructible<BufferImage2D, const BufferImage2D&>{}));
CORRADE_VERIFY(!(std::is_assignable<BufferImage2D, const BufferImage2D&>{}));
}
void BufferImageGLTest::constructMove() {
const char data[4] = { 'a', 'b', 'c', 'd' };
BufferImage2D a(ColorFormat::Red, ColorType::UnsignedByte, {4, 1}, data, BufferUsage::StaticDraw);
const Int id = a.buffer().id();
MAGNUM_VERIFY_NO_ERROR();
CORRADE_VERIFY(id > 0);
BufferImage2D b(std::move(a));
CORRADE_COMPARE(a.buffer().id(), 0);
CORRADE_COMPARE(a.size(), Vector2i());
CORRADE_COMPARE(b.format(), ColorFormat::Red);
CORRADE_COMPARE(b.type(), ColorType::UnsignedByte);
CORRADE_COMPARE(b.size(), Vector2i(4, 1));
CORRADE_COMPARE(b.buffer().id(), id);
const unsigned short data2[2*4] = { 1, 2, 3, 4, 5, 6, 7, 8 };
BufferImage2D c(ColorFormat::RGBA, ColorType::UnsignedShort, {1, 2}, data2, BufferUsage::StaticDraw);
const Int cId = c.buffer().id();
c = std::move(b);
MAGNUM_VERIFY_NO_ERROR();
CORRADE_VERIFY(cId > 0);
CORRADE_COMPARE(b.buffer().id(), cId);
CORRADE_COMPARE(b.size(), Vector2i(1, 2));
CORRADE_COMPARE(c.format(), ColorFormat::Red);
CORRADE_COMPARE(c.type(), ColorType::UnsignedByte);
CORRADE_COMPARE(c.size(), Vector2i(4, 1));
CORRADE_COMPARE(c.buffer().id(), id);
}
void BufferImageGLTest::setData() {
const char data[4] = { 'a', 'b', 'c', 'd' };
BufferImage2D a(ColorFormat::Red, ColorType::UnsignedByte, {4, 1}, data, BufferUsage::StaticDraw);
const UnsignedShort data2[2*4] = { 1, 2, 3, 4, 5, 6, 7, 8 };
a.setData(ColorFormat::RGBA, ColorType::UnsignedShort, {1, 2}, data2, BufferUsage::StaticDraw);
#ifndef MAGNUM_TARGET_GLES
const auto imageData = a.buffer().data<UnsignedShort>();
#endif
MAGNUM_VERIFY_NO_ERROR();
CORRADE_COMPARE(a.format(), ColorFormat::RGBA);
CORRADE_COMPARE(a.type(), ColorType::UnsignedShort);
CORRADE_COMPARE(a.size(), Vector2i(1, 2));
/** @todo How to verify the contents in ES? */
#ifndef MAGNUM_TARGET_GLES
CORRADE_COMPARE_AS(std::vector<UnsignedShort>(imageData.begin(), imageData.end()),
std::vector<UnsignedShort>(data2, data2 + 8),
TestSuite::Compare::Container);
#endif
}
}}
CORRADE_TEST_MAIN(Magnum::Test::BufferImageGLTest)
<|endoftext|> |
<commit_before>#include "seat.hpp"
#include "core.hpp"
#include "input-manager.hpp"
#include "render-manager.hpp"
#include "../../view/priv-view.hpp"
extern "C"
{
#include <wlr/backend/libinput.h>
}
static void handle_drag_icon_map(wl_listener* listener, void *data)
{
auto wlr_icon = (wlr_drag_icon*) data;
auto icon = wf_surface_from_void(wlr_icon->data);
icon->map(wlr_icon->surface);
}
static void handle_drag_icon_unmap(wl_listener* listener, void *data)
{
auto wlr_icon = (wlr_drag_icon*) data;
auto icon = wf_surface_from_void(wlr_icon->data);
icon->unmap();
}
static void handle_drag_icon_destroy(wl_listener* listener, void *data)
{
auto wlr_icon = (wlr_drag_icon*) data;
auto icon = (wf_drag_icon*) wlr_icon->data;
auto it = std::find_if(core->input->drag_icons.begin(),
core->input->drag_icons.end(),
[=] (const std::unique_ptr<wf_drag_icon>& ptr)
{return ptr.get() == icon;});
/* we don't dec_keep_count() because the surface memory is
* managed by the unique_ptr */
assert(it != core->input->drag_icons.end());
core->input->drag_icons.erase(it);
}
wf_drag_icon::wf_drag_icon(wlr_drag_icon *ic)
: wayfire_surface_t(nullptr), icon(ic)
{
map_ev.notify = handle_drag_icon_map;
unmap_ev.notify = handle_drag_icon_unmap;
destroy.notify = handle_drag_icon_destroy;
wl_signal_add(&icon->events.map, &map_ev);
wl_signal_add(&icon->events.unmap, &unmap_ev);
wl_signal_add(&icon->events.destroy, &destroy);
icon->data = this;
}
wf_point wf_drag_icon::get_output_position()
{
auto pos = icon->is_pointer ?
core->get_cursor_position() : core->get_touch_position(icon->touch_id);
GetTuple(x, y, pos);
x += icon->sx;
y += icon->sy;
if (output)
{
auto og = output->get_full_geometry();
x -= og.x;
y -= og.y;
}
return {x, y};
}
void wf_drag_icon::damage(const wlr_box& box)
{
if (!is_mapped())
return;
core->for_each_output([=] (wayfire_output *output)
{
auto output_geometry = output->get_full_geometry();
if (rect_intersect(output_geometry, box))
{
auto local = box;
local.x -= output_geometry.x;
local.y -= output_geometry.y;
output->render->damage(local);
}
});
}
static void handle_new_drag_icon_cb(wl_listener*, void *data)
{
auto di = static_cast<wlr_drag_icon*> (data);
auto icon = std::unique_ptr<wf_drag_icon>(new wf_drag_icon(di));
core->input->drag_icons.push_back(std::move(icon));
}
static void handle_request_set_cursor(wl_listener*, void *data)
{
auto ev = static_cast<wlr_seat_pointer_request_set_cursor_event*> (data);
core->input->set_cursor(ev);
}
void input_manager::set_cursor(wlr_seat_pointer_request_set_cursor_event *ev)
{
auto focused_surface = ev->seat_client->seat->pointer_state.focused_surface;
auto client = focused_surface ? wl_resource_get_client(focused_surface->resource) : NULL;
if (ev->surface && client == ev->seat_client->client && !input_grabbed())
wlr_cursor_set_surface(cursor, ev->surface, ev->hotspot_x, ev->hotspot_y);
}
void input_manager::create_seat()
{
create_cursor();
request_set_cursor.notify = handle_request_set_cursor;
wl_signal_add(&seat->events.request_set_cursor, &request_set_cursor);
new_drag_icon.notify = handle_new_drag_icon_cb;
wl_signal_add(&seat->events.new_drag_icon, &new_drag_icon);
}
/* TODO: possibly add more input options which aren't available right now */
namespace device_config
{
int touchpad_tap_enabled;
int touchpad_dwl_enabled;
int touchpad_natural_scroll_enabled;
std::string drm_device;
wayfire_config *config;
void load(wayfire_config *conf)
{
config = conf;
auto section = (*config)["input"];
touchpad_tap_enabled = *section->get_option("tap_to_click", "1");
touchpad_dwl_enabled = *section->get_option("disable_while_typing", "0");
touchpad_natural_scroll_enabled = *section->get_option("naturall_scroll", "0");
drm_device = (*config)["core"]->get_option("drm_device", "default")->raw_value;
}
}
void configure_input_device(libinput_device *device)
{
assert(device);
/* we are configuring a touchpad */
if (libinput_device_config_tap_get_finger_count(device) > 0)
{
libinput_device_config_tap_set_enabled(device,
device_config::touchpad_tap_enabled ?
LIBINPUT_CONFIG_TAP_ENABLED : LIBINPUT_CONFIG_TAP_DISABLED);
libinput_device_config_dwt_set_enabled(device,
device_config::touchpad_dwl_enabled ?
LIBINPUT_CONFIG_DWT_ENABLED : LIBINPUT_CONFIG_DWT_DISABLED);
if (libinput_device_config_scroll_has_natural_scroll(device) > 0)
{
libinput_device_config_scroll_set_natural_scroll_enabled(device,
device_config::touchpad_natural_scroll_enabled);
}
}
}
<commit_msg>seat: scale drag icons<commit_after>#include "seat.hpp"
#include "core.hpp"
#include "input-manager.hpp"
#include "render-manager.hpp"
#include "../../view/priv-view.hpp"
extern "C"
{
#include <wlr/backend/libinput.h>
}
static void handle_drag_icon_map(wl_listener* listener, void *data)
{
auto wlr_icon = (wlr_drag_icon*) data;
auto icon = wf_surface_from_void(wlr_icon->data);
icon->map(wlr_icon->surface);
}
static void handle_drag_icon_unmap(wl_listener* listener, void *data)
{
auto wlr_icon = (wlr_drag_icon*) data;
auto icon = wf_surface_from_void(wlr_icon->data);
icon->unmap();
}
static void handle_drag_icon_destroy(wl_listener* listener, void *data)
{
auto wlr_icon = (wlr_drag_icon*) data;
auto icon = (wf_drag_icon*) wlr_icon->data;
auto it = std::find_if(core->input->drag_icons.begin(),
core->input->drag_icons.end(),
[=] (const std::unique_ptr<wf_drag_icon>& ptr)
{return ptr.get() == icon;});
/* we don't dec_keep_count() because the surface memory is
* managed by the unique_ptr */
assert(it != core->input->drag_icons.end());
core->input->drag_icons.erase(it);
}
wf_drag_icon::wf_drag_icon(wlr_drag_icon *ic)
: wayfire_surface_t(nullptr), icon(ic)
{
map_ev.notify = handle_drag_icon_map;
unmap_ev.notify = handle_drag_icon_unmap;
destroy.notify = handle_drag_icon_destroy;
wl_signal_add(&icon->events.map, &map_ev);
wl_signal_add(&icon->events.unmap, &unmap_ev);
wl_signal_add(&icon->events.destroy, &destroy);
icon->data = this;
}
wf_point wf_drag_icon::get_output_position()
{
auto pos = icon->is_pointer ?
core->get_cursor_position() : core->get_touch_position(icon->touch_id);
GetTuple(x, y, pos);
x += icon->sx;
y += icon->sy;
if (output)
{
auto og = output->get_full_geometry();
x -= og.x;
y -= og.y;
}
return {x, y};
}
void wf_drag_icon::damage(const wlr_box& box)
{
if (!is_mapped())
return;
core->for_each_output([=] (wayfire_output *output)
{
auto output_geometry = output->get_full_geometry();
if (rect_intersect(output_geometry, box))
{
auto local = box;
local.x -= output_geometry.x;
local.y -= output_geometry.y;
output->render->damage(get_output_box_from_box(local, output->handle->scale));
}
});
}
static void handle_new_drag_icon_cb(wl_listener*, void *data)
{
auto di = static_cast<wlr_drag_icon*> (data);
auto icon = std::unique_ptr<wf_drag_icon>(new wf_drag_icon(di));
core->input->drag_icons.push_back(std::move(icon));
}
static void handle_request_set_cursor(wl_listener*, void *data)
{
auto ev = static_cast<wlr_seat_pointer_request_set_cursor_event*> (data);
core->input->set_cursor(ev);
}
void input_manager::set_cursor(wlr_seat_pointer_request_set_cursor_event *ev)
{
auto focused_surface = ev->seat_client->seat->pointer_state.focused_surface;
auto client = focused_surface ? wl_resource_get_client(focused_surface->resource) : NULL;
if (ev->surface && client == ev->seat_client->client && !input_grabbed())
wlr_cursor_set_surface(cursor, ev->surface, ev->hotspot_x, ev->hotspot_y);
}
void input_manager::create_seat()
{
create_cursor();
request_set_cursor.notify = handle_request_set_cursor;
wl_signal_add(&seat->events.request_set_cursor, &request_set_cursor);
new_drag_icon.notify = handle_new_drag_icon_cb;
wl_signal_add(&seat->events.new_drag_icon, &new_drag_icon);
}
/* TODO: possibly add more input options which aren't available right now */
namespace device_config
{
int touchpad_tap_enabled;
int touchpad_dwl_enabled;
int touchpad_natural_scroll_enabled;
std::string drm_device;
wayfire_config *config;
void load(wayfire_config *conf)
{
config = conf;
auto section = (*config)["input"];
touchpad_tap_enabled = *section->get_option("tap_to_click", "1");
touchpad_dwl_enabled = *section->get_option("disable_while_typing", "0");
touchpad_natural_scroll_enabled = *section->get_option("naturall_scroll", "0");
drm_device = (*config)["core"]->get_option("drm_device", "default")->raw_value;
}
}
void configure_input_device(libinput_device *device)
{
assert(device);
/* we are configuring a touchpad */
if (libinput_device_config_tap_get_finger_count(device) > 0)
{
libinput_device_config_tap_set_enabled(device,
device_config::touchpad_tap_enabled ?
LIBINPUT_CONFIG_TAP_ENABLED : LIBINPUT_CONFIG_TAP_DISABLED);
libinput_device_config_dwt_set_enabled(device,
device_config::touchpad_dwl_enabled ?
LIBINPUT_CONFIG_DWT_ENABLED : LIBINPUT_CONFIG_DWT_DISABLED);
if (libinput_device_config_scroll_has_natural_scroll(device) > 0)
{
libinput_device_config_scroll_set_natural_scroll_enabled(device,
device_config::touchpad_natural_scroll_enabled);
}
}
}
<|endoftext|> |
<commit_before>/*
* fMBT, free Model Based Testing tool
* Copyright (c) 2011, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include "coverage_market.hh"
#include "model.hh"
Coverage_Market::Coverage_Market(Log& l, std::string& params) :
Coverage(l)
{
add_requirement(params);
}
bool Coverage_Market::execute(int action)
{
/* Dummy */
for(size_t i=0;i<Units.size();i++) {
Units[i]->execute(action);
}
return true;
}
float Coverage_Market::getCoverage()
{
val v,tmp;
v.first=0;
v.second=0;
for(size_t i=0;i<Units.size();i++) {
tmp=Units[i]->get_value();
v.first+=tmp.first;
v.second+=tmp.second;
}
if (v.second) {
return ((float)v.first)/((float)v.second);
}
return 0;
}
int Coverage_Market::fitness(int* action,int n,float* fitness)
{
float m=-1;
int pos=-1;
for(int i=0;i<n;i++) {
val b(0,0);
val e(0,0);
val tmp;
log.debug("%s:%i\n",__func__,i);
for(size_t j=0;j<Units.size();j++) {
log.debug("%s:%i,%i (%i)\n",__func__,i,j,action[i]);
Units[j]->update();
tmp=Units[j]->get_value();
b.first+=tmp.first;
b.second+=tmp.second;
Units[j]->push();
Units[j]->execute(action[i]);
Units[j]->update();
tmp=Units[j]->get_value();
e.first+=tmp.first;
e.second+=tmp.second;
Units[j]->pop();
Units[j]->update();
}
log.debug("(%i:%i) (%i:%i)\n",b.first,b.second,
e.first,e.second);
if (b.second) {
fitness[i]=((float)(e.first-b.first))/((float)(b.second));
} else {
fitness[i]=0.0;
}
if (m<fitness[i]) {
pos=i;
m=fitness[i];
}
}
return pos;
}
#include "dparse.h"
extern "C" {
extern D_ParserTables parser_tables_covlang;
};
extern Coverage_Market* cobj;
void Coverage_Market::add_requirement(std::string& req)
{
cobj=this;
D_Parser *p = new_D_Parser(&parser_tables_covlang, 32);
dparse(p,(char*)req.c_str(),req.length());
free_D_Parser(p);
}
Coverage_Market::unit* Coverage_Market::req_rx_action(const char m,const char* action) {
/* m(ode) == a|e */
std::vector<std::string> &names(model->getActionNames());
regex_t rx;
Coverage_Market::unit* u=NULL;
if (m) {
if (regcomp(&rx,action,0)) {
log.debug("Something went wrong with RexExp\n");
abort();
}
for(size_t i=0;i<names.size();i++) {
if (regexec(&rx,names[i].c_str(),0,0,0)==0) {
/* Match */
/*
log.debug("RegExp \"%s\" matched to str \"%s\"\n",
action,names[i].c_str());
*/
if (u) {
if (m=='e') {
u=new Coverage_Market::unit_or(u,new Coverage_Market::unit_leaf(i));
} else {
u=new Coverage_Market::unit_and(u,new Coverage_Market::unit_leaf(i));
}
} else {
u=new Coverage_Market::unit_leaf(i);
}
}
}
regfree(&rx);
} else {
std::string s(action);
int an = model->action_number(s);
if (an<=0) {
throw((int)42000);
}
u = new Coverage_Market::unit_leaf(an);
}
if (u==NULL) {
throw((int)42001);
}
return u;
}
FACTORY_DEFAULT_CREATOR(Coverage, Coverage_Market, "covlang");
<commit_msg>error handling...<commit_after>/*
* fMBT, free Model Based Testing tool
* Copyright (c) 2011, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include "coverage_market.hh"
#include "model.hh"
Coverage_Market::Coverage_Market(Log& l, std::string& params) :
Coverage(l)
{
add_requirement(params);
}
bool Coverage_Market::execute(int action)
{
/* Dummy */
for(size_t i=0;i<Units.size();i++) {
Units[i]->execute(action);
}
return true;
}
float Coverage_Market::getCoverage()
{
val v,tmp;
v.first=0;
v.second=0;
for(size_t i=0;i<Units.size();i++) {
tmp=Units[i]->get_value();
v.first+=tmp.first;
v.second+=tmp.second;
}
if (v.second) {
return ((float)v.first)/((float)v.second);
}
return 0;
}
int Coverage_Market::fitness(int* action,int n,float* fitness)
{
float m=-1;
int pos=-1;
for(int i=0;i<n;i++) {
val b(0,0);
val e(0,0);
val tmp;
log.debug("%s:%i\n",__func__,i);
for(size_t j=0;j<Units.size();j++) {
log.debug("%s:%i,%i (%i)\n",__func__,i,j,action[i]);
Units[j]->update();
tmp=Units[j]->get_value();
b.first+=tmp.first;
b.second+=tmp.second;
Units[j]->push();
Units[j]->execute(action[i]);
Units[j]->update();
tmp=Units[j]->get_value();
e.first+=tmp.first;
e.second+=tmp.second;
Units[j]->pop();
Units[j]->update();
}
log.debug("(%i:%i) (%i:%i)\n",b.first,b.second,
e.first,e.second);
if (b.second) {
fitness[i]=((float)(e.first-b.first))/((float)(b.second));
} else {
fitness[i]=0.0;
}
if (m<fitness[i]) {
pos=i;
m=fitness[i];
}
}
return pos;
}
#include "dparse.h"
extern "C" {
extern D_ParserTables parser_tables_covlang;
};
extern Coverage_Market* cobj;
void Coverage_Market::add_requirement(std::string& req)
{
cobj=this;
D_Parser *p = new_D_Parser(&parser_tables_covlang, 32);
bool ret=dparse(p,(char*)req.c_str(),req.length());
status&=ret;
free_D_Parser(p);
}
Coverage_Market::unit* Coverage_Market::req_rx_action(const char m,const char* action) {
/* m(ode) == a|e */
if (!status) {
return NULL;
}
std::vector<std::string> &names(model->getActionNames());
regex_t rx;
Coverage_Market::unit* u=NULL;
if (m) {
if (regcomp(&rx,action,0)) {
errormsg=std::string("Something wrong with RexExp \"")+std::string(action)+std::string("\"");
status=false;
return NULL;
}
for(size_t i=0;i<names.size();i++) {
if (regexec(&rx,names[i].c_str(),0,0,0)==0) {
/* Match */
/*
log.debug("RegExp \"%s\" matched to str \"%s\"\n",
action,names[i].c_str());
*/
if (u) {
if (m=='e') {
u=new Coverage_Market::unit_or(u,new Coverage_Market::unit_leaf(i));
} else {
u=new Coverage_Market::unit_and(u,new Coverage_Market::unit_leaf(i));
}
} else {
u=new Coverage_Market::unit_leaf(i);
}
}
}
regfree(&rx);
} else {
std::string s(action);
int an = model->action_number(s);
if (an<=0) {
errormsg=std::string("No such action \"")+s+std::string("\"");
status=false;
}
u = new Coverage_Market::unit_leaf(an);
}
if (u==NULL) {
errormsg=std::string("parse error");
status=false;
}
return u;
}
FACTORY_DEFAULT_CREATOR(Coverage, Coverage_Market, "covlang");
<|endoftext|> |
<commit_before>#include "tests.h"
#include "memory.h"
#include "runtime.h"
#include "stream.h"
#include "container/range.h"
#include <sstream>
namespace kcon {
using container::range;
template<class Env>
struct Tester
{
typedef typename Env::Allocator Allocator;
typedef typename Env::kostream kostream;
typedef typename Env::kistream kistream;
typedef typename Env::kostream::KManip KManip;
typedef typename Env::Scheme::pcell_t pcell_t;
typedef typename Env::Scheme::elem_t elem_t;
template<class T>
using auto_root_ref = typename Allocator::template auto_root_ref<T>;
template<class T>
using auto_root = typename Allocator::template auto_root<T>;
static auto parse( Allocator& allocator, const std::string& in ) -> auto_root_ref<elem_t>
{
std::istringstream iss( in );
elem_t elem;
kistream( iss, allocator ) >> elem;
auto_root_ref<elem_t> r( allocator, elem );
return r;
}
static auto print( elem_t e, KManip m=flat ) -> std::string
{
std::ostringstream oss;
kostream( oss ) << m << e;
return oss.str();
}
static void test_ostream()
{TEST
Allocator a( 1024 );
pcell_t p = a.new_Cell(
1,
a.new_Cell(
a.new_Cell(3,3, {}),
2, {} ), {} );
auto found_flat = print( p, flat );
auto expected_flat = "[1 [3 3] 2]";
test( found_flat == expected_flat, "Incorrect flat printing found '" + found_flat + "'\nExpected '" + expected_flat + "'" );
auto found_deep = print( p, deep );
auto expected_deep = "[1 [[3 3] 2]]";
test( found_deep == expected_deep, "Incorrect deep printing found '" + found_deep + "'\nExpected '" + expected_deep + "'" );
}
static void test_io( const std::string& in, KManip m=flat, std::string out="" )
{
if( out.empty() )
out = in;
Allocator a( 1024 );
std::ostringstream oss;
auto found = print( parse( a, in ).value, m );
test( found == out, "IO failed for: '" + in + "'\nExpected: '" + out + "'\nFound: '" + found + "'" );
}
template<class SubType=AnyType>
static void test_io_error( const std::string& in, const std::string& msg )
{
Allocator a( 1024 );
std::string found;
try
{
found = print( parse( a, in ).value );
}
catch( const Error<Syntax,SubType>& e )
{
test( e.message() == msg, "IO failed for: '" + in + "'\nExpected error: '" + msg + "'\nFound: '" + e.message() + "'" );
return pass();
}
test( false, "IO failed for: '" + in + "'\nExpected error: '" + msg + "'\nFound: '" + found + "'" );
}
static void test_iostream()
{TEST
test_io( "3" );
test_io( " 3 ", flat, "3" );
test_io( "[0 [1 2]]", flat, "[0 1 2]" );
test_io( " [ 0 [ 1\n 2]\t]\t", flat, "[0 1 2]" );
test_io( "[0 1 2]", deep, "[0 [1 2]]" );
test_io( "[0 [1 [2 3] 4] 5 6]", flat );
test_io( "[0 [1 [2 3] 4] 5 6]", deep, "[0 [[1 [[2 3] 4]] [5 6]]]" );
test_io( "[[0 1] 2]", deep );
test_io( "[[0 1] 2]", flat );
test_io( "[[[0 1] [2 3]] [[4 5] [6 7]]]", deep );
test_io( "[[[0 1] [2 3]] [[4 5] [6 7]]]", flat, "[[[0 1] 2 3] [4 5] 6 7]" );
test_io( "[[[0 1] 2 3] [4 5] 6 7]", flat );
test_io_error<EOS>( "[", "Unexpected end of input" );
test_io_error( "]", "Unexpected ']'" );
test_io_error( "[0]", "Unexpected singleton" );
test_io_error( "[[0] 2]", "Unexpected singleton" );
test_io_error( "[]", "Unexpected empty cell" );
test_io_error( "[[] 2]", "Unexpected empty cell" );
}
static void test_gc()
{TEST
try
{
Allocator a( 1 );
elem_t p = a.new_Cell( 1, 1, {} );
a.new_Cell( 1, 1, {&p} );
fail( "Failed to catch out of memory" );
}
catch( const Error<Runtime,OutOfMemory>& ) { pass(); }
{
Allocator a( 10 );
elem_t p = a.new_Cell( 1, 2, {} );
a.new_Cell( 1, 1, {&p} );
test( a.num_allocated() == 2, "Failed to register allocated cells" );
test( p->head().is_byte() && p->head().byte() == 1, "Cell head incorrect before GC" );
test( p->tail().is_byte() && p->tail().byte() == 2, "Cell tail incorrect before GC" );
a.gc({&p});
test( p->head().is_byte() && p->head().byte() == 1, "Cell head incorrect after GC" );
test( p->tail().is_byte() && p->tail().byte() == 2, "Cell tail incorrect after GC" );
test( a.num_allocated() == 1, "Failed to cleanup after GC" );
}
{
Allocator a( 1024 );
auto_root<elem_t> p( parse( a, "[0 [1 [2 3] 4] 5 6]" ) );
auto_root<elem_t> q( parse( a, "[0 [1 [2 3] 4] 5 6]" ) );
a.gc({&p,&q});
test( a.gc_count() > 0, "GC failed to run with 2 roots" );
test( a.num_allocated() == 12, "Failed to hold all cells in GC" );
test( print( p ) == "[0 [1 [2 3] 4] 5 6]", "Complex tree (1) altered by GC" );
test( print( q ) == "[0 [1 [2 3] 4] 5 6]", "Complex tree (2) altered by GC" );
}
{
Allocator a( 1024 );
auto_root<elem_t> p( parse( a, "[0 [1 [2 3] 4] 5 6]" ) );
parse( a, "[0 [1 [2 3] 4] 5 6]" );
a.gc({&p});
test( a.gc_count() > 0, "GC failed to run with 1 root" );
test( a.num_allocated() == 6, "Failed to hold and cleanup all cells in GC" );
test( print( p ) == "[0 [1 [2 3] 4] 5 6]", "Complex tree (3) altered by GC" );
elem_t t = p->tail();
a.gc({&t});
test( a.num_allocated() == 5, "Failed to hold and cleanup tail cells in GC" );
test( print( t ) == "[[1 [2 3] 4] 5 6]", "Complex tree tail altered by GC" );
}
{
//Test with minimal memory to create memory churn
/*for( auto i : range(1,8) )
{
try
{
Allocator a( i );
parse( a, "[0 [1 [2 3] 4] 5 6]", {} );
fail( "Parsed in low memory enviroment" );
}
catch( const Error<Runtime,OutOfMemory>& )
{
pass();
}
}*/
}
{
//Test with minimal memory to create memory churn
Allocator a( 1024 );
auto_root<elem_t> p( parse( a, "[0 [1 [2 3] 4] 5 6]" ) );
//test( a.gc_count() > 0, "GC failed to run during low memory parse" );
a.gc({&p});
test( print( p ) == "[0 [1 [2 3] 4] 5 6]", "Low memory parse tree tail altered by GC" );
test( a.num_allocated() == 6, "Failed to hold and cleanup all cells in GC" );
}
}
static void run_tests()
{
std::cout << "TEST: " << TYPENAME( Env );
test_ostream();
test_iostream();
test_gc();
std::cout << "\n\n";
}
};
void run_tests()
{
Tester< Env< Debug, SimpleScheme, TestAllocator > >::run_tests();
Tester< Env< Debug, SimpleScheme, SimpleAllocator > >::run_tests();
}
} //namespace<commit_msg>Fixing tests<commit_after>#include "tests.h"
#include "memory.h"
#include "runtime.h"
#include "stream.h"
#include "container/range.h"
#include <sstream>
namespace kcon {
using container::range;
template<class Env>
struct Tester
{
typedef typename Env::Allocator Allocator;
typedef typename Env::kostream kostream;
typedef typename Env::kistream kistream;
typedef typename Env::kostream::KManip KManip;
typedef typename Env::Scheme::pcell_t pcell_t;
typedef typename Env::Scheme::elem_t elem_t;
template<class T>
using auto_root_ref = typename Allocator::template auto_root_ref<T>;
template<class T>
using auto_root = typename Allocator::template auto_root<T>;
static auto parse( Allocator& allocator, const std::string& in ) -> auto_root_ref<elem_t>
{
std::istringstream iss( in );
elem_t elem;
kistream( iss, allocator ) >> elem;
auto_root_ref<elem_t> r( allocator, elem );
return r;
}
static auto print( elem_t e, KManip m=flat ) -> std::string
{
std::ostringstream oss;
kostream( oss ) << m << e;
return oss.str();
}
static void test_ostream()
{TEST
Allocator a( 1024 );
pcell_t p = a.new_Cell(
1,
a.new_Cell(
a.new_Cell(3,3, {}),
2, {} ), {} );
auto found_flat = print( p, flat );
auto expected_flat = "[1 [3 3] 2]";
test( found_flat == expected_flat, "Incorrect flat printing found '" + found_flat + "'\nExpected '" + expected_flat + "'" );
auto found_deep = print( p, deep );
auto expected_deep = "[1 [[3 3] 2]]";
test( found_deep == expected_deep, "Incorrect deep printing found '" + found_deep + "'\nExpected '" + expected_deep + "'" );
}
static void test_io( const std::string& in, KManip m=flat, std::string out="" )
{
if( out.empty() )
out = in;
Allocator a( 1024 );
std::ostringstream oss;
auto found = print( parse( a, in ).value, m );
test( found == out, "IO failed for: '" + in + "'\nExpected: '" + out + "'\nFound: '" + found + "'" );
}
template<class SubType=AnyType>
static void test_io_error( const std::string& in, const std::string& msg )
{
Allocator a( 1024 );
std::string found;
try
{
found = print( parse( a, in ).value );
}
catch( const Error<Syntax,SubType>& e )
{
test( e.message() == msg, "IO failed for: '" + in + "'\nExpected error: '" + msg + "'\nFound: '" + e.message() + "'" );
return pass();
}
test( false, "IO failed for: '" + in + "'\nExpected error: '" + msg + "'\nFound: '" + found + "'" );
}
static void test_iostream()
{TEST
test_io( "3" );
test_io( " 3 ", flat, "3" );
test_io( "[0 [1 2]]", flat, "[0 1 2]" );
test_io( " [ 0 [ 1\n 2]\t]\t", flat, "[0 1 2]" );
test_io( "[0 1 2]", deep, "[0 [1 2]]" );
test_io( "[0 [1 [2 3] 4] 5 6]", flat );
test_io( "[0 [1 [2 3] 4] 5 6]", deep, "[0 [[1 [[2 3] 4]] [5 6]]]" );
test_io( "[[0 1] 2]", deep );
test_io( "[[0 1] 2]", flat );
test_io( "[[[0 1] [2 3]] [[4 5] [6 7]]]", deep );
test_io( "[[[0 1] [2 3]] [[4 5] [6 7]]]", flat, "[[[0 1] 2 3] [4 5] 6 7]" );
test_io( "[[[0 1] 2 3] [4 5] 6 7]", flat );
test_io_error<EOS>( "[", "Unexpected end of input" );
test_io_error( "]", "Unexpected ']'" );
test_io_error( "[0]", "Unexpected singleton" );
test_io_error( "[[0] 2]", "Unexpected singleton" );
test_io_error( "[]", "Unexpected empty cell" );
test_io_error( "[[] 2]", "Unexpected empty cell" );
}
static void test_gc()
{TEST
try
{
Allocator a( 1 );
elem_t p = a.new_Cell( 1, 1, {} );
a.new_Cell( 1, 1, {&p} );
fail( "Failed to catch out of memory" );
}
catch( const Error<Runtime,OutOfMemory>& ) { pass(); }
{
Allocator a( 10 );
elem_t p = a.new_Cell( 1, 2, {} );
a.new_Cell( 1, 1, {&p} );
test( a.num_allocated() == 2, "Failed to register allocated cells" );
test( p->head().is_byte() && p->head().byte() == 1, "Cell head incorrect before GC" );
test( p->tail().is_byte() && p->tail().byte() == 2, "Cell tail incorrect before GC" );
a.gc({&p});
test( p->head().is_byte() && p->head().byte() == 1, "Cell head incorrect after GC" );
test( p->tail().is_byte() && p->tail().byte() == 2, "Cell tail incorrect after GC" );
test( a.num_allocated() == 1, "Failed to cleanup after GC" );
}
{
Allocator a( 1024 );
auto_root<elem_t> p( parse( a, "[0 [1 [2 3] 4] 5 6]" ) );
auto_root<elem_t> q( parse( a, "[0 [1 [2 3] 4] 5 6]" ) );
a.gc({&p,&q});
test( a.gc_count() > 0, "GC failed to run with 2 roots" );
test( a.num_allocated() == 12, "Failed to hold all cells in GC" );
test( print( p ) == "[0 [1 [2 3] 4] 5 6]", "Complex tree (1) altered by GC" );
test( print( q ) == "[0 [1 [2 3] 4] 5 6]", "Complex tree (2) altered by GC" );
}
{
Allocator a( 1024 );
elem_t pp = parse( a, "[0 [1 [2 3] 4] 5 6]" ).value;
{
auto_root<elem_t> p( a, pp );
parse( a, "[0 [1 [2 3] 4] 5 6]" );
a.gc({});
test( a.gc_count() > 0, "GC failed to run with 1 root" );
test( a.num_allocated() == 6, "Failed to hold and cleanup all cells in GC" );
test( print( p ) == "[0 [1 [2 3] 4] 5 6]", "Complex tree (3) altered by GC" );
pp = p;
}
auto_root<elem_t> t( a, pp->tail() );
a.gc({});
test( a.num_allocated() == 5, "Failed to hold and cleanup tail cells in GC" );
test( print( t ) == "[[1 [2 3] 4] 5 6]", "Complex tree tail altered by GC" );
}
{
//Test with minimal memory to create memory churn
/*for( auto i : range(1,8) )
{
try
{
Allocator a( i );
parse( a, "[0 [1 [2 3] 4] 5 6]", {} );
fail( "Parsed in low memory enviroment" );
}
catch( const Error<Runtime,OutOfMemory>& )
{
pass();
}
}*/
}
{
//Test with minimal memory to create memory churn
Allocator a( 1024 );
auto_root<elem_t> p( parse( a, "[0 [1 [2 3] 4] 5 6]" ) );
//test( a.gc_count() > 0, "GC failed to run during low memory parse" );
a.gc({&p});
test( print( p ) == "[0 [1 [2 3] 4] 5 6]", "Low memory parse tree tail altered by GC" );
test( a.num_allocated() == 6, "Failed to hold and cleanup all cells in GC" );
}
}
static void run_tests()
{
std::cout << "TEST: " << TYPENAME( Env );
test_ostream();
test_iostream();
test_gc();
std::cout << "\n\n";
}
};
void run_tests()
{
Tester< Env< Debug, SimpleScheme, TestAllocator > >::run_tests();
Tester< Env< Debug, SimpleScheme, SimpleAllocator > >::run_tests();
}
} //namespace<|endoftext|> |
<commit_before>/**
* @file
* @copyright Copyright 2016 GNSS Sensor Ltd. All right reserved.
* @author Sergey Khabarov - sergeykhbr@gmail.com
* @brief Core API methods implementation.
*/
#include <string>
#include "api_core.h"
#include "api_types.h"
#include "iclass.h"
#include "ihap.h"
#include "coreservices/ithread.h"
#include "coreservices/iclock.h"
namespace debugger {
static AttributeType Config_;
static AttributeType listClasses_(Attr_List);
static AttributeType listHap_(Attr_List);
static AttributeType listPlugins_(Attr_List);
extern mutex_def mutex_printf;
extern mutex_def mutexDefaultConsoles_;
extern void _load_plugins(AttributeType *list);
extern void _unload_plugins(AttributeType *list);
class CoreService : public IService {
public:
CoreService(const char *name) : IService("CoreService") {
active_ = 1;
RISCV_mutex_init(&mutex_printf);
RISCV_mutex_init(&mutexDefaultConsoles_);
RISCV_event_create(&mutexExiting_, "mutexExiting_");
//logLevel_.make_int64(LOG_DEBUG); // default = LOG_ERROR
}
virtual ~CoreService() {
RISCV_event_close(&mutexExiting_);
}
int isActive() { return active_; }
void shutdown() { active_ = 0; }
bool isExiting() { return mutexExiting_.state; }
void setExiting() { RISCV_event_set(&mutexExiting_); }
private:
int active_;
event_def mutexExiting_;
};
static CoreService *pcore_ = NULL;
IFace *getInterface(const char *name) {
return pcore_->getInterface(name);
}
extern "C" int RISCV_init() {
pcore_ = new CoreService("core");
#if defined(_WIN32) || defined(__CYGWIN__)
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData)) {
RISCV_error("Can't initialize sockets library", NULL);
}
#endif
_load_plugins(&listPlugins_);
return 0;
}
extern "C" void RISCV_cleanup() {
IClass *icls;
// Pre-deletion
for (unsigned i = 0; i < listClasses_.size(); i++) {
icls = static_cast<IClass *>(listClasses_[i].to_iface());
icls->predeleteServices();
}
#if defined(_WIN32) || defined(__CYGWIN__)
WSACleanup();
#endif
_unload_plugins(&listPlugins_);
RISCV_mutex_lock(&mutex_printf);
RISCV_mutex_destroy(&mutex_printf);
RISCV_mutex_lock(&mutexDefaultConsoles_);
RISCV_mutex_destroy(&mutexDefaultConsoles_);
delete pcore_;
RISCV_disable_log();
}
extern "C" int RISCV_set_configuration(AttributeType *cfg) {
IClass *icls;
IService *iserv;
Config_.clone(cfg);
if (!Config_.is_dict()) {
RISCV_error("Wrong configuration.", NULL);
return -1;
}
AttributeType &Services = Config_["Services"];
if (Services.is_list()) {
for (unsigned i = 0; i < Services.size(); i++) {
const char *clsname = Services[i]["Class"].to_string();
icls = static_cast<IClass *>(RISCV_get_class(clsname));
if (icls == NULL) {
RISCV_error("Class %s not found",
Services[i]["Class"].to_string());
return -1;
}
/** Special global setting for the GUI class: */
if (strcmp(icls->getClassName(), "GuiPluginClass") == 0) {
if (!Config_["GlobalSettings"]["GUI"].to_bool()) {
RISCV_info("%s", "GUI disabled");
continue;
}
}
AttributeType &Instances = Services[i]["Instances"];
for (unsigned n = 0; n < Instances.size(); n++) {
iserv = icls->createService(Instances[n]["Name"].to_string());
iserv->initService(&Instances[n]["Attr"]);
}
}
}
// Post initialization
for (unsigned i = 0; i < listClasses_.size(); i++) {
icls = static_cast<IClass *>(listClasses_[i].to_iface());
icls->postinitServices();
}
RISCV_printf(getInterface(IFACE_SERVICE), 0, "%s",
"\n**********************************************************\n"
" RISC-V debugger\n"
" Author: Sergey Khabarov - sergeykhbr@gmail.com\n"
" Copyright 2016 GNSS Sensor Ltd. All right reserved.\n"
"**********************************************************");
IHap *ihap;
for (unsigned i = 0; i < listHap_.size(); i++) {
ihap = static_cast<IHap *>(listHap_[i].to_iface());
if (ihap->getType() == HAP_ConfigDone) {
ihap->hapTriggered(getInterface(IFACE_SERVICE),
HAP_ConfigDone, "Initial config done");
}
}
return 0;
}
extern "C" void RISCV_get_configuration(AttributeType *cfg) {
IClass *icls;
cfg->make_dict();
(*cfg)["GlobalSettings"] = Config_["GlobalSettings"];
(*cfg)["Services"].make_list(0);
for (unsigned i = 0; i < listClasses_.size(); i++) {
icls = static_cast<IClass *>(listClasses_[i].to_iface());
AttributeType val = icls->getConfiguration();
(*cfg)["Services"].add_to_list(&val);
}
cfg->to_config();
}
extern "C" const AttributeType *RISCV_get_global_settings() {
return &Config_["GlobalSettings"];
}
extern "C" void RISCV_register_class(IFace *icls) {
AttributeType item(icls);
listClasses_.add_to_list(&item);
}
extern "C" void RISCV_register_hap(IFace *ihap) {
AttributeType item(ihap);
listHap_.add_to_list(&item);
}
extern "C" void RISCV_trigger_hap(IFace *isrc, int type,
const char *descr) {
IHap *ihap;
EHapType etype = static_cast<EHapType>(type);
for (unsigned i = 0; i < listHap_.size(); i++) {
ihap = static_cast<IHap *>(listHap_[i].to_iface());
if (ihap->getType() == etype) {
ihap->hapTriggered(isrc, etype, descr);
}
}
}
extern "C" IFace *RISCV_get_class(const char *name) {
IClass *icls;
for (unsigned i = 0; i < listClasses_.size(); i++) {
icls = static_cast<IClass *>(listClasses_[i].to_iface());
if (strcmp(name, icls->getClassName()) == 0) {
return icls;
}
}
return NULL;
}
extern "C" IFace *RISCV_create_service(IFace *iclass, const char *name,
AttributeType *args) {
IClass *icls = static_cast<IClass *>(iclass);
IService *iobj = icls->createService(name);
iobj->initService(args);
iobj->postinitService();
return iobj;
}
extern "C" IFace *RISCV_get_service(const char *name) {
IClass *icls;
IService *iserv;
for (unsigned i = 0; i < listClasses_.size(); i++) {
icls = static_cast<IClass *>(listClasses_[i].to_iface());
if ((iserv = icls->getInstance(name)) != NULL) {
return iserv;
}
}
return NULL;
}
extern "C" IFace *RISCV_get_service_iface(const char *servname,
const char *facename) {
IService *iserv = static_cast<IService *>(RISCV_get_service(servname));
if (iserv == NULL) {
RISCV_error("Service '%s' not found.", servname);
return NULL;
}
return iserv->getInterface(facename);
}
extern "C" IFace *RISCV_get_service_port_iface(const char *servname,
const char *portname,
const char *facename) {
IService *iserv = static_cast<IService *>(RISCV_get_service(servname));
if (iserv == NULL) {
RISCV_error("Service '%s' not found.", servname);
return NULL;
}
return iserv->getPortInterface(portname, facename);
}
extern "C" void RISCV_get_services_with_iface(const char *iname,
AttributeType *list) {
IClass *icls;
IService *iserv;
IFace *iface;
const AttributeType *tlist;
list->make_list(0);
for (unsigned i = 0; i < listClasses_.size(); i++) {
icls = static_cast<IClass *>(listClasses_[i].to_iface());
tlist = icls->getInstanceList();
if (tlist->size()) {
iserv = static_cast<IService *>((*tlist)[0u].to_iface());
iface = iserv->getInterface(iname);
if (iface) {
AttributeType t1(iserv);
list->add_to_list(&t1);
}
}
}
}
extern "C" void RISCV_get_clock_services(AttributeType *list) {
IService *iserv;
RISCV_get_services_with_iface(IFACE_CLOCK, list);
for (unsigned i = 0; i < list->size(); i++) {
iserv = static_cast<IService *>((*list)[i].to_iface());
(*list)[i].make_iface(iserv->getInterface(IFACE_CLOCK));
}
}
static thread_return_t safe_exit_thread(void *args) {
AttributeType t1, t2;
IService *iserv;
IThread *ith;
RISCV_get_services_with_iface(IFACE_THREAD, &t1);
for (unsigned i = 0; i < t1.size(); i++) {
iserv = static_cast<IService *>(t1[i].to_iface());
ith = static_cast<IThread *>(iserv->getInterface(IFACE_THREAD));
printf("Stopping thread service '%s'. . .", iserv->getObjName());
ith->stop();
printf("Stopped\n");
}
RISCV_trigger_hap(getInterface(IFACE_SERVICE),
HAP_BreakSimulation, "Exiting");
printf("All threads were stopped!\n");
pcore_->shutdown();
return 0;
}
struct TimerType {
timer_callback_type cb;
void *args;
int interval;
int delta;
int single_shot;
};
static const int TIMERS_MAX = 2;
static TimerType timers_[TIMERS_MAX] = {{0}};
extern "C" void RISCV_break_simulation() {
if (pcore_->isExiting()) {
return;
}
pcore_->setExiting();
LibThreadType data;
data.func = reinterpret_cast<lib_thread_func>(safe_exit_thread);
data.args = 0;
RISCV_thread_create(&data);
}
extern "C" void RISCV_dispatcher_start() {
TimerType *tmr;
int sleep_interval = 20;
int delta;
while (pcore_->isActive()) {
delta = 20;
for (int i = 0; i < TIMERS_MAX; i++) {
tmr = &timers_[i];
if (!tmr->cb || !tmr->interval) {
continue;
}
tmr->delta -= sleep_interval;
if (tmr->delta <= 0) {
tmr->cb(tmr->args);
tmr->delta += tmr->interval;
if (tmr->single_shot) {
RISCV_unregister_timer(tmr->cb);
continue;
}
}
if (delta > tmr->delta) {
delta = tmr->delta;
}
}
sleep_interval = delta;
RISCV_sleep_ms(sleep_interval);
}
}
extern "C" void RISCV_register_timer(int msec, int single_shot,
timer_callback_type cb, void *args) {
TimerType *tmr = 0;
for (int i = 0; i < TIMERS_MAX; i++) {
if (timers_[i].cb == 0) {
tmr = &timers_[i];
break;
}
}
if (tmr == 0) {
RISCV_error("%s", "No available timer slot");
return;
}
tmr->cb = cb;
tmr->args = args;
tmr->interval = msec;
tmr->delta = msec;
tmr->single_shot = single_shot;
}
extern "C" void RISCV_unregister_timer(timer_callback_type cb) {
for (int i = 0; i < TIMERS_MAX; i++) {
if (timers_[i].cb == cb) {
timers_[i].cb = 0;
timers_[i].args = 0;
timers_[i].interval = 0;
timers_[i].delta = 0;
timers_[i].single_shot = 0;
}
}
}
} // namespace debugger
<commit_msg>[!] Fix bug in HAP callbacks. HAPs registered as HAP_all weren't called properly<commit_after>/**
* @file
* @copyright Copyright 2016 GNSS Sensor Ltd. All right reserved.
* @author Sergey Khabarov - sergeykhbr@gmail.com
* @brief Core API methods implementation.
*/
#include <string>
#include "api_core.h"
#include "api_types.h"
#include "iclass.h"
#include "ihap.h"
#include "coreservices/ithread.h"
#include "coreservices/iclock.h"
namespace debugger {
static AttributeType Config_;
static AttributeType listClasses_(Attr_List);
static AttributeType listHap_(Attr_List);
static AttributeType listPlugins_(Attr_List);
extern mutex_def mutex_printf;
extern mutex_def mutexDefaultConsoles_;
extern void _load_plugins(AttributeType *list);
extern void _unload_plugins(AttributeType *list);
class CoreService : public IService {
public:
CoreService(const char *name) : IService("CoreService") {
active_ = 1;
RISCV_mutex_init(&mutex_printf);
RISCV_mutex_init(&mutexDefaultConsoles_);
RISCV_event_create(&mutexExiting_, "mutexExiting_");
//logLevel_.make_int64(LOG_DEBUG); // default = LOG_ERROR
}
virtual ~CoreService() {
RISCV_event_close(&mutexExiting_);
}
int isActive() { return active_; }
void shutdown() { active_ = 0; }
bool isExiting() { return mutexExiting_.state; }
void setExiting() { RISCV_event_set(&mutexExiting_); }
private:
int active_;
event_def mutexExiting_;
};
static CoreService *pcore_ = NULL;
IFace *getInterface(const char *name) {
return pcore_->getInterface(name);
}
extern "C" int RISCV_init() {
pcore_ = new CoreService("core");
#if defined(_WIN32) || defined(__CYGWIN__)
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData)) {
RISCV_error("Can't initialize sockets library", NULL);
}
#endif
_load_plugins(&listPlugins_);
return 0;
}
extern "C" void RISCV_cleanup() {
IClass *icls;
// Pre-deletion
for (unsigned i = 0; i < listClasses_.size(); i++) {
icls = static_cast<IClass *>(listClasses_[i].to_iface());
icls->predeleteServices();
}
#if defined(_WIN32) || defined(__CYGWIN__)
WSACleanup();
#endif
_unload_plugins(&listPlugins_);
RISCV_mutex_lock(&mutex_printf);
RISCV_mutex_destroy(&mutex_printf);
RISCV_mutex_lock(&mutexDefaultConsoles_);
RISCV_mutex_destroy(&mutexDefaultConsoles_);
delete pcore_;
RISCV_disable_log();
}
extern "C" int RISCV_set_configuration(AttributeType *cfg) {
IClass *icls;
IService *iserv;
Config_.clone(cfg);
if (!Config_.is_dict()) {
RISCV_error("Wrong configuration.", NULL);
return -1;
}
AttributeType &Services = Config_["Services"];
if (Services.is_list()) {
for (unsigned i = 0; i < Services.size(); i++) {
const char *clsname = Services[i]["Class"].to_string();
icls = static_cast<IClass *>(RISCV_get_class(clsname));
if (icls == NULL) {
RISCV_error("Class %s not found",
Services[i]["Class"].to_string());
return -1;
}
/** Special global setting for the GUI class: */
if (strcmp(icls->getClassName(), "GuiPluginClass") == 0) {
if (!Config_["GlobalSettings"]["GUI"].to_bool()) {
RISCV_info("%s", "GUI disabled");
continue;
}
}
AttributeType &Instances = Services[i]["Instances"];
for (unsigned n = 0; n < Instances.size(); n++) {
iserv = icls->createService(Instances[n]["Name"].to_string());
iserv->initService(&Instances[n]["Attr"]);
}
}
}
// Post initialization
for (unsigned i = 0; i < listClasses_.size(); i++) {
icls = static_cast<IClass *>(listClasses_[i].to_iface());
icls->postinitServices();
}
RISCV_printf(getInterface(IFACE_SERVICE), 0, "%s",
"\n**********************************************************\n"
" RISC-V debugger\n"
" Author: Sergey Khabarov - sergeykhbr@gmail.com\n"
" Copyright 2016 GNSS Sensor Ltd. All right reserved.\n"
"**********************************************************");
IHap *ihap;
for (unsigned i = 0; i < listHap_.size(); i++) {
ihap = static_cast<IHap *>(listHap_[i].to_iface());
if (ihap->getType() == HAP_ConfigDone) {
ihap->hapTriggered(getInterface(IFACE_SERVICE),
HAP_ConfigDone, "Initial config done");
}
}
return 0;
}
extern "C" void RISCV_get_configuration(AttributeType *cfg) {
IClass *icls;
cfg->make_dict();
(*cfg)["GlobalSettings"] = Config_["GlobalSettings"];
(*cfg)["Services"].make_list(0);
for (unsigned i = 0; i < listClasses_.size(); i++) {
icls = static_cast<IClass *>(listClasses_[i].to_iface());
AttributeType val = icls->getConfiguration();
(*cfg)["Services"].add_to_list(&val);
}
cfg->to_config();
}
extern "C" const AttributeType *RISCV_get_global_settings() {
return &Config_["GlobalSettings"];
}
extern "C" void RISCV_register_class(IFace *icls) {
AttributeType item(icls);
listClasses_.add_to_list(&item);
}
extern "C" void RISCV_register_hap(IFace *ihap) {
AttributeType item(ihap);
listHap_.add_to_list(&item);
}
extern "C" void RISCV_trigger_hap(IFace *isrc, int type,
const char *descr) {
IHap *ihap;
EHapType etype = static_cast<EHapType>(type);
for (unsigned i = 0; i < listHap_.size(); i++) {
ihap = static_cast<IHap *>(listHap_[i].to_iface());
if (ihap->getType() == HAP_All || ihap->getType() == etype) {
ihap->hapTriggered(isrc, etype, descr);
}
}
}
extern "C" IFace *RISCV_get_class(const char *name) {
IClass *icls;
for (unsigned i = 0; i < listClasses_.size(); i++) {
icls = static_cast<IClass *>(listClasses_[i].to_iface());
if (strcmp(name, icls->getClassName()) == 0) {
return icls;
}
}
return NULL;
}
extern "C" IFace *RISCV_create_service(IFace *iclass, const char *name,
AttributeType *args) {
IClass *icls = static_cast<IClass *>(iclass);
IService *iobj = icls->createService(name);
iobj->initService(args);
iobj->postinitService();
return iobj;
}
extern "C" IFace *RISCV_get_service(const char *name) {
IClass *icls;
IService *iserv;
for (unsigned i = 0; i < listClasses_.size(); i++) {
icls = static_cast<IClass *>(listClasses_[i].to_iface());
if ((iserv = icls->getInstance(name)) != NULL) {
return iserv;
}
}
return NULL;
}
extern "C" IFace *RISCV_get_service_iface(const char *servname,
const char *facename) {
IService *iserv = static_cast<IService *>(RISCV_get_service(servname));
if (iserv == NULL) {
RISCV_error("Service '%s' not found.", servname);
return NULL;
}
return iserv->getInterface(facename);
}
extern "C" IFace *RISCV_get_service_port_iface(const char *servname,
const char *portname,
const char *facename) {
IService *iserv = static_cast<IService *>(RISCV_get_service(servname));
if (iserv == NULL) {
RISCV_error("Service '%s' not found.", servname);
return NULL;
}
return iserv->getPortInterface(portname, facename);
}
extern "C" void RISCV_get_services_with_iface(const char *iname,
AttributeType *list) {
IClass *icls;
IService *iserv;
IFace *iface;
const AttributeType *tlist;
list->make_list(0);
for (unsigned i = 0; i < listClasses_.size(); i++) {
icls = static_cast<IClass *>(listClasses_[i].to_iface());
tlist = icls->getInstanceList();
for (unsigned n = 0; n < tlist->size(); n++) {
iserv = static_cast<IService *>((*tlist)[n].to_iface());
iface = iserv->getInterface(iname);
if (iface) {
AttributeType t1(iserv);
list->add_to_list(&t1);
}
}
}
}
extern "C" void RISCV_get_clock_services(AttributeType *list) {
IService *iserv;
RISCV_get_services_with_iface(IFACE_CLOCK, list);
for (unsigned i = 0; i < list->size(); i++) {
iserv = static_cast<IService *>((*list)[i].to_iface());
(*list)[i].make_iface(iserv->getInterface(IFACE_CLOCK));
}
}
static thread_return_t safe_exit_thread(void *args) {
AttributeType t1, t2;
IService *iserv;
IThread *ith;
RISCV_get_services_with_iface(IFACE_THREAD, &t1);
for (unsigned i = 0; i < t1.size(); i++) {
iserv = static_cast<IService *>(t1[i].to_iface());
ith = static_cast<IThread *>(iserv->getInterface(IFACE_THREAD));
printf("Stopping thread service '%s'. . .", iserv->getObjName());
ith->stop();
printf("Stopped\n");
}
RISCV_trigger_hap(getInterface(IFACE_SERVICE),
HAP_BreakSimulation, "Exiting");
printf("All threads were stopped!\n");
pcore_->shutdown();
return 0;
}
struct TimerType {
timer_callback_type cb;
void *args;
int interval;
int delta;
int single_shot;
};
static const int TIMERS_MAX = 2;
static TimerType timers_[TIMERS_MAX] = {{0}};
extern "C" void RISCV_break_simulation() {
if (pcore_->isExiting()) {
return;
}
pcore_->setExiting();
LibThreadType data;
data.func = reinterpret_cast<lib_thread_func>(safe_exit_thread);
data.args = 0;
RISCV_thread_create(&data);
}
extern "C" void RISCV_dispatcher_start() {
TimerType *tmr;
int sleep_interval = 20;
int delta;
while (pcore_->isActive()) {
delta = 20;
for (int i = 0; i < TIMERS_MAX; i++) {
tmr = &timers_[i];
if (!tmr->cb || !tmr->interval) {
continue;
}
tmr->delta -= sleep_interval;
if (tmr->delta <= 0) {
tmr->cb(tmr->args);
tmr->delta += tmr->interval;
if (tmr->single_shot) {
RISCV_unregister_timer(tmr->cb);
continue;
}
}
if (delta > tmr->delta) {
delta = tmr->delta;
}
}
sleep_interval = delta;
RISCV_sleep_ms(sleep_interval);
}
}
extern "C" void RISCV_register_timer(int msec, int single_shot,
timer_callback_type cb, void *args) {
TimerType *tmr = 0;
for (int i = 0; i < TIMERS_MAX; i++) {
if (timers_[i].cb == 0) {
tmr = &timers_[i];
break;
}
}
if (tmr == 0) {
RISCV_error("%s", "No available timer slot");
return;
}
tmr->cb = cb;
tmr->args = args;
tmr->interval = msec;
tmr->delta = msec;
tmr->single_shot = single_shot;
}
extern "C" void RISCV_unregister_timer(timer_callback_type cb) {
for (int i = 0; i < TIMERS_MAX; i++) {
if (timers_[i].cb == cb) {
timers_[i].cb = 0;
timers_[i].args = 0;
timers_[i].interval = 0;
timers_[i].delta = 0;
timers_[i].single_shot = 0;
}
}
}
} // namespace debugger
<|endoftext|> |
<commit_before>// Copyright 2014 Toggl Desktop developers.
#include "./timeentrylistwidget.h"
#include "./ui_timeentrylistwidget.h"
#include "./toggl.h"
#include "./timerwidget.h"
#include "./timeentrycellwidget.h"
TimeEntryListWidget::TimeEntryListWidget(QWidget *parent) : QWidget(parent),
ui(new Ui::TimeEntryListWidget) {
ui->setupUi(this);
setVisible(false);
connect(TogglApi::instance, SIGNAL(displayLogin(bool,uint64_t)), // NOLINT
this, SLOT(displayLogin(bool,uint64_t))); // NOLINT
connect(TogglApi::instance, SIGNAL(displayTimeEntryList(bool,QVector<TimeEntryView*>)), // NOLINT
this, SLOT(displayTimeEntryList(bool,QVector<TimeEntryView*>))); // NOLINT
connect(TogglApi::instance, SIGNAL(displayTimeEntryEditor(bool,TimeEntryView*,QString)), // NOLINT
this, SLOT(displayTimeEntryEditor(bool,TimeEntryView*,QString))); // NOLINT
ui->blankView->setVisible(false);
}
TimeEntryListWidget::~TimeEntryListWidget() {
delete ui;
}
void TimeEntryListWidget::displayLogin(
const bool open,
const uint64_t user_id) {
if (open || !user_id) {
ui->list->clear();
setVisible(false);
}
}
void TimeEntryListWidget::displayTimeEntryList(
const bool open,
QVector<TimeEntryView *> list) {
if (open) {
setVisible(true);
}
render_m_.lock();
for (int i = 0; i < list.size(); i++) {
TimeEntryView *te = list.at(i);
QListWidgetItem *item = 0;
TimeEntryCellWidget *cell = 0;
if (ui->list->count() > i) {
item = ui->list->item(i);
cell = static_cast<TimeEntryCellWidget *>(ui->list->itemWidget(item));
}
if (!item) {
item = new QListWidgetItem();
cell = new TimeEntryCellWidget();
ui->list->addItem(item);
ui->list->setItemWidget(item, cell);
}
item->setSizeHint(cell->getSizeHint(te->IsHeader));
cell->display(te);
}
while (ui->list->count() > list.size())
{
ui->list->model()->removeRow(list.size());
}
ui->list->setVisible(!list.isEmpty());
ui->blankView->setVisible(list.isEmpty());
render_m_.unlock();
}
void TimeEntryListWidget::displayTimeEntryEditor(
const bool open,
TimeEntryView *view,
const QString focused_field_name) {
if (open) {
setVisible(false);
}
}
void TimeEntryListWidget::on_blankView_linkActivated(const QString &link)
{
TogglApi::instance->openInBrowser();
}
<commit_msg>Fixed window resizing after entry edit (linux), closes #1109<commit_after>// Copyright 2014 Toggl Desktop developers.
#include "./timeentrylistwidget.h"
#include "./ui_timeentrylistwidget.h"
#include "./toggl.h"
#include "./timerwidget.h"
#include "./timeentrycellwidget.h"
TimeEntryListWidget::TimeEntryListWidget(QWidget *parent) : QWidget(parent),
ui(new Ui::TimeEntryListWidget) {
ui->setupUi(this);
setVisible(false);
connect(TogglApi::instance, SIGNAL(displayLogin(bool,uint64_t)), // NOLINT
this, SLOT(displayLogin(bool,uint64_t))); // NOLINT
connect(TogglApi::instance, SIGNAL(displayTimeEntryList(bool,QVector<TimeEntryView*>)), // NOLINT
this, SLOT(displayTimeEntryList(bool,QVector<TimeEntryView*>))); // NOLINT
connect(TogglApi::instance, SIGNAL(displayTimeEntryEditor(bool,TimeEntryView*,QString)), // NOLINT
this, SLOT(displayTimeEntryEditor(bool,TimeEntryView*,QString))); // NOLINT
ui->blankView->setVisible(false);
}
TimeEntryListWidget::~TimeEntryListWidget() {
delete ui;
}
void TimeEntryListWidget::displayLogin(
const bool open,
const uint64_t user_id) {
if (open || !user_id) {
ui->list->clear();
setVisible(false);
}
}
void TimeEntryListWidget::displayTimeEntryList(
const bool open,
QVector<TimeEntryView *> list) {
if (open) {
setVisible(true);
}
setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
render_m_.lock();
for (int i = 0; i < list.size(); i++) {
TimeEntryView *te = list.at(i);
QListWidgetItem *item = 0;
TimeEntryCellWidget *cell = 0;
if (ui->list->count() > i) {
item = ui->list->item(i);
cell = static_cast<TimeEntryCellWidget *>(ui->list->itemWidget(item));
}
if (!item) {
item = new QListWidgetItem();
cell = new TimeEntryCellWidget();
ui->list->addItem(item);
ui->list->setItemWidget(item, cell);
}
item->setSizeHint(cell->getSizeHint(te->IsHeader));
cell->display(te);
}
while (ui->list->count() > list.size())
{
ui->list->model()->removeRow(list.size());
}
ui->list->setVisible(!list.isEmpty());
ui->blankView->setVisible(list.isEmpty());
render_m_.unlock();
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
}
void TimeEntryListWidget::displayTimeEntryEditor(
const bool open,
TimeEntryView *view,
const QString focused_field_name) {
if (open) {
setVisible(false);
}
}
void TimeEntryListWidget::on_blankView_linkActivated(const QString &link)
{
TogglApi::instance->openInBrowser();
}
<|endoftext|> |
<commit_before>/* Copyright 2017 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/compiler/xla/util.h"
#include <list>
#include "tensorflow/compiler/xla/test.h"
#include "tensorflow/compiler/xla/types.h"
namespace xla {
namespace {
// Verifies that, even with a different number of leading spaces, the
// Reindent routine turns them into a uniform number of leading spaces.
//
// Also throws in some trailing whitespace on the original to show it is
// removed.
TEST(UtilTest, ReindentsDifferentNumberOfLeadingSpacesUniformly) {
string original = R"( hello there
world)";
string got = Reindent(original, " ");
string want = R"( hello there
world)";
EXPECT_EQ(want, got);
}
TEST(UtilTest, HumanReadableNumFlopsExample) {
ASSERT_EQ("1.00GFLOP/s", HumanReadableNumFlops(1e9, 1e9));
}
TEST(UtilTest, CommaSeparatedString) {
EXPECT_EQ(CommaSeparatedString({}), "");
EXPECT_EQ(CommaSeparatedString({"hello world"}), "hello world");
EXPECT_EQ(CommaSeparatedString({1, 57, 2}, "foo", "bar"), "foo1, 57, 2bar");
}
TEST(UtilTest, VectorString) {
std::list<int64> empty_list;
EXPECT_EQ(VectorString(empty_list), "()");
std::vector<float> float_vector = {5.5};
EXPECT_EQ(VectorString(float_vector), "(5.5)");
std::set<const char*> string_set = {"a", "b"};
EXPECT_EQ(VectorString(string_set), "(a, b)");
EXPECT_EQ(VectorString({}), "()");
EXPECT_EQ(VectorString({1, 57, 2}), "(1, 57, 2)");
}
TEST(UtilTest, LogLines) {
// Just make sure this code runs (not verifying the output).
LogLines(tensorflow::INFO, "hello\n\nworld", __FILE__, __LINE__);
}
TEST(UtilTest, CommonFactors) {
struct {
std::vector<int64> a, b;
std::vector<std::pair<int64, int64>> expected;
} test_cases[] = {
{/*.a =*/{0}, /*.b =*/{0}, /*.expected =*/{{0, 0}, {1, 1}}},
{/*.a =*/{}, /*.b =*/{}, /*.expected =*/{{0, 0}}},
{/*.a =*/{2, 5, 1, 3},
/*.b =*/{1, 10, 3, 1},
/*.expected =*/{{0, 0}, {0, 1}, {2, 2}, {3, 2}, {4, 3}, {4, 4}}},
};
for (const auto& test_case : test_cases) {
EXPECT_TRUE(absl::c_equal(test_case.expected,
CommonFactors(test_case.a, test_case.b)));
}
}
TEST(UtilTest, SanitizeFileName) {
EXPECT_EQ(SanitizeFileName(""), "");
EXPECT_EQ(SanitizeFileName("abc"), "abc");
EXPECT_EQ(SanitizeFileName("/\\[]"), "____");
EXPECT_EQ(SanitizeFileName("/A\\B[C]"), "_A_B_C_");
}
} // namespace
} // namespace xla
<commit_msg>[XLA] Add more tests to ShapeUtil::CommonFactors with degenerated dimensions.<commit_after>/* Copyright 2017 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/compiler/xla/util.h"
#include <list>
#include "tensorflow/compiler/xla/test.h"
#include "tensorflow/compiler/xla/types.h"
namespace xla {
namespace {
// Verifies that, even with a different number of leading spaces, the
// Reindent routine turns them into a uniform number of leading spaces.
//
// Also throws in some trailing whitespace on the original to show it is
// removed.
TEST(UtilTest, ReindentsDifferentNumberOfLeadingSpacesUniformly) {
string original = R"( hello there
world)";
string got = Reindent(original, " ");
string want = R"( hello there
world)";
EXPECT_EQ(want, got);
}
TEST(UtilTest, HumanReadableNumFlopsExample) {
ASSERT_EQ("1.00GFLOP/s", HumanReadableNumFlops(1e9, 1e9));
}
TEST(UtilTest, CommaSeparatedString) {
EXPECT_EQ(CommaSeparatedString({}), "");
EXPECT_EQ(CommaSeparatedString({"hello world"}), "hello world");
EXPECT_EQ(CommaSeparatedString({1, 57, 2}, "foo", "bar"), "foo1, 57, 2bar");
}
TEST(UtilTest, VectorString) {
std::list<int64> empty_list;
EXPECT_EQ(VectorString(empty_list), "()");
std::vector<float> float_vector = {5.5};
EXPECT_EQ(VectorString(float_vector), "(5.5)");
std::set<const char*> string_set = {"a", "b"};
EXPECT_EQ(VectorString(string_set), "(a, b)");
EXPECT_EQ(VectorString({}), "()");
EXPECT_EQ(VectorString({1, 57, 2}), "(1, 57, 2)");
}
TEST(UtilTest, LogLines) {
// Just make sure this code runs (not verifying the output).
LogLines(tensorflow::INFO, "hello\n\nworld", __FILE__, __LINE__);
}
TEST(UtilTest, CommonFactors) {
struct {
std::vector<int64> a, b;
std::vector<std::pair<int64, int64>> expected;
} test_cases[] = {
{/*.a =*/{0}, /*.b =*/{0}, /*.expected =*/{{0, 0}, {1, 1}}},
{/*.a =*/{}, /*.b =*/{}, /*.expected =*/{{0, 0}}},
{/*.a =*/{2, 5, 1, 3},
/*.b =*/{1, 10, 3, 1},
/*.expected =*/{{0, 0}, {0, 1}, {2, 2}, {3, 2}, {4, 3}, {4, 4}}},
{/*.a =*/{1, 1, 3},
/*.b =*/{1, 1, 3},
/*.expected =*/{{0, 0}, {1, 1}, {2, 2}, {3, 3}}},
// Splitting and combining dimensions.
{/*.a =*/{2, 6},
/*.b =*/{4, 3},
/*.expected =*/{{0, 0}, {2, 2}}},
{/*.a =*/{1, 2, 6},
/*.b =*/{4, 1, 3, 1},
/*.expected =*/{{0, 0}, {1, 0}, {3, 3}, {3, 4}}},
// Extra degenerated dimension (second and third dims in the output) forms
// single common factor group.
{/*.a =*/{1, 2, 1},
/*.b =*/{1, 1, 1, 2},
/*.expected =*/{{0, 0}, {1, 1}, {1, 2}, {1, 3}, {2, 4}, {3, 4}}}};
for (const auto& test_case : test_cases) {
EXPECT_EQ(test_case.expected, CommonFactors(test_case.a, test_case.b));
}
}
TEST(UtilTest, SanitizeFileName) {
EXPECT_EQ(SanitizeFileName(""), "");
EXPECT_EQ(SanitizeFileName("abc"), "abc");
EXPECT_EQ(SanitizeFileName("/\\[]"), "____");
EXPECT_EQ(SanitizeFileName("/A\\B[C]"), "_A_B_C_");
}
} // namespace
} // namespace xla
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/isteps/istep06/call_host_voltage_config.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2017 */
/* [+] 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 */
#include <stdint.h>
#include <trace/interface.H>
#include <errl/errlentry.H>
#include <errl/errlmanager.H>
#include <isteps/hwpisteperror.H>
#include <initservice/isteps_trace.H>
#include <fapi2.H>
#include <fapi2/plat_hwp_invoker.H>
//Targeting
#include <targeting/common/commontargeting.H>
#include <targeting/common/util.H>
#include <targeting/common/utilFilter.H>
#include <targeting/common/target.H>
#include <p9_pm_get_poundv_bucket.H>
#include <p9_setup_evid.H>
#include <p9_frequency_buckets.H>
#include <initservice/mboxRegs.H>
using namespace TARGETING;
namespace ISTEP_06
{
errlHndl_t getBootNestFreq( uint32_t & o_bootNestFreq )
{
errlHndl_t l_err = nullptr;
INITSERVICE::SPLESS::MboxScratch4_t l_scratch4;
TARGETING::Target * l_sys = nullptr;
(void) TARGETING::targetService().getTopLevelTarget( l_sys );
assert( l_sys, "getBootNestFreq() system target is NULL");
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
ENTER_MRK"Enter getBootNestFreq()");
do
{
TARGETING::ATTR_MASTER_MBOX_SCRATCH_type l_scratchRegs;
assert(l_sys->tryGetAttr
<TARGETING::ATTR_MASTER_MBOX_SCRATCH>(l_scratchRegs),
"getBootNestFreq() failed to get MASTER_MBOX_SCRATCH");
l_scratch4.data32 = l_scratchRegs[INITSERVICE::SPLESS::SCRATCH_4];
TRACDCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"The nest PLL bucket id is %d",
l_scratch4.nestPllBucket );
size_t sizeOfPll = sizeof(NEST_PLL_FREQ_LIST)/
sizeof(NEST_PLL_FREQ_LIST[0]);
assert((uint8_t)(l_scratch4.nestPllBucket-1) < (uint8_t) sizeOfPll );
// The nest PLL bucket IDs are numbered 1 - 5. Subtract 1 to
// take zero-based indexing into account.
o_bootNestFreq = NEST_PLL_FREQ_LIST[l_scratch4.nestPllBucket-1];
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"getBootNestFreq::The boot frequency was %d: Bucket Id = %d",
o_bootNestFreq,
l_scratch4.nestPllBucket );
}while( 0 );
TRACDCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
EXIT_MRK "Exit getBootNestFreq()");
return l_err;
}
void* call_host_voltage_config( void *io_pArgs )
{
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"call_host_voltage_config entry" );
ISTEP_ERROR::IStepError l_stepError;
errlHndl_t l_err = nullptr;
Target * l_sys = nullptr;
TargetHandleList l_procList;
TargetHandleList l_eqList;
fapi2::voltageBucketData_t l_voltageData;
fapi2::ReturnCode l_rc;
uint32_t l_nominalFreq = 0; //ATTR_NOMINAL_FREQ_MHZ
uint32_t l_floorFreq = 0; //ATTR_FREQ_FLOOR_MHZ
uint32_t l_ceilingFreq = 0; //ATTR_FREQ_CORE_CEILING_MHZ
uint32_t l_ultraTurboFreq = 0; //ATTR_ULTRA_TURBO_FREQ_MHZ
uint32_t l_turboFreq = 0; //ATTR_FREQ_CORE_MAX
uint32_t l_vddBootVoltage = 0; //ATTR_VDD_BOOT_VOLTAGE
uint32_t l_vdnBootVoltage = 0; //ATTR_VDN_BOOT_VOLTAGE
uint32_t l_vcsBootVoltage = 0; //ATTR_VCS_BOOT_VOLTAGE
uint32_t l_nestFreq = 0; //ATTR_FREQ_PB_MHZ
bool l_firstPass = true;
PredicateCTM l_eqFilter(CLASS_UNIT, TYPE_EQ);
PredicateHwas l_predPres;
l_predPres.present(true);
PredicatePostfixExpr l_presentEqs;
l_presentEqs.push(&l_eqFilter).push(&l_predPres).And();
do
{
// Get the system target
targetService().getTopLevelTarget(l_sys);
// Set the Nest frequency to whatever we boot with
l_err = getBootNestFreq( l_nestFreq );
if( l_err )
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_host_voltage_config.C::"
"Failed getting the boot nest frequency");
break;
}
l_sys->setAttr<TARGETING::ATTR_FREQ_PB_MHZ>( l_nestFreq );
// Get the child proc chips
getChildAffinityTargets( l_procList,
l_sys,
CLASS_CHIP,
TYPE_PROC );
// for each proc target
for( const auto & l_proc : l_procList )
{
// get the child EQ targets
targetService().getAssociated(
l_eqList,
l_proc,
TargetService::CHILD_BY_AFFINITY,
TargetService::ALL,
&l_presentEqs );
if( l_eqList.empty() )
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"No children of proc 0x%x found to have type EQ",
get_huid(l_proc));
/*@
* @errortype
* @moduleid ISTEP::MOD_VOLTAGE_CONFIG
* @reasoncode ISTEP::RC_NO_PRESENT_EQS
* @userdata1 Parent PROC huid
* @devdesc No present EQs found on processor
* @custdesc A problem occurred during the IPL of the system.
*/
l_err = new ERRORLOG::ErrlEntry
(ERRORLOG::ERRL_SEV_CRITICAL_SYS_TERM,
ISTEP::MOD_VOLTAGE_CONFIG,
ISTEP::RC_NO_PRESENT_EQS,
get_huid(l_proc),
0,
true /*HB SW error*/ );
l_err->addHwCallout(l_proc,
HWAS::SRCI_PRIORITY_HIGH,
HWAS::NO_DECONFIG,
HWAS::GARD_NULL );
// We will allow this for the lab as long as this isn't the
// master processor
TARGETING::Target* l_masterProc = NULL;
targetService().masterProcChipTargetHandle( l_masterProc );
if( l_masterProc == l_proc )
{
break;
}
// Commit Error
errlCommit( l_err, ISTEP_COMP_ID );
continue;
}
// for each child EQ target
for( const auto & l_eq : l_eqList )
{
// cast to fapi2 target
fapi2::Target<fapi2::TARGET_TYPE_EQ> l_fapiEq( l_eq );
// get the #V data for this EQ
FAPI_INVOKE_HWP( l_err,
p9_pm_get_poundv_bucket,
l_fapiEq,
l_voltageData);
if( l_err )
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"Error in call_host_voltage_config::p9_pm_get_poundv_bucket");
// Create IStep error log and cross reference occurred error
l_stepError.addErrorDetails( l_err );
// Commit Error
errlCommit( l_err, ISTEP_COMP_ID );
continue;
}
// Save the voltage data for future comparison
if( l_firstPass )
{
l_nominalFreq = l_voltageData.nomFreq;
l_floorFreq = l_voltageData.PSFreq;
l_ceilingFreq = l_voltageData.turboFreq;
l_ultraTurboFreq = l_voltageData.uTurboFreq;
l_turboFreq = l_voltageData.turboFreq;
l_vddBootVoltage = l_voltageData.VddPSVltg;
l_vdnBootVoltage = l_voltageData.VdnPbVltg;
l_vcsBootVoltage = l_voltageData.VcsPSVltg;
l_firstPass = false;
}
else
{
// save it to variable and compare agains other nomFreq
// All of the buckets should report the same Nominal frequency
if( l_nominalFreq != l_voltageData.nomFreq )
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"NOMINAL FREQ MISMATCH! expected: %d actual: %d",
l_nominalFreq, l_voltageData.nomFreq );
l_err = new ERRORLOG::ErrlEntry
(ERRORLOG::ERRL_SEV_CRITICAL_SYS_TERM,
ISTEP::MOD_VOLTAGE_CONFIG,
ISTEP::RC_NOMINAL_FREQ_MISMATCH,
l_nominalFreq,
l_voltageData.nomFreq,
false );
l_err->addHwCallout(l_proc,
HWAS::SRCI_PRIORITY_HIGH,
HWAS::DECONFIG,
HWAS::GARD_NULL );
// Create IStep error log and cross reference occurred error
l_stepError.addErrorDetails( l_err );
// Commit Error
errlCommit( l_err, ISTEP_COMP_ID );
continue;
}
// Floor frequency is the maximum of the Power Save Freqs
l_floorFreq =
(l_voltageData.PSFreq > l_floorFreq) ? l_voltageData.PSFreq : l_floorFreq;
// Ceiling frequency is the minimum of the Turbo Freqs
l_ceilingFreq = (l_voltageData.turboFreq < l_ceilingFreq) ?
l_voltageData.turboFreq : l_ceilingFreq;
// Ultra Turbo frequency is the minimum of the Ultra Turbo Freqs
l_ultraTurboFreq = (l_voltageData.uTurboFreq < l_ultraTurboFreq) ?
l_voltageData.uTurboFreq : l_ultraTurboFreq;
// Turbo frequency is the minimum of the Turbo Freqs
l_turboFreq = l_ceilingFreq;
}
} // EQ for-loop
// set the approprate attributes on the processor
l_proc->setAttr<ATTR_VDD_BOOT_VOLTAGE>( l_vddBootVoltage );
l_proc->setAttr<ATTR_VDN_BOOT_VOLTAGE>( l_vdnBootVoltage );
l_proc->setAttr<ATTR_VCS_BOOT_VOLTAGE>( l_vcsBootVoltage );
TRACDCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"Setting VDD/VDN/VCS boot voltage for proc huid = 0x%x"
" VDD = %d, VDN = %d, VCS = %d",
get_huid(l_proc),
l_vddBootVoltage,
l_vdnBootVoltage,
l_vcsBootVoltage );
// call p9_setup_evid for each processor
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>l_fapiProc(l_proc);
FAPI_INVOKE_HWP(l_err, p9_setup_evid, l_fapiProc, COMPUTE_VOLTAGE_SETTINGS);
if( l_err )
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"Error in call_host_voltage_config::p9_setup_evid");
// Create IStep error log and cross reference occurred error
l_stepError.addErrorDetails( l_err );
// Commit Error
errlCommit( l_err, ISTEP_COMP_ID );
continue;
}
} // PROC for-loop
// If we hit an error from p9_setup_evid, quit
if( l_err )
{
break;
}
// set the frequency system targets
l_sys->setAttr<ATTR_NOMINAL_FREQ_MHZ>( l_nominalFreq );
l_sys->setAttr<ATTR_MIN_FREQ_MHZ>( l_floorFreq );
l_sys->setAttr<ATTR_FREQ_CORE_CEILING_MHZ>( l_ceilingFreq );
l_sys->setAttr<ATTR_FREQ_CORE_MAX>( l_turboFreq );
l_sys->setAttr<ATTR_ULTRA_TURBO_FREQ_MHZ>(l_ultraTurboFreq);
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"Setting System Frequency Attributes: "
"Nominal = %d, Floor = %d, Ceiling = %d, "
"Turbo = %d, UltraTurbo = %d",
l_nominalFreq, l_floorFreq, l_ceilingFreq,
l_turboFreq, l_ultraTurboFreq );
// Setup the remaining attributes that are based on PB/Nest
TARGETING::setFrequencyAttributes(l_sys,
l_nestFreq);
} while( 0 );
if( l_err )
{
// Create IStep error log and cross reference occurred error
l_stepError.addErrorDetails( l_err );
// Commit Error
errlCommit( l_err, ISTEP_COMP_ID );
}
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"call_host_voltage_config exit" );
return l_stepError.getErrorHandle();
}
};
<commit_msg>p9_setup_evid: add system parm (loadline, etc) support<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/isteps/istep06/call_host_voltage_config.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2017 */
/* [+] 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 */
#include <stdint.h>
#include <trace/interface.H>
#include <errl/errlentry.H>
#include <errl/errlmanager.H>
#include <isteps/hwpisteperror.H>
#include <initservice/isteps_trace.H>
#include <fapi2.H>
#include <fapi2/plat_hwp_invoker.H>
//Targeting
#include <targeting/common/commontargeting.H>
#include <targeting/common/util.H>
#include <targeting/common/utilFilter.H>
#include <targeting/common/target.H>
#include <p9_pm_get_poundv_bucket.H>
#include <p9_setup_evid.H>
#include <p9_frequency_buckets.H>
#include <initservice/mboxRegs.H>
using namespace TARGETING;
namespace ISTEP_06
{
errlHndl_t getBootNestFreq( uint32_t & o_bootNestFreq )
{
errlHndl_t l_err = nullptr;
INITSERVICE::SPLESS::MboxScratch4_t l_scratch4;
TARGETING::Target * l_sys = nullptr;
(void) TARGETING::targetService().getTopLevelTarget( l_sys );
assert( l_sys, "getBootNestFreq() system target is NULL");
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
ENTER_MRK"Enter getBootNestFreq()");
do
{
TARGETING::ATTR_MASTER_MBOX_SCRATCH_type l_scratchRegs;
assert(l_sys->tryGetAttr
<TARGETING::ATTR_MASTER_MBOX_SCRATCH>(l_scratchRegs),
"getBootNestFreq() failed to get MASTER_MBOX_SCRATCH");
l_scratch4.data32 = l_scratchRegs[INITSERVICE::SPLESS::SCRATCH_4];
TRACDCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"The nest PLL bucket id is %d",
l_scratch4.nestPllBucket );
size_t sizeOfPll = sizeof(NEST_PLL_FREQ_LIST)/
sizeof(NEST_PLL_FREQ_LIST[0]);
assert((uint8_t)(l_scratch4.nestPllBucket-1) < (uint8_t) sizeOfPll );
// The nest PLL bucket IDs are numbered 1 - 5. Subtract 1 to
// take zero-based indexing into account.
o_bootNestFreq = NEST_PLL_FREQ_LIST[l_scratch4.nestPllBucket-1];
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"getBootNestFreq::The boot frequency was %d: Bucket Id = %d",
o_bootNestFreq,
l_scratch4.nestPllBucket );
}while( 0 );
TRACDCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
EXIT_MRK "Exit getBootNestFreq()");
return l_err;
}
void* call_host_voltage_config( void *io_pArgs )
{
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"call_host_voltage_config entry" );
ISTEP_ERROR::IStepError l_stepError;
errlHndl_t l_err = nullptr;
Target * l_sys = nullptr;
TargetHandleList l_procList;
TargetHandleList l_eqList;
fapi2::voltageBucketData_t l_voltageData;
fapi2::ReturnCode l_rc;
uint32_t l_nominalFreq = 0; //ATTR_NOMINAL_FREQ_MHZ
uint32_t l_floorFreq = 0; //ATTR_FREQ_FLOOR_MHZ
uint32_t l_ceilingFreq = 0; //ATTR_FREQ_CORE_CEILING_MHZ
uint32_t l_ultraTurboFreq = 0; //ATTR_ULTRA_TURBO_FREQ_MHZ
uint32_t l_turboFreq = 0; //ATTR_FREQ_CORE_MAX
uint32_t l_nestFreq = 0; //ATTR_FREQ_PB_MHZ
bool l_firstPass = true;
PredicateCTM l_eqFilter(CLASS_UNIT, TYPE_EQ);
PredicateHwas l_predPres;
l_predPres.present(true);
PredicatePostfixExpr l_presentEqs;
l_presentEqs.push(&l_eqFilter).push(&l_predPres).And();
do
{
// Get the system target
targetService().getTopLevelTarget(l_sys);
// Set the Nest frequency to whatever we boot with
l_err = getBootNestFreq( l_nestFreq );
if( l_err )
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_host_voltage_config.C::"
"Failed getting the boot nest frequency");
break;
}
l_sys->setAttr<TARGETING::ATTR_FREQ_PB_MHZ>( l_nestFreq );
// Get the child proc chips
getChildAffinityTargets( l_procList,
l_sys,
CLASS_CHIP,
TYPE_PROC );
// for each proc target
for( const auto & l_proc : l_procList )
{
// get the child EQ targets
targetService().getAssociated(
l_eqList,
l_proc,
TargetService::CHILD_BY_AFFINITY,
TargetService::ALL,
&l_presentEqs );
if( l_eqList.empty() )
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"No children of proc 0x%x found to have type EQ",
get_huid(l_proc));
/*@
* @errortype
* @moduleid ISTEP::MOD_VOLTAGE_CONFIG
* @reasoncode ISTEP::RC_NO_PRESENT_EQS
* @userdata1 Parent PROC huid
* @devdesc No present EQs found on processor
* @custdesc A problem occurred during the IPL of the system.
*/
l_err = new ERRORLOG::ErrlEntry
(ERRORLOG::ERRL_SEV_CRITICAL_SYS_TERM,
ISTEP::MOD_VOLTAGE_CONFIG,
ISTEP::RC_NO_PRESENT_EQS,
get_huid(l_proc),
0,
true /*HB SW error*/ );
l_err->addHwCallout(l_proc,
HWAS::SRCI_PRIORITY_HIGH,
HWAS::NO_DECONFIG,
HWAS::GARD_NULL );
// We will allow this for the lab as long as this isn't the
// master processor
TARGETING::Target* l_masterProc = NULL;
targetService().masterProcChipTargetHandle( l_masterProc );
if( l_masterProc == l_proc )
{
break;
}
// Commit Error
errlCommit( l_err, ISTEP_COMP_ID );
continue;
}
// for each child EQ target
for( const auto & l_eq : l_eqList )
{
// cast to fapi2 target
fapi2::Target<fapi2::TARGET_TYPE_EQ> l_fapiEq( l_eq );
// get the #V data for this EQ
FAPI_INVOKE_HWP( l_err,
p9_pm_get_poundv_bucket,
l_fapiEq,
l_voltageData);
if( l_err )
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"Error in call_host_voltage_config::p9_pm_get_poundv_bucket");
// Create IStep error log and cross reference occurred error
l_stepError.addErrorDetails( l_err );
// Commit Error
errlCommit( l_err, ISTEP_COMP_ID );
continue;
}
// Save the freq data for future comparison
if( l_firstPass )
{
l_nominalFreq = l_voltageData.nomFreq;
l_floorFreq = l_voltageData.PSFreq;
l_ceilingFreq = l_voltageData.turboFreq;
l_ultraTurboFreq = l_voltageData.uTurboFreq;
l_turboFreq = l_voltageData.turboFreq;
l_firstPass = false;
}
else
{
// save it to variable and compare agains other nomFreq
// All of the buckets should report the same Nominal frequency
if( l_nominalFreq != l_voltageData.nomFreq )
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"NOMINAL FREQ MISMATCH! expected: %d actual: %d",
l_nominalFreq, l_voltageData.nomFreq );
l_err = new ERRORLOG::ErrlEntry
(ERRORLOG::ERRL_SEV_CRITICAL_SYS_TERM,
ISTEP::MOD_VOLTAGE_CONFIG,
ISTEP::RC_NOMINAL_FREQ_MISMATCH,
l_nominalFreq,
l_voltageData.nomFreq,
false );
l_err->addHwCallout(l_proc,
HWAS::SRCI_PRIORITY_HIGH,
HWAS::DECONFIG,
HWAS::GARD_NULL );
// Create IStep error log and cross reference occurred error
l_stepError.addErrorDetails( l_err );
// Commit Error
errlCommit( l_err, ISTEP_COMP_ID );
continue;
}
// Floor frequency is the maximum of the Power Save Freqs
l_floorFreq =
(l_voltageData.PSFreq > l_floorFreq) ? l_voltageData.PSFreq : l_floorFreq;
// Ceiling frequency is the minimum of the Turbo Freqs
l_ceilingFreq = (l_voltageData.turboFreq < l_ceilingFreq) ?
l_voltageData.turboFreq : l_ceilingFreq;
// Ultra Turbo frequency is the minimum of the Ultra Turbo Freqs
l_ultraTurboFreq = (l_voltageData.uTurboFreq < l_ultraTurboFreq) ?
l_voltageData.uTurboFreq : l_ultraTurboFreq;
// Turbo frequency is the minimum of the Turbo Freqs
l_turboFreq = l_ceilingFreq;
}
} // EQ for-loop
// Don't set the boot voltage ATTR -- instead the
// setup_evid will calculate from each chips #V and factor
// in loadline/distloss/etc
// call p9_setup_evid for each processor
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>l_fapiProc(l_proc);
FAPI_INVOKE_HWP(l_err, p9_setup_evid, l_fapiProc, COMPUTE_VOLTAGE_SETTINGS);
if( l_err )
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"Error in call_host_voltage_config::p9_setup_evid");
// Create IStep error log and cross reference occurred error
l_stepError.addErrorDetails( l_err );
// Commit Error
errlCommit( l_err, ISTEP_COMP_ID );
continue;
}
} // PROC for-loop
// If we hit an error from p9_setup_evid, quit
if( l_err )
{
break;
}
// set the frequency system targets
l_sys->setAttr<ATTR_NOMINAL_FREQ_MHZ>( l_nominalFreq );
l_sys->setAttr<ATTR_MIN_FREQ_MHZ>( l_floorFreq );
l_sys->setAttr<ATTR_FREQ_CORE_CEILING_MHZ>( l_ceilingFreq );
l_sys->setAttr<ATTR_FREQ_CORE_MAX>( l_turboFreq );
l_sys->setAttr<ATTR_ULTRA_TURBO_FREQ_MHZ>(l_ultraTurboFreq);
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"Setting System Frequency Attributes: "
"Nominal = %d, Floor = %d, Ceiling = %d, "
"Turbo = %d, UltraTurbo = %d",
l_nominalFreq, l_floorFreq, l_ceilingFreq,
l_turboFreq, l_ultraTurboFreq );
// Setup the remaining attributes that are based on PB/Nest
TARGETING::setFrequencyAttributes(l_sys,
l_nestFreq);
} while( 0 );
if( l_err )
{
// Create IStep error log and cross reference occurred error
l_stepError.addErrorDetails( l_err );
// Commit Error
errlCommit( l_err, ISTEP_COMP_ID );
}
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"call_host_voltage_config exit" );
return l_stepError.getErrorHandle();
}
};
<|endoftext|> |
<commit_before>/* Copyright 2015 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.
==============================================================================*/
// See docs in ../ops/data_flow_ops.cc.
#include <limits.h>
#include <atomic>
#include <vector>
#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/framework/device_base.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/refcount.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/thread_annotations.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;
class Stack : public ResourceBase {
public:
static std::atomic<int64> stack_counter;
struct TensorAndAllocation {
Tensor tensor;
AllocatorAttributes alloc_attrs;
bool swapped_to_cpu;
};
Stack(const DataType& elem_type, const Tensor& handle)
: elem_type_(elem_type), handle_(handle), closed_(false) {}
Status Push(const TensorAndAllocation& value) {
mutex_lock l(mu_);
TF_RETURN_IF_ERROR(CheckNotClosed());
stack_.push_back(value);
return Status::OK();
}
Status Pop(TensorAndAllocation* value) {
mutex_lock l(mu_);
TF_RETURN_IF_ERROR(CheckNotClosed());
if (stack_.empty()) {
const string& stack_name = handle_.vec<string>()(1);
return errors::InvalidArgument("Stack[", stack_name,
"] is empty when calling Pop().");
}
*value = stack_.back();
stack_.pop_back();
return Status::OK();
}
// We don't swap the first tensor on the stack and any subsequent tensors
// that share the buffer with the first tensor.
bool IsUsefulToSwap(const Tensor& tensor) const {
mutex_lock l(mu_);
if (stack_.empty()) {
return false;
}
const Tensor& first = stack_.front().tensor;
return !tensor.SharesBufferWith(first);
}
void Close() {
mutex_lock l(mu_);
stack_.clear();
closed_ = true;
}
DataType ElemType() { return elem_type_; }
string DebugString() override {
mutex_lock l(mu_);
const string& stack_name = handle_.vec<string>()(1);
return strings::StrCat("Stack[", stack_name, "]");
}
private:
friend class StackOp;
mutex* mu() { return &mu_; }
Tensor* handle() { return &handle_; }
mutable mutex mu_;
DataType elem_type_;
Tensor handle_;
bool closed_ GUARDED_BY(mu_);
std::vector<TensorAndAllocation> stack_ GUARDED_BY(mu_);
Status CheckNotClosed() const EXCLUSIVE_LOCKS_REQUIRED(mu_) {
if (closed_) {
const string& stack_name = handle_.vec<string>()(1);
return errors::InvalidArgument("Stack[", stack_name,
"] has already been closed.");
}
return Status::OK();
}
};
Status GetStack(OpKernelContext* ctx, Stack** stack) {
Tensor Tstack_handle = ctx->mutable_input(0, false);
if (Tstack_handle.NumElements() != 2) {
return errors::InvalidArgument(
"Stack handle must have two elements, but had shape: ",
Tstack_handle.shape().DebugString());
}
const string& container = Tstack_handle.flat<string>()(0);
const string& stack_name = Tstack_handle.flat<string>()(1);
ResourceMgr* rm = ctx->resource_manager();
if (rm == nullptr) {
return errors::Internal("No resource manager.");
}
TF_RETURN_IF_ERROR(rm->Lookup(ctx->step_container()->name(),
strings::StrCat(container, stack_name), stack));
return Status::OK();
}
std::atomic<int64> Stack::stack_counter{0};
// A per-run local stack. The stack uses a "per-step" resource manager which
// ensures that correct garbage collection on error or successful completion.
class StackOp : public OpKernel {
public:
explicit StackOp(OpKernelConstruction* context) : OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("elem_type", &elem_type_));
OP_REQUIRES_OK(context, context->GetAttr("stack_name", &stack_name_));
if (stack_name_ == "") stack_name_ = name();
}
void Compute(OpKernelContext* ctx) override {
// Create the stack handle.
Tensor stack_handle;
AllocatorAttributes alloc_attr;
alloc_attr.set_on_host(true);
OP_REQUIRES_OK(ctx, ctx->allocate_temp(tensorflow::DT_STRING,
tensorflow::TensorShape({2}),
&stack_handle, alloc_attr));
auto stack_id = Stack::stack_counter.fetch_add(1);
auto handle = stack_handle.flat<string>();
handle(0) = "_stacks";
handle(1) = strings::StrCat(stack_name_, "_", stack_id);
// Store the handle in a per-step container.
ResourceMgr* rm = ctx->resource_manager();
OP_REQUIRES(ctx, rm != nullptr, errors::Internal("No resource manager."));
Stack* stack = new Stack(elem_type_, stack_handle);
OP_REQUIRES_OK(ctx,
rm->Create(ctx->step_container()->name(),
strings::StrCat(handle(0), handle(1)), stack));
ctx->set_output_ref(0, stack->mu(), stack->handle());
}
private:
DataType elem_type_;
string stack_name_;
TF_DISALLOW_COPY_AND_ASSIGN(StackOp);
};
REGISTER_KERNEL_BUILDER(Name("Stack").Device(DEVICE_CPU), StackOp);
REGISTER_KERNEL_BUILDER(Name("Stack").Device(DEVICE_GPU).HostMemory("handle"),
StackOp);
template <typename Device>
class StackPushOp : public AsyncOpKernel {
public:
explicit StackPushOp(OpKernelConstruction* context) : AsyncOpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("swap_memory", &swap_memory_));
}
void ComputeAsync(OpKernelContext* ctx, DoneCallback done) override {
// Get the stack from the handle.
Stack* stack = nullptr;
OP_REQUIRES_OK_ASYNC(ctx, GetStack(ctx, &stack), done);
core::ScopedUnref unref(stack);
if (ctx->input_dtype(1) != stack->ElemType()) {
ctx->CtxFailure(errors::InvalidArgument("Must have type ",
stack->ElemType(), " but got ",
ctx->input_dtype(1)));
done();
return;
}
// Push the tensor onto the stack. Swap the tensor to CPU if instructed.
const Tensor& tensor = ctx->input(1);
AllocatorAttributes alloc_attrs = ctx->input_alloc_attr(1);
// For now, we use a simple heuristic for swapping: A GPU tensor is moved
// to CPU if the tensor has more than kCopyThreshold bytes and the GPU
// allocator says more than kOccupancy of the memory is in use.
static constexpr int kCopyThreshold = 2048;
static constexpr double kOccupancy = 0.7;
if (swap_memory_ && !alloc_attrs.on_host() &&
std::is_same<Device, GPUDevice>::value &&
tensor.TotalBytes() > kCopyThreshold && stack->IsUsefulToSwap(tensor)) {
DeviceContext* device_ctxt = ctx->op_device_context();
auto device = static_cast<tensorflow::Device*>(ctx->device());
Allocator* allocator = device->GetAllocator(alloc_attrs);
AllocatorStats stats;
allocator->GetStats(&stats);
if (stats.bytes_in_use > (stats.bytes_limit * kOccupancy)) {
// Asynchronously copy the tensor from GPU to CPU memory.
// TODO(yuanbyu): Swap the oldest tensor first.
AllocatorAttributes host_alloc_attrs;
host_alloc_attrs.set_gpu_compatible(true);
host_alloc_attrs.set_on_host(true);
Allocator* cpu_allocator = device->GetAllocator(host_alloc_attrs);
Tensor* cpu_tensor =
new Tensor(cpu_allocator, tensor.dtype(), tensor.shape());
device_ctxt->CopyDeviceTensorToCPU(
&tensor, "StackPush", device, cpu_tensor,
[cpu_tensor, stack, ctx, done](const Status& s) {
ctx->SetStatus(s);
if (s.ok()) {
AllocatorAttributes alloc_attrs = ctx->input_alloc_attr(1);
ctx->SetStatus(stack->Push({*cpu_tensor, alloc_attrs, true}));
}
if (ctx->status().ok()) {
ctx->set_output(0, *cpu_tensor);
}
done();
delete cpu_tensor;
});
return;
}
}
// Execute synchronously if not swapped.
OP_REQUIRES_OK(ctx, stack->Push({tensor, alloc_attrs, false}));
ctx->set_output(0, tensor);
done();
}
bool IsExpensive() override { return false; }
private:
bool swap_memory_;
};
REGISTER_KERNEL_BUILDER(Name("StackPush").Device(DEVICE_CPU),
StackPushOp<CPUDevice>);
#define REGISTER_GPU_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("StackPush") \
.Device(DEVICE_GPU) \
.HostMemory("handle") \
.TypeConstraint<type>("T"), \
StackPushOp<GPUDevice>);
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_GPU_KERNEL);
#undef REGISTER_GPU_KERNEL
// Special GPU kernels for int32 and bool.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
#define REGISTER_GPU_HOST_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("StackPush") \
.Device(DEVICE_GPU) \
.HostMemory("handle") \
.HostMemory("elem") \
.HostMemory("output") \
.TypeConstraint<type>("T"), \
StackPushOp<GPUDevice>)
REGISTER_GPU_HOST_KERNEL(int32);
REGISTER_GPU_HOST_KERNEL(bool);
#undef REGISTER_GPU_HOST_KERNEL
class StackPopOp : public AsyncOpKernel {
public:
explicit StackPopOp(OpKernelConstruction* context) : AsyncOpKernel(context) {}
void ComputeAsync(OpKernelContext* ctx, DoneCallback done) override {
// Get the stack from the handle.
Stack* stack = nullptr;
OP_REQUIRES_OK_ASYNC(ctx, GetStack(ctx, &stack), done);
core::ScopedUnref unref(stack);
// Pop the tensor. Transfer the tensor back to device if it was
// swapped out to CPU.
Stack::TensorAndAllocation value;
OP_REQUIRES_OK_ASYNC(ctx, stack->Pop(&value), done);
if (value.swapped_to_cpu) {
// Asynchronously copy the tensor back from CPU to GPU memory.
DeviceContext* device_ctxt = ctx->op_device_context();
Device* device = static_cast<Device*>(ctx->device());
Tensor* cpu_tensor = &value.tensor;
Allocator* gpu_allocator = device->GetAllocator(value.alloc_attrs);
Tensor* device_tensor =
new Tensor(gpu_allocator, cpu_tensor->dtype(), cpu_tensor->shape());
device_ctxt->CopyCPUTensorToDevice(
cpu_tensor, device, device_tensor,
[device_tensor, ctx, done](const Status& s) {
ctx->SetStatus(s);
if (s.ok()) {
ctx->set_output(0, *device_tensor);
}
done();
delete device_tensor;
});
} else {
// Execute synchronously if not swapped.
ctx->set_output(0, value.tensor);
done();
}
}
bool IsExpensive() override { return false; }
};
REGISTER_KERNEL_BUILDER(Name("StackPop").Device(DEVICE_CPU), StackPopOp);
#define REGISTER_GPU_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("StackPop") \
.Device(DEVICE_GPU) \
.HostMemory("handle") \
.TypeConstraint<type>("elem_type"), \
StackPopOp)
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_GPU_KERNEL);
#undef REGISTER_GPU_KERNEL
// Special GPU kernels for int32 and bool.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
#define REGISTER_GPU_HOST_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("StackPop") \
.Device(DEVICE_GPU) \
.HostMemory("handle") \
.HostMemory("elem") \
.TypeConstraint<type>("elem_type"), \
StackPopOp)
REGISTER_GPU_HOST_KERNEL(int32);
REGISTER_GPU_HOST_KERNEL(bool);
#undef REGISTER_GPU_HOST_KERNEL
class StackCloseOp : public OpKernel {
public:
explicit StackCloseOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* ctx) override {
Stack* stack = nullptr;
OP_REQUIRES_OK(ctx, GetStack(ctx, &stack));
core::ScopedUnref unref(stack);
stack->Close();
}
bool IsExpensive() override { return false; }
};
REGISTER_KERNEL_BUILDER(Name("StackClose").Device(DEVICE_CPU), StackCloseOp);
REGISTER_KERNEL_BUILDER(
Name("StackClose").Device(DEVICE_GPU).HostMemory("handle"), StackCloseOp);
} // namespace tensorflow
<commit_msg>Avoids potential deadlock when pushing synchronously to a closed stack.<commit_after>/* Copyright 2015 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.
==============================================================================*/
// See docs in ../ops/data_flow_ops.cc.
#include <limits.h>
#include <atomic>
#include <vector>
#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/framework/device_base.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/refcount.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/thread_annotations.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;
class Stack : public ResourceBase {
public:
static std::atomic<int64> stack_counter;
struct TensorAndAllocation {
Tensor tensor;
AllocatorAttributes alloc_attrs;
bool swapped_to_cpu;
};
Stack(const DataType& elem_type, const Tensor& handle)
: elem_type_(elem_type), handle_(handle), closed_(false) {}
Status Push(const TensorAndAllocation& value) {
mutex_lock l(mu_);
TF_RETURN_IF_ERROR(CheckNotClosed());
stack_.push_back(value);
return Status::OK();
}
Status Pop(TensorAndAllocation* value) {
mutex_lock l(mu_);
TF_RETURN_IF_ERROR(CheckNotClosed());
if (stack_.empty()) {
const string& stack_name = handle_.vec<string>()(1);
return errors::InvalidArgument("Stack[", stack_name,
"] is empty when calling Pop().");
}
*value = stack_.back();
stack_.pop_back();
return Status::OK();
}
// We don't swap the first tensor on the stack and any subsequent tensors
// that share the buffer with the first tensor.
bool IsUsefulToSwap(const Tensor& tensor) const {
mutex_lock l(mu_);
if (stack_.empty()) {
return false;
}
const Tensor& first = stack_.front().tensor;
return !tensor.SharesBufferWith(first);
}
void Close() {
mutex_lock l(mu_);
stack_.clear();
closed_ = true;
}
DataType ElemType() { return elem_type_; }
string DebugString() override {
mutex_lock l(mu_);
const string& stack_name = handle_.vec<string>()(1);
return strings::StrCat("Stack[", stack_name, "]");
}
private:
friend class StackOp;
mutex* mu() { return &mu_; }
Tensor* handle() { return &handle_; }
mutable mutex mu_;
DataType elem_type_;
Tensor handle_;
bool closed_ GUARDED_BY(mu_);
std::vector<TensorAndAllocation> stack_ GUARDED_BY(mu_);
Status CheckNotClosed() const EXCLUSIVE_LOCKS_REQUIRED(mu_) {
if (closed_) {
const string& stack_name = handle_.vec<string>()(1);
return errors::InvalidArgument("Stack[", stack_name,
"] has already been closed.");
}
return Status::OK();
}
};
Status GetStack(OpKernelContext* ctx, Stack** stack) {
Tensor Tstack_handle = ctx->mutable_input(0, false);
if (Tstack_handle.NumElements() != 2) {
return errors::InvalidArgument(
"Stack handle must have two elements, but had shape: ",
Tstack_handle.shape().DebugString());
}
const string& container = Tstack_handle.flat<string>()(0);
const string& stack_name = Tstack_handle.flat<string>()(1);
ResourceMgr* rm = ctx->resource_manager();
if (rm == nullptr) {
return errors::Internal("No resource manager.");
}
TF_RETURN_IF_ERROR(rm->Lookup(ctx->step_container()->name(),
strings::StrCat(container, stack_name), stack));
return Status::OK();
}
std::atomic<int64> Stack::stack_counter{0};
// A per-run local stack. The stack uses a "per-step" resource manager which
// ensures that correct garbage collection on error or successful completion.
class StackOp : public OpKernel {
public:
explicit StackOp(OpKernelConstruction* context) : OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("elem_type", &elem_type_));
OP_REQUIRES_OK(context, context->GetAttr("stack_name", &stack_name_));
if (stack_name_ == "") stack_name_ = name();
}
void Compute(OpKernelContext* ctx) override {
// Create the stack handle.
Tensor stack_handle;
AllocatorAttributes alloc_attr;
alloc_attr.set_on_host(true);
OP_REQUIRES_OK(ctx, ctx->allocate_temp(tensorflow::DT_STRING,
tensorflow::TensorShape({2}),
&stack_handle, alloc_attr));
auto stack_id = Stack::stack_counter.fetch_add(1);
auto handle = stack_handle.flat<string>();
handle(0) = "_stacks";
handle(1) = strings::StrCat(stack_name_, "_", stack_id);
// Store the handle in a per-step container.
ResourceMgr* rm = ctx->resource_manager();
OP_REQUIRES(ctx, rm != nullptr, errors::Internal("No resource manager."));
Stack* stack = new Stack(elem_type_, stack_handle);
OP_REQUIRES_OK(ctx,
rm->Create(ctx->step_container()->name(),
strings::StrCat(handle(0), handle(1)), stack));
ctx->set_output_ref(0, stack->mu(), stack->handle());
}
private:
DataType elem_type_;
string stack_name_;
TF_DISALLOW_COPY_AND_ASSIGN(StackOp);
};
REGISTER_KERNEL_BUILDER(Name("Stack").Device(DEVICE_CPU), StackOp);
REGISTER_KERNEL_BUILDER(Name("Stack").Device(DEVICE_GPU).HostMemory("handle"),
StackOp);
template <typename Device>
class StackPushOp : public AsyncOpKernel {
public:
explicit StackPushOp(OpKernelConstruction* context) : AsyncOpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("swap_memory", &swap_memory_));
}
void ComputeAsync(OpKernelContext* ctx, DoneCallback done) override {
// Get the stack from the handle.
Stack* stack = nullptr;
OP_REQUIRES_OK_ASYNC(ctx, GetStack(ctx, &stack), done);
core::ScopedUnref unref(stack);
if (ctx->input_dtype(1) != stack->ElemType()) {
ctx->CtxFailure(errors::InvalidArgument("Must have type ",
stack->ElemType(), " but got ",
ctx->input_dtype(1)));
done();
return;
}
// Push the tensor onto the stack. Swap the tensor to CPU if instructed.
const Tensor& tensor = ctx->input(1);
AllocatorAttributes alloc_attrs = ctx->input_alloc_attr(1);
// For now, we use a simple heuristic for swapping: A GPU tensor is moved
// to CPU if the tensor has more than kCopyThreshold bytes and the GPU
// allocator says more than kOccupancy of the memory is in use.
static constexpr int kCopyThreshold = 2048;
static constexpr double kOccupancy = 0.7;
if (swap_memory_ && !alloc_attrs.on_host() &&
std::is_same<Device, GPUDevice>::value &&
tensor.TotalBytes() > kCopyThreshold && stack->IsUsefulToSwap(tensor)) {
DeviceContext* device_ctxt = ctx->op_device_context();
auto device = static_cast<tensorflow::Device*>(ctx->device());
Allocator* allocator = device->GetAllocator(alloc_attrs);
AllocatorStats stats;
allocator->GetStats(&stats);
if (stats.bytes_in_use > (stats.bytes_limit * kOccupancy)) {
// Asynchronously copy the tensor from GPU to CPU memory.
// TODO(yuanbyu): Swap the oldest tensor first.
AllocatorAttributes host_alloc_attrs;
host_alloc_attrs.set_gpu_compatible(true);
host_alloc_attrs.set_on_host(true);
Allocator* cpu_allocator = device->GetAllocator(host_alloc_attrs);
Tensor* cpu_tensor =
new Tensor(cpu_allocator, tensor.dtype(), tensor.shape());
device_ctxt->CopyDeviceTensorToCPU(
&tensor, "StackPush", device, cpu_tensor,
[cpu_tensor, stack, ctx, done](const Status& s) {
ctx->SetStatus(s);
if (s.ok()) {
AllocatorAttributes alloc_attrs = ctx->input_alloc_attr(1);
ctx->SetStatus(stack->Push({*cpu_tensor, alloc_attrs, true}));
}
if (ctx->status().ok()) {
ctx->set_output(0, *cpu_tensor);
}
done();
delete cpu_tensor;
});
return;
}
}
// Execute synchronously if not swapped.
OP_REQUIRES_OK_ASYNC(ctx, stack->Push({tensor, alloc_attrs, false}), done);
ctx->set_output(0, tensor);
done();
}
bool IsExpensive() override { return false; }
private:
bool swap_memory_;
};
REGISTER_KERNEL_BUILDER(Name("StackPush").Device(DEVICE_CPU),
StackPushOp<CPUDevice>);
#define REGISTER_GPU_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("StackPush") \
.Device(DEVICE_GPU) \
.HostMemory("handle") \
.TypeConstraint<type>("T"), \
StackPushOp<GPUDevice>);
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_GPU_KERNEL);
#undef REGISTER_GPU_KERNEL
// Special GPU kernels for int32 and bool.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
#define REGISTER_GPU_HOST_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("StackPush") \
.Device(DEVICE_GPU) \
.HostMemory("handle") \
.HostMemory("elem") \
.HostMemory("output") \
.TypeConstraint<type>("T"), \
StackPushOp<GPUDevice>)
REGISTER_GPU_HOST_KERNEL(int32);
REGISTER_GPU_HOST_KERNEL(bool);
#undef REGISTER_GPU_HOST_KERNEL
class StackPopOp : public AsyncOpKernel {
public:
explicit StackPopOp(OpKernelConstruction* context) : AsyncOpKernel(context) {}
void ComputeAsync(OpKernelContext* ctx, DoneCallback done) override {
// Get the stack from the handle.
Stack* stack = nullptr;
OP_REQUIRES_OK_ASYNC(ctx, GetStack(ctx, &stack), done);
core::ScopedUnref unref(stack);
// Pop the tensor. Transfer the tensor back to device if it was
// swapped out to CPU.
Stack::TensorAndAllocation value;
OP_REQUIRES_OK_ASYNC(ctx, stack->Pop(&value), done);
if (value.swapped_to_cpu) {
// Asynchronously copy the tensor back from CPU to GPU memory.
DeviceContext* device_ctxt = ctx->op_device_context();
Device* device = static_cast<Device*>(ctx->device());
Tensor* cpu_tensor = &value.tensor;
Allocator* gpu_allocator = device->GetAllocator(value.alloc_attrs);
Tensor* device_tensor =
new Tensor(gpu_allocator, cpu_tensor->dtype(), cpu_tensor->shape());
device_ctxt->CopyCPUTensorToDevice(
cpu_tensor, device, device_tensor,
[device_tensor, ctx, done](const Status& s) {
ctx->SetStatus(s);
if (s.ok()) {
ctx->set_output(0, *device_tensor);
}
done();
delete device_tensor;
});
} else {
// Execute synchronously if not swapped.
ctx->set_output(0, value.tensor);
done();
}
}
bool IsExpensive() override { return false; }
};
REGISTER_KERNEL_BUILDER(Name("StackPop").Device(DEVICE_CPU), StackPopOp);
#define REGISTER_GPU_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("StackPop") \
.Device(DEVICE_GPU) \
.HostMemory("handle") \
.TypeConstraint<type>("elem_type"), \
StackPopOp)
TF_CALL_NUMBER_TYPES_NO_INT32(REGISTER_GPU_KERNEL);
#undef REGISTER_GPU_KERNEL
// Special GPU kernels for int32 and bool.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
#define REGISTER_GPU_HOST_KERNEL(type) \
REGISTER_KERNEL_BUILDER(Name("StackPop") \
.Device(DEVICE_GPU) \
.HostMemory("handle") \
.HostMemory("elem") \
.TypeConstraint<type>("elem_type"), \
StackPopOp)
REGISTER_GPU_HOST_KERNEL(int32);
REGISTER_GPU_HOST_KERNEL(bool);
#undef REGISTER_GPU_HOST_KERNEL
class StackCloseOp : public OpKernel {
public:
explicit StackCloseOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* ctx) override {
Stack* stack = nullptr;
OP_REQUIRES_OK(ctx, GetStack(ctx, &stack));
core::ScopedUnref unref(stack);
stack->Close();
}
bool IsExpensive() override { return false; }
};
REGISTER_KERNEL_BUILDER(Name("StackClose").Device(DEVICE_CPU), StackCloseOp);
REGISTER_KERNEL_BUILDER(
Name("StackClose").Device(DEVICE_GPU).HostMemory("handle"), StackCloseOp);
} // namespace tensorflow
<|endoftext|> |
<commit_before>/* Copyright 2017 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/lite/kernels/test_util.h"
#include "tensorflow/lite/version.h"
#include "tensorflow/core/platform/logging.h"
namespace tflite {
using ::testing::FloatNear;
using ::testing::Matcher;
std::vector<Matcher<float>> ArrayFloatNear(const std::vector<float>& values,
float max_abs_error) {
std::vector<Matcher<float>> matchers;
matchers.reserve(values.size());
for (const float& v : values) {
matchers.emplace_back(FloatNear(v, max_abs_error));
}
return matchers;
}
std::vector<Matcher<std::complex<float>>> ArrayComplex64Near(
const std::vector<std::complex<float>>& values, float max_abs_error) {
std::vector<Matcher<std::complex<float>>> matchers;
matchers.reserve(values.size());
for (const std::complex<float>& v : values) {
matchers.emplace_back(
AllOf(::testing::Property(&std::complex<float>::real,
FloatNear(v.real(), max_abs_error)),
::testing::Property(&std::complex<float>::imag,
FloatNear(v.imag(), max_abs_error))));
}
return matchers;
}
int SingleOpModel::AddInput(const TensorData& t, bool is_variable) {
int id = AddTensor<float>(t, {}, is_variable);
inputs_.push_back(id);
return id;
}
int SingleOpModel::AddNullInput() {
int id = kOptionalTensor;
inputs_.push_back(id);
return id;
}
int SingleOpModel::AddOutput(const TensorData& t) {
int id = AddTensor<float>(t, {});
outputs_.push_back(id);
return id;
}
void SingleOpModel::SetBuiltinOp(BuiltinOperator type,
BuiltinOptions builtin_options_type,
flatbuffers::Offset<void> builtin_options) {
opcodes_.push_back(CreateOperatorCode(builder_, type, 0));
operators_.push_back(CreateOperator(
builder_, /*opcode_index=*/0, builder_.CreateVector<int32_t>(inputs_),
builder_.CreateVector<int32_t>(outputs_), builtin_options_type,
builtin_options,
/*custom_options=*/0, CustomOptionsFormat_FLEXBUFFERS));
}
void SingleOpModel::SetCustomOp(
const string& name, const std::vector<uint8_t>& custom_option,
const std::function<TfLiteRegistration*()>& registration) {
custom_registrations_[name] = registration;
opcodes_.push_back(
CreateOperatorCodeDirect(builder_, BuiltinOperator_CUSTOM, name.data()));
operators_.push_back(CreateOperator(
builder_, /*opcode_index=*/0, builder_.CreateVector<int32_t>(inputs_),
builder_.CreateVector<int32_t>(outputs_), BuiltinOptions_NONE, 0,
builder_.CreateVector<uint8_t>(custom_option),
CustomOptionsFormat_FLEXBUFFERS));
}
void SingleOpModel::BuildInterpreter(std::vector<std::vector<int>> input_shapes,
bool allow_fp32_relax_to_fp16) {
auto opcodes = builder_.CreateVector(opcodes_);
auto operators = builder_.CreateVector(operators_);
auto tensors = builder_.CreateVector(tensors_);
auto inputs = builder_.CreateVector<int32_t>(inputs_);
auto outputs = builder_.CreateVector<int32_t>(outputs_);
// Create a single subgraph
std::vector<flatbuffers::Offset<SubGraph>> subgraphs;
auto subgraph = CreateSubGraph(builder_, tensors, inputs, outputs, operators);
subgraphs.push_back(subgraph);
auto subgraphs_flatbuffer = builder_.CreateVector(subgraphs);
auto buffers = builder_.CreateVector(buffers_);
auto description = builder_.CreateString("programmatic model");
builder_.Finish(CreateModel(builder_, TFLITE_SCHEMA_VERSION, opcodes,
subgraphs_flatbuffer, description, buffers));
auto* model = GetModel(builder_.GetBufferPointer());
if (!resolver_) {
auto resolver = new ops::builtin::BuiltinOpResolver();
for (const auto& reg : custom_registrations_) {
resolver->AddCustom(reg.first.data(), reg.second());
}
resolver_ = std::unique_ptr<OpResolver>(resolver);
}
CHECK(InterpreterBuilder(model, *resolver_)(&interpreter_) == kTfLiteOk);
CHECK(interpreter_ != nullptr);
int i = 0;
for (const auto& shape : input_shapes) {
int input_idx = interpreter_->inputs()[i++];
if (input_idx == kOptionalTensor) continue;
if (shape.empty()) continue;
CHECK(interpreter_->ResizeInputTensor(input_idx, shape) == kTfLiteOk);
}
interpreter_->SetAllowFp16PrecisionForFp32(allow_fp32_relax_to_fp16);
// Modify delegate with function.
if (apply_delegate_fn_) {
apply_delegate_fn_(interpreter_.get());
}
CHECK(interpreter_->AllocateTensors() == kTfLiteOk)
<< "Cannot allocate tensors";
interpreter_->ResetVariableTensors();
}
void SingleOpModel::Invoke() { CHECK(interpreter_->Invoke() == kTfLiteOk); }
int32_t SingleOpModel::GetTensorSize(int index) const {
TfLiteTensor* t = interpreter_->tensor(index);
CHECK(t);
int total_size = 1;
for (int i = 0; i < t->dims->size; ++i) {
total_size *= t->dims->data[i];
}
return total_size;
}
template <>
std::vector<string> SingleOpModel::ExtractVector(int index) {
TfLiteTensor* tensor_ptr = interpreter_->tensor(index);
CHECK(tensor_ptr != nullptr);
const int num_strings = GetStringCount(tensor_ptr);
std::vector<string> result;
result.reserve(num_strings);
for (int i = 0; i < num_strings; ++i) {
const auto str = GetString(tensor_ptr, i);
result.emplace_back(str.str, str.len);
}
return result;
}
} // namespace tflite
<commit_msg>Fix the test_util to ModifyGraphWithDelegate after AllocateTensors.<commit_after>/* Copyright 2017 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/lite/kernels/test_util.h"
#include "tensorflow/lite/version.h"
#include "tensorflow/core/platform/logging.h"
namespace tflite {
using ::testing::FloatNear;
using ::testing::Matcher;
std::vector<Matcher<float>> ArrayFloatNear(const std::vector<float>& values,
float max_abs_error) {
std::vector<Matcher<float>> matchers;
matchers.reserve(values.size());
for (const float& v : values) {
matchers.emplace_back(FloatNear(v, max_abs_error));
}
return matchers;
}
std::vector<Matcher<std::complex<float>>> ArrayComplex64Near(
const std::vector<std::complex<float>>& values, float max_abs_error) {
std::vector<Matcher<std::complex<float>>> matchers;
matchers.reserve(values.size());
for (const std::complex<float>& v : values) {
matchers.emplace_back(
AllOf(::testing::Property(&std::complex<float>::real,
FloatNear(v.real(), max_abs_error)),
::testing::Property(&std::complex<float>::imag,
FloatNear(v.imag(), max_abs_error))));
}
return matchers;
}
int SingleOpModel::AddInput(const TensorData& t, bool is_variable) {
int id = AddTensor<float>(t, {}, is_variable);
inputs_.push_back(id);
return id;
}
int SingleOpModel::AddNullInput() {
int id = kOptionalTensor;
inputs_.push_back(id);
return id;
}
int SingleOpModel::AddOutput(const TensorData& t) {
int id = AddTensor<float>(t, {});
outputs_.push_back(id);
return id;
}
void SingleOpModel::SetBuiltinOp(BuiltinOperator type,
BuiltinOptions builtin_options_type,
flatbuffers::Offset<void> builtin_options) {
opcodes_.push_back(CreateOperatorCode(builder_, type, 0));
operators_.push_back(CreateOperator(
builder_, /*opcode_index=*/0, builder_.CreateVector<int32_t>(inputs_),
builder_.CreateVector<int32_t>(outputs_), builtin_options_type,
builtin_options,
/*custom_options=*/0, CustomOptionsFormat_FLEXBUFFERS));
}
void SingleOpModel::SetCustomOp(
const string& name, const std::vector<uint8_t>& custom_option,
const std::function<TfLiteRegistration*()>& registration) {
custom_registrations_[name] = registration;
opcodes_.push_back(
CreateOperatorCodeDirect(builder_, BuiltinOperator_CUSTOM, name.data()));
operators_.push_back(CreateOperator(
builder_, /*opcode_index=*/0, builder_.CreateVector<int32_t>(inputs_),
builder_.CreateVector<int32_t>(outputs_), BuiltinOptions_NONE, 0,
builder_.CreateVector<uint8_t>(custom_option),
CustomOptionsFormat_FLEXBUFFERS));
}
void SingleOpModel::BuildInterpreter(std::vector<std::vector<int>> input_shapes,
bool allow_fp32_relax_to_fp16) {
auto opcodes = builder_.CreateVector(opcodes_);
auto operators = builder_.CreateVector(operators_);
auto tensors = builder_.CreateVector(tensors_);
auto inputs = builder_.CreateVector<int32_t>(inputs_);
auto outputs = builder_.CreateVector<int32_t>(outputs_);
// Create a single subgraph
std::vector<flatbuffers::Offset<SubGraph>> subgraphs;
auto subgraph = CreateSubGraph(builder_, tensors, inputs, outputs, operators);
subgraphs.push_back(subgraph);
auto subgraphs_flatbuffer = builder_.CreateVector(subgraphs);
auto buffers = builder_.CreateVector(buffers_);
auto description = builder_.CreateString("programmatic model");
builder_.Finish(CreateModel(builder_, TFLITE_SCHEMA_VERSION, opcodes,
subgraphs_flatbuffer, description, buffers));
auto* model = GetModel(builder_.GetBufferPointer());
if (!resolver_) {
auto resolver = new ops::builtin::BuiltinOpResolver();
for (const auto& reg : custom_registrations_) {
resolver->AddCustom(reg.first.data(), reg.second());
}
resolver_ = std::unique_ptr<OpResolver>(resolver);
}
CHECK(InterpreterBuilder(model, *resolver_)(&interpreter_) == kTfLiteOk);
CHECK(interpreter_ != nullptr);
int i = 0;
for (const auto& shape : input_shapes) {
int input_idx = interpreter_->inputs()[i++];
if (input_idx == kOptionalTensor) continue;
if (shape.empty()) continue;
CHECK(interpreter_->ResizeInputTensor(input_idx, shape) == kTfLiteOk);
}
interpreter_->SetAllowFp16PrecisionForFp32(allow_fp32_relax_to_fp16);
CHECK(interpreter_->AllocateTensors() == kTfLiteOk)
<< "Cannot allocate tensors";
interpreter_->ResetVariableTensors();
// Modify delegate with function.
if (apply_delegate_fn_) {
apply_delegate_fn_(interpreter_.get());
}
}
void SingleOpModel::Invoke() { CHECK(interpreter_->Invoke() == kTfLiteOk); }
int32_t SingleOpModel::GetTensorSize(int index) const {
TfLiteTensor* t = interpreter_->tensor(index);
CHECK(t);
int total_size = 1;
for (int i = 0; i < t->dims->size; ++i) {
total_size *= t->dims->data[i];
}
return total_size;
}
template <>
std::vector<string> SingleOpModel::ExtractVector(int index) {
TfLiteTensor* tensor_ptr = interpreter_->tensor(index);
CHECK(tensor_ptr != nullptr);
const int num_strings = GetStringCount(tensor_ptr);
std::vector<string> result;
result.reserve(num_strings);
for (int i = 0; i < num_strings; ++i) {
const auto str = GetString(tensor_ptr, i);
result.emplace_back(str.str, str.len);
}
return result;
}
} // namespace tflite
<|endoftext|> |
<commit_before>#ifdef _MSC_VER
#pragma warning(disable: 4786 4250 4503 4224 4180)
#endif
#include "../CppUnit/framework/TestCase.h"
#include "../CppUnit/framework/TestSuite.h"
#include "../CppUnit/framework/TestCaller.h"
#include <XPath/XPath.hpp>
#include "../silly_string/silly_string.hpp"
using namespace Arabica::XPath;
class ArithmeticTest : public TestCase
{
public:
ArithmeticTest(const std::string& name) : TestCase(name)
{
} // ArithmeticTest
void setUp()
{
} // setUp
void test1()
{
XPathExpression<silly_string, silly_string_adaptor>* p1 = new NumericValue<silly_string, silly_string_adaptor>(1);
XPathExpression<silly_string, silly_string_adaptor>* p2 = new NumericValue<silly_string, silly_string_adaptor>(2);
XPathExpressionPtr<silly_string, silly_string_adaptor> add(new impl::PlusOperator<silly_string, silly_string_adaptor>(p1, p2));
assertEquals(1, add.use_count());
add->evaluate(dummy_);
assertEquals(3.0, add->evaluateAsNumber(dummy_), 0.0);
assertEquals(1, add.use_count());
} // test1
void test2()
{
XPathExpression<silly_string, silly_string_adaptor>* p1 = new NumericValue<silly_string, silly_string_adaptor>(1);
XPathExpression<silly_string, silly_string_adaptor>* p2 = new NumericValue<silly_string, silly_string_adaptor>(2);
XPathExpressionPtr<silly_string, silly_string_adaptor> minus(new impl::MinusOperator<silly_string, silly_string_adaptor>(p1, p2));
assertEquals(-1.0, minus->evaluateAsNumber(dummy_), 0.0);
} // test2
void test3()
{
XPathExpression<silly_string, silly_string_adaptor>* p1 = new NumericValue<silly_string, silly_string_adaptor>(3);
XPathExpression<silly_string, silly_string_adaptor>* p2 = new NumericValue<silly_string, silly_string_adaptor>(2);
XPathExpressionPtr<silly_string, silly_string_adaptor> mult(new impl::MultiplyOperator<silly_string, silly_string_adaptor>(p1, p2));
assertEquals(6, mult->evaluateAsNumber(dummy_), 0.0);
} // test3
void test4()
{
XPathExpression<silly_string, silly_string_adaptor>* mult = new impl::MultiplyOperator<silly_string, silly_string_adaptor>(new NumericValue<silly_string, silly_string_adaptor>(4), new NumericValue<silly_string, silly_string_adaptor>(2));
XPathExpressionPtr<silly_string, silly_string_adaptor> minus(new impl::MinusOperator<silly_string, silly_string_adaptor>(mult, new NumericValue<silly_string, silly_string_adaptor>(2)));
assertEquals(8, mult->evaluateAsNumber(dummy_), 0.0);
assertEquals(6, minus->evaluateAsNumber(dummy_), 0.0);
} // test4
void test5()
{
XPathExpression<silly_string, silly_string_adaptor>* p1 = new NumericValue<silly_string, silly_string_adaptor>(12);
XPathExpression<silly_string, silly_string_adaptor>* p2 = new NumericValue<silly_string, silly_string_adaptor>(2);
XPathExpressionPtr<silly_string, silly_string_adaptor> div(new impl::DivideOperator<silly_string, silly_string_adaptor>(p1, p2));
assertEquals(6, div->evaluateAsNumber(dummy_), 0.0);
} // test5
void test6()
{
XPathExpression<silly_string, silly_string_adaptor>* p1 = new NumericValue<silly_string, silly_string_adaptor>(12);
XPathExpression<silly_string, silly_string_adaptor>* p2 = new NumericValue<silly_string, silly_string_adaptor>(2);
XPathExpressionPtr<silly_string, silly_string_adaptor> mod(new impl::ModOperator<silly_string, silly_string_adaptor>(p1, p2));
assertEquals(0, mod->evaluateAsNumber(dummy_), 0.0);
} // test6
void test7()
{
XPathExpression<silly_string, silly_string_adaptor>* p1 = new NumericValue<silly_string, silly_string_adaptor>(11);
XPathExpression<silly_string, silly_string_adaptor>* p2 = new NumericValue<silly_string, silly_string_adaptor>(2);
XPathExpressionPtr<silly_string, silly_string_adaptor> div(new impl::DivideOperator<silly_string, silly_string_adaptor>(p1, p2));
assertEquals(5.5, div->evaluateAsNumber(dummy_), 0.0);
} // test7
void test8()
{
XPathExpression<silly_string, silly_string_adaptor>* p1 = new NumericValue<silly_string, silly_string_adaptor>(11);
XPathExpression<silly_string, silly_string_adaptor>* p2 = new NumericValue<silly_string, silly_string_adaptor>(4);
XPathExpressionPtr<silly_string, silly_string_adaptor> mod(new impl::ModOperator<silly_string, silly_string_adaptor>(p1, p2));
assertEquals(3, mod->evaluateAsNumber(dummy_), 0.0);
} // test8
void test9()
{
XPathExpression<silly_string, silly_string_adaptor>* p1 = new NumericValue<silly_string, silly_string_adaptor>(5);
XPathExpression<silly_string, silly_string_adaptor>* p2 = new NumericValue<silly_string, silly_string_adaptor>(2);
XPathExpressionPtr<silly_string, silly_string_adaptor> mod(new impl::ModOperator<silly_string, silly_string_adaptor>(p1, p2));
assertEquals(1.0, mod->evaluateAsNumber(dummy_), 0.0);
} // test9
void test10()
{
XPathExpression<silly_string, silly_string_adaptor>* p1 = new NumericValue<silly_string, silly_string_adaptor>(5);
XPathExpression<silly_string, silly_string_adaptor>* p2 = new NumericValue<silly_string, silly_string_adaptor>(-2);
XPathExpressionPtr<silly_string, silly_string_adaptor> mod(new impl::ModOperator<silly_string, silly_string_adaptor>(p1, p2));
assertEquals(1.00, mod->evaluateAsNumber(dummy_), 0.0);
} // test10
void test11()
{
XPathExpression<silly_string, silly_string_adaptor>* p1 = new NumericValue<silly_string, silly_string_adaptor>(-5);
XPathExpression<silly_string, silly_string_adaptor>* p2 = new NumericValue<silly_string, silly_string_adaptor>(2);
XPathExpressionPtr<silly_string, silly_string_adaptor> mod(new impl::ModOperator<silly_string, silly_string_adaptor>(p1, p2));
assertEquals(-1.0, mod->evaluateAsNumber(dummy_), 0.0);
} // test11
void test12()
{
XPathExpression<silly_string, silly_string_adaptor>* p1 = new NumericValue<silly_string, silly_string_adaptor>(-5);
XPathExpression<silly_string, silly_string_adaptor>* p2 = new NumericValue<silly_string, silly_string_adaptor>(-2);
XPathExpressionPtr<silly_string, silly_string_adaptor> mod(new impl::ModOperator<silly_string, silly_string_adaptor>(p1, p2));
assertEquals(-1.0, mod->evaluateAsNumber(dummy_), 0.0);
} // test12
void test13()
{
XPathExpression<silly_string, silly_string_adaptor>* p1 = new NumericValue<silly_string, silly_string_adaptor>(5);
XPathExpressionPtr<silly_string, silly_string_adaptor> p2(new impl::UnaryNegative<silly_string, silly_string_adaptor>(p1));
assertEquals(-5.0, p2->evaluateAsNumber(dummy_), 0.0);
} // test13
void test14()
{
XPathExpression<silly_string, silly_string_adaptor>* p1 = new NumericValue<silly_string, silly_string_adaptor>(-5);
XPathExpressionPtr<silly_string, silly_string_adaptor> p2(new impl::UnaryNegative<silly_string, silly_string_adaptor>(p1));
assertEquals(5.0, p2->evaluateAsNumber(dummy_), 0.0);
} // test14
private:
DOM::Node<silly_string> dummy_;
}; // ArithmeticTest
TestSuite* ArithmeticTest_suite()
{
TestSuite *suiteOfTests = new TestSuite;
suiteOfTests->addTest(new TestCaller<ArithmeticTest>("test1", &ArithmeticTest::test1));
suiteOfTests->addTest(new TestCaller<ArithmeticTest>("test2", &ArithmeticTest::test2));
suiteOfTests->addTest(new TestCaller<ArithmeticTest>("test3", &ArithmeticTest::test3));
suiteOfTests->addTest(new TestCaller<ArithmeticTest>("test4", &ArithmeticTest::test4));
suiteOfTests->addTest(new TestCaller<ArithmeticTest>("test5", &ArithmeticTest::test5));
suiteOfTests->addTest(new TestCaller<ArithmeticTest>("test6", &ArithmeticTest::test6));
suiteOfTests->addTest(new TestCaller<ArithmeticTest>("test7", &ArithmeticTest::test7));
suiteOfTests->addTest(new TestCaller<ArithmeticTest>("test8", &ArithmeticTest::test8));
suiteOfTests->addTest(new TestCaller<ArithmeticTest>("test9", &ArithmeticTest::test9));
suiteOfTests->addTest(new TestCaller<ArithmeticTest>("test10", &ArithmeticTest::test10));
suiteOfTests->addTest(new TestCaller<ArithmeticTest>("test11", &ArithmeticTest::test11));
suiteOfTests->addTest(new TestCaller<ArithmeticTest>("test12", &ArithmeticTest::test12));
suiteOfTests->addTest(new TestCaller<ArithmeticTest>("test13", &ArithmeticTest::test13));
suiteOfTests->addTest(new TestCaller<ArithmeticTest>("test14", &ArithmeticTest::test14));
return suiteOfTests;
} // ArithmeticTest_suite
<commit_msg>*** empty log message ***<commit_after><|endoftext|> |
<commit_before>#ifndef STAN_MATH_OPENCL_KERNEL_GENERATOR_OPENCL_CODE_HPP
#define STAN_MATH_OPENCL_KERNEL_GENERATOR_OPENCL_CODE_HPP
#ifdef STAN_OPENCL
#include <stan/math/prim/meta.hpp>
#include <stan/math/opencl/matrix_cl_view.hpp>
#include <stan/math/opencl/kernel_generator/type_str.hpp>
#include <stan/math/opencl/kernel_generator/name_generator.hpp>
#include <stan/math/opencl/kernel_generator/operation_cl.hpp>
#include <stan/math/opencl/kernel_generator/as_operation_cl.hpp>
#include <stan/math/opencl/kernel_generator/common_return_scalar.hpp>
#include <stan/math/prim/functor/for_each.hpp>
#include <algorithm>
#include <set>
#include <string>
#include <type_traits>
#include <utility>
namespace stan {
namespace math {
/** \addtogroup opencl_kernel_generator
* @{
*/
/**
* Represents output variable of custom code in kernel generator expressions.
* @tparam T_code intantiation of `opencl_code_` class template this is output
* of
* @tparam T_scalar scalar type of the output variable
*/
template <typename T_code, typename T_scalar>
class opencl_code_output
: public operation_cl<opencl_code_output<T_code, T_scalar>, T_scalar,
T_code> {
public:
using Scalar = T_scalar;
using base
= operation_cl<opencl_code_output<T_code, T_scalar>, T_scalar, T_code>;
using base::var_name_;
const char* custom_var_name_;
/**
* Constructor
* @param code code object
* @param custom_var_name variable name from the custom code
*/
opencl_code_output(T_code code, const char* custom_var_name)
: base(std::move(code)), custom_var_name_(custom_var_name) {}
/**
* Creates a deep copy of this expression.
* @return copy of \c *this
*/
inline auto deep_copy() const {
auto&& code_copy = this->template get_arg<0>().deep_copy();
return opencl_code_output<std::remove_reference_t<decltype(code_copy)>,
T_scalar>(std::move(code_copy), custom_var_name_);
}
/**
* Generates kernel code for this operation.
* @param row_index_name row index variable name
* @param col_index_name column index variable name
* @param view_handled whether whether caller already handled matrix view
* @param var_name_condition variable name of the condition expression
* @param var_name_else variable name of the then expression
* @param var_name_then variable name of the else expression
* @return part of kernel with code for this expression
*/
inline kernel_parts generate(const std::string& row_index_name,
const std::string& col_index_name,
const bool view_handled,
const std::string& dummy_var_name_code) const {
kernel_parts res{};
res.body = type_str<Scalar>() + " " + var_name_ + " = " + custom_var_name_
+ ";\n";
return res;
}
/**
* Determine indices of extreme sub- and superdiagonals written.
* @return pair of indices - bottom and top diagonal
*/
inline std::pair<int, int> extreme_diagonals() const {
return {-this->rows() + 1, this->cols() - 1};
}
};
namespace internal {
template <const char* Code, typename... T_arguments>
class opencl_code_impl
: public operation_cl<opencl_code_impl<Code, T_arguments...>, double,
T_arguments...> {
public:
// using Scalar = double;
using base = operation_cl<opencl_code_impl<Code, T_arguments...>, double,
T_arguments...>;
using names_tuple
= std::tuple<typename std::pair<const char*, T_arguments>::first_type...>;
using base::var_name_;
names_tuple names_;
/**
* Constructor
* @param condition condition expression
* @param then then expression
* @param els else expression
*/
explicit opencl_code_impl(names_tuple names, T_arguments&&... arguments)
: base(std::forward<T_arguments>(arguments)...), names_(names) {}
/**
* Generates kernel code for this (select) operation.
* @param row_index_name row index variable name
* @param col_index_name column index variable name
* @param view_handled whether whether caller already handled matrix
* view
* @param var_name_condition variable name of the condition
* expression
* @param var_name_else variable name of the then expression
* @param var_name_then variable name of the else expression
* @return part of kernel with code for this expression
*/
inline kernel_parts generate(
const std::string& row_index_name, const std::string& col_index_name,
const bool view_handled,
std::tuple_element_t<
0, std::pair<const std::string&, T_arguments>>... var_names) const {
return index_apply<sizeof...(T_arguments)>([this](auto... Is) {
kernel_parts res{};
std::array<std::string, sizeof...(T_arguments)> input_renames{
(type_str<scalar_type_t<decltype(this->template get_arg<Is>())>>()
+ " " + std::get<Is>(names_) + " = "
+ this->template get_arg<Is>().var_name_ + ";\n")...};
res.body = std::accumulate(input_renames.begin(), input_renames.end(),
std::string())
+ Code;
return res;
});
}
};
} // namespace internal
/**
* Represents custom code in kernel generator expressions.
* @tparam Code custom code
* @tparam T_arguments types of argument expressions
*/
template <const char* Code, typename... T_arguments>
class opencl_code_ : public operation_cl_base {
public:
std::shared_ptr<internal::opencl_code_impl<Code, T_arguments...>> impl_;
std::string& var_name_;
using names_tuple
= std::tuple<typename std::pair<const char*, T_arguments>::first_type...>;
using Deriv = internal::opencl_code_impl<Code, T_arguments...>;
/**
* Constructor
* @param names tuple of names of the input variables (that hold values of
* argument expressions)
* @param arguments arguments to this operation
*/
explicit opencl_code_(const names_tuple& names, T_arguments&&... arguments)
: impl_(
std::make_shared<internal::opencl_code_impl<Code, T_arguments...>>(
names, std::forward<T_arguments>(arguments)...)),
var_name_(impl_->var_name_) {}
/**
* Copy constructor.
* @param other object to copy
*/
opencl_code_(const opencl_code_<Code, T_arguments...>& other)
: impl_(other.impl_), var_name_(impl_->var_name_) {}
/**
* Generates kernel code for this and nested expressions.
* @param[in,out] generated map from (pointer to) already generated local
* operations to variable names
* @param[in,out] generated_all map from (pointer to) already generated all
* operations to variable names
* @param name_gen name generator for this kernel
* @param row_index_name row index variable name
* @param col_index_name column index variable name
* @param view_handled whether caller already handled matrix view
* @return part of kernel with code for this and nested expressions
*/
auto get_kernel_parts(std::map<const void*, const char*>& generated,
std::map<const void*, const char*>& generated_all,
name_generator& name_gen,
const std::string& row_index_name,
const std::string& col_index_name,
bool view_handled) const {
return impl_->get_kernel_parts(generated, generated_all, name_gen,
row_index_name, col_index_name,
view_handled);
}
/**
* Sets kernel arguments for nested expressions.
* @param[in,out] generated map from (pointer to) already generated local
* operations to variable names
* @param[in,out] generated_all map from (pointer to) already generated all
* operations to variable names
* @param kernel kernel to set arguments on
* @param[in,out] arg_num consecutive number of the first argument to set.
* This is incremented for each argument set by this function.
*/
auto set_args(std::map<const void*, const char*>& generated,
std::map<const void*, const char*>& generated_all,
cl::Kernel& kernel, int& arg_num) const {
return impl_->set_args(generated, generated_all, kernel, arg_num);
}
/**
* Adds read event to any matrices used by nested expressions.
* @param e the event to add
*/
auto add_read_event(cl::Event& e) const { return impl_->add_read_event(e); }
/**
* Adds all write events on any matrices used by nested expressions to a list.
* @param[out] events List of all events.
*/
auto get_write_events(std::vector<cl::Event>& events) const {
return impl_->get_write_events(events);
}
/**
* Number of rows of a matrix that would be the result of evaluating this
* expression. Some subclasses may need to override this.
* @return number of rows
*/
template <std::enable_if_t<(sizeof...(T_arguments) > 0)>* = nullptr>
auto rows() const {
return impl_->rows();
}
template <std::enable_if_t<(sizeof...(T_arguments) == 0)>* = nullptr>
auto rows() const {
return -1;
}
/**
* Number of columns of a matrix that would be the result of evaluating this
* expression. Some subclasses may need to override this.
* @return number of columns
*/
template <std::enable_if_t<(sizeof...(T_arguments) > 0)>* = nullptr>
auto cols() const {
return impl_->cols();
}
template <std::enable_if_t<(sizeof...(T_arguments) == 0)>* = nullptr>
auto cols() const {
return -1;
}
/**
* Number of rows threads need to be launched for. For most expressions this
* equals number of rows of the result.
* @return number of rows
*/
template <std::enable_if_t<(sizeof...(T_arguments) > 0)>* = nullptr>
auto thread_rows() const {
return impl_->thread_rows();
}
template <std::enable_if_t<(sizeof...(T_arguments) == 0)>* = nullptr>
auto thread_rows() const {
return -1;
}
/**
* Number of columns threads need to be launched for. For most expressions
* this equals number of cols of the result.
* @return number of columns
*/
template <std::enable_if_t<(sizeof...(T_arguments) > 0)>* = nullptr>
auto thread_cols() const {
return impl_->thread_cols();
}
template <std::enable_if_t<(sizeof...(T_arguments) == 0)>* = nullptr>
auto thread_cols() const {
return -1;
}
/**
* Determine indices of extreme sub- and superdiagonals written.
* @return pair of indices - bottom and top diagonal
*/
auto extreme_diagonals() const { return impl_->extreme_diagonals(); }
/**
* Collects data that is needed beside types to uniqly identify a kernel
* generator expression.
* @param[out] uids ids of unique matrix accesses
* @param[in,out] id_map map from memory addresses to unique ids
* @param[in,out] next_id neqt unique id to use
*/
auto get_unique_matrix_accesses(std::vector<int>& uids,
std::map<const void*, int>& id_map,
int& next_id) const {
return impl_->get_unique_matrix_accesses(uids, id_map, next_id);
}
/**
* Creates a deep copy of this expression.
* @return copy of \c *this
*/
inline auto deep_copy() const {
return index_apply<sizeof...(T_arguments)>([this](auto... Is) {
auto args_copy
= std::make_tuple(this->impl_->template get_arg<Is>().deep_copy()...);
return opencl_code_<
Code, std::remove_reference_t<decltype(std::get<Is>(args_copy))>...>(
this->impl_->names_, std::move(std::get<Is>(args_copy))...);
});
}
/**
* Get object representing output variable of ccustom code.
* @param var_name name of the variable output object represents
*/
template <typename T_scalar>
inline auto output(const char* var_name) const {
return opencl_code_output<opencl_code_<Code, T_arguments...>, T_scalar>(
*this, var_name);
}
};
/**
* Custom code in kernel generator expressions.
* @tparam Code custom code
* @tparam T_arguments types of argument expressions
* @param names tuple of names of the input variables (that hold values of
* argument expressions)
* @param arguments arguments to this operation
*/
template <const char* Code, typename... T_arguments,
require_all_kernel_expressions_t<T_arguments...>* = nullptr>
inline auto opencl_code(
std::tuple<typename std::pair<const char*, T_arguments>::first_type...>
names,
T_arguments&&... arguments) {
return opencl_code_<Code, as_operation_cl_t<T_arguments>...>(
names, as_operation_cl(std::forward<T_arguments>(arguments))...);
}
/** @}*/
} // namespace math
} // namespace stan
#endif
#endif
<commit_msg>fixed doxygen<commit_after>#ifndef STAN_MATH_OPENCL_KERNEL_GENERATOR_OPENCL_CODE_HPP
#define STAN_MATH_OPENCL_KERNEL_GENERATOR_OPENCL_CODE_HPP
#ifdef STAN_OPENCL
#include <stan/math/prim/meta.hpp>
#include <stan/math/opencl/matrix_cl_view.hpp>
#include <stan/math/opencl/kernel_generator/type_str.hpp>
#include <stan/math/opencl/kernel_generator/name_generator.hpp>
#include <stan/math/opencl/kernel_generator/operation_cl.hpp>
#include <stan/math/opencl/kernel_generator/as_operation_cl.hpp>
#include <stan/math/opencl/kernel_generator/common_return_scalar.hpp>
#include <stan/math/prim/functor/for_each.hpp>
#include <algorithm>
#include <set>
#include <string>
#include <type_traits>
#include <utility>
namespace stan {
namespace math {
/** \addtogroup opencl_kernel_generator
* @{
*/
/**
* Represents output variable of custom code in kernel generator expressions.
* @tparam T_code intantiation of `opencl_code_` class template this is output
* of
* @tparam T_scalar scalar type of the output variable
*/
template <typename T_code, typename T_scalar>
class opencl_code_output
: public operation_cl<opencl_code_output<T_code, T_scalar>, T_scalar,
T_code> {
public:
using Scalar = T_scalar;
using base
= operation_cl<opencl_code_output<T_code, T_scalar>, T_scalar, T_code>;
using base::var_name_;
const char* custom_var_name_;
/**
* Constructor
* @param code code object
* @param custom_var_name variable name from the custom code
*/
opencl_code_output(T_code code, const char* custom_var_name)
: base(std::move(code)), custom_var_name_(custom_var_name) {}
/**
* Creates a deep copy of this expression.
* @return copy of \c *this
*/
inline auto deep_copy() const {
auto&& code_copy = this->template get_arg<0>().deep_copy();
return opencl_code_output<std::remove_reference_t<decltype(code_copy)>,
T_scalar>(std::move(code_copy), custom_var_name_);
}
/**
* Generates kernel code for this operation.
* @param row_index_name row index variable name
* @param col_index_name column index variable name
* @param view_handled whether whether caller already handled matrix view
* @param dummy_var_name_code variable name of the code operation (unused)
* @return part of kernel with code for this expression
*/
inline kernel_parts generate(const std::string& row_index_name,
const std::string& col_index_name,
const bool view_handled,
const std::string& dummy_var_name_code) const {
kernel_parts res{};
res.body = type_str<Scalar>() + " " + var_name_ + " = " + custom_var_name_
+ ";\n";
return res;
}
/**
* Determine indices of extreme sub- and superdiagonals written.
* @return pair of indices - bottom and top diagonal
*/
inline std::pair<int, int> extreme_diagonals() const {
return {-this->rows() + 1, this->cols() - 1};
}
};
namespace internal {
template <const char* Code, typename... T_arguments>
class opencl_code_impl
: public operation_cl<opencl_code_impl<Code, T_arguments...>, double,
T_arguments...> {
public:
// using Scalar = double;
using base = operation_cl<opencl_code_impl<Code, T_arguments...>, double,
T_arguments...>;
using names_tuple
= std::tuple<typename std::pair<const char*, T_arguments>::first_type...>;
using base::var_name_;
names_tuple names_;
/**
* Constructor
* @param names tuple of names of the input variables (that hold values of
* argument expressions)
* @param arguments arguments to this operation
*/
explicit opencl_code_impl(names_tuple names, T_arguments&&... arguments)
: base(std::forward<T_arguments>(arguments)...), names_(names) {}
/**
* Generates kernel code for this (select) operation.
* @param row_index_name row index variable name
* @param col_index_name column index variable name
* @param view_handled whether whether caller already handled matrix
* view
* @param var_names variable names of the argument expressions
* @return part of kernel with code for this expression
*/
inline kernel_parts generate(
const std::string& row_index_name, const std::string& col_index_name,
const bool view_handled,
std::tuple_element_t<
0, std::pair<const std::string&, T_arguments>>... var_names) const {
return index_apply<sizeof...(T_arguments)>([this](auto... Is) {
kernel_parts res{};
std::array<std::string, sizeof...(T_arguments)> input_renames{
(type_str<scalar_type_t<decltype(this->template get_arg<Is>())>>()
+ " " + std::get<Is>(names_) + " = "
+ this->template get_arg<Is>().var_name_ + ";\n")...};
res.body = std::accumulate(input_renames.begin(), input_renames.end(),
std::string())
+ Code;
return res;
});
}
};
} // namespace internal
/**
* Represents custom code in kernel generator expressions.
* @tparam Code custom code
* @tparam T_arguments types of argument expressions
*/
template <const char* Code, typename... T_arguments>
class opencl_code_ : public operation_cl_base {
public:
std::shared_ptr<internal::opencl_code_impl<Code, T_arguments...>> impl_;
std::string& var_name_;
using names_tuple
= std::tuple<typename std::pair<const char*, T_arguments>::first_type...>;
using Deriv = internal::opencl_code_impl<Code, T_arguments...>;
/**
* Constructor
* @param names tuple of names of the input variables (that hold values of
* argument expressions)
* @param arguments arguments to this operation
*/
explicit opencl_code_(const names_tuple& names, T_arguments&&... arguments)
: impl_(
std::make_shared<internal::opencl_code_impl<Code, T_arguments...>>(
names, std::forward<T_arguments>(arguments)...)),
var_name_(impl_->var_name_) {}
/**
* Copy constructor.
* @param other object to copy
*/
opencl_code_(const opencl_code_<Code, T_arguments...>& other)
: impl_(other.impl_), var_name_(impl_->var_name_) {}
/**
* Generates kernel code for this and nested expressions.
* @param[in,out] generated map from (pointer to) already generated local
* operations to variable names
* @param[in,out] generated_all map from (pointer to) already generated all
* operations to variable names
* @param name_gen name generator for this kernel
* @param row_index_name row index variable name
* @param col_index_name column index variable name
* @param view_handled whether caller already handled matrix view
* @return part of kernel with code for this and nested expressions
*/
auto get_kernel_parts(std::map<const void*, const char*>& generated,
std::map<const void*, const char*>& generated_all,
name_generator& name_gen,
const std::string& row_index_name,
const std::string& col_index_name,
bool view_handled) const {
return impl_->get_kernel_parts(generated, generated_all, name_gen,
row_index_name, col_index_name,
view_handled);
}
/**
* Sets kernel arguments for nested expressions.
* @param[in,out] generated map from (pointer to) already generated local
* operations to variable names
* @param[in,out] generated_all map from (pointer to) already generated all
* operations to variable names
* @param kernel kernel to set arguments on
* @param[in,out] arg_num consecutive number of the first argument to set.
* This is incremented for each argument set by this function.
*/
auto set_args(std::map<const void*, const char*>& generated,
std::map<const void*, const char*>& generated_all,
cl::Kernel& kernel, int& arg_num) const {
return impl_->set_args(generated, generated_all, kernel, arg_num);
}
/**
* Adds read event to any matrices used by nested expressions.
* @param e the event to add
*/
auto add_read_event(cl::Event& e) const { return impl_->add_read_event(e); }
/**
* Adds all write events on any matrices used by nested expressions to a list.
* @param[out] events List of all events.
*/
auto get_write_events(std::vector<cl::Event>& events) const {
return impl_->get_write_events(events);
}
/**
* Number of rows of a matrix that would be the result of evaluating this
* expression. Some subclasses may need to override this.
* @return number of rows
*/
template <std::enable_if_t<(sizeof...(T_arguments) > 0)>* = nullptr>
auto rows() const {
return impl_->rows();
}
template <std::enable_if_t<(sizeof...(T_arguments) == 0)>* = nullptr>
auto rows() const {
return -1;
}
/**
* Number of columns of a matrix that would be the result of evaluating this
* expression. Some subclasses may need to override this.
* @return number of columns
*/
template <std::enable_if_t<(sizeof...(T_arguments) > 0)>* = nullptr>
auto cols() const {
return impl_->cols();
}
template <std::enable_if_t<(sizeof...(T_arguments) == 0)>* = nullptr>
auto cols() const {
return -1;
}
/**
* Number of rows threads need to be launched for. For most expressions this
* equals number of rows of the result.
* @return number of rows
*/
template <std::enable_if_t<(sizeof...(T_arguments) > 0)>* = nullptr>
auto thread_rows() const {
return impl_->thread_rows();
}
template <std::enable_if_t<(sizeof...(T_arguments) == 0)>* = nullptr>
auto thread_rows() const {
return -1;
}
/**
* Number of columns threads need to be launched for. For most expressions
* this equals number of cols of the result.
* @return number of columns
*/
template <std::enable_if_t<(sizeof...(T_arguments) > 0)>* = nullptr>
auto thread_cols() const {
return impl_->thread_cols();
}
template <std::enable_if_t<(sizeof...(T_arguments) == 0)>* = nullptr>
auto thread_cols() const {
return -1;
}
/**
* Determine indices of extreme sub- and superdiagonals written.
* @return pair of indices - bottom and top diagonal
*/
auto extreme_diagonals() const { return impl_->extreme_diagonals(); }
/**
* Collects data that is needed beside types to uniqly identify a kernel
* generator expression.
* @param[out] uids ids of unique matrix accesses
* @param[in,out] id_map map from memory addresses to unique ids
* @param[in,out] next_id neqt unique id to use
*/
auto get_unique_matrix_accesses(std::vector<int>& uids,
std::map<const void*, int>& id_map,
int& next_id) const {
return impl_->get_unique_matrix_accesses(uids, id_map, next_id);
}
/**
* Creates a deep copy of this expression.
* @return copy of \c *this
*/
inline auto deep_copy() const {
return index_apply<sizeof...(T_arguments)>([this](auto... Is) {
auto args_copy
= std::make_tuple(this->impl_->template get_arg<Is>().deep_copy()...);
return opencl_code_<
Code, std::remove_reference_t<decltype(std::get<Is>(args_copy))>...>(
this->impl_->names_, std::move(std::get<Is>(args_copy))...);
});
}
/**
* Get object representing output variable of ccustom code.
* @param var_name name of the variable output object represents
*/
template <typename T_scalar>
inline auto output(const char* var_name) const {
return opencl_code_output<opencl_code_<Code, T_arguments...>, T_scalar>(
*this, var_name);
}
};
/**
* Custom code in kernel generator expressions.
* @tparam Code custom code
* @tparam T_arguments types of argument expressions
* @param names tuple of names of the input variables (that hold values of
* argument expressions)
* @param arguments arguments to this operation
*/
template <const char* Code, typename... T_arguments,
require_all_kernel_expressions_t<T_arguments...>* = nullptr>
inline auto opencl_code(
std::tuple<typename std::pair<const char*, T_arguments>::first_type...>
names,
T_arguments&&... arguments) {
return opencl_code_<Code, as_operation_cl_t<T_arguments>...>(
names, as_operation_cl(std::forward<T_arguments>(arguments))...);
}
/** @}*/
} // namespace math
} // namespace stan
#endif
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2018-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/test/apptests.h>
#include <chainparams.h>
#include <key.h>
#include <qt/bitcoin.h>
#include <qt/bitcoingui.h>
#include <qt/networkstyle.h>
#include <qt/rpcconsole.h>
#include <shutdown.h>
#include <test/util/setup_common.h>
#include <univalue.h>
#include <validation.h>
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <QAction>
#include <QEventLoop>
#include <QLineEdit>
#include <QScopedPointer>
#include <QTest>
#include <QTextEdit>
#include <QtGlobal>
#include <QtTest/QtTestWidgets>
#include <QtTest/QtTestGui>
namespace {
//! Call getblockchaininfo RPC and check first field of JSON output.
void TestRpcCommand(RPCConsole* console)
{
QEventLoop loop;
QTextEdit* messagesWidget = console->findChild<QTextEdit*>("messagesWidget");
QObject::connect(messagesWidget, &QTextEdit::textChanged, &loop, &QEventLoop::quit);
QLineEdit* lineEdit = console->findChild<QLineEdit*>("lineEdit");
QTest::keyClicks(lineEdit, "getblockchaininfo");
QTest::keyClick(lineEdit, Qt::Key_Return);
loop.exec();
QString output = messagesWidget->toPlainText();
UniValue value;
value.read(output.right(output.size() - output.lastIndexOf(QChar::ObjectReplacementCharacter) - 1).toStdString());
QCOMPARE(value["chain"].get_str(), std::string("regtest"));
}
} // namespace
//! Entry point for BitcoinApplication tests.
void AppTests::appTests()
{
#ifdef Q_OS_MAC
if (QApplication::platformName() == "minimal") {
// Disable for mac on "minimal" platform to avoid crashes inside the Qt
// framework when it tries to look up unimplemented cocoa functions,
// and fails to handle returned nulls
// (https://bugreports.qt.io/browse/QTBUG-49686).
QWARN("Skipping AppTests on mac build with 'minimal' platform set due to Qt bugs. To run AppTests, invoke "
"with 'QT_QPA_PLATFORM=cocoa test_bitcoin-qt' on mac, or else use a linux or windows build.");
return;
}
#endif
BasicTestingSetup test{CBaseChainParams::REGTEST}; // Create a temp data directory to backup the gui settings to
ECC_Stop(); // Already started by the common test setup, so stop it to avoid interference
LogInstance().DisconnectTestLogger();
m_app.parameterSetup();
m_app.createOptionsModel(true /* reset settings */);
QScopedPointer<const NetworkStyle> style(NetworkStyle::instantiate(Params().NetworkIDString()));
m_app.setupPlatformStyle();
m_app.createWindow(style.data());
connect(&m_app, &BitcoinApplication::windowShown, this, &AppTests::guiTests);
expectCallback("guiTests");
m_app.baseInitialize();
m_app.requestInitialize();
m_app.exec();
m_app.requestShutdown();
m_app.exec();
// Reset global state to avoid interfering with later tests.
AbortShutdown();
UnloadBlockIndex();
WITH_LOCK(::cs_main, g_chainman.Reset());
}
//! Entry point for BitcoinGUI tests.
void AppTests::guiTests(BitcoinGUI* window)
{
HandleCallback callback{"guiTests", *this};
connect(window, &BitcoinGUI::consoleShown, this, &AppTests::consoleTests);
expectCallback("consoleTests");
QAction* action = window->findChild<QAction*>("openRPCConsoleAction");
action->activate(QAction::Trigger);
}
//! Entry point for RPCConsole tests.
void AppTests::consoleTests(RPCConsole* console)
{
HandleCallback callback{"consoleTests", *this};
TestRpcCommand(console);
}
//! Destructor to shut down after the last expected callback completes.
AppTests::HandleCallback::~HandleCallback()
{
auto& callbacks = m_app_tests.m_callbacks;
auto it = callbacks.find(m_callback);
assert(it != callbacks.end());
callbacks.erase(it);
if (callbacks.empty()) {
m_app_tests.m_app.quit();
}
}
<commit_msg>gui tests: Limit life-time of dummy testing setup<commit_after>// Copyright (c) 2018-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/test/apptests.h>
#include <chainparams.h>
#include <key.h>
#include <qt/bitcoin.h>
#include <qt/bitcoingui.h>
#include <qt/networkstyle.h>
#include <qt/rpcconsole.h>
#include <shutdown.h>
#include <test/util/setup_common.h>
#include <univalue.h>
#include <validation.h>
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <QAction>
#include <QEventLoop>
#include <QLineEdit>
#include <QScopedPointer>
#include <QTest>
#include <QTextEdit>
#include <QtGlobal>
#include <QtTest/QtTestWidgets>
#include <QtTest/QtTestGui>
namespace {
//! Call getblockchaininfo RPC and check first field of JSON output.
void TestRpcCommand(RPCConsole* console)
{
QEventLoop loop;
QTextEdit* messagesWidget = console->findChild<QTextEdit*>("messagesWidget");
QObject::connect(messagesWidget, &QTextEdit::textChanged, &loop, &QEventLoop::quit);
QLineEdit* lineEdit = console->findChild<QLineEdit*>("lineEdit");
QTest::keyClicks(lineEdit, "getblockchaininfo");
QTest::keyClick(lineEdit, Qt::Key_Return);
loop.exec();
QString output = messagesWidget->toPlainText();
UniValue value;
value.read(output.right(output.size() - output.lastIndexOf(QChar::ObjectReplacementCharacter) - 1).toStdString());
QCOMPARE(value["chain"].get_str(), std::string("regtest"));
}
} // namespace
//! Entry point for BitcoinApplication tests.
void AppTests::appTests()
{
#ifdef Q_OS_MAC
if (QApplication::platformName() == "minimal") {
// Disable for mac on "minimal" platform to avoid crashes inside the Qt
// framework when it tries to look up unimplemented cocoa functions,
// and fails to handle returned nulls
// (https://bugreports.qt.io/browse/QTBUG-49686).
QWARN("Skipping AppTests on mac build with 'minimal' platform set due to Qt bugs. To run AppTests, invoke "
"with 'QT_QPA_PLATFORM=cocoa test_bitcoin-qt' on mac, or else use a linux or windows build.");
return;
}
#endif
fs::create_directories([] {
BasicTestingSetup test{CBaseChainParams::REGTEST}; // Create a temp data directory to backup the gui settings to
return GetDataDir() / "blocks";
}());
m_app.parameterSetup();
m_app.createOptionsModel(true /* reset settings */);
QScopedPointer<const NetworkStyle> style(NetworkStyle::instantiate(Params().NetworkIDString()));
m_app.setupPlatformStyle();
m_app.createWindow(style.data());
connect(&m_app, &BitcoinApplication::windowShown, this, &AppTests::guiTests);
expectCallback("guiTests");
m_app.baseInitialize();
m_app.requestInitialize();
m_app.exec();
m_app.requestShutdown();
m_app.exec();
// Reset global state to avoid interfering with later tests.
LogInstance().DisconnectTestLogger();
AbortShutdown();
UnloadBlockIndex();
WITH_LOCK(::cs_main, g_chainman.Reset());
}
//! Entry point for BitcoinGUI tests.
void AppTests::guiTests(BitcoinGUI* window)
{
HandleCallback callback{"guiTests", *this};
connect(window, &BitcoinGUI::consoleShown, this, &AppTests::consoleTests);
expectCallback("consoleTests");
QAction* action = window->findChild<QAction*>("openRPCConsoleAction");
action->activate(QAction::Trigger);
}
//! Entry point for RPCConsole tests.
void AppTests::consoleTests(RPCConsole* console)
{
HandleCallback callback{"consoleTests", *this};
TestRpcCommand(console);
}
//! Destructor to shut down after the last expected callback completes.
AppTests::HandleCallback::~HandleCallback()
{
auto& callbacks = m_app_tests.m_callbacks;
auto it = callbacks.find(m_callback);
assert(it != callbacks.end());
callbacks.erase(it);
if (callbacks.empty()) {
m_app_tests.m_app.quit();
}
}
<|endoftext|> |
<commit_before>/* -*- mode: C++ ; c-file-style: "stroustrup" -*- *****************************
* Qwt Widget Library
* Copyright (C) 1997 Josef Wilgen
* Copyright (C) 2002 Uwe Rathmann
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Qwt License, Version 1.0
*****************************************************************************/
#include "qwt_system_clock.h"
#include <qdatetime.h>
#if !defined(Q_OS_WIN)
#include <unistd.h>
#endif
#if defined(Q_OS_MAC)
#include <stdint.h>
#include <mach/mach_time.h>
#define QWT_HIGH_RESOLUTION_CLOCK
#elif defined(_POSIX_TIMERS)
#include <time.h>
#define QWT_HIGH_RESOLUTION_CLOCK
#elif defined(Q_OS_WIN)
#define QWT_HIGH_RESOLUTION_CLOCK
#include <qt_windows.h>
#endif
#if defined(QWT_HIGH_RESOLUTION_CLOCK)
class QwtHighResolutionClock
{
public:
QwtHighResolutionClock();
void start();
double restart();
double elapsed() const;
bool isNull() const;
static double precision();
private:
#if defined(Q_OS_MAC)
static double msecsTo( uint64_t, uint64_t );
uint64_t d_timeStamp;
#elif defined(_POSIX_TIMERS)
static double msecsTo( const struct timespec &,
const struct timespec & );
static bool isMonotonic();
struct timespec d_timeStamp;
clockid_t d_clockId;
#elif defined(Q_OS_WIN)
LARGE_INTEGER d_startTicks;
LARGE_INTEGER d_ticksPerSecond;
#endif
};
#if defined(Q_OS_MAC)
QwtHighResolutionClock::QwtHighResolutionClock():
d_timeStamp( 0 )
{
}
double QwtHighResolutionClock::precision()
{
return 1e-6;
}
void QwtHighResolutionClock::start()
{
d_timeStamp = mach_absolute_time();
}
double QwtHighResolutionClock::restart()
{
const uint64_t timeStamp = mach_absolute_time();
const double elapsed = msecsTo( d_timeStamp, timeStamp );
d_timeStamp = timeStamp;
return elapsed;
}
double QwtHighResolutionClock::elapsed() const
{
return msecsTo( d_timeStamp, mach_absolute_time() );
}
bool QwtHighResolutionClock::isNull() const
{
return d_timeStamp == 0;
}
double QwtHighResolutionClock::msecsTo(
uint64_t from, uint64_t to )
{
const uint64_t difference = from - to;
static double conversion = 0.0;
if ( conversion == 0.0 )
{
mach_timebase_info_data_t info;
kern_return_t err = mach_timebase_info( &info );
//Convert the timebase into ms
if ( err == 0 )
conversion = 1e-6 * ( double ) info.numer / ( double ) info.denom;
}
return conversion * ( double ) difference;
}
#elif defined(_POSIX_TIMERS)
QwtHighResolutionClock::QwtHighResolutionClock()
{
d_clockId = isMonotonic() ? CLOCK_MONOTONIC : CLOCK_REALTIME;
d_timeStamp.tv_sec = d_timeStamp.tv_nsec = 0;
}
double QwtHighResolutionClock::precision()
{
struct timespec resolution;
int clockId = isMonotonic() ? CLOCK_MONOTONIC : CLOCK_REALTIME;
::clock_getres( clockId, &resolution );
return resolution.tv_nsec / 1e3;
}
inline bool QwtHighResolutionClock::isNull() const
{
return d_timeStamp.tv_sec <= 0 && d_timeStamp.tv_nsec <= 0;
}
inline void QwtHighResolutionClock::start()
{
::clock_gettime( d_clockId, &d_timeStamp );
}
double QwtHighResolutionClock::restart()
{
struct timespec timeStamp;
::clock_gettime( d_clockId, &timeStamp );
const double elapsed = msecsTo( d_timeStamp, timeStamp );
d_timeStamp = timeStamp;
return elapsed;
}
inline double QwtHighResolutionClock::elapsed() const
{
struct timespec timeStamp;
::clock_gettime( d_clockId, &timeStamp );
return msecsTo( d_timeStamp, timeStamp );
}
inline double QwtHighResolutionClock::msecsTo(
const struct timespec &t1, const struct timespec &t2 )
{
return ( t2.tv_sec - t1.tv_sec ) * 1e3
+ ( t2.tv_nsec - t1.tv_nsec ) * 1e-6;
}
bool QwtHighResolutionClock::isMonotonic()
{
// code copied from qcore_unix.cpp
#if (_POSIX_MONOTONIC_CLOCK-0 > 0)
return true;
#else
static int returnValue = 0;
if ( returnValue == 0 )
{
#if (_POSIX_MONOTONIC_CLOCK-0 < 0) || !defined(_SC_MONOTONIC_CLOCK)
returnValue = -1;
#elif (_POSIX_MONOTONIC_CLOCK == 0)
// detect if the system support monotonic timers
const long x = sysconf( _SC_MONOTONIC_CLOCK );
returnValue = ( x >= 200112L ) ? 1 : -1;
#endif
}
return returnValue != -1;
#endif
}
#elif defined(Q_OS_WIN)
QwtHighResolutionClock::QwtHighResolutionClock()
{
d_startTicks.QuadPart = 0;
QueryPerformanceFrequency( &d_ticksPerSecond );
}
double QwtHighResolutionClock::precision()
{
LARGE_INTEGER ticks;
if ( QueryPerformanceFrequency( &ticks ) && ticks.QuadPart > 0 )
return 1e3 / ticks.QuadPart;
return 0.0;
}
inline bool QwtHighResolutionClock::isNull() const
{
return d_startTicks.QuadPart <= 0;
}
inline void QwtHighResolutionClock::start()
{
QueryPerformanceCounter( &d_startTicks );
}
inline double QwtHighResolutionClock::restart()
{
LARGE_INTEGER ticks;
QueryPerformanceCounter( &ticks );
const double dt = ticks.QuadPart - d_startTicks.QuadPart;
d_startTicks = ticks;
return dt / d_ticksPerSecond.QuadPart * 1e3;
}
inline double QwtHighResolutionClock::elapsed() const
{
LARGE_INTEGER ticks;
QueryPerformanceCounter( &ticks );
const double dt = ticks.QuadPart - d_startTicks.QuadPart;
return dt / d_ticksPerSecond.QuadPart * 1e3;
}
#endif
#endif // QWT_HIGH_RESOLUTION_CLOCK
class QwtSystemClock::PrivateData
{
public:
#if defined(QWT_HIGH_RESOLUTION_CLOCK)
QwtHighResolutionClock *clock;
#endif
QTime time;
};
//! Constructs a null clock object.
QwtSystemClock::QwtSystemClock()
{
d_data = new PrivateData;
#if defined(QWT_HIGH_RESOLUTION_CLOCK)
d_data->clock = NULL;
if ( QwtHighResolutionClock::precision() > 0.0 )
d_data->clock = new QwtHighResolutionClock;
#endif
}
//! Destructor
QwtSystemClock::~QwtSystemClock()
{
#if defined(QWT_HIGH_RESOLUTION_CLOCK)
delete d_data->clock;
#endif
delete d_data;
}
/*!
\return true if the clock has never been started.
*/
bool QwtSystemClock::isNull() const
{
#if defined(QWT_HIGH_RESOLUTION_CLOCK)
if ( d_data->clock )
return d_data->clock->isNull();
#endif
return d_data->time.isNull();
}
/*!
Sets the start time to the current time.
*/
void QwtSystemClock::start()
{
#if defined(QWT_HIGH_RESOLUTION_CLOCK)
if ( d_data->clock )
{
d_data->clock->start();
return;
}
#endif
d_data->time.start();
}
/*!
The start time to the current time and
return the time, that is elapsed since the
previous start time.
*/
double QwtSystemClock::restart()
{
#if defined(QWT_HIGH_RESOLUTION_CLOCK)
if ( d_data->clock )
return d_data->clock->restart();
#endif
return d_data->time.restart();
}
/*!
\return Number of milliseconds that have elapsed since the last time
start() or restart() was called or 0.0 for null clocks.
*/
double QwtSystemClock::elapsed() const
{
double elapsed = 0.0;
#if defined(QWT_HIGH_RESOLUTION_CLOCK)
if ( d_data->clock )
{
if ( !d_data->clock->isNull() )
elapsed = d_data->clock->elapsed();
return elapsed;
}
#endif
if ( !d_data->time.isNull() )
elapsed = d_data->time.elapsed();
return elapsed;
}
/*!
\return Accuracy of the system clock in milliseconds.
*/
double QwtSystemClock::precision()
{
static double prec = 0.0;
if ( prec <= 0.0 )
{
#if defined(QWT_HIGH_RESOLUTION_CLOCK)
prec = QwtHighResolutionClock::precision();
#endif
if ( prec <= 0.0 )
prec = 1.0; // QTime offers 1 ms
}
return prec;
}
<commit_msg>msecsTo fixed for the Mac<commit_after>/* -*- mode: C++ ; c-file-style: "stroustrup" -*- *****************************
* Qwt Widget Library
* Copyright (C) 1997 Josef Wilgen
* Copyright (C) 2002 Uwe Rathmann
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Qwt License, Version 1.0
*****************************************************************************/
#include "qwt_system_clock.h"
#include <qdatetime.h>
#if !defined(Q_OS_WIN)
#include <unistd.h>
#endif
#if defined(Q_OS_MAC)
#include <stdint.h>
#include <mach/mach_time.h>
#define QWT_HIGH_RESOLUTION_CLOCK
#elif defined(_POSIX_TIMERS)
#include <time.h>
#define QWT_HIGH_RESOLUTION_CLOCK
#elif defined(Q_OS_WIN)
#define QWT_HIGH_RESOLUTION_CLOCK
#include <qt_windows.h>
#endif
#if defined(QWT_HIGH_RESOLUTION_CLOCK)
class QwtHighResolutionClock
{
public:
QwtHighResolutionClock();
void start();
double restart();
double elapsed() const;
bool isNull() const;
static double precision();
private:
#if defined(Q_OS_MAC)
static double msecsTo( uint64_t, uint64_t );
uint64_t d_timeStamp;
#elif defined(_POSIX_TIMERS)
static double msecsTo( const struct timespec &,
const struct timespec & );
static bool isMonotonic();
struct timespec d_timeStamp;
clockid_t d_clockId;
#elif defined(Q_OS_WIN)
LARGE_INTEGER d_startTicks;
LARGE_INTEGER d_ticksPerSecond;
#endif
};
#if defined(Q_OS_MAC)
QwtHighResolutionClock::QwtHighResolutionClock():
d_timeStamp( 0 )
{
}
double QwtHighResolutionClock::precision()
{
return 1e-6;
}
void QwtHighResolutionClock::start()
{
d_timeStamp = mach_absolute_time();
}
double QwtHighResolutionClock::restart()
{
const uint64_t timeStamp = mach_absolute_time();
const double elapsed = msecsTo( d_timeStamp, timeStamp );
d_timeStamp = timeStamp;
return elapsed;
}
double QwtHighResolutionClock::elapsed() const
{
return msecsTo( d_timeStamp, mach_absolute_time() );
}
bool QwtHighResolutionClock::isNull() const
{
return d_timeStamp == 0;
}
double QwtHighResolutionClock::msecsTo(
uint64_t from, uint64_t to )
{
const uint64_t difference = to - from;
static double conversion = 0.0;
if ( conversion == 0.0 )
{
mach_timebase_info_data_t info;
kern_return_t err = mach_timebase_info( &info );
//Convert the timebase into ms
if ( err == 0 )
conversion = 1e-6 * ( double ) info.numer / ( double ) info.denom;
}
return conversion * ( double ) difference;
}
#elif defined(_POSIX_TIMERS)
QwtHighResolutionClock::QwtHighResolutionClock()
{
d_clockId = isMonotonic() ? CLOCK_MONOTONIC : CLOCK_REALTIME;
d_timeStamp.tv_sec = d_timeStamp.tv_nsec = 0;
}
double QwtHighResolutionClock::precision()
{
struct timespec resolution;
int clockId = isMonotonic() ? CLOCK_MONOTONIC : CLOCK_REALTIME;
::clock_getres( clockId, &resolution );
return resolution.tv_nsec / 1e3;
}
inline bool QwtHighResolutionClock::isNull() const
{
return d_timeStamp.tv_sec <= 0 && d_timeStamp.tv_nsec <= 0;
}
inline void QwtHighResolutionClock::start()
{
::clock_gettime( d_clockId, &d_timeStamp );
}
double QwtHighResolutionClock::restart()
{
struct timespec timeStamp;
::clock_gettime( d_clockId, &timeStamp );
const double elapsed = msecsTo( d_timeStamp, timeStamp );
d_timeStamp = timeStamp;
return elapsed;
}
inline double QwtHighResolutionClock::elapsed() const
{
struct timespec timeStamp;
::clock_gettime( d_clockId, &timeStamp );
return msecsTo( d_timeStamp, timeStamp );
}
inline double QwtHighResolutionClock::msecsTo(
const struct timespec &t1, const struct timespec &t2 )
{
return ( t2.tv_sec - t1.tv_sec ) * 1e3
+ ( t2.tv_nsec - t1.tv_nsec ) * 1e-6;
}
bool QwtHighResolutionClock::isMonotonic()
{
// code copied from qcore_unix.cpp
#if (_POSIX_MONOTONIC_CLOCK-0 > 0)
return true;
#else
static int returnValue = 0;
if ( returnValue == 0 )
{
#if (_POSIX_MONOTONIC_CLOCK-0 < 0) || !defined(_SC_MONOTONIC_CLOCK)
returnValue = -1;
#elif (_POSIX_MONOTONIC_CLOCK == 0)
// detect if the system support monotonic timers
const long x = sysconf( _SC_MONOTONIC_CLOCK );
returnValue = ( x >= 200112L ) ? 1 : -1;
#endif
}
return returnValue != -1;
#endif
}
#elif defined(Q_OS_WIN)
QwtHighResolutionClock::QwtHighResolutionClock()
{
d_startTicks.QuadPart = 0;
QueryPerformanceFrequency( &d_ticksPerSecond );
}
double QwtHighResolutionClock::precision()
{
LARGE_INTEGER ticks;
if ( QueryPerformanceFrequency( &ticks ) && ticks.QuadPart > 0 )
return 1e3 / ticks.QuadPart;
return 0.0;
}
inline bool QwtHighResolutionClock::isNull() const
{
return d_startTicks.QuadPart <= 0;
}
inline void QwtHighResolutionClock::start()
{
QueryPerformanceCounter( &d_startTicks );
}
inline double QwtHighResolutionClock::restart()
{
LARGE_INTEGER ticks;
QueryPerformanceCounter( &ticks );
const double dt = ticks.QuadPart - d_startTicks.QuadPart;
d_startTicks = ticks;
return dt / d_ticksPerSecond.QuadPart * 1e3;
}
inline double QwtHighResolutionClock::elapsed() const
{
LARGE_INTEGER ticks;
QueryPerformanceCounter( &ticks );
const double dt = ticks.QuadPart - d_startTicks.QuadPart;
return dt / d_ticksPerSecond.QuadPart * 1e3;
}
#endif
#endif // QWT_HIGH_RESOLUTION_CLOCK
class QwtSystemClock::PrivateData
{
public:
#if defined(QWT_HIGH_RESOLUTION_CLOCK)
QwtHighResolutionClock *clock;
#endif
QTime time;
};
//! Constructs a null clock object.
QwtSystemClock::QwtSystemClock()
{
d_data = new PrivateData;
#if defined(QWT_HIGH_RESOLUTION_CLOCK)
d_data->clock = NULL;
if ( QwtHighResolutionClock::precision() > 0.0 )
d_data->clock = new QwtHighResolutionClock;
#endif
}
//! Destructor
QwtSystemClock::~QwtSystemClock()
{
#if defined(QWT_HIGH_RESOLUTION_CLOCK)
delete d_data->clock;
#endif
delete d_data;
}
/*!
\return true if the clock has never been started.
*/
bool QwtSystemClock::isNull() const
{
#if defined(QWT_HIGH_RESOLUTION_CLOCK)
if ( d_data->clock )
return d_data->clock->isNull();
#endif
return d_data->time.isNull();
}
/*!
Sets the start time to the current time.
*/
void QwtSystemClock::start()
{
#if defined(QWT_HIGH_RESOLUTION_CLOCK)
if ( d_data->clock )
{
d_data->clock->start();
return;
}
#endif
d_data->time.start();
}
/*!
The start time to the current time and
return the time, that is elapsed since the
previous start time.
*/
double QwtSystemClock::restart()
{
#if defined(QWT_HIGH_RESOLUTION_CLOCK)
if ( d_data->clock )
return d_data->clock->restart();
#endif
return d_data->time.restart();
}
/*!
\return Number of milliseconds that have elapsed since the last time
start() or restart() was called or 0.0 for null clocks.
*/
double QwtSystemClock::elapsed() const
{
double elapsed = 0.0;
#if defined(QWT_HIGH_RESOLUTION_CLOCK)
if ( d_data->clock )
{
if ( !d_data->clock->isNull() )
elapsed = d_data->clock->elapsed();
return elapsed;
}
#endif
if ( !d_data->time.isNull() )
elapsed = d_data->time.elapsed();
return elapsed;
}
/*!
\return Accuracy of the system clock in milliseconds.
*/
double QwtSystemClock::precision()
{
static double prec = 0.0;
if ( prec <= 0.0 )
{
#if defined(QWT_HIGH_RESOLUTION_CLOCK)
prec = QwtHighResolutionClock::precision();
#endif
if ( prec <= 0.0 )
prec = 1.0; // QTime offers 1 ms
}
return prec;
}
<|endoftext|> |
<commit_before>/* libs/graphics/effects/SkCullPoints.cpp
**
** Copyright 2006, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#include "SkCullPoints.h"
#include "Sk64.h"
static bool cross_product_is_neg(const SkIPoint& v, int dx, int dy)
{
#if 0
return v.fX * dy - v.fY * dx < 0;
#else
Sk64 tmp0, tmp1;
tmp0.setMul(v.fX, dy);
tmp1.setMul(dx, v.fY);
tmp0.sub(tmp1);
return tmp0.isNeg();
#endif
}
bool SkCullPoints::sect_test(int x0, int y0, int x1, int y1) const
{
const SkIRect& r = fR;
if (x0 < r.fLeft && x1 < r.fLeft ||
x0 > r.fRight && x1 > r.fRight ||
y0 < r.fTop && y1 < r.fTop ||
y0 > r.fBottom && y1 > r.fBottom)
return false;
// since the crossprod test is a little expensive, check for easy-in cases first
if (r.contains(x0, y0) || r.contains(x1, y1))
return true;
// At this point we're not sure, so we do a crossprod test
SkIPoint vec;
const SkIPoint* rAsQuad = fAsQuad;
vec.set(x1 - x0, y1 - y0);
bool isNeg = cross_product_is_neg(vec, x0 - rAsQuad[0].fX, y0 - rAsQuad[0].fY);
for (int i = 1; i < 4; i++) {
if (cross_product_is_neg(vec, x0 - rAsQuad[i].fX, y0 - rAsQuad[i].fY) != isNeg)
{
return true;
}
}
return false; // we didn't intersect
}
static void toQuad(const SkIRect& r, SkIPoint quad[4])
{
SkASSERT(quad);
quad[0].set(r.fLeft, r.fTop);
quad[1].set(r.fRight, r.fTop);
quad[2].set(r.fRight, r.fBottom);
quad[3].set(r.fLeft, r.fBottom);
}
SkCullPoints::SkCullPoints()
{
SkIRect r;
r.setEmpty();
this->reset(r);
}
SkCullPoints::SkCullPoints(const SkIRect& r)
{
this->reset(r);
}
void SkCullPoints::reset(const SkIRect& r)
{
fR = r;
toQuad(fR, fAsQuad);
fPrevPt.set(0, 0);
fPrevResult = kNo_Result;
}
void SkCullPoints::moveTo(int x, int y)
{
fPrevPt.set(x, y);
fPrevResult = kNo_Result; // so we trigger a movetolineto later
}
SkCullPoints::LineToResult SkCullPoints::lineTo(int x, int y, SkIPoint line[])
{
SkASSERT(line != NULL);
LineToResult result = kNo_Result;
int x0 = fPrevPt.fX;
int y0 = fPrevPt.fY;
// need to upgrade sect_test to chop the result
// and to correctly return kLineTo_Result when the result is connected
// to the previous call-out
if (this->sect_test(x0, y0, x, y))
{
line[0].set(x0, y0);
line[1].set(x, y);
if (fPrevResult != kNo_Result && fPrevPt.equals(x0, y0))
result = kLineTo_Result;
else
result = kMoveToLineTo_Result;
}
fPrevPt.set(x, y);
fPrevResult = result;
return result;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
#include "SkPath.h"
SkCullPointsPath::SkCullPointsPath()
: fCP(), fPath(NULL)
{
}
SkCullPointsPath::SkCullPointsPath(const SkIRect& r, SkPath* dst)
: fCP(r), fPath(dst)
{
}
void SkCullPointsPath::reset(const SkIRect& r, SkPath* dst)
{
fCP.reset(r);
fPath = dst;
}
void SkCullPointsPath::moveTo(int x, int y)
{
fCP.moveTo(x, y);
}
void SkCullPointsPath::lineTo(int x, int y)
{
SkIPoint pts[2];
switch (fCP.lineTo(x, y, pts)) {
case SkCullPoints::kMoveToLineTo_Result:
fPath->moveTo(SkIntToScalar(pts[0].fX), SkIntToScalar(pts[0].fY));
// fall through to the lineto case
case SkCullPoints::kLineTo_Result:
fPath->lineTo(SkIntToScalar(pts[1].fX), SkIntToScalar(pts[1].fY));
break;
default:
break;
}
}
<commit_msg>Linux: GCC 4.3 warning fixes<commit_after>/* libs/graphics/effects/SkCullPoints.cpp
**
** Copyright 2006, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#include "SkCullPoints.h"
#include "Sk64.h"
static bool cross_product_is_neg(const SkIPoint& v, int dx, int dy)
{
#if 0
return v.fX * dy - v.fY * dx < 0;
#else
Sk64 tmp0, tmp1;
tmp0.setMul(v.fX, dy);
tmp1.setMul(dx, v.fY);
tmp0.sub(tmp1);
return tmp0.isNeg();
#endif
}
bool SkCullPoints::sect_test(int x0, int y0, int x1, int y1) const
{
const SkIRect& r = fR;
if ((x0 < r.fLeft && x1 < r.fLeft) ||
(x0 > r.fRight && x1 > r.fRight) ||
(y0 < r.fTop && y1 < r.fTop) ||
(y0 > r.fBottom && y1 > r.fBottom))
return false;
// since the crossprod test is a little expensive, check for easy-in cases first
if (r.contains(x0, y0) || r.contains(x1, y1))
return true;
// At this point we're not sure, so we do a crossprod test
SkIPoint vec;
const SkIPoint* rAsQuad = fAsQuad;
vec.set(x1 - x0, y1 - y0);
bool isNeg = cross_product_is_neg(vec, x0 - rAsQuad[0].fX, y0 - rAsQuad[0].fY);
for (int i = 1; i < 4; i++) {
if (cross_product_is_neg(vec, x0 - rAsQuad[i].fX, y0 - rAsQuad[i].fY) != isNeg)
{
return true;
}
}
return false; // we didn't intersect
}
static void toQuad(const SkIRect& r, SkIPoint quad[4])
{
SkASSERT(quad);
quad[0].set(r.fLeft, r.fTop);
quad[1].set(r.fRight, r.fTop);
quad[2].set(r.fRight, r.fBottom);
quad[3].set(r.fLeft, r.fBottom);
}
SkCullPoints::SkCullPoints()
{
SkIRect r;
r.setEmpty();
this->reset(r);
}
SkCullPoints::SkCullPoints(const SkIRect& r)
{
this->reset(r);
}
void SkCullPoints::reset(const SkIRect& r)
{
fR = r;
toQuad(fR, fAsQuad);
fPrevPt.set(0, 0);
fPrevResult = kNo_Result;
}
void SkCullPoints::moveTo(int x, int y)
{
fPrevPt.set(x, y);
fPrevResult = kNo_Result; // so we trigger a movetolineto later
}
SkCullPoints::LineToResult SkCullPoints::lineTo(int x, int y, SkIPoint line[])
{
SkASSERT(line != NULL);
LineToResult result = kNo_Result;
int x0 = fPrevPt.fX;
int y0 = fPrevPt.fY;
// need to upgrade sect_test to chop the result
// and to correctly return kLineTo_Result when the result is connected
// to the previous call-out
if (this->sect_test(x0, y0, x, y))
{
line[0].set(x0, y0);
line[1].set(x, y);
if (fPrevResult != kNo_Result && fPrevPt.equals(x0, y0))
result = kLineTo_Result;
else
result = kMoveToLineTo_Result;
}
fPrevPt.set(x, y);
fPrevResult = result;
return result;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
#include "SkPath.h"
SkCullPointsPath::SkCullPointsPath()
: fCP(), fPath(NULL)
{
}
SkCullPointsPath::SkCullPointsPath(const SkIRect& r, SkPath* dst)
: fCP(r), fPath(dst)
{
}
void SkCullPointsPath::reset(const SkIRect& r, SkPath* dst)
{
fCP.reset(r);
fPath = dst;
}
void SkCullPointsPath::moveTo(int x, int y)
{
fCP.moveTo(x, y);
}
void SkCullPointsPath::lineTo(int x, int y)
{
SkIPoint pts[2];
switch (fCP.lineTo(x, y, pts)) {
case SkCullPoints::kMoveToLineTo_Result:
fPath->moveTo(SkIntToScalar(pts[0].fX), SkIntToScalar(pts[0].fY));
// fall through to the lineto case
case SkCullPoints::kLineTo_Result:
fPath->lineTo(SkIntToScalar(pts[1].fX), SkIntToScalar(pts[1].fY));
break;
default:
break;
}
}
<|endoftext|> |
<commit_before>#include "stream.h"
Buffer::Buffer()
{
}
Buffer::Buffer(const Buffer &other, uint64_t start, uint64_t length)
{
this->data = other.data + start;
this->length = length;
this->_dont_delete = true;
}
Buffer::Buffer(const Buffer &other)
{
this->length = other.length;
if (other.data)
{
this->data = (byte *)malloc((size_t)this->length);
memcpy(this->data, other.data, (size_t)this->length);
}
}
Buffer::~Buffer()
{
if (!_dont_delete)
{
free(this->data);
}
}
Buffer &Buffer::operator=(const Buffer &other)
{
delete[] this->data;
this->length = other.length;
if (other.data)
{
this->data = (byte *)malloc(this->length);
memcpy(this->data, other.data, this->length);
}
return *this;
}
void Buffer::resize(uint64_t new_length)
{
byte *new_data = (byte *)malloc(new_length);
if (data)
{
memcpy(new_data, this->data, min(this->length, new_length));
}
free(this->data);
this->data = new_data;
this->length = new_length;
}
void Buffer::append(const byte *data, uint64_t data_length)
{
const uint64_t old_length = this->length;
const uint64_t new_length = old_length + data_length;
assert(new_length > old_length);
resize(new_length);
memcpy(this->data + old_length, data, data_length);
}
<commit_msg>vm: fix some size_t/uint64_t issues (26)<commit_after>#include "stream.h"
Buffer::Buffer()
{
}
Buffer::Buffer(const Buffer &other, uint64_t start, uint64_t length)
{
this->data = other.data + start;
this->length = length;
this->_dont_delete = true;
}
Buffer::Buffer(const Buffer &other)
{
this->length = other.length;
if (other.data)
{
this->data = (byte *)malloc((size_t)this->length);
memcpy(this->data, other.data, (size_t)this->length);
}
}
Buffer::~Buffer()
{
if (!_dont_delete)
{
free(this->data);
}
}
Buffer &Buffer::operator=(const Buffer &other)
{
delete[] this->data;
this->length = other.length;
if (other.data)
{
this->data = (byte *)malloc((size_t)this->length);
memcpy(this->data, other.data, (size_t)this->length);
}
return *this;
}
void Buffer::resize(uint64_t new_length)
{
byte *new_data = (byte *)malloc(new_length);
if (data)
{
memcpy(new_data, this->data, min(this->length, new_length));
}
free(this->data);
this->data = new_data;
this->length = new_length;
}
void Buffer::append(const byte *data, uint64_t data_length)
{
const uint64_t old_length = this->length;
const uint64_t new_length = old_length + data_length;
assert(new_length > old_length);
resize(new_length);
memcpy(this->data + old_length, data, data_length);
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tightdb/util/safe_int_ops.hpp>
#include "util.hpp"
#include "io_realm_internal_Group.h"
using namespace tightdb;
using std::string;
JNIEXPORT jlong JNICALL Java_io_realm_internal_Group_createNative__(
JNIEnv* env, jobject)
{
Group *ptr = new Group();
TR((LOG_DEBUG, log_tag, "Group::createNative(): %x.", ptr));
return reinterpret_cast<jlong>(ptr);
}
JNIEXPORT jlong JNICALL Java_io_realm_internal_Group_createNative__Ljava_lang_String_2I(
JNIEnv* env, jobject, jstring jFileName, jint mode, jbyteArray keyArray)
{
TR_ENTER()
Group* pGroup = 0;
StringData file_name;
try {
JStringAccessor file_name_tmp(env, jFileName); // throws
file_name = StringData(file_name_tmp);
Group::OpenMode openmode;
switch (mode) {
case 0: openmode = Group::mode_ReadOnly; break;
case 1: openmode = Group::mode_ReadWrite; break;
case 2: openmode = Group::mode_ReadWriteNoCreate; break;
default:
TR((LOG_DEBUG, log_tag, "Invalid mode: %d", mode));
ThrowException(env, IllegalArgument, "Group(): Invalid mode parameter.");
return 0;
}
KeyBuffer key(env, keyArray);
#ifdef TIGHTDB_ENABLE_ENCRYPTION
pGroup = new Group(file_name, key.data(), openmode);
#else
pGroup = new Group(file_name, openmode);
#endif
TR((LOG_DEBUG, log_tag, "%x", pGroup))
return reinterpret_cast<jlong>(pGroup);
}
CATCH_FILE(file_name)
CATCH_STD()
// Failed - cleanup
if (pGroup)
delete pGroup;
return 0;
}
JNIEXPORT jlong JNICALL Java_io_realm_internal_Group_createNative___3B(
JNIEnv* env, jobject, jbyteArray jData)
{
TR_ENTER()
// Copy the group buffer given
jsize byteArrayLength = env->GetArrayLength(jData);
if (byteArrayLength == 0)
return 0;
jbyte* buf = static_cast<jbyte*>(malloc(S(byteArrayLength)*sizeof(jbyte)));
if (!buf) {
ThrowException(env, OutOfMemory, "copying the group buffer.");
return 0;
}
env->GetByteArrayRegion(jData, 0, byteArrayLength, buf);
TR((LOG_DEBUG, log_tag, " %d bytes.", byteArrayLength))
Group* pGroup = 0;
try {
pGroup = new Group(BinaryData(reinterpret_cast<char*>(buf), S(byteArrayLength)), true);
TR((LOG_DEBUG, log_tag, " groupPtr: %x", pGroup));
return reinterpret_cast<jlong>(pGroup);
}
CATCH_FILE("memory-buffer")
CATCH_STD()
// Failed - cleanup
if (buf)
free(buf);
return 0;
}
// FIXME: Remove this method? It's dangerous to not own the group data...
JNIEXPORT jlong JNICALL Java_io_realm_internal_Group_createNative__Ljava_nio_ByteBuffer_2(
JNIEnv* env, jobject, jobject jByteBuffer)
{
TR_ENTER()
BinaryData bin;
if (!GetBinaryData(env, jByteBuffer, bin))
return 0;
TR((LOG_DEBUG, log_tag, " %d bytes.", bin.size()))
Group* pGroup = 0;
try {
pGroup = new Group(BinaryData(bin.data(), bin.size()), false);
}
CATCH_FILE("memory-buffer")
CATCH_STD()
TR((LOG_DEBUG, log_tag, "%x", pGroup))
return reinterpret_cast<jlong>(pGroup);
}
JNIEXPORT void JNICALL Java_io_realm_internal_Group_nativeClose(
JNIEnv* env, jclass, jlong nativeGroupPtr)
{
TR_ENTER_PTR(nativeGroupPtr)
delete G(nativeGroupPtr);
}
JNIEXPORT jlong JNICALL Java_io_realm_internal_Group_nativeSize(
JNIEnv*, jobject, jlong nativeGroupPtr)
{
TR_ENTER_PTR(nativeGroupPtr)
return static_cast<jlong>( G(nativeGroupPtr)->size() ); // noexcept
}
JNIEXPORT jboolean JNICALL Java_io_realm_internal_Group_nativeHasTable(
JNIEnv* env, jobject, jlong nativeGroupPtr, jstring jTableName)
{
TR_ENTER_PTR(nativeGroupPtr)
try {
JStringAccessor tableName(env, jTableName); // throws
return G(nativeGroupPtr)->has_table(tableName);
} CATCH_STD()
return false;
}
JNIEXPORT jstring JNICALL Java_io_realm_internal_Group_nativeGetTableName(
JNIEnv* env, jobject, jlong nativeGroupPtr, jint index)
{
TR_ENTER_PTR(nativeGroupPtr)
try {
return to_jstring(env, G(nativeGroupPtr)->get_table_name(index));
} CATCH_STD()
return 0;
}
JNIEXPORT jlong JNICALL Java_io_realm_internal_Group_nativeGetTableNativePtr(
JNIEnv *env, jobject, jlong nativeGroupPtr, jstring name)
{
TR_ENTER_PTR(nativeGroupPtr)
try {
JStringAccessor tableName(env, name); // throws
Table* pTable = LangBindHelper::get_or_add_table(*G(nativeGroupPtr), tableName);
return (jlong)pTable;
} CATCH_STD()
return 0;
}
JNIEXPORT void JNICALL Java_io_realm_internal_Group_nativeWriteToFile(
JNIEnv* env, jobject, jlong nativeGroupPtr, jstring jFileName, jbyteArray keyArray)
{
TR_ENTER_PTR(nativeGroupPtr)
StringData file_name;
KeyBuffer key(env, keyArray);
try {
JStringAccessor file_name_tmp(env, jFileName); // throws
file_name = StringData(file_name_tmp);
#ifdef TIGHTDB_ENABLE_ENCRYPTION
G(nativeGroupPtr)->write(file_name_tmp), key.data());
#else
G(nativeGroupPtr)->write(file_name);
#endif
}
CATCH_FILE(file_name)
CATCH_STD()
}
JNIEXPORT jbyteArray JNICALL Java_io_realm_internal_Group_nativeWriteToMem(
JNIEnv* env, jobject, jlong nativeGroupPtr)
{
TR_ENTER_PTR(nativeGroupPtr)
BinaryData buffer;
char* bufPtr = 0;
try {
buffer = G(nativeGroupPtr)->write_to_mem(); // throws
bufPtr = const_cast<char*>(buffer.data());
// Copy the data to Java array, so Java owns it.
jbyteArray jArray = 0;
if (buffer.size() <= MAX_JSIZE) {
jsize jlen = static_cast<jsize>(buffer.size());
jArray = env->NewByteArray(jlen);
if (jArray)
// Copy data to Byte[]
env->SetByteArrayRegion(jArray, 0, jlen, reinterpret_cast<const jbyte*>(bufPtr));
// SetByteArrayRegion() may throw ArrayIndexOutOfBoundsException - logic error
}
if (!jArray) {
ThrowException(env, IndexOutOfBounds, "Group too big to copy and write.");
}
free(bufPtr);
return jArray;
}
CATCH_STD()
if (bufPtr)
free(bufPtr);
return 0;
}
JNIEXPORT jobject JNICALL Java_io_realm_internal_Group_nativeWriteToByteBuffer(
JNIEnv* env, jobject, jlong nativeGroupPtr)
{
TR_ENTER_PTR(nativeGroupPtr)
BinaryData buffer;
try {
buffer = G(nativeGroupPtr)->write_to_mem();
if (util::int_less_than_or_equal(buffer.size(), MAX_JLONG)) {
return env->NewDirectByteBuffer(const_cast<char*>(buffer.data()), static_cast<jlong>(buffer.size()));
// Data is now owned by the Java DirectByteBuffer - so we must not free it.
}
else {
ThrowException(env, IndexOutOfBounds, "Group too big to write.");
return NULL;
}
}
CATCH_STD()
return NULL;
}
JNIEXPORT void JNICALL Java_io_realm_internal_Group_nativeCommit(
JNIEnv*, jobject, jlong nativeGroupPtr)
{
G(nativeGroupPtr)->commit();
}
JNIEXPORT jstring JNICALL Java_io_realm_internal_Group_nativeToJson(
JNIEnv* env, jobject, jlong nativeGroupPtr)
{
Group* grp = G(nativeGroupPtr);
try {
// Write group to string in JSON format
std::ostringstream ss;
ss.sync_with_stdio(false); // for performance
grp->to_json(ss);
const std::string str = ss.str();
return to_jstring(env, str);
} CATCH_STD()
return 0;
}
JNIEXPORT jstring JNICALL Java_io_realm_internal_Group_nativeToString(
JNIEnv* env, jobject, jlong nativeGroupPtr)
{
Group* grp = G(nativeGroupPtr);
try {
// Write group to string
std::ostringstream ss;
ss.sync_with_stdio(false); // for performance
grp->to_string(ss);
const std::string str = ss.str();
return to_jstring(env, str);
} CATCH_STD()
return 0;
}
JNIEXPORT jboolean JNICALL Java_io_realm_internal_Group_nativeEquals(
JNIEnv* env, jobject, jlong nativeGroupPtr, jlong nativeGroupToComparePtr)
{
Group* grp = G(nativeGroupPtr);
Group* grpToCompare = G(nativeGroupToComparePtr);
try {
return (*grp == *grpToCompare);
} CATCH_STD()
return false;
}
<commit_msg>Update io_realm_internal_Group.cpp<commit_after>/*
* Copyright 2014 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tightdb/util/safe_int_ops.hpp>
#include "util.hpp"
#include "io_realm_internal_Group.h"
using namespace tightdb;
using std::string;
JNIEXPORT jlong JNICALL Java_io_realm_internal_Group_createNative__(
JNIEnv* env, jobject)
{
TR_ENTER()
Group *ptr = new Group();
TR((LOG_DEBUG, log_tag, "Group::createNative(): %x.", ptr));
return reinterpret_cast<jlong>(ptr);
}
JNIEXPORT jlong JNICALL Java_io_realm_internal_Group_createNative__Ljava_lang_String_2I(
JNIEnv* env, jobject, jstring jFileName, jint mode, jbyteArray keyArray)
{
TR_ENTER()
Group* pGroup = 0;
StringData file_name;
try {
JStringAccessor file_name_tmp(env, jFileName); // throws
file_name = StringData(file_name_tmp);
Group::OpenMode openmode;
switch (mode) {
case 0: openmode = Group::mode_ReadOnly; break;
case 1: openmode = Group::mode_ReadWrite; break;
case 2: openmode = Group::mode_ReadWriteNoCreate; break;
default:
TR((LOG_DEBUG, log_tag, "Invalid mode: %d", mode));
ThrowException(env, IllegalArgument, "Group(): Invalid mode parameter.");
return 0;
}
KeyBuffer key(env, keyArray);
#ifdef TIGHTDB_ENABLE_ENCRYPTION
pGroup = new Group(file_name, key.data(), openmode);
#else
pGroup = new Group(file_name, openmode);
#endif
TR((LOG_DEBUG, log_tag, "group: %x", pGroup))
return reinterpret_cast<jlong>(pGroup);
}
CATCH_FILE(file_name)
CATCH_STD()
// Failed - cleanup
if (pGroup)
delete pGroup;
return 0;
}
JNIEXPORT jlong JNICALL Java_io_realm_internal_Group_createNative___3B(
JNIEnv* env, jobject, jbyteArray jData)
{
TR_ENTER()
// Copy the group buffer given
jsize byteArrayLength = env->GetArrayLength(jData);
if (byteArrayLength == 0)
return 0;
jbyte* buf = static_cast<jbyte*>(malloc(S(byteArrayLength)*sizeof(jbyte)));
if (!buf) {
ThrowException(env, OutOfMemory, "copying the group buffer.");
return 0;
}
env->GetByteArrayRegion(jData, 0, byteArrayLength, buf);
TR((LOG_DEBUG, log_tag, " %d bytes.", byteArrayLength))
Group* pGroup = 0;
try {
pGroup = new Group(BinaryData(reinterpret_cast<char*>(buf), S(byteArrayLength)), true);
TR((LOG_DEBUG, log_tag, " groupPtr: %x", pGroup));
return reinterpret_cast<jlong>(pGroup);
}
CATCH_FILE("memory-buffer")
CATCH_STD()
// Failed - cleanup
if (buf)
free(buf);
return 0;
}
// FIXME: Remove this method? It's dangerous to not own the group data...
JNIEXPORT jlong JNICALL Java_io_realm_internal_Group_createNative__Ljava_nio_ByteBuffer_2(
JNIEnv* env, jobject, jobject jByteBuffer)
{
TR_ENTER()
BinaryData bin;
if (!GetBinaryData(env, jByteBuffer, bin))
return 0;
TR((LOG_DEBUG, log_tag, " %d bytes.", bin.size()))
Group* pGroup = 0;
try {
pGroup = new Group(BinaryData(bin.data(), bin.size()), false);
}
CATCH_FILE("memory-buffer")
CATCH_STD()
TR((LOG_DEBUG, log_tag, "%x", pGroup))
return reinterpret_cast<jlong>(pGroup);
}
JNIEXPORT void JNICALL Java_io_realm_internal_Group_nativeClose(
JNIEnv* env, jclass, jlong nativeGroupPtr)
{
TR_ENTER_PTR(nativeGroupPtr)
delete G(nativeGroupPtr);
}
JNIEXPORT jlong JNICALL Java_io_realm_internal_Group_nativeSize(
JNIEnv*, jobject, jlong nativeGroupPtr)
{
TR_ENTER_PTR(nativeGroupPtr)
return static_cast<jlong>( G(nativeGroupPtr)->size() ); // noexcept
}
JNIEXPORT jboolean JNICALL Java_io_realm_internal_Group_nativeHasTable(
JNIEnv* env, jobject, jlong nativeGroupPtr, jstring jTableName)
{
TR_ENTER_PTR(nativeGroupPtr)
try {
JStringAccessor tableName(env, jTableName); // throws
return G(nativeGroupPtr)->has_table(tableName);
} CATCH_STD()
return false;
}
JNIEXPORT jstring JNICALL Java_io_realm_internal_Group_nativeGetTableName(
JNIEnv* env, jobject, jlong nativeGroupPtr, jint index)
{
TR_ENTER_PTR(nativeGroupPtr)
try {
return to_jstring(env, G(nativeGroupPtr)->get_table_name(index));
} CATCH_STD()
return 0;
}
JNIEXPORT jlong JNICALL Java_io_realm_internal_Group_nativeGetTableNativePtr(
JNIEnv *env, jobject, jlong nativeGroupPtr, jstring name)
{
TR_ENTER_PTR(nativeGroupPtr)
try {
JStringAccessor tableName(env, name); // throws
Table* pTable = LangBindHelper::get_or_add_table(*G(nativeGroupPtr), tableName);
return (jlong)pTable;
} CATCH_STD()
return 0;
}
JNIEXPORT void JNICALL Java_io_realm_internal_Group_nativeWriteToFile(
JNIEnv* env, jobject, jlong nativeGroupPtr, jstring jFileName, jbyteArray keyArray)
{
TR_ENTER_PTR(nativeGroupPtr)
StringData file_name;
KeyBuffer key(env, keyArray);
try {
JStringAccessor file_name_tmp(env, jFileName); // throws
file_name = StringData(file_name_tmp);
#ifdef TIGHTDB_ENABLE_ENCRYPTION
G(nativeGroupPtr)->write(file_name_tmp), key.data());
#else
G(nativeGroupPtr)->write(file_name);
#endif
}
CATCH_FILE(file_name)
CATCH_STD()
}
JNIEXPORT jbyteArray JNICALL Java_io_realm_internal_Group_nativeWriteToMem(
JNIEnv* env, jobject, jlong nativeGroupPtr)
{
TR_ENTER_PTR(nativeGroupPtr)
BinaryData buffer;
char* bufPtr = 0;
try {
buffer = G(nativeGroupPtr)->write_to_mem(); // throws
bufPtr = const_cast<char*>(buffer.data());
// Copy the data to Java array, so Java owns it.
jbyteArray jArray = 0;
if (buffer.size() <= MAX_JSIZE) {
jsize jlen = static_cast<jsize>(buffer.size());
jArray = env->NewByteArray(jlen);
if (jArray)
// Copy data to Byte[]
env->SetByteArrayRegion(jArray, 0, jlen, reinterpret_cast<const jbyte*>(bufPtr));
// SetByteArrayRegion() may throw ArrayIndexOutOfBoundsException - logic error
}
if (!jArray) {
ThrowException(env, IndexOutOfBounds, "Group too big to copy and write.");
}
free(bufPtr);
return jArray;
}
CATCH_STD()
if (bufPtr)
free(bufPtr);
return 0;
}
JNIEXPORT jobject JNICALL Java_io_realm_internal_Group_nativeWriteToByteBuffer(
JNIEnv* env, jobject, jlong nativeGroupPtr)
{
TR_ENTER_PTR(nativeGroupPtr)
BinaryData buffer;
try {
buffer = G(nativeGroupPtr)->write_to_mem();
if (util::int_less_than_or_equal(buffer.size(), MAX_JLONG)) {
return env->NewDirectByteBuffer(const_cast<char*>(buffer.data()), static_cast<jlong>(buffer.size()));
// Data is now owned by the Java DirectByteBuffer - so we must not free it.
}
else {
ThrowException(env, IndexOutOfBounds, "Group too big to write.");
return NULL;
}
}
CATCH_STD()
return NULL;
}
JNIEXPORT void JNICALL Java_io_realm_internal_Group_nativeCommit(
JNIEnv*, jobject, jlong nativeGroupPtr)
{
TR_ENTER()
G(nativeGroupPtr)->commit();
}
JNIEXPORT jstring JNICALL Java_io_realm_internal_Group_nativeToJson(
JNIEnv* env, jobject, jlong nativeGroupPtr)
{
Group* grp = G(nativeGroupPtr);
try {
// Write group to string in JSON format
std::ostringstream ss;
ss.sync_with_stdio(false); // for performance
grp->to_json(ss);
const std::string str = ss.str();
return to_jstring(env, str);
} CATCH_STD()
return 0;
}
JNIEXPORT jstring JNICALL Java_io_realm_internal_Group_nativeToString(
JNIEnv* env, jobject, jlong nativeGroupPtr)
{
Group* grp = G(nativeGroupPtr);
try {
// Write group to string
std::ostringstream ss;
ss.sync_with_stdio(false); // for performance
grp->to_string(ss);
const std::string str = ss.str();
return to_jstring(env, str);
} CATCH_STD()
return 0;
}
JNIEXPORT jboolean JNICALL Java_io_realm_internal_Group_nativeEquals(
JNIEnv* env, jobject, jlong nativeGroupPtr, jlong nativeGroupToComparePtr)
{
Group* grp = G(nativeGroupPtr);
Group* grpToCompare = G(nativeGroupToComparePtr);
try {
return (*grp == *grpToCompare);
} CATCH_STD()
return false;
}
<|endoftext|> |
<commit_before>#include <iostream>
using namespace std;
int main()
{
cout<<"Hello, World!!"<<endl;
}
<commit_msg>test_travis<commit_after>#include <iostream>
using namespace std;
int main()
{
cout<<"Hello, World!!"<<endl;
return 0;
}
<|endoftext|> |
<commit_before>#include "raspboop/data/RBPPacket.h"
#include <iostream>
using namespace std;
namespace raspboop
{
#define pack754_32(f) (Pack754((f), 32, 8))
#define pack754_64(f) (Pack754((f), 64, 11))
#define unpack754_32(i) (Unpack754((i), 32, 8))
#define unpack754_64(i) (Unpack754((i), 64, 11))
RBPPacket::RBPPacket()
{
}
Command* RBPPacket::DecodeDataToCommand(unsigned char* data)
{
int8_t componentId;
int8_t commandId;
vector<float> cmdParams;
int index = 0;
cmdParams.reserve(4);
componentId = Unpackint8(data);
index++;
commandId = Unpackint8(data + index);
index++;
while(data[index] != '\0')
{
int32_t fparam = Unpackint32(data + index);
cmdParams.push_back(unpack754_32(fparam));
index += 4;
}
return Command::CreateCommand(componentId, commandId, cmdParams);
}
void RBPPacket::Packint8(unsigned char* buffer, int8_t i)
{
*buffer++ = (i >> 0) & 0xff;
}
int8_t RBPPacket::Unpackint8(unsigned char* buffer)
{
return *buffer++;
}
void RBPPacket::Packint32(unsigned char* buffer, int32_t i)
{
*buffer++ = i >> 24;
*buffer++ = i >> 16;
*buffer++ = i >> 8;
*buffer++ = i;
}
int32_t RBPPacket::Unpackint32(unsigned char* buffer)
{
return (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3];
}
uint64_t RBPPacket::Pack754(long double f, unsigned bits, unsigned expbits)
{
long double fnorm;
int shift;
long long sign, exp, significand;
unsigned significandbits = bits - expbits - 1; // -1 for sign bit
if (f == 0.0) return 0; // get this special case out of the way
// check sign and begin normalization
if (f < 0) { sign = 1; fnorm = -f; }
else { sign = 0; fnorm = f; }
// get the normalized form of f and track the exponent
shift = 0;
while(fnorm >= 2.0) { fnorm /= 2.0; shift++; }
while(fnorm < 1.0) { fnorm *= 2.0; shift--; }
fnorm = fnorm - 1.0;
// calculate the binary form (non-float) of the significand data
significand = fnorm * ((1LL<<significandbits) + 0.5f);
// get the biased exponent
exp = shift + ((1<<(expbits-1)) - 1); // shift + bias
// return the final answer
return (sign<<(bits-1)) | (exp<<(bits-expbits-1)) | significand;
}
long double RBPPacket::Unpack754(uint64_t i, unsigned bits, unsigned expbits)
{
long double result;
long long shift;
unsigned bias;
unsigned significandbits = bits - expbits - 1; // -1 for sign bit
if (i == 0) return 0.0;
// pull the significand
result = (i&((1LL<<significandbits)-1)); // mask
result /= (1LL<<significandbits); // convert back to float
result += 1.0f; // add the one back on
// deal with the exponent
bias = (1<<(expbits-1)) - 1;
shift = ((i>>significandbits)&((1LL<<expbits)-1)) - bias;
while(shift > 0) { result *= 2.0; shift--; }
while(shift < 0) { result /= 2.0; shift++; }
// sign it
result *= (i>>(bits-1))&1? -1.0: 1.0;
return result;
}
RBPPacket::~RBPPacket()
{
}
} /* raspboop */
<commit_msg>RBPPacket: remove IO include directives<commit_after>#include "raspboop/data/RBPPacket.h"
namespace raspboop
{
#define pack754_32(f) (Pack754((f), 32, 8))
#define pack754_64(f) (Pack754((f), 64, 11))
#define unpack754_32(i) (Unpack754((i), 32, 8))
#define unpack754_64(i) (Unpack754((i), 64, 11))
RBPPacket::RBPPacket()
{
}
Command* RBPPacket::DecodeDataToCommand(unsigned char* data)
{
int8_t componentId;
int8_t commandId;
vector<float> cmdParams;
int index = 0;
cmdParams.reserve(4);
componentId = Unpackint8(data);
index++;
commandId = Unpackint8(data + index);
index++;
while(data[index] != '\0')
{
int32_t fparam = Unpackint32(data + index);
cmdParams.push_back(unpack754_32(fparam));
index += 4;
}
return Command::CreateCommand(componentId, commandId, cmdParams);
}
void RBPPacket::Packint8(unsigned char* buffer, int8_t i)
{
*buffer++ = (i >> 0) & 0xff;
}
int8_t RBPPacket::Unpackint8(unsigned char* buffer)
{
return *buffer++;
}
void RBPPacket::Packint32(unsigned char* buffer, int32_t i)
{
*buffer++ = i >> 24;
*buffer++ = i >> 16;
*buffer++ = i >> 8;
*buffer++ = i;
}
int32_t RBPPacket::Unpackint32(unsigned char* buffer)
{
return (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3];
}
uint64_t RBPPacket::Pack754(long double f, unsigned bits, unsigned expbits)
{
long double fnorm;
int shift;
long long sign, exp, significand;
unsigned significandbits = bits - expbits - 1; // -1 for sign bit
if (f == 0.0) return 0; // get this special case out of the way
// check sign and begin normalization
if (f < 0) { sign = 1; fnorm = -f; }
else { sign = 0; fnorm = f; }
// get the normalized form of f and track the exponent
shift = 0;
while(fnorm >= 2.0) { fnorm /= 2.0; shift++; }
while(fnorm < 1.0) { fnorm *= 2.0; shift--; }
fnorm = fnorm - 1.0;
// calculate the binary form (non-float) of the significand data
significand = fnorm * ((1LL<<significandbits) + 0.5f);
// get the biased exponent
exp = shift + ((1<<(expbits-1)) - 1); // shift + bias
// return the final answer
return (sign<<(bits-1)) | (exp<<(bits-expbits-1)) | significand;
}
long double RBPPacket::Unpack754(uint64_t i, unsigned bits, unsigned expbits)
{
long double result;
long long shift;
unsigned bias;
unsigned significandbits = bits - expbits - 1; // -1 for sign bit
if (i == 0) return 0.0;
// pull the significand
result = (i&((1LL<<significandbits)-1)); // mask
result /= (1LL<<significandbits); // convert back to float
result += 1.0f; // add the one back on
// deal with the exponent
bias = (1<<(expbits-1)) - 1;
shift = ((i>>significandbits)&((1LL<<expbits)-1)) - bias;
while(shift > 0) { result *= 2.0; shift--; }
while(shift < 0) { result /= 2.0; shift++; }
// sign it
result *= (i>>(bits-1))&1? -1.0: 1.0;
return result;
}
RBPPacket::~RBPPacket()
{
}
} /* raspboop */
<|endoftext|> |
<commit_before>#include <taichi/lang.h>
#include <taichi/testing.h>
#include <numeric>
TLANG_NAMESPACE_BEGIN
TC_TEST("gpu_gc_basics") {
for (auto arch : {Arch::gpu}) {
int n = 32;
Program prog(arch);
Global(x, i32);
layout([&]() {
auto i = Index(0);
auto j = Index(1);
root.dense(i, n).pointer().dense(j, n).place(x);
});
kernel([&]() {
For(0, n, [&](Expr i) {
For(0, i, [&](Expr j) { Activate(x.snode(), {i, j}); });
});
})();
kernel([&]() {
For(0, n, [&](Expr i) { For(0, i, [&](Expr j) { x[i, j] = i + j; }); });
})();
auto stat = x.parent().parent().snode()->stat();
TC_CHECK(stat.num_resident_blocks == n - 1);
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
TC_CHECK(x.val<int>(i, j) == i + j);
}
}
x.parent().parent().snode()->clear_data_and_deactivate();
stat = x.parent().parent().snode()->stat();
TC_CHECK(stat.num_resident_blocks == 0);
TC_CHECK(stat.num_recycled_blocks == 0);
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
TC_CHECK(x.val<int>(i, j) == 0);
}
}
}
};
TC_TEST("parallel_particle_sort") {
Program prog(Arch::gpu);
CoreState::set_trigger_gdb_when_crash(true);
constexpr int n = 256;
const real dx = 1.0_f / n, inv_dx = 1.0_f / dx;
constexpr int dim = 3;
auto f32 = DataType::f32;
int grid_block_size = 4;
Vector particle_x(f32, dim);
Global(l, i32);
Vector grid_v(f32, dim);
Global(grid_m, f32);
int max_n_particles = 1024 * 1024;
int n_particles = 0;
std::vector<float> benchmark_particles;
std::vector<Vector3> p_x;
n_particles = max_n_particles;
p_x.resize(n_particles);
for (int i = 0; i < n_particles; i++) {
Vector3 offset = Vector3::rand() - Vector3(0.5_f);
p_x[i] = Vector3(0.5_f) + offset * 0.7f;
}
TC_ASSERT(n_particles <= max_n_particles);
auto i = Index(0), j = Index(1), k = Index(2);
auto p = Index(3);
layout([&]() {
auto &fork = root.dynamic(p, max_n_particles);
for (int i = 0; i < dim; i++) {
fork.place(particle_x(i));
}
TC_ASSERT(n % grid_block_size == 0);
auto &block = root.dense({i, j, k}, n / grid_block_size).pointer();
block.dense({i, j, k}, grid_block_size)
.place(grid_v(0), grid_v(1), grid_v(2), grid_m);
block.dynamic(p, pow<dim>(grid_block_size) * 64).place(l);
});
TC_ASSERT(bit::is_power_of_two(n));
Kernel(sort).def([&] {
BlockDim(256);
For(particle_x(0), [&](Expr p) {
auto node_coord = floor(particle_x[p] * inv_dx - 0.5_f);
Append(l.parent(),
(cast<int32>(node_coord(0)), cast<int32>(node_coord(1)),
cast<int32>(node_coord(2))),
p);
});
});
for (int i = 0; i < n_particles; i++) {
for (int d = 0; d < dim; d++) {
particle_x(d).val<float32>(i) = p_x[i][d];
}
}
int last_nb = -1;
for (int i = 0; i < 2048; i++) {
grid_m.parent().parent().snode()->clear_data_and_deactivate();
sort();
prog.synchronize();
auto stat = grid_m.parent().parent().snode()->stat();
int nb = stat.num_resident_blocks;
if (last_nb == -1) {
last_nb = nb;
TC_P(last_nb);
} else {
if (last_nb != nb) {
TC_P(i);
}
TC_CHECK(last_nb == nb);
}
}
};
TLANG_NAMESPACE_END
<commit_msg>removed dynamic in sort test<commit_after>#include <taichi/lang.h>
#include <taichi/testing.h>
#include <numeric>
TLANG_NAMESPACE_BEGIN
TC_TEST("gpu_gc_basics") {
for (auto arch : {Arch::gpu}) {
int n = 32;
Program prog(arch);
Global(x, i32);
layout([&]() {
auto i = Index(0);
auto j = Index(1);
root.dense(i, n).pointer().dense(j, n).place(x);
});
kernel([&]() {
For(0, n, [&](Expr i) {
For(0, i, [&](Expr j) { Activate(x.snode(), {i, j}); });
});
})();
kernel([&]() {
For(0, n, [&](Expr i) { For(0, i, [&](Expr j) { x[i, j] = i + j; }); });
})();
auto stat = x.parent().parent().snode()->stat();
TC_CHECK(stat.num_resident_blocks == n - 1);
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
TC_CHECK(x.val<int>(i, j) == i + j);
}
}
x.parent().parent().snode()->clear_data_and_deactivate();
stat = x.parent().parent().snode()->stat();
TC_CHECK(stat.num_resident_blocks == 0);
TC_CHECK(stat.num_recycled_blocks == 0);
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
TC_CHECK(x.val<int>(i, j) == 0);
}
}
}
};
TC_TEST("parallel_particle_sort") {
Program prog(Arch::gpu);
CoreState::set_trigger_gdb_when_crash(true);
constexpr int n = 256;
const real dx = 1.0_f / n, inv_dx = 1.0_f / dx;
constexpr int dim = 3;
auto f32 = DataType::f32;
int grid_block_size = 4;
Vector particle_x(f32, dim);
Global(l, i32);
Vector grid_v(f32, dim);
Global(grid_m, f32);
int max_n_particles = 1024 * 1024;
int n_particles = 0;
std::vector<float> benchmark_particles;
std::vector<Vector3> p_x;
n_particles = max_n_particles;
p_x.resize(n_particles);
for (int i = 0; i < n_particles; i++) {
Vector3 offset = Vector3::rand() - Vector3(0.5_f);
p_x[i] = Vector3(0.5_f) + offset * 0.7f;
}
TC_ASSERT(n_particles <= max_n_particles);
auto i = Index(0), j = Index(1), k = Index(2);
auto p = Index(3);
layout([&]() {
auto &fork = root.dynamic(p, max_n_particles);
for (int i = 0; i < dim; i++) {
fork.place(particle_x(i));
}
TC_ASSERT(n % grid_block_size == 0);
auto &block = root.dense({i, j, k}, n / grid_block_size).pointer();
block.dense({i, j, k}, grid_block_size)
.place(grid_v(0), grid_v(1), grid_v(2), grid_m);
});
TC_ASSERT(bit::is_power_of_two(n));
Kernel(sort).def([&] {
BlockDim(256);
For(particle_x(0), [&](Expr p) {
auto node_coord = floor(particle_x[p] * inv_dx - 0.5_f);
grid_v[cast<int32>(node_coord(0)), cast<int32>(node_coord(1)),
cast<int32>(node_coord(2))](0) = 1;
});
});
for (int i = 0; i < n_particles; i++) {
for (int d = 0; d < dim; d++) {
particle_x(d).val<float32>(i) = p_x[i][d];
}
}
int last_nb = -1;
for (int i = 0; i < 2048; i++) {
grid_m.parent().parent().snode()->clear_data_and_deactivate();
sort();
prog.synchronize();
auto stat = grid_m.parent().parent().snode()->stat();
int nb = stat.num_resident_blocks;
if (last_nb == -1) {
last_nb = nb;
TC_P(last_nb);
} else {
if (last_nb != nb) {
TC_P(i);
}
TC_CHECK(last_nb == nb);
}
}
};
TLANG_NAMESPACE_END
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014, webvariants GmbH, http://www.webvariants.de
*
* This file is released under the terms of the MIT license. You can find the
* complete text in the attached LICENSE file or online at:
*
* http://www.opensource.org/licenses/mit-license.php
*
* @author: Thomas Krause (thomas.krause@webvariants.de)
*/
#include "gtest/gtest.h"
#include "events/global.h"
#include <condition_variable>
#include <chrono>
#include "iocontroller/IOEventInterface.h"
class IOEventInterfaceTest : public ::testing::Test {
protected:
bool callbackCalled = false;
std::condition_variable cond;
std::mutex m;
void SetUp() override {
//world.setupLogger();
//Susi::setLogLevel(Susi::Logger::ALL);
world.setupIOController();
world.ioController->makeDir("./IO_EVENT_TESTS/CHECKDIR/");
}
virtual void TearDown() override {
world.ioController->deletePath("./IO_EVENT_TESTS/");
}
};
/*
#include <gtest/gtest.h>
#include <Poco/Dynamic/Var.h>
#include "iocontroller/IOEventInterface.h"
#include "world/World.h"
class IOEventInterfaceTest : public ::testing::Test {
protected:
bool callbackCalled = false;
std::condition_variable cond;
std::mutex m;
void SetUp() override {
//world.setupLogger();
//Susi::setLogLevel(Susi::Logger::ALL);
world.setupIOController();
world.ioController->makeDir("./IO_EVENT_TESTS/CHECKDIR/");
}
virtual void TearDown() override {
world.ioController->deletePath("./IO_EVENT_TESTS/");
}
};
TEST_F(IOEventInterfaceTest, WriteFile) {
Susi::once("file_write_result",[this](Susi::Event & event){
EXPECT_TRUE(event.payload.convert<bool>());
callbackCalled = true;
cond.notify_one();
});
auto event = Susi::Event("io::writeFile",Susi::Event::Payload({
{"filename","./IO_EVENT_TESTS/write.txt"},
{"content","foo bar"}
}));
event.returnAddr = "file_write_result";
Susi::publish(event);
{
std::unique_lock<std::mutex> lk(m);
cond.wait_for(lk,
std::chrono::duration<int,std::milli>{500},
[this](){return callbackCalled;});
EXPECT_TRUE(callbackCalled);
}
}
TEST_F(IOEventInterfaceTest, WriteFileInvalidDirectory) {
Susi::once("file_write_invalid_result",[this](Susi::Event & event){
EXPECT_FALSE(event.payload.convert<bool>());
callbackCalled = true;
cond.notify_one();
});
auto event = Susi::Event("io::writeFile",Susi::Event::Payload({
{"filename","./IO_EVENT_TESTS/BLAA/write.txt"},
{"content","foo bar"}
}));
event.returnAddr = "file_write_invalid_result";
Susi::publish(event);
{
std::unique_lock<std::mutex> lk(m);
cond.wait_for(lk,
std::chrono::duration<int,std::milli>{500},
[this](){return callbackCalled;});
EXPECT_TRUE(callbackCalled);
}
}
TEST_F(IOEventInterfaceTest, ReadFile) {
world.ioController->writeFile("./IO_EVENT_TESTS/read.txt","foobar");
Susi::once("file_read_result",[this](Susi::Event & event){
EXPECT_EQ("foobar",event.payload.convert<std::string>());
callbackCalled = true;
cond.notify_one();
});
auto event = Susi::Event("io::readFile",Susi::Event::Payload({
{"filename","./IO_EVENT_TESTS/read.txt"},
}));
event.returnAddr = "file_read_result";
Susi::publish(event);
{
std::unique_lock<std::mutex> lk(m);
cond.wait_for(lk,
std::chrono::duration<int,std::milli>{500},
[this](){return callbackCalled;});
EXPECT_TRUE(callbackCalled);
}
}
TEST_F(IOEventInterfaceTest, DeletePath) {
world.ioController->writeFile("./IO_EVENT_TESTS/delete.txt","TEXT TO DELETE");
Susi::once("file_delete_result",[this](Susi::Event & event){
callbackCalled = true;
cond.notify_one();
});
auto event = Susi::Event("io::deletePath",Susi::Event::Payload({
{"path","./IO_EVENT_TESTS/delete.txt"},
}));
event.returnAddr = "file_delete_result";
Susi::publish(event);
{
std::unique_lock<std::mutex> lk(m);
cond.wait_for(lk,
std::chrono::duration<int,std::milli>{500},
[this](){return callbackCalled;});
EXPECT_TRUE(callbackCalled);
}
}
TEST_F(IOEventInterfaceTest, MakeDir) {
Susi::once("make_dir_result",[this](Susi::Event event){
EXPECT_TRUE(event.payload.convert<bool>());
callbackCalled = true;
cond.notify_one();
});
auto event = Susi::Event("io::makeDir",Susi::Event::Payload({
{"dir","./IO_EVENT_TESTS/test_dir"},
}));
event.returnAddr = "make_dir_result";
Susi::publish(event);
{
std::unique_lock<std::mutex> lk(m);
cond.wait_for(lk,
std::chrono::duration<int,std::milli>{500},
[this](){return callbackCalled;});
EXPECT_TRUE(callbackCalled);
}
}
TEST_F(IOEventInterfaceTest, MovePath) {
Susi::once("move_path_result",[this](Susi::Event & event){
EXPECT_TRUE(event.payload.convert<bool>());
callbackCalled = true;
cond.notify_one();
});
auto event = Susi::Event("io::movePath",Susi::Event::Payload({
{"source_path","./IO_EVENT_TESTS/CHECKDIR/"},
{"dest_path","./IO_EVENT_TESTS/MOVED_CHECKDIR"},
}));
event.returnAddr = "move_path_result";
Susi::publish(event);
{
std::unique_lock<std::mutex> lk(m);
cond.wait_for(lk,
std::chrono::duration<int,std::milli>{500},
[this](){return callbackCalled;});
EXPECT_TRUE(callbackCalled);
}
}
TEST_F(IOEventInterfaceTest, CopyPath) {
Susi::once("copy_path_result",[this](Susi::Event & event){
EXPECT_TRUE(event.payload.convert<bool>());
callbackCalled = true;
cond.notify_one();
});
auto event = Susi::Event("io::copyPath",Susi::Event::Payload({
{"source_path","./IO_EVENT_TESTS/CHECKDIR/"},
{"dest_path","./IO_EVENT_TESTS/MOVED_CHECKDIR"},
}));
event.returnAddr = "copy_path_result";
Susi::publish(event);
{
std::unique_lock<std::mutex> lk(m);
cond.wait_for(lk,
std::chrono::duration<int,std::milli>{500},
[this](){return callbackCalled;});
EXPECT_TRUE(callbackCalled);
}
}
*/<commit_msg>[IOEventTest] refactored;<commit_after>/*
* Copyright (c) 2014, webvariants GmbH, http://www.webvariants.de
*
* This file is released under the terms of the MIT license. You can find the
* complete text in the attached LICENSE file or online at:
*
* http://www.opensource.org/licenses/mit-license.php
*
* @author: Thomas Krause (thomas.krause@webvariants.de)
*/
#include "gtest/gtest.h"
#include "events/global.h"
#include <condition_variable>
#include <chrono>
#include "iocontroller/IOEventInterface.h"
class IOEventInterfaceTest : public ::testing::Test {
protected:
std::mutex mutex;
bool callbackCalledOne = false;
std::condition_variable condOne;
bool callbackCalledTwo = false;
std::condition_variable condTwo;
void SetUp() override {
world.setupEventManager();
world.setupIOController();
world.ioController->makeDir("./IO_EVENT_TESTS/CHECKDIR/");
}
virtual void TearDown() override {
world.ioController->deletePath("./IO_EVENT_TESTS/");
}
};
using namespace Susi::Events;
TEST_F(IOEventInterfaceTest, WriteFile) {
auto event = createEvent("io::writeFile");
event->payload = Susi::Util::Any::Object{
{"filename","./IO_EVENT_TESTS/write.txt"},
{"content","foo bar"}
};
publish(std::move(event),[this](SharedEventPtr event){
EXPECT_NO_THROW ({
int bytesWritten = event->payload["bytesWritten"];
EXPECT_EQ(7,bytesWritten);
});
callbackCalledOne = true;
condOne.notify_all();
});
{
std::unique_lock<std::mutex> lk(mutex);
condOne.wait_for(lk,std::chrono::milliseconds{100},[this](){return callbackCalledOne;});
EXPECT_TRUE(callbackCalledOne);
}
}
TEST_F(IOEventInterfaceTest, WriteFileInvalidDirectory) {
auto event = createEvent("io::writeFile");
event->payload = Susi::Util::Any::Object{
{"filename","./IO_EVENT_TESTS/BLAA/write.txt"},
{"content","foo bar"}
};
publish(std::move(event),[this](SharedEventPtr event){
EXPECT_EQ(1,event->headers.size());
EXPECT_EQ("error", event->headers[0].first);
EXPECT_EQ("Error in handleWriteFile(): WriteFile: Dir don't exists!./IO_EVENT_TESTS/BLAA/write.txt", event->headers[0].second);
callbackCalledOne = true;
condOne.notify_all();
});
{
std::unique_lock<std::mutex> lk(mutex);
condOne.wait_for(lk,std::chrono::milliseconds{500},[this](){return callbackCalledOne;});
EXPECT_TRUE(callbackCalledOne);
}
}
TEST_F(IOEventInterfaceTest, ReadFile) {
world.ioController->writeFile("./IO_EVENT_TESTS/read.txt","foobar");
auto event = createEvent("io::readFile");
event->payload = Susi::Util::Any::Object{
{"filename","./IO_EVENT_TESTS/read.txt"}
};
publish(std::move(event),[this](SharedEventPtr event){
EXPECT_NO_THROW ({
std::string content = event->payload["content"];
EXPECT_EQ("foobar",content);
});
callbackCalledOne = true;
condOne.notify_all();
});
{
std::unique_lock<std::mutex> lk(mutex);
condOne.wait_for(lk,std::chrono::milliseconds{500},[this](){return callbackCalledOne;});
EXPECT_TRUE(callbackCalledOne);
}
}
TEST_F(IOEventInterfaceTest, DeletePath) {
world.ioController->writeFile("./IO_EVENT_TESTS/delete.txt","TEXT TO DELETE");
auto event = createEvent("io::deletePath");
event->payload = Susi::Util::Any::Object{
{"path","./IO_EVENT_TESTS/delete.txt"}
};
publish(std::move(event),[this](SharedEventPtr event){
EXPECT_NO_THROW ({
bool success = event->payload["success"];
EXPECT_TRUE(success);
});
callbackCalledOne = true;
condOne.notify_all();
});
{
std::unique_lock<std::mutex> lk(mutex);
condOne.wait_for(lk,std::chrono::milliseconds{500},[this](){return callbackCalledOne;});
EXPECT_TRUE(callbackCalledOne);
}
}
TEST_F(IOEventInterfaceTest, MakeDir) {
auto event = createEvent("io::makeDir");
event->payload = Susi::Util::Any::Object{
{"dir","./IO_EVENT_TESTS/test_dir"}
};
publish(std::move(event),[this](SharedEventPtr event){
EXPECT_NO_THROW ({
bool success = event->payload["success"];
EXPECT_TRUE(success);
});
callbackCalledOne = true;
condOne.notify_all();
});
{
std::unique_lock<std::mutex> lk(mutex);
condOne.wait_for(lk,std::chrono::milliseconds{500},[this](){return callbackCalledOne;});
EXPECT_TRUE(callbackCalledOne);
}
}
TEST_F(IOEventInterfaceTest, MovePath) {
auto event = createEvent("io::movePath");
event->payload = Susi::Util::Any::Object{
{"source_path","./IO_EVENT_TESTS/CHECKDIR/"},
{"dest_path","./IO_EVENT_TESTS/MOVED_CHECKDIR"}
};
publish(std::move(event),[this](SharedEventPtr event){
EXPECT_NO_THROW ({
bool success = event->payload["success"];
EXPECT_TRUE(success);
});
callbackCalledOne = true;
condOne.notify_all();
});
{
std::unique_lock<std::mutex> lk(mutex);
condOne.wait_for(lk,std::chrono::milliseconds{500},[this](){return callbackCalledOne;});
EXPECT_TRUE(callbackCalledOne);
}
}
TEST_F(IOEventInterfaceTest, CopyPath) {
auto event = createEvent("io::copyPath");
event->payload = Susi::Util::Any::Object{
{"source_path","./IO_EVENT_TESTS/CHECKDIR/"},
{"dest_path","./IO_EVENT_TESTS/MOVED_CHECKDIR"}
};
publish(std::move(event),[this](SharedEventPtr event){
EXPECT_NO_THROW ({
bool success = event->payload["success"];
EXPECT_TRUE(success);
});
callbackCalledOne = true;
condOne.notify_all();
});
{
std::unique_lock<std::mutex> lk(mutex);
condOne.wait_for(lk,std::chrono::milliseconds{500},[this](){return callbackCalledOne;});
EXPECT_TRUE(callbackCalledOne);
}
}<|endoftext|> |
<commit_before>// Copyright (c) 2015-2016 William W. Fisher (at gmail dot com)
// This file is distributed under the MIT License.
#include "ofp/instructionlist.h"
#include "ofp/unittest.h"
using namespace ofp;
static void MakeInstructionList(InstructionList &) {}
template <class Type, class... Args>
void MakeInstructionList(InstructionList &set, Type value, Args... args) {
set.add(value);
MakeInstructionList(set, args...);
}
template <class Type, class... Args>
InstructionList MakeInstructions(Type value, Args... args) {
InstructionList set;
MakeInstructionList(set, value, args...);
return set;
}
template <class Head, class... Tail>
void MakeInstructionListFromTuple(InstructionList &set,
std::tuple<Head, Tail...> tuple) {
set.add(std::get<0>(tuple));
MakeInstructionListFromTuple(set, tuple);
}
template <class Head, class... Tail>
InstructionList MakeInstructionsFromTuple(std::tuple<Head, Tail...> tuple) {
InstructionList set;
MakeInstructionListFromTuple(tuple);
return set;
}
TEST(instructionlist, test) {
InstructionList list;
list.add(IT_GOTO_TABLE{5});
list.add(IT_CLEAR_ACTIONS{});
EXPECT_EQ(16, list.size());
auto expected = "0001-0008-05-000000 0005-0008-00000000";
EXPECT_HEX(expected, list.data(), list.size());
auto iter = list.begin();
auto iterEnd = list.end();
EXPECT_EQ(IT_GOTO_TABLE::type(), iter->type());
EXPECT_EQ(8, iter.size());
++iter;
EXPECT_EQ(IT_CLEAR_ACTIONS::type(), iter->type());
EXPECT_EQ(8, iter.size());
++iter;
EXPECT_EQ(iterEnd, iter);
}
TEST(instructionlist, MakeInstructions) {
auto set = MakeInstructions(IT_GOTO_TABLE{5}, IT_CLEAR_ACTIONS{});
auto expected = "0001-0008-05-000000 0005-0008-00000000";
EXPECT_HEX(expected, set.data(), set.size());
}
TEST(instructionlist, MakeInstructionList) {
InstructionList set;
MakeInstructionList(set, IT_GOTO_TABLE{5}, IT_CLEAR_ACTIONS{});
auto expected = "0001-0008-05-000000 0005-0008-00000000";
EXPECT_HEX(expected, set.data(), set.size());
}
<commit_msg>Fix gcc build failures.<commit_after>// Copyright (c) 2015-2016 William W. Fisher (at gmail dot com)
// This file is distributed under the MIT License.
#include "ofp/protocollist.h"
#include "ofp/instructionlist.h"
#include "ofp/unittest.h"
using namespace ofp;
static void MakeInstructionList(InstructionList &) {}
template <class Type, class... Args>
void MakeInstructionList(InstructionList &set, Type value, Args... args) {
set.add(value);
MakeInstructionList(set, args...);
}
template <class Type, class... Args>
InstructionList MakeInstructions(Type value, Args... args) {
InstructionList set;
MakeInstructionList(set, value, args...);
return set;
}
template <class Head, class... Tail>
void MakeInstructionListFromTuple(InstructionList &set,
std::tuple<Head, Tail...> tuple) {
set.add(std::get<0>(tuple));
MakeInstructionListFromTuple(set, tuple);
}
template <class Head, class... Tail>
InstructionList MakeInstructionsFromTuple(std::tuple<Head, Tail...> tuple) {
InstructionList set;
MakeInstructionListFromTuple(tuple);
return set;
}
TEST(instructionlist, test) {
InstructionList list;
list.add(IT_GOTO_TABLE{5});
list.add(IT_CLEAR_ACTIONS{});
EXPECT_EQ(16, list.size());
auto expected = "0001-0008-05-000000 0005-0008-00000000";
EXPECT_HEX(expected, list.data(), list.size());
auto iter = list.begin();
auto iterEnd = list.end();
EXPECT_EQ(IT_GOTO_TABLE::type(), iter->type());
EXPECT_EQ(8, iter.size());
++iter;
EXPECT_EQ(IT_CLEAR_ACTIONS::type(), iter->type());
EXPECT_EQ(8, iter.size());
++iter;
EXPECT_EQ(iterEnd, iter);
}
TEST(instructionlist, MakeInstructions) {
auto set = MakeInstructions(IT_GOTO_TABLE{5}, IT_CLEAR_ACTIONS{});
auto expected = "0001-0008-05-000000 0005-0008-00000000";
EXPECT_HEX(expected, set.data(), set.size());
}
TEST(instructionlist, MakeInstructionList) {
InstructionList set;
MakeInstructionList(set, IT_GOTO_TABLE{5}, IT_CLEAR_ACTIONS{});
auto expected = "0001-0008-05-000000 0005-0008-00000000";
EXPECT_HEX(expected, set.data(), set.size());
}
<|endoftext|> |
<commit_before>// Copyright 2021 The gVisor Authors.
//
// 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 <net/if.h>
#include <netinet/if_ether.h>
#include <netpacket/packet.h>
#include <poll.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <limits>
#include "gtest/gtest.h"
#include "test/syscalls/linux/ip_socket_test_util.h"
#include "test/util/capability_util.h"
#include "test/util/file_descriptor.h"
#include "test/util/socket_util.h"
namespace gvisor {
namespace testing {
namespace {
using ::testing::AnyOf;
using ::testing::Combine;
using ::testing::Eq;
using ::testing::Values;
class PacketSocketCreationTest
: public ::testing::TestWithParam<std::tuple<int, int>> {
protected:
void SetUp() override {
if (!ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability())) {
const auto [type, protocol] = GetParam();
ASSERT_THAT(socket(AF_PACKET, type, htons(protocol)),
SyscallFailsWithErrno(EPERM));
GTEST_SKIP() << "Missing packet socket capability";
}
}
};
TEST_P(PacketSocketCreationTest, Create) {
const auto [type, protocol] = GetParam();
FileDescriptor fd =
ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_PACKET, type, htons(protocol)));
EXPECT_GE(fd.get(), 0);
}
INSTANTIATE_TEST_SUITE_P(AllPacketSocketTests, PacketSocketCreationTest,
Combine(Values(SOCK_DGRAM, SOCK_RAW),
Values(0, 1, 255, ETH_P_IP, ETH_P_IPV6,
std::numeric_limits<uint16_t>::max())));
class PacketSocketTest : public ::testing::TestWithParam<int> {
protected:
void SetUp() override {
if (!ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability())) {
ASSERT_THAT(socket(AF_PACKET, GetParam(), 0),
SyscallFailsWithErrno(EPERM));
GTEST_SKIP() << "Missing packet socket capability";
}
socket_ = ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_PACKET, GetParam(), 0));
}
FileDescriptor socket_;
};
TEST_P(PacketSocketTest, GetSockName) {
{
// First check the local address of an unbound packet socket.
sockaddr_ll addr;
socklen_t addrlen = sizeof(addr);
ASSERT_THAT(getsockname(socket_.get(), reinterpret_cast<sockaddr*>(&addr),
&addrlen),
SyscallSucceeds());
// sockaddr_ll ends with an 8 byte physical address field, but only the
// bytes that are used in the sockaddr_ll.sll_addr field are included in the
// address length. Seems Linux used to return the size of sockaddr_ll, but
// https://github.com/torvalds/linux/commit/0fb375fb9b93b7d822debc6a734052337ccfdb1f
// changed things to only return `sizeof(sockaddr_ll) + sll.sll_addr`.
ASSERT_THAT(addrlen, AnyOf(Eq(sizeof(addr)),
Eq(sizeof(addr) - sizeof(addr.sll_addr))));
EXPECT_EQ(addr.sll_family, AF_PACKET);
EXPECT_EQ(addr.sll_ifindex, 0);
if (IsRunningOnGvisor() && !IsRunningWithHostinet() &&
GvisorPlatform() != Platform::kFuchsia) {
// TODO(https://gvisor.dev/issue/6530): Do not assume all interfaces have
// an ethernet address.
EXPECT_EQ(addr.sll_halen, ETH_ALEN);
} else {
EXPECT_EQ(addr.sll_halen, 0);
}
EXPECT_EQ(ntohs(addr.sll_protocol), 0);
EXPECT_EQ(addr.sll_hatype, 0);
}
// Next we bind the socket to loopback before checking the local address.
const sockaddr_ll bind_addr = {
.sll_family = AF_PACKET,
.sll_protocol = htons(ETH_P_IP),
.sll_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex()),
};
ASSERT_THAT(bind(socket_.get(), reinterpret_cast<const sockaddr*>(&bind_addr),
sizeof(bind_addr)),
SyscallSucceeds());
{
sockaddr_ll addr;
socklen_t addrlen = sizeof(addr);
ASSERT_THAT(getsockname(socket_.get(), reinterpret_cast<sockaddr*>(&addr),
&addrlen),
SyscallSucceeds());
ASSERT_THAT(addrlen,
AnyOf(Eq(sizeof(addr)),
Eq(sizeof(addr) - sizeof(addr.sll_addr) + ETH_ALEN)));
EXPECT_EQ(addr.sll_family, AF_PACKET);
EXPECT_EQ(addr.sll_ifindex, bind_addr.sll_ifindex);
EXPECT_EQ(addr.sll_halen, ETH_ALEN);
// Bound to loopback which has the all zeroes address.
for (int i = 0; i < addr.sll_halen; ++i) {
EXPECT_EQ(addr.sll_addr[i], 0) << "byte mismatch @ idx = " << i;
}
EXPECT_EQ(ntohs(addr.sll_protocol), htons(addr.sll_protocol));
if (IsRunningOnGvisor() && !IsRunningWithHostinet() &&
GvisorPlatform() != Platform::kFuchsia) {
// TODO(https://gvisor.dev/issue/6621): Support populating sll_hatype.
EXPECT_EQ(addr.sll_hatype, 0);
} else {
EXPECT_EQ(addr.sll_hatype, ARPHRD_LOOPBACK);
}
}
}
TEST_P(PacketSocketTest, RebindProtocol) {
const bool kEthHdrIncluded = GetParam() == SOCK_RAW;
sockaddr_in udp_bind_addr = {
.sin_family = AF_INET,
.sin_addr = {.s_addr = htonl(INADDR_LOOPBACK)},
};
FileDescriptor udp_sock =
ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, 0));
{
// Bind the socket so that we have something to send packets to.
//
// If we didn't do this, the UDP packets we send will be responded to with
// ICMP Destination Port Unreachable errors.
ASSERT_THAT(
bind(udp_sock.get(), reinterpret_cast<const sockaddr*>(&udp_bind_addr),
sizeof(udp_bind_addr)),
SyscallSucceeds());
socklen_t addrlen = sizeof(udp_bind_addr);
ASSERT_THAT(
getsockname(udp_sock.get(), reinterpret_cast<sockaddr*>(&udp_bind_addr),
&addrlen),
SyscallSucceeds());
ASSERT_THAT(addrlen, sizeof(udp_bind_addr));
}
const int loopback_index = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());
auto send_udp_message = [&](const uint64_t v) {
ASSERT_THAT(
sendto(udp_sock.get(), reinterpret_cast<const char*>(&v), sizeof(v),
0 /* flags */, reinterpret_cast<const sockaddr*>(&udp_bind_addr),
sizeof(udp_bind_addr)),
SyscallSucceeds());
// Make sure the payload has been delivered (in case of asynchronous
// delivery).
char buf[sizeof(v)];
EXPECT_THAT(RecvTimeout(udp_sock.get(), buf, sizeof(v), 1 /*timeout*/),
IsPosixErrorOkAndHolds(sizeof(v)));
ASSERT_EQ(*reinterpret_cast<uint64_t*>(buf), v);
};
auto bind_to_network_protocol = [&](uint16_t protocol) {
const sockaddr_ll packet_bind_addr = {
.sll_family = AF_PACKET,
.sll_protocol = htons(protocol),
.sll_ifindex = loopback_index,
};
ASSERT_THAT(bind(socket_.get(),
reinterpret_cast<const sockaddr*>(&packet_bind_addr),
sizeof(packet_bind_addr)),
SyscallSucceeds());
};
auto test_recv = [&, this](const uint64_t v) {
struct {
ethhdr eth;
iphdr ip;
udphdr udp;
uint64_t payload;
char unused;
} ABSL_ATTRIBUTE_PACKED read_pkt;
sockaddr_ll src;
socklen_t src_len = sizeof(src);
char* buf = reinterpret_cast<char*>(&read_pkt);
size_t buflen = sizeof(read_pkt);
size_t expected_read_len = sizeof(read_pkt) - sizeof(read_pkt.unused);
if (!kEthHdrIncluded) {
buf += sizeof(read_pkt.eth);
buflen -= sizeof(read_pkt.eth);
expected_read_len -= sizeof(read_pkt.eth);
}
iovec received_iov = {
.iov_base = buf,
.iov_len = buflen,
};
msghdr received_msg = {
.msg_name = &src,
.msg_namelen = src_len,
.msg_iov = &received_iov,
.msg_iovlen = 1,
};
ASSERT_THAT(RecvMsgTimeout(socket_.get(), &received_msg, 1 /*timeout*/),
IsPosixErrorOkAndHolds(expected_read_len));
// sockaddr_ll ends with an 8 byte physical address field, but ethernet
// addresses only use 6 bytes. Linux used to return sizeof(sockaddr_ll)-2
// here, but returns sizeof(sockaddr_ll) since
// https://github.com/torvalds/linux/commit/b2cf86e1563e33a14a1c69b3e508d15dc12f804c.
ASSERT_THAT(received_msg.msg_namelen,
AnyOf(Eq(sizeof(src)),
Eq(sizeof(src) - sizeof(src.sll_addr) + ETH_ALEN)));
EXPECT_EQ(src.sll_family, AF_PACKET);
EXPECT_EQ(src.sll_ifindex, loopback_index);
EXPECT_EQ(src.sll_halen, ETH_ALEN);
EXPECT_EQ(ntohs(src.sll_protocol), ETH_P_IP);
// This came from the loopback device, so the address is all 0s.
constexpr uint8_t allZeroesMAC[ETH_ALEN] = {};
EXPECT_EQ(memcmp(src.sll_addr, allZeroesMAC, sizeof(allZeroesMAC)), 0);
if (kEthHdrIncluded) {
EXPECT_EQ(memcmp(read_pkt.eth.h_dest, allZeroesMAC, sizeof(allZeroesMAC)),
0);
EXPECT_EQ(
memcmp(read_pkt.eth.h_source, allZeroesMAC, sizeof(allZeroesMAC)), 0);
EXPECT_EQ(ntohs(read_pkt.eth.h_proto), ETH_P_IP);
}
// IHL hold the size of the header in 4 byte units.
EXPECT_EQ(read_pkt.ip.ihl, sizeof(iphdr) / 4);
EXPECT_EQ(read_pkt.ip.version, IPVERSION);
const uint16_t ip_pkt_size =
sizeof(read_pkt) - sizeof(read_pkt.eth) - sizeof(read_pkt.unused);
EXPECT_EQ(ntohs(read_pkt.ip.tot_len), ip_pkt_size);
EXPECT_EQ(read_pkt.ip.protocol, IPPROTO_UDP);
EXPECT_EQ(ntohl(read_pkt.ip.daddr), INADDR_LOOPBACK);
EXPECT_EQ(ntohl(read_pkt.ip.saddr), INADDR_LOOPBACK);
EXPECT_EQ(read_pkt.udp.source, udp_bind_addr.sin_port);
EXPECT_EQ(read_pkt.udp.dest, udp_bind_addr.sin_port);
EXPECT_EQ(ntohs(read_pkt.udp.len), ip_pkt_size - sizeof(read_pkt.ip));
EXPECT_EQ(read_pkt.payload, v);
};
// The packet socket is not bound to IPv4 so we should not receive the sent
// message.
uint64_t counter = 0;
ASSERT_NO_FATAL_FAILURE(send_udp_message(++counter));
// Bind to IPv4 and expect to receive the UDP packet we send after binding.
ASSERT_NO_FATAL_FAILURE(bind_to_network_protocol(ETH_P_IP));
ASSERT_NO_FATAL_FAILURE(send_udp_message(++counter));
ASSERT_NO_FATAL_FAILURE(test_recv(counter));
// Bind the packet socket to a random protocol.
ASSERT_NO_FATAL_FAILURE(bind_to_network_protocol(255));
ASSERT_NO_FATAL_FAILURE(send_udp_message(++counter));
// Bind back to IPv4 and expect to the UDP packet we send after binding
// back to IPv4.
ASSERT_NO_FATAL_FAILURE(bind_to_network_protocol(ETH_P_IP));
ASSERT_NO_FATAL_FAILURE(send_udp_message(++counter));
ASSERT_NO_FATAL_FAILURE(test_recv(counter));
// A zero valued protocol number should not change the bound network protocol.
ASSERT_NO_FATAL_FAILURE(bind_to_network_protocol(0));
ASSERT_NO_FATAL_FAILURE(send_udp_message(++counter));
ASSERT_NO_FATAL_FAILURE(test_recv(counter));
}
INSTANTIATE_TEST_SUITE_P(AllPacketSocketTests, PacketSocketTest,
Values(SOCK_DGRAM, SOCK_RAW));
} // namespace
} // namespace testing
} // namespace gvisor
<commit_msg>Align stack variables in RebindProtocol test<commit_after>// Copyright 2021 The gVisor Authors.
//
// 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 <net/if.h>
#include <netinet/if_ether.h>
#include <netpacket/packet.h>
#include <poll.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <limits>
#include "gtest/gtest.h"
#include "test/syscalls/linux/ip_socket_test_util.h"
#include "test/util/capability_util.h"
#include "test/util/file_descriptor.h"
#include "test/util/socket_util.h"
namespace gvisor {
namespace testing {
namespace {
using ::testing::AnyOf;
using ::testing::Combine;
using ::testing::Eq;
using ::testing::Values;
class PacketSocketCreationTest
: public ::testing::TestWithParam<std::tuple<int, int>> {
protected:
void SetUp() override {
if (!ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability())) {
const auto [type, protocol] = GetParam();
ASSERT_THAT(socket(AF_PACKET, type, htons(protocol)),
SyscallFailsWithErrno(EPERM));
GTEST_SKIP() << "Missing packet socket capability";
}
}
};
TEST_P(PacketSocketCreationTest, Create) {
const auto [type, protocol] = GetParam();
FileDescriptor fd =
ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_PACKET, type, htons(protocol)));
EXPECT_GE(fd.get(), 0);
}
INSTANTIATE_TEST_SUITE_P(AllPacketSocketTests, PacketSocketCreationTest,
Combine(Values(SOCK_DGRAM, SOCK_RAW),
Values(0, 1, 255, ETH_P_IP, ETH_P_IPV6,
std::numeric_limits<uint16_t>::max())));
class PacketSocketTest : public ::testing::TestWithParam<int> {
protected:
void SetUp() override {
if (!ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability())) {
ASSERT_THAT(socket(AF_PACKET, GetParam(), 0),
SyscallFailsWithErrno(EPERM));
GTEST_SKIP() << "Missing packet socket capability";
}
socket_ = ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_PACKET, GetParam(), 0));
}
FileDescriptor socket_;
};
TEST_P(PacketSocketTest, GetSockName) {
{
// First check the local address of an unbound packet socket.
sockaddr_ll addr;
socklen_t addrlen = sizeof(addr);
ASSERT_THAT(getsockname(socket_.get(), reinterpret_cast<sockaddr*>(&addr),
&addrlen),
SyscallSucceeds());
// sockaddr_ll ends with an 8 byte physical address field, but only the
// bytes that are used in the sockaddr_ll.sll_addr field are included in the
// address length. Seems Linux used to return the size of sockaddr_ll, but
// https://github.com/torvalds/linux/commit/0fb375fb9b93b7d822debc6a734052337ccfdb1f
// changed things to only return `sizeof(sockaddr_ll) + sll.sll_addr`.
ASSERT_THAT(addrlen, AnyOf(Eq(sizeof(addr)),
Eq(sizeof(addr) - sizeof(addr.sll_addr))));
EXPECT_EQ(addr.sll_family, AF_PACKET);
EXPECT_EQ(addr.sll_ifindex, 0);
if (IsRunningOnGvisor() && !IsRunningWithHostinet() &&
GvisorPlatform() != Platform::kFuchsia) {
// TODO(https://gvisor.dev/issue/6530): Do not assume all interfaces have
// an ethernet address.
EXPECT_EQ(addr.sll_halen, ETH_ALEN);
} else {
EXPECT_EQ(addr.sll_halen, 0);
}
EXPECT_EQ(ntohs(addr.sll_protocol), 0);
EXPECT_EQ(addr.sll_hatype, 0);
}
// Next we bind the socket to loopback before checking the local address.
const sockaddr_ll bind_addr = {
.sll_family = AF_PACKET,
.sll_protocol = htons(ETH_P_IP),
.sll_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex()),
};
ASSERT_THAT(bind(socket_.get(), reinterpret_cast<const sockaddr*>(&bind_addr),
sizeof(bind_addr)),
SyscallSucceeds());
{
sockaddr_ll addr;
socklen_t addrlen = sizeof(addr);
ASSERT_THAT(getsockname(socket_.get(), reinterpret_cast<sockaddr*>(&addr),
&addrlen),
SyscallSucceeds());
ASSERT_THAT(addrlen,
AnyOf(Eq(sizeof(addr)),
Eq(sizeof(addr) - sizeof(addr.sll_addr) + ETH_ALEN)));
EXPECT_EQ(addr.sll_family, AF_PACKET);
EXPECT_EQ(addr.sll_ifindex, bind_addr.sll_ifindex);
EXPECT_EQ(addr.sll_halen, ETH_ALEN);
// Bound to loopback which has the all zeroes address.
for (int i = 0; i < addr.sll_halen; ++i) {
EXPECT_EQ(addr.sll_addr[i], 0) << "byte mismatch @ idx = " << i;
}
EXPECT_EQ(ntohs(addr.sll_protocol), htons(addr.sll_protocol));
if (IsRunningOnGvisor() && !IsRunningWithHostinet() &&
GvisorPlatform() != Platform::kFuchsia) {
// TODO(https://gvisor.dev/issue/6621): Support populating sll_hatype.
EXPECT_EQ(addr.sll_hatype, 0);
} else {
EXPECT_EQ(addr.sll_hatype, ARPHRD_LOOPBACK);
}
}
}
TEST_P(PacketSocketTest, RebindProtocol) {
const bool kEthHdrIncluded = GetParam() == SOCK_RAW;
sockaddr_in udp_bind_addr = {
.sin_family = AF_INET,
.sin_addr = {.s_addr = htonl(INADDR_LOOPBACK)},
};
FileDescriptor udp_sock =
ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, 0));
{
// Bind the socket so that we have something to send packets to.
//
// If we didn't do this, the UDP packets we send will be responded to with
// ICMP Destination Port Unreachable errors.
ASSERT_THAT(
bind(udp_sock.get(), reinterpret_cast<const sockaddr*>(&udp_bind_addr),
sizeof(udp_bind_addr)),
SyscallSucceeds());
socklen_t addrlen = sizeof(udp_bind_addr);
ASSERT_THAT(
getsockname(udp_sock.get(), reinterpret_cast<sockaddr*>(&udp_bind_addr),
&addrlen),
SyscallSucceeds());
ASSERT_THAT(addrlen, sizeof(udp_bind_addr));
}
const int loopback_index = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());
auto send_udp_message = [&](const uint64_t v) {
ASSERT_THAT(
sendto(udp_sock.get(), reinterpret_cast<const char*>(&v), sizeof(v),
0 /* flags */, reinterpret_cast<const sockaddr*>(&udp_bind_addr),
sizeof(udp_bind_addr)),
SyscallSucceeds());
// Make sure the payload has been delivered (in case of asynchronous
// delivery).
char buf[sizeof(v)];
EXPECT_THAT(RecvTimeout(udp_sock.get(), buf, sizeof(v), 1 /*timeout*/),
IsPosixErrorOkAndHolds(sizeof(v)));
ASSERT_EQ(*reinterpret_cast<uint64_t*>(buf), v);
};
auto bind_to_network_protocol = [&](uint16_t protocol) {
const sockaddr_ll packet_bind_addr = {
.sll_family = AF_PACKET,
.sll_protocol = htons(protocol),
.sll_ifindex = loopback_index,
};
ASSERT_THAT(bind(socket_.get(),
reinterpret_cast<const sockaddr*>(&packet_bind_addr),
sizeof(packet_bind_addr)),
SyscallSucceeds());
};
auto test_recv = [&, this](const uint64_t v) {
// Declare each section of the packet as a separate stack variable in order
// to ensure all sections are 8-byte aligned.
ethhdr eth;
iphdr ip;
udphdr udp;
uint64_t payload;
char unused;
constexpr size_t kStorageLen = sizeof(eth) + sizeof(ip) + sizeof(udp) +
sizeof(payload) + sizeof(unused);
char storage[kStorageLen];
sockaddr_ll src;
socklen_t src_len = sizeof(src);
char* buf = storage;
size_t buflen = kStorageLen;
auto advance_buf = [&buf, &buflen](size_t amount) {
buf += amount;
buflen -= amount;
};
size_t expected_read_len = buflen - sizeof(unused);
if (!kEthHdrIncluded) {
advance_buf(sizeof(eth));
expected_read_len -= sizeof(eth);
}
iovec received_iov = {
.iov_base = buf,
.iov_len = buflen,
};
msghdr received_msg = {
.msg_name = &src,
.msg_namelen = src_len,
.msg_iov = &received_iov,
.msg_iovlen = 1,
};
ASSERT_THAT(RecvMsgTimeout(socket_.get(), &received_msg, 1 /*timeout*/),
IsPosixErrorOkAndHolds(expected_read_len));
// sockaddr_ll ends with an 8 byte physical address field, but ethernet
// addresses only use 6 bytes. Linux used to return sizeof(sockaddr_ll)-2
// here, but returns sizeof(sockaddr_ll) since
// https://github.com/torvalds/linux/commit/b2cf86e1563e33a14a1c69b3e508d15dc12f804c.
ASSERT_THAT(received_msg.msg_namelen,
AnyOf(Eq(sizeof(src)),
Eq(sizeof(src) - sizeof(src.sll_addr) + ETH_ALEN)));
EXPECT_EQ(src.sll_family, AF_PACKET);
EXPECT_EQ(src.sll_ifindex, loopback_index);
EXPECT_EQ(src.sll_halen, ETH_ALEN);
EXPECT_EQ(ntohs(src.sll_protocol), ETH_P_IP);
// This came from the loopback device, so the address is all 0s.
constexpr uint8_t allZeroesMAC[ETH_ALEN] = {};
EXPECT_EQ(memcmp(src.sll_addr, allZeroesMAC, sizeof(allZeroesMAC)), 0);
if (kEthHdrIncluded) {
memcpy(ð, buf, sizeof(eth));
EXPECT_EQ(memcmp(eth.h_dest, allZeroesMAC, sizeof(allZeroesMAC)), 0);
EXPECT_EQ(memcmp(eth.h_source, allZeroesMAC, sizeof(allZeroesMAC)), 0);
EXPECT_EQ(ntohs(eth.h_proto), ETH_P_IP);
advance_buf(sizeof(eth));
}
// IHL hold the size of the header in 4 byte units.
memcpy(&ip, buf, sizeof(ip));
EXPECT_EQ(ip.ihl, sizeof(iphdr) / 4);
EXPECT_EQ(ip.version, IPVERSION);
const uint16_t ip_pkt_size = sizeof(ip) + sizeof(udp) + sizeof(payload);
EXPECT_EQ(ntohs(ip.tot_len), ip_pkt_size);
EXPECT_EQ(ip.protocol, IPPROTO_UDP);
EXPECT_EQ(ntohl(ip.daddr), INADDR_LOOPBACK);
EXPECT_EQ(ntohl(ip.saddr), INADDR_LOOPBACK);
advance_buf(sizeof(ip));
memcpy(&udp, buf, sizeof(udp));
EXPECT_EQ(udp.source, udp_bind_addr.sin_port);
EXPECT_EQ(udp.dest, udp_bind_addr.sin_port);
EXPECT_EQ(ntohs(udp.len), ip_pkt_size - sizeof(ip));
advance_buf(sizeof(udp));
memcpy(&payload, buf, sizeof(payload));
EXPECT_EQ(payload, v);
};
// The packet socket is not bound to IPv4 so we should not receive the sent
// message.
uint64_t counter = 0;
ASSERT_NO_FATAL_FAILURE(send_udp_message(++counter));
// Bind to IPv4 and expect to receive the UDP packet we send after binding.
ASSERT_NO_FATAL_FAILURE(bind_to_network_protocol(ETH_P_IP));
ASSERT_NO_FATAL_FAILURE(send_udp_message(++counter));
ASSERT_NO_FATAL_FAILURE(test_recv(counter));
// Bind the packet socket to a random protocol.
ASSERT_NO_FATAL_FAILURE(bind_to_network_protocol(255));
ASSERT_NO_FATAL_FAILURE(send_udp_message(++counter));
// Bind back to IPv4 and expect to the UDP packet we send after binding
// back to IPv4.
ASSERT_NO_FATAL_FAILURE(bind_to_network_protocol(ETH_P_IP));
ASSERT_NO_FATAL_FAILURE(send_udp_message(++counter));
ASSERT_NO_FATAL_FAILURE(test_recv(counter));
// A zero valued protocol number should not change the bound network protocol.
ASSERT_NO_FATAL_FAILURE(bind_to_network_protocol(0));
ASSERT_NO_FATAL_FAILURE(send_udp_message(++counter));
ASSERT_NO_FATAL_FAILURE(test_recv(counter));
}
INSTANTIATE_TEST_SUITE_P(AllPacketSocketTests, PacketSocketTest,
Values(SOCK_DGRAM, SOCK_RAW));
} // namespace
} // namespace testing
} // namespace gvisor
<|endoftext|> |
<commit_before>#include "ImageDescriberCommon.hpp"
#include "openMVG/types.hpp"
#include "openMVG/stl/split.hpp"
#include <exception>
#include <cassert>
namespace openMVG {
namespace features {
std::string EImageDescriberType_enumToString(EImageDescriberType imageDescriberType)
{
switch(imageDescriberType)
{
case EImageDescriberType::SIFT: return "SIFT";
case EImageDescriberType::SIFT_FLOAT: return "SIFT_FLOAT";
case EImageDescriberType::AKAZE: return "AKAZE";
case EImageDescriberType::AKAZE_LIOP: return "AKAZE_LIOP";
case EImageDescriberType::AKAZE_MLDB: return "AKAZE_MLDB";
#ifdef HAVE_CCTAG
case EImageDescriberType::CCTAG3: return "CCTAG3";
case EImageDescriberType::CCTAG4: return "CCTAG4";
#endif //HAVE_CCTAG
#ifdef HAVE_OPENCV
#ifdef USE_OCVSIFT
case EImageDescriberType::SIFT_OCV: return "SIFT_OCV";
#endif
case EImageDescriberType::AKAZE_OCV: return "AKAZE_OCV";
#endif//HAVE_OPENCV
case EImageDescriberType::UNKNOWN: return "UNKNOWN";
case EImageDescriberType::UNINITIALIZED: break; // Should throw an error.
}
throw std::out_of_range("Invalid imageDescriber enum");
}
EImageDescriberType EImageDescriberType_stringToEnum(const std::string& imageDescriberType)
{
if(imageDescriberType == "SIFT") return EImageDescriberType::SIFT;
if(imageDescriberType == "SIFT_FLOAT") return EImageDescriberType::SIFT_FLOAT;
if(imageDescriberType == "AKAZE_FLOAT") return EImageDescriberType::AKAZE;
if(imageDescriberType == "AKAZE_LIOP") return EImageDescriberType::AKAZE_LIOP;
if(imageDescriberType == "AKAZE_MLDB") return EImageDescriberType::AKAZE_MLDB;
#ifdef HAVE_CCTAG
if(imageDescriberType == "CCTAG3") return EImageDescriberType::CCTAG3;
if(imageDescriberType == "CCTAG4") return EImageDescriberType::CCTAG4;
#endif //HAVE_CCTAG
#ifdef HAVE_OPENCV
#ifdef USE_OCVSIFT
if(imageDescriberType == "SIFT_OCV") return EImageDescriberType::SIFT_OCV;
#endif
if(imageDescriberType == "AKAZE_OCV") return EImageDescriberType::AKAZE_OCV;
#endif//HAVE_OPENCV
if(imageDescriberType == "UNKNOWN") return EImageDescriberType::UNKNOWN;
// UNINITIALIZED should throw an error.
throw std::out_of_range("Invalid imageDescriber : " + imageDescriberType);
}
std::vector<EImageDescriberType> EImageDescriberType_stringToEnums(const std::string& describerMethods)
{
std::vector<EImageDescriberType> out;
std::vector<std::string> describerMethodsVec;
stl::split(describerMethods, ",", describerMethodsVec);
for(const auto& describerMethod: describerMethodsVec)
{
out.push_back(EImageDescriberType_stringToEnum(describerMethod));
}
return out;
}
} // namespace features
} // namespace openMVG
<commit_msg>[features] fix : Conversion AKAZE string to enum<commit_after>#include "ImageDescriberCommon.hpp"
#include "openMVG/types.hpp"
#include "openMVG/stl/split.hpp"
#include <exception>
#include <cassert>
namespace openMVG {
namespace features {
std::string EImageDescriberType_enumToString(EImageDescriberType imageDescriberType)
{
switch(imageDescriberType)
{
case EImageDescriberType::SIFT: return "SIFT";
case EImageDescriberType::SIFT_FLOAT: return "SIFT_FLOAT";
case EImageDescriberType::AKAZE: return "AKAZE";
case EImageDescriberType::AKAZE_LIOP: return "AKAZE_LIOP";
case EImageDescriberType::AKAZE_MLDB: return "AKAZE_MLDB";
#ifdef HAVE_CCTAG
case EImageDescriberType::CCTAG3: return "CCTAG3";
case EImageDescriberType::CCTAG4: return "CCTAG4";
#endif //HAVE_CCTAG
#ifdef HAVE_OPENCV
#ifdef USE_OCVSIFT
case EImageDescriberType::SIFT_OCV: return "SIFT_OCV";
#endif
case EImageDescriberType::AKAZE_OCV: return "AKAZE_OCV";
#endif//HAVE_OPENCV
case EImageDescriberType::UNKNOWN: return "UNKNOWN";
case EImageDescriberType::UNINITIALIZED: break; // Should throw an error.
}
throw std::out_of_range("Invalid imageDescriber enum");
}
EImageDescriberType EImageDescriberType_stringToEnum(const std::string& imageDescriberType)
{
if(imageDescriberType == "SIFT") return EImageDescriberType::SIFT;
if(imageDescriberType == "SIFT_FLOAT") return EImageDescriberType::SIFT_FLOAT;
if(imageDescriberType == "AKAZE") return EImageDescriberType::AKAZE;
if(imageDescriberType == "AKAZE_LIOP") return EImageDescriberType::AKAZE_LIOP;
if(imageDescriberType == "AKAZE_MLDB") return EImageDescriberType::AKAZE_MLDB;
#ifdef HAVE_CCTAG
if(imageDescriberType == "CCTAG3") return EImageDescriberType::CCTAG3;
if(imageDescriberType == "CCTAG4") return EImageDescriberType::CCTAG4;
#endif //HAVE_CCTAG
#ifdef HAVE_OPENCV
#ifdef USE_OCVSIFT
if(imageDescriberType == "SIFT_OCV") return EImageDescriberType::SIFT_OCV;
#endif
if(imageDescriberType == "AKAZE_OCV") return EImageDescriberType::AKAZE_OCV;
#endif//HAVE_OPENCV
if(imageDescriberType == "UNKNOWN") return EImageDescriberType::UNKNOWN;
// UNINITIALIZED should throw an error.
throw std::out_of_range("Invalid imageDescriber : " + imageDescriberType);
}
std::vector<EImageDescriberType> EImageDescriberType_stringToEnums(const std::string& describerMethods)
{
std::vector<EImageDescriberType> out;
std::vector<std::string> describerMethodsVec;
stl::split(describerMethods, ",", describerMethodsVec);
for(const auto& describerMethod: describerMethodsVec)
{
out.push_back(EImageDescriberType_stringToEnum(describerMethod));
}
return out;
}
} // namespace features
} // namespace openMVG
<|endoftext|> |
<commit_before>/** @file
@brief Header
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include <osvr/Common/NormalizeDeviceDescriptor.h>
// Library/third-party includes
// - none
// Standard includes
#include <json/value.h>
#include <json/reader.h>
#include <boost/noncopyable.hpp>
#include <boost/variant/get.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/erase.hpp>
#include <boost/algorithm/string.hpp>
#include <iostream>
namespace osvr {
namespace common {
static const char INTERFACES_KEY[] = "interfaces";
static const char EYETRACKER_KEY[] = "eyetracker";
static const char LOCATION2D_KEY[] = "location2D";
static const char DIRECTION_KEY[] = "direction";
static const char TRACKER_KEY[] = "tracker";
static const char BUTTON_KEY[] = "button";
static const char COUNT_KEY[] = "count";
static const char POSITION_KEY[] = "position";
static const char ORIENTATION_KEY[] = "orientation";
static const char BOUNDED_KEY[] = "bounded";
/// @todo when appending interfaces you might encounter that there are
/// independent interfaces that are same as subinterfaces
/// for example, eyetracker device and tracker device plugin
/// eyetracker breaks down into 4 interfaces including tracker
/// so to avoid replacing tracker data, we need to safely merge them
void mergeIdenticalInterfaces(Json::Value &existingIface,
Json::Value &newIface,
std::string const &detail) {}
/// @brief appends json value for a given string
void appendCurrentIface(Json::Value &augInterface,
Json::Value &currInterface) {
for (auto &detail : currInterface.getMemberNames()) {
Json::Value const &obj = augInterface[detail];
if (obj.isObject()) {
/// @todo mergeIdenticalInterfaces(currInterface, augInterface,
/// detail)
} else {
augInterface[detail] = currInterface[detail];
}
}
}
/// @brief For eyetracker, it will add the following interfaces to the
/// descriptor provided that they are set to true:
/// OSVR_Direction, OSVR_Location2D, OSVR_Tracker, OSVR_Button
void normalizeForEyeTracker(Json::Value &descriptor,
std::string const &ifaceName) {
// step into the interfaces object
Json::Value const &iface = descriptor[INTERFACES_KEY][ifaceName];
// hold the count for eyetracker sensors to initialize
int count = descriptor[INTERFACES_KEY][ifaceName][COUNT_KEY].asInt();
// if we couldn't find count then return
if (!count) {
return;
}
Json::Value augInterfaces(Json::objectValue);
// go thru details of interface and
for (auto &subIface : iface.getMemberNames()) {
// check if subinterface is set to true
bool enabled =
descriptor[INTERFACES_KEY][ifaceName][subIface].asBool();
if (enabled) {
if (boost::iequals(subIface, LOCATION2D_KEY)) {
augInterfaces[LOCATION2D_KEY][COUNT_KEY] = count;
} else if (boost::iequals(subIface, DIRECTION_KEY)) {
augInterfaces[DIRECTION_KEY][COUNT_KEY] = count;
} else if (boost::iequals(subIface, TRACKER_KEY)) {
augInterfaces[TRACKER_KEY][POSITION_KEY] = true;
augInterfaces[TRACKER_KEY][ORIENTATION_KEY] = false;
augInterfaces[TRACKER_KEY][BOUNDED_KEY] = true;
augInterfaces[TRACKER_KEY][COUNT_KEY] = count;
} else if (boost::iequals(subIface, BUTTON_KEY)) {
augInterfaces[BUTTON_KEY][COUNT_KEY] = count;
} else {
continue;
}
}
}
if (augInterfaces.size() > 0) {
Json::Value &currInterfaces = descriptor[INTERFACES_KEY];
appendCurrentIface(augInterfaces, currInterfaces);
descriptor[INTERFACES_KEY] = augInterfaces;
}
}
/// @todo process for tracker interface
std::string normalizeDeviceDescriptor(std::string const &jsonDescriptor) {
Json::Value descriptor;
{
Json::Reader reader;
if (!reader.parse(jsonDescriptor, descriptor)) {
/// if can't parse as json then leave unchanged, err will be
/// handler later
return jsonDescriptor;
}
}
/// no interfaces member so don't chanage anything
if (!descriptor.isMember(INTERFACES_KEY)) {
return jsonDescriptor;
}
Json::Value const &ifaceNames = descriptor[INTERFACES_KEY];
// interfaces member isn't an object
if (!ifaceNames.isObject()) {
return jsonDescriptor;
}
for (auto const &ifaceName : ifaceNames.getMemberNames()) {
if (boost::iequals(ifaceName, EYETRACKER_KEY)) {
normalizeForEyeTracker(descriptor, ifaceName);
} else if (boost::iequals(ifaceName, TRACKER_KEY)) {
/// @todo for tracker
} else {
/// @todo for future interfaces
}
}
const std::string normalizedDescriptor = descriptor.toStyledString();
return normalizedDescriptor;
}
} // namespace common
} // namespace osvr<commit_msg>Workaround for Boost 1.58.0<commit_after>/** @file
@brief Header
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include <boost/type_traits/remove_cv.hpp>
#include <osvr/Common/NormalizeDeviceDescriptor.h>
// Library/third-party includes
// - none
// Standard includes
#include <json/value.h>
#include <json/reader.h>
#include <boost/noncopyable.hpp>
#include <boost/variant/get.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/erase.hpp>
#include <boost/algorithm/string.hpp>
#include <iostream>
namespace osvr {
namespace common {
static const char INTERFACES_KEY[] = "interfaces";
static const char EYETRACKER_KEY[] = "eyetracker";
static const char LOCATION2D_KEY[] = "location2D";
static const char DIRECTION_KEY[] = "direction";
static const char TRACKER_KEY[] = "tracker";
static const char BUTTON_KEY[] = "button";
static const char COUNT_KEY[] = "count";
static const char POSITION_KEY[] = "position";
static const char ORIENTATION_KEY[] = "orientation";
static const char BOUNDED_KEY[] = "bounded";
/// @todo when appending interfaces you might encounter that there are
/// independent interfaces that are same as subinterfaces
/// for example, eyetracker device and tracker device plugin
/// eyetracker breaks down into 4 interfaces including tracker
/// so to avoid replacing tracker data, we need to safely merge them
void mergeIdenticalInterfaces(Json::Value &existingIface,
Json::Value &newIface,
std::string const &detail) {}
/// @brief appends json value for a given string
void appendCurrentIface(Json::Value &augInterface,
Json::Value &currInterface) {
for (auto &detail : currInterface.getMemberNames()) {
Json::Value const &obj = augInterface[detail];
if (obj.isObject()) {
/// @todo mergeIdenticalInterfaces(currInterface, augInterface,
/// detail)
} else {
augInterface[detail] = currInterface[detail];
}
}
}
/// @brief For eyetracker, it will add the following interfaces to the
/// descriptor provided that they are set to true:
/// OSVR_Direction, OSVR_Location2D, OSVR_Tracker, OSVR_Button
void normalizeForEyeTracker(Json::Value &descriptor,
std::string const &ifaceName) {
// step into the interfaces object
Json::Value const &iface = descriptor[INTERFACES_KEY][ifaceName];
// hold the count for eyetracker sensors to initialize
int count = descriptor[INTERFACES_KEY][ifaceName][COUNT_KEY].asInt();
// if we couldn't find count then return
if (!count) {
return;
}
Json::Value augInterfaces(Json::objectValue);
// go thru details of interface and
for (auto &subIface : iface.getMemberNames()) {
// check if subinterface is set to true
bool enabled =
descriptor[INTERFACES_KEY][ifaceName][subIface].asBool();
if (enabled) {
if (boost::iequals(subIface, LOCATION2D_KEY)) {
augInterfaces[LOCATION2D_KEY][COUNT_KEY] = count;
} else if (boost::iequals(subIface, DIRECTION_KEY)) {
augInterfaces[DIRECTION_KEY][COUNT_KEY] = count;
} else if (boost::iequals(subIface, TRACKER_KEY)) {
augInterfaces[TRACKER_KEY][POSITION_KEY] = true;
augInterfaces[TRACKER_KEY][ORIENTATION_KEY] = false;
augInterfaces[TRACKER_KEY][BOUNDED_KEY] = true;
augInterfaces[TRACKER_KEY][COUNT_KEY] = count;
} else if (boost::iequals(subIface, BUTTON_KEY)) {
augInterfaces[BUTTON_KEY][COUNT_KEY] = count;
} else {
continue;
}
}
}
if (augInterfaces.size() > 0) {
Json::Value &currInterfaces = descriptor[INTERFACES_KEY];
appendCurrentIface(augInterfaces, currInterfaces);
descriptor[INTERFACES_KEY] = augInterfaces;
}
}
/// @todo process for tracker interface
std::string normalizeDeviceDescriptor(std::string const &jsonDescriptor) {
Json::Value descriptor;
{
Json::Reader reader;
if (!reader.parse(jsonDescriptor, descriptor)) {
/// if can't parse as json then leave unchanged, err will be
/// handler later
return jsonDescriptor;
}
}
/// no interfaces member so don't chanage anything
if (!descriptor.isMember(INTERFACES_KEY)) {
return jsonDescriptor;
}
Json::Value const &ifaceNames = descriptor[INTERFACES_KEY];
// interfaces member isn't an object
if (!ifaceNames.isObject()) {
return jsonDescriptor;
}
for (auto const &ifaceName : ifaceNames.getMemberNames()) {
if (boost::iequals(ifaceName, EYETRACKER_KEY)) {
normalizeForEyeTracker(descriptor, ifaceName);
} else if (boost::iequals(ifaceName, TRACKER_KEY)) {
/// @todo for tracker
} else {
/// @todo for future interfaces
}
}
const std::string normalizedDescriptor = descriptor.toStyledString();
return normalizedDescriptor;
}
} // namespace common
} // namespace osvr
<|endoftext|> |
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2011 Dennis Nienhüser <earthwings@gentoo.org>
//
#include "RouteRequestModel.h"
#include "routing/RoutingManager.h"
#include "routing/RouteRequest.h"
#include "MarbleDeclarativeWidget.h"
#include "MarbleModel.h"
#include "Routing.h"
RouteRequestModel::RouteRequestModel( QObject *parent ) :
QAbstractListModel( parent ),
m_routing( 0 ),
m_request( 0 )
{
QHash<int,QByteArray> roles = roleNames();
roles[LongitudeRole] = "longitude";
roles[LatitudeRole] = "latitude";
setRoleNames( roles );
}
RouteRequestModel::~RouteRequestModel()
{
// nothing to do
}
int RouteRequestModel::rowCount ( const QModelIndex &parent ) const
{
if ( !parent.isValid() && m_request ) {
return m_request->size();
}
return 0;
}
QVariant RouteRequestModel::headerData ( int section, Qt::Orientation orientation, int role ) const
{
if ( orientation == Qt::Horizontal && role == Qt::DisplayRole && section == 0 ) {
return QString( "Waypoint" );
}
return QVariant();
}
QVariant RouteRequestModel::data ( const QModelIndex &index, int role ) const
{
if ( index.isValid() && m_request && index.row() >= 0 && index.row() < m_request->size() ) {
switch ( role ) {
case Qt::DisplayRole: return m_request->name( index.row() );
case LongitudeRole: return m_request->at( index.row() ).longitude( Marble::GeoDataCoordinates::Degree );
case LatitudeRole: return m_request->at( index.row() ).latitude( Marble::GeoDataCoordinates::Degree );
}
}
return QVariant();
}
Routing *RouteRequestModel::routing()
{
return m_routing;
}
void RouteRequestModel::setRouting( Routing *routing )
{
if ( routing != m_routing ) {
m_routing = routing;
updateMap();
connect( m_routing, SIGNAL(mapChanged()), this, SLOT(updateMap()) );
emit routingChanged();
}
}
void RouteRequestModel::updateMap()
{
if ( m_routing && m_routing->map() ) {
m_request = m_routing->map()->model()->routingManager()->routeRequest();
connect( m_request, SIGNAL(positionChanged(int,GeoDataCoordinates)),
this, SLOT(updateData(int)) );
connect( m_request, SIGNAL(positionAdded(int)),
this, SLOT(updateAfterAddition(int)) );
connect( m_request, SIGNAL(positionRemoved(int)),
this, SLOT(updateAfterRemoval(int)) );
emit layoutChanged();
}
}
void RouteRequestModel::updateData( int idx )
{
QModelIndex affected = index( idx );
emit dataChanged( affected, affected );
}
void RouteRequestModel::updateAfterRemoval( int idx )
{
beginRemoveRows( QModelIndex(), idx, idx );
removeRow( idx );
endRemoveRows();
}
void RouteRequestModel::updateAfterAddition( int idx )
{
beginInsertRows( QModelIndex(), idx, idx );
insertRow( idx );
endInsertRows();
}
void RouteRequestModel::setPosition ( int index, qreal longitude, qreal latitude )
{
if ( index >= 0 && index < m_request->size() ) {
m_request->setPosition( index, Marble::GeoDataCoordinates( longitude, latitude, 0.0, Marble::GeoDataCoordinates::Degree ) );
}
}
#include "RouteRequestModel.moc"
<commit_msg>fix initialization order<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2011 Dennis Nienhüser <earthwings@gentoo.org>
//
#include "RouteRequestModel.h"
#include "routing/RoutingManager.h"
#include "routing/RouteRequest.h"
#include "MarbleDeclarativeWidget.h"
#include "MarbleModel.h"
#include "Routing.h"
RouteRequestModel::RouteRequestModel( QObject *parent ) :
QAbstractListModel( parent ),
m_request( 0 ),
m_routing( 0 )
{
QHash<int,QByteArray> roles = roleNames();
roles[LongitudeRole] = "longitude";
roles[LatitudeRole] = "latitude";
setRoleNames( roles );
}
RouteRequestModel::~RouteRequestModel()
{
// nothing to do
}
int RouteRequestModel::rowCount ( const QModelIndex &parent ) const
{
if ( !parent.isValid() && m_request ) {
return m_request->size();
}
return 0;
}
QVariant RouteRequestModel::headerData ( int section, Qt::Orientation orientation, int role ) const
{
if ( orientation == Qt::Horizontal && role == Qt::DisplayRole && section == 0 ) {
return QString( "Waypoint" );
}
return QVariant();
}
QVariant RouteRequestModel::data ( const QModelIndex &index, int role ) const
{
if ( index.isValid() && m_request && index.row() >= 0 && index.row() < m_request->size() ) {
switch ( role ) {
case Qt::DisplayRole: return m_request->name( index.row() );
case LongitudeRole: return m_request->at( index.row() ).longitude( Marble::GeoDataCoordinates::Degree );
case LatitudeRole: return m_request->at( index.row() ).latitude( Marble::GeoDataCoordinates::Degree );
}
}
return QVariant();
}
Routing *RouteRequestModel::routing()
{
return m_routing;
}
void RouteRequestModel::setRouting( Routing *routing )
{
if ( routing != m_routing ) {
m_routing = routing;
updateMap();
connect( m_routing, SIGNAL(mapChanged()), this, SLOT(updateMap()) );
emit routingChanged();
}
}
void RouteRequestModel::updateMap()
{
if ( m_routing && m_routing->map() ) {
m_request = m_routing->map()->model()->routingManager()->routeRequest();
connect( m_request, SIGNAL(positionChanged(int,GeoDataCoordinates)),
this, SLOT(updateData(int)) );
connect( m_request, SIGNAL(positionAdded(int)),
this, SLOT(updateAfterAddition(int)) );
connect( m_request, SIGNAL(positionRemoved(int)),
this, SLOT(updateAfterRemoval(int)) );
emit layoutChanged();
}
}
void RouteRequestModel::updateData( int idx )
{
QModelIndex affected = index( idx );
emit dataChanged( affected, affected );
}
void RouteRequestModel::updateAfterRemoval( int idx )
{
beginRemoveRows( QModelIndex(), idx, idx );
removeRow( idx );
endRemoveRows();
}
void RouteRequestModel::updateAfterAddition( int idx )
{
beginInsertRows( QModelIndex(), idx, idx );
insertRow( idx );
endInsertRows();
}
void RouteRequestModel::setPosition ( int index, qreal longitude, qreal latitude )
{
if ( index >= 0 && index < m_request->size() ) {
m_request->setPosition( index, Marble::GeoDataCoordinates( longitude, latitude, 0.0, Marble::GeoDataCoordinates::Degree ) );
}
}
#include "RouteRequestModel.moc"
<|endoftext|> |
<commit_before>
/*
Methods
*/
// Get parameter
#define GET_PARAM(outVar, paramName, paramDefault) outVar = [paramName,paramDefault] call F_getSaveableParam;\
publicVariable #outVar
// Get parameter and convert to bool
#define GET_PARAM_BOOL(outVar, paramName, paramDefault) outVar = [paramName,paramDefault] call F_getSaveableParam;\
if (outVar == 1) then {outVar = true} else {outVar = false};\
publicVariable #outVar
<commit_msg>Small format tweak<commit_after>
/*
Methods
*/
// Get parameter
#define GET_PARAM(outVar, paramName, paramDefault) outVar = [paramName,paramDefault] call F_getSaveableParam;\
publicVariable #outVar
// Get parameter and convert to bool
#define GET_PARAM_BOOL(outVar, paramName, paramDefault) outVar = [paramName,paramDefault] call F_getSaveableParam;\
if (outVar == 1) then {outVar = true} else {outVar = false};\
publicVariable #outVar
<|endoftext|> |
<commit_before>/*
Copyright (C) 2012 by Ivan Safrin
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 "PolyUIButton.h"
#include "PolyConfig.h"
#include "PolyInputEvent.h"
#include "PolyLabel.h"
#include "PolyCoreServices.h"
#include "PolyCore.h"
using namespace Polycode;
UIButton::UIButton(String text, Number width, Number height) : UIElement() {
Config *conf = CoreServices::getInstance()->getConfig();
String fontName = conf->getStringValue("Polycode", "uiDefaultFontName");
int fontSize = conf->getNumericValue("Polycode", "uiButtonFontSize");
Number st = conf->getNumericValue("Polycode", "uiButtonSkinT");
Number sr = conf->getNumericValue("Polycode", "uiButtonSkinR");
Number sb = conf->getNumericValue("Polycode", "uiButtonSkinB");
Number sl = conf->getNumericValue("Polycode", "uiButtonSkinL");
labelOffsetX = conf->getNumericValue("Polycode", "uiButtonLabelOffsetX");
labelOffsetY = conf->getNumericValue("Polycode", "uiButtonLabelOffsetY");
buttonRect = new UIBox(conf->getStringValue("Polycode", "uiButtonSkin"),
st,sr,sb,sl,
width, height);
buttonRect->blockMouseInput = true;
buttonFocusedRect= new UIBox(conf->getStringValue("Polycode", "uiButtonFocusedSkin"),
st,sr,sb,sl,
width, height);
blockMouseInput = true;
addChild(buttonRect);
addChild(buttonFocusedRect);
buttonFocusedRect->visible = false;
buttonRect->addEventListener(this, InputEvent::EVENT_MOUSEOVER);
buttonRect->addEventListener(this, InputEvent::EVENT_MOUSEOUT);
buttonRect->addEventListener(this, InputEvent::EVENT_MOUSEUP);
buttonRect->addEventListener(this, InputEvent::EVENT_MOUSEUP_OUTSIDE);
buttonRect->addEventListener(this, InputEvent::EVENT_MOUSEDOWN);
coreInput = CoreServices::getInstance()->getCore()->getInput();
coreInput->addEventListener(this, InputEvent::EVENT_KEYDOWN);
pressedDown = false;
buttonLabel = new SceneLabel(text, fontSize, fontName, Label::ANTIALIAS_FULL);
buttonLabel->color.setColorHexFromString(conf->getStringValue("Polycode", "uiButtonFontColor"));
addChild(buttonLabel);
labelXPos = floor((width-buttonLabel->getWidth())/2.0f) + labelOffsetX;
labelYPos = labelOffsetY;
buttonLabel->setPosition(labelXPos,labelYPos);
buttonLabel->positionAtBaseline = true;
buttonLabel->setAnchorPoint(-1.0, -1.0, 0.0);
setWidth(width);
setHeight(height);
focusable = true;
buttonRect->processInputEvents = true;
}
void UIButton::Resize(Number width, Number height) {
buttonRect->resizeBox(width, height);
buttonFocusedRect->resizeBox(width, height);
setWidth(width);
setHeight(height);
matrixDirty = true;
labelXPos = floor((width-buttonLabel->getWidth())/2.0f) + labelOffsetX;
labelYPos = floor(height/2.0) + labelOffsetY;
buttonLabel->setPosition(labelXPos,labelYPos);
UIElement::Resize(width, height);
}
void UIButton::Update() {
if(hasFocus) {
buttonFocusedRect->visible = true;
buttonRect->visible = false;
} else {
buttonFocusedRect->visible = false;
buttonRect->visible = true;
}
}
UIButton::~UIButton() {
coreInput->removeAllHandlersForListener(this);
if(!ownsChildren) {
delete buttonRect;
delete buttonFocusedRect;
delete buttonLabel;
}
}
void UIButton::handleEvent(Event *event) {
if(event->getDispatcher() == coreInput) {
switch(event->getEventCode()) {
case InputEvent::EVENT_KEYDOWN:
if(hasFocus) {
if(((InputEvent*)event)->key == KEY_RETURN || ((InputEvent*)event)->key == KEY_SPACE) {
dispatchEvent(new UIEvent(), UIEvent::CLICK_EVENT);
}
}
break;
}
}
if(event->getDispatcher() == buttonRect) {
switch(event->getEventCode()) {
case InputEvent::EVENT_MOUSEOVER:
break;
case InputEvent::EVENT_MOUSEOUT:
buttonLabel->setPosition(labelXPos,labelYPos);
buttonRect->setPosition(0,0);
pressedDown = false;
break;
case InputEvent::EVENT_MOUSEUP_OUTSIDE:
buttonLabel->setPosition(labelXPos,labelYPos);
buttonRect->setPosition(0,0);
break;
case InputEvent::EVENT_MOUSEUP:
buttonLabel->setPosition(labelXPos,labelYPos);
buttonRect->setPosition(0,0);
if(pressedDown) {
dispatchEvent(new UIEvent(), UIEvent::CLICK_EVENT);
}
pressedDown = false;
break;
case InputEvent::EVENT_MOUSEDOWN:
pressedDown = true;
if(focusParent)
focusParent->focusChild(this);
buttonLabel->setPosition(labelXPos+1,labelYPos+1);
buttonRect->setPosition(1,1);
break;
}
}
}<commit_msg>Fixed UIButton resize<commit_after>/*
Copyright (C) 2012 by Ivan Safrin
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 "PolyUIButton.h"
#include "PolyConfig.h"
#include "PolyInputEvent.h"
#include "PolyLabel.h"
#include "PolyCoreServices.h"
#include "PolyCore.h"
using namespace Polycode;
UIButton::UIButton(String text, Number width, Number height) : UIElement() {
Config *conf = CoreServices::getInstance()->getConfig();
String fontName = conf->getStringValue("Polycode", "uiDefaultFontName");
int fontSize = conf->getNumericValue("Polycode", "uiButtonFontSize");
Number st = conf->getNumericValue("Polycode", "uiButtonSkinT");
Number sr = conf->getNumericValue("Polycode", "uiButtonSkinR");
Number sb = conf->getNumericValue("Polycode", "uiButtonSkinB");
Number sl = conf->getNumericValue("Polycode", "uiButtonSkinL");
labelOffsetX = conf->getNumericValue("Polycode", "uiButtonLabelOffsetX");
labelOffsetY = conf->getNumericValue("Polycode", "uiButtonLabelOffsetY");
buttonRect = new UIBox(conf->getStringValue("Polycode", "uiButtonSkin"),
st,sr,sb,sl,
width, height);
buttonRect->blockMouseInput = true;
buttonFocusedRect= new UIBox(conf->getStringValue("Polycode", "uiButtonFocusedSkin"),
st,sr,sb,sl,
width, height);
blockMouseInput = true;
addChild(buttonRect);
addChild(buttonFocusedRect);
buttonFocusedRect->visible = false;
buttonRect->addEventListener(this, InputEvent::EVENT_MOUSEOVER);
buttonRect->addEventListener(this, InputEvent::EVENT_MOUSEOUT);
buttonRect->addEventListener(this, InputEvent::EVENT_MOUSEUP);
buttonRect->addEventListener(this, InputEvent::EVENT_MOUSEUP_OUTSIDE);
buttonRect->addEventListener(this, InputEvent::EVENT_MOUSEDOWN);
coreInput = CoreServices::getInstance()->getCore()->getInput();
coreInput->addEventListener(this, InputEvent::EVENT_KEYDOWN);
pressedDown = false;
buttonLabel = new SceneLabel(text, fontSize, fontName, Label::ANTIALIAS_FULL);
buttonLabel->color.setColorHexFromString(conf->getStringValue("Polycode", "uiButtonFontColor"));
addChild(buttonLabel);
labelXPos = floor((width-buttonLabel->getWidth())/2.0f) + labelOffsetX;
labelYPos = labelOffsetY;
buttonLabel->setPosition(labelXPos,labelYPos);
buttonLabel->positionAtBaseline = true;
buttonLabel->setAnchorPoint(-1.0, -1.0, 0.0);
setWidth(width);
setHeight(height);
focusable = true;
buttonRect->processInputEvents = true;
}
void UIButton::Resize(Number width, Number height) {
buttonRect->resizeBox(width, height);
buttonFocusedRect->resizeBox(width, height);
setWidth(width);
setHeight(height);
matrixDirty = true;
labelXPos = floor((width-buttonLabel->getWidth())/2.0f) + labelOffsetX;
buttonLabel->setPosition(labelXPos,labelYPos);
UIElement::Resize(width, height);
}
void UIButton::Update() {
if(hasFocus) {
buttonFocusedRect->visible = true;
buttonRect->visible = false;
} else {
buttonFocusedRect->visible = false;
buttonRect->visible = true;
}
}
UIButton::~UIButton() {
coreInput->removeAllHandlersForListener(this);
if(!ownsChildren) {
delete buttonRect;
delete buttonFocusedRect;
delete buttonLabel;
}
}
void UIButton::handleEvent(Event *event) {
if(event->getDispatcher() == coreInput) {
switch(event->getEventCode()) {
case InputEvent::EVENT_KEYDOWN:
if(hasFocus) {
if(((InputEvent*)event)->key == KEY_RETURN || ((InputEvent*)event)->key == KEY_SPACE) {
dispatchEvent(new UIEvent(), UIEvent::CLICK_EVENT);
}
}
break;
}
}
if(event->getDispatcher() == buttonRect) {
switch(event->getEventCode()) {
case InputEvent::EVENT_MOUSEOVER:
break;
case InputEvent::EVENT_MOUSEOUT:
buttonLabel->setPosition(labelXPos,labelYPos);
buttonRect->setPosition(0,0);
pressedDown = false;
break;
case InputEvent::EVENT_MOUSEUP_OUTSIDE:
buttonLabel->setPosition(labelXPos,labelYPos);
buttonRect->setPosition(0,0);
break;
case InputEvent::EVENT_MOUSEUP:
buttonLabel->setPosition(labelXPos,labelYPos);
buttonRect->setPosition(0,0);
if(pressedDown) {
dispatchEvent(new UIEvent(), UIEvent::CLICK_EVENT);
}
pressedDown = false;
break;
case InputEvent::EVENT_MOUSEDOWN:
pressedDown = true;
if(focusParent)
focusParent->focusChild(this);
buttonLabel->setPosition(labelXPos+1,labelYPos+1);
buttonRect->setPosition(1,1);
break;
}
}
}<|endoftext|> |
<commit_before>/*===========================================================================*\
* *
* OpenMesh *
* Copyright (C) 2001-2010 by Computer Graphics Group, RWTH Aachen *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
* *
* OpenMesh 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 with the *
* following exceptions: *
* *
* If other files instantiate templates or use macros *
* or inline functions from this file, or you compile this file and *
* link it with other files to produce an executable, this file does *
* not by itself cause the resulting executable to be covered by the *
* GNU Lesser General Public License. This exception does not however *
* invalidate any other reasons why the executable file might be *
* covered by the GNU Lesser General Public License. *
* *
* OpenMesh 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 LesserGeneral Public *
* License along with OpenMesh. If not, *
* see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
/*===========================================================================*\
* *
* $Revision$ *
* $Date$ *
* *
\*===========================================================================*/
//=============================================================================
//
// CLASS VectorT
//
//=============================================================================
// Don't parse this header file with doxygen since
// for some reason (obviously due to a bug in doxygen,
// bugreport: https://bugzilla.gnome.org/show_bug.cgi?id=629182)
// macro expansion and preprocessor defines
// don't work properly.
#ifndef DOXYGEN
#ifndef OPENMESH_VECTOR_HH
#define OPENMESH_VECTOR_HH
//== INCLUDES =================================================================
#include <OpenMesh/Core/System/config.h>
#include <iostream>
#include <assert.h>
#include <math.h>
#include <string.h>
#if defined(__GNUC__) && defined(__SSE__)
#include <xmmintrin.h>
#endif
//== NAMESPACES ===============================================================
namespace OpenMesh {
//== CLASS DEFINITION =========================================================
/** The N values of the template Scalar type are the only data members
of the class VectorT<Scalar,N>. This guarantees 100% compatibility
with arrays of type Scalar and size N, allowing us to define the
cast operators to and from arrays and array pointers.
In addition, this class will be specialized for Vec4f to be 16 bit
aligned, so that aligned SSE instructions can be used on these
vectors.
*/
template <typename Scalar,int N> struct VectorDataT
{
Scalar values_[N];
};
#if defined(__GNUC__) && defined(__SSE__)
/// This specialization enables us to use aligned SSE instructions.
template <> struct VectorDataT<float, 4>
{
union
{
__m128 m128;
float values_[4];
};
};
#endif
//== CLASS DEFINITION =========================================================
#define DIM N
#define TEMPLATE_HEADER template <typename Scalar, int N>
#define CLASSNAME VectorT
#define DERIVED VectorDataT<Scalar,N>
#define unroll(expr) for (int i=0; i<N; ++i) expr(i)
/** \class VectorT VectorT.hh <OpenMesh/Core/Math/VectorT.hh>
A vector is an array of \<N\> values of type \<Scalar\>.
The actual data is stored in an VectorDataT, this class just adds
the necessary operators.
*/
#include "VectorT_inc.hh"
#undef DIM
#undef TEMPLATE_HEADER
#undef CLASSNAME
#undef DERIVED
#undef unroll
//== PARTIAL TEMPLATE SPECIALIZATIONS =========================================
#if OM_PARTIAL_SPECIALIZATION
#define TEMPLATE_HEADER template <typename Scalar>
#define CLASSNAME VectorT<Scalar,DIM>
#define DERIVED VectorDataT<Scalar,DIM>
#define DIM 2
#define unroll(expr) expr(0) expr(1)
#define unroll_comb(expr, op) expr(0) op expr(1)
#define unroll_csv(expr) expr(0), expr(1)
#include "VectorT_inc.hh"
#undef DIM
#undef unroll
#undef unroll_comb
#undef unroll_csv
#define DIM 3
#define unroll(expr) expr(0) expr(1) expr(2)
#define unroll_comb(expr, op) expr(0) op expr(1) op expr(2)
#define unroll_csv(expr) expr(0), expr(1), expr(2)
#include "VectorT_inc.hh"
#undef DIM
#undef unroll
#undef unroll_comb
#undef unroll_csv
#define DIM 4
#define unroll(expr) expr(0) expr(1) expr(2) expr(3)
#define unroll_comb(expr, op) expr(0) op expr(1) op expr(2) op expr(3)
#define unroll_csv(expr) expr(0), expr(1), expr(2), expr(3)
#include "VectorT_inc.hh"
#undef DIM
#undef unroll
#undef unroll_comb
#undef unroll_csv
#undef TEMPLATE_HEADER
#undef CLASSNAME
#undef DERIVED
//== FULL TEMPLATE SPECIALIZATIONS ============================================
#else
/// cross product for Vec3f
template<>
inline VectorT<float,3>
VectorT<float,3>::operator%(const VectorT<float,3>& _rhs) const
{
return
VectorT<float,3>(values_[1]*_rhs.values_[2]-values_[2]*_rhs.values_[1],
values_[2]*_rhs.values_[0]-values_[0]*_rhs.values_[2],
values_[0]*_rhs.values_[1]-values_[1]*_rhs.values_[0]);
}
/// cross product for Vec3d
template<>
inline VectorT<double,3>
VectorT<double,3>::operator%(const VectorT<double,3>& _rhs) const
{
return
VectorT<double,3>(values_[1]*_rhs.values_[2]-values_[2]*_rhs.values_[1],
values_[2]*_rhs.values_[0]-values_[0]*_rhs.values_[2],
values_[0]*_rhs.values_[1]-values_[1]*_rhs.values_[0]);
}
#endif
//== GLOBAL FUNCTIONS =========================================================
/// \relates OpenMesh::VectorT
/// scalar * vector
template<typename Scalar,int N>
inline VectorT<Scalar,N> operator*(Scalar _s, const VectorT<Scalar,N>& _v) {
return VectorT<Scalar,N>(_v) *= _s;
}
/// \relates OpenMesh::VectorT
/// symmetric version of the dot product
template<typename Scalar, int N>
inline Scalar
dot(const VectorT<Scalar,N>& _v1, const VectorT<Scalar,N>& _v2) {
return (_v1 | _v2);
}
/// \relates OpenMesh::VectorT
/// symmetric version of the cross product
template<typename Scalar, int N>
inline VectorT<Scalar,N>
cross(const VectorT<Scalar,N>& _v1, const VectorT<Scalar,N>& _v2) {
return (_v1 % _v2);
}
//== TYPEDEFS =================================================================
/** 1-byte signed vector */
typedef VectorT<signed char,1> Vec1c;
/** 1-byte unsigned vector */
typedef VectorT<unsigned char,1> Vec1uc;
/** 1-short signed vector */
typedef VectorT<signed short int,1> Vec1s;
/** 1-short unsigned vector */
typedef VectorT<unsigned short int,1> Vec1us;
/** 1-int signed vector */
typedef VectorT<signed int,1> Vec1i;
/** 1-int unsigned vector */
typedef VectorT<unsigned int,1> Vec1ui;
/** 1-float vector */
typedef VectorT<float,1> Vec1f;
/** 1-double vector */
typedef VectorT<double,1> Vec1d;
/** 2-byte signed vector */
typedef VectorT<signed char,2> Vec2c;
/** 2-byte unsigned vector */
typedef VectorT<unsigned char,2> Vec2uc;
/** 2-short signed vector */
typedef VectorT<signed short int,2> Vec2s;
/** 2-short unsigned vector */
typedef VectorT<unsigned short int,2> Vec2us;
/** 2-int signed vector */
typedef VectorT<signed int,2> Vec2i;
/** 2-int unsigned vector */
typedef VectorT<unsigned int,2> Vec2ui;
/** 2-float vector */
typedef VectorT<float,2> Vec2f;
/** 2-double vector */
typedef VectorT<double,2> Vec2d;
/** 3-byte signed vector */
typedef VectorT<signed char,3> Vec3c;
/** 3-byte unsigned vector */
typedef VectorT<unsigned char,3> Vec3uc;
/** 3-short signed vector */
typedef VectorT<signed short int,3> Vec3s;
/** 3-short unsigned vector */
typedef VectorT<unsigned short int,3> Vec3us;
/** 3-int signed vector */
typedef VectorT<signed int,3> Vec3i;
/** 3-int unsigned vector */
typedef VectorT<unsigned int,3> Vec3ui;
/** 3-float vector */
typedef VectorT<float,3> Vec3f;
/** 3-double vector */
typedef VectorT<double,3> Vec3d;
/** 4-byte signed vector */
typedef VectorT<signed char,4> Vec4c;
/** 4-byte unsigned vector */
typedef VectorT<unsigned char,4> Vec4uc;
/** 4-short signed vector */
typedef VectorT<signed short int,4> Vec4s;
/** 4-short unsigned vector */
typedef VectorT<unsigned short int,4> Vec4us;
/** 4-int signed vector */
typedef VectorT<signed int,4> Vec4i;
/** 4-int unsigned vector */
typedef VectorT<unsigned int,4> Vec4ui;
/** 4-float vector */
typedef VectorT<float,4> Vec4f;
/** 4-double vector */
typedef VectorT<double,4> Vec4d;
/** 6-byte signed vector */
typedef VectorT<signed char,6> Vec6c;
/** 6-byte unsigned vector */
typedef VectorT<unsigned char,6> Vec6uc;
/** 6-short signed vector */
typedef VectorT<signed short int,6> Vec6s;
/** 6-short unsigned vector */
typedef VectorT<unsigned short int,6> Vec6us;
/** 6-int signed vector */
typedef VectorT<signed int,6> Vec6i;
/** 6-int unsigned vector */
typedef VectorT<unsigned int,6> Vec6ui;
/** 6-float vector */
typedef VectorT<float,6> Vec6f;
/** 6-double vector */
typedef VectorT<double,6> Vec6d;
//=============================================================================
} // namespace OpenMesh
//=============================================================================
#endif // OPENMESH_VECTOR_HH defined
//=============================================================================
#endif DOXYGEN
<commit_msg>Corrected some expression that caused a compiler warning.<commit_after>/*===========================================================================*\
* *
* OpenMesh *
* Copyright (C) 2001-2010 by Computer Graphics Group, RWTH Aachen *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
* *
* OpenMesh 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 with the *
* following exceptions: *
* *
* If other files instantiate templates or use macros *
* or inline functions from this file, or you compile this file and *
* link it with other files to produce an executable, this file does *
* not by itself cause the resulting executable to be covered by the *
* GNU Lesser General Public License. This exception does not however *
* invalidate any other reasons why the executable file might be *
* covered by the GNU Lesser General Public License. *
* *
* OpenMesh 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 LesserGeneral Public *
* License along with OpenMesh. If not, *
* see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
/*===========================================================================*\
* *
* $Revision$ *
* $Date$ *
* *
\*===========================================================================*/
//=============================================================================
//
// CLASS VectorT
//
//=============================================================================
// Don't parse this header file with doxygen since
// for some reason (obviously due to a bug in doxygen,
// bugreport: https://bugzilla.gnome.org/show_bug.cgi?id=629182)
// macro expansion and preprocessor defines
// don't work properly.
#ifndef DOXYGEN
#ifndef OPENMESH_VECTOR_HH
#define OPENMESH_VECTOR_HH
//== INCLUDES =================================================================
#include <OpenMesh/Core/System/config.h>
#include <iostream>
#include <assert.h>
#include <math.h>
#include <string.h>
#if defined(__GNUC__) && defined(__SSE__)
#include <xmmintrin.h>
#endif
//== NAMESPACES ===============================================================
namespace OpenMesh {
//== CLASS DEFINITION =========================================================
/** The N values of the template Scalar type are the only data members
of the class VectorT<Scalar,N>. This guarantees 100% compatibility
with arrays of type Scalar and size N, allowing us to define the
cast operators to and from arrays and array pointers.
In addition, this class will be specialized for Vec4f to be 16 bit
aligned, so that aligned SSE instructions can be used on these
vectors.
*/
template <typename Scalar,int N> struct VectorDataT
{
Scalar values_[N];
};
#if defined(__GNUC__) && defined(__SSE__)
/// This specialization enables us to use aligned SSE instructions.
template <> struct VectorDataT<float, 4>
{
union
{
__m128 m128;
float values_[4];
};
};
#endif
//== CLASS DEFINITION =========================================================
#define DIM N
#define TEMPLATE_HEADER template <typename Scalar, int N>
#define CLASSNAME VectorT
#define DERIVED VectorDataT<Scalar,N>
#define unroll(expr) for (int i=0; i<N; ++i) expr(i)
/** \class VectorT VectorT.hh <OpenMesh/Core/Math/VectorT.hh>
A vector is an array of \<N\> values of type \<Scalar\>.
The actual data is stored in an VectorDataT, this class just adds
the necessary operators.
*/
#include "VectorT_inc.hh"
#undef DIM
#undef TEMPLATE_HEADER
#undef CLASSNAME
#undef DERIVED
#undef unroll
//== PARTIAL TEMPLATE SPECIALIZATIONS =========================================
#if OM_PARTIAL_SPECIALIZATION
#define TEMPLATE_HEADER template <typename Scalar>
#define CLASSNAME VectorT<Scalar,DIM>
#define DERIVED VectorDataT<Scalar,DIM>
#define DIM 2
#define unroll(expr) expr(0) expr(1)
#define unroll_comb(expr, op) expr(0) op expr(1)
#define unroll_csv(expr) expr(0), expr(1)
#include "VectorT_inc.hh"
#undef DIM
#undef unroll
#undef unroll_comb
#undef unroll_csv
#define DIM 3
#define unroll(expr) expr(0) expr(1) expr(2)
#define unroll_comb(expr, op) expr(0) op expr(1) op expr(2)
#define unroll_csv(expr) expr(0), expr(1), expr(2)
#include "VectorT_inc.hh"
#undef DIM
#undef unroll
#undef unroll_comb
#undef unroll_csv
#define DIM 4
#define unroll(expr) expr(0) expr(1) expr(2) expr(3)
#define unroll_comb(expr, op) expr(0) op expr(1) op expr(2) op expr(3)
#define unroll_csv(expr) expr(0), expr(1), expr(2), expr(3)
#include "VectorT_inc.hh"
#undef DIM
#undef unroll
#undef unroll_comb
#undef unroll_csv
#undef TEMPLATE_HEADER
#undef CLASSNAME
#undef DERIVED
//== FULL TEMPLATE SPECIALIZATIONS ============================================
#else
/// cross product for Vec3f
template<>
inline VectorT<float,3>
VectorT<float,3>::operator%(const VectorT<float,3>& _rhs) const
{
return
VectorT<float,3>(values_[1]*_rhs.values_[2]-values_[2]*_rhs.values_[1],
values_[2]*_rhs.values_[0]-values_[0]*_rhs.values_[2],
values_[0]*_rhs.values_[1]-values_[1]*_rhs.values_[0]);
}
/// cross product for Vec3d
template<>
inline VectorT<double,3>
VectorT<double,3>::operator%(const VectorT<double,3>& _rhs) const
{
return
VectorT<double,3>(values_[1]*_rhs.values_[2]-values_[2]*_rhs.values_[1],
values_[2]*_rhs.values_[0]-values_[0]*_rhs.values_[2],
values_[0]*_rhs.values_[1]-values_[1]*_rhs.values_[0]);
}
#endif
//== GLOBAL FUNCTIONS =========================================================
/// \relates OpenMesh::VectorT
/// scalar * vector
template<typename Scalar,int N>
inline VectorT<Scalar,N> operator*(Scalar _s, const VectorT<Scalar,N>& _v) {
return VectorT<Scalar,N>(_v) *= _s;
}
/// \relates OpenMesh::VectorT
/// symmetric version of the dot product
template<typename Scalar, int N>
inline Scalar
dot(const VectorT<Scalar,N>& _v1, const VectorT<Scalar,N>& _v2) {
return (_v1 | _v2);
}
/// \relates OpenMesh::VectorT
/// symmetric version of the cross product
template<typename Scalar, int N>
inline VectorT<Scalar,N>
cross(const VectorT<Scalar,N>& _v1, const VectorT<Scalar,N>& _v2) {
return (_v1 % _v2);
}
//== TYPEDEFS =================================================================
/** 1-byte signed vector */
typedef VectorT<signed char,1> Vec1c;
/** 1-byte unsigned vector */
typedef VectorT<unsigned char,1> Vec1uc;
/** 1-short signed vector */
typedef VectorT<signed short int,1> Vec1s;
/** 1-short unsigned vector */
typedef VectorT<unsigned short int,1> Vec1us;
/** 1-int signed vector */
typedef VectorT<signed int,1> Vec1i;
/** 1-int unsigned vector */
typedef VectorT<unsigned int,1> Vec1ui;
/** 1-float vector */
typedef VectorT<float,1> Vec1f;
/** 1-double vector */
typedef VectorT<double,1> Vec1d;
/** 2-byte signed vector */
typedef VectorT<signed char,2> Vec2c;
/** 2-byte unsigned vector */
typedef VectorT<unsigned char,2> Vec2uc;
/** 2-short signed vector */
typedef VectorT<signed short int,2> Vec2s;
/** 2-short unsigned vector */
typedef VectorT<unsigned short int,2> Vec2us;
/** 2-int signed vector */
typedef VectorT<signed int,2> Vec2i;
/** 2-int unsigned vector */
typedef VectorT<unsigned int,2> Vec2ui;
/** 2-float vector */
typedef VectorT<float,2> Vec2f;
/** 2-double vector */
typedef VectorT<double,2> Vec2d;
/** 3-byte signed vector */
typedef VectorT<signed char,3> Vec3c;
/** 3-byte unsigned vector */
typedef VectorT<unsigned char,3> Vec3uc;
/** 3-short signed vector */
typedef VectorT<signed short int,3> Vec3s;
/** 3-short unsigned vector */
typedef VectorT<unsigned short int,3> Vec3us;
/** 3-int signed vector */
typedef VectorT<signed int,3> Vec3i;
/** 3-int unsigned vector */
typedef VectorT<unsigned int,3> Vec3ui;
/** 3-float vector */
typedef VectorT<float,3> Vec3f;
/** 3-double vector */
typedef VectorT<double,3> Vec3d;
/** 4-byte signed vector */
typedef VectorT<signed char,4> Vec4c;
/** 4-byte unsigned vector */
typedef VectorT<unsigned char,4> Vec4uc;
/** 4-short signed vector */
typedef VectorT<signed short int,4> Vec4s;
/** 4-short unsigned vector */
typedef VectorT<unsigned short int,4> Vec4us;
/** 4-int signed vector */
typedef VectorT<signed int,4> Vec4i;
/** 4-int unsigned vector */
typedef VectorT<unsigned int,4> Vec4ui;
/** 4-float vector */
typedef VectorT<float,4> Vec4f;
/** 4-double vector */
typedef VectorT<double,4> Vec4d;
/** 6-byte signed vector */
typedef VectorT<signed char,6> Vec6c;
/** 6-byte unsigned vector */
typedef VectorT<unsigned char,6> Vec6uc;
/** 6-short signed vector */
typedef VectorT<signed short int,6> Vec6s;
/** 6-short unsigned vector */
typedef VectorT<unsigned short int,6> Vec6us;
/** 6-int signed vector */
typedef VectorT<signed int,6> Vec6i;
/** 6-int unsigned vector */
typedef VectorT<unsigned int,6> Vec6ui;
/** 6-float vector */
typedef VectorT<float,6> Vec6f;
/** 6-double vector */
typedef VectorT<double,6> Vec6d;
//=============================================================================
} // namespace OpenMesh
//=============================================================================
#endif // OPENMESH_VECTOR_HH defined
//=============================================================================
#endif // DOXYGEN
<|endoftext|> |
<commit_before>#include "3rd-party/catch.hpp"
#include <memory>
#include "cache.h"
#include "configcontainer.h"
#include "feedcontainer.h"
#include "rss.h"
#include "test-helpers.h"
using namespace newsboat;
namespace {
std::vector<std::shared_ptr<rss_feed>> get_five_empty_feeds(cache* rsscache)
{
std::vector<std::shared_ptr<rss_feed>> feeds;
for (int i = 0; i < 5; ++i) {
const auto feed = std::make_shared<rss_feed>(rsscache);
feeds.push_back(feed);
}
return feeds;
}
} // anonymous namespace
TEST_CASE("get_feed() returns feed by its position number", "[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
const auto feeds = get_five_empty_feeds(rsscache.get());
int i = 0;
for (const auto& feed : feeds) {
feed->set_title(std::to_string(i));
feed->set_rssurl("url/" + std::to_string(i));
i++;
}
feedcontainer.set_feeds(feeds);
auto feed = feedcontainer.get_feed(0);
REQUIRE(feed->title_raw() == "0");
feed = feedcontainer.get_feed(4);
REQUIRE(feed->title_raw() == "4");
}
TEST_CASE("get_all_feeds() returns copy of FeedContainer's feed vector",
"[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
const auto feeds = get_five_empty_feeds(rsscache.get());
feedcontainer.set_feeds(feeds);
REQUIRE(feedcontainer.get_all_feeds() == feeds);
}
TEST_CASE("add_feed() adds specific feed to its \"feeds\" vector", "[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
feedcontainer.set_feeds({});
const auto feed = std::make_shared<rss_feed>(rsscache.get());
feed->set_title("Example feed");
feedcontainer.add_feed(feed);
REQUIRE(feedcontainer.get_feed(0)->title_raw() == "Example feed");
}
TEST_CASE("set_feeds() sets FeedContainer's feed vector to the given one",
"[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
const auto feeds = get_five_empty_feeds(rsscache.get());
feedcontainer.set_feeds(feeds);
REQUIRE(feedcontainer.feeds == feeds);
}
TEST_CASE("get_feed_by_url() returns feed by its URL", "[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
const auto feeds = get_five_empty_feeds(rsscache.get());
int i = 0;
for (const auto& feed : feeds) {
feed->set_title(std::to_string(i));
feed->set_rssurl("url/" + std::to_string(i));
i++;
}
feedcontainer.set_feeds(feeds);
auto feed = feedcontainer.get_feed_by_url("url/1");
REQUIRE(feed->title_raw() == "1");
feed = feedcontainer.get_feed_by_url("url/4");
REQUIRE(feed->title_raw() == "4");
}
TEST_CASE(
"get_feed_by_url() returns nullptr when it cannot find feed with "
"given URL",
"[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
const auto feeds = get_five_empty_feeds(rsscache.get());
int i = 0;
for (const auto& feed : feeds) {
feed->set_rssurl("url/" + std::to_string(i));
i++;
}
feedcontainer.set_feeds(feeds);
auto feed = feedcontainer.get_feed_by_url("Wrong URL");
REQUIRE(feed == nullptr);
}
TEST_CASE("Throws on get_feed() with pos out of range", "[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
feedcontainer.set_feeds(get_five_empty_feeds(rsscache.get()));
REQUIRE_NOTHROW(feedcontainer.get_feed(4));
CHECK_THROWS_AS(feedcontainer.get_feed(5), std::out_of_range);
CHECK_THROWS_AS(feedcontainer.get_feed(-1), std::out_of_range);
}
TEST_CASE("Returns correct number using get_feed_count_by_tag()",
"[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
feedcontainer.set_feeds(get_five_empty_feeds(rsscache.get()));
feedcontainer.get_feed(0)->set_tags({"Chicken", "Horse"});
feedcontainer.get_feed(1)->set_tags({"Horse", "Duck"});
feedcontainer.get_feed(2)->set_tags({"Duck", "Frog"});
feedcontainer.get_feed(3)->set_tags({"Duck", "Hawk"});
REQUIRE(feedcontainer.get_feed_count_per_tag("Ice Cream") == 0);
REQUIRE(feedcontainer.get_feed_count_per_tag("Chicken") == 1);
REQUIRE(feedcontainer.get_feed_count_per_tag("Horse") == 2);
REQUIRE(feedcontainer.get_feed_count_per_tag("Duck") == 3);
}
TEST_CASE("Correctly returns pos of next unread item", "[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
const auto feeds = get_five_empty_feeds(rsscache.get());
int i = 0;
for (const auto& feed : feeds) {
const auto item = std::make_shared<rss_item>(rsscache.get());
if ((i % 2) == 0)
item->set_unread_nowrite(true);
else
item->set_unread_nowrite(false);
feed->add_item(item);
i++;
}
feedcontainer.set_feeds(feeds);
REQUIRE(feedcontainer.get_pos_of_next_unread(0) == 2);
REQUIRE(feedcontainer.get_pos_of_next_unread(2) == 4);
}
TEST_CASE("feeds_size() returns FeedContainer's current feed vector size",
"[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
const auto feeds = get_five_empty_feeds(rsscache.get());
feedcontainer.set_feeds(feeds);
REQUIRE(feedcontainer.feeds_size() == feeds.size());
}
TEST_CASE("Correctly sorts feeds", "[feedcontainer]")
{
SECTION("by none asc")
{
}
SECTION("by none desc")
{
}
SECTION("by firsttag asc")
{
}
SECTION("by firsttag desc")
{
}
SECTION("by title asc")
{
}
SECTION("by title desc")
{
}
SECTION("by articlecount asc")
{
}
SECTION("by articlecount desc")
{
}
SECTION("by unreadarticlecount asc")
{
}
SECTION("by unreadarticlecount desc")
{
}
SECTION("by lastupdated asc")
{
}
SECTION("by lastupdated desc")
{
}
}
TEST_CASE("mark_all_feed_items_read() marks all of feed's items as read",
"[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
const auto feeds = get_five_empty_feeds(rsscache.get());
const auto feed = feeds.at(0);
for (int j = 0; j < 5; ++j) {
const auto item = std::make_shared<rss_item>(rsscache.get());
item->set_unread_nowrite(true);
feed->add_item(item);
}
feedcontainer.set_feeds(feeds);
feedcontainer.mark_all_feed_items_read(0);
for (const auto& item : feed->items()) {
REQUIRE(item->unread() == false);
}
}
TEST_CASE(
"reset_feeds_status() changes status of all feeds to \"to be "
"downloaded\"",
"[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
const auto feeds = get_five_empty_feeds(rsscache.get());
feeds[0]->set_status(dl_status::SUCCESS);
feeds[1]->set_status(dl_status::TO_BE_DOWNLOADED);
feeds[2]->set_status(dl_status::DURING_DOWNLOAD);
feeds[3]->set_status(dl_status::DL_ERROR);
feedcontainer.set_feeds(feeds);
feedcontainer.reset_feeds_status();
for (const auto& feed : feeds) {
REQUIRE(feed->get_status() == "_");
}
}
TEST_CASE("clear_feeds_items() clears all of feed's items", "[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
feedcontainer.set_feeds({});
const auto feed = std::make_shared<rss_feed>(rsscache.get());
for (int j = 0; j < 5; ++j) {
feed->add_item(std::make_shared<rss_item>(rsscache.get()));
}
feedcontainer.add_feed(feed);
REQUIRE(feed->items().size() == 5);
feedcontainer.clear_feeds_items();
REQUIRE(feed->items().size() == 0);
}
TEST_CASE(
"unread_feed_count() returns number of feeds that have unread items in "
"them",
"[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
const auto feeds = get_five_empty_feeds(rsscache.get());
for (int j = 0; j < 5; ++j) {
// Make sure that number of unread items in feed doesn't matter
const auto item = std::make_shared<rss_item>(rsscache.get());
const auto item2 = std::make_shared<rss_item>(rsscache.get());
if ((j % 2) == 0) {
item->set_unread_nowrite(false);
item2->set_unread_nowrite(false);
}
feeds[j]->add_item(item);
feeds[j]->add_item(item2);
}
feedcontainer.set_feeds(feeds);
REQUIRE(feedcontainer.unread_feed_count() == 2);
}
<commit_msg>Add unread_item_count() test<commit_after>#include "3rd-party/catch.hpp"
#include <memory>
#include "cache.h"
#include "configcontainer.h"
#include "feedcontainer.h"
#include "rss.h"
#include "test-helpers.h"
using namespace newsboat;
namespace {
std::vector<std::shared_ptr<rss_feed>> get_five_empty_feeds(cache* rsscache)
{
std::vector<std::shared_ptr<rss_feed>> feeds;
for (int i = 0; i < 5; ++i) {
const auto feed = std::make_shared<rss_feed>(rsscache);
feeds.push_back(feed);
}
return feeds;
}
} // anonymous namespace
TEST_CASE("get_feed() returns feed by its position number", "[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
const auto feeds = get_five_empty_feeds(rsscache.get());
int i = 0;
for (const auto& feed : feeds) {
feed->set_title(std::to_string(i));
feed->set_rssurl("url/" + std::to_string(i));
i++;
}
feedcontainer.set_feeds(feeds);
auto feed = feedcontainer.get_feed(0);
REQUIRE(feed->title_raw() == "0");
feed = feedcontainer.get_feed(4);
REQUIRE(feed->title_raw() == "4");
}
TEST_CASE("get_all_feeds() returns copy of FeedContainer's feed vector",
"[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
const auto feeds = get_five_empty_feeds(rsscache.get());
feedcontainer.set_feeds(feeds);
REQUIRE(feedcontainer.get_all_feeds() == feeds);
}
TEST_CASE("add_feed() adds specific feed to its \"feeds\" vector", "[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
feedcontainer.set_feeds({});
const auto feed = std::make_shared<rss_feed>(rsscache.get());
feed->set_title("Example feed");
feedcontainer.add_feed(feed);
REQUIRE(feedcontainer.get_feed(0)->title_raw() == "Example feed");
}
TEST_CASE("set_feeds() sets FeedContainer's feed vector to the given one",
"[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
const auto feeds = get_five_empty_feeds(rsscache.get());
feedcontainer.set_feeds(feeds);
REQUIRE(feedcontainer.feeds == feeds);
}
TEST_CASE("get_feed_by_url() returns feed by its URL", "[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
const auto feeds = get_five_empty_feeds(rsscache.get());
int i = 0;
for (const auto& feed : feeds) {
feed->set_title(std::to_string(i));
feed->set_rssurl("url/" + std::to_string(i));
i++;
}
feedcontainer.set_feeds(feeds);
auto feed = feedcontainer.get_feed_by_url("url/1");
REQUIRE(feed->title_raw() == "1");
feed = feedcontainer.get_feed_by_url("url/4");
REQUIRE(feed->title_raw() == "4");
}
TEST_CASE(
"get_feed_by_url() returns nullptr when it cannot find feed with "
"given URL",
"[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
const auto feeds = get_five_empty_feeds(rsscache.get());
int i = 0;
for (const auto& feed : feeds) {
feed->set_rssurl("url/" + std::to_string(i));
i++;
}
feedcontainer.set_feeds(feeds);
auto feed = feedcontainer.get_feed_by_url("Wrong URL");
REQUIRE(feed == nullptr);
}
TEST_CASE("Throws on get_feed() with pos out of range", "[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
feedcontainer.set_feeds(get_five_empty_feeds(rsscache.get()));
REQUIRE_NOTHROW(feedcontainer.get_feed(4));
CHECK_THROWS_AS(feedcontainer.get_feed(5), std::out_of_range);
CHECK_THROWS_AS(feedcontainer.get_feed(-1), std::out_of_range);
}
TEST_CASE("Returns correct number using get_feed_count_by_tag()",
"[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
feedcontainer.set_feeds(get_five_empty_feeds(rsscache.get()));
feedcontainer.get_feed(0)->set_tags({"Chicken", "Horse"});
feedcontainer.get_feed(1)->set_tags({"Horse", "Duck"});
feedcontainer.get_feed(2)->set_tags({"Duck", "Frog"});
feedcontainer.get_feed(3)->set_tags({"Duck", "Hawk"});
REQUIRE(feedcontainer.get_feed_count_per_tag("Ice Cream") == 0);
REQUIRE(feedcontainer.get_feed_count_per_tag("Chicken") == 1);
REQUIRE(feedcontainer.get_feed_count_per_tag("Horse") == 2);
REQUIRE(feedcontainer.get_feed_count_per_tag("Duck") == 3);
}
TEST_CASE("Correctly returns pos of next unread item", "[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
const auto feeds = get_five_empty_feeds(rsscache.get());
int i = 0;
for (const auto& feed : feeds) {
const auto item = std::make_shared<rss_item>(rsscache.get());
if ((i % 2) == 0)
item->set_unread_nowrite(true);
else
item->set_unread_nowrite(false);
feed->add_item(item);
i++;
}
feedcontainer.set_feeds(feeds);
REQUIRE(feedcontainer.get_pos_of_next_unread(0) == 2);
REQUIRE(feedcontainer.get_pos_of_next_unread(2) == 4);
}
TEST_CASE("feeds_size() returns FeedContainer's current feed vector size",
"[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
const auto feeds = get_five_empty_feeds(rsscache.get());
feedcontainer.set_feeds(feeds);
REQUIRE(feedcontainer.feeds_size() == feeds.size());
}
TEST_CASE("Correctly sorts feeds", "[feedcontainer]")
{
SECTION("by none asc")
{
}
SECTION("by none desc")
{
}
SECTION("by firsttag asc")
{
}
SECTION("by firsttag desc")
{
}
SECTION("by title asc")
{
}
SECTION("by title desc")
{
}
SECTION("by articlecount asc")
{
}
SECTION("by articlecount desc")
{
}
SECTION("by unreadarticlecount asc")
{
}
SECTION("by unreadarticlecount desc")
{
}
SECTION("by lastupdated asc")
{
}
SECTION("by lastupdated desc")
{
}
}
TEST_CASE("mark_all_feed_items_read() marks all of feed's items as read",
"[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
const auto feeds = get_five_empty_feeds(rsscache.get());
const auto feed = feeds.at(0);
for (int j = 0; j < 5; ++j) {
const auto item = std::make_shared<rss_item>(rsscache.get());
item->set_unread_nowrite(true);
feed->add_item(item);
}
feedcontainer.set_feeds(feeds);
feedcontainer.mark_all_feed_items_read(0);
for (const auto& item : feed->items()) {
REQUIRE(item->unread() == false);
}
}
TEST_CASE(
"reset_feeds_status() changes status of all feeds to \"to be "
"downloaded\"",
"[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
const auto feeds = get_five_empty_feeds(rsscache.get());
feeds[0]->set_status(dl_status::SUCCESS);
feeds[1]->set_status(dl_status::TO_BE_DOWNLOADED);
feeds[2]->set_status(dl_status::DURING_DOWNLOAD);
feeds[3]->set_status(dl_status::DL_ERROR);
feedcontainer.set_feeds(feeds);
feedcontainer.reset_feeds_status();
for (const auto& feed : feeds) {
REQUIRE(feed->get_status() == "_");
}
}
TEST_CASE("clear_feeds_items() clears all of feed's items", "[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
feedcontainer.set_feeds({});
const auto feed = std::make_shared<rss_feed>(rsscache.get());
for (int j = 0; j < 5; ++j) {
feed->add_item(std::make_shared<rss_item>(rsscache.get()));
}
feedcontainer.add_feed(feed);
REQUIRE(feed->items().size() == 5);
feedcontainer.clear_feeds_items();
REQUIRE(feed->items().size() == 0);
}
TEST_CASE(
"unread_feed_count() returns number of feeds that have unread items in "
"them",
"[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
const auto feeds = get_five_empty_feeds(rsscache.get());
for (int j = 0; j < 5; ++j) {
// Make sure that number of unread items in feed doesn't matter
const auto item = std::make_shared<rss_item>(rsscache.get());
const auto item2 = std::make_shared<rss_item>(rsscache.get());
if ((j % 2) == 0) {
item->set_unread_nowrite(false);
item2->set_unread_nowrite(false);
}
feeds[j]->add_item(item);
feeds[j]->add_item(item2);
}
feedcontainer.set_feeds(feeds);
REQUIRE(feedcontainer.unread_feed_count() == 2);
}
TEST_CASE("unread_item_count() returns number of unread items in all feeds",
"[feedcontainer]")
{
FeedContainer feedcontainer;
std::unique_ptr<configcontainer> cfg(new configcontainer());
std::unique_ptr<cache> rsscache(new cache(":memory:", cfg.get()));
const auto feeds = get_five_empty_feeds(rsscache.get());
for (int j = 0; j < 5; ++j) {
const auto item = std::make_shared<rss_item>(rsscache.get());
const auto item2 = std::make_shared<rss_item>(rsscache.get());
if ((j % 2) == 0) {
item->set_unread_nowrite(false);
item2->set_unread_nowrite(false);
}
feeds[j]->add_item(item);
feeds[j]->add_item(item2);
}
feedcontainer.set_feeds(feeds);
REQUIRE(feedcontainer.unread_item_count() == 4);
}
<|endoftext|> |
<commit_before>#include "mitkPropertyManager.h"
#include "mitkBoolProperty.h"
mitk::PropertyManager::PropertyManager() {
std::cout << "ctor PropertyManager" << std::endl;
m_DefaultPropertyNameSet.insert(std::string("visible"));
}
const mitk::PropertyManager::PropertyNameSet& mitk::PropertyManager::GetDefaultPropertyNames() {
static mitk::PropertyManager propManager;
return propManager.m_DefaultPropertyNameSet;
};
mitk::BaseProperty::Pointer mitk::PropertyManager::CreateDefaultProperty(std::string name) {
mitk::BaseProperty::Pointer newProperty(NULL);
if ( name == "visible" ) {
newProperty = new mitk::BoolProperty(true);
} else {
std::cout << "Warning: non-existing default property requested: "
<< name << std::endl;
}
};
<commit_msg>added return value<commit_after>#include "mitkPropertyManager.h"
#include "mitkBoolProperty.h"
mitk::PropertyManager::PropertyManager() {
std::cout << "ctor PropertyManager" << std::endl;
m_DefaultPropertyNameSet.insert(std::string("visible"));
}
const mitk::PropertyManager::PropertyNameSet& mitk::PropertyManager::GetDefaultPropertyNames() {
static mitk::PropertyManager propManager;
return propManager.m_DefaultPropertyNameSet;
};
mitk::BaseProperty::Pointer mitk::PropertyManager::CreateDefaultProperty(std::string name) {
mitk::BaseProperty::Pointer newProperty(NULL);
if ( name == "visible" ) {
newProperty = new mitk::BoolProperty(true);
} else {
std::cout << "Warning: non-existing default property requested: "
<< name << std::endl;
}
return NULL;
};
<|endoftext|> |
<commit_before>#include "gmcphandlers.h"
#include "being.h"
#include "connect.h"
#include "room.h"
#include "person.h"
#include "json.hpp"
namespace {
unsigned char GMCP = 201;
unsigned char iac = 255; /* interpret as command: */
unsigned char dont = 254; /* you are not to use option */
unsigned char do_ = 253; /* please, you use option */
unsigned char wont = 252; /* I won't use option */
unsigned char will = 251; /* I will use option */
unsigned char sb = 250; /* interpret as subnegotiation */
// unsigned char se = 240; /* end sub negotiation */
void handleCoreHello(sstring const& s, Descriptor& d) {
auto hello = s.substr(sizeof("Core.Hello"));
auto js = nlohmann::json::parse(hello);
try {
d.mudclient = js.at("client");
d.clientversion = js.at("version");
} catch (const std::range_error&) {
vlogf(LOG_MISC, format("Client sent bad Core.Hello: %s") % hello);
}
}
void handleRemember(sstring const& s, Descriptor& d)
{
sstring arg = s.dropWord();
auto player = dynamic_cast<TPerson*>(d.character);
if (player)
player->doRemember(false, arg);
}
void handleRememberPlayer(sstring const& s, Descriptor& d)
{
sstring arg = s.dropWord();
auto player = dynamic_cast<TPerson*>(d.character);
if (player)
player->doRememberPlayer(false, arg);
}
void handleRetrieve(sstring const& s, Descriptor& d)
{
sstring key = s.word(1);
auto player = dynamic_cast<TPerson*>(d.character);
if (player)
player->doRetrieve(false, key);
}
std::map<std::string, std::function<void(std::string, Descriptor&)>> commandHandlers = {
{"Core.Supports.Set", [](std::string, Descriptor&){}}, // squelch
{"Core.Hello", handleCoreHello},
{"remember", handleRemember},
{"rememberplayer", handleRememberPlayer},
{"retrieve", handleRetrieve},
};
void handleGmcpCommand(sstring const& s, Descriptor* d)
{
assert(d);
decltype(commandHandlers)::iterator it;
if (s == "request sectors") {
sstring str;
for (int i = 0; i < MAX_SECTOR_TYPES; i++) {
str += format(", { \"id\" : %d, \"name\" : \"%s\", \"color\" : %d }")
% i
% TerrainInfo[i]->name
% TerrainInfo[i]->color;
}
str = sstring("room.sectors { \"sectors\" : [ ") + str.substr(2) + " ] }";
d->sendGmcp(str, true);
}
else if (s == "request area") {
TRoom* roomp = d->character->roomp;
sstring area = format(
"room.area { \"id\":\"%d\", \"name\": \"%s\", \"x\": 0, \"y\": 0, \"z\": 0, \"col\": \"\", \
\"flags\": \"quiet\" }")
% roomp->getZone()->zone_nr
% roomp->getZone()->name;
d->sendGmcp(area, true);
}
else if ((it = commandHandlers.find(s.word(0))) != commandHandlers.end()) {
it->second(s, *d);
}
else
vlogf(LOG_MISC, format("Telnet: Unknown GMCP command '%s' ") % s);
}
}
sstring handleTelnetOpts(sstring& s, Descriptor* d)
{
sstring result;
size_t iac_pos = s.find(iac);
if (iac_pos == sstring::npos)
return "";
// Ugliest hack ever: clients don't bother to negotiate for GMCP. Therefore, if they ever send any Telnet commands, assume they can handle subchannels.
d->gmcp = true;
// I wonder if this ever happens
if (iac_pos > s.length() - 2) {
vlogf(LOG_MISC, "Telnet: truncated Telnet IAC");
return "";
}
unsigned char cmd = s[iac_pos + 1];
if (cmd == will || cmd == do_ || cmd == wont || cmd == dont) {
// I wonder if this ever happens
if (iac_pos > s.length() - 3) {
vlogf(LOG_MISC, "Telnet: truncated Telnet IAC WILL/DO/WONT/DONT");
return "";
}
unsigned char arg = s[iac_pos+2];
if (cmd == will && arg == GMCP) { // let's have a lil' GMCP
// IAC DO GMCP
d->gmcp = true;
result = "\xff\0xfc\xc9";
}
else if (cmd == do_ && arg == GMCP) { // I can handle GMCP should you wish
// IAC WILL GMCP
d->gmcp = true;
result = "\xff\0xfb\xc9";
}
else if (cmd == will) { // Anything else is unsupported
// IAC DONT ...
vlogf(LOG_MISC, format("Telnet: Unsupported protocol request: IAC WILL 0x%2x") % static_cast<int>(arg));
result = format("\xff\xfe%c") % arg;
}
else if (cmd == do_) { // Anything else is unsupported
// IAC WONT ...
vlogf(LOG_MISC, format("Telnet: Unsupported protocol request: IAC DO 0x%02x") % static_cast<int>(arg));
result = format("\xff\xfd%c") % arg;
}
else {
if (arg == GMCP)
d->gmcp = false;
// vlogf(LOG_MISC, format("Telnet: Unsupported IAC DONT/WONT: 0x%02x") % static_cast<int>(arg));
}
// so that it won't get into general processing
s.erase(iac_pos, 3);
return result + handleTelnetOpts(s, d); // also handle other commands in the same string
}
else if (cmd == sb) {
// eat everything up to and including IAC SE
// I wonder if this ever happens
if (iac_pos > s.length() - 5) {
vlogf(LOG_MISC, "Telnet: truncated Telnet IAC SB");
return "";
}
unsigned char arg = s[iac_pos+2];
size_t begin = iac_pos + 3;
size_t end = s.find("\xff\xf0"); // IAC SE
if (end == sstring::npos) {
vlogf(LOG_MISC, format("Telnet: Truncated IAC SB 0x%02x") % static_cast<int>(arg));
return "";
}
sstring client_gmcp_cmd = s.substr(begin, end-begin);
s.erase(iac_pos, end + 1 - iac_pos);
if (arg == GMCP) {
handleGmcpCommand(client_gmcp_cmd, d);
return handleTelnetOpts(s, d);
}
else {
// vlogf(LOG_MISC, format("Telnet: Got unhandled IAC SB 0x%02x: '%s'")
// % static_cast<int>(arg) % client_gmcp_cmd);
return handleTelnetOpts(s, d);
}
}
else
return "";
}
<commit_msg>Don't crash if naughty client sends bad json<commit_after>#include "gmcphandlers.h"
#include "being.h"
#include "connect.h"
#include "room.h"
#include "person.h"
#include "json.hpp"
namespace {
unsigned char GMCP = 201;
unsigned char iac = 255; /* interpret as command: */
unsigned char dont = 254; /* you are not to use option */
unsigned char do_ = 253; /* please, you use option */
unsigned char wont = 252; /* I won't use option */
unsigned char will = 251; /* I will use option */
unsigned char sb = 250; /* interpret as subnegotiation */
// unsigned char se = 240; /* end sub negotiation */
void handleCoreHello(sstring const& s, Descriptor& d) {
auto hello = s.substr(sizeof("Core.Hello"));
try {
auto js = nlohmann::json::parse(hello);
d.mudclient = js.at("client");
d.clientversion = js.at("version");
} catch(nlohmann::json::parse_error) {
vlogf(LOG_MISC, format("Client sent bad Core.Hello: %s") % hello);
} catch (const std::range_error&) {
vlogf(LOG_MISC, format("Client sent bad Core.Hello: %s") % hello);
}
}
void handleRemember(sstring const& s, Descriptor& d)
{
sstring arg = s.dropWord();
auto player = dynamic_cast<TPerson*>(d.character);
if (player)
player->doRemember(false, arg);
}
void handleRememberPlayer(sstring const& s, Descriptor& d)
{
sstring arg = s.dropWord();
auto player = dynamic_cast<TPerson*>(d.character);
if (player)
player->doRememberPlayer(false, arg);
}
void handleRetrieve(sstring const& s, Descriptor& d)
{
sstring key = s.word(1);
auto player = dynamic_cast<TPerson*>(d.character);
if (player)
player->doRetrieve(false, key);
}
std::map<std::string, std::function<void(std::string, Descriptor&)>> commandHandlers = {
{"Core.Supports.Set", [](std::string, Descriptor&){}}, // squelch
{"Core.Hello", handleCoreHello},
{"remember", handleRemember},
{"rememberplayer", handleRememberPlayer},
{"retrieve", handleRetrieve},
};
void handleGmcpCommand(sstring const& s, Descriptor* d)
{
assert(d);
decltype(commandHandlers)::iterator it;
if (s == "request sectors") {
sstring str;
for (int i = 0; i < MAX_SECTOR_TYPES; i++) {
str += format(", { \"id\" : %d, \"name\" : \"%s\", \"color\" : %d }")
% i
% TerrainInfo[i]->name
% TerrainInfo[i]->color;
}
str = sstring("room.sectors { \"sectors\" : [ ") + str.substr(2) + " ] }";
d->sendGmcp(str, true);
}
else if (s == "request area") {
TRoom* roomp = d->character->roomp;
sstring area = format(
"room.area { \"id\":\"%d\", \"name\": \"%s\", \"x\": 0, \"y\": 0, \"z\": 0, \"col\": \"\", \
\"flags\": \"quiet\" }")
% roomp->getZone()->zone_nr
% roomp->getZone()->name;
d->sendGmcp(area, true);
}
else if ((it = commandHandlers.find(s.word(0))) != commandHandlers.end()) {
it->second(s, *d);
}
else
vlogf(LOG_MISC, format("Telnet: Unknown GMCP command '%s' ") % s);
}
}
sstring handleTelnetOpts(sstring& s, Descriptor* d)
{
sstring result;
size_t iac_pos = s.find(iac);
if (iac_pos == sstring::npos)
return "";
// Ugliest hack ever: clients don't bother to negotiate for GMCP. Therefore, if they ever send any Telnet commands, assume they can handle subchannels.
d->gmcp = true;
// I wonder if this ever happens
if (iac_pos > s.length() - 2) {
vlogf(LOG_MISC, "Telnet: truncated Telnet IAC");
return "";
}
unsigned char cmd = s[iac_pos + 1];
if (cmd == will || cmd == do_ || cmd == wont || cmd == dont) {
// I wonder if this ever happens
if (iac_pos > s.length() - 3) {
vlogf(LOG_MISC, "Telnet: truncated Telnet IAC WILL/DO/WONT/DONT");
return "";
}
unsigned char arg = s[iac_pos+2];
if (cmd == will && arg == GMCP) { // let's have a lil' GMCP
// IAC DO GMCP
d->gmcp = true;
result = "\xff\0xfc\xc9";
}
else if (cmd == do_ && arg == GMCP) { // I can handle GMCP should you wish
// IAC WILL GMCP
d->gmcp = true;
result = "\xff\0xfb\xc9";
}
else if (cmd == will) { // Anything else is unsupported
// IAC DONT ...
vlogf(LOG_MISC, format("Telnet: Unsupported protocol request: IAC WILL 0x%2x") % static_cast<int>(arg));
result = format("\xff\xfe%c") % arg;
}
else if (cmd == do_) { // Anything else is unsupported
// IAC WONT ...
vlogf(LOG_MISC, format("Telnet: Unsupported protocol request: IAC DO 0x%02x") % static_cast<int>(arg));
result = format("\xff\xfd%c") % arg;
}
else {
if (arg == GMCP)
d->gmcp = false;
// vlogf(LOG_MISC, format("Telnet: Unsupported IAC DONT/WONT: 0x%02x") % static_cast<int>(arg));
}
// so that it won't get into general processing
s.erase(iac_pos, 3);
return result + handleTelnetOpts(s, d); // also handle other commands in the same string
}
else if (cmd == sb) {
// eat everything up to and including IAC SE
// I wonder if this ever happens
if (iac_pos > s.length() - 5) {
vlogf(LOG_MISC, "Telnet: truncated Telnet IAC SB");
return "";
}
unsigned char arg = s[iac_pos+2];
size_t begin = iac_pos + 3;
size_t end = s.find("\xff\xf0"); // IAC SE
if (end == sstring::npos) {
vlogf(LOG_MISC, format("Telnet: Truncated IAC SB 0x%02x") % static_cast<int>(arg));
return "";
}
sstring client_gmcp_cmd = s.substr(begin, end-begin);
s.erase(iac_pos, end + 1 - iac_pos);
if (arg == GMCP) {
handleGmcpCommand(client_gmcp_cmd, d);
return handleTelnetOpts(s, d);
}
else {
// vlogf(LOG_MISC, format("Telnet: Got unhandled IAC SB 0x%02x: '%s'")
// % static_cast<int>(arg) % client_gmcp_cmd);
return handleTelnetOpts(s, d);
}
}
else
return "";
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sdrole2primitive2d.cxx,v $
*
* $Revision: 1.2.18.1 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "precompiled_svx.hxx"
#include <svx/sdr/primitive2d/sdrole2primitive2d.hxx>
#include <svx/sdr/primitive2d/svx_primitivetypes2d.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <svx/sdr/primitive2d/sdrdecompositiontools.hxx>
#include <drawinglayer/primitive2d/sdrdecompositiontools2d.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
//////////////////////////////////////////////////////////////////////////////
using namespace com::sun::star;
//////////////////////////////////////////////////////////////////////////////
namespace drawinglayer
{
namespace primitive2d
{
SdrOle2Primitive2D::SdrOle2Primitive2D(
const Primitive2DSequence& rOLEContent,
const basegfx::B2DHomMatrix& rTransform,
const attribute::SdrLineFillShadowTextAttribute& rSdrLFSTAttribute)
: BasePrimitive2D(),
maOLEContent(rOLEContent),
maTransform(rTransform),
maSdrLFSTAttribute(rSdrLFSTAttribute)
{
}
bool SdrOle2Primitive2D::operator==(const BasePrimitive2D& rPrimitive) const
{
if(BasePrimitive2D::operator==(rPrimitive))
{
const SdrOle2Primitive2D& rCompare = (SdrOle2Primitive2D&)rPrimitive;
if(getOLEContent() == rCompare.getOLEContent()
&& getTransform() == rCompare.getTransform()
&& getSdrLFSTAttribute() == rCompare.getSdrLFSTAttribute())
{
return true;
}
}
return false;
}
Primitive2DSequence SdrOle2Primitive2D::get2DDecomposition(const geometry::ViewInformation2D& /*aViewInformation*/) const
{
// to take care of getSdrLFSTAttribute() later, the same as in SdrGrafPrimitive2D::create2DDecomposition
// should happen. For the moment we only need the OLE itself
// Added complete primitive preparation using getSdrLFSTAttribute() now. To not do stuff which is not needed now, it
// may be supressed by using a static bool. The paint version only supported text.
static bool bBehaveCompatibleToPaintVersion(true);
Primitive2DSequence aRetval;
// create unit outline polygon
const basegfx::B2DPolygon aUnitOutline(basegfx::tools::createUnitPolygon());
// add fill
if(!bBehaveCompatibleToPaintVersion
&& !getSdrLFSTAttribute().getFill().isDefault())
{
appendPrimitive2DReferenceToPrimitive2DSequence(aRetval,
createPolyPolygonFillPrimitive(
basegfx::B2DPolyPolygon(aUnitOutline),
getTransform(),
getSdrLFSTAttribute().getFill(),
getSdrLFSTAttribute().getFillFloatTransGradient()));
}
// add line
// #i97981# condition was inverse to purpose. When being compatible to paint version,
// border needs to be suppressed
if(!bBehaveCompatibleToPaintVersion
&& !getSdrLFSTAttribute().getLine().isDefault())
{
// if line width is given, polygon needs to be grown by half of it to make the
// outline to be outside of the bitmap
if(0.0 != getSdrLFSTAttribute().getLine().getWidth())
{
// decompose to get scale
basegfx::B2DVector aScale, aTranslate;
double fRotate, fShearX;
getTransform().decompose(aScale, aTranslate, fRotate, fShearX);
// create expanded range (add relative half line width to unit rectangle)
double fHalfLineWidth(getSdrLFSTAttribute().getLine().getWidth() * 0.5);
double fScaleX(0.0 != aScale.getX() ? fHalfLineWidth / fabs(aScale.getX()) : 1.0);
double fScaleY(0.0 != aScale.getY() ? fHalfLineWidth / fabs(aScale.getY()) : 1.0);
const basegfx::B2DRange aExpandedRange(-fScaleX, -fScaleY, 1.0 + fScaleX, 1.0 + fScaleY);
basegfx::B2DPolygon aExpandedUnitOutline(basegfx::tools::createPolygonFromRect(aExpandedRange));
appendPrimitive2DReferenceToPrimitive2DSequence(aRetval,
createPolygonLinePrimitive(
aExpandedUnitOutline,
getTransform(),
getSdrLFSTAttribute().getLine(),
attribute::SdrLineStartEndAttribute()));
}
else
{
appendPrimitive2DReferenceToPrimitive2DSequence(aRetval,
createPolygonLinePrimitive(
aUnitOutline,
getTransform(),
getSdrLFSTAttribute().getLine(),
attribute::SdrLineStartEndAttribute()));
}
}
else
{
// if initially no line is defined, create one for HitTest and BoundRect
appendPrimitive2DReferenceToPrimitive2DSequence(aRetval,
createHiddenGeometryPrimitives2D(
false,
basegfx::B2DPolyPolygon(aUnitOutline),
getTransform()));
}
// add graphic content
appendPrimitive2DSequenceToPrimitive2DSequence(aRetval, getOLEContent());
// add text, no need to supress to stay compatible since text was
// always supported by the old paints, too
if(!getSdrLFSTAttribute().getText().isDefault())
{
appendPrimitive2DReferenceToPrimitive2DSequence(aRetval,
createTextPrimitive(
basegfx::B2DPolyPolygon(aUnitOutline),
getTransform(),
getSdrLFSTAttribute().getText(),
getSdrLFSTAttribute().getLine(),
false,
false,
false));
}
// add shadow
if(!bBehaveCompatibleToPaintVersion
&& !getSdrLFSTAttribute().getShadow().isDefault())
{
aRetval = createEmbeddedShadowPrimitive(
aRetval,
getSdrLFSTAttribute().getShadow());
}
return aRetval;
}
// provide unique ID
ImplPrimitrive2DIDBlock(SdrOle2Primitive2D, PRIMITIVE2D_ID_SDROLE2PRIMITIVE2D)
} // end of namespace primitive2d
} // end of namespace drawinglayer
//////////////////////////////////////////////////////////////////////////////
// eof
<commit_msg>aw079 #i108636# use better operator== for comparing two UNO API sequences of primitives<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sdrole2primitive2d.cxx,v $
*
* $Revision: 1.2.18.1 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "precompiled_svx.hxx"
#include <svx/sdr/primitive2d/sdrole2primitive2d.hxx>
#include <svx/sdr/primitive2d/svx_primitivetypes2d.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <svx/sdr/primitive2d/sdrdecompositiontools.hxx>
#include <drawinglayer/primitive2d/sdrdecompositiontools2d.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
//////////////////////////////////////////////////////////////////////////////
using namespace com::sun::star;
//////////////////////////////////////////////////////////////////////////////
namespace drawinglayer
{
namespace primitive2d
{
SdrOle2Primitive2D::SdrOle2Primitive2D(
const Primitive2DSequence& rOLEContent,
const basegfx::B2DHomMatrix& rTransform,
const attribute::SdrLineFillShadowTextAttribute& rSdrLFSTAttribute)
: BasePrimitive2D(),
maOLEContent(rOLEContent),
maTransform(rTransform),
maSdrLFSTAttribute(rSdrLFSTAttribute)
{
}
bool SdrOle2Primitive2D::operator==(const BasePrimitive2D& rPrimitive) const
{
if(BasePrimitive2D::operator==(rPrimitive))
{
const SdrOle2Primitive2D& rCompare = (SdrOle2Primitive2D&)rPrimitive;
// #i108636# The standard operator== on two UNO sequences did not work as i
// would have expected; it just checks the .is() states and the data type
// of the sequence. What i need here is detection of equality of the whole
// sequence content, thus i need to use the arePrimitive2DSequencesEqual helper
// here instead of the operator== which lead to always returning false and thus
// always re-decompositions of the subcontent.
if(arePrimitive2DSequencesEqual(getOLEContent(), rCompare.getOLEContent())
&& getTransform() == rCompare.getTransform()
&& getSdrLFSTAttribute() == rCompare.getSdrLFSTAttribute())
{
return true;
}
}
return false;
}
Primitive2DSequence SdrOle2Primitive2D::get2DDecomposition(const geometry::ViewInformation2D& /*aViewInformation*/) const
{
// to take care of getSdrLFSTAttribute() later, the same as in SdrGrafPrimitive2D::create2DDecomposition
// should happen. For the moment we only need the OLE itself
// Added complete primitive preparation using getSdrLFSTAttribute() now. To not do stuff which is not needed now, it
// may be supressed by using a static bool. The paint version only supported text.
static bool bBehaveCompatibleToPaintVersion(true);
Primitive2DSequence aRetval;
// create unit outline polygon
const basegfx::B2DPolygon aUnitOutline(basegfx::tools::createUnitPolygon());
// add fill
if(!bBehaveCompatibleToPaintVersion
&& !getSdrLFSTAttribute().getFill().isDefault())
{
appendPrimitive2DReferenceToPrimitive2DSequence(aRetval,
createPolyPolygonFillPrimitive(
basegfx::B2DPolyPolygon(aUnitOutline),
getTransform(),
getSdrLFSTAttribute().getFill(),
getSdrLFSTAttribute().getFillFloatTransGradient()));
}
// add line
// #i97981# condition was inverse to purpose. When being compatible to paint version,
// border needs to be suppressed
if(!bBehaveCompatibleToPaintVersion
&& !getSdrLFSTAttribute().getLine().isDefault())
{
// if line width is given, polygon needs to be grown by half of it to make the
// outline to be outside of the bitmap
if(0.0 != getSdrLFSTAttribute().getLine().getWidth())
{
// decompose to get scale
basegfx::B2DVector aScale, aTranslate;
double fRotate, fShearX;
getTransform().decompose(aScale, aTranslate, fRotate, fShearX);
// create expanded range (add relative half line width to unit rectangle)
double fHalfLineWidth(getSdrLFSTAttribute().getLine().getWidth() * 0.5);
double fScaleX(0.0 != aScale.getX() ? fHalfLineWidth / fabs(aScale.getX()) : 1.0);
double fScaleY(0.0 != aScale.getY() ? fHalfLineWidth / fabs(aScale.getY()) : 1.0);
const basegfx::B2DRange aExpandedRange(-fScaleX, -fScaleY, 1.0 + fScaleX, 1.0 + fScaleY);
basegfx::B2DPolygon aExpandedUnitOutline(basegfx::tools::createPolygonFromRect(aExpandedRange));
appendPrimitive2DReferenceToPrimitive2DSequence(aRetval,
createPolygonLinePrimitive(
aExpandedUnitOutline,
getTransform(),
getSdrLFSTAttribute().getLine(),
attribute::SdrLineStartEndAttribute()));
}
else
{
appendPrimitive2DReferenceToPrimitive2DSequence(aRetval,
createPolygonLinePrimitive(
aUnitOutline,
getTransform(),
getSdrLFSTAttribute().getLine(),
attribute::SdrLineStartEndAttribute()));
}
}
else
{
// if initially no line is defined, create one for HitTest and BoundRect
appendPrimitive2DReferenceToPrimitive2DSequence(aRetval,
createHiddenGeometryPrimitives2D(
false,
basegfx::B2DPolyPolygon(aUnitOutline),
getTransform()));
}
// add graphic content
appendPrimitive2DSequenceToPrimitive2DSequence(aRetval, getOLEContent());
// add text, no need to supress to stay compatible since text was
// always supported by the old paints, too
if(!getSdrLFSTAttribute().getText().isDefault())
{
appendPrimitive2DReferenceToPrimitive2DSequence(aRetval,
createTextPrimitive(
basegfx::B2DPolyPolygon(aUnitOutline),
getTransform(),
getSdrLFSTAttribute().getText(),
getSdrLFSTAttribute().getLine(),
false,
false,
false));
}
// add shadow
if(!bBehaveCompatibleToPaintVersion
&& !getSdrLFSTAttribute().getShadow().isDefault())
{
aRetval = createEmbeddedShadowPrimitive(
aRetval,
getSdrLFSTAttribute().getShadow());
}
return aRetval;
}
// provide unique ID
ImplPrimitrive2DIDBlock(SdrOle2Primitive2D, PRIMITIVE2D_ID_SDROLE2PRIMITIVE2D)
} // end of namespace primitive2d
} // end of namespace drawinglayer
//////////////////////////////////////////////////////////////////////////////
// eof
<|endoftext|> |
<commit_before>// The MIT License (MIT)
// Copyright (c) 2013-2016 Rapptz, ThePhD and contributors
// 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.
#ifndef SOL_VERSION_HPP
#define SOL_VERSION_HPP
#ifdef SOL_USING_CXX_LUA
#include <lua.h>
#include <lualib.h>
#include <luaxlib.h>
#else
#include <lua.hpp>
#endif // C++-compiler Lua
#if defined(_WIN32) || defined(_MSC_VER)
#ifndef SOL_CODECVT_SUPPORT
#define SOL_CODECVT_SUPPORT 1
#endif // sol codecvt support
#elif defined(__GNUC__)
#if __GNUC__ >= 5
#ifndef SOL_CODECVT_SUPPORT
#define SOL_CODECVT_SUPPORT 1
#endif // codecvt support
#endif // g++ 5.x.x (MinGW too)
#else
// Clang sucks and doesn't really utilize codecvt support,
// not without checking the library versions explicitly (and we're not gonna do that, so fuck you)
#endif // Windows/VC++ vs. g++ vs Others
#ifdef LUAJIT_VERSION
#ifndef SOL_LUAJIT
#define SOL_LUAJIT
#define SOL_LUAJIT_VERSION LUAJIT_VERSION_NUM
#endif // sol luajit
#endif // luajit
#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 502
#define SOL_LUA_VERSION LUA_VERSION_NUM
#elif defined(LUA_VERSION_NUM) && LUA_VERSION_NUM == 501
#define SOL_LUA_VERSION LUA_VERSION_NUM
#elif !defined(LUA_VERSION_NUM)
// Definitely 5.0
#define SOL_LUA_VERSION 500
#else
// ??? Not sure, assume 502?
#define SOL_LUA_VERSION 502
#endif // Lua Version 502, 501 || luajit, 500
#ifdef _MSC_VER
#ifdef _DEBUG
#ifndef NDEBUG
#ifndef SOL_CHECK_ARGUMENTS
// Do not define by default: let user turn it on
//#define SOL_CHECK_ARGUMENTS
#endif // Check Arguments
#ifndef SOL_SAFE_USERTYPE
#define SOL_SAFE_USERTYPE
#endif // Safe Usertypes
#endif // NDEBUG
#endif // Debug
#ifndef _CPPUNWIND
#ifndef SOL_NO_EXCEPTIONS
#define SOL_NO_EXCEPTIONS 1
#endif
#endif // Automatic Exceptions
#ifndef _CPPRTTI
#ifndef SOL_NO_RTTI
#define SOL_NO_RTTI 1
#endif
#endif // Automatic RTTI
#elif defined(__GNUC__) || defined(__clang__)
#ifndef NDEBUG
#ifndef __OPTIMIZE__
#ifndef SOL_CHECK_ARGUMENTS
// Do not define by default: let user choose
//#define SOL_CHECK_ARGUMENTS
// But do check userdata by default:
#endif // Check Arguments
#ifndef SOL_SAFE_USERTYPE
#define SOL_SAFE_USERTYPE
#endif // Safe Usertypes
#endif // g++ optimizer flag
#endif // Not Debug
#ifndef __EXCEPTIONS
#ifndef SOL_NO_EXCEPTIONS
#define SOL_NO_EXCEPTIONS 1
#endif
#endif // No Exceptions
#ifndef __GXX_RTTI
#ifndef SOL_NO_RTII
#define SOL_NO_RTTI 1
#endif
#endif // No RTTI
#endif // vc++ || clang++/g++
#ifndef SOL_SAFE_USERTYPE
#ifdef SOL_CHECK_ARGUMENTS
#define SOL_SAFE_USERTYPE
#endif // Turn on Safety for all
#endif // Safe Usertypes
#endif // SOL_VERSION_HPP
<commit_msg>Fixed typo: luaxlib.h -> lauxlib.h<commit_after>// The MIT License (MIT)
// Copyright (c) 2013-2016 Rapptz, ThePhD and contributors
// 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.
#ifndef SOL_VERSION_HPP
#define SOL_VERSION_HPP
#ifdef SOL_USING_CXX_LUA
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#else
#include <lua.hpp>
#endif // C++-compiler Lua
#if defined(_WIN32) || defined(_MSC_VER)
#ifndef SOL_CODECVT_SUPPORT
#define SOL_CODECVT_SUPPORT 1
#endif // sol codecvt support
#elif defined(__GNUC__)
#if __GNUC__ >= 5
#ifndef SOL_CODECVT_SUPPORT
#define SOL_CODECVT_SUPPORT 1
#endif // codecvt support
#endif // g++ 5.x.x (MinGW too)
#else
// Clang sucks and doesn't really utilize codecvt support,
// not without checking the library versions explicitly (and we're not gonna do that, so fuck you)
#endif // Windows/VC++ vs. g++ vs Others
#ifdef LUAJIT_VERSION
#ifndef SOL_LUAJIT
#define SOL_LUAJIT
#define SOL_LUAJIT_VERSION LUAJIT_VERSION_NUM
#endif // sol luajit
#endif // luajit
#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 502
#define SOL_LUA_VERSION LUA_VERSION_NUM
#elif defined(LUA_VERSION_NUM) && LUA_VERSION_NUM == 501
#define SOL_LUA_VERSION LUA_VERSION_NUM
#elif !defined(LUA_VERSION_NUM)
// Definitely 5.0
#define SOL_LUA_VERSION 500
#else
// ??? Not sure, assume 502?
#define SOL_LUA_VERSION 502
#endif // Lua Version 502, 501 || luajit, 500
#ifdef _MSC_VER
#ifdef _DEBUG
#ifndef NDEBUG
#ifndef SOL_CHECK_ARGUMENTS
// Do not define by default: let user turn it on
//#define SOL_CHECK_ARGUMENTS
#endif // Check Arguments
#ifndef SOL_SAFE_USERTYPE
#define SOL_SAFE_USERTYPE
#endif // Safe Usertypes
#endif // NDEBUG
#endif // Debug
#ifndef _CPPUNWIND
#ifndef SOL_NO_EXCEPTIONS
#define SOL_NO_EXCEPTIONS 1
#endif
#endif // Automatic Exceptions
#ifndef _CPPRTTI
#ifndef SOL_NO_RTTI
#define SOL_NO_RTTI 1
#endif
#endif // Automatic RTTI
#elif defined(__GNUC__) || defined(__clang__)
#ifndef NDEBUG
#ifndef __OPTIMIZE__
#ifndef SOL_CHECK_ARGUMENTS
// Do not define by default: let user choose
//#define SOL_CHECK_ARGUMENTS
// But do check userdata by default:
#endif // Check Arguments
#ifndef SOL_SAFE_USERTYPE
#define SOL_SAFE_USERTYPE
#endif // Safe Usertypes
#endif // g++ optimizer flag
#endif // Not Debug
#ifndef __EXCEPTIONS
#ifndef SOL_NO_EXCEPTIONS
#define SOL_NO_EXCEPTIONS 1
#endif
#endif // No Exceptions
#ifndef __GXX_RTTI
#ifndef SOL_NO_RTII
#define SOL_NO_RTTI 1
#endif
#endif // No RTTI
#endif // vc++ || clang++/g++
#ifndef SOL_SAFE_USERTYPE
#ifdef SOL_CHECK_ARGUMENTS
#define SOL_SAFE_USERTYPE
#endif // Turn on Safety for all
#endif // Safe Usertypes
#endif // SOL_VERSION_HPP
<|endoftext|> |
<commit_before>//
// game_menu_view.cc
// AirHockey
//
// Created by Jon Sharkey on 2013-03-04.
// Copyright 2013 Sharkable. All rights reserved.
//
#include "airhockey/views/game_menu_view.h"
#include "gameengine/entities/simple_item.h"
#include "gameengine/modules/ad_engine.h"
#include "gameengine/coordinate_types.h"
#include "gameengine/sprite.h"
#include "airhockey/entities/sound_slider.h"
GameMenuView::GameMenuView(sp<GameEngine> game_engine, GameMenuViewDelegate *delegate,
bool match_finished)
: EngineView(game_engine),
delegate_(delegate) {
Init(match_finished);
}
// ButtonDelegate
void GameMenuView::ButtonPressed(Button *button) {
if (game_engine()->platform_type() == kPlatformTypeTablet) {
game_engine()->ad_engine()->RemoveAd();
}
game_engine()->PopView();
if (button == rematch_button_.get()) {
delegate_->RematchPressed();
} else if (button == menu_button_.get()) {
delegate_->MenuPressed();
} else if (button == continue_button_.get()) {
delegate_->ContinuePressed();
}
}
// private
void GameMenuView::Init(bool match_finished) {
Sprite menu_background_sprite(game_engine(), "game_menu_bg");
menu_background_.reset(new SimpleItem());
menu_background_->add_sprite(menu_background_sprite);
menu_background_->set_position(game_engine()->position("game_menu_bg"));
AddEntity(menu_background_);
GamePoint sound_slider_position = game_engine()->position("sound_slider_game_menu");
sound_slider_.reset(new SoundSlider(game_engine(), sound_slider_position));
AddEntity(sound_slider_);
if (match_finished) {
Sprite rematch_button_sprite(game_engine(), "rematch_button");
Sprite rematch_button_pressed_sprite(game_engine(), "rematch_button_pressed");
rematch_button_.reset(new Button());
rematch_button_->set_normal_sprite(rematch_button_sprite);
rematch_button_->set_pressed_sprite(rematch_button_pressed_sprite);
rematch_button_->set_position(game_engine()->position("rematch_button"));
rematch_button_->set_delegate(this);
AddEntity(rematch_button_);
} else {
Sprite continue_button_sprite(game_engine(), "continue_button");
Sprite continue_button_pressed_sprite(game_engine(), "continue_button_pressed");
continue_button_.reset(new Button());
continue_button_->set_normal_sprite(continue_button_sprite);
continue_button_->set_pressed_sprite(continue_button_pressed_sprite);
continue_button_->set_position(game_engine()->position("continue_button"));
continue_button_->set_delegate(this);
AddEntity(continue_button_);
}
Sprite menu_button_sprite(game_engine(), "menu_button");
Sprite menu_button_pressed_sprite(game_engine(), "menu_button_pressed");
menu_button_.reset(new Button());
menu_button_->set_normal_sprite(menu_button_sprite);
menu_button_->set_pressed_sprite(menu_button_pressed_sprite);
menu_button_->set_position(game_engine()->position("menu_button"));
menu_button_->set_delegate(this);
AddEntity(menu_button_);
if (game_engine()->platform_type() == kPlatformTypeTablet) {
ScreenPoint ad_position = screen_point_make((game_engine()->game_size().width - 320) / 2, 380);
game_engine()->ad_engine()->SetAdAtPoint(ad_position);
}
}
<commit_msg>Removing tablet ad for now.<commit_after>//
// game_menu_view.cc
// AirHockey
//
// Created by Jon Sharkey on 2013-03-04.
// Copyright 2013 Sharkable. All rights reserved.
//
#include "airhockey/views/game_menu_view.h"
#include "gameengine/entities/simple_item.h"
#include "gameengine/modules/ad_engine.h"
#include "gameengine/coordinate_types.h"
#include "gameengine/sprite.h"
#include "airhockey/entities/sound_slider.h"
GameMenuView::GameMenuView(sp<GameEngine> game_engine, GameMenuViewDelegate *delegate,
bool match_finished)
: EngineView(game_engine),
delegate_(delegate) {
Init(match_finished);
}
// ButtonDelegate
void GameMenuView::ButtonPressed(Button *button) {
if (game_engine()->platform_type() == kPlatformTypeTablet) {
game_engine()->ad_engine()->RemoveAd();
}
game_engine()->PopView();
if (button == rematch_button_.get()) {
delegate_->RematchPressed();
} else if (button == menu_button_.get()) {
delegate_->MenuPressed();
} else if (button == continue_button_.get()) {
delegate_->ContinuePressed();
}
}
// private
void GameMenuView::Init(bool match_finished) {
Sprite menu_background_sprite(game_engine(), "game_menu_bg");
menu_background_.reset(new SimpleItem());
menu_background_->add_sprite(menu_background_sprite);
menu_background_->set_position(game_engine()->position("game_menu_bg"));
AddEntity(menu_background_);
GamePoint sound_slider_position = game_engine()->position("sound_slider_game_menu");
sound_slider_.reset(new SoundSlider(game_engine(), sound_slider_position));
AddEntity(sound_slider_);
if (match_finished) {
Sprite rematch_button_sprite(game_engine(), "rematch_button");
Sprite rematch_button_pressed_sprite(game_engine(), "rematch_button_pressed");
rematch_button_.reset(new Button());
rematch_button_->set_normal_sprite(rematch_button_sprite);
rematch_button_->set_pressed_sprite(rematch_button_pressed_sprite);
rematch_button_->set_position(game_engine()->position("rematch_button"));
rematch_button_->set_delegate(this);
AddEntity(rematch_button_);
} else {
Sprite continue_button_sprite(game_engine(), "continue_button");
Sprite continue_button_pressed_sprite(game_engine(), "continue_button_pressed");
continue_button_.reset(new Button());
continue_button_->set_normal_sprite(continue_button_sprite);
continue_button_->set_pressed_sprite(continue_button_pressed_sprite);
continue_button_->set_position(game_engine()->position("continue_button"));
continue_button_->set_delegate(this);
AddEntity(continue_button_);
}
Sprite menu_button_sprite(game_engine(), "menu_button");
Sprite menu_button_pressed_sprite(game_engine(), "menu_button_pressed");
menu_button_.reset(new Button());
menu_button_->set_normal_sprite(menu_button_sprite);
menu_button_->set_pressed_sprite(menu_button_pressed_sprite);
menu_button_->set_position(game_engine()->position("menu_button"));
menu_button_->set_delegate(this);
AddEntity(menu_button_);
if (game_engine()->platform_type() == kPlatformTypeTablet) {
// TODO do I want this ad?
// ScreenPoint ad_position = screen_point_make((game_engine()->game_size().width - 320) / 2, 380);
// game_engine()->ad_engine()->SetAdAtPoint(ad_position);
}
}
<|endoftext|> |
<commit_before>/*
Queue World is copyright (c) 2014 Ross Bencina
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 "QwMpmcPopAllLifoStack.h"
#include "catch.hpp"
namespace {
struct TestNode{
TestNode *links_[2];
enum { LINK_INDEX_1, LINK_COUNT };
int value;
TestNode()
: value( 0 )
{
for( int i=0; i < LINK_COUNT; ++i )
links_[i] = 0;
}
};
typedef QwMpmcPopAllLifoStack<TestNode*, TestNode::LINK_INDEX_1> TestMpmcPopAllLifoStack;
} // end anonymous namespace
TEST_CASE( "qw/mpmc_pop_all_lifo_stack/single-threaded", "QwMpmcPopAllLifoStack single threaded test" ) {
TestNode nodes[10];
TestNode *a = &nodes[0];
TestNode *b = &nodes[1];
TestNode *c = &nodes[2];
TestNode *d = &nodes[3];
TestMpmcPopAllLifoStack stack;
REQUIRE( stack.empty() );
REQUIRE( stack.pop_all() == (TestNode*)NULL );
// void push( node_ptr_type node )
stack.push(a);
REQUIRE( !stack.empty() );
REQUIRE( stack.pop_all() == a );
REQUIRE( stack.empty() );
REQUIRE( stack.pop_all() == (TestNode*)NULL );
for (int i=0; i < 10; ++i)
stack.push(&nodes[i]);
REQUIRE( !stack.empty() );
{ // verify that pop-all returns items in LIFO order:
TestNode *xs = stack.pop_all();
REQUIRE( stack.empty() );
for (int i=9; i >=0; --i) {
REQUIRE( xs == &nodes[i] );
TestNode *next = xs->links_[TestNode::LINK_INDEX_1];
// zero links as we go. in test mode the data structure requires all links to be zeroed
xs->links_[TestNode::LINK_INDEX_1] = 0;
xs = next;
}
REQUIRE( xs == (TestNode*)NULL );
}
// void push( node_ptr_type node, bool& wasEmpty )
REQUIRE( stack.empty() );
bool wasEmpty=false;
stack.push(a,wasEmpty);
REQUIRE( wasEmpty == true );
stack.push(b,wasEmpty);
REQUIRE( wasEmpty == false );
REQUIRE( stack.pop_all() == b );
REQUIRE( stack.empty() );
a->links_[TestNode::LINK_INDEX_1] = 0;
b->links_[TestNode::LINK_INDEX_1] = 0;
// void push_multiple( node_ptr_type front, node_ptr_type back )
a->links_[TestNode::LINK_INDEX_1] = b;
b->links_[TestNode::LINK_INDEX_1] = c;
c->links_[TestNode::LINK_INDEX_1] = 0;
stack.push_multiple(a, c);
REQUIRE( !stack.empty() );
{ // verify that pop-all returns items in LIFO order:
TestNode *xs = stack.pop_all();
REQUIRE( stack.empty() );
REQUIRE( xs == a );
REQUIRE( xs->links_[TestNode::LINK_INDEX_1] == b );
REQUIRE( xs->links_[TestNode::LINK_INDEX_1]->links_[TestNode::LINK_INDEX_1] == c );
a->links_[TestNode::LINK_INDEX_1] = 0;
b->links_[TestNode::LINK_INDEX_1] = 0;
c->links_[TestNode::LINK_INDEX_1] = 0;
}
// test push_multiple(...,wasEmpty)
a->links_[TestNode::LINK_INDEX_1] = b;
b->links_[TestNode::LINK_INDEX_1] = c;
c->links_[TestNode::LINK_INDEX_1] = 0;
d->links_[TestNode::LINK_INDEX_1] = 0;
REQUIRE( stack.empty() );
wasEmpty = false;
stack.push_multiple(a, c, wasEmpty);
REQUIRE( wasEmpty == true );
stack.push_multiple(d, d, wasEmpty);
REQUIRE( wasEmpty == false );
{ // verify that pop-all returns items in LIFO order:
TestNode *xs = stack.pop_all();
REQUIRE( stack.empty() );
REQUIRE( xs == d );
REQUIRE( xs->links_[TestNode::LINK_INDEX_1] == a );
REQUIRE( xs->links_[TestNode::LINK_INDEX_1]->links_[TestNode::LINK_INDEX_1] == b );
REQUIRE( xs->links_[TestNode::LINK_INDEX_1]->links_[TestNode::LINK_INDEX_1]->links_[TestNode::LINK_INDEX_1] == c );
a->links_[TestNode::LINK_INDEX_1] = 0;
b->links_[TestNode::LINK_INDEX_1] = 0;
c->links_[TestNode::LINK_INDEX_1] = 0;
d->links_[TestNode::LINK_INDEX_1] = 0;
}
}
#if __cplusplus >= 201103L // C++11. concurrency test using C++11 threads.
#include <cstddef> // size_t
#include <cstdlib> // rand and srand
#include <ctime> // time()
#include <thread>
namespace {
static const std::size_t TEST_THREAD_COUNT=15;
static const std::size_t TEST_STACK_COUNT=5;
static const std::size_t TEST_PER_STACK_NODE_COUNT=200;
static const std::size_t THREAD_ITERATIONS=100000;
//static const std::size_t THREAD_ITERATIONS=10000000;
static TestMpmcPopAllLifoStack *testStacks_[ TEST_THREAD_COUNT ];
static unsigned testThreadProc()
{
std::srand(static_cast<unsigned int>(std::time(0)));
for( std::size_t i=0; i < THREAD_ITERATIONS; ++i ){
// randomly pop all from one stack and push on to others
TestNode *all = testStacks_[ static_cast<std::size_t>(rand()) % TEST_STACK_COUNT ]->pop_all();
while( all ){
TestNode *n = all;
all = all->links_[TestNode::LINK_INDEX_1];
#if (QW_VALIDATE_NODE_LINKS == 1)
n->links_[TestNode::LINK_INDEX_1] = 0; // validation code in push expects link to be cleared on entry
#endif
testStacks_[ static_cast<std::size_t>(rand()) % TEST_STACK_COUNT ]->push(n);
}
}
return 0;
}
}
TEST_CASE( "qw/mpmc_pop_all_lifo_stack/multi-threaded", "[slow][vslow][fuzz] QwMpmcPopAllLifoStack multi-threaded randomised sanity test" ) {
int allocatedNodeCount = 0;
for( std::size_t i=0; i < TEST_STACK_COUNT; ++i ){
testStacks_[i] = new TestMpmcPopAllLifoStack;
for( std::size_t j=0; j < TEST_PER_STACK_NODE_COUNT; ++j ){
testStacks_[i]->push( new TestNode );
++allocatedNodeCount;
}
}
std::thread* threads[TEST_THREAD_COUNT];
for( std::size_t i=0; i < TEST_THREAD_COUNT; ++i ){
threads[i] = new std::thread(testThreadProc);
}
for( std::size_t i=0; i < TEST_THREAD_COUNT; ++i ){
threads[i]->join();
delete threads[i];
}
int freedNodeCount = 0;
for( std::size_t i=0; i < TEST_STACK_COUNT; ++i ){
TestNode *all = testStacks_[i]->pop_all();
while( all ){
TestNode *n = all;
all = all->links_[TestNode::LINK_INDEX_1];
delete n;
++freedNodeCount;
}
delete testStacks_[i];
}
REQUIRE( freedNodeCount == allocatedNodeCount );
}
#endif // end __cplusplus >= 201103L
<commit_msg>C++11 migration: remove conditional compilation of std::thread based test for QwMpmcPopAllLifoStack<commit_after>/*
Queue World is copyright (c) 2014 Ross Bencina
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 "QwMpmcPopAllLifoStack.h"
#include "catch.hpp"
#include <cstddef> // size_t
#include <cstdlib> // rand and srand
#include <ctime> // time()
#include <thread>
namespace {
struct TestNode{
TestNode *links_[2];
enum { LINK_INDEX_1, LINK_COUNT };
int value;
TestNode()
: value( 0 )
{
for( int i=0; i < LINK_COUNT; ++i )
links_[i] = 0;
}
};
typedef QwMpmcPopAllLifoStack<TestNode*, TestNode::LINK_INDEX_1> TestMpmcPopAllLifoStack;
} // end anonymous namespace
TEST_CASE( "qw/mpmc_pop_all_lifo_stack/single-threaded", "QwMpmcPopAllLifoStack single threaded test" ) {
TestNode nodes[10];
TestNode *a = &nodes[0];
TestNode *b = &nodes[1];
TestNode *c = &nodes[2];
TestNode *d = &nodes[3];
TestMpmcPopAllLifoStack stack;
REQUIRE( stack.empty() );
REQUIRE( stack.pop_all() == (TestNode*)NULL );
// void push( node_ptr_type node )
stack.push(a);
REQUIRE( !stack.empty() );
REQUIRE( stack.pop_all() == a );
REQUIRE( stack.empty() );
REQUIRE( stack.pop_all() == (TestNode*)NULL );
for (int i=0; i < 10; ++i)
stack.push(&nodes[i]);
REQUIRE( !stack.empty() );
{ // verify that pop-all returns items in LIFO order:
TestNode *xs = stack.pop_all();
REQUIRE( stack.empty() );
for (int i=9; i >=0; --i) {
REQUIRE( xs == &nodes[i] );
TestNode *next = xs->links_[TestNode::LINK_INDEX_1];
// zero links as we go. in test mode the data structure requires all links to be zeroed
xs->links_[TestNode::LINK_INDEX_1] = 0;
xs = next;
}
REQUIRE( xs == (TestNode*)NULL );
}
// void push( node_ptr_type node, bool& wasEmpty )
REQUIRE( stack.empty() );
bool wasEmpty=false;
stack.push(a,wasEmpty);
REQUIRE( wasEmpty == true );
stack.push(b,wasEmpty);
REQUIRE( wasEmpty == false );
REQUIRE( stack.pop_all() == b );
REQUIRE( stack.empty() );
a->links_[TestNode::LINK_INDEX_1] = 0;
b->links_[TestNode::LINK_INDEX_1] = 0;
// void push_multiple( node_ptr_type front, node_ptr_type back )
a->links_[TestNode::LINK_INDEX_1] = b;
b->links_[TestNode::LINK_INDEX_1] = c;
c->links_[TestNode::LINK_INDEX_1] = 0;
stack.push_multiple(a, c);
REQUIRE( !stack.empty() );
{ // verify that pop-all returns items in LIFO order:
TestNode *xs = stack.pop_all();
REQUIRE( stack.empty() );
REQUIRE( xs == a );
REQUIRE( xs->links_[TestNode::LINK_INDEX_1] == b );
REQUIRE( xs->links_[TestNode::LINK_INDEX_1]->links_[TestNode::LINK_INDEX_1] == c );
a->links_[TestNode::LINK_INDEX_1] = 0;
b->links_[TestNode::LINK_INDEX_1] = 0;
c->links_[TestNode::LINK_INDEX_1] = 0;
}
// test push_multiple(...,wasEmpty)
a->links_[TestNode::LINK_INDEX_1] = b;
b->links_[TestNode::LINK_INDEX_1] = c;
c->links_[TestNode::LINK_INDEX_1] = 0;
d->links_[TestNode::LINK_INDEX_1] = 0;
REQUIRE( stack.empty() );
wasEmpty = false;
stack.push_multiple(a, c, wasEmpty);
REQUIRE( wasEmpty == true );
stack.push_multiple(d, d, wasEmpty);
REQUIRE( wasEmpty == false );
{ // verify that pop-all returns items in LIFO order:
TestNode *xs = stack.pop_all();
REQUIRE( stack.empty() );
REQUIRE( xs == d );
REQUIRE( xs->links_[TestNode::LINK_INDEX_1] == a );
REQUIRE( xs->links_[TestNode::LINK_INDEX_1]->links_[TestNode::LINK_INDEX_1] == b );
REQUIRE( xs->links_[TestNode::LINK_INDEX_1]->links_[TestNode::LINK_INDEX_1]->links_[TestNode::LINK_INDEX_1] == c );
a->links_[TestNode::LINK_INDEX_1] = 0;
b->links_[TestNode::LINK_INDEX_1] = 0;
c->links_[TestNode::LINK_INDEX_1] = 0;
d->links_[TestNode::LINK_INDEX_1] = 0;
}
}
namespace {
static const std::size_t TEST_THREAD_COUNT=15;
static const std::size_t TEST_STACK_COUNT=5;
static const std::size_t TEST_PER_STACK_NODE_COUNT=200;
static const std::size_t THREAD_ITERATIONS=100000;
//static const std::size_t THREAD_ITERATIONS=10000000;
static TestMpmcPopAllLifoStack *testStacks_[ TEST_THREAD_COUNT ];
static unsigned testThreadProc()
{
std::srand(static_cast<unsigned int>(std::time(0)));
for( std::size_t i=0; i < THREAD_ITERATIONS; ++i ){
// randomly pop all from one stack and push on to others
TestNode *all = testStacks_[ static_cast<std::size_t>(rand()) % TEST_STACK_COUNT ]->pop_all();
while( all ){
TestNode *n = all;
all = all->links_[TestNode::LINK_INDEX_1];
#if (QW_VALIDATE_NODE_LINKS == 1)
n->links_[TestNode::LINK_INDEX_1] = 0; // validation code in push expects link to be cleared on entry
#endif
testStacks_[ static_cast<std::size_t>(rand()) % TEST_STACK_COUNT ]->push(n);
}
}
return 0;
}
}
TEST_CASE( "qw/mpmc_pop_all_lifo_stack/multi-threaded", "[slow][vslow][fuzz] QwMpmcPopAllLifoStack multi-threaded randomised sanity test" ) {
int allocatedNodeCount = 0;
for( std::size_t i=0; i < TEST_STACK_COUNT; ++i ){
testStacks_[i] = new TestMpmcPopAllLifoStack;
for( std::size_t j=0; j < TEST_PER_STACK_NODE_COUNT; ++j ){
testStacks_[i]->push( new TestNode );
++allocatedNodeCount;
}
}
std::thread* threads[TEST_THREAD_COUNT];
for( std::size_t i=0; i < TEST_THREAD_COUNT; ++i ){
threads[i] = new std::thread(testThreadProc);
}
for( std::size_t i=0; i < TEST_THREAD_COUNT; ++i ){
threads[i]->join();
delete threads[i];
}
int freedNodeCount = 0;
for( std::size_t i=0; i < TEST_STACK_COUNT; ++i ){
TestNode *all = testStacks_[i]->pop_all();
while( all ){
TestNode *n = all;
all = all->links_[TestNode::LINK_INDEX_1];
delete n;
++freedNodeCount;
}
delete testStacks_[i];
}
REQUIRE( freedNodeCount == allocatedNodeCount );
}
<|endoftext|> |
<commit_before>//Copyright (c) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include <numeric>
#include "TimeEstimateCalculatorTest.h"
#include "../src/PrintFeature.h" //We get time estimates per print feature.
#include "../src/settings/types/Duration.h"
namespace cura
{
#define MINIMUM_PLANNER_SPEED 0.05 // mm/sec
#define EPSILON 0.00001 //Allowed error in comparing floating point values.
CPPUNIT_TEST_SUITE_REGISTRATION(TimeEstimateCalculatorTest);
void TimeEstimateCalculatorTest::setUp()
{
//Reset the calculator, but not by using its reset() function. That would be broken if the reset() function is broken.
calculator = TimeEstimateCalculator();
um3.add("machine_max_feedrate_x", "300");
um3.add("machine_max_feedrate_y", "300");
um3.add("machine_max_feedrate_z", "40");
um3.add("machine_max_feedrate_e", "45");
um3.add("machine_max_acceleration_x", "9000");
um3.add("machine_max_acceleration_y", "9000");
um3.add("machine_max_acceleration_z", "100");
um3.add("machine_max_acceleration_e", "10000");
um3.add("machine_max_jerk_xy", "20");
um3.add("machine_max_jerk_z", "0.4");
um3.add("machine_max_jerk_e", "5");
um3.add("machine_minimum_feedrate", "0");
um3.add("machine_acceleration", "3000");
always_50.add("machine_max_feedrate_x", "50");
always_50.add("machine_max_feedrate_y", "50");
always_50.add("machine_max_feedrate_z", "50");
always_50.add("machine_max_feedrate_e", "50");
always_50.add("machine_max_acceleration_x", "50");
always_50.add("machine_max_acceleration_y", "50");
always_50.add("machine_max_acceleration_z", "50");
always_50.add("machine_max_acceleration_e", "50");
always_50.add("machine_max_jerk_xy", "1000");
always_50.add("machine_max_jerk_z", "1000");
always_50.add("machine_max_jerk_e", "1000");
always_50.add("machine_minimum_feedrate", "0");
always_50.add("machine_acceleration", "50");
jerkless.add("machine_max_feedrate_x", "50");
jerkless.add("machine_max_feedrate_y", "50");
jerkless.add("machine_max_feedrate_z", "50");
jerkless.add("machine_max_feedrate_e", "50");
jerkless.add("machine_max_acceleration_x", "50");
jerkless.add("machine_max_acceleration_y", "50");
jerkless.add("machine_max_acceleration_z", "50");
jerkless.add("machine_max_acceleration_e", "50");
jerkless.add("machine_max_jerk_xy", "0");
jerkless.add("machine_max_jerk_z", "0");
jerkless.add("machine_max_jerk_e", "0");
jerkless.add("machine_minimum_feedrate", "0");
jerkless.add("machine_acceleration", "50");
calculator.setFirmwareDefaults(um3);
calculator.setPosition(TimeEstimateCalculator::Position(0, 0, 0, 0));
}
void TimeEstimateCalculatorTest::addTime()
{
calculator.addTime(2);
std::vector<Duration> result = calculator.calculate();
CPPUNIT_ASSERT_DOUBLES_EQUAL(Duration(2.0), result[static_cast<size_t>(PrintFeatureType::NoneType)], EPSILON);
calculator.addTime(3); //Has to add up, not replace.
result = calculator.calculate();
CPPUNIT_ASSERT_DOUBLES_EQUAL(Duration(5.0), result[static_cast<size_t>(PrintFeatureType::NoneType)], EPSILON);
calculator.addTime(-7);
result = calculator.calculate();
CPPUNIT_ASSERT_DOUBLES_EQUAL(Duration(5.0), result[static_cast<size_t>(PrintFeatureType::NoneType)], EPSILON); //Due to how Duration works, it can never go lower.
}
void TimeEstimateCalculatorTest::startWithZero()
{
const std::vector<Duration> result = calculator.calculate();
CPPUNIT_ASSERT_DOUBLES_EQUAL(static_cast<size_t>(PrintFeatureType::NumPrintFeatureTypes), result.size(), EPSILON);
for (const Duration estimate : result)
{
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Time estimates must be zero before anything has been planned.", Duration(0.0), estimate, EPSILON);
}
}
void TimeEstimateCalculatorTest::moveToCurrentLocation()
{
const TimeEstimateCalculator::Position position(1000, 2000, 3000, 4000);
calculator.setPosition(position);
std::vector<Duration> result = calculator.calculate();
Duration estimate = std::accumulate(result.begin(), result.end(), Duration(0.0));
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("setPosition should not add any time to the estimate.", Duration(0.0), estimate, EPSILON);
calculator.plan(position, Velocity(10), PrintFeatureType::Infill);
result = calculator.calculate();
estimate = std::accumulate(result.begin(), result.end(), Duration(0.0));
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Moving to the same location as where you already were should not cost any time.", Duration(0.0), estimate, EPSILON);
}
void TimeEstimateCalculatorTest::singleLineOnlyJerk()
{
calculator.setFirmwareDefaults(always_50);
const TimeEstimateCalculator::Position destination(1000, 0, 0, 0);
/*
* This line:
* Accelerate instantly from 0 to 50 mm/s because of jerk.
* Travel at 50 mm/s throughout the line.
* Decelerate to minimum planner speed because at the end of the planner, jerk is not used.
*/
calculator.plan(destination, 50.0, PrintFeatureType::Infill);
//Deceleration distance is 1/2 at² + vt. We decelerate at 50mm/s for almost a second, ending at a speed of MINIMUM_PLANNER_SPEED.
const double t = (50.0 - MINIMUM_PLANNER_SPEED) / 50.0;
const double decelerate_distance = 0.5 * 50.0 * t * t + MINIMUM_PLANNER_SPEED * t;
const double cruise_distance = 1000.0 - decelerate_distance;
const std::vector<Duration> result = calculator.calculate();
CPPUNIT_ASSERT_DOUBLES_EQUAL(
Duration(cruise_distance / 50.0 + t), //1000mm at 50mm/s, then decelerate for almost one second.
result[static_cast<size_t>(PrintFeatureType::Infill)],
EPSILON
);
}
void TimeEstimateCalculatorTest::doubleLineOnlyJerk()
{
calculator.setFirmwareDefaults(always_50);
/*
* These lines:
* Accelerate instantly from 0 to 50mm/s because of jerk.
* Travel at 50 mm/s throughout the first line.
* At the end of the first line, continue at 50 mm/s with the second line. No acceleration is needed.
* Travel at 50 mm/s throughout the second line.
* Decelerate to minimum planner speed because at the end of the planner, jerk is not used.
*/
const TimeEstimateCalculator::Position destination_1(1000, 0, 0, 0);
calculator.plan(destination_1, 50.0, PrintFeatureType::Infill);
const TimeEstimateCalculator::Position destination_2(2000, 0, 0, 0);
calculator.plan(destination_2, 50.0, PrintFeatureType::Infill);
//Deceleration distance is 1/2 at² + vt. We decelerate at 50mm/s for almost a second, ending at a speed of MINIMUM_PLANNER_SPEED.
const double t = (50.0 - MINIMUM_PLANNER_SPEED) / 50.0;
const double decelerate_distance = 0.5 * 50.0 * t * t + MINIMUM_PLANNER_SPEED * t;
const double cruise_distance = 2000.0 - decelerate_distance;
const std::vector<Duration> result = calculator.calculate();
CPPUNIT_ASSERT_DOUBLES_EQUAL(
Duration(cruise_distance / 50.0 + t), //2000mm at 50mm/s, then decelerate for almost one second.
result[static_cast<size_t>(PrintFeatureType::Infill)],
EPSILON
);
}
void TimeEstimateCalculatorTest::singleLineNoJerk()
{
calculator.setFirmwareDefaults(jerkless);
/*
* This line:
* Accelerate from 0 to 50mm/s in one second.
* At the end, decelerate from 50 to 0mm/s in one second again.
* In the middle, cruise at 50mm/s.
*/
const TimeEstimateCalculator::Position destination(1000, 0, 0, 0);
calculator.plan(destination, 50.0, PrintFeatureType::Infill);
//Distance needed to accelerate: 1/2 at² + vt. We accelerate at 50mm/s². No initial velocity, but we decelerate to MINIMUM_PLANNER_SPEED.
const double accelerate_distance = 0.5 * 50 * 1 * 1 + 0 * 1;
const double decelerate_t = (50.0 - MINIMUM_PLANNER_SPEED) / 50.0;
const double decelerate_distance = 0.5 * 50.0 * decelerate_t * decelerate_t + MINIMUM_PLANNER_SPEED * decelerate_t;
const double cruise_distance = 1000.0 - accelerate_distance - decelerate_distance;
const std::vector<Duration> result = calculator.calculate();
CPPUNIT_ASSERT_DOUBLES_EQUAL(
Duration(1.0 + cruise_distance / 50.0 + decelerate_t), //Accelerate, cruise, decelerate.
result[static_cast<size_t>(PrintFeatureType::Infill)],
EPSILON
);
}
void TimeEstimateCalculatorTest::doubleLineNoJerk()
{
calculator.setFirmwareDefaults(jerkless);
/*
* These lines:
* Accelerate from 0 to 50mm/s in one second.
* Cruise at 50mm/s to the halfway point. It won't need to decelerate since the next line is in the same direction.
* Cruise at 50mm/s to just before the end.
* Decelerate from 50 to 0mm/s in one second.
*/
const TimeEstimateCalculator::Position destination_1(1000, 0, 0, 0);
calculator.plan(destination_1, 50.0, PrintFeatureType::Infill);
const TimeEstimateCalculator::Position destination_2(2000, 0, 0, 0);
calculator.plan(destination_2, 50.0, PrintFeatureType::Infill);
//Distance needed to accelerate: 1/2 at² + vt. We accelerate at 50mm/s². No initial velocity, but we decelerate to MINIMUM_PLANNER_SPEED.
const double accelerate_distance = 0.5 * 50 * 1 * 1 + 0 * 1;
const double decelerate_t = (50.0 - MINIMUM_PLANNER_SPEED) / 50.0;
const double decelerate_distance = 0.5 * 50.0 * decelerate_t * decelerate_t + MINIMUM_PLANNER_SPEED * decelerate_t;
const double cruise_distance = 2000.0 - accelerate_distance - decelerate_distance;
const std::vector<Duration> result = calculator.calculate();
CPPUNIT_ASSERT_DOUBLES_EQUAL(
Duration(1.0 + cruise_distance / 50.0 + decelerate_t), //Accelerate, cruise, decelerate.
result[static_cast<size_t>(PrintFeatureType::Infill)],
EPSILON
);
}
void TimeEstimateCalculatorTest::diagonalLineNoJerk()
{
calculator.setFirmwareDefaults(jerkless);
/*
* This line:
* Total acceleration will be 50mm/s, since the minimum of X and Y acceleration is 50 (both are 50 in fact).
* Accelerate the X and Y axes from 0 to 50mm/s in 1 second.
* Cruise at 50mm/s towards the destination.
* Decelerate the X and Y axes from 50mm/s to the minimum planner speed in less than one second.
*/
const TimeEstimateCalculator::Position destination(1000, 1000, 0, 0);
calculator.plan(destination, 50.0, PrintFeatureType::Infill);
//Distance needed to accelerate: 1/2 at² + vt. We accelerate at 50mm/s². No initial velocity, but we decelerate to MINIMUM_PLANNER_SPEED.
const double accelerate_distance = 0.5 * 50.0 * 1.0 * 1.0 + 0.0 * 1.0;
const double decelerate_t = (50.0 - MINIMUM_PLANNER_SPEED) / 50.0;
const double decelerate_distance = 0.5 * 50.0 * decelerate_t * decelerate_t + MINIMUM_PLANNER_SPEED * decelerate_t;
const double cruise_distance = std::sqrt(2.0) * 1000.0 - accelerate_distance - decelerate_distance; //Thank you Mr. Pythagoras.
const std::vector<Duration> result = calculator.calculate();
CPPUNIT_ASSERT_DOUBLES_EQUAL(
Duration(1.0 + cruise_distance / 50.0 + decelerate_t), //Accelerate, cruise, decelerate.
result[static_cast<size_t>(PrintFeatureType::Infill)],
EPSILON
);
}
} //namespace cura<commit_msg>Add missing header file in TimeEstimateCalculatorTest<commit_after>//Copyright (c) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include <cmath>
#include <numeric>
#include "TimeEstimateCalculatorTest.h"
#include "../src/PrintFeature.h" //We get time estimates per print feature.
#include "../src/settings/types/Duration.h"
namespace cura
{
#define MINIMUM_PLANNER_SPEED 0.05 // mm/sec
#define EPSILON 0.00001 //Allowed error in comparing floating point values.
CPPUNIT_TEST_SUITE_REGISTRATION(TimeEstimateCalculatorTest);
void TimeEstimateCalculatorTest::setUp()
{
//Reset the calculator, but not by using its reset() function. That would be broken if the reset() function is broken.
calculator = TimeEstimateCalculator();
um3.add("machine_max_feedrate_x", "300");
um3.add("machine_max_feedrate_y", "300");
um3.add("machine_max_feedrate_z", "40");
um3.add("machine_max_feedrate_e", "45");
um3.add("machine_max_acceleration_x", "9000");
um3.add("machine_max_acceleration_y", "9000");
um3.add("machine_max_acceleration_z", "100");
um3.add("machine_max_acceleration_e", "10000");
um3.add("machine_max_jerk_xy", "20");
um3.add("machine_max_jerk_z", "0.4");
um3.add("machine_max_jerk_e", "5");
um3.add("machine_minimum_feedrate", "0");
um3.add("machine_acceleration", "3000");
always_50.add("machine_max_feedrate_x", "50");
always_50.add("machine_max_feedrate_y", "50");
always_50.add("machine_max_feedrate_z", "50");
always_50.add("machine_max_feedrate_e", "50");
always_50.add("machine_max_acceleration_x", "50");
always_50.add("machine_max_acceleration_y", "50");
always_50.add("machine_max_acceleration_z", "50");
always_50.add("machine_max_acceleration_e", "50");
always_50.add("machine_max_jerk_xy", "1000");
always_50.add("machine_max_jerk_z", "1000");
always_50.add("machine_max_jerk_e", "1000");
always_50.add("machine_minimum_feedrate", "0");
always_50.add("machine_acceleration", "50");
jerkless.add("machine_max_feedrate_x", "50");
jerkless.add("machine_max_feedrate_y", "50");
jerkless.add("machine_max_feedrate_z", "50");
jerkless.add("machine_max_feedrate_e", "50");
jerkless.add("machine_max_acceleration_x", "50");
jerkless.add("machine_max_acceleration_y", "50");
jerkless.add("machine_max_acceleration_z", "50");
jerkless.add("machine_max_acceleration_e", "50");
jerkless.add("machine_max_jerk_xy", "0");
jerkless.add("machine_max_jerk_z", "0");
jerkless.add("machine_max_jerk_e", "0");
jerkless.add("machine_minimum_feedrate", "0");
jerkless.add("machine_acceleration", "50");
calculator.setFirmwareDefaults(um3);
calculator.setPosition(TimeEstimateCalculator::Position(0, 0, 0, 0));
}
void TimeEstimateCalculatorTest::addTime()
{
calculator.addTime(2);
std::vector<Duration> result = calculator.calculate();
CPPUNIT_ASSERT_DOUBLES_EQUAL(Duration(2.0), result[static_cast<size_t>(PrintFeatureType::NoneType)], EPSILON);
calculator.addTime(3); //Has to add up, not replace.
result = calculator.calculate();
CPPUNIT_ASSERT_DOUBLES_EQUAL(Duration(5.0), result[static_cast<size_t>(PrintFeatureType::NoneType)], EPSILON);
calculator.addTime(-7);
result = calculator.calculate();
CPPUNIT_ASSERT_DOUBLES_EQUAL(Duration(5.0), result[static_cast<size_t>(PrintFeatureType::NoneType)], EPSILON); //Due to how Duration works, it can never go lower.
}
void TimeEstimateCalculatorTest::startWithZero()
{
const std::vector<Duration> result = calculator.calculate();
CPPUNIT_ASSERT_DOUBLES_EQUAL(static_cast<size_t>(PrintFeatureType::NumPrintFeatureTypes), result.size(), EPSILON);
for (const Duration estimate : result)
{
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Time estimates must be zero before anything has been planned.", Duration(0.0), estimate, EPSILON);
}
}
void TimeEstimateCalculatorTest::moveToCurrentLocation()
{
const TimeEstimateCalculator::Position position(1000, 2000, 3000, 4000);
calculator.setPosition(position);
std::vector<Duration> result = calculator.calculate();
Duration estimate = std::accumulate(result.begin(), result.end(), Duration(0.0));
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("setPosition should not add any time to the estimate.", Duration(0.0), estimate, EPSILON);
calculator.plan(position, Velocity(10), PrintFeatureType::Infill);
result = calculator.calculate();
estimate = std::accumulate(result.begin(), result.end(), Duration(0.0));
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Moving to the same location as where you already were should not cost any time.", Duration(0.0), estimate, EPSILON);
}
void TimeEstimateCalculatorTest::singleLineOnlyJerk()
{
calculator.setFirmwareDefaults(always_50);
const TimeEstimateCalculator::Position destination(1000, 0, 0, 0);
/*
* This line:
* Accelerate instantly from 0 to 50 mm/s because of jerk.
* Travel at 50 mm/s throughout the line.
* Decelerate to minimum planner speed because at the end of the planner, jerk is not used.
*/
calculator.plan(destination, 50.0, PrintFeatureType::Infill);
//Deceleration distance is 1/2 at² + vt. We decelerate at 50mm/s for almost a second, ending at a speed of MINIMUM_PLANNER_SPEED.
const double t = (50.0 - MINIMUM_PLANNER_SPEED) / 50.0;
const double decelerate_distance = 0.5 * 50.0 * t * t + MINIMUM_PLANNER_SPEED * t;
const double cruise_distance = 1000.0 - decelerate_distance;
const std::vector<Duration> result = calculator.calculate();
CPPUNIT_ASSERT_DOUBLES_EQUAL(
Duration(cruise_distance / 50.0 + t), //1000mm at 50mm/s, then decelerate for almost one second.
result[static_cast<size_t>(PrintFeatureType::Infill)],
EPSILON
);
}
void TimeEstimateCalculatorTest::doubleLineOnlyJerk()
{
calculator.setFirmwareDefaults(always_50);
/*
* These lines:
* Accelerate instantly from 0 to 50mm/s because of jerk.
* Travel at 50 mm/s throughout the first line.
* At the end of the first line, continue at 50 mm/s with the second line. No acceleration is needed.
* Travel at 50 mm/s throughout the second line.
* Decelerate to minimum planner speed because at the end of the planner, jerk is not used.
*/
const TimeEstimateCalculator::Position destination_1(1000, 0, 0, 0);
calculator.plan(destination_1, 50.0, PrintFeatureType::Infill);
const TimeEstimateCalculator::Position destination_2(2000, 0, 0, 0);
calculator.plan(destination_2, 50.0, PrintFeatureType::Infill);
//Deceleration distance is 1/2 at² + vt. We decelerate at 50mm/s for almost a second, ending at a speed of MINIMUM_PLANNER_SPEED.
const double t = (50.0 - MINIMUM_PLANNER_SPEED) / 50.0;
const double decelerate_distance = 0.5 * 50.0 * t * t + MINIMUM_PLANNER_SPEED * t;
const double cruise_distance = 2000.0 - decelerate_distance;
const std::vector<Duration> result = calculator.calculate();
CPPUNIT_ASSERT_DOUBLES_EQUAL(
Duration(cruise_distance / 50.0 + t), //2000mm at 50mm/s, then decelerate for almost one second.
result[static_cast<size_t>(PrintFeatureType::Infill)],
EPSILON
);
}
void TimeEstimateCalculatorTest::singleLineNoJerk()
{
calculator.setFirmwareDefaults(jerkless);
/*
* This line:
* Accelerate from 0 to 50mm/s in one second.
* At the end, decelerate from 50 to 0mm/s in one second again.
* In the middle, cruise at 50mm/s.
*/
const TimeEstimateCalculator::Position destination(1000, 0, 0, 0);
calculator.plan(destination, 50.0, PrintFeatureType::Infill);
//Distance needed to accelerate: 1/2 at² + vt. We accelerate at 50mm/s². No initial velocity, but we decelerate to MINIMUM_PLANNER_SPEED.
const double accelerate_distance = 0.5 * 50 * 1 * 1 + 0 * 1;
const double decelerate_t = (50.0 - MINIMUM_PLANNER_SPEED) / 50.0;
const double decelerate_distance = 0.5 * 50.0 * decelerate_t * decelerate_t + MINIMUM_PLANNER_SPEED * decelerate_t;
const double cruise_distance = 1000.0 - accelerate_distance - decelerate_distance;
const std::vector<Duration> result = calculator.calculate();
CPPUNIT_ASSERT_DOUBLES_EQUAL(
Duration(1.0 + cruise_distance / 50.0 + decelerate_t), //Accelerate, cruise, decelerate.
result[static_cast<size_t>(PrintFeatureType::Infill)],
EPSILON
);
}
void TimeEstimateCalculatorTest::doubleLineNoJerk()
{
calculator.setFirmwareDefaults(jerkless);
/*
* These lines:
* Accelerate from 0 to 50mm/s in one second.
* Cruise at 50mm/s to the halfway point. It won't need to decelerate since the next line is in the same direction.
* Cruise at 50mm/s to just before the end.
* Decelerate from 50 to 0mm/s in one second.
*/
const TimeEstimateCalculator::Position destination_1(1000, 0, 0, 0);
calculator.plan(destination_1, 50.0, PrintFeatureType::Infill);
const TimeEstimateCalculator::Position destination_2(2000, 0, 0, 0);
calculator.plan(destination_2, 50.0, PrintFeatureType::Infill);
//Distance needed to accelerate: 1/2 at² + vt. We accelerate at 50mm/s². No initial velocity, but we decelerate to MINIMUM_PLANNER_SPEED.
const double accelerate_distance = 0.5 * 50 * 1 * 1 + 0 * 1;
const double decelerate_t = (50.0 - MINIMUM_PLANNER_SPEED) / 50.0;
const double decelerate_distance = 0.5 * 50.0 * decelerate_t * decelerate_t + MINIMUM_PLANNER_SPEED * decelerate_t;
const double cruise_distance = 2000.0 - accelerate_distance - decelerate_distance;
const std::vector<Duration> result = calculator.calculate();
CPPUNIT_ASSERT_DOUBLES_EQUAL(
Duration(1.0 + cruise_distance / 50.0 + decelerate_t), //Accelerate, cruise, decelerate.
result[static_cast<size_t>(PrintFeatureType::Infill)],
EPSILON
);
}
void TimeEstimateCalculatorTest::diagonalLineNoJerk()
{
calculator.setFirmwareDefaults(jerkless);
/*
* This line:
* Total acceleration will be 50mm/s, since the minimum of X and Y acceleration is 50 (both are 50 in fact).
* Accelerate the X and Y axes from 0 to 50mm/s in 1 second.
* Cruise at 50mm/s towards the destination.
* Decelerate the X and Y axes from 50mm/s to the minimum planner speed in less than one second.
*/
const TimeEstimateCalculator::Position destination(1000, 1000, 0, 0);
calculator.plan(destination, 50.0, PrintFeatureType::Infill);
//Distance needed to accelerate: 1/2 at² + vt. We accelerate at 50mm/s². No initial velocity, but we decelerate to MINIMUM_PLANNER_SPEED.
const double accelerate_distance = 0.5 * 50.0 * 1.0 * 1.0 + 0.0 * 1.0;
const double decelerate_t = (50.0 - MINIMUM_PLANNER_SPEED) / 50.0;
const double decelerate_distance = 0.5 * 50.0 * decelerate_t * decelerate_t + MINIMUM_PLANNER_SPEED * decelerate_t;
const double cruise_distance = std::sqrt(2.0) * 1000.0 - accelerate_distance - decelerate_distance; //Thank you Mr. Pythagoras.
const std::vector<Duration> result = calculator.calculate();
CPPUNIT_ASSERT_DOUBLES_EQUAL(
Duration(1.0 + cruise_distance / 50.0 + decelerate_t), //Accelerate, cruise, decelerate.
result[static_cast<size_t>(PrintFeatureType::Infill)],
EPSILON
);
}
} //namespace cura<|endoftext|> |
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2012-2013 Esteban Tovagliari, Jupiter Jazz Limited
//
// 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.
//
// Has to be first, to avoid redefinition warnings.
#include "bind_auto_release_ptr.h"
// appleseed.python headers.
#include "bind_typed_entity_containers.h"
#include "dict2dict.h"
// appleseed.renderer headers.
#include "renderer/api/frame.h"
#include "renderer/api/project.h"
#include "renderer/api/scene.h"
// appleseed.foundation headers.
#include "foundation/utility/autoreleaseptr.h"
#include "foundation/utility/foreach.h"
#include "foundation/utility/searchpaths.h"
// Standard headers.
#include <string>
namespace bpy = boost::python;
using namespace foundation;
using namespace renderer;
namespace detail
{
auto_release_ptr<Project> create_project(const std::string& name)
{
return ProjectFactory::create(name.c_str());
}
bpy::object create_default_project()
{
auto_release_ptr<Project> project(DefaultProjectFactory::create());
return bpy::object(project);
}
bpy::object create_cornell_box_project()
{
auto_release_ptr<Project> project(CornellBoxProjectFactory::create());
return bpy::object(project);
}
bpy::list project_get_search_paths(const Project* project)
{
bpy::list paths;
for (const_each<SearchPaths> i = project->get_search_paths(); i; ++i)
paths.append(*i);
return paths;
}
void project_set_search_paths(Project* proj, const bpy::list& paths)
{
proj->get_search_paths().clear();
for (bpy::ssize_t i = 0, e = bpy::len(paths); i < e; ++i)
{
const bpy::extract<const char*> extractor(paths[i]);
if (extractor.check())
proj->get_search_paths().push_back(extractor());
else
{
PyErr_SetString(PyExc_TypeError, "Incompatible type. Only strings accepted.");
bpy::throw_error_already_set();
}
}
}
ConfigurationContainer* project_get_configs(Project* proj)
{
return &(proj->configurations());
}
bool write_project_default_opts(const ProjectFileWriter* writer, const Project* project, const char* filepath)
{
return ProjectFileWriter::write(*project, filepath);
}
bool write_project_with_opts(const ProjectFileWriter* writer, const Project* project,
const char* filepath, ProjectFileWriter::Options opts)
{
return ProjectFileWriter::write(*project, filepath, opts);
}
auto_release_ptr<Configuration> create_config(const std::string& name)
{
return ConfigurationFactory::create(name.c_str());
}
auto_release_ptr<Configuration> create_config_with_params(const std::string& name, const bpy::dict& params)
{
return ConfigurationFactory::create(name.c_str(), bpy_dict_to_param_array(params));
}
bpy::object create_base_final_config()
{
auto_release_ptr<Configuration> config(BaseConfigurationFactory::create_base_final());
return bpy::object(config);
}
bpy::object create_base_interactive_config()
{
auto_release_ptr<Configuration> config(BaseConfigurationFactory::create_base_interactive());
return bpy::object(config);
}
bpy::dict config_get_inherited_parameters(const Configuration* config)
{
ParamArray params(config->get_inherited_parameters());
return param_array_to_bpy_dict(params);
}
bpy::object project_file_reader_read(ProjectFileReader* reader,
const char* project_filename,
const char* schema_filename)
{
auto_release_ptr<Project> project(reader->read(project_filename, schema_filename));
return bpy::object(project);
}
bpy::object project_file_reader_load_builtin(ProjectFileReader* reader, const char* project_name)
{
auto_release_ptr<Project> project(reader->load_builtin(project_name));
return bpy::object(project);
}
}
void bind_project()
{
bpy::class_<Configuration, auto_release_ptr<Configuration>, bpy::bases<Entity>, boost::noncopyable>("Configuration", bpy::no_init)
.def("create_base_final", detail::create_base_final_config).staticmethod("create_base_final")
.def("create_base_interactive", detail::create_base_interactive_config).staticmethod("create_base_interactive")
.def("__init__", bpy::make_constructor(detail::create_config))
.def("__init__", bpy::make_constructor(detail::create_config_with_params))
.def("set_base", &Configuration::set_base)
.def("get_base", &Configuration::get_base, bpy::return_value_policy<bpy::reference_existing_object>())
.def("get_inherited_parameters", detail::config_get_inherited_parameters)
;
bind_typed_entity_map<Configuration>("ConfigurationContainer");
bpy::class_<Project, auto_release_ptr<Project>, bpy::bases<Entity>, boost::noncopyable>("Project", bpy::no_init)
.def("create_default", detail::create_default_project).staticmethod("create_default")
.def("create_cornell_box", detail::create_cornell_box_project).staticmethod("create_cornell_box")
.def("__init__", bpy::make_constructor(detail::create_project))
.def("add_default_configurations", &Project::add_default_configurations)
.def("has_path", &Project::has_path)
.def("set_path", &Project::set_path)
.def("get_path", &Project::get_path)
.def("set_scene", &Project::set_scene)
.def("get_scene", &Project::get_scene, bpy::return_value_policy<bpy::reference_existing_object>())
.def("set_frame", &Project::set_frame)
.def("get_frame", &Project::get_frame, bpy::return_value_policy<bpy::reference_existing_object>())
.def("create_aov_images", &Project::create_aov_images)
.def("get_search_paths", detail::project_get_search_paths)
.def("set_search_paths", detail::project_set_search_paths)
.def("configurations", detail::project_get_configs, bpy::return_value_policy<bpy::reference_existing_object>())
;
bpy::class_<ProjectFileReader>("ProjectFileReader")
.def("read", &detail::project_file_reader_read)
.def("load_builtin", &detail::project_file_reader_load_builtin)
;
bpy::enum_<ProjectFileWriter::Options>("ProjectFileWriterOptions")
.value("Defaults", ProjectFileWriter::Defaults)
.value("OmitHeaderComment", ProjectFileWriter::OmitHeaderComment)
.value("OmitWritingMeshFiles", ProjectFileWriter::OmitWritingMeshFiles)
.value("OmitCopyingAssets", ProjectFileWriter::OmitCopyingAssets)
.value("OmitSearchPaths", ProjectFileWriter::OmitSearchPaths)
;
bpy::class_<ProjectFileWriter>("ProjectFileWriter")
// These methods are static, but for symmetry with
// ProjectFileReader, I'm wrapping them non-static.
.def("write", detail::write_project_default_opts)
.def("write", detail::write_project_with_opts)
;
}
<commit_msg>fixed styling issues.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2012-2013 Esteban Tovagliari, Jupiter Jazz Limited
//
// 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.
//
// Has to be first, to avoid redefinition warnings.
#include "bind_auto_release_ptr.h"
// appleseed.python headers.
#include "bind_typed_entity_containers.h"
#include "dict2dict.h"
// appleseed.renderer headers.
#include "renderer/api/frame.h"
#include "renderer/api/project.h"
#include "renderer/api/scene.h"
// appleseed.foundation headers.
#include "foundation/utility/autoreleaseptr.h"
#include "foundation/utility/foreach.h"
#include "foundation/utility/searchpaths.h"
// Standard headers.
#include <string>
namespace bpy = boost::python;
using namespace foundation;
using namespace renderer;
namespace detail
{
auto_release_ptr<Project> create_project(const std::string& name)
{
return ProjectFactory::create(name.c_str());
}
bpy::object create_default_project()
{
auto_release_ptr<Project> project(DefaultProjectFactory::create());
return bpy::object(project);
}
bpy::object create_cornell_box_project()
{
auto_release_ptr<Project> project(CornellBoxProjectFactory::create());
return bpy::object(project);
}
bpy::list project_get_search_paths(const Project* project)
{
bpy::list paths;
for (const_each<SearchPaths> i = project->get_search_paths(); i; ++i)
paths.append(*i);
return paths;
}
void project_set_search_paths(Project* project, const bpy::list& paths)
{
project->get_search_paths().clear();
for (bpy::ssize_t i = 0, e = bpy::len(paths); i < e; ++i)
{
const bpy::extract<const char*> extractor(paths[i]);
if (extractor.check())
project->get_search_paths().push_back(extractor());
else
{
PyErr_SetString(PyExc_TypeError, "Incompatible type. Only strings accepted.");
bpy::throw_error_already_set();
}
}
}
ConfigurationContainer* project_get_configs(Project* project)
{
return &(project->configurations());
}
bool write_project_default_opts(
const ProjectFileWriter* writer,
const Project* project,
const char* filepath)
{
return ProjectFileWriter::write(*project, filepath);
}
bool write_project_with_opts(
const ProjectFileWriter* writer,
const Project* project,
const char* filepath,
const ProjectFileWriter::Options opts)
{
return ProjectFileWriter::write(*project, filepath, opts);
}
auto_release_ptr<Configuration> create_config(const std::string& name)
{
return ConfigurationFactory::create(name.c_str());
}
auto_release_ptr<Configuration> create_config_with_params(
const std::string& name,
const bpy::dict& params)
{
return ConfigurationFactory::create(name.c_str(), bpy_dict_to_param_array(params));
}
bpy::object create_base_final_config()
{
auto_release_ptr<Configuration> config(BaseConfigurationFactory::create_base_final());
return bpy::object(config);
}
bpy::object create_base_interactive_config()
{
auto_release_ptr<Configuration> config(BaseConfigurationFactory::create_base_interactive());
return bpy::object(config);
}
bpy::dict config_get_inherited_parameters(const Configuration* config)
{
ParamArray params(config->get_inherited_parameters());
return param_array_to_bpy_dict(params);
}
bpy::object project_file_reader_read(
ProjectFileReader* reader,
const char* project_filename,
const char* schema_filename)
{
auto_release_ptr<Project> project(reader->read(project_filename, schema_filename));
return bpy::object(project);
}
bpy::object project_file_reader_load_builtin(ProjectFileReader* reader, const char* project_name)
{
auto_release_ptr<Project> project(reader->load_builtin(project_name));
return bpy::object(project);
}
}
void bind_project()
{
bpy::class_<Configuration, auto_release_ptr<Configuration>, bpy::bases<Entity>, boost::noncopyable>("Configuration", bpy::no_init)
.def("create_base_final", detail::create_base_final_config).staticmethod("create_base_final")
.def("create_base_interactive", detail::create_base_interactive_config).staticmethod("create_base_interactive")
.def("__init__", bpy::make_constructor(detail::create_config))
.def("__init__", bpy::make_constructor(detail::create_config_with_params))
.def("set_base", &Configuration::set_base)
.def("get_base", &Configuration::get_base, bpy::return_value_policy<bpy::reference_existing_object>())
.def("get_inherited_parameters", detail::config_get_inherited_parameters);
bind_typed_entity_map<Configuration>("ConfigurationContainer");
bpy::class_<Project, auto_release_ptr<Project>, bpy::bases<Entity>, boost::noncopyable>("Project", bpy::no_init)
.def("create_default", detail::create_default_project).staticmethod("create_default")
.def("create_cornell_box", detail::create_cornell_box_project).staticmethod("create_cornell_box")
.def("__init__", bpy::make_constructor(detail::create_project))
.def("add_default_configurations", &Project::add_default_configurations)
.def("has_path", &Project::has_path)
.def("set_path", &Project::set_path)
.def("get_path", &Project::get_path)
.def("set_scene", &Project::set_scene)
.def("get_scene", &Project::get_scene, bpy::return_value_policy<bpy::reference_existing_object>())
.def("set_frame", &Project::set_frame)
.def("get_frame", &Project::get_frame, bpy::return_value_policy<bpy::reference_existing_object>())
.def("create_aov_images", &Project::create_aov_images)
.def("get_search_paths", detail::project_get_search_paths)
.def("set_search_paths", detail::project_set_search_paths)
.def("configurations", detail::project_get_configs, bpy::return_value_policy<bpy::reference_existing_object>());
bpy::class_<ProjectFileReader>("ProjectFileReader")
.def("read", &detail::project_file_reader_read)
.def("load_builtin", &detail::project_file_reader_load_builtin)
;
bpy::enum_<ProjectFileWriter::Options>("ProjectFileWriterOptions")
.value("Defaults", ProjectFileWriter::Defaults)
.value("OmitHeaderComment", ProjectFileWriter::OmitHeaderComment)
.value("OmitWritingMeshFiles", ProjectFileWriter::OmitWritingMeshFiles)
.value("OmitCopyingAssets", ProjectFileWriter::OmitCopyingAssets)
.value("OmitSearchPaths", ProjectFileWriter::OmitSearchPaths);
bpy::class_<ProjectFileWriter>("ProjectFileWriter")
// These methods are static, but for symmetry with
// ProjectFileReader, I'm wrapping them non-static.
.def("write", detail::write_project_default_opts)
.def("write", detail::write_project_with_opts);
}
<|endoftext|> |
<commit_before>// DESCRIPTION: Appropriate license header at the top, e.g.,
/*
* Copyright (c) 2018, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// DESCRIPTION: A brief description of the overall purpose and contents of this file
// DESCRIPTION: The text on the same line as the @brief will show up in lists and
// summaries, whereas the detailed text following on the next line is the detailed
// description.
/** ---------------------------------------------------------------------------*
* @file example_documentation.cpp
* @brief Example code documentation for libgdf.
*
* This file provides examples of how source files, classes, functions, and variables
* should be documented in libgdf.
* ---------------------------------------------------------------------------**/
// DESCRIPTION: A brief description of the purpose and functionality of the class
/* --------------------------------------------------------------------------*/
/**
* @brief This class serves as an example of how classes in libgdf should
* be documented.
*
* In detail, this class shows how member functions and member variables should
* be documented.
*/
/* ----------------------------------------------------------------------------*/
template <typename T>
class example_class
{
// DESCRIPTION: Trivial class functions should be given names that make their purpose clear
// DESCRIPTION: If their name makes the functionality obvious, no documentation is necessary
void get_my_int() {
return my_int;
}
void set_my_int(int new_value){
my_int = new_value;
}
// DESCRIPTION: Non-trivial member functions should have a brief description of the
// function as well as all of its parameters. Every parameter should be decorated to
// indicate if it is an input or output parameter, or both with @Param[in], @Param[out],
// and @Param[in,out] respectively.
/* --------------------------------------------------------------------------*/
/**
* @brief This is a complicated function that requires more detailed documentation.
*
* Here is the more detailed description of what this function does and what its
* logic is.
*
* @Param[in] first_parameter This parameter is an input parameter to the function
* @Param[in,out] second_parameter This parameter is used both as an input and output
* @Param[out] third_parameter This parameter is an output of the function
*
* @Returns The result of the complex function
*/
/* ----------------------------------------------------------------------------*/
T complicated_function(int const first_parameter,
double * second_parameter,
float * third_parameter)
{
// DESCRIPTION: Notice the use of *human readable* variable names. Human readable
// variable names are vastly prefered to short, hard to read names. E.g.,
// use 'first_parameter' or `firstParameter` instead of 'fp'. When in doubt, opt for
// the longer, easier to read name that conveys the meaning and purpose of the variable.
// Well named variables are self-documenting. As developers, we usually spend more time
// reading code than writing code, so the easier you make it to read your code,
// the more efficient we will all be.
// DESCRIPTION: In-line comments that describe the logic inside of your functions
// are extremely helpful both to others as well as your future self to aid in
// understanding your thought process
}
private:
int my_int; //< An example private member variable
std::vector<T> my_vector; //< An example private member variable
};
// DESCRIPTION: Free functions should be commented in the same way as non-trivial
// class member functions. If the function is templated, use @tparam to describe
// the purpose of the template parameters.
/* --------------------------------------------------------------------------*/
/**
* @brief An example of a free function (non-class member). This function
* calls a functor on an input argument and returns the result.
*
* @Param[in] functor The functor to be called on the input argument
* @Param[in] input_argument The input argument passed into the functor
* @tparam functor_type The type of the functor
* @tparam input_type The datatype of the input argument
* @tparam return_type The return type of the functor
*
* @Returns The result of calling the functor on the input argument
*/
/* ----------------------------------------------------------------------------*/
template <class functor_type,
typename input_type,
typename return_type>
return_type free_function(functor_type functor,
input_type input_argument)
{
// Calls the passed in functor on the passed in input argument and returns
// the result
return functor(input_argument);
}
// DESCRIPTION: Enumeration types should have a brief overall description of
// the purpose of the enums, as well as a description of each enum member.
/* --------------------------------------------------------------------------*/
/**
* @brief The purpose of these enumerations is to provide an example
* of how enumerations should be documented.
*/
/* ----------------------------------------------------------------------------*/
enum class example_enum
{
first_enum, //< Description of the first enum
second_enum, //< Description of the second enum
third_enum //< Description of the third enum
};
<commit_msg>Update example_documentation.cpp<commit_after>// DESCRIPTION: Appropriate license header at the top, e.g.,
/*
* Copyright (c) 2018, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// DESCRIPTION: A brief description of the overall purpose and contents of this file.
// Note the use of the @file for file descriptions
// DESCRIPTION: The text on the same line as the @brief will show up in lists and
// summaries, whereas the detailed text following on the next line is the detailed
// description.
/** ---------------------------------------------------------------------------*
* @file example_documentation.cpp
* @brief Example code documentation for libgdf.
*
* This file provides examples of how source files, classes, functions, and variables
* should be documented in libgdf.
* ---------------------------------------------------------------------------**/
// DESCRIPTION: A brief description of the purpose and functionality of the class
/* --------------------------------------------------------------------------*/
/**
* @brief This class serves as an example of how classes in libgdf should
* be documented.
*
* In detail, this class shows how member functions and member variables should
* be documented.
*/
/* ----------------------------------------------------------------------------*/
template <typename T>
class example_class
{
// DESCRIPTION: Trivial class functions should be given names that make their purpose clear
// DESCRIPTION: If their name makes the functionality obvious, no documentation is necessary
void get_my_int() {
return my_int;
}
void set_my_int(int new_value){
my_int = new_value;
}
// DESCRIPTION: Non-trivial member functions should have a brief description of the
// function as well as all of its parameters. Every parameter should be decorated to
// indicate if it is an input or output parameter, or both with @Param[in], @Param[out],
// and @Param[in,out] respectively.
/* --------------------------------------------------------------------------*/
/**
* @brief This is a complicated function that requires more detailed documentation.
*
* Here is the more detailed description of what this function does and what its
* logic is.
*
* @Param[in] first_parameter This parameter is an input parameter to the function
* @Param[in,out] second_parameter This parameter is used both as an input and output
* @Param[out] third_parameter This parameter is an output of the function
*
* @Returns The result of the complex function
*/
/* ----------------------------------------------------------------------------*/
T complicated_function(int const first_parameter,
double * second_parameter,
float * third_parameter)
{
// DESCRIPTION: Notice the use of *human readable* variable names. Human readable
// variable names are vastly prefered to short, hard to read names. E.g.,
// use 'first_parameter' or `firstParameter` instead of 'fp'. When in doubt, opt for
// the longer, easier to read name that conveys the meaning and purpose of the variable.
// Well named variables are self-documenting. As developers, we usually spend more time
// reading code than writing code, so the easier you make it to read your code,
// the more efficient we will all be.
// DESCRIPTION: In-line comments that describe the logic inside of your functions
// are extremely helpful both to others as well as your future self to aid in
// understanding your thought process
}
private:
int my_int; //< An example private member variable
std::vector<T> my_vector; //< An example private member variable
};
// DESCRIPTION: Free functions should be commented in the same way as non-trivial
// class member functions. If the function is templated, use @tparam to describe
// the purpose of the template parameters.
/* --------------------------------------------------------------------------*/
/**
* @brief An example of a free function (non-class member). This function
* calls a functor on an input argument and returns the result.
*
* @Param[in] functor The functor to be called on the input argument
* @Param[in] input_argument The input argument passed into the functor
* @tparam functor_type The type of the functor
* @tparam input_type The datatype of the input argument
* @tparam return_type The return type of the functor
*
* @Returns The result of calling the functor on the input argument
*/
/* ----------------------------------------------------------------------------*/
template <class functor_type,
typename input_type,
typename return_type>
return_type free_function(functor_type functor,
input_type input_argument)
{
// Calls the passed in functor on the passed in input argument and returns
// the result
return functor(input_argument);
}
// DESCRIPTION: Enumeration types should have a brief overall description of
// the purpose of the enums, as well as a description of each enum member.
/* --------------------------------------------------------------------------*/
/**
* @brief The purpose of these enumerations is to provide an example
* of how enumerations should be documented.
*/
/* ----------------------------------------------------------------------------*/
enum class example_enum
{
first_enum, //< Description of the first enum
second_enum, //< Description of the second enum
third_enum //< Description of the third enum
};
<|endoftext|> |
<commit_before>/*
Starstructor, the Starbound Toolet
Copyright (C) 2013-2014 Chris Stamford
Source file contributers:
Chris Stamford contact: cstamford@gmail.com
Licensed under the terms of the GPL.
Contact: starstructor@gmail.com
*/
#ifndef STEXCEPTION_HPP
#define STEXCEPTION_HPP
#include <string>
#include <ostream>
namespace Starstructor { namespace Exception {
class Exception
{
public:
Exception(const std::string& message, const std::string& exType = "General exception") noexcept
: m_message{ message }, m_exType{ exType }
{}
virtual ~Exception()
{}
std::string what() const noexcept
{
return m_exType + ": " + m_message;
}
std::string message() const noexcept
{
return m_message;
}
private:
std::string m_message;
std::string m_exType;
};
class FileNotFoundException : public Exception
{
public:
FileNotFoundException(const std::string& message) noexcept
: Exception{ message, "File not found exception" }
{}
virtual ~FileNotFoundException()
{}
};
class JsonInvalidFormat : public Exception
{
public:
JsonInvalidFormat(const std::string& message) noexcept
: Exception{ message, "JSON invalid format exception" }
{}
virtual ~JsonInvalidFormat()
{}
};
}
}
#endif // STEXCEPTION_HPP
<commit_msg>hopefully this should fix msvc and noexcept<commit_after>/*
Starstructor, the Starbound Toolet
Copyright (C) 2013-2014 Chris Stamford
Source file contributers:
Chris Stamford contact: cstamford@gmail.com
Licensed under the terms of the GPL.
Contact: starstructor@gmail.com
*/
#ifndef STEXCEPTION_HPP
#define STEXCEPTION_HPP
#ifdef _MSC_VER
#define noexcept throw()
#endif
#include <string>
#include <ostream>
namespace Starstructor { namespace Exception {
class Exception
{
public:
Exception(const std::string& message, const std::string& exType = "General exception") noexcept
: m_message{ message }, m_exType{ exType }
{}
virtual ~Exception()
{}
std::string what() const noexcept
{
return m_exType + ": " + m_message;
}
std::string message() const noexcept
{
return m_message;
}
private:
std::string m_message;
std::string m_exType;
};
class FileNotFoundException : public Exception
{
public:
FileNotFoundException(const std::string& message) noexcept
: Exception{ message, "File not found exception" }
{}
virtual ~FileNotFoundException()
{}
};
class JsonInvalidFormat : public Exception
{
public:
JsonInvalidFormat(const std::string& message) noexcept
: Exception{ message, "JSON invalid format exception" }
{}
virtual ~JsonInvalidFormat()
{}
};
}
}
#endif // STEXCEPTION_HPP
<|endoftext|> |
<commit_before>#include "gamestates/introstate.hpp"
#include <SFML/Window/Event.hpp>
#include <SFML/Graphics/Texture.hpp>
#include <SFML/Graphics/Sprite.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <iostream>
namespace qrw
{
IntroState::IntroState(sf::RenderWindow* renderWindow)
: GameState(renderWindow, EGameStateId::EGSID_INTRO_STATE)
{
}
IntroState::~IntroState()
{
}
void IntroState::init(GameState* previousState)
{
// Create render window
_renderWindow->create(
sf::VideoMode(640, 480),
"Quad-Ruled War - Loading...",
sf::Style::None
);
_quit = false;
_splashTexture = new sf::Texture();
_splashTexture->loadFromFile("./res/img/splash.png");
_splashSprite = new sf::Sprite();
_splashSprite->setTexture(*_splashTexture);
}
EGameStateId IntroState::update()
{
if(_quit)
{
delete _splashTexture;
delete _splashSprite;
return EGameStateId::EGSID_QUIT;
}
return EGameStateId::EGSID_NO_CHANGE;
}
void IntroState::draw()
{
_renderWindow->draw(*_splashSprite);
}
void IntroState::handleEvent(sf::Event& event)
{
std::cout << "Handle event\n";
if(event.type == sf::Event::KeyPressed)
{
_quit = true;
}
}
} // namespace qrw
<commit_msg>Adjusted intro state render window size.<commit_after>#include "gamestates/introstate.hpp"
#include <SFML/Window/Event.hpp>
#include <SFML/Graphics/Texture.hpp>
#include <SFML/Graphics/Sprite.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <iostream>
namespace qrw
{
IntroState::IntroState(sf::RenderWindow* renderWindow)
: GameState(renderWindow, EGameStateId::EGSID_INTRO_STATE)
{
}
IntroState::~IntroState()
{
}
void IntroState::init(GameState* previousState)
{
// Create render window
_renderWindow->create(
sf::VideoMode(640, 240),
"Quad-Ruled War - Loading...",
sf::Style::None
);
_quit = false;
_splashTexture = new sf::Texture();
_splashTexture->loadFromFile("./res/img/splash.png");
_splashSprite = new sf::Sprite();
_splashSprite->setTexture(*_splashTexture);
}
EGameStateId IntroState::update()
{
if(_quit)
{
delete _splashTexture;
delete _splashSprite;
return EGameStateId::EGSID_QUIT;
}
return EGameStateId::EGSID_NO_CHANGE;
}
void IntroState::draw()
{
_renderWindow->draw(*_splashSprite);
}
void IntroState::handleEvent(sf::Event& event)
{
std::cout << "Handle event\n";
if(event.type == sf::Event::KeyPressed)
{
_quit = true;
}
}
} // namespace qrw
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2018 Tuukka Norri
* This code is licensed under MIT license (see LICENSE for details).
*/
#include <vcf2multialign/generate_graph_context.hh>
namespace lb = libbio;
namespace vcf2multialign {
void generate_graph_context::open_files(
char const *reference_fname,
char const *variants_fname,
char const *report_fname,
char const *output_fname
)
{
generate_context_base::open_files(reference_fname, variants_fname, report_fname);
lb::open_file_for_writing(output_fname, m_output_stream, m_should_overwrite_files);
}
void generate_graph_context::swap_buffers_and_generate_graph()
{
// Make sure that m_graph_writer has finished with the previous set of buffers.
dispatch_semaphore_wait(*m_output_sema, DISPATCH_TIME_FOREVER);
// Swap buffers between haplotypes and m_buffers.
// Also reset the range pointers in the new haplotype buffers.
std::size_t i(0);
for (auto &kv : m_haplotypes)
{
auto &haplotype_vec(kv.second);
for (auto &haplotype : haplotype_vec)
{
auto &buffer(m_buffers[i]);
using std::swap;
swap(haplotype.output_sequence, buffer);
haplotype.output_sequence.clear();
++i;
}
}
// Process in background thread.
lb::dispatch_async_fn(*m_output_queue, [this](){
m_graph_writer.process_segment(m_buffers);
});
}
void generate_graph_context::graph_writer_did_process_segment(graph_writer &)
{
// Done with the previous segment, buffers are writable again.
dispatch_semaphore_signal(*m_output_sema);
}
void generate_graph_context::variant_handler_did_process_overlap_stack(variant_handler &handler)
{
if (1 == handler.m_overlap_stack.size())
swap_buffers_and_generate_graph();
}
void generate_graph_context::variant_handler_did_finish(variant_handler &handler)
{
// Handle the last segment.
swap_buffers_and_generate_graph();
// Finalize the graph.
lb::dispatch_caller caller(&m_graph_writer);
caller.template sync <&graph_writer::finish>(*m_output_queue);
// Everything done.
finish();
}
void generate_graph_context::prepare_haplotypes()
{
std::size_t count(0);
auto const &sample_names(m_vcf_reader.sample_names());
for (auto const &kv : sample_names)
{
auto const &sample_name(kv.first);
auto const sample_no(kv.second);
auto const current_ploidy(m_ploidy.find(sample_no)->second);
auto const did_emplace(m_haplotypes.emplace(
std::piecewise_construct,
std::forward_as_tuple(sample_no),
std::forward_as_tuple(current_ploidy)
).second);
lb::always_assert(did_emplace);
++count;
}
m_buffers.resize(count);
m_graph_writer.init(count);
}
void generate_graph_context::load_and_generate(
char const *reference_fname,
char const *variants_fname,
char const *report_fname,
char const *output_fname,
sv_handling const sv_handling_method,
bool const should_check_ref
)
{
// Open the files.
std::cerr << "Opening files…" << std::endl;
open_files(reference_fname, variants_fname, report_fname, output_fname);
generate_context_base::load_and_generate(
sv_handling_method,
should_check_ref
);
// Replace the placeholder variant_handler.
{
variant_handler temp(
m_main_queue,
m_parsing_queue,
m_vcf_reader,
m_reference,
sv_handling_method,
m_skipped_variants,
m_null_allele_seq,
m_error_logger,
*this
);
m_variant_handler = std::move(temp);
m_variant_handler.get_variant_buffer().set_delegate(m_variant_handler);
}
// Replace the placeholder graph_writer.
{
graph_writer temp(*this, m_output_stream);
m_graph_writer = std::move(temp);
}
// Create the required buffers.
prepare_haplotypes();
std::cerr << "Generating variant graph…" << std::endl;
m_start_time = std::chrono::system_clock::now();
m_variant_handler.process_variants(m_haplotypes);
}
}
<commit_msg>Add haplotype for the reference, count the haplotypes correctly<commit_after>/*
* Copyright (c) 2018 Tuukka Norri
* This code is licensed under MIT license (see LICENSE for details).
*/
#include <vcf2multialign/generate_graph_context.hh>
namespace lb = libbio;
namespace vcf2multialign {
void generate_graph_context::open_files(
char const *reference_fname,
char const *variants_fname,
char const *report_fname,
char const *output_fname
)
{
generate_context_base::open_files(reference_fname, variants_fname, report_fname);
lb::open_file_for_writing(output_fname, m_output_stream, m_should_overwrite_files);
}
void generate_graph_context::swap_buffers_and_generate_graph()
{
// Make sure that m_graph_writer has finished with the previous set of buffers.
dispatch_semaphore_wait(*m_output_sema, DISPATCH_TIME_FOREVER);
// Swap buffers between haplotypes and m_buffers.
// Also reset the range pointers in the new haplotype buffers.
std::size_t i(0);
for (auto &kv : m_haplotypes)
{
auto &haplotype_vec(kv.second);
for (auto &haplotype : haplotype_vec)
{
assert(i < m_buffers.size());
auto &buffer(m_buffers[i]);
using std::swap;
swap(haplotype.output_sequence, buffer);
haplotype.output_sequence.clear();
++i;
}
}
// Process in background thread.
lb::dispatch_async_fn(*m_output_queue, [this](){
m_graph_writer.process_segment(m_buffers);
});
}
void generate_graph_context::graph_writer_did_process_segment(graph_writer &)
{
// Done with the previous segment, buffers are writable again.
dispatch_semaphore_signal(*m_output_sema);
}
void generate_graph_context::variant_handler_did_process_overlap_stack(variant_handler &handler)
{
if (1 == handler.m_overlap_stack.size())
swap_buffers_and_generate_graph();
}
void generate_graph_context::variant_handler_did_finish(variant_handler &handler)
{
// Handle the last segment.
swap_buffers_and_generate_graph();
// Finalize the graph.
lb::dispatch_caller caller(&m_graph_writer);
caller.template sync <&graph_writer::finish>(*m_output_queue);
// Everything done.
finish();
}
void generate_graph_context::prepare_haplotypes()
{
std::size_t count(0);
auto const &sample_names(m_vcf_reader.sample_names());
for (auto const &kv : sample_names)
{
auto const &sample_name(kv.first);
auto const sample_no(kv.second);
auto const current_ploidy(m_ploidy.find(sample_no)->second);
auto const did_emplace(m_haplotypes.emplace(
std::piecewise_construct,
std::forward_as_tuple(sample_no),
std::forward_as_tuple(current_ploidy)
).second);
lb::always_assert(did_emplace);
count += current_ploidy;
}
{
lb::always_assert(
m_haplotypes.cend() == m_haplotypes.find(REF_SAMPLE_NUMBER),
"REF_SAMPLE_NUMBER already in use"
);
auto const did_emplace(m_haplotypes.emplace(
std::piecewise_construct,
std::forward_as_tuple(REF_SAMPLE_NUMBER),
std::forward_as_tuple(1)
).second);
lb::always_assert(did_emplace);
++count;
}
m_buffers.resize(count);
m_graph_writer.init(count);
}
void generate_graph_context::load_and_generate(
char const *reference_fname,
char const *variants_fname,
char const *report_fname,
char const *output_fname,
sv_handling const sv_handling_method,
bool const should_check_ref
)
{
// Open the files.
std::cerr << "Opening files…" << std::endl;
open_files(reference_fname, variants_fname, report_fname, output_fname);
generate_context_base::load_and_generate(
sv_handling_method,
should_check_ref
);
// Replace the placeholder variant_handler.
{
variant_handler temp(
m_main_queue,
m_parsing_queue,
m_vcf_reader,
m_reference,
sv_handling_method,
m_skipped_variants,
m_null_allele_seq,
m_error_logger,
*this
);
m_variant_handler = std::move(temp);
m_variant_handler.get_variant_buffer().set_delegate(m_variant_handler);
}
// Replace the placeholder graph_writer.
{
graph_writer temp(*this, m_output_stream);
m_graph_writer = std::move(temp);
}
// Create the required buffers.
prepare_haplotypes();
std::cerr << "Generating variant graph…" << std::endl;
m_start_time = std::chrono::system_clock::now();
m_variant_handler.process_variants(m_haplotypes);
}
}
<|endoftext|> |
<commit_before>/* indivudal.cpp - CS 472 Project #2: Genetic Programming
* Copyright 2014 Andrew Schwartzmeyer
*
* Source file for Individual
*/
#include <cmath>
#include <iostream>
#include <memory>
#include <tuple>
#include <vector>
#include "individual.hpp"
#include "../problem/problem.hpp"
#include "../random/random_generator.hpp"
using namespace individual;
using namespace random_generator;
using problem::Problem;
Node::Node(const Problem & problem, const int & depth) {
if (depth < problem.max_depth) {
// Assign random internal type
int_dist dist(0, internal_types - 1); // Closed interval
type = Type(dist(engine));
// Recursively create subtrees
for (int i = 0; i < arity; i++)
children.emplace_back(Node(problem, depth + 1));
} else {
// Reached max depth, assign random terminal type
int_dist dist(internal_types, internal_types + terminal_types - 1); // Closed interval
type = Type(dist(engine));
// Setup constant type; input is provided on evaluation
if (type == CONSTANT) {
// Choose a random value between the problem's min and max
real_dist dist(problem.constant_min, problem.constant_max);
constant = dist(engine);
}
}
}
double Node::evaluate(const double & input) {
double left, right;
if (type != INPUT and type != CONSTANT) {
left = children[0].evaluate(input);
right = children[1].evaluate(input);
}
switch(type) {
case ADD:
return left + right;
case SUBTRACT:
return left - right;
case MULTIPLY:
return left * right;
case DIVIDE:
if (right == 0)
return 1;
return left / right;
case CONSTANT:
return constant;
case INPUT:
return input;
}
}
int Node::size() {
// Recursively count children via pre-order traversal
int count = 1;
for (auto child : children)
count += child.size();
return count;
}
void Node::print(const int & depth) {
// Post-order traversal print of expression in RPN/posfix notation
std::cout << '(';
for (auto child : children)
child.print(depth + 1);
switch(type) {
case ADD:
std:: cout << " + ";
break;
case SUBTRACT:
std:: cout << " - ";
break;
case MULTIPLY:
std:: cout << " * ";
break;
case DIVIDE:
std:: cout << " / ";
break;
case CONSTANT:
std:: cout << constant;
break;
case INPUT:
std:: cout << "X";
break;
}
std:: cout << ')';
}
Individual::Individual(const Problem & p): problem(p), root(Node(problem)) {
}
double Individual::evaluate() {
double fitness = 0;
for (auto pair : problem.values) {
double output = root.evaluate(std::get<0>(pair));
fitness += std::pow(output - std::get<1>(pair), 2);
}
return std::sqrt(fitness);
}
void Individual::print() {
std::cout << "Tree of size " << root.size()
<< " has the following formula: " << std::endl;
root.print();
std::cout << std::endl
<< "Has a fitness of: " << evaluate() << std::endl;
}
<commit_msg>Indentation fix<commit_after>/* indivudal.cpp - CS 472 Project #2: Genetic Programming
* Copyright 2014 Andrew Schwartzmeyer
*
* Source file for Individual
*/
#include <cmath>
#include <iostream>
#include <memory>
#include <tuple>
#include <vector>
#include "individual.hpp"
#include "../problem/problem.hpp"
#include "../random/random_generator.hpp"
using namespace individual;
using namespace random_generator;
using problem::Problem;
Node::Node(const Problem & problem, const int & depth) {
if (depth < problem.max_depth) {
// Assign random internal type
int_dist dist(0, internal_types - 1); // Closed interval
type = Type(dist(engine));
// Recursively create subtrees
for (int i = 0; i < arity; i++)
children.emplace_back(Node(problem, depth + 1));
} else {
// Reached max depth, assign random terminal type
int_dist dist(internal_types, internal_types + terminal_types - 1); // Closed interval
type = Type(dist(engine));
// Setup constant type; input is provided on evaluation
if (type == CONSTANT) {
// Choose a random value between the problem's min and max
real_dist dist(problem.constant_min, problem.constant_max);
constant = dist(engine);
}
}
}
double Node::evaluate(const double & input) {
double left, right;
if (type != INPUT and type != CONSTANT) {
left = children[0].evaluate(input);
right = children[1].evaluate(input);
}
switch(type) {
case ADD:
return left + right;
case SUBTRACT:
return left - right;
case MULTIPLY:
return left * right;
case DIVIDE:
if (right == 0)
return 1;
return left / right;
case CONSTANT:
return constant;
case INPUT:
return input;
}
}
int Node::size() {
// Recursively count children via pre-order traversal
int count = 1;
for (auto child : children)
count += child.size();
return count;
}
void Node::print(const int & depth) {
// Post-order traversal print of expression in RPN/posfix notation
std::cout << '(';
for (auto child : children)
child.print(depth + 1);
switch(type) {
case ADD:
std:: cout << " + ";
break;
case SUBTRACT:
std:: cout << " - ";
break;
case MULTIPLY:
std:: cout << " * ";
break;
case DIVIDE:
std:: cout << " / ";
break;
case CONSTANT:
std:: cout << constant;
break;
case INPUT:
std:: cout << "X";
break;
}
std:: cout << ')';
}
Individual::Individual(const Problem & p): problem(p), root(Node(problem)) {
size = root.size();
fitness = evaluate();
}
double Individual::evaluate() {
double fitness = 0;
for (auto pair : problem.values) {
double output = root.evaluate(std::get<0>(pair));
fitness += std::pow(output - std::get<1>(pair), 2);
}
return std::sqrt(fitness);
}
void Individual::print() {
std::cout << "Tree of size " << root.size()
<< " has the following formula: " << std::endl;
root.print();
std::cout << std::endl
<< "Has a fitness of: " << evaluate() << std::endl;
}
<|endoftext|> |
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
// MOOSE includes
#include "ComputeElemAuxBcsThread.h"
#include "AuxiliarySystem.h"
#include "FEProblem.h"
#include "AuxKernel.h"
// libmesh includes
#include "libmesh/threads.h"
ComputeElemAuxBcsThread::ComputeElemAuxBcsThread(FEProblemBase & problem,
const MooseObjectWarehouse<AuxKernel> & storage,
bool need_materials) :
_problem(problem),
_aux_sys(problem.getAuxiliarySystem()),
_storage(storage),
_need_materials(need_materials)
{
}
// Splitting Constructor
ComputeElemAuxBcsThread::ComputeElemAuxBcsThread(ComputeElemAuxBcsThread & x, Threads::split /*split*/) :
_problem(x._problem),
_aux_sys(x._aux_sys),
_storage(x._storage),
_need_materials(x._need_materials)
{
}
void
ComputeElemAuxBcsThread::operator() (const ConstBndElemRange & range)
{
ParallelUniqueId puid;
_tid = puid.id;
// Reference to all boundary restricted AuxKernels for the current thread
const auto & boundary_kernels = _storage.getActiveBoundaryObjects(_tid);
for (const auto & belem : range)
{
const Elem * elem = belem->_elem;
unsigned short int side = belem->_side;
BoundaryID boundary_id = belem->_bnd_id;
if (elem->processor_id() == _problem.processor_id())
{
// prepare variables
for (const auto & it : _aux_sys._elem_vars[_tid])
{
MooseVariable * var = it.second;
var->prepareAux();
}
// Locate the AuxKernel objects for the current BoundaryID
const auto iter = boundary_kernels.find(boundary_id);
if (iter != boundary_kernels.end() && !(iter->second.empty()) )
{
_problem.prepare(elem, _tid);
_problem.reinitElemFace(elem, side, boundary_id, _tid);
if (_need_materials)
{
_problem.reinitMaterialsFace(elem->subdomain_id(), _tid);
_problem.reinitMaterialsBoundary(boundary_id, _tid);
}
// Set the active boundary id so that BoundaryRestrictable::_boundary_id is correct
_problem.setCurrentBoundaryID(boundary_id);
for (const auto & aux : iter->second)
aux->compute();
if (_need_materials)
_problem.swapBackMaterialsFace(_tid);
// Set active boundary id to invalid
_problem.setCurrentBoundaryID(Moose::INVALID_BOUNDARY_ID);
}
// update the solution vector
{
Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx);
for (const auto & it : _aux_sys._elem_vars[_tid])
{
MooseVariable * var = it.second;
var->insert(_aux_sys.solution());
}
}
}
}
}
void
ComputeElemAuxBcsThread::join(const ComputeElemAuxBcsThread & /*y*/)
{
}
<commit_msg>Fix compute thread for ElemAuxBcs (#8444).<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
// MOOSE includes
#include "ComputeElemAuxBcsThread.h"
#include "AuxiliarySystem.h"
#include "FEProblem.h"
#include "AuxKernel.h"
// libmesh includes
#include "libmesh/threads.h"
ComputeElemAuxBcsThread::ComputeElemAuxBcsThread(FEProblemBase & problem,
const MooseObjectWarehouse<AuxKernel> & storage,
bool need_materials) :
_problem(problem),
_aux_sys(problem.getAuxiliarySystem()),
_storage(storage),
_need_materials(need_materials)
{
}
// Splitting Constructor
ComputeElemAuxBcsThread::ComputeElemAuxBcsThread(ComputeElemAuxBcsThread & x, Threads::split /*split*/) :
_problem(x._problem),
_aux_sys(x._aux_sys),
_storage(x._storage),
_need_materials(x._need_materials)
{
}
void
ComputeElemAuxBcsThread::operator() (const ConstBndElemRange & range)
{
ParallelUniqueId puid;
_tid = puid.id;
// Reference to all boundary restricted AuxKernels for the current thread
const auto & boundary_kernels = _storage.getActiveBoundaryObjects(_tid);
for (const auto & belem : range)
{
const Elem * elem = belem->_elem;
unsigned short int side = belem->_side;
BoundaryID boundary_id = belem->_bnd_id;
if (elem->processor_id() == _problem.processor_id())
{
// prepare variables
for (const auto & it : _aux_sys._elem_vars[_tid])
{
MooseVariable * var = it.second;
var->prepareAux();
}
// Locate the AuxKernel objects for the current BoundaryID
const auto iter = boundary_kernels.find(boundary_id);
if (iter != boundary_kernels.end() && !(iter->second.empty()) )
{
_problem.prepare(elem, _tid);
_problem.reinitElemFace(elem, side, boundary_id, _tid);
std::set<unsigned int> needed_mat_props;
for (const auto & aux : iter->second)
{
const std::set<unsigned int> & mp_deps = aux->getMatPropDependencies();
needed_mat_props.insert(mp_deps.begin(), mp_deps.end());
}
_problem.setActiveMaterialProperties(needed_mat_props, _tid);
if (_need_materials)
{
_problem.reinitMaterialsFace(elem->subdomain_id(), _tid);
_problem.reinitMaterialsBoundary(boundary_id, _tid);
}
// Set the active boundary id so that BoundaryRestrictable::_boundary_id is correct
_problem.setCurrentBoundaryID(boundary_id);
for (const auto & aux : iter->second)
aux->compute();
if (_need_materials)
_problem.swapBackMaterialsFace(_tid);
// Set active boundary id to invalid
_problem.setCurrentBoundaryID(Moose::INVALID_BOUNDARY_ID);
}
// update the solution vector
{
Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx);
for (const auto & it : _aux_sys._elem_vars[_tid])
{
MooseVariable * var = it.second;
var->insert(_aux_sys.solution());
}
}
}
}
_problem.clearActiveMaterialProperties(_tid);
}
void
ComputeElemAuxBcsThread::join(const ComputeElemAuxBcsThread & /*y*/)
{
}
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include <iostream>
#include "itkPSMCommandLineClass.h"
#include "itkPSMCommandLineClass.cxx"
int main( int argc, char *argv[] )
{
std::string output_path = "";
std::string input_path_prefix = "";
// Check for proper arguments
if (argc < 2)
{
std::cout << "Wrong number of arguments. \nUse: "
<< "PSMCLI parameter_file [output_path] [input_path]\n"
<< "See itk::PSMParameterFileReader for documentation on the parameter file format.\n"
<< "Note that input_path will be prefixed to any file names and paths in the xml parameter file.\n"
<< std::endl;
return EXIT_FAILURE;
}
if (argc >2)
{
output_path = std::string(argv[2]);
}
if (argc >3)
{
input_path_prefix = std::string(argv[3]);
}
try
{
itk::PSMCommandLineClass<3>::Pointer psmClass = itk::PSMCommandLineClass<3>::New();
psmClass->Run( argv[1], input_path_prefix, output_path );
}
catch(itk::ExceptionObject &e)
{
std::cerr << "ITK exception with description: " << e.GetDescription()
<< "\n at location:" << e.GetLocation()
<< "\n in file:" << e.GetFile() << std::endl;
return EXIT_FAILURE;
}
catch(...)
{
std::cerr << "Unknown exception thrown" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}<commit_msg>Fixed runtime error where image formats were not recognized<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkIncludeRequiredIOFactories.h"
#include <iostream>
#include "itkPSMCommandLineClass.h"
#include "itkPSMCommandLineClass.cxx"
int main( int argc, char *argv[] )
{
std::string output_path = "";
std::string input_path_prefix = "";
// Check for proper arguments
if (argc < 2)
{
std::cout << "Wrong number of arguments. \nUse: "
<< "PSMCLI parameter_file [output_path] [input_path]\n"
<< "See itk::PSMParameterFileReader for documentation on the parameter file format.\n"
<< "Note that input_path will be prefixed to any file names and paths in the xml parameter file.\n"
<< std::endl;
return EXIT_FAILURE;
}
if (argc >2)
{
output_path = std::string(argv[2]);
}
if (argc >3)
{
input_path_prefix = std::string(argv[3]);
}
try
{
RegisterRequiredFactories();
itk::PSMCommandLineClass<3>::Pointer psmClass = itk::PSMCommandLineClass<3>::New();
psmClass->Run( argv[1], input_path_prefix, output_path );
}
catch(itk::ExceptionObject &e)
{
std::cerr << "ITK exception with description: " << e.GetDescription()
<< "\n at location:" << e.GetLocation()
<< "\n in file:" << e.GetFile() << std::endl;
return EXIT_FAILURE;
}
catch(...)
{
std::cerr << "Unknown exception thrown" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}<|endoftext|> |
<commit_before>/* $Id$ */
/*
* Copyright (c) 2010 SURFnet bv
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
/*****************************************************************************
OSSLCryptoFactory.cpp
This is an OpenSSL based cryptographic algorithm factory
*****************************************************************************/
#include "config.h"
#include "OSSLCryptoFactory.h"
#include "OSSLRNG.h"
#include "OSSLAES.h"
#include "OSSLDES.h"
#include "OSSLMD5.h"
#include "OSSLSHA1.h"
#include "OSSLSHA256.h"
#include "OSSLSHA512.h"
#include "OSSLRSA.h"
#include "OSSLDSA.h"
#include <algorithm>
#include <string.h>
#include <openssl/ssl.h>
// Initialise the one-and-only instance
std::auto_ptr<OSSLCryptoFactory> OSSLCryptoFactory::instance;
// Constructor
OSSLCryptoFactory::OSSLCryptoFactory()
{
// Initialise OpenSSL
OpenSSL_add_all_algorithms();
// Initialise the one-and-only RNG
rng = new OSSLRNG();
}
// Destructor
OSSLCryptoFactory::~OSSLCryptoFactory()
{
// Destroy the one-and-only RNG
delete rng;
}
// Return the one-and-only instance
OSSLCryptoFactory* OSSLCryptoFactory::i()
{
if (!instance.get())
{
instance = std::auto_ptr<OSSLCryptoFactory>(new OSSLCryptoFactory());
}
return instance.get();
}
// Create a concrete instance of a symmetric algorithm
SymmetricAlgorithm* OSSLCryptoFactory::getSymmetricAlgorithm(std::string algorithm)
{
std::string lcAlgo;
lcAlgo.resize(algorithm.size());
std::transform(algorithm.begin(), algorithm.end(), lcAlgo.begin(), tolower);
if (!lcAlgo.compare("aes"))
{
return new OSSLAES();
}
else if (!lcAlgo.compare("des") || !lcAlgo.compare("3des"))
{
return new OSSLDES();
}
else
{
// No algorithm implementation is available
ERROR_MSG("Unknown algorithm '%s'", lcAlgo.c_str());
return NULL;
}
}
// Create a concrete instance of an asymmetric algorithm
AsymmetricAlgorithm* OSSLCryptoFactory::getAsymmetricAlgorithm(std::string algorithm)
{
std::string lcAlgo;
lcAlgo.resize(algorithm.size());
std::transform(algorithm.begin(), algorithm.end(), lcAlgo.begin(), tolower);
if (!lcAlgo.compare("rsa"))
{
return new OSSLRSA();
}
else if (!lcAlgo.compare("dsa"))
{
return new OSSLDSA();
}
else
{
// No algorithm implementation is available
ERROR_MSG("Unknown algorithm '%s'", algorithm.c_str());
return NULL;
}
}
// Create a concrete instance of a hash algorithm
HashAlgorithm* OSSLCryptoFactory::getHashAlgorithm(std::string algorithm)
{
std::string lcAlgo;
lcAlgo.resize(algorithm.size());
std::transform(algorithm.begin(), algorithm.end(), lcAlgo.begin(), tolower);
if (!lcAlgo.compare("md5"))
{
return new OSSLMD5();
}
else if (!lcAlgo.compare("sha1"))
{
return new OSSLSHA1();
}
else if (!lcAlgo.compare("sha256"))
{
return new OSSLSHA256();
}
else if (!lcAlgo.compare("sha512"))
{
return new OSSLSHA512();
}
else
{
// No algorithm implementation is available
ERROR_MSG("Unknown algorithm '%s'", algorithm.c_str());
return NULL;
}
// No algorithm implementation is available
return NULL;
}
// Create a concrete instance of an RNG
RNG* OSSLCryptoFactory::getRNG(std::string name /* = "default" */)
{
std::string lcAlgo;
lcAlgo.resize(name.size());
std::transform(name.begin(), name.end(), lcAlgo.begin(), tolower);
if (!lcAlgo.compare("default"))
{
return rng;
}
else
{
// No algorithm implementation is available
ERROR_MSG("Unknown algorithm '%s'", name.c_str());
return NULL;
}
}
void OSSLCryptoFactory::recycleRNG(RNG* toRecycle)
{
// Do nothing; we keep the one-and-only instance
}
<commit_msg>Close down OpenSSL<commit_after>/* $Id$ */
/*
* Copyright (c) 2010 SURFnet bv
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
/*****************************************************************************
OSSLCryptoFactory.cpp
This is an OpenSSL based cryptographic algorithm factory
*****************************************************************************/
#include "config.h"
#include "OSSLCryptoFactory.h"
#include "OSSLRNG.h"
#include "OSSLAES.h"
#include "OSSLDES.h"
#include "OSSLMD5.h"
#include "OSSLSHA1.h"
#include "OSSLSHA256.h"
#include "OSSLSHA512.h"
#include "OSSLRSA.h"
#include "OSSLDSA.h"
#include <algorithm>
#include <string.h>
#include <openssl/ssl.h>
// Initialise the one-and-only instance
std::auto_ptr<OSSLCryptoFactory> OSSLCryptoFactory::instance;
// Constructor
OSSLCryptoFactory::OSSLCryptoFactory()
{
// Initialise OpenSSL
OpenSSL_add_all_algorithms();
// Initialise the one-and-only RNG
rng = new OSSLRNG();
}
// Destructor
OSSLCryptoFactory::~OSSLCryptoFactory()
{
// Destroy the one-and-only RNG
delete rng;
// Clean up OpenSSL
EVP_cleanup();
}
// Return the one-and-only instance
OSSLCryptoFactory* OSSLCryptoFactory::i()
{
if (!instance.get())
{
instance = std::auto_ptr<OSSLCryptoFactory>(new OSSLCryptoFactory());
}
return instance.get();
}
// Create a concrete instance of a symmetric algorithm
SymmetricAlgorithm* OSSLCryptoFactory::getSymmetricAlgorithm(std::string algorithm)
{
std::string lcAlgo;
lcAlgo.resize(algorithm.size());
std::transform(algorithm.begin(), algorithm.end(), lcAlgo.begin(), tolower);
if (!lcAlgo.compare("aes"))
{
return new OSSLAES();
}
else if (!lcAlgo.compare("des") || !lcAlgo.compare("3des"))
{
return new OSSLDES();
}
else
{
// No algorithm implementation is available
ERROR_MSG("Unknown algorithm '%s'", lcAlgo.c_str());
return NULL;
}
}
// Create a concrete instance of an asymmetric algorithm
AsymmetricAlgorithm* OSSLCryptoFactory::getAsymmetricAlgorithm(std::string algorithm)
{
std::string lcAlgo;
lcAlgo.resize(algorithm.size());
std::transform(algorithm.begin(), algorithm.end(), lcAlgo.begin(), tolower);
if (!lcAlgo.compare("rsa"))
{
return new OSSLRSA();
}
else if (!lcAlgo.compare("dsa"))
{
return new OSSLDSA();
}
else
{
// No algorithm implementation is available
ERROR_MSG("Unknown algorithm '%s'", algorithm.c_str());
return NULL;
}
}
// Create a concrete instance of a hash algorithm
HashAlgorithm* OSSLCryptoFactory::getHashAlgorithm(std::string algorithm)
{
std::string lcAlgo;
lcAlgo.resize(algorithm.size());
std::transform(algorithm.begin(), algorithm.end(), lcAlgo.begin(), tolower);
if (!lcAlgo.compare("md5"))
{
return new OSSLMD5();
}
else if (!lcAlgo.compare("sha1"))
{
return new OSSLSHA1();
}
else if (!lcAlgo.compare("sha256"))
{
return new OSSLSHA256();
}
else if (!lcAlgo.compare("sha512"))
{
return new OSSLSHA512();
}
else
{
// No algorithm implementation is available
ERROR_MSG("Unknown algorithm '%s'", algorithm.c_str());
return NULL;
}
// No algorithm implementation is available
return NULL;
}
// Create a concrete instance of an RNG
RNG* OSSLCryptoFactory::getRNG(std::string name /* = "default" */)
{
std::string lcAlgo;
lcAlgo.resize(name.size());
std::transform(name.begin(), name.end(), lcAlgo.begin(), tolower);
if (!lcAlgo.compare("default"))
{
return rng;
}
else
{
// No algorithm implementation is available
ERROR_MSG("Unknown algorithm '%s'", name.c_str());
return NULL;
}
}
void OSSLCryptoFactory::recycleRNG(RNG* toRecycle)
{
// Do nothing; we keep the one-and-only instance
}
<|endoftext|> |
<commit_before>/// \file
/// \ingroup tutorial_tdataframe
/// \notebook -draw
/// This tutorial shows how to implement a custom action.
/// As an example, we build a helper for filling THns.
///
/// \macro_code
///
/// \date April 2018
/// \author Enrico Guiraud, Danilo Piparo
template <typename T, unsigned int NDIM, typename... ColumnTypes>
class THnHelper : public ROOT::Detail::TDF::TActionImpl<THnHelper<T, NDIM, ColumnTypes...>> {
public:
// This is the list of the types of the columns
using ColumnTypes_t = ROOT::TypeTraits::TypeList<ColumnTypes...>;
using THn_t = THnT<T>;
using Result_t = THn_t;
private:
std::vector<std::shared_ptr<THn_t>> fHistos; // one per slot
const ROOT::Detail::TDF::ColumnNames_t fColumnNames;
public:
THnHelper(std::string_view name, std::string_view title, std::array<int, NDIM> nbins, std::array<double, NDIM> xmins,
std::array<double, NDIM> xmax, unsigned int nSlots, ROOT::Detail::TDF::ColumnNames_t columnNames)
: fHistos(nSlots, std::make_shared<THn_t>(std::string(name).c_str(), std::string(title).c_str(), NDIM,
nbins.data(), xmins.data(), xmax.data())),
fColumnNames(columnNames)
{
}
THnHelper(THnHelper &&) = default;
THnHelper(const THnHelper &) = delete;
ROOT::Detail::TDF::ColumnNames_t GetColumnNames() const { return fColumnNames; }
std::shared_ptr<THn_t> GetResultPtr() const { return fHistos[0]; }
void Initialize() {}
void InitTask(TTreeReader *, unsigned int) {}
void Exec(unsigned int slot, ColumnTypes... values)
{
std::array<double, sizeof...(ColumnTypes)> valuesArr{(double)values...};
fHistos[slot]->Fill(valuesArr.data());
}
void Finalize()
{
auto &res = fHistos[0];
for (auto slot : ROOT::TSeqU(1, fHistos.size())) {
res->Add(fHistos[slot].get());
}
}
};
void tdf018_customActions()
{
const auto nSlots = 4;
ROOT::EnableImplicitMT(nSlots);
ROOT::Experimental::TDataFrame d(128);
auto genD = []() { return gRandom->Uniform(-5, 5); };
auto genF = [&genD]() { return (float)genD(); };
auto genI = [&genD]() { return (int)genD(); };
auto dd = d.Define("x0", genD).Define("x1", genD).Define("x2", genF).Define("x3", genI);
using Helper_t = THnHelper<float, 4, double, double, float, int>;
Helper_t helper{"myThN",
"A THn with 4 dimensions",
{4, 4, 8, 2},
{-10., -10, -4., -6.},
{10., 10, 5., 7.},
nSlots,
{"x0", "x1", "x2", "x3", "x4"}};
auto myTHnT = dd.Book(std::move(helper));
myTHnT->Print();
}
<commit_msg>[TDF] Fix bug in MT execution, more elegant code, more explainations.<commit_after>/// \file
/// \ingroup tutorial_tdataframe
/// \notebook -draw
/// This tutorial shows how to implement a custom action.
/// As an example, we build a helper for filling THns.
///
/// \macro_code
///
/// \date April 2018
/// \author Enrico Guiraud, Danilo Piparo
// This is a custom action which respects a well defined interface. It supports parallelism,
// in the sense that it behaves correctly if implicit multi threading is enabled.
// We template it on:
// - The type of the internal THnT(s)
// - The dimension of the internal THnT(s)
// - The types of the columns which we will use
// Note the plural: in presence of a MT execution, internally more than a single THnT is created.
template <typename T, unsigned int NDIM, typename... ColumnTypes>
class THnHelper : public ROOT::Detail::TDF::TActionImpl<THnHelper<T, NDIM, ColumnTypes...>> {
public:
/// This is the list of the types of the columns, a requirement for every helper.
using ColumnTypes_t = ROOT::TypeTraits::TypeList<ColumnTypes...>;
/// This is a handy, expressive shortcut.
using THn_t = THnT<T>;
/// This type is a requirement for every helper.
using Result_t = THn_t;
private:
std::vector<std::shared_ptr<THn_t>> fHistos; // one per data processing slot
const ROOT::Detail::TDF::ColumnNames_t fColumnNames;
public:
/// This constructor takes all the parameters necessary to build the THnTs. In addition, it requires the names of
/// the columns which will be used.
THnHelper(std::string_view name, std::string_view title, std::array<int, NDIM> nbins, std::array<double, NDIM> xmins,
std::array<double, NDIM> xmax, ROOT::Detail::TDF::ColumnNames_t columnNames)
: fColumnNames(columnNames)
{
const auto nSlots = ROOT::GetImplicitMTPoolSize();
for (auto i : ROOT::TSeqU(nSlots)) {
fHistos.emplace_back(nSlots, std::make_shared<THn_t>(std::string(name).c_str(), std::string(title).c_str(),
NDIM, nbins.data(), xmins.data(), xmax.data())),
}
}
THnHelper(THnHelper &&) = default;
THnHelper(const THnHelper &) = delete;
ROOT::Detail::TDF::ColumnNames_t GetColumnNames() const { return fColumnNames; }
std::shared_ptr<THn_t> GetResultPtr() const { return fHistos[0]; }
void Initialize() {}
void InitTask(TTreeReader *, unsigned int) {}
/// This is a method executed at every entry. The types of the parameters are the ones with which we
/// templated the Helper.
void Exec(unsigned int slot, ColumnTypes... values)
{
// Since THnT<T>::Fill expects a double*, we build it passing through a std::array.
std::array<double, sizeof...(ColumnTypes)> valuesArr{std::static_cast<double>(values)...};
fHistos[slot]->Fill(valuesArr.data());
}
/// This method is called at the end of the event loop. It is used to merge all the internal THnTs which
/// were used in each of the data processing slots.
void Finalize()
{
auto &res = fHistos[0];
for (auto slot : ROOT::TSeqU(1, fHistos.size())) {
res->Add(fHistos[slot].get());
}
}
};
void tdf018_customActions()
{
// We enable implicit parallelism
ROOT::EnableImplicitMT();
// We create an empty TDataFrame which contains 4 columns filled with random numbers.
// The type of the numbers held by the columns are: double, double, float, int.
ROOT::Experimental::TDataFrame d(128);
auto genD = []() { return gRandom->Uniform(-5, 5); };
auto genF = [&genD]() { return (float)genD(); };
auto genI = [&genD]() { return (int)genD(); };
auto dd = d.Define("x0", genD).Define("x1", genD).Define("x2", genF).Define("x3", genI);
// Our Helper type: templated on the internal THnT type, the size, the types of the columns
// we'll use to fill.
using Helper_t = THnHelper<float, 4, double, double, float, int>;
Helper_t helper{"myThN", // Name
"A THn with 4 dimensions", // Title
{4, 4, 8, 2}, // NBins
{-10., -10, -4., -6.}, // Axes min values
{10., 10, 5., 7.}, // Axes max values
{"x0", "x1", "x2", "x3", "x4"}};
// We book the action: it will be treated during the event loop.
auto myTHnT = dd.Book(std::move(helper));
myTHnT->Print();
}
<|endoftext|> |
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2011 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// 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 "sparse.h"
template<typename Scalar> void sparse_vector(int rows, int cols)
{
double densityMat = (std::max)(8./(rows*cols), 0.01);
double densityVec = (std::max)(8./float(rows), 0.1);
typedef Matrix<Scalar,Dynamic,Dynamic> DenseMatrix;
typedef Matrix<Scalar,Dynamic,1> DenseVector;
typedef SparseVector<Scalar> SparseVectorType;
typedef SparseMatrix<Scalar> SparseMatrixType;
Scalar eps = 1e-6;
SparseMatrixType m1(rows,rows);
SparseVectorType v1(rows), v2(rows), v3(rows);
DenseMatrix refM1 = DenseMatrix::Zero(rows, rows);
DenseVector refV1 = DenseVector::Random(rows),
refV2 = DenseVector::Random(rows),
refV3 = DenseVector::Random(rows);
std::vector<int> zerocoords, nonzerocoords;
initSparse<Scalar>(densityVec, refV1, v1, &zerocoords, &nonzerocoords);
initSparse<Scalar>(densityMat, refM1, m1);
initSparse<Scalar>(densityVec, refV2, v2);
initSparse<Scalar>(densityVec, refV3, v3);
Scalar s1 = internal::random<Scalar>();
// test coeff and coeffRef
for (unsigned int i=0; i<zerocoords.size(); ++i)
{
VERIFY_IS_MUCH_SMALLER_THAN( v1.coeff(zerocoords[i]), eps );
//VERIFY_RAISES_ASSERT( v1.coeffRef(zerocoords[i]) = 5 );
}
{
VERIFY(int(nonzerocoords.size()) == v1.nonZeros());
int j=0;
for (typename SparseVectorType::InnerIterator it(v1); it; ++it,++j)
{
VERIFY(nonzerocoords[j]==it.index());
VERIFY(it.value()==v1.coeff(it.index()));
VERIFY(it.value()==refV1.coeff(it.index()));
}
}
VERIFY_IS_APPROX(v1, refV1);
v1.coeffRef(nonzerocoords[0]) = Scalar(5);
refV1.coeffRef(nonzerocoords[0]) = Scalar(5);
VERIFY_IS_APPROX(v1, refV1);
VERIFY_IS_APPROX(v1+v2, refV1+refV2);
VERIFY_IS_APPROX(v1+v2+v3, refV1+refV2+refV3);
VERIFY_IS_APPROX(v1*s1-v2, refV1*s1-refV2);
VERIFY_IS_APPROX(v1*=s1, refV1*=s1);
VERIFY_IS_APPROX(v1/=s1, refV1/=s1);
VERIFY_IS_APPROX(v1+=v2, refV1+=refV2);
VERIFY_IS_APPROX(v1-=v2, refV1-=refV2);
VERIFY_IS_APPROX(v1.dot(v2), refV1.dot(refV2));
VERIFY_IS_APPROX(v1.dot(refV2), refV1.dot(refV2));
VERIFY_IS_APPROX(v1.dot(m1*v2), refV1.dot(refM1*refV2));
int i = internal::random<int>(0,rows-1);
VERIFY_IS_APPROX(v1.dot(m1.col(i)), refV1.dot(refM1.col(i)));
VERIFY_IS_APPROX(v1.squaredNorm(), refV1.squaredNorm());
// test aliasing
VERIFY_IS_APPROX((v1 = -v1), (refV1 = -refV1));
VERIFY_IS_APPROX((v1 = v1.transpose()), (refV1 = refV1.transpose().eval()));
VERIFY_IS_APPROX((v1 += -v1), (refV1 += -refV1));
}
void test_sparse_vector()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( sparse_vector<double>(8, 8) );
CALL_SUBTEST_2( sparse_vector<std::complex<double> >(16, 16) );
CALL_SUBTEST_1( sparse_vector<double>(299, 535) );
}
}
<commit_msg>Test for the sparse Blue norm<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2011 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// 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 "sparse.h"
template<typename Scalar> void sparse_vector(int rows, int cols)
{
double densityMat = (std::max)(8./(rows*cols), 0.01);
double densityVec = (std::max)(8./float(rows), 0.1);
typedef Matrix<Scalar,Dynamic,Dynamic> DenseMatrix;
typedef Matrix<Scalar,Dynamic,1> DenseVector;
typedef SparseVector<Scalar> SparseVectorType;
typedef SparseMatrix<Scalar> SparseMatrixType;
Scalar eps = 1e-6;
SparseMatrixType m1(rows,rows);
SparseVectorType v1(rows), v2(rows), v3(rows);
DenseMatrix refM1 = DenseMatrix::Zero(rows, rows);
DenseVector refV1 = DenseVector::Random(rows),
refV2 = DenseVector::Random(rows),
refV3 = DenseVector::Random(rows);
std::vector<int> zerocoords, nonzerocoords;
initSparse<Scalar>(densityVec, refV1, v1, &zerocoords, &nonzerocoords);
initSparse<Scalar>(densityMat, refM1, m1);
initSparse<Scalar>(densityVec, refV2, v2);
initSparse<Scalar>(densityVec, refV3, v3);
Scalar s1 = internal::random<Scalar>();
// test coeff and coeffRef
for (unsigned int i=0; i<zerocoords.size(); ++i)
{
VERIFY_IS_MUCH_SMALLER_THAN( v1.coeff(zerocoords[i]), eps );
//VERIFY_RAISES_ASSERT( v1.coeffRef(zerocoords[i]) = 5 );
}
{
VERIFY(int(nonzerocoords.size()) == v1.nonZeros());
int j=0;
for (typename SparseVectorType::InnerIterator it(v1); it; ++it,++j)
{
VERIFY(nonzerocoords[j]==it.index());
VERIFY(it.value()==v1.coeff(it.index()));
VERIFY(it.value()==refV1.coeff(it.index()));
}
}
VERIFY_IS_APPROX(v1, refV1);
v1.coeffRef(nonzerocoords[0]) = Scalar(5);
refV1.coeffRef(nonzerocoords[0]) = Scalar(5);
VERIFY_IS_APPROX(v1, refV1);
VERIFY_IS_APPROX(v1+v2, refV1+refV2);
VERIFY_IS_APPROX(v1+v2+v3, refV1+refV2+refV3);
VERIFY_IS_APPROX(v1*s1-v2, refV1*s1-refV2);
VERIFY_IS_APPROX(v1*=s1, refV1*=s1);
VERIFY_IS_APPROX(v1/=s1, refV1/=s1);
VERIFY_IS_APPROX(v1+=v2, refV1+=refV2);
VERIFY_IS_APPROX(v1-=v2, refV1-=refV2);
VERIFY_IS_APPROX(v1.dot(v2), refV1.dot(refV2));
VERIFY_IS_APPROX(v1.dot(refV2), refV1.dot(refV2));
VERIFY_IS_APPROX(v1.dot(m1*v2), refV1.dot(refM1*refV2));
int i = internal::random<int>(0,rows-1);
VERIFY_IS_APPROX(v1.dot(m1.col(i)), refV1.dot(refM1.col(i)));
VERIFY_IS_APPROX(v1.squaredNorm(), refV1.squaredNorm());
VERIFY_IS_APPROX(v1.blueNorm(), refV1.blueNorm());
// test aliasing
VERIFY_IS_APPROX((v1 = -v1), (refV1 = -refV1));
VERIFY_IS_APPROX((v1 = v1.transpose()), (refV1 = refV1.transpose().eval()));
VERIFY_IS_APPROX((v1 += -v1), (refV1 += -refV1));
}
void test_sparse_vector()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( sparse_vector<double>(8, 8) );
CALL_SUBTEST_2( sparse_vector<std::complex<double> >(16, 16) );
CALL_SUBTEST_1( sparse_vector<double>(299, 535) );
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* *
* Copyright (c) 2013-2016 Boris Pek <tehnick-8@mail.ru> *
* *
* 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 <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <ctime>
#include <map>
#include <sys/types.h>
#include <sys/stat.h>
#include <cstdlib>
#include <cstring>
#include <fcgi_stdio.h>
#include "Version.h"
using std::map;
using std::string;
using std::stringstream;
using std::ifstream;
using std::ofstream;
using std::ios;
using std::cout;
string prefix_str = "/bosixnet/";
string log_dir = "/var/tmp/bosixnet";
string conf_file = "/etc/bosixnet/bosixnet-webui.conf";
map<string, string> hosts_map;
map<string, string> timestamps_map;
bool check_options(int, char **);
void read_options(int, char **);
void read_config();
void show_help();
void show_version();
void show_html(const string &);
void show_map(const map<string, string> &);
void show_hosts_map();
void show_timestamps_map();
void update_prefix_str(const string &);
void update_timestamp(const string &);
void read_file(const string &, map<string, string> &,
bool (*is_valid)(const string &));
void read_hosts();
void read_timestamps();
void write_file(const string &, const map<string, string> &);
void write_hosts();
void write_timestamps();
bool ends_with(const string &, const string &);
bool starts_with(const string &, const string &);
bool is_valid_ipv6_address(const string &);
bool is_valid_timestamp(const string &);
string get_env_var(const string &);
string get_param(const string &, const string &);
string get_conf_var(const string &, const string &);
string remove_extra_symbols(const string &, const string &);
int main(int argc, char **argv)
{
if (check_options(argc, argv))
return 0;
// Settings in config file have lower priority than command line options.
const string conf_file_default = conf_file;
read_config();
read_options(argc, argv);
if (conf_file != conf_file_default) {
read_config();
read_options(argc, argv);
}
read_hosts();
read_timestamps();
unsigned long long counter = 0;
while (FCGI_Accept() >= 0) {
++counter;
string content;
const string request_method = get_env_var("REQUEST_METHOD");
if (request_method.empty()) {
continue;
}
if (request_method == "GET") {
content = get_env_var("QUERY_STRING");
}
else {
show_html("<center><h2>Only GET request method is allowed!</h2></center>\n");
continue;
};
const string full_path = get_env_var("SCRIPT_NAME");
if (ends_with(full_path, prefix_str)) {
show_hosts_map();
}
else if (ends_with(full_path, prefix_str + "hosts")) {
show_hosts_map();
}
else if (ends_with(full_path, prefix_str + "timestamps")) {
show_timestamps_map();
}
else if (ends_with(full_path, prefix_str + "counter")) {
stringstream counter_str;
counter_str << counter;
show_html("Counter: " + counter_str.str());
}
else {
const string host_name = full_path.substr(full_path.rfind("/") + 1);
const string new_address = get_param(content, "update=");
if (new_address.empty()) {
const auto it = hosts_map.find(host_name);
if (it != hosts_map.end()) {
update_timestamp(host_name);
show_html(it->second);
}
else {
show_html("");
}
}
else if (is_valid_ipv6_address(new_address)) {
update_timestamp(host_name);
if (hosts_map[host_name] != new_address) {
hosts_map[host_name] = new_address;
write_hosts();
write_timestamps();
}
show_html(new_address);
}
else {
show_html(new_address + " is not a valid IPv6 address!");
}
}
}
return 0;
}
bool check_options(int argc, char **argv)
{
string arg;
for (int idx = 1 ; idx < argc ; ++idx) {
arg = argv[idx];
if (arg == "-h" || arg == "--help") {
show_help();
return true;
}
else if (arg == "-v" || arg == "--version") {
show_version();
return true;
}
}
return false;
}
void read_options(int argc, char **argv)
{
if (argc > 2) {
string arg;
string arg_next;
for (int idx = 1 ; idx < argc - 1 ; ++idx) {
arg = argv[idx];
arg_next = argv[idx + 1];
if (arg == "-b" || arg == "--prefix-str") {
update_prefix_str(arg_next);
}
else if (arg == "-l" || arg == "--log-dir") {
log_dir = arg_next;
}
else if (arg == "-c" || arg == "--conf-file") {
conf_file = arg_next;
}
}
}
}
void read_config()
{
ifstream file;
file.open(conf_file.c_str(), ios::in);
if (file.is_open()) {
string buff, var, tmp;
while (!file.eof()) {
getline(file, buff);
buff = remove_extra_symbols(buff, " \t");
if (buff.size() >= 3 && buff.at(0) != '#') {
// This block is added for back compatibility:
{ // TODO: delete later
var = "BASIC_STR";
tmp = get_conf_var(buff, var);
if (!tmp.empty()) {
update_prefix_str(tmp);
}
}
var = "PREFIX_STR";
tmp = get_conf_var(buff, var);
if (!tmp.empty()) {
update_prefix_str(tmp);
}
var = "LOG_DIR";
tmp = get_conf_var(buff, var);
if (!tmp.empty()) {
log_dir = tmp;
}
}
}
file.close();
}
}
void show_help()
{
cout << "Usage: bosixnet_webui [options]\n"
"\n"
"FastCGI program which passively listens for incoming connections and\n"
"generates list of hosts in your IPv6 network. This daemon prepares data\n"
"which may be put directly into /etc/hosts.\n"
"\n"
"Generic options:\n"
" -h, --help show help and exit\n"
" -v, --version show version and exit\n"
"\n"
"Options:\n"
" -b <string>, --prefix-str <string> set url prefix (default: " + prefix_str + ")\n"
" -l <dir>, --log-dir <dir> set directory for auxiliary files (default: " + log_dir + ")\n"
" -c <file>, --conf-file <file> set config file (default: " + conf_file + ")\n"
"\n"
"Settings in config file have lower priority than command line options.\n";
}
void show_version()
{
cout << "Version: " << VERSION << "\n";
}
void show_html(const string &str)
{
printf("Content-type: text/html\n\n");
printf("%s", str.c_str());
}
void show_map(const map<string, string> &map_name)
{
string out;
for (const auto &it : map_name) {
out += it.second + " " + it.first + "<br>\n";
}
show_html(out);
}
void show_hosts_map()
{
show_map(hosts_map);
}
void show_timestamps_map()
{
show_map(timestamps_map);
}
void update_prefix_str(const string &new_prefix_str)
{
prefix_str = new_prefix_str;
if (prefix_str.at(prefix_str.size()-1) != '/') {
prefix_str.push_back('/');
}
}
void update_timestamp(const string &host_name)
{
const time_t current_time = time(0);
const struct tm *time_info = localtime(¤t_time);
char new_timestamp[26];
strftime(new_timestamp, 26, "%F_%H:%M:%S_%z", time_info);
timestamps_map[host_name] = string(new_timestamp);
}
void read_file(const string &file_name, map<string, string> &map_name,
bool (*is_valid)(const string &))
{
const string log_file = log_dir + file_name;
ifstream file;
file.open(log_file.c_str(), ios::in);
if (file.is_open()) {
string buff, key, value;
stringstream str;
while (!file.eof()) {
getline(file, buff);
str.clear();
str << buff;
str >> value;
str >> key;
if (!value.empty() && !key.empty()) {
if (is_valid(value)) {
map_name[key] = value;
}
}
}
file.close();
}
}
void read_hosts()
{
read_file("/hosts", hosts_map, is_valid_ipv6_address);
}
void read_timestamps()
{
read_file("/timestamps", timestamps_map, is_valid_timestamp);
}
void write_file(const string &file_name, const map<string, string> &map_name)
{
struct stat info;
if (stat(log_dir.c_str(), &info)) {
if (mkdir(log_dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)) {
cout << "Directory " << log_dir << " was not created!\n";
return;
}
}
const string log_file = log_dir + file_name;
ofstream file;
file.open(log_file.c_str(), ios::out);
if (file.is_open()) {
for (const auto &it : map_name) {
file << it.second << " " << it.first << "\n";
}
file.close();
}
}
void write_hosts()
{
write_file("/hosts", hosts_map);
}
void write_timestamps()
{
write_file("/timestamps", timestamps_map);
}
bool ends_with(const string &str, const string &sfx)
{
if (sfx.size() > str.size())
return false;
return equal(str.begin() + str.size() - sfx.size(), str.end(), sfx.begin());
}
bool starts_with(const string &str, const string &pfx)
{
if (pfx.size() > str.size())
return false;
return equal(str.begin(), str.begin() + pfx.size(), pfx.begin());
}
bool is_valid_ipv6_address(const string &str)
{
const size_t len = str.size();
if (len < 8)
return false;
else if (len > 39)
return false;
unsigned int counter = 0;
const char *p = str.c_str();
while (strstr(p,":")) {
++counter;
++p;
}
if (counter < 3)
return false;
else if (str.at(4) != ':')
return false;
if (str.find_first_not_of(":0123456789abcdefABCDEF") != string::npos)
return false;
return true;
}
bool is_valid_timestamp(const string &str)
{
if (str.size() != 25)
return false;
if (str.at(4) != '-')
return false;
else if (str.at(7) != '-')
return false;
else if (str.at(10) != '_')
return false;
else if (str.at(13) != ':')
return false;
else if (str.at(16) != ':')
return false;
else if (str.at(19) != '_')
return false;
else if (str.at(20) != '+')
return false;
if (str.find_first_not_of("_+-:0123456789") != string::npos)
return false;
return true;
}
string get_env_var(const string &var)
{
const char *ptr = getenv(var.c_str());
return (ptr ? string(ptr) : "");
}
string get_param(const string &buff, const string &name)
{
if (buff.empty() || name.empty())
return "";
size_t param_begin = buff.find(name);
if (param_begin == string::npos)
return "";
param_begin += name.size();
if (param_begin >= buff.size())
return "";
size_t param_end = buff.find("&", param_begin);
if (param_end == string::npos)
param_end = buff.size();
const string out = buff.substr(param_begin, param_end - param_begin);
return out;
}
string get_conf_var(const string &buff, const string &var)
{
if (!starts_with(buff, var))
return "";
string out = buff.substr(var.size());
out = remove_extra_symbols(out, "= \t\"");
return out;
}
string remove_extra_symbols(const string &str, const string &symbols)
{
string out = str;
size_t pos = out.find_first_not_of(symbols);
if (pos != string::npos) {
out = out.substr(pos);
}
pos = out.find_last_not_of(symbols);
if (pos != string::npos && pos != out.size() - 1) {
out = out.substr(0, pos + 1);
}
return out;
}
<commit_msg>[Web UI] Decrease counter size.<commit_after>/*****************************************************************************
* *
* Copyright (c) 2013-2016 Boris Pek <tehnick-8@mail.ru> *
* *
* 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 <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <ctime>
#include <map>
#include <sys/types.h>
#include <sys/stat.h>
#include <cstdlib>
#include <cstring>
#include <fcgi_stdio.h>
#include "Version.h"
using std::map;
using std::string;
using std::stringstream;
using std::ifstream;
using std::ofstream;
using std::ios;
using std::cout;
string prefix_str = "/bosixnet/";
string log_dir = "/var/tmp/bosixnet";
string conf_file = "/etc/bosixnet/bosixnet-webui.conf";
map<string, string> hosts_map;
map<string, string> timestamps_map;
bool check_options(int, char **);
void read_options(int, char **);
void read_config();
void show_help();
void show_version();
void show_html(const string &);
void show_map(const map<string, string> &);
void show_hosts_map();
void show_timestamps_map();
void update_prefix_str(const string &);
void update_timestamp(const string &);
void read_file(const string &, map<string, string> &,
bool (*is_valid)(const string &));
void read_hosts();
void read_timestamps();
void write_file(const string &, const map<string, string> &);
void write_hosts();
void write_timestamps();
bool ends_with(const string &, const string &);
bool starts_with(const string &, const string &);
bool is_valid_ipv6_address(const string &);
bool is_valid_timestamp(const string &);
string get_env_var(const string &);
string get_param(const string &, const string &);
string get_conf_var(const string &, const string &);
string remove_extra_symbols(const string &, const string &);
int main(int argc, char **argv)
{
if (check_options(argc, argv))
return 0;
// Settings in config file have lower priority than command line options.
const string conf_file_default = conf_file;
read_config();
read_options(argc, argv);
if (conf_file != conf_file_default) {
read_config();
read_options(argc, argv);
}
read_hosts();
read_timestamps();
unsigned long counter = 0;
while (FCGI_Accept() >= 0) {
++counter;
string content;
const string request_method = get_env_var("REQUEST_METHOD");
if (request_method.empty()) {
continue;
}
if (request_method == "GET") {
content = get_env_var("QUERY_STRING");
}
else {
show_html("<center><h2>Only GET request method is allowed!</h2></center>\n");
continue;
};
const string full_path = get_env_var("SCRIPT_NAME");
if (ends_with(full_path, prefix_str)) {
show_hosts_map();
}
else if (ends_with(full_path, prefix_str + "hosts")) {
show_hosts_map();
}
else if (ends_with(full_path, prefix_str + "timestamps")) {
show_timestamps_map();
}
else if (ends_with(full_path, prefix_str + "counter")) {
stringstream counter_str;
counter_str << counter;
show_html("Counter: " + counter_str.str());
}
else {
const string host_name = full_path.substr(full_path.rfind("/") + 1);
const string new_address = get_param(content, "update=");
if (new_address.empty()) {
const auto it = hosts_map.find(host_name);
if (it != hosts_map.end()) {
update_timestamp(host_name);
show_html(it->second);
}
else {
show_html("");
}
}
else if (is_valid_ipv6_address(new_address)) {
update_timestamp(host_name);
if (hosts_map[host_name] != new_address) {
hosts_map[host_name] = new_address;
write_hosts();
write_timestamps();
}
show_html(new_address);
}
else {
show_html(new_address + " is not a valid IPv6 address!");
}
}
}
return 0;
}
bool check_options(int argc, char **argv)
{
string arg;
for (int idx = 1 ; idx < argc ; ++idx) {
arg = argv[idx];
if (arg == "-h" || arg == "--help") {
show_help();
return true;
}
else if (arg == "-v" || arg == "--version") {
show_version();
return true;
}
}
return false;
}
void read_options(int argc, char **argv)
{
if (argc > 2) {
string arg;
string arg_next;
for (int idx = 1 ; idx < argc - 1 ; ++idx) {
arg = argv[idx];
arg_next = argv[idx + 1];
if (arg == "-b" || arg == "--prefix-str") {
update_prefix_str(arg_next);
}
else if (arg == "-l" || arg == "--log-dir") {
log_dir = arg_next;
}
else if (arg == "-c" || arg == "--conf-file") {
conf_file = arg_next;
}
}
}
}
void read_config()
{
ifstream file;
file.open(conf_file.c_str(), ios::in);
if (file.is_open()) {
string buff, var, tmp;
while (!file.eof()) {
getline(file, buff);
buff = remove_extra_symbols(buff, " \t");
if (buff.size() >= 3 && buff.at(0) != '#') {
// This block is added for back compatibility:
{ // TODO: delete later
var = "BASIC_STR";
tmp = get_conf_var(buff, var);
if (!tmp.empty()) {
update_prefix_str(tmp);
}
}
var = "PREFIX_STR";
tmp = get_conf_var(buff, var);
if (!tmp.empty()) {
update_prefix_str(tmp);
}
var = "LOG_DIR";
tmp = get_conf_var(buff, var);
if (!tmp.empty()) {
log_dir = tmp;
}
}
}
file.close();
}
}
void show_help()
{
cout << "Usage: bosixnet_webui [options]\n"
"\n"
"FastCGI program which passively listens for incoming connections and\n"
"generates list of hosts in your IPv6 network. This daemon prepares data\n"
"which may be put directly into /etc/hosts.\n"
"\n"
"Generic options:\n"
" -h, --help show help and exit\n"
" -v, --version show version and exit\n"
"\n"
"Options:\n"
" -b <string>, --prefix-str <string> set url prefix (default: " + prefix_str + ")\n"
" -l <dir>, --log-dir <dir> set directory for auxiliary files (default: " + log_dir + ")\n"
" -c <file>, --conf-file <file> set config file (default: " + conf_file + ")\n"
"\n"
"Settings in config file have lower priority than command line options.\n";
}
void show_version()
{
cout << "Version: " << VERSION << "\n";
}
void show_html(const string &str)
{
printf("Content-type: text/html\n\n");
printf("%s", str.c_str());
}
void show_map(const map<string, string> &map_name)
{
string out;
for (const auto &it : map_name) {
out += it.second + " " + it.first + "<br>\n";
}
show_html(out);
}
void show_hosts_map()
{
show_map(hosts_map);
}
void show_timestamps_map()
{
show_map(timestamps_map);
}
void update_prefix_str(const string &new_prefix_str)
{
prefix_str = new_prefix_str;
if (prefix_str.at(prefix_str.size()-1) != '/') {
prefix_str.push_back('/');
}
}
void update_timestamp(const string &host_name)
{
const time_t current_time = time(0);
const struct tm *time_info = localtime(¤t_time);
char new_timestamp[26];
strftime(new_timestamp, 26, "%F_%H:%M:%S_%z", time_info);
timestamps_map[host_name] = string(new_timestamp);
}
void read_file(const string &file_name, map<string, string> &map_name,
bool (*is_valid)(const string &))
{
const string log_file = log_dir + file_name;
ifstream file;
file.open(log_file.c_str(), ios::in);
if (file.is_open()) {
string buff, key, value;
stringstream str;
while (!file.eof()) {
getline(file, buff);
str.clear();
str << buff;
str >> value;
str >> key;
if (!value.empty() && !key.empty()) {
if (is_valid(value)) {
map_name[key] = value;
}
}
}
file.close();
}
}
void read_hosts()
{
read_file("/hosts", hosts_map, is_valid_ipv6_address);
}
void read_timestamps()
{
read_file("/timestamps", timestamps_map, is_valid_timestamp);
}
void write_file(const string &file_name, const map<string, string> &map_name)
{
struct stat info;
if (stat(log_dir.c_str(), &info)) {
if (mkdir(log_dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)) {
cout << "Directory " << log_dir << " was not created!\n";
return;
}
}
const string log_file = log_dir + file_name;
ofstream file;
file.open(log_file.c_str(), ios::out);
if (file.is_open()) {
for (const auto &it : map_name) {
file << it.second << " " << it.first << "\n";
}
file.close();
}
}
void write_hosts()
{
write_file("/hosts", hosts_map);
}
void write_timestamps()
{
write_file("/timestamps", timestamps_map);
}
bool ends_with(const string &str, const string &sfx)
{
if (sfx.size() > str.size())
return false;
return equal(str.begin() + str.size() - sfx.size(), str.end(), sfx.begin());
}
bool starts_with(const string &str, const string &pfx)
{
if (pfx.size() > str.size())
return false;
return equal(str.begin(), str.begin() + pfx.size(), pfx.begin());
}
bool is_valid_ipv6_address(const string &str)
{
const size_t len = str.size();
if (len < 8)
return false;
else if (len > 39)
return false;
unsigned int counter = 0;
const char *p = str.c_str();
while (strstr(p,":")) {
++counter;
++p;
}
if (counter < 3)
return false;
else if (str.at(4) != ':')
return false;
if (str.find_first_not_of(":0123456789abcdefABCDEF") != string::npos)
return false;
return true;
}
bool is_valid_timestamp(const string &str)
{
if (str.size() != 25)
return false;
if (str.at(4) != '-')
return false;
else if (str.at(7) != '-')
return false;
else if (str.at(10) != '_')
return false;
else if (str.at(13) != ':')
return false;
else if (str.at(16) != ':')
return false;
else if (str.at(19) != '_')
return false;
else if (str.at(20) != '+')
return false;
if (str.find_first_not_of("_+-:0123456789") != string::npos)
return false;
return true;
}
string get_env_var(const string &var)
{
const char *ptr = getenv(var.c_str());
return (ptr ? string(ptr) : "");
}
string get_param(const string &buff, const string &name)
{
if (buff.empty() || name.empty())
return "";
size_t param_begin = buff.find(name);
if (param_begin == string::npos)
return "";
param_begin += name.size();
if (param_begin >= buff.size())
return "";
size_t param_end = buff.find("&", param_begin);
if (param_end == string::npos)
param_end = buff.size();
const string out = buff.substr(param_begin, param_end - param_begin);
return out;
}
string get_conf_var(const string &buff, const string &var)
{
if (!starts_with(buff, var))
return "";
string out = buff.substr(var.size());
out = remove_extra_symbols(out, "= \t\"");
return out;
}
string remove_extra_symbols(const string &str, const string &symbols)
{
string out = str;
size_t pos = out.find_first_not_of(symbols);
if (pos != string::npos) {
out = out.substr(pos);
}
pos = out.find_last_not_of(symbols);
if (pos != string::npos && pos != out.size() - 1) {
out = out.substr(0, pos + 1);
}
return out;
}
<|endoftext|> |
<commit_before>//---
//
// License: MIT
//
// File: ossim-foo.cpp
//
// Description: Contains application definition "ossim-foo" app.
//
// NOTE: This is supplied for simple quick test. DO NOT checkin your test to
// the svn repository. Simply edit ossim-foo.cpp and run your test.
// After completion you can do a "git checkout -- ossimfoo.cpp" if
// you want to keep your working repository up to snuff.
//
// $Id$
//---
// System includes:
#include <cmath>
#include <memory>
#include <sstream>
#include <iostream>
// ossim includes: These are here just to save time/typing...
#include <ossim/base/ossimApplicationUsage.h>
#include <ossim/base/ossimArgumentParser.h>
#include <ossim/base/ossimConnectableObject.h>
#include <ossim/base/ossimCsvFile.h>
#include <ossim/base/ossimDate.h>
#include <ossim/base/ossimDpt.h>
#include <ossim/base/ossimDrect.h>
#include <ossim/base/ossimException.h>
#include <ossim/base/ossimFilename.h>
#include <ossim/base/ossimIpt.h>
#include <ossim/base/ossimIrect.h>
#include <ossim/base/ossimKeywordlist.h>
#include <ossim/base/ossimKeywordNames.h>
#include <ossim/base/ossimNotify.h>
#include <ossim/base/ossimObjectFactory.h>
#include <ossim/base/ossimObjectFactoryRegistry.h>
#include <ossim/base/ossimProperty.h>
#include <ossim/base/ossimRefPtr.h>
#include <ossim/base/ossimString.h>
#include <ossim/base/ossimScalarTypeLut.h>
#include <ossim/base/ossimStdOutProgress.h>
#include <ossim/base/ossimStreamFactoryRegistry.h>
#include <ossim/base/ossimStringProperty.h>
#include <ossim/base/ossimTimer.h>
#include <ossim/base/ossimTrace.h>
#include <ossim/base/ossimUrl.h>
#include <ossim/base/ossimVisitor.h>
#include <ossim/base/ossimEcefPoint.h>
#include <ossim/base/ossimEcefVector.h>
#include <ossim/base/ossim2dBilinearTransform.h>
#include <ossim/imaging/ossimNitfTileSource.h>
#include <ossim/imaging/ossimBrightnessContrastSource.h>
#include <ossim/imaging/ossimBumpShadeTileSource.h>
#include <ossim/imaging/ossimFilterResampler.h>
#include <ossim/imaging/ossimFusionCombiner.h>
#include <ossim/imaging/ossimImageData.h>
#include <ossim/imaging/ossimImageFileWriter.h>
#include <ossim/imaging/ossimImageGeometry.h>
#include <ossim/imaging/ossimImageHandler.h>
#include <ossim/imaging/ossimImageMosaic.h>
#include <ossim/imaging/ossimImageRenderer.h>
#include <ossim/imaging/ossimImageSource.h>
#include <ossim/imaging/ossimImageSourceFilter.h>
#include <ossim/imaging/ossimImageToPlaneNormalFilter.h>
#include <ossim/imaging/ossimImageWriterFactoryRegistry.h>
#include <ossim/imaging/ossimIndexToRgbLutFilter.h>
#include <ossim/imaging/ossimRectangleCutFilter.h>
#include <ossim/imaging/ossimScalarRemapper.h>
#include <ossim/imaging/ossimSFIMFusion.h>
#include <ossim/imaging/ossimTwoColorView.h>
#include <ossim/imaging/ossimImageSourceFactoryRegistry.h>
#include <ossim/imaging/ossimImageHandlerRegistry.h>
#include <ossim/support_data/ImageHandlerState.h>
#include <ossim/init/ossimInit.h>
#include <ossim/projection/ossimEquDistCylProjection.h>
#include <ossim/projection/ossimImageViewAffineTransform.h>
#include <ossim/projection/ossimMapProjection.h>
#include <ossim/projection/ossimProjection.h>
#include <ossim/projection/ossimProjectionFactoryRegistry.h>
#include <ossim/projection/ossimUtmProjection.h>
#include <ossim/support_data/ossimSrcRecord.h>
#include <ossim/support_data/ossimWkt.h>
#include <ossim/base/Barrier.h>
#include <ossim/base/Block.h>
#include <ossim/base/Thread.h>
#include <ossim/support_data/TiffHandlerState.h>
#include <ossim/support_data/ImageHandlerStateRegistry.h>
// Put your includes here:
#include<ossim/projection/ossimNitfRpcModel.h>
#include<ossim/projection/ossimQuickbirdRpcModel.h>
int main(int argc, char *argv[])
{
int returnCode = 0;
ossimArgumentParser ap(&argc, argv);
ossimInit::instance()->addOptions(ap);
ossimInit::instance()->initialize(ap);
ossimFilename fname (argv[1]);
try
{
ossimImageHandlerRegistry* handlerReg = ossimImageHandlerRegistry::instance();
ossimProjectionFactoryRegistry* projReg = ossimProjectionFactoryRegistry::instance();
// Open the image and fetch the geometry via the plugin:
ossimRefPtr<ossimImageHandler> pluginHandler = handlerReg->open(fname, true, false);
ossimRefPtr<ossimImageGeometry> pluginGeom = pluginHandler->getImageGeometry();
cout<<"pluginGeom's projection: "<<pluginGeom->getProjection()->getClassName()<<endl;
// NITF:
ossimRefPtr<ossimNitfRpcModel> nitfProj = new ossimNitfRpcModel(fname);
ossimRefPtr<ossimImageGeometry> nitfGeom = new ossimImageGeometry(0, nitfProj.get());
cout<<"NITF projection: "<<nitfProj->getClassName()<<endl;
// QB:
ossimRefPtr<ossimQuickbirdRpcModel> dgqbProj = new ossimQuickbirdRpcModel();
dgqbProj->parseFile(fname);
ossimRefPtr<ossimImageGeometry> dgqbGeom = new ossimImageGeometry(0, dgqbProj.get());
cout<<"DG/QB projection: "<<dgqbProj->getClassName()<<endl;
// Establish even image point distribution:
ossimIrect imageRect;
pluginGeom->getBoundingRect(imageRect);
int dx = (imageRect.width()-1)/2;
int dy = (imageRect.height()-1)/2;
ossimGpt pluginGpt, nitfGpt, dgqbGpt;
ossimDpt ip0;
double nitfDist, dgqbDist;
// Compute residual error between models:
for (int Y=0; Y<3; Y++)
{
ip0.y = dy*Y;
for (int X=0; X<3; X++)
{
ip0.x = dx*X;
pluginGeom->localToWorld(ip0, 0, pluginGpt);
nitfGeom->localToWorld(ip0, 0, nitfGpt);
nitfDist = pluginGpt.distanceTo(nitfGpt);
dgqbGeom->localToWorld(ip0, 0, dgqbGpt);
dgqbDist = pluginGpt.distanceTo(dgqbGpt);
cout <<"\nGround residuals for image point "<<ip0<<":"
<<"\n NITF: "<<nitfDist<<" m"
<<"\n DGQB: "<<dgqbDist<<" m"<<endl;
}
}
}
catch(const ossimException& e)
{
ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl;
returnCode = 1;
}
catch( ... )
{
ossimNotify(ossimNotifyLevel_WARN)
<< "ossim-foo caught unhandled exception!" << std::endl;
returnCode = 1;
}
return returnCode;
}
<commit_msg>Reverted ossim-foo<commit_after>//---
//
// License: MIT
//
// File: ossim-foo.cpp
//
// Description: Contains application definition "ossim-foo" app.
//
// NOTE: This is supplied for simple quick test. DO NOT checkin your test to
// the svn repository. Simply edit ossim-foo.cpp and run your test.
// After completion you can do a "git checkout -- ossimfoo.cpp" if
// you want to keep your working repository up to snuff.
//
// $Id$
//---
// System includes:
#include <cmath>
#include <memory>
#include <sstream>
#include <iostream>
// ossim includes: These are here just to save time/typing...
#include <ossim/base/ossimApplicationUsage.h>
#include <ossim/base/ossimArgumentParser.h>
#include <ossim/base/ossimConnectableObject.h>
#include <ossim/base/ossimCsvFile.h>
#include <ossim/base/ossimDate.h>
#include <ossim/base/ossimDpt.h>
#include <ossim/base/ossimDrect.h>
#include <ossim/base/ossimException.h>
#include <ossim/base/ossimFilename.h>
#include <ossim/base/ossimIpt.h>
#include <ossim/base/ossimIrect.h>
#include <ossim/base/ossimKeywordlist.h>
#include <ossim/base/ossimKeywordNames.h>
#include <ossim/base/ossimNotify.h>
#include <ossim/base/ossimObjectFactory.h>
#include <ossim/base/ossimObjectFactoryRegistry.h>
#include <ossim/base/ossimProperty.h>
#include <ossim/base/ossimRefPtr.h>
#include <ossim/base/ossimString.h>
#include <ossim/base/ossimScalarTypeLut.h>
#include <ossim/base/ossimStdOutProgress.h>
#include <ossim/base/ossimStreamFactoryRegistry.h>
#include <ossim/base/ossimStringProperty.h>
#include <ossim/base/ossimTimer.h>
#include <ossim/base/ossimTrace.h>
#include <ossim/base/ossimUrl.h>
#include <ossim/base/ossimVisitor.h>
#include <ossim/base/ossimEcefPoint.h>
#include <ossim/base/ossimEcefVector.h>
#include <ossim/base/ossim2dBilinearTransform.h>
#include <ossim/imaging/ossimNitfTileSource.h>
#include <ossim/imaging/ossimBrightnessContrastSource.h>
#include <ossim/imaging/ossimBumpShadeTileSource.h>
#include <ossim/imaging/ossimFilterResampler.h>
#include <ossim/imaging/ossimFusionCombiner.h>
#include <ossim/imaging/ossimImageData.h>
#include <ossim/imaging/ossimImageFileWriter.h>
#include <ossim/imaging/ossimImageGeometry.h>
#include <ossim/imaging/ossimImageHandler.h>
#include <ossim/imaging/ossimImageMosaic.h>
#include <ossim/imaging/ossimImageRenderer.h>
#include <ossim/imaging/ossimImageSource.h>
#include <ossim/imaging/ossimImageSourceFilter.h>
#include <ossim/imaging/ossimImageToPlaneNormalFilter.h>
#include <ossim/imaging/ossimImageWriterFactoryRegistry.h>
#include <ossim/imaging/ossimIndexToRgbLutFilter.h>
#include <ossim/imaging/ossimRectangleCutFilter.h>
#include <ossim/imaging/ossimScalarRemapper.h>
#include <ossim/imaging/ossimSFIMFusion.h>
#include <ossim/imaging/ossimTwoColorView.h>
#include <ossim/imaging/ossimImageSourceFactoryRegistry.h>
#include <ossim/imaging/ossimImageHandlerRegistry.h>
#include <ossim/support_data/ImageHandlerState.h>
#include <ossim/init/ossimInit.h>
#include <ossim/projection/ossimEquDistCylProjection.h>
#include <ossim/projection/ossimImageViewAffineTransform.h>
#include <ossim/projection/ossimMapProjection.h>
#include <ossim/projection/ossimProjection.h>
#include <ossim/projection/ossimProjectionFactoryRegistry.h>
#include <ossim/projection/ossimUtmProjection.h>
#include <ossim/support_data/ossimSrcRecord.h>
#include <ossim/support_data/ossimWkt.h>
#include <ossim/base/Barrier.h>
#include <ossim/base/Block.h>
#include <ossim/base/Thread.h>
#include <ossim/support_data/TiffHandlerState.h>
#include <ossim/support_data/ImageHandlerStateRegistry.h>
#include <ossim/projection/ossimNitfRpcModel.h>
#include <ossim/projection/ossimQuickbirdRpcModel.h>
// Put your includes here:
int main(int argc, char *argv[])
{
int returnCode = 0;
ossimArgumentParser ap(&argc, argv);
ossimInit::instance()->addOptions(ap);
ossimInit::instance()->initialize(ap);
ossimFilename fname (argv[1]);
try
{
}
catch(const ossimException& e)
{
ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl;
returnCode = 1;
}
catch( ... )
{
ossimNotify(ossimNotifyLevel_WARN)
<< "ossim-foo caught unhandled exception!" << std::endl;
returnCode = 1;
}
return returnCode;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Kamil Michalak <kmichalak8@gmail.com>
*
* 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 "test/inc/querytest.hpp"
#include "inc/query.hpp"
#include "test/inc/assert.hpp"
void QueryTest::SetUp()
{
}
void QueryTest::TearDown()
{
}
TEST_F(QueryTest, WithProjectSetsProjectInJsonStructure)
{
// given
std::string projectName = "MyTestProjectToSet";
jippi::Query *query = new jippi::Query("http:://mock.url.org");
// when
query->withProject(projectName);
// then - should get something like "jql":"project = MyTestProjectToSet"
std::string jsonPayload = query->getJsonPayload();
std::string expected = "\"jql\" : \"project=" + projectName+"\"";
std::cerr << expected << std::endl;
EXPECT_STR_CONTAINS(jsonPayload, expected);
}
TEST_F(QueryTest, WithAssigneeSetsAssigneeInJsonStructure)
{
// when
std::string assignee = "MyMockAssignee";
jippi::Query *query = new jippi::Query("http://mock.url.org");
// when
query->withAssignee(assignee);
std::string jsonPayload = query->getJsonPayload();
// then
std::string expected = "\"assignee\" : \""+ assignee+"\"";
std::cerr << expected << std::endl;
EXPECT_STR_CONTAINS(jsonPayload, expected);
}
<commit_msg>Reformat querytest.cpp<commit_after>/*
* Copyright 2014 Kamil Michalak <kmichalak8@gmail.com>
*
* 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 "test/inc/querytest.hpp"
#include "inc/query.hpp"
#include "test/inc/assert.hpp"
void QueryTest::SetUp()
{
}
void QueryTest::TearDown()
{
}
TEST_F(QueryTest, WithProjectSetsProjectInJsonStructure)
{
// given
std::string projectName = "MyTestProjectToSet";
jippi::Query *query = new jippi::Query("http:://mock.url.org");
// when
query->withProject(projectName);
// then - should get something like "jql":"project = MyTestProjectToSet"
std::string jsonPayload = query->getJsonPayload();
EXPECT_STR_CONTAINS(jsonPayload, "\"jql\" : \"project=" + projectName+"\"");
}
TEST_F(QueryTest, WithAssigneeSetsAssigneeInJsonStructure)
{
// when
std::string assignee = "MyMockAssignee";
jippi::Query *query = new jippi::Query("http://mock.url.org");
// when
query->withAssignee(assignee);
std::string jsonPayload = query->getJsonPayload();
// then;
EXPECT_STR_CONTAINS(jsonPayload, "\"assignee\" : \""+ assignee+"\"");
}
<|endoftext|> |
<commit_before>#include "BoundingBox.hpp"
#include "Exceptions.hpp"
#include "clipper/clipper.hpp"
#include "builders/BuilderContext.hpp"
#include "builders/terrain/LineGridSplitter.hpp"
#include "builders/terrain/TerraBuilder.hpp"
#include "entities/Node.hpp"
#include "entities/Way.hpp"
#include "entities/Area.hpp"
#include "entities/Relation.hpp"
#include "entities/ElementVisitor.hpp"
#include "meshing/Polygon.hpp"
#include "meshing/MeshBuilder.hpp"
#include "utils/CompatibilityUtils.hpp"
#include "utils/GeoUtils.hpp"
#include "utils/MapCssUtils.hpp"
#include "utils/NoiseUtils.hpp"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <functional>
#include <iterator>
#include <sstream>
#include <map>
#include <unordered_map>
#include <vector>
using namespace ClipperLib;
using namespace utymap::builders;
using namespace utymap::entities;
using namespace utymap::index;
using namespace utymap::heightmap;
using namespace utymap::mapcss;
using namespace utymap::meshing;
using namespace utymap::utils;
const uint64_t Scale = 1E7; // max precision for Lat/Lon: seven decimal positions
const double Tolerance = 10; // Tolerance for splitting algorithm
const double AreaTolerance = 100; // Tolerance for meshing
// Represents terrain region points.
struct Region
{
bool isLayer;
std::shared_ptr<MeshBuilder::Options> options; // optional: might be empty if polygon is layer
Paths points;
};
typedef std::vector<Point> Points;
typedef std::vector<Region> Regions;
typedef std::unordered_map<std::string, Regions> Layers;
// mapcss specific keys
const static std::string TerrainLayerKey = "terrain-layer";
const static std::string ColorNoiseFreqKey = "color-noise-freq";
const static std::string EleNoiseFreqKey = "ele-noise-freq";
const static std::string GradientKey= "color";
const static std::string MaxAreaKey = "max-area";
const static std::string WidthKey = "width";
const static std::string HeightKey = "height";
const static std::string LayerPriorityKey = "layer-priority";
const static std::string MeshNameKey = "mesh-name";
class TerraBuilder::TerraBuilderImpl : public ElementBuilder
{
public:
TerraBuilderImpl(const BuilderContext& context) :
ElementBuilder(context), splitter_(), mesh_("terrain")
{
}
void visitNode(const utymap::entities::Node& node)
{
}
void visitWay(const utymap::entities::Way& way)
{
Style style = context_.styleProvider.forElement(way, context_.quadKey.levelOfDetail);
Region region = createRegion(style, way.coordinates);
// make polygon from line by offsetting it using width specified
double width = utymap::utils::getDouble(WidthKey, context_.stringTable, style);
Paths offsetSolution;
offset_.AddPaths(region.points, jtMiter, etOpenSquare);
offset_.Execute(offsetSolution, width * Scale);
offset_.Clear();
region.points = offsetSolution;
std::string type = region.isLayer ? utymap::utils::getString(TerrainLayerKey, context_.stringTable, style) : "";
layers_[type].push_back(region);
}
void visitArea(const utymap::entities::Area& area)
{
Style style = context_.styleProvider.forElement(area, context_.quadKey.levelOfDetail);
Region region = createRegion(style, area.coordinates);
std::string type = region.isLayer
? utymap::utils::getString(TerrainLayerKey, context_.stringTable, style)
: "";
layers_[type].push_back(region);
}
void visitRelation(const utymap::entities::Relation& relation)
{
Region region;
struct RelationVisitor : public ElementVisitor
{
const Relation& relation;
TerraBuilder::TerraBuilderImpl& builder;
Region& region;
RelationVisitor(TerraBuilder::TerraBuilderImpl& builder, const Relation& relation, Region& region) :
builder(builder), relation(relation), region(region) {}
void visitNode(const utymap::entities::Node& node) { node.accept(builder); }
void visitWay(const utymap::entities::Way& way) { way.accept(builder); }
void visitArea(const utymap::entities::Area& area)
{
Path path;
path.reserve(area.coordinates.size());
for (const GeoCoordinate& c : area.coordinates)
path.push_back(IntPoint(c.longitude * Scale, c.latitude * Scale));
region.points.push_back(path);
}
void visitRelation(const utymap::entities::Relation& relation) { relation.accept(builder); }
} visitor(*this, relation, region);
for (const auto& element : relation.elements) {
// if there are no tags, then this element is result of clipping
if (element->tags.empty())
element->tags = relation.tags;
element->accept(visitor);
}
if (!region.points.empty()) {
Style style = context_.styleProvider.forElement(relation, context_.quadKey.levelOfDetail);
region.isLayer = style.has(context_.stringTable.getId(TerrainLayerKey));
if (!region.isLayer)
region.options = createMeshOptions(style, "");
std::string type = region.isLayer
? utymap::utils::getString(TerrainLayerKey, context_.stringTable, style)
: "";
layers_[type].push_back(region);
}
}
// builds tile mesh using data provided.
void complete()
{
Style style = context_.styleProvider.forCanvas(context_.quadKey.levelOfDetail);
double step = utymap::utils::getDouble(MaxAreaKey, context_.stringTable, style);
splitter_.setParams(Scale, step, Tolerance);
BoundingBox bbox = utymap::utils::GeoUtils::quadKeyToBoundingBox(context_.quadKey);
rect_ = Rectangle(bbox.minPoint.longitude, bbox.minPoint.latitude,
bbox.maxPoint.longitude, bbox.maxPoint.latitude);
buildLayers(style);
buildBackground(style);
context_.meshCallback(mesh_);
}
private:
// process all found layers.
void buildLayers(const Style& style)
{
// 1. process layers: regions with shared properties.
std::stringstream ss(utymap::utils::getString(LayerPriorityKey, context_.stringTable, style));
while (ss.good()) {
std::string name;
getline(ss, name, ',');
auto layer = layers_.find(name);
if (layer != layers_.end()) {
buildFromRegions(layer->second, createMeshOptions(style, name + "-"));
layers_.erase(layer);
}
}
// 2. Process the rest: each region has aready its own properties.
for (auto& layer : layers_)
for (auto& region : layer.second) {
buildFromPaths(region.points, region.options, false);
}
}
// process the rest area.
void buildBackground(const Style& style)
{
BoundingBox bbox = utymap::utils::GeoUtils::quadKeyToBoundingBox(context_.quadKey);
Path tileRect;
tileRect.push_back(IntPoint(bbox.minPoint.longitude*Scale, bbox.minPoint.latitude *Scale));
tileRect.push_back(IntPoint(bbox.maxPoint.longitude *Scale, bbox.minPoint.latitude *Scale));
tileRect.push_back(IntPoint(bbox.maxPoint.longitude *Scale, bbox.maxPoint.latitude*Scale));
tileRect.push_back(IntPoint(bbox.minPoint.longitude*Scale, bbox.maxPoint.latitude*Scale));
clipper_.AddPath(tileRect, ptSubject, true);
clipper_.AddPaths(backgroundClipArea_, ptClip, true);
Paths background;
clipper_.Execute(ctDifference, background, pftPositive, pftPositive);
clipper_.Clear();
if (!background.empty())
populateMesh(createMeshOptions(style, ""), background);
}
Region createRegion(const Style& style, const std::vector<GeoCoordinate>& coordinates)
{
Region region;
Path path;
path.reserve(coordinates.size());
for (const GeoCoordinate& c : coordinates)
path.push_back(IntPoint(c.longitude * Scale, c.latitude * Scale));
region.points.push_back(path);
region.isLayer = style.has(context_.stringTable.getId(TerrainLayerKey));
if (!region.isLayer)
region.options = createMeshOptions(style, "");
return std::move(region);
}
std::shared_ptr<MeshBuilder::Options> createMeshOptions(const Style& style, const std::string& prefix)
{
std::string gradientKey = utymap::utils::getString(prefix + GradientKey, context_.stringTable, style);
return std::shared_ptr<MeshBuilder::Options>(new MeshBuilder::Options(
utymap::utils::getDouble(prefix + MaxAreaKey, context_.stringTable, style),
utymap::utils::getDouble(prefix + EleNoiseFreqKey, context_.stringTable, style),
utymap::utils::getDouble(prefix + ColorNoiseFreqKey, context_.stringTable, style),
utymap::utils::getDouble(prefix + HeightKey, context_.stringTable, style, 0),
context_.styleProvider.getGradient(gradientKey),
utymap::utils::getString(prefix + MeshNameKey, context_.stringTable, style, "")));
}
void buildFromRegions(const Regions& regions, const std::shared_ptr<MeshBuilder::Options>& options)
{
// merge all regions together
Clipper clipper;
for (const Region& region : regions)
clipper.AddPaths(region.points, ptSubject, true);
Paths result;
clipper.Execute(ctUnion, result, pftPositive, pftPositive);
buildFromPaths(result, options);
}
void buildFromPaths(Paths& paths, const std::shared_ptr<MeshBuilder::Options>& options, bool moveSubjectToClip = true)
{
clipper_.AddPaths(paths, ptSubject, true);
paths.clear();
clipper_.Execute(ctDifference, paths, pftPositive, pftPositive);
// NOTE: this is performance optimization: we cannot make all
// polygons to be clipping as it slows down clipper dramatically.
if (moveSubjectToClip) {
clipper_.moveSubjectToClip();
}
else {
backgroundClipArea_.insert(backgroundClipArea_.end(), paths.begin(), paths.end());
clipper_.removeSubject();
}
populateMesh(options, paths);
}
void populateMesh(const std::shared_ptr<MeshBuilder::Options>& options, Paths& paths)
{
ClipperLib::SimplifyPolygons(paths);
ClipperLib::CleanPolygons(paths);
bool hasHeightOffset = std::abs(options->heightOffset) > 1E-8;
// calculate approximate size of overall points
auto size = 0;
for (auto i = 0; i < paths.size(); ++i)
size += paths[i].size() * 1.5;
Polygon polygon(size);
for (const Path& path : paths) {
double area = ClipperLib::Area(path);
bool isHole = area < 0;
if (std::abs(area) < AreaTolerance)
continue;
Points points = restorePoints(path);
if (isHole)
polygon.addHole(points);
else
polygon.addContour(points);
if (hasHeightOffset)
processHeightOffset(options, points, isHole);
}
if (!polygon.points.empty())
fillMesh(options, polygon);
}
// restores mesh points from clipper points and injects new ones according to grid.
Points restorePoints(const Path& path)
{
int lastItemIndex = path.size() - 1;
Points points;
points.reserve(path.size());
for (int i = 0; i <= lastItemIndex; i++)
splitter_.split(path[i], path[i == lastItemIndex ? 0 : i + 1], points);
return std::move(points);
}
void fillMesh(const std::shared_ptr<MeshBuilder::Options>& options, Polygon& polygon)
{
if (options->meshName != "") {
Mesh polygonMesh(options->meshName);
context_.meshBuilder.addPolygon(polygonMesh, polygon, *options);
context_.meshCallback(polygonMesh);
}
else {
context_.meshBuilder.addPolygon(mesh_, polygon, *options);
}
}
void processHeightOffset(const std::shared_ptr<MeshBuilder::Options>& options, const Points& points, bool isHole)
{
auto index = mesh_.vertices.size() / 3;
for (auto i = 0; i < points.size(); ++i) {
Point p1 = points[i];
Point p2 = points[i == (points.size() - 1) ? 0 : i + 1];
// check whether two points are on cell rect
if (rect_.isOnBorder(p1) && rect_.isOnBorder(p2)) continue;
context_.meshBuilder.addPlane(mesh_, p1, p2, *options);
}
}
ClipperEx clipper_;
ClipperOffset offset_;
LineGridSplitter splitter_;
Rectangle rect_;
Layers layers_;
Paths backgroundClipArea_;
Mesh mesh_;
};
void TerraBuilder::visitNode(const utymap::entities::Node& node) { pimpl_->visitNode(node); }
void TerraBuilder::visitWay(const utymap::entities::Way& way) { pimpl_->visitWay(way); }
void TerraBuilder::visitArea(const utymap::entities::Area& area) { pimpl_->visitArea(area); }
void TerraBuilder::visitRelation(const utymap::entities::Relation& relation) { pimpl_->visitRelation(relation); }
void TerraBuilder::complete() { pimpl_->complete(); }
TerraBuilder::~TerraBuilder() { }
TerraBuilder::TerraBuilder(const BuilderContext& context) :
utymap::builders::ElementBuilder(context),
pimpl_(new TerraBuilder::TerraBuilderImpl(context))
{
}
<commit_msg>terra builder: introduce ratio<commit_after>#include "BoundingBox.hpp"
#include "Exceptions.hpp"
#include "clipper/clipper.hpp"
#include "builders/BuilderContext.hpp"
#include "builders/terrain/LineGridSplitter.hpp"
#include "builders/terrain/TerraBuilder.hpp"
#include "entities/Node.hpp"
#include "entities/Way.hpp"
#include "entities/Area.hpp"
#include "entities/Relation.hpp"
#include "entities/ElementVisitor.hpp"
#include "meshing/Polygon.hpp"
#include "meshing/MeshBuilder.hpp"
#include "utils/CompatibilityUtils.hpp"
#include "utils/GeoUtils.hpp"
#include "utils/MapCssUtils.hpp"
#include "utils/NoiseUtils.hpp"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <functional>
#include <iterator>
#include <sstream>
#include <map>
#include <unordered_map>
#include <vector>
using namespace ClipperLib;
using namespace utymap::builders;
using namespace utymap::entities;
using namespace utymap::index;
using namespace utymap::heightmap;
using namespace utymap::mapcss;
using namespace utymap::meshing;
using namespace utymap::utils;
const uint64_t Scale = 1E7; // max precision for Lat/Lon: seven decimal positions
const double Tolerance = 10; // Tolerance for splitting algorithm
const double AreaTolerance = 100; // Tolerance for meshing
// Represents terrain region points.
struct Region
{
bool isLayer;
std::shared_ptr<MeshBuilder::Options> options; // optional: might be empty if polygon is layer
Paths points;
};
typedef std::vector<Point> Points;
typedef std::vector<Region> Regions;
typedef std::unordered_map<std::string, Regions> Layers;
// mapcss specific keys
const static std::string TerrainLayerKey = "terrain-layer";
const static std::string ColorNoiseFreqKey = "color-noise-freq";
const static std::string EleNoiseFreqKey = "ele-noise-freq";
const static std::string GradientKey= "color";
const static std::string MaxAreaKey = "max-area";
const static std::string WidthKey = "width";
const static std::string HeightKey = "height";
const static std::string LayerPriorityKey = "layer-priority";
const static std::string MeshNameKey = "mesh-name";
class TerraBuilder::TerraBuilderImpl : public ElementBuilder
{
public:
TerraBuilderImpl(const BuilderContext& context) :
ElementBuilder(context), splitter_(), mesh_("terrain")
{
}
void visitNode(const utymap::entities::Node& node)
{
}
void visitWay(const utymap::entities::Way& way)
{
Style style = context_.styleProvider.forElement(way, context_.quadKey.levelOfDetail);
Region region = createRegion(style, way.coordinates);
// make polygon from line by offsetting it using width specified
double width = utymap::utils::getDouble(WidthKey, context_.stringTable, style);
Paths offsetSolution;
offset_.AddPaths(region.points, jtMiter, etOpenSquare);
offset_.Execute(offsetSolution, width * getLodRatio() * Scale);
offset_.Clear();
region.points = offsetSolution;
std::string type = region.isLayer
? utymap::utils::getString(TerrainLayerKey, context_.stringTable, style)
: "";
layers_[type].push_back(region);
}
void visitArea(const utymap::entities::Area& area)
{
Style style = context_.styleProvider.forElement(area, context_.quadKey.levelOfDetail);
Region region = createRegion(style, area.coordinates);
std::string type = region.isLayer
? utymap::utils::getString(TerrainLayerKey, context_.stringTable, style)
: "";
layers_[type].push_back(region);
}
void visitRelation(const utymap::entities::Relation& relation)
{
Region region;
struct RelationVisitor : public ElementVisitor
{
const Relation& relation;
TerraBuilder::TerraBuilderImpl& builder;
Region& region;
RelationVisitor(TerraBuilder::TerraBuilderImpl& builder, const Relation& relation, Region& region) :
builder(builder), relation(relation), region(region) {}
void visitNode(const utymap::entities::Node& node) { node.accept(builder); }
void visitWay(const utymap::entities::Way& way) { way.accept(builder); }
void visitArea(const utymap::entities::Area& area)
{
Path path;
path.reserve(area.coordinates.size());
for (const GeoCoordinate& c : area.coordinates)
path.push_back(IntPoint(c.longitude * Scale, c.latitude * Scale));
region.points.push_back(path);
}
void visitRelation(const utymap::entities::Relation& relation) { relation.accept(builder); }
} visitor(*this, relation, region);
for (const auto& element : relation.elements) {
// if there are no tags, then this element is result of clipping
if (element->tags.empty())
element->tags = relation.tags;
element->accept(visitor);
}
if (!region.points.empty()) {
Style style = context_.styleProvider.forElement(relation, context_.quadKey.levelOfDetail);
region.isLayer = style.has(context_.stringTable.getId(TerrainLayerKey));
if (!region.isLayer)
region.options = createMeshOptions(style, "");
std::string type = region.isLayer
? utymap::utils::getString(TerrainLayerKey, context_.stringTable, style)
: "";
layers_[type].push_back(region);
}
}
// builds tile mesh using data provided.
void complete()
{
Style style = context_.styleProvider.forCanvas(context_.quadKey.levelOfDetail);
configure(style);
buildLayers(style);
buildBackground(style);
context_.meshCallback(mesh_);
}
private:
inline double getLodRatio() {
return std::pow(2, -(context_.quadKey.levelOfDetail - 1));
}
void configure(const Style& style)
{
BoundingBox bbox = utymap::utils::GeoUtils::quadKeyToBoundingBox(context_.quadKey);
rect_ = Rectangle(bbox.minPoint.longitude, bbox.minPoint.latitude,
bbox.maxPoint.longitude, bbox.maxPoint.latitude);
double step = utymap::utils::getDouble(MaxAreaKey, context_.stringTable, style) * getLodRatio();
splitter_.setParams(Scale, step, Tolerance);
}
// process all found layers.
void buildLayers(const Style& style)
{
// 1. process layers: regions with shared properties.
std::stringstream ss(utymap::utils::getString(LayerPriorityKey, context_.stringTable, style));
while (ss.good()) {
std::string name;
getline(ss, name, ',');
auto layer = layers_.find(name);
if (layer != layers_.end()) {
buildFromRegions(layer->second, createMeshOptions(style, name + "-"));
layers_.erase(layer);
}
}
// 2. Process the rest: each region has aready its own properties.
for (auto& layer : layers_)
for (auto& region : layer.second) {
buildFromPaths(region.points, region.options, false);
}
}
// process the rest area.
void buildBackground(const Style& style)
{
BoundingBox bbox = utymap::utils::GeoUtils::quadKeyToBoundingBox(context_.quadKey);
Path tileRect;
tileRect.push_back(IntPoint(bbox.minPoint.longitude*Scale, bbox.minPoint.latitude *Scale));
tileRect.push_back(IntPoint(bbox.maxPoint.longitude *Scale, bbox.minPoint.latitude *Scale));
tileRect.push_back(IntPoint(bbox.maxPoint.longitude *Scale, bbox.maxPoint.latitude*Scale));
tileRect.push_back(IntPoint(bbox.minPoint.longitude*Scale, bbox.maxPoint.latitude*Scale));
clipper_.AddPath(tileRect, ptSubject, true);
clipper_.AddPaths(backgroundClipArea_, ptClip, true);
Paths background;
clipper_.Execute(ctDifference, background, pftPositive, pftPositive);
clipper_.Clear();
if (!background.empty())
populateMesh(createMeshOptions(style, ""), background);
}
Region createRegion(const Style& style, const std::vector<GeoCoordinate>& coordinates)
{
Region region;
Path path;
path.reserve(coordinates.size());
for (const GeoCoordinate& c : coordinates)
path.push_back(IntPoint(c.longitude * Scale, c.latitude * Scale));
region.points.push_back(path);
region.isLayer = style.has(context_.stringTable.getId(TerrainLayerKey));
if (!region.isLayer)
region.options = createMeshOptions(style, "");
return std::move(region);
}
std::shared_ptr<MeshBuilder::Options> createMeshOptions(const Style& style, const std::string& prefix)
{
std::string gradientKey = utymap::utils::getString(prefix + GradientKey, context_.stringTable, style);
return std::shared_ptr<MeshBuilder::Options>(new MeshBuilder::Options(
utymap::utils::getDouble(prefix + MaxAreaKey, context_.stringTable, style),
utymap::utils::getDouble(prefix + EleNoiseFreqKey, context_.stringTable, style),
utymap::utils::getDouble(prefix + ColorNoiseFreqKey, context_.stringTable, style),
utymap::utils::getDouble(prefix + HeightKey, context_.stringTable, style, 0),
context_.styleProvider.getGradient(gradientKey),
utymap::utils::getString(prefix + MeshNameKey, context_.stringTable, style, "")));
}
void buildFromRegions(const Regions& regions, const std::shared_ptr<MeshBuilder::Options>& options)
{
// merge all regions together
Clipper clipper;
for (const Region& region : regions)
clipper.AddPaths(region.points, ptSubject, true);
Paths result;
clipper.Execute(ctUnion, result, pftPositive, pftPositive);
buildFromPaths(result, options);
}
void buildFromPaths(Paths& paths, const std::shared_ptr<MeshBuilder::Options>& options, bool moveSubjectToClip = true)
{
clipper_.AddPaths(paths, ptSubject, true);
paths.clear();
clipper_.Execute(ctDifference, paths, pftPositive, pftPositive);
// NOTE: this is performance optimization: we cannot make all
// polygons to be clipping as it slows down clipper dramatically.
if (moveSubjectToClip) {
clipper_.moveSubjectToClip();
}
else {
backgroundClipArea_.insert(backgroundClipArea_.end(), paths.begin(), paths.end());
clipper_.removeSubject();
}
populateMesh(options, paths);
}
void populateMesh(const std::shared_ptr<MeshBuilder::Options>& options, Paths& paths)
{
ClipperLib::SimplifyPolygons(paths);
ClipperLib::CleanPolygons(paths);
bool hasHeightOffset = std::abs(options->heightOffset) > 1E-8;
// calculate approximate size of overall points
auto size = 0;
for (auto i = 0; i < paths.size(); ++i)
size += paths[i].size() * 1.5;
Polygon polygon(size);
for (const Path& path : paths) {
double area = ClipperLib::Area(path);
bool isHole = area < 0;
if (std::abs(area) < AreaTolerance)
continue;
Points points = restorePoints(path);
if (isHole)
polygon.addHole(points);
else
polygon.addContour(points);
if (hasHeightOffset)
processHeightOffset(options, points, isHole);
}
if (!polygon.points.empty())
fillMesh(options, polygon);
}
// restores mesh points from clipper points and injects new ones according to grid.
Points restorePoints(const Path& path)
{
int lastItemIndex = path.size() - 1;
Points points;
points.reserve(path.size());
for (int i = 0; i <= lastItemIndex; i++)
splitter_.split(path[i], path[i == lastItemIndex ? 0 : i + 1], points);
return std::move(points);
}
void fillMesh(const std::shared_ptr<MeshBuilder::Options>& options, Polygon& polygon)
{
if (options->meshName != "") {
Mesh polygonMesh(options->meshName);
context_.meshBuilder.addPolygon(polygonMesh, polygon, *options);
context_.meshCallback(polygonMesh);
}
else {
context_.meshBuilder.addPolygon(mesh_, polygon, *options);
}
}
void processHeightOffset(const std::shared_ptr<MeshBuilder::Options>& options, const Points& points, bool isHole)
{
auto index = mesh_.vertices.size() / 3;
for (auto i = 0; i < points.size(); ++i) {
Point p1 = points[i];
Point p2 = points[i == (points.size() - 1) ? 0 : i + 1];
// check whether two points are on cell rect
if (rect_.isOnBorder(p1) && rect_.isOnBorder(p2)) continue;
context_.meshBuilder.addPlane(mesh_, p1, p2, *options);
}
}
ClipperEx clipper_;
ClipperOffset offset_;
LineGridSplitter splitter_;
Rectangle rect_;
Layers layers_;
Paths backgroundClipArea_;
Mesh mesh_;
};
void TerraBuilder::visitNode(const utymap::entities::Node& node) { pimpl_->visitNode(node); }
void TerraBuilder::visitWay(const utymap::entities::Way& way) { pimpl_->visitWay(way); }
void TerraBuilder::visitArea(const utymap::entities::Area& area) { pimpl_->visitArea(area); }
void TerraBuilder::visitRelation(const utymap::entities::Relation& relation) { pimpl_->visitRelation(relation); }
void TerraBuilder::complete() { pimpl_->complete(); }
TerraBuilder::~TerraBuilder() { }
TerraBuilder::TerraBuilder(const BuilderContext& context) :
utymap::builders::ElementBuilder(context),
pimpl_(new TerraBuilder::TerraBuilderImpl(context))
{
}
<|endoftext|> |
<commit_before>/*
* Copyright 2007-2021 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "cgi/Address.hxx"
#include "AllocatorPtr.hxx"
#include "TestPool.hxx"
#include <gtest/gtest.h>
[[gnu::pure]]
static constexpr auto
MakeCgiAddress(const char *executable_path, const char *script_name,
const char *path_info) noexcept
{
CgiAddress address(executable_path);
address.script_name = script_name;
address.path_info = path_info;
return address;
}
TEST(CgiAddressTest, Uri)
{
TestPool pool;
AllocatorPtr alloc(pool);
CgiAddress a("/usr/bin/cgi");
ASSERT_FALSE(a.IsExpandable());
ASSERT_STREQ(a.GetURI(alloc), "/");
a.script_name = "/";
ASSERT_STREQ(a.GetURI(alloc), "/");
a.path_info = "foo";
ASSERT_STREQ(a.GetURI(alloc), "/foo");
a.query_string = "";
ASSERT_STREQ(a.GetURI(alloc), "/foo?");
a.query_string = "a=b";
ASSERT_STREQ(a.GetURI(alloc), "/foo?a=b");
a.path_info = "";
ASSERT_STREQ(a.GetURI(alloc), "/?a=b");
a.path_info = nullptr;
ASSERT_STREQ(a.GetURI(alloc), "/?a=b");
a.script_name = "/test.cgi";
a.path_info = nullptr;
a.query_string = nullptr;
ASSERT_STREQ(a.GetURI(alloc), "/test.cgi");
a.path_info = "/foo";
ASSERT_STREQ(a.GetURI(alloc), "/test.cgi/foo");
a.script_name = "/bar/";
ASSERT_STREQ(a.GetURI(alloc), "/bar/foo");
a.script_name = "/";
ASSERT_STREQ(a.GetURI(alloc), "/foo");
a.script_name = nullptr;
ASSERT_STREQ(a.GetURI(alloc), "/foo");
}
TEST(CgiAddressTest, Apply)
{
TestPool pool;
AllocatorPtr alloc(pool);
auto a = MakeCgiAddress("/usr/bin/cgi", "/test.pl", "/foo");
auto b = a.Apply(alloc, "");
ASSERT_EQ((const CgiAddress *)&a, b);
b = a.Apply(alloc, "bar");
ASSERT_NE(b, nullptr);
ASSERT_NE(b, &a);
ASSERT_FALSE(b->IsValidBase());
ASSERT_STREQ(b->path, a.path);
ASSERT_STREQ(b->script_name, a.script_name);
ASSERT_STREQ(b->path_info, "/bar");
a.path_info = "/foo/";
ASSERT_EQ(true, a.IsValidBase());
b = a.Apply(alloc, "bar");
ASSERT_NE(b, nullptr);
ASSERT_NE(b, &a);
ASSERT_FALSE(b->IsValidBase());
ASSERT_STREQ(b->path, a.path);
ASSERT_STREQ(b->script_name, a.script_name);
ASSERT_STREQ(b->path_info, "/foo/bar");
b = a.Apply(alloc, "/bar");
ASSERT_NE(b, nullptr);
ASSERT_NE(b, &a);
ASSERT_FALSE(b->IsValidBase());
ASSERT_STREQ(b->path, a.path);
ASSERT_STREQ(b->script_name, a.script_name);
ASSERT_STREQ(b->path_info, "/bar");
}
static bool
operator==(const StringView a, const StringView b) noexcept
{
if (a.IsNull() || b.IsNull())
return a.IsNull() && b.IsNull();
if (a.size != b.size)
return false;
return memcmp(a.data, b.data, a.size) == 0;
}
static bool
operator==(const StringView a, const char *b) noexcept
{
return a == StringView(b);
}
static bool
operator==(const StringView a, std::nullptr_t b) noexcept
{
return a == StringView(b);
}
TEST(CgiAddressTest, RelativeTo)
{
TestPool pool;
AllocatorPtr alloc(pool);
static constexpr auto base = MakeCgiAddress("/usr/bin/cgi", "/test.pl", "/foo/");
ASSERT_EQ(MakeCgiAddress("/usr/bin/other-cgi", "/test.pl", "/foo/").RelativeTo(base), nullptr);
ASSERT_EQ(MakeCgiAddress("/usr/bin/cgi", "/test.pl", nullptr).RelativeTo(base), nullptr);
ASSERT_EQ(MakeCgiAddress("/usr/bin/cgi", "/test.pl", "/").RelativeTo(base), nullptr);
ASSERT_EQ(MakeCgiAddress("/usr/bin/cgi", "/test.pl", "/foo").RelativeTo(base), nullptr);
ASSERT_EQ(MakeCgiAddress("/usr/bin/cgi", "/test.pl", "/foo/").RelativeTo(base), "");
ASSERT_EQ(MakeCgiAddress("/usr/bin/cgi", "/test.pl", "/foo/bar").RelativeTo(base), "bar");
}
<commit_msg>test/t_cgi_address: pass URI to MakeCgiAddress()<commit_after>/*
* Copyright 2007-2021 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "cgi/Address.hxx"
#include "AllocatorPtr.hxx"
#include "TestPool.hxx"
#include <gtest/gtest.h>
[[gnu::pure]]
static constexpr auto
MakeCgiAddress(const char *executable_path, const char *uri,
const char *script_name, const char *path_info) noexcept
{
CgiAddress address(executable_path);
address.uri = uri;
address.script_name = script_name;
address.path_info = path_info;
return address;
}
TEST(CgiAddressTest, Uri)
{
TestPool pool;
AllocatorPtr alloc(pool);
CgiAddress a("/usr/bin/cgi");
ASSERT_FALSE(a.IsExpandable());
ASSERT_STREQ(a.GetURI(alloc), "/");
a.script_name = "/";
ASSERT_STREQ(a.GetURI(alloc), "/");
a.path_info = "foo";
ASSERT_STREQ(a.GetURI(alloc), "/foo");
a.query_string = "";
ASSERT_STREQ(a.GetURI(alloc), "/foo?");
a.query_string = "a=b";
ASSERT_STREQ(a.GetURI(alloc), "/foo?a=b");
a.path_info = "";
ASSERT_STREQ(a.GetURI(alloc), "/?a=b");
a.path_info = nullptr;
ASSERT_STREQ(a.GetURI(alloc), "/?a=b");
a.script_name = "/test.cgi";
a.path_info = nullptr;
a.query_string = nullptr;
ASSERT_STREQ(a.GetURI(alloc), "/test.cgi");
a.path_info = "/foo";
ASSERT_STREQ(a.GetURI(alloc), "/test.cgi/foo");
a.script_name = "/bar/";
ASSERT_STREQ(a.GetURI(alloc), "/bar/foo");
a.script_name = "/";
ASSERT_STREQ(a.GetURI(alloc), "/foo");
a.script_name = nullptr;
ASSERT_STREQ(a.GetURI(alloc), "/foo");
}
TEST(CgiAddressTest, Apply)
{
TestPool pool;
AllocatorPtr alloc(pool);
auto a = MakeCgiAddress("/usr/bin/cgi", nullptr, "/test.pl", "/foo");
auto b = a.Apply(alloc, "");
ASSERT_EQ((const CgiAddress *)&a, b);
b = a.Apply(alloc, "bar");
ASSERT_NE(b, nullptr);
ASSERT_NE(b, &a);
ASSERT_FALSE(b->IsValidBase());
ASSERT_STREQ(b->path, a.path);
ASSERT_STREQ(b->script_name, a.script_name);
ASSERT_STREQ(b->path_info, "/bar");
a.path_info = "/foo/";
ASSERT_EQ(true, a.IsValidBase());
b = a.Apply(alloc, "bar");
ASSERT_NE(b, nullptr);
ASSERT_NE(b, &a);
ASSERT_FALSE(b->IsValidBase());
ASSERT_STREQ(b->path, a.path);
ASSERT_STREQ(b->script_name, a.script_name);
ASSERT_STREQ(b->path_info, "/foo/bar");
b = a.Apply(alloc, "/bar");
ASSERT_NE(b, nullptr);
ASSERT_NE(b, &a);
ASSERT_FALSE(b->IsValidBase());
ASSERT_STREQ(b->path, a.path);
ASSERT_STREQ(b->script_name, a.script_name);
ASSERT_STREQ(b->path_info, "/bar");
}
static bool
operator==(const StringView a, const StringView b) noexcept
{
if (a.IsNull() || b.IsNull())
return a.IsNull() && b.IsNull();
if (a.size != b.size)
return false;
return memcmp(a.data, b.data, a.size) == 0;
}
static bool
operator==(const StringView a, const char *b) noexcept
{
return a == StringView(b);
}
static bool
operator==(const StringView a, std::nullptr_t b) noexcept
{
return a == StringView(b);
}
TEST(CgiAddressTest, RelativeTo)
{
TestPool pool;
AllocatorPtr alloc(pool);
static constexpr auto base = MakeCgiAddress("/usr/bin/cgi", nullptr, "/test.pl", "/foo/");
ASSERT_EQ(MakeCgiAddress("/usr/bin/other-cgi", nullptr, "/test.pl", "/foo/").RelativeTo(base), nullptr);
ASSERT_EQ(MakeCgiAddress("/usr/bin/cgi", nullptr, "/test.pl", nullptr).RelativeTo(base), nullptr);
ASSERT_EQ(MakeCgiAddress("/usr/bin/cgi", nullptr, "/test.pl", "/").RelativeTo(base), nullptr);
ASSERT_EQ(MakeCgiAddress("/usr/bin/cgi", nullptr, "/test.pl", "/foo").RelativeTo(base), nullptr);
ASSERT_EQ(MakeCgiAddress("/usr/bin/cgi", nullptr, "/test.pl", "/foo/").RelativeTo(base), "");
ASSERT_EQ(MakeCgiAddress("/usr/bin/cgi", nullptr, "/test.pl", "/foo/bar").RelativeTo(base), "bar");
}
<|endoftext|> |
<commit_before>#include "catch.hpp"
#include <communique/Client.h>
#include <communique/Server.h>
#include <thread>
#include <iostream>
#include "testinputs.h"
SCENARIO( "Test that the Client and Server can interact properly", "[integration][local]" )
{
GIVEN( "A Client and server" )
{
communique::Server myServer;
myServer.setCertificateChainFile( testinputs::testFileDirectory+"old/server.pem" );
myServer.setPrivateKeyFile( testinputs::testFileDirectory+"old/server.pem" );
communique::Client myClient;
myClient.setVerifyFile( testinputs::testFileDirectory+"old/rootCA.pem" );
WHEN( "I start a server listening and try and connect a client to it" )
{
REQUIRE_NOTHROW( myServer.listen( ++testinputs::portNumber ) );
std::this_thread::sleep_for( testinputs::shortWait );
REQUIRE_NOTHROW( myClient.connect( "ws://localhost:"+std::to_string(testinputs::portNumber) ) );
std::this_thread::sleep_for( testinputs::shortWait );
REQUIRE( myClient.isConnected() );
REQUIRE( myServer.currentConnections().size()==1 );
REQUIRE_NOTHROW( myClient.disconnect() );
REQUIRE_NOTHROW( myServer.stop() );
}
WHEN( "I send info messages from a client to a server" )
{
std::string concatenatedInfoMessages; // Store all received info message in here
REQUIRE_NOTHROW( myServer.setDefaultInfoHandler( [&](const std::string& message){ concatenatedInfoMessages+=message; } ) );
std::string concatenatedRequestMessages; // Store all received info message in here
REQUIRE_NOTHROW( myServer.setDefaultRequestHandler( [&](const std::string& message){ concatenatedRequestMessages+=message; return "Answer is: "+message; } ) );
REQUIRE_NOTHROW( myServer.listen( ++testinputs::portNumber ) );
std::this_thread::sleep_for( testinputs::shortWait );
REQUIRE_NOTHROW( myClient.connect( "ws://localhost:"+std::to_string(testinputs::portNumber) ) );
std::this_thread::sleep_for( testinputs::shortWait );
myClient.sendInfo( "This is the first test" );
std::this_thread::sleep_for( testinputs::shortWait );
CHECK( concatenatedInfoMessages=="This is the first test" );
CHECK( concatenatedRequestMessages=="" );
concatenatedInfoMessages.clear();
REQUIRE_NOTHROW( myClient.disconnect() );
std::this_thread::sleep_for( std::chrono::seconds(2) );
REQUIRE_NOTHROW( myServer.stop() );
}
WHEN( "I send info messages from a server to a client" )
{
std::string concatenatedInfoMessages; // Store all received info message in here
REQUIRE_NOTHROW( myClient.setInfoHandler( [&](const std::string& message){ concatenatedInfoMessages+=message; } ) );
std::string concatenatedRequestMessages; // Store all received info message in here
REQUIRE_NOTHROW( myClient.setRequestHandler( [&](const std::string& message){ concatenatedRequestMessages+=message; return "Answer is: "+message; } ) );
REQUIRE_NOTHROW( myServer.listen( ++testinputs::portNumber ) );
std::this_thread::sleep_for( testinputs::shortWait );
REQUIRE_NOTHROW( myClient.connect( "ws://localhost:"+std::to_string(testinputs::portNumber) ) );
std::this_thread::sleep_for( testinputs::shortWait );
for( auto& pConnection : myServer.currentConnections() ) pConnection->sendInfo( "This is the first test" );
std::this_thread::sleep_for( testinputs::shortWait ); // Allow 1/2 a second for the message to arrive
CHECK( concatenatedInfoMessages=="This is the first test" );
for( auto& pConnection : myServer.currentConnections() ) pConnection->sendInfo( "This is the second test" );
std::this_thread::sleep_for( testinputs::shortWait ); // Allow 1/2 a second for the message to arrive
CHECK( concatenatedInfoMessages=="This is the first testThis is the second test" );
CHECK( concatenatedRequestMessages=="" );
concatenatedInfoMessages.clear();
// Always disconnect the client first, otherwise the port can get tied up.
REQUIRE_NOTHROW( myClient.disconnect() );
std::this_thread::sleep_for( std::chrono::seconds(2) );
REQUIRE_NOTHROW( myServer.stop() );
}
WHEN( "I send request messages from a client to a server" )
{
std::string concatenatedResponses; // Store all received info message in here
std::string concatenatedRequestMessages; // Store all received info message in here
REQUIRE_NOTHROW( myServer.setDefaultRequestHandler( [&](const std::string& message){ concatenatedRequestMessages+=message; return "Answer is: "+message; } ) );
REQUIRE_NOTHROW( myServer.listen( ++testinputs::portNumber ) );
std::this_thread::sleep_for( testinputs::shortWait );
REQUIRE_NOTHROW( myClient.connect( "ws://localhost:"+std::to_string(testinputs::portNumber) ) );
std::this_thread::sleep_for( testinputs::shortWait );
myClient.sendRequest( "This is the first test", [&](const std::string& message){concatenatedResponses+=message;} );
std::this_thread::sleep_for( testinputs::shortWait );
CHECK( concatenatedResponses=="Answer is: This is the first test" );
CHECK( concatenatedRequestMessages=="This is the first test" );
REQUIRE_NOTHROW( myClient.disconnect() );
std::this_thread::sleep_for( std::chrono::seconds(2) );
REQUIRE_NOTHROW( myServer.stop() );
}
WHEN( "I connect and disconnect several clients to a server" )
{
const size_t numberOfClients=5;
// Create several clients
std::vector<communique::Client> clients;
for( size_t index=0; index<numberOfClients; ++index ) clients.emplace_back();
REQUIRE_NOTHROW( myServer.listen( ++testinputs::portNumber ) );
std::this_thread::sleep_for( testinputs::shortWait );
// Connect all of the clients, and check that the server sees them
for( size_t index=0; index<clients.size(); ++index )
{
REQUIRE_NOTHROW( clients[index].connect( "ws://localhost:"+std::to_string(testinputs::portNumber) ) );
std::this_thread::sleep_for( testinputs::shortWait );
CHECK( myServer.currentConnections().size()==index+1 );
}
// disconnect all the clients, and check that the server realises they're disconnected
for( size_t index=0; index<clients.size(); ++index )
{
REQUIRE_NOTHROW( clients[index].disconnect() );
CHECK( myServer.currentConnections().size()==clients.size()-index-1 );
}
}
}
}
<commit_msg>Use isConnected() method to block during state transition and avoid race conditions in the test assertions<commit_after>#include "catch.hpp"
#include <communique/Client.h>
#include <communique/Server.h>
#include <thread>
#include <iostream>
#include "testinputs.h"
SCENARIO( "Test that the Client and Server can interact properly", "[integration][local]" )
{
GIVEN( "A Client and server" )
{
communique::Server myServer;
myServer.setCertificateChainFile( testinputs::testFileDirectory+"old/server.pem" );
myServer.setPrivateKeyFile( testinputs::testFileDirectory+"old/server.pem" );
communique::Client myClient;
myClient.setVerifyFile( testinputs::testFileDirectory+"old/rootCA.pem" );
WHEN( "I start a server listening and try and connect a client to it" )
{
REQUIRE_NOTHROW( myServer.listen( ++testinputs::portNumber ) );
std::this_thread::sleep_for( testinputs::shortWait );
REQUIRE_NOTHROW( myClient.connect( "ws://localhost:"+std::to_string(testinputs::portNumber) ) );
std::this_thread::sleep_for( testinputs::shortWait );
REQUIRE( myClient.isConnected() );
REQUIRE( myServer.currentConnections().size()==1 );
REQUIRE_NOTHROW( myClient.disconnect() );
REQUIRE_NOTHROW( myServer.stop() );
}
WHEN( "I send info messages from a client to a server" )
{
std::string concatenatedInfoMessages; // Store all received info message in here
REQUIRE_NOTHROW( myServer.setDefaultInfoHandler( [&](const std::string& message){ concatenatedInfoMessages+=message; } ) );
std::string concatenatedRequestMessages; // Store all received info message in here
REQUIRE_NOTHROW( myServer.setDefaultRequestHandler( [&](const std::string& message){ concatenatedRequestMessages+=message; return "Answer is: "+message; } ) );
REQUIRE_NOTHROW( myServer.listen( ++testinputs::portNumber ) );
std::this_thread::sleep_for( testinputs::shortWait );
REQUIRE_NOTHROW( myClient.connect( "ws://localhost:"+std::to_string(testinputs::portNumber) ) );
std::this_thread::sleep_for( testinputs::shortWait );
myClient.sendInfo( "This is the first test" );
std::this_thread::sleep_for( testinputs::shortWait );
CHECK( concatenatedInfoMessages=="This is the first test" );
CHECK( concatenatedRequestMessages=="" );
concatenatedInfoMessages.clear();
REQUIRE_NOTHROW( myClient.disconnect() );
std::this_thread::sleep_for( std::chrono::seconds(2) );
REQUIRE_NOTHROW( myServer.stop() );
}
WHEN( "I send info messages from a server to a client" )
{
std::string concatenatedInfoMessages; // Store all received info message in here
REQUIRE_NOTHROW( myClient.setInfoHandler( [&](const std::string& message){ concatenatedInfoMessages+=message; } ) );
std::string concatenatedRequestMessages; // Store all received info message in here
REQUIRE_NOTHROW( myClient.setRequestHandler( [&](const std::string& message){ concatenatedRequestMessages+=message; return "Answer is: "+message; } ) );
REQUIRE_NOTHROW( myServer.listen( ++testinputs::portNumber ) );
std::this_thread::sleep_for( testinputs::shortWait );
REQUIRE_NOTHROW( myClient.connect( "ws://localhost:"+std::to_string(testinputs::portNumber) ) );
std::this_thread::sleep_for( testinputs::shortWait );
for( auto& pConnection : myServer.currentConnections() ) pConnection->sendInfo( "This is the first test" );
std::this_thread::sleep_for( testinputs::shortWait ); // Allow 1/2 a second for the message to arrive
CHECK( concatenatedInfoMessages=="This is the first test" );
for( auto& pConnection : myServer.currentConnections() ) pConnection->sendInfo( "This is the second test" );
std::this_thread::sleep_for( testinputs::shortWait ); // Allow 1/2 a second for the message to arrive
CHECK( concatenatedInfoMessages=="This is the first testThis is the second test" );
CHECK( concatenatedRequestMessages=="" );
concatenatedInfoMessages.clear();
// Always disconnect the client first, otherwise the port can get tied up.
REQUIRE_NOTHROW( myClient.disconnect() );
std::this_thread::sleep_for( std::chrono::seconds(2) );
REQUIRE_NOTHROW( myServer.stop() );
}
WHEN( "I send request messages from a client to a server" )
{
std::string concatenatedResponses; // Store all received info message in here
std::string concatenatedRequestMessages; // Store all received info message in here
REQUIRE_NOTHROW( myServer.setDefaultRequestHandler( [&](const std::string& message){ concatenatedRequestMessages+=message; return "Answer is: "+message; } ) );
REQUIRE_NOTHROW( myServer.listen( ++testinputs::portNumber ) );
std::this_thread::sleep_for( testinputs::shortWait );
REQUIRE_NOTHROW( myClient.connect( "ws://localhost:"+std::to_string(testinputs::portNumber) ) );
std::this_thread::sleep_for( testinputs::shortWait );
myClient.sendRequest( "This is the first test", [&](const std::string& message){concatenatedResponses+=message;} );
std::this_thread::sleep_for( testinputs::shortWait );
CHECK( concatenatedResponses=="Answer is: This is the first test" );
CHECK( concatenatedRequestMessages=="This is the first test" );
REQUIRE_NOTHROW( myClient.disconnect() );
std::this_thread::sleep_for( std::chrono::seconds(2) );
REQUIRE_NOTHROW( myServer.stop() );
}
WHEN( "I connect and disconnect several clients to a server" )
{
const size_t numberOfClients=5;
// Create several clients
std::vector<communique::Client> clients;
for( size_t index=0; index<numberOfClients; ++index ) clients.emplace_back();
REQUIRE_NOTHROW( myServer.listen( ++testinputs::portNumber ) );
std::this_thread::sleep_for( testinputs::shortWait );
// Connect all of the clients, and check that the server sees them
for( size_t index=0; index<clients.size(); ++index )
{
REQUIRE_NOTHROW( clients[index].connect( "ws://localhost:"+std::to_string(testinputs::portNumber) ) );
CHECK( clients[index].isConnected() ); // This call blocks until handshake completes or fails
CHECK( myServer.currentConnections().size()==index+1 );
}
// disconnect all the clients, and check that the server realises they're disconnected
for( size_t index=0; index<clients.size(); ++index )
{
REQUIRE_NOTHROW( clients[index].disconnect() );
CHECK( !clients[index].isConnected() ); // This call blocks until connections transitions
CHECK( myServer.currentConnections().size()==clients.size()-index-1 );
}
}
}
}
<|endoftext|> |
<commit_before>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <chartsql/expressions/aggregate.h>
#include <chartsql/svalue.h>
namespace csql {
namespace expressions {
/**
* COUNT() expression
*/
void countExprAcc(void* scratchpad, int argc, SValue* argv) {
switch(argv->getType()) {
case SValue::T_NULL:
return;
default:
++(*(uint64_t*) scratchpad);
return;
}
}
void countExprGet(void* scratchpad, SValue* out) {
*out = SValue(SValue::IntegerType(*((uint64_t*) scratchpad)));
}
void countExprReset(void* scratchpad) {
memset(scratchpad, 0, sizeof(uint64_t));
}
void countExprMerge(void* scratchpad, const void* other) {
*(uint64_t*) scratchpad += *(uint64_t*) other;
}
void countExprSave(void* scratchpad, OutputStream* os) {
os->appendVarUInt(*(uint64_t*) scratchpad);
}
void countExprLoad(void* scratchpad, InputStream* is) {
*(uint64_t*) scratchpad = is->readVarUInt();
}
const AggregateFunction kCountExpr {
.scratch_size = sizeof(uint64_t),
.accumulate = &countExprAcc,
.get = &countExprGet,
.reset = &countExprReset,
.init = &countExprReset,
.free = nullptr,
.merge = &countExprMerge,
.savestate = &countExprSave,
.loadstate = &countExprLoad
};
/**
* SUM() expression
*/
struct sum_expr_scratchpad {
SValue::kSValueType type;
double val;
};
void sumExprAcc(void* scratchpad, int argc, SValue* argv) {
SValue* val = argv;
auto data = (sum_expr_scratchpad*) scratchpad;
if (argc != 1) {
RAISE(
kRuntimeError,
"wrong number of arguments for sum(). expected: 1, got: %i\n",
argc);
}
switch(val->getType()) {
case SValue::T_NULL:
return;
case SValue::T_INTEGER:
data->type = SValue::T_INTEGER;
data->val += val->getInteger();
return;
case SValue::T_FLOAT:
default:
data->type = SValue::T_FLOAT;
data->val += val->getFloat();
return;
}
}
void sumExprGet(void* scratchpad, SValue* out) {
auto data = (sum_expr_scratchpad*) scratchpad;
switch(data->type) {
case SValue::T_INTEGER:
*out = SValue(SValue::IntegerType(data->val));
return;
case SValue::T_FLOAT:
*out = SValue(SValue::FloatType(data->val));
return;
default:
*out = SValue();
return;
}
}
void sumExprReset(void* scratchpad) {
memset(scratchpad, 0, sizeof(sum_expr_scratchpad));
}
void sumExprMerge(void* scratchpad, const void* other) {
auto this_data = (sum_expr_scratchpad*) scratchpad;
auto other_data = (const sum_expr_scratchpad*) other;
if (this_data->type == SValue::T_INTEGER &&
other_data->type == SValue::T_INTEGER) {
this_data->type = SValue::T_INTEGER;
} else {
this_data->type = SValue::T_FLOAT;
}
this_data->val += other_data->val;
}
void sumExprSave(void* scratchpad, OutputStream* os) {
auto data = (sum_expr_scratchpad*) scratchpad;
os->appendVarUInt(data->type);
os->appendDouble(data->val);
}
void sumExprLoad(void* scratchpad, InputStream* is) {
auto data = (sum_expr_scratchpad*) scratchpad;
data->type = (SValue::kSValueType) is->readVarUInt();
data->val = is->readDouble();
}
const AggregateFunction kSumExpr {
.scratch_size = sizeof(sum_expr_scratchpad),
.accumulate = &sumExprAcc,
.get = &sumExprGet,
.reset = &sumExprReset,
.init = &sumExprReset,
.free = nullptr,
.merge = &sumExprMerge,
.savestate = &sumExprSave,
.loadstate = &sumExprLoad
};
/**
* MEAN() expression
*/
union mean_expr_scratchpad {
double sum;
int count;
};
void meanExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
SValue* val = argv;
union mean_expr_scratchpad* data = (union mean_expr_scratchpad*) scratchpad;
if (argc != 1) {
RAISE(
kRuntimeError,
"wrong number of arguments for mean(). expected: 1, got: %i\n",
argc);
}
switch(val->getType()) {
case SValue::T_NULL:
return;
default:
data->sum += val->getFloat();
data->count += 1;
*out = SValue(data->sum / data->count);
return;
}
}
void meanExprFree(void* scratchpad) {
/* noop */
}
size_t meanExprScratchpadSize() {
return sizeof(union mean_expr_scratchpad);
}
/**
* MAX() expression
*/
union max_expr_scratchpad {
double max;
int count;
};
void maxExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
SValue* val = argv;
union max_expr_scratchpad* data = (union max_expr_scratchpad*) scratchpad;
if (argc != 1) {
RAISE(
kRuntimeError,
"wrong number of arguments for max(). expected: 1, got: %i\n",
argc);
}
switch(val->getType()) {
case SValue::T_NULL:
return;
default: {
auto fval = val->getFloat();
if (data->count == 0 || fval > data->max) {
data->max = fval;
}
data->count = 1;
*out = SValue(data->max);
return;
}
}
}
void maxExprFree(void* scratchpad) {
/* noop */
}
size_t maxExprScratchpadSize() {
return sizeof(union max_expr_scratchpad);
}
/**
* MIN() expression
*/
union min_expr_scratchpad {
double min;
int count;
};
void minExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
SValue* val = argv;
union min_expr_scratchpad* data = (union min_expr_scratchpad*) scratchpad;
if (argc != 1) {
RAISE(
kRuntimeError,
"wrong number of arguments for min(). expected: 1, got: %i\n",
argc);
}
switch(val->getType()) {
case SValue::T_NULL:
return;
default: {
auto fval = val->getFloat();
if (data->count == 0 || fval < data->min) {
data->min = fval;
}
data->count = 1;
*out = SValue(data->min);
return;
}
}
}
void minExprFree(void* scratchpad) {
/* noop */
}
size_t minExprScratchpadSize() {
return sizeof(union min_expr_scratchpad);
}
}
}
<commit_msg>bring back mean() expr<commit_after>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <chartsql/expressions/aggregate.h>
#include <chartsql/svalue.h>
namespace csql {
namespace expressions {
/**
* COUNT() expression
*/
void countExprAcc(void* scratchpad, int argc, SValue* argv) {
switch(argv->getType()) {
case SValue::T_NULL:
return;
default:
++(*(uint64_t*) scratchpad);
return;
}
}
void countExprGet(void* scratchpad, SValue* out) {
*out = SValue(SValue::IntegerType(*((uint64_t*) scratchpad)));
}
void countExprReset(void* scratchpad) {
memset(scratchpad, 0, sizeof(uint64_t));
}
void countExprMerge(void* scratchpad, const void* other) {
*(uint64_t*) scratchpad += *(uint64_t*) other;
}
void countExprSave(void* scratchpad, OutputStream* os) {
os->appendVarUInt(*(uint64_t*) scratchpad);
}
void countExprLoad(void* scratchpad, InputStream* is) {
*(uint64_t*) scratchpad = is->readVarUInt();
}
const AggregateFunction kCountExpr {
.scratch_size = sizeof(uint64_t),
.accumulate = &countExprAcc,
.get = &countExprGet,
.reset = &countExprReset,
.init = &countExprReset,
.free = nullptr,
.merge = &countExprMerge,
.savestate = &countExprSave,
.loadstate = &countExprLoad
};
/**
* SUM() expression
*/
struct sum_expr_scratchpad {
SValue::kSValueType type;
double val;
};
void sumExprAcc(void* scratchpad, int argc, SValue* argv) {
SValue* val = argv;
auto data = (sum_expr_scratchpad*) scratchpad;
if (argc != 1) {
RAISE(
kRuntimeError,
"wrong number of arguments for sum(). expected: 1, got: %i\n",
argc);
}
switch(val->getType()) {
case SValue::T_NULL:
return;
case SValue::T_INTEGER:
data->type = SValue::T_INTEGER;
data->val += val->getInteger();
return;
case SValue::T_FLOAT:
default:
data->type = SValue::T_FLOAT;
data->val += val->getFloat();
return;
}
}
void sumExprGet(void* scratchpad, SValue* out) {
auto data = (sum_expr_scratchpad*) scratchpad;
switch(data->type) {
case SValue::T_INTEGER:
*out = SValue(SValue::IntegerType(data->val));
return;
case SValue::T_FLOAT:
*out = SValue(SValue::FloatType(data->val));
return;
default:
*out = SValue();
return;
}
}
void sumExprReset(void* scratchpad) {
memset(scratchpad, 0, sizeof(sum_expr_scratchpad));
}
void sumExprMerge(void* scratchpad, const void* other) {
auto this_data = (sum_expr_scratchpad*) scratchpad;
auto other_data = (const sum_expr_scratchpad*) other;
if (this_data->type == SValue::T_INTEGER &&
other_data->type == SValue::T_INTEGER) {
this_data->type = SValue::T_INTEGER;
} else {
this_data->type = SValue::T_FLOAT;
}
this_data->val += other_data->val;
}
void sumExprSave(void* scratchpad, OutputStream* os) {
auto data = (sum_expr_scratchpad*) scratchpad;
os->appendVarUInt(data->type);
os->appendDouble(data->val);
}
void sumExprLoad(void* scratchpad, InputStream* is) {
auto data = (sum_expr_scratchpad*) scratchpad;
data->type = (SValue::kSValueType) is->readVarUInt();
data->val = is->readDouble();
}
const AggregateFunction kSumExpr {
.scratch_size = sizeof(sum_expr_scratchpad),
.accumulate = &sumExprAcc,
.get = &sumExprGet,
.reset = &sumExprReset,
.init = &sumExprReset,
.free = nullptr,
.merge = &sumExprMerge,
.savestate = &sumExprSave,
.loadstate = &sumExprLoad
};
/**
* MEAN() expression
*/
struct mean_expr_scratchpad {
double sum;
int count;
};
void meanExprAcc(void* scratchpad, int argc, SValue* argv) {
SValue* val = argv;
auto data = (mean_expr_scratchpad*) scratchpad;
if (argc != 1) {
RAISE(
kRuntimeError,
"wrong number of arguments for mean(). expected: 1, got: %i\n",
argc);
}
switch(val->getType()) {
case SValue::T_NULL:
return;
default:
data->sum += val->getFloat();
data->count += 1;
return;
}
}
void meanExprGet(void* scratchpad, SValue* out) {
auto data = (mean_expr_scratchpad*) scratchpad;
*out = SValue(data->sum / data->count);
}
void meanExprReset(void* scratchpad) {
memset(scratchpad, 0, sizeof(mean_expr_scratchpad));
}
void meanExprFree(void* scratchpad) {
/* noop */
}
size_t meanExprScratchpadSize() {
return sizeof(mean_expr_scratchpad);
}
void meanExprMerge(void* scratchpad, const void* other) {
auto this_data = (mean_expr_scratchpad*) scratchpad;
auto other_data = (const mean_expr_scratchpad*) other;
this_data->sum += other_data->sum;
this_data->count += other_data->count;
}
void meanExprSave(void* scratchpad, OutputStream* os) {
auto data = (mean_expr_scratchpad*) scratchpad;
os->appendVarUInt(data->count);
os->appendDouble(data->sum);
}
void meanExprLoad(void* scratchpad, InputStream* is) {
auto data = (mean_expr_scratchpad*) scratchpad;
data->count = is->readVarUInt();
data->sum = is->readDouble();
}
const AggregateFunction kMeanExpr {
.scratch_size = sizeof(mean_expr_scratchpad),
.accumulate = &meanExprAcc,
.get = &meanExprGet,
.reset = &meanExprReset,
.init = &meanExprReset,
.free = nullptr,
.merge = &meanExprMerge,
.savestate = &meanExprSave,
.loadstate = &meanExprLoad
};
/**
* MAX() expression
*/
union max_expr_scratchpad {
double max;
int count;
};
void maxExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
SValue* val = argv;
union max_expr_scratchpad* data = (union max_expr_scratchpad*) scratchpad;
if (argc != 1) {
RAISE(
kRuntimeError,
"wrong number of arguments for max(). expected: 1, got: %i\n",
argc);
}
switch(val->getType()) {
case SValue::T_NULL:
return;
default: {
auto fval = val->getFloat();
if (data->count == 0 || fval > data->max) {
data->max = fval;
}
data->count = 1;
*out = SValue(data->max);
return;
}
}
}
void maxExprFree(void* scratchpad) {
/* noop */
}
size_t maxExprScratchpadSize() {
return sizeof(union max_expr_scratchpad);
}
/**
* MIN() expression
*/
union min_expr_scratchpad {
double min;
int count;
};
void minExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {
SValue* val = argv;
union min_expr_scratchpad* data = (union min_expr_scratchpad*) scratchpad;
if (argc != 1) {
RAISE(
kRuntimeError,
"wrong number of arguments for min(). expected: 1, got: %i\n",
argc);
}
switch(val->getType()) {
case SValue::T_NULL:
return;
default: {
auto fval = val->getFloat();
if (data->count == 0 || fval < data->min) {
data->min = fval;
}
data->count = 1;
*out = SValue(data->min);
return;
}
}
}
void minExprFree(void* scratchpad) {
/* noop */
}
size_t minExprScratchpadSize() {
return sizeof(union min_expr_scratchpad);
}
}
}
<|endoftext|> |
<commit_before>//===-- sdbcoreC.cpp ----------------------------------------------------------------*- C++ -*-===//
//
// S E R I A L B O X
//
// This file is distributed under terms of BSD license.
// See LICENSE.txt for more information
//
//===------------------------------------------------------------------------------------------===//
//
/// \file
/// This file contains utility functions for the sdb core library
///
//===------------------------------------------------------------------------------------------===//
#include <Python.h>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/ndarrayobject.h>
#include <cmath>
#include <iostream>
#include <vector>
namespace {
template <class T>
class NumpyArray {
public:
NumpyArray(PyArrayObject* array)
: data_((T*)PyArray_DATA(array)), size_(PyArray_SIZE(array)),
shape_(PyArray_DIMS(array), PyArray_DIMS(array) + PyArray_NDIM(array)) {}
/// \brief Access data pointer
const T* data() const noexcept { return data_; }
T* data() noexcept { return data_; }
/// \brief Shape of the numpy array
const std::vector<npy_intp>& shape() const noexcept { return shape_; }
/// \brief Size of the array
npy_intp size() const noexcept { return size_; }
/// \brief Convert to string
friend std::ostream& operator<<(std::ostream& stream, const NumpyArray& array) {
stream << "shape = [ ";
for(const auto& s : array.shape())
stream << s << " ";
stream << "], size = " << array.size() << ", data = " << array.data();
return stream;
}
private:
T* data_;
npy_intp size_;
std::vector<npy_intp> shape_;
};
template <class T>
struct ErrorList {
std::vector<int> index;
T input_value;
T reference_value;
};
/// \brief Compute positions of errors of input and reference fields
///
/// The error_position field is set to True if
///
/// absolute(input - reference) <= (atol + rtol * absolute(reference))
///
/// evaluates to False.
template <class T>
inline int compute_error_positions(const NumpyArray<T>& input, const NumpyArray<T>& reference,
NumpyArray<bool>& error_positions, const double& atol,
const double& rtol) noexcept {
const int size = input.size();
const T* input_ptr = input.data();
const T* reference_ptr = reference.data();
bool* error_positions_ptr = error_positions.data();
int num_errors = 0;
for(int i = 0; i < size; ++i) {
const T a = input_ptr[i];
const T b = reference_ptr[i];
const bool res = !(std::abs(a - b) <= (atol + rtol * std::abs(b)));
num_errors += res;
error_positions_ptr[i] = res;
}
return num_errors;
}
inline void increment_index(std::vector<int>& index, const std::vector<npy_intp>& shape) noexcept {
const int size = index.size();
for(int i = 0; i < size; ++i)
if(++index[i] < shape[i])
break;
else
index[i] = 0;
}
/// \brief Compute list of errors with elements (index, input_value, reference_value)
template <class T>
inline void compute_error_list(const NumpyArray<T>& input, const NumpyArray<T>& reference,
const NumpyArray<bool>& error_positions,
std::vector<ErrorList<T>>& error_list) noexcept {
const int size = input.size();
const T* input_ptr = input.data();
const T* reference_ptr = reference.data();
const bool* error_positions_ptr = error_positions.data();
const std::vector<npy_intp>& shape = input.shape();
std::vector<int> index(input.shape().size(), 0);
int error_list_idx = 0;
for(int i = 0; i < size; ++i, increment_index(index, shape)) {
if(error_positions_ptr[i]) {
error_list[error_list_idx].index = index;
error_list[error_list_idx].input_value = input_ptr[i];
error_list[error_list_idx].reference_value = reference_ptr[i];
error_list_idx++;
}
}
}
} // anonymous namespace
/// \brief Compute the list of errors and positions
static PyObject* sdbcoreC_make_error_list_c(PyObject* self, PyObject* args) {
PyObject* input_field;
PyArrayObject* input_array;
PyObject* reference_field;
PyArrayObject* reference_array;
PyArrayObject* error_positions_array = NULL;
PyObject* error_list_object = NULL;
double atol;
double rtol;
//
// Parse arguments
//
if(!PyArg_ParseTuple(args, "OOdd", &input_field, &reference_field, &atol, &rtol))
return NULL;
try {
//
// Extract numpy arrays
//
if(!(input_array =
(PyArrayObject*)PyArray_FROM_OTF(input_field, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY)))
throw std::runtime_error("internal error: failed to extract input array");
if(!(reference_array =
(PyArrayObject*)PyArray_FROM_OTF(reference_field, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY)))
throw std::runtime_error("internal error: failed to extract reference array");
NumpyArray<double> input(input_array);
NumpyArray<double> reference(reference_array);
if(input.shape() != reference.shape())
throw std::runtime_error("internal error: dimension mismatch");
//
// Allocate error positions array (boolean array)
//
error_positions_array = (PyArrayObject*)PyArray_SimpleNew(PyArray_NDIM(input_array),
PyArray_DIMS(input_array), NPY_BOOL);
NumpyArray<bool> error_positions(error_positions_array);
//
// Compute error positions
//
int num_errors = compute_error_positions(input, reference, error_positions, atol, rtol);
//
// Allocate list of errors
//
std::vector<ErrorList<double>> error_list(num_errors);
error_list_object = PyList_New(error_list.size());
//
// Compute list of errors
//
compute_error_list(input, reference, error_positions, error_list);
//
// Prepare return
//
for(int i = 0; i < error_list.size(); ++i) {
PyObject* list_element = PyList_New(3);
PyObject* index_list = PyList_New(error_list[i].index.size());
const int index_size = error_list[i].index.size();
for(int ii = 0; ii < error_list[i].index.size(); ++ii)
PyList_SetItem(index_list, ii, PyLong_FromLong(error_list[i].index[index_size - 1 - ii]));
PyList_SetItem(list_element, 0, index_list);
PyList_SetItem(list_element, 1, PyFloat_FromDouble(error_list[i].input_value));
PyList_SetItem(list_element, 2, PyFloat_FromDouble(error_list[i].reference_value));
PyList_SetItem(error_list_object, i, list_element);
}
} catch(std::runtime_error& e) {
PyErr_SetString(PyExc_RuntimeError, e.what());
Py_XDECREF(input_array);
Py_XDECREF(reference_array);
if(error_list_object)
Py_XDECREF(error_list_object);
if(error_positions_array)
Py_XDECREF(error_positions_array);
return NULL;
}
return Py_BuildValue("OO", error_list_object, error_positions_array);
}
//===------------------------------------------------------------------------------------------===//
// Module definitions
//===------------------------------------------------------------------------------------------===//
// Method specification
static PyMethodDef module_methods[] = {
{"make_error_list_c", sdbcoreC_make_error_list_c, METH_VARARGS, ""}, {NULL, NULL, 0, NULL}};
// Module specification
static struct PyModuleDef sdbcoreC_module_definition = {
PyModuleDef_HEAD_INIT, "sdbcoreC", "This module provides C extensions to the sdbcore module.",
-1, module_methods};
// Initialize the sdbcoreC module
PyMODINIT_FUNC PyInit_sdbcoreC(void) {
Py_Initialize();
import_array();
return PyModule_Create(&sdbcoreC_module_definition);
}
<commit_msg>Add missing stdexcept include<commit_after>//===-- sdbcoreC.cpp ----------------------------------------------------------------*- C++ -*-===//
//
// S E R I A L B O X
//
// This file is distributed under terms of BSD license.
// See LICENSE.txt for more information
//
//===------------------------------------------------------------------------------------------===//
//
/// \file
/// This file contains utility functions for the sdb core library
///
//===------------------------------------------------------------------------------------------===//
#include <Python.h>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/ndarrayobject.h>
#include <cmath>
#include <vector>
#include <stdexcept>
namespace {
template <class T>
class NumpyArray {
public:
NumpyArray(PyArrayObject* array)
: data_((T*)PyArray_DATA(array)), size_(PyArray_SIZE(array)),
shape_(PyArray_DIMS(array), PyArray_DIMS(array) + PyArray_NDIM(array)) {}
/// \brief Access data pointer
const T* data() const noexcept { return data_; }
T* data() noexcept { return data_; }
/// \brief Shape of the numpy array
const std::vector<npy_intp>& shape() const noexcept { return shape_; }
/// \brief Size of the array
npy_intp size() const noexcept { return size_; }
/// \brief Convert to string
friend std::ostream& operator<<(std::ostream& stream, const NumpyArray& array) {
stream << "shape = [ ";
for(const auto& s : array.shape())
stream << s << " ";
stream << "], size = " << array.size() << ", data = " << array.data();
return stream;
}
private:
T* data_;
npy_intp size_;
std::vector<npy_intp> shape_;
};
template <class T>
struct ErrorList {
std::vector<int> index;
T input_value;
T reference_value;
};
/// \brief Compute positions of errors of input and reference fields
///
/// The error_position field is set to True if
///
/// absolute(input - reference) <= (atol + rtol * absolute(reference))
///
/// evaluates to False.
template <class T>
inline int compute_error_positions(const NumpyArray<T>& input, const NumpyArray<T>& reference,
NumpyArray<bool>& error_positions, const double& atol,
const double& rtol) noexcept {
const int size = input.size();
const T* input_ptr = input.data();
const T* reference_ptr = reference.data();
bool* error_positions_ptr = error_positions.data();
int num_errors = 0;
for(int i = 0; i < size; ++i) {
const T a = input_ptr[i];
const T b = reference_ptr[i];
const bool res = !(std::abs(a - b) <= (atol + rtol * std::abs(b)));
num_errors += res;
error_positions_ptr[i] = res;
}
return num_errors;
}
inline void increment_index(std::vector<int>& index, const std::vector<npy_intp>& shape) noexcept {
const int size = index.size();
for(int i = 0; i < size; ++i)
if(++index[i] < shape[i])
break;
else
index[i] = 0;
}
/// \brief Compute list of errors with elements (index, input_value, reference_value)
template <class T>
inline void compute_error_list(const NumpyArray<T>& input, const NumpyArray<T>& reference,
const NumpyArray<bool>& error_positions,
std::vector<ErrorList<T>>& error_list) noexcept {
const int size = input.size();
const T* input_ptr = input.data();
const T* reference_ptr = reference.data();
const bool* error_positions_ptr = error_positions.data();
const std::vector<npy_intp>& shape = input.shape();
std::vector<int> index(input.shape().size(), 0);
int error_list_idx = 0;
for(int i = 0; i < size; ++i, increment_index(index, shape)) {
if(error_positions_ptr[i]) {
error_list[error_list_idx].index = index;
error_list[error_list_idx].input_value = input_ptr[i];
error_list[error_list_idx].reference_value = reference_ptr[i];
error_list_idx++;
}
}
}
} // anonymous namespace
/// \brief Compute the list of errors and positions
static PyObject* sdbcoreC_make_error_list_c(PyObject* self, PyObject* args) {
PyObject* input_field;
PyArrayObject* input_array;
PyObject* reference_field;
PyArrayObject* reference_array;
PyArrayObject* error_positions_array = NULL;
PyObject* error_list_object = NULL;
double atol;
double rtol;
//
// Parse arguments
//
if(!PyArg_ParseTuple(args, "OOdd", &input_field, &reference_field, &atol, &rtol))
return NULL;
try {
//
// Extract numpy arrays
//
if(!(input_array =
(PyArrayObject*)PyArray_FROM_OTF(input_field, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY)))
throw std::runtime_error("internal error: failed to extract input array");
if(!(reference_array =
(PyArrayObject*)PyArray_FROM_OTF(reference_field, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY)))
throw std::runtime_error("internal error: failed to extract reference array");
NumpyArray<double> input(input_array);
NumpyArray<double> reference(reference_array);
if(input.shape() != reference.shape())
throw std::runtime_error("internal error: dimension mismatch");
//
// Allocate error positions array (boolean array)
//
error_positions_array = (PyArrayObject*)PyArray_SimpleNew(PyArray_NDIM(input_array),
PyArray_DIMS(input_array), NPY_BOOL);
NumpyArray<bool> error_positions(error_positions_array);
//
// Compute error positions
//
int num_errors = compute_error_positions(input, reference, error_positions, atol, rtol);
//
// Allocate list of errors
//
std::vector<ErrorList<double>> error_list(num_errors);
error_list_object = PyList_New(error_list.size());
//
// Compute list of errors
//
compute_error_list(input, reference, error_positions, error_list);
//
// Prepare return
//
for(int i = 0; i < error_list.size(); ++i) {
PyObject* list_element = PyList_New(3);
PyObject* index_list = PyList_New(error_list[i].index.size());
const int index_size = error_list[i].index.size();
for(int ii = 0; ii < error_list[i].index.size(); ++ii)
PyList_SetItem(index_list, ii, PyLong_FromLong(error_list[i].index[index_size - 1 - ii]));
PyList_SetItem(list_element, 0, index_list);
PyList_SetItem(list_element, 1, PyFloat_FromDouble(error_list[i].input_value));
PyList_SetItem(list_element, 2, PyFloat_FromDouble(error_list[i].reference_value));
PyList_SetItem(error_list_object, i, list_element);
}
} catch(std::runtime_error& e) {
PyErr_SetString(PyExc_RuntimeError, e.what());
Py_XDECREF(input_array);
Py_XDECREF(reference_array);
if(error_list_object)
Py_XDECREF(error_list_object);
if(error_positions_array)
Py_XDECREF(error_positions_array);
return NULL;
}
return Py_BuildValue("OO", error_list_object, error_positions_array);
}
//===------------------------------------------------------------------------------------------===//
// Module definitions
//===------------------------------------------------------------------------------------------===//
// Method specification
static PyMethodDef module_methods[] = {
{"make_error_list_c", sdbcoreC_make_error_list_c, METH_VARARGS, ""}, {NULL, NULL, 0, NULL}};
// Module specification
static struct PyModuleDef sdbcoreC_module_definition = {
PyModuleDef_HEAD_INIT, "sdbcoreC", "This module provides C extensions to the sdbcore module.",
-1, module_methods};
// Initialize the sdbcoreC module
PyMODINIT_FUNC PyInit_sdbcoreC(void) {
Py_Initialize();
import_array();
return PyModule_Create(&sdbcoreC_module_definition);
}
<|endoftext|> |
<commit_before>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2012 Sergey Lisitsyn
* Copyright (C) 2012 Sergey Lisitsyn
*/
#include <shogun/lib/config.h>
#ifdef HAVE_LAPACK
#include <shogun/multiclass/MulticlassLibLinear.h>
#include <shogun/classifier/svm/SVM_linear.h>
#include <shogun/mathematics/Math.h>
#include <shogun/lib/v_array.h>
using namespace shogun;
CMulticlassLibLinear::CMulticlassLibLinear() :
CLinearMulticlassMachine()
{
init_defaults();
}
CMulticlassLibLinear::CMulticlassLibLinear(float64_t C, CDotFeatures* features, CLabels* labs) :
CLinearMulticlassMachine(ONE_VS_REST_STRATEGY,features,NULL,labs)
{
init_defaults();
set_C(C);
}
void CMulticlassLibLinear::init_defaults()
{
set_C(1.0);
set_epsilon(1e-2);
set_max_iter(10000);
set_use_bias(false);
set_save_train_state(false);
m_train_state = NULL;
}
void CMulticlassLibLinear::register_parameters()
{
m_parameters->add(&m_C, "m_C", "regularization constant");
m_parameters->add(&m_epsilon, "m_epsilon", "tolerance epsilon");
m_parameters->add(&m_max_iter, "m_max_iter", "max number of iterations");
m_parameters->add(&m_use_bias, "m_use_bias", "indicates whether bias should be used");
m_parameters->add(&m_save_train_state, "m_save_train_state", "indicates whether bias should be used");
}
CMulticlassLibLinear::~CMulticlassLibLinear()
{
reset_train_state();
}
SGVector<int32_t> CMulticlassLibLinear::get_support_vectors() const
{
if (!m_train_state)
SG_ERROR("Please enable save_train_state option and train machine.\n");
int32_t num_vectors = m_features->get_num_vectors();
int32_t num_classes = m_labels->get_num_classes();
v_array<int32_t> nz_idxs;
nz_idxs.reserve(num_vectors);
for (int32_t i=0; i<num_vectors; i++)
{
for (int32_t y=0; y<num_classes; y++)
{
if (CMath::abs(m_train_state->alpha[i*num_classes+y])>1e-6)
{
nz_idxs.push(i);
break;
}
}
}
int32_t num_nz = nz_idxs.index();
nz_idxs.reserve(num_nz);
return SGVector<int32_t>(nz_idxs.begin,num_nz);
}
bool CMulticlassLibLinear::train_machine(CFeatures* data)
{
if (data)
set_features((CDotFeatures*)data);
int32_t num_vectors = m_features->get_num_vectors();
int32_t num_classes = m_labels->get_num_classes();
int32_t bias_n = m_use_bias ? 1 : 0;
problem mc_problem;
mc_problem.l = num_vectors;
mc_problem.n = m_features->get_dim_feature_space() + bias_n;
mc_problem.y = SG_MALLOC(int32_t, mc_problem.l);
for (int32_t i=0; i<num_vectors; i++)
mc_problem.y[i] = m_labels->get_int_label(i);
mc_problem.x = m_features;
mc_problem.use_bias = m_use_bias;
if (!m_train_state)
m_train_state = new mcsvm_state();
float64_t* C = SG_MALLOC(float64_t, num_vectors);
for (int32_t i=0; i<num_vectors; i++)
C[i] = m_C;
Solver_MCSVM_CS solver(&mc_problem,num_classes,C,m_epsilon,
m_max_iter,m_max_train_time,m_train_state);
solver.solve();
clear_machines();
m_machines = SGVector<CMachine*>(num_classes);
for (int32_t i=0; i<num_classes; i++)
{
CLinearMachine* machine = new CLinearMachine();
float64_t* cw = SG_MALLOC(float64_t, mc_problem.n);
for (int32_t j=0; j<mc_problem.n-bias_n; j++)
cw[j] = m_train_state->w[j*num_classes+i];
machine->set_w(SGVector<float64_t>(cw,mc_problem.n-bias_n));
if (m_use_bias)
machine->set_bias(m_train_state->w[(mc_problem.n-bias_n)*num_classes+i]);
m_machines[i] = machine;
}
if (!m_save_train_state)
reset_train_state();
SG_FREE(C);
SG_FREE(mc_problem.y);
return true;
}
#endif /* HAVE_LAPACK */
<commit_msg>SG_ADD for MC liblinear<commit_after>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2012 Sergey Lisitsyn
* Copyright (C) 2012 Sergey Lisitsyn
*/
#include <shogun/lib/config.h>
#ifdef HAVE_LAPACK
#include <shogun/multiclass/MulticlassLibLinear.h>
#include <shogun/classifier/svm/SVM_linear.h>
#include <shogun/mathematics/Math.h>
#include <shogun/lib/v_array.h>
using namespace shogun;
CMulticlassLibLinear::CMulticlassLibLinear() :
CLinearMulticlassMachine()
{
init_defaults();
}
CMulticlassLibLinear::CMulticlassLibLinear(float64_t C, CDotFeatures* features, CLabels* labs) :
CLinearMulticlassMachine(ONE_VS_REST_STRATEGY,features,NULL,labs)
{
init_defaults();
set_C(C);
}
void CMulticlassLibLinear::init_defaults()
{
set_C(1.0);
set_epsilon(1e-2);
set_max_iter(10000);
set_use_bias(false);
set_save_train_state(false);
m_train_state = NULL;
}
void CMulticlassLibLinear::register_parameters()
{
SG_ADD(&m_C, "m_C", "regularization constant",MS_AVAILABLE);
SG_ADD(&m_epsilon, "m_epsilon", "tolerance epsilon",MS_NOT_AVAILABLE);
SG_ADD(&m_max_iter, "m_max_iter", "max number of iterations",MS_NOT_AVAILABLE);
SG_ADD(&m_use_bias, "m_use_bias", "indicates whether bias should be used",MS_NOT_AVAILABLE);
SG_ADD(&m_save_train_state, "m_save_train_state", "indicates whether bias should be used",MS_NOT_AVAILABLE);
}
CMulticlassLibLinear::~CMulticlassLibLinear()
{
reset_train_state();
}
SGVector<int32_t> CMulticlassLibLinear::get_support_vectors() const
{
if (!m_train_state)
SG_ERROR("Please enable save_train_state option and train machine.\n");
int32_t num_vectors = m_features->get_num_vectors();
int32_t num_classes = m_labels->get_num_classes();
v_array<int32_t> nz_idxs;
nz_idxs.reserve(num_vectors);
for (int32_t i=0; i<num_vectors; i++)
{
for (int32_t y=0; y<num_classes; y++)
{
if (CMath::abs(m_train_state->alpha[i*num_classes+y])>1e-6)
{
nz_idxs.push(i);
break;
}
}
}
int32_t num_nz = nz_idxs.index();
nz_idxs.reserve(num_nz);
return SGVector<int32_t>(nz_idxs.begin,num_nz);
}
bool CMulticlassLibLinear::train_machine(CFeatures* data)
{
if (data)
set_features((CDotFeatures*)data);
int32_t num_vectors = m_features->get_num_vectors();
int32_t num_classes = m_labels->get_num_classes();
int32_t bias_n = m_use_bias ? 1 : 0;
problem mc_problem;
mc_problem.l = num_vectors;
mc_problem.n = m_features->get_dim_feature_space() + bias_n;
mc_problem.y = SG_MALLOC(int32_t, mc_problem.l);
for (int32_t i=0; i<num_vectors; i++)
mc_problem.y[i] = m_labels->get_int_label(i);
mc_problem.x = m_features;
mc_problem.use_bias = m_use_bias;
if (!m_train_state)
m_train_state = new mcsvm_state();
float64_t* C = SG_MALLOC(float64_t, num_vectors);
for (int32_t i=0; i<num_vectors; i++)
C[i] = m_C;
Solver_MCSVM_CS solver(&mc_problem,num_classes,C,m_epsilon,
m_max_iter,m_max_train_time,m_train_state);
solver.solve();
clear_machines();
m_machines = SGVector<CMachine*>(num_classes);
for (int32_t i=0; i<num_classes; i++)
{
CLinearMachine* machine = new CLinearMachine();
float64_t* cw = SG_MALLOC(float64_t, mc_problem.n);
for (int32_t j=0; j<mc_problem.n-bias_n; j++)
cw[j] = m_train_state->w[j*num_classes+i];
machine->set_w(SGVector<float64_t>(cw,mc_problem.n-bias_n));
if (m_use_bias)
machine->set_bias(m_train_state->w[(mc_problem.n-bias_n)*num_classes+i]);
m_machines[i] = machine;
}
if (!m_save_train_state)
reset_train_state();
SG_FREE(C);
SG_FREE(mc_problem.y);
return true;
}
#endif /* HAVE_LAPACK */
<|endoftext|> |
<commit_before>/*!
\copyright (c) RDO-Team, 2003-2012
\file chart_serie.cpp
\author
\date 31.03.2003
\brief
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
#include "app/rdo_studio/pch/stdpch.h"
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "app/rdo_studio/src/chart/chart_serie.h"
// --------------------------------------------------------------------------------
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// --------------------------------------------------------------------------------
// -------------------- ChartSerie::Options
// --------------------------------------------------------------------------------
ChartSerie::Options::Options()
: color (QColor(0x00, 0x00, 0x00))
, markerType (RDOSM_NONE)
, markerSize (2) //! @todo qt , 1
, markerNeedDraw (true)
, markerTransparent(true)
, showInLegend (true)
{}
rbool ChartSerie::Options::operator== (CREF(Options) options) const
{
return title == options.title
&& color == options.color
&& markerType == options.markerType
&& markerSize == options.markerSize
&& markerNeedDraw == options.markerNeedDraw
&& markerTransparent == options.markerTransparent
&& showInLegend == options.showInLegend;
}
// --------------------------------------------------------------------------------
// -------------------- ChartSerie
// --------------------------------------------------------------------------------
ChartSerie::ChartSerie(TracerSerie* pSerie)
: m_pSerie(pSerie)
{
if (m_pSerie)
{
m_options.title = m_pSerie->getTitle();
}
}
ChartSerie::~ChartSerie()
{}
TracerSerie* ChartSerie::getSerie() const
{
return m_pSerie;
}
CREF(ChartSerie::Options) ChartSerie::options() const
{
return m_options;
}
void ChartSerie::setOptions(CREF(Options) options)
{
m_options = options;
}
rbool ChartSerie::isTracerSerie(const TracerSerie* pSerie) const
{
return m_pSerie == pSerie;
}
void ChartSerie::drawSerie(ChartView* const pView, QPainter& painter, const QRect& rect) const
{
m_pSerie->drawSerie(pView, painter, rect, m_options.color, m_options.markerType, m_options.markerSize, m_options.markerNeedDraw, m_options.markerTransparent);
}
void ChartSerie::getCaptions(std::vector<tstring> &captions, const int val_count) const
{
m_pSerie->getCaptions(captions, val_count);
}
void ChartSerie::lock()
{
m_pSerie->mutex.Lock();
}
void ChartSerie::unlock()
{
m_pSerie->mutex.Unlock();
}
rbool ChartSerie::empty() const
{
return m_pSerie->empty();
}
QSize ChartSerie::getLegendSize(const QFontMetrics& fm, const QRect& rect) const
{
QSize size(0, 0);
if (!m_options.showInLegend || rect.isEmpty())
return size;
QRect tmprect;
int markerAreaWidth = 10 + m_options.markerSize * 2 + 5;
tmprect.setLeft(rect.left() + markerAreaWidth);
tmprect.setRight(rect.right());
tmprect.setTop(rect.top());
tmprect.setBottom(rect.bottom());
tmprect = fm.boundingRect(tmprect, Qt::AlignLeft | Qt::TextSingleLine, QString::fromLocal8Bit(m_options.title.c_str()));
size.setHeight(tmprect.height());
if (size.height() < m_options.markerSize * 2)
{
size.setHeight(m_options.markerSize * 2);
}
size.setWidth(tmprect.right() - rect.left());
size.setHeight(size.height() + 2);
if (size.width() > rect.width())
{
size.setWidth(rect.width());
}
return size;
}
QSize ChartSerie::drawLegend(QPainter& painter, const QRect& rect, const QColor& textColor) const
{
QSize size = getLegendSize(painter.fontMetrics(), rect);
if (!m_options.showInLegend || size.isEmpty())
return size;
QPoint markerCenter(5 + m_options.markerSize, rect.top() + (size.height() - 2) / 2);
if (m_options.markerNeedDraw)
{
QPen pen(m_options.color);
QBrush brush(m_options.color, m_options.markerTransparent ? Qt::NoBrush : Qt::SolidPattern);
painter.setPen(pen);
painter.setBrush(brush);
m_pSerie->drawMarker(painter, rect.left() + markerCenter.x(), markerCenter.y(), m_options.markerType, m_options.markerSize);
}
painter.drawLine(rect.left(), markerCenter.y(), rect.left() + markerCenter.x() * 2, markerCenter.y());
QRect tmprect(rect);
tmprect.setLeft(tmprect.left() + markerCenter.x() * 2 + 5);
if (tmprect.isEmpty())
return size;
painter.setPen(textColor);
//! @todo qt +DT_END_ELLIPSIS
painter.drawText(tmprect, Qt::AlignLeft | Qt::TextSingleLine, QString::fromLocal8Bit(m_options.title.c_str()));
return size;
}
<commit_msg> - исправлен вывод текста в легенде<commit_after>/*!
\copyright (c) RDO-Team, 2003-2012
\file chart_serie.cpp
\author
\date 31.03.2003
\brief
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
#include "app/rdo_studio/pch/stdpch.h"
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "app/rdo_studio/src/chart/chart_serie.h"
// --------------------------------------------------------------------------------
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// --------------------------------------------------------------------------------
// -------------------- ChartSerie::Options
// --------------------------------------------------------------------------------
ChartSerie::Options::Options()
: color (QColor(0x00, 0x00, 0x00))
, markerType (RDOSM_NONE)
, markerSize (2) //! @todo qt , 1
, markerNeedDraw (true)
, markerTransparent(true)
, showInLegend (true)
{}
rbool ChartSerie::Options::operator== (CREF(Options) options) const
{
return title == options.title
&& color == options.color
&& markerType == options.markerType
&& markerSize == options.markerSize
&& markerNeedDraw == options.markerNeedDraw
&& markerTransparent == options.markerTransparent
&& showInLegend == options.showInLegend;
}
// --------------------------------------------------------------------------------
// -------------------- ChartSerie
// --------------------------------------------------------------------------------
ChartSerie::ChartSerie(TracerSerie* pSerie)
: m_pSerie(pSerie)
{
if (m_pSerie)
{
m_options.title = m_pSerie->getTitle();
}
}
ChartSerie::~ChartSerie()
{}
TracerSerie* ChartSerie::getSerie() const
{
return m_pSerie;
}
CREF(ChartSerie::Options) ChartSerie::options() const
{
return m_options;
}
void ChartSerie::setOptions(CREF(Options) options)
{
m_options = options;
}
rbool ChartSerie::isTracerSerie(const TracerSerie* pSerie) const
{
return m_pSerie == pSerie;
}
void ChartSerie::drawSerie(ChartView* const pView, QPainter& painter, const QRect& rect) const
{
m_pSerie->drawSerie(pView, painter, rect, m_options.color, m_options.markerType, m_options.markerSize, m_options.markerNeedDraw, m_options.markerTransparent);
}
void ChartSerie::getCaptions(std::vector<tstring> &captions, const int val_count) const
{
m_pSerie->getCaptions(captions, val_count);
}
void ChartSerie::lock()
{
m_pSerie->mutex.Lock();
}
void ChartSerie::unlock()
{
m_pSerie->mutex.Unlock();
}
rbool ChartSerie::empty() const
{
return m_pSerie->empty();
}
QSize ChartSerie::getLegendSize(const QFontMetrics& fm, const QRect& rect) const
{
QSize size(0, 0);
if (!m_options.showInLegend || rect.isEmpty())
return size;
QRect tmprect;
int markerAreaWidth = 10 + m_options.markerSize * 2 + 5;
tmprect.setLeft(rect.left() + markerAreaWidth);
tmprect.setRight(rect.right());
tmprect.setTop(rect.top());
tmprect.setBottom(rect.bottom());
tmprect = fm.boundingRect(tmprect, Qt::AlignLeft | Qt::TextSingleLine, QString::fromLocal8Bit(m_options.title.c_str()));
size.setHeight(tmprect.height());
if (size.height() < m_options.markerSize * 2)
{
size.setHeight(m_options.markerSize * 2);
}
size.setWidth(tmprect.right() - rect.left());
size.setHeight(size.height() + 2);
if (size.width() > rect.width())
{
size.setWidth(rect.width());
}
return size;
}
QSize ChartSerie::drawLegend(QPainter& painter, const QRect& rect, const QColor& textColor) const
{
QSize size = getLegendSize(painter.fontMetrics(), rect);
if (!m_options.showInLegend || size.isEmpty())
return size;
QPoint markerCenter(5 + m_options.markerSize, rect.top() + (size.height() - 2) / 2);
if (m_options.markerNeedDraw)
{
QPen pen(m_options.color);
QBrush brush(m_options.color, m_options.markerTransparent ? Qt::NoBrush : Qt::SolidPattern);
painter.setPen(pen);
painter.setBrush(brush);
m_pSerie->drawMarker(painter, rect.left() + markerCenter.x(), markerCenter.y(), m_options.markerType, m_options.markerSize);
}
painter.drawLine(rect.left(), markerCenter.y(), rect.left() + markerCenter.x() * 2, markerCenter.y());
QRect tmprect(rect);
tmprect.setLeft(tmprect.left() + markerCenter.x() * 2 + 5);
if (tmprect.isEmpty())
return size;
painter.setPen(textColor);
painter.drawText(tmprect, Qt::AlignLeft | Qt::TextSingleLine, painter.fontMetrics().elidedText(QString::fromLocal8Bit(m_options.title.c_str()), Qt::ElideRight, tmprect.width()));
return size;
}
<|endoftext|> |
<commit_before>/*!
\copyright (c) RDO-Team, 2011
\file main.cpp
\authors Урусов Андрей (rdo@rk9.bmstu.ru)
\authors Клеванец Игорь (impus@hotbox.ru)
\date 2.10.2011
\brief Тест законов распределения
\indent 4T
*/
// ----------------------------------------------------------------------- PLATFORM
#include "utils/src/common/platform.h"
// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- INCLUDES
#define BOOST_TEST_MODULE RDOSequencesTest
#include <iostream>
#include <fstream>
#include <vector>
#include <math.h>
#include <boost/test/included/unit_test.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
#include "utils/src/file/rdofile.h"
#include "utils/src/locale/rdolocale.h"
#include "simulator/runtime/rdo_random_distribution.h"
// --------------------------------------------------------------------------------
typedef std::vector<double> Container;
typedef std::vector<ruint> ContainerInt;
typedef const tstring contstr;
const long int g_seed = 123456789; //!< база генератора
contstr g_filePath = "../../test/sequences/"; //!< путь к файлам относительно проекта
contstr g_fileNormalName = "data_normal.txt"; //!< файл данных
contstr g_fileUniformName = "data_uniform.txt"; //!< файл данных
contstr g_fileExponentialName = "data_exponential.txt"; //!< файл данных
contstr g_fileTriangularName = "data_trinagular.txt"; //!< файл данных
const ruint g_count = 100000; //!< количество генерируемых данных
const double g_main = 10.0; //!< параметр закона экспоненциального и нормального
const double g_var = 1.0; //!< параметр закона нормального
const double g_from = 1.0; //!< параметр закона равномерного и треугольного
const double g_to = 7.0; //!< параметр закона равномерного и треугольного
const double g_top = 5.0; //!< параметр закона треугольного
#if defined(ARCHITECTURE_X86)
const ruint g_precision = 20; //!< точность вещественного числа при выводе в поток
#elif defined(ARCHITECTURE_AMD64) || defined(ARCHITECTURE_ARM)
const ruint g_precision = 14; //!< точность вещественного числа при выводе в поток
#endif
const ruint g_countOfExamples = 2000; //!< количество чисел в выборке
const ruint g_countOfR = 39; //!< число разрядов
const double pi = 3.141592653; //!< фундаментальная константа
const double g_ksiEtalon = 50.9985; //!< табличное значение. 95% вероятность того, что это действительно тот самый закон распределения
// --------------------------------------------------------------------------------
// -------Templates
// --------------------------------------------------------------------------------
template <class T, class F, class contstr>
void onGenerateData(F binder, contstr g_fileName)
{
if (rdo::File::exist(g_fileName))
return;
T sequence(g_seed);
Container test;
test.reserve(g_count);
for (ruint i = 0; i < g_count; ++i)
{
test.push_back(binder.operator()(&sequence));
}
std::ofstream stream(g_fileName.c_str());
stream.precision(g_precision);
STL_FOR_ALL(test, it)
{
stream << *it << std::endl;
}
}
template <class T, class F>
void onCheckData(F binder, contstr& g_fileName)
{
T sequence(g_seed);
std::ifstream stream(g_fileName.c_str());
const boost::posix_time::time_duration testDuration = boost::posix_time::microseconds(100000);
unsigned int minTestCount = 100;
boost::posix_time::ptime testStart = boost::posix_time::microsec_clock::local_time();
while (boost::posix_time::microsec_clock::local_time() - testStart < testDuration)
{
for (unsigned int i = 0; i < minTestCount; ++i)
{
if (!stream.good())
return;
double valueOriginal;
stream >> valueOriginal;
if (!stream.good())
return;
qqq++;
{
std::stringstream s;
s.precision(g_precision);
s << valueOriginal;
s >> valueOriginal;
}
double valueTest;
{
std::stringstream s;
s.precision(g_precision);
s << binder.operator()(&sequence);
s >> valueTest;
}
rbool check = valueOriginal == valueTest;
BOOST_CHECK(check);
if (!check)
{
std::cout.precision(g_precision);
std::cout << valueOriginal << " != " << valueTest << std::endl;
}
}
}
}
template <class T,class F>
double area (F binder, double n, double m)
{
double k = 1;
double S1 = 1;
double S2 = 0;
ruint t = 10;
while (fabs(S1-S2)/S1 > 0.01)
{
S2 = S1;
S1 = 0;
for (ruint g = 0; g < t + 1; ++g)
{
if ((g == 0) || (g == t - 1))
k = 0.5;
S1 += k*(binder.operator()(n + g*(m-n)/t));
k = 1;
}
S1 *= (m-n)/t;
t *= 10;
}
return S1;
}
template <class T, class G, class F, class S>
void onCheckKsi(F binder, S binderSeq, double left, double right)
{
Container x;
x.reserve(g_countOfR + 1);
double elem = (right-left)/(g_countOfR*1.0); //расстояние между точками на прямой
for (ruint i = 0; i < g_countOfR + 1; ++i)
{
x.push_back(left + elem*i);
}
Container vb; //контейнер для хранения выборки
vb.reserve(g_countOfExamples);
G sequence(g_seed); //выборка
for (ruint i = 0; i < g_countOfExamples; ++i)
{
vb.push_back(binderSeq.operator()(&sequence));
}
Container f_vb; //контейнер для храниения количества попаданий на интервал
f_vb.reserve(g_countOfR);
for(ruint i = 0; i < g_countOfR; ++i) //нахождение количества попаданий на интервал
{
ruint freq = 0;
for(ruint k = 0; k < g_countOfExamples; ++k)
{
if((vb[k] > x[i]) & (vb[k] <= x[i+1]))
{
++freq;
}
}
f_vb.push_back(freq);
}
Container F_etalon;
F_etalon.reserve(g_countOfR);
for (ruint i = 0; i < g_countOfR; ++i)
{
F_etalon.push_back(area<T>(binder, x[i], x[i+1]));
}
double ksi = 0;
for(ruint i = 0; i < g_countOfR; ++i)
{
double ksiTemp = F_etalon[i]*g_countOfExamples;
ksi += (f_vb[i] - ksiTemp)*(f_vb[i] - ksiTemp)/ksiTemp;
}
BOOST_CHECK(ksi <= g_ksiEtalon);
if (ksi > g_ksiEtalon)
{
std::cout << ksi << std::endl;
}
}
// --------------------------------------------------------------------------------
class SequenceNormal
{
public:
SequenceNormal(double main, double var)
: m_main(main)
, m_var (var )
{}
double get(double x) const
{
return 1/(sqrt(2*pi)*m_var*exp((x - m_main)*(x - m_main)/(2*m_var*m_var)));
}
private:
double m_main;
double m_var;
};
class SequenceExponential
{
public:
SequenceExponential(double main)
: m_main(main)
{}
double get(double x) const
{
return 1/(m_main*exp(x/m_main));
}
private:
double m_main;
};
class SequenceUniform
{
public:
SequenceUniform(double min, double max)
: m_min(min)
, m_max(max)
{}
double get(double x) const
{
UNUSED(x);
return 1/(m_max-m_min);
}
private:
double m_min;
double m_max;
};
class SequenceTriangular
{
public:
SequenceTriangular(double min, double top, double max)
: m_min(min-top)
, m_top(top)
, m_max(max-top)
{}
double get(double x) const
{
x -= m_top;
double temp;
if (x < 0)
{
temp = -2*x/((m_max - m_min)*m_min) + 2/(m_max - m_min);
}
else
{
temp = -2*x/((m_max - m_min)*m_max) + 2/(m_max - m_min);
}
return temp;
}
private:
double m_min;
double m_top;
double m_max;
};
BOOST_AUTO_TEST_SUITE(RDOSequencesTest)
// --------------------------------------------------------------------------------
// -------Normal sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDONormalTestCreate)
{
rdo::locale::init();
onGenerateData<rdo::runtime::RandGeneratorNormal>
(boost::bind(&rdo::runtime::RandGeneratorNormal::next, _1, g_main, g_var), g_filePath + g_fileNormalName);
}
BOOST_AUTO_TEST_CASE(RDONormalTestCheck)
{
onCheckData<rdo::runtime::RandGeneratorNormal>
(boost::bind(&rdo::runtime::RandGeneratorNormal::next, _1, g_main, g_var), g_filePath + g_fileNormalName);
SequenceNormal normal(g_main, g_var);
onCheckKsi<SequenceNormal, rdo::runtime::RandGeneratorNormal>
(boost::bind(&SequenceNormal::get, normal, _1),
boost::bind(&rdo::runtime::RandGeneratorNormal::next, _1, g_main, g_var),
g_main-4*g_var,
g_main+4*g_var);
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// -------Uniform sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDOUniformTestCreate)
{
onGenerateData<rdo::runtime::RandGeneratorUniform>
(boost::bind(&rdo::runtime::RandGeneratorUniform::next, _1, g_from, g_to), g_filePath + g_fileUniformName);
}
BOOST_AUTO_TEST_CASE(RDOUniformTestCheck)
{
onCheckData<rdo::runtime::RandGeneratorUniform>
(boost::bind(&rdo::runtime::RandGeneratorUniform::next, _1, g_from, g_to), g_filePath + g_fileUniformName);
SequenceUniform uniform(g_from, g_to);
onCheckKsi<SequenceUniform, rdo::runtime::RandGeneratorUniform>
(boost::bind(&SequenceUniform::get, uniform, _1),
boost::bind(&rdo::runtime::RandGeneratorUniform::next, _1, g_from, g_to),
g_from,
g_to);
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// -------Exponential sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDOExponentialTestCreate)
{
onGenerateData<rdo::runtime::RandGeneratorExponential>
(boost::bind(&rdo::runtime::RandGeneratorExponential::next, _1, g_main), g_filePath + g_fileExponentialName);
}
BOOST_AUTO_TEST_CASE(RDOExponentialTestCheck)
{
onCheckData<rdo::runtime::RandGeneratorExponential>
(boost::bind(&rdo::runtime::RandGeneratorExponential::next, _1, g_main), g_filePath + g_fileExponentialName);
SequenceExponential exponential(g_main);
onCheckKsi<SequenceExponential, rdo::runtime::RandGeneratorExponential>
(boost::bind(&SequenceExponential::get, exponential, _1),
boost::bind(&rdo::runtime::RandGeneratorExponential::next, _1, g_main),
0,
7*g_main);
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// -------Triangular sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDOTriangularTestCreate)
{
onGenerateData<rdo::runtime::RandGeneratorTriangular>
(boost::bind(&rdo::runtime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to), g_filePath + g_fileTriangularName);
}
BOOST_AUTO_TEST_CASE(RDOTriangularTestCheck)
{
onCheckData<rdo::runtime::RandGeneratorTriangular>
(boost::bind(&rdo::runtime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to), g_filePath + g_fileTriangularName);
SequenceTriangular triangular(g_from, g_top, g_to);
onCheckKsi<SequenceTriangular, rdo::runtime::RandGeneratorTriangular>
(boost::bind(&SequenceTriangular::get, triangular, _1),
boost::bind(&rdo::runtime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to),
g_from,
g_to);
}
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_SUITE_END()
<commit_msg> - к пред. коммиту<commit_after>/*!
\copyright (c) RDO-Team, 2011
\file main.cpp
\authors Урусов Андрей (rdo@rk9.bmstu.ru)
\authors Клеванец Игорь (impus@hotbox.ru)
\date 2.10.2011
\brief Тест законов распределения
\indent 4T
*/
// ----------------------------------------------------------------------- PLATFORM
#include "utils/src/common/platform.h"
// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- INCLUDES
#define BOOST_TEST_MODULE RDOSequencesTest
#include <iostream>
#include <fstream>
#include <vector>
#include <math.h>
#include <boost/test/included/unit_test.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
#include "utils/src/file/rdofile.h"
#include "utils/src/locale/rdolocale.h"
#include "simulator/runtime/rdo_random_distribution.h"
// --------------------------------------------------------------------------------
typedef std::vector<double> Container;
typedef std::vector<ruint> ContainerInt;
typedef const tstring contstr;
const long int g_seed = 123456789; //!< база генератора
contstr g_filePath = "../../test/sequences/"; //!< путь к файлам относительно проекта
contstr g_fileNormalName = "data_normal.txt"; //!< файл данных
contstr g_fileUniformName = "data_uniform.txt"; //!< файл данных
contstr g_fileExponentialName = "data_exponential.txt"; //!< файл данных
contstr g_fileTriangularName = "data_trinagular.txt"; //!< файл данных
const ruint g_count = 100000; //!< количество генерируемых данных
const double g_main = 10.0; //!< параметр закона экспоненциального и нормального
const double g_var = 1.0; //!< параметр закона нормального
const double g_from = 1.0; //!< параметр закона равномерного и треугольного
const double g_to = 7.0; //!< параметр закона равномерного и треугольного
const double g_top = 5.0; //!< параметр закона треугольного
#if defined(ARCHITECTURE_X86)
const ruint g_precision = 20; //!< точность вещественного числа при выводе в поток
#elif defined(ARCHITECTURE_AMD64) || defined(ARCHITECTURE_ARM)
const ruint g_precision = 14; //!< точность вещественного числа при выводе в поток
#endif
const ruint g_countOfExamples = 2000; //!< количество чисел в выборке
const ruint g_countOfR = 39; //!< число разрядов
const double pi = 3.141592653; //!< фундаментальная константа
const double g_ksiEtalon = 50.9985; //!< табличное значение. 95% вероятность того, что это действительно тот самый закон распределения
// --------------------------------------------------------------------------------
// -------Templates
// --------------------------------------------------------------------------------
template <class T, class F, class contstr>
void onGenerateData(F binder, contstr g_fileName)
{
if (rdo::File::exist(g_fileName))
return;
T sequence(g_seed);
Container test;
test.reserve(g_count);
for (ruint i = 0; i < g_count; ++i)
{
test.push_back(binder.operator()(&sequence));
}
std::ofstream stream(g_fileName.c_str());
stream.precision(g_precision);
STL_FOR_ALL(test, it)
{
stream << *it << std::endl;
}
}
template <class T, class F>
void onCheckData(F binder, contstr& g_fileName)
{
T sequence(g_seed);
std::ifstream stream(g_fileName.c_str());
const boost::posix_time::time_duration testDuration = boost::posix_time::microseconds(100000);
unsigned int minTestCount = 100;
boost::posix_time::ptime testStart = boost::posix_time::microsec_clock::local_time();
while (boost::posix_time::microsec_clock::local_time() - testStart < testDuration)
{
for (unsigned int i = 0; i < minTestCount; ++i)
{
if (!stream.good())
return;
double valueOriginal;
stream >> valueOriginal;
if (!stream.good())
return;
{
std::stringstream s;
s.precision(g_precision);
s << valueOriginal;
s >> valueOriginal;
}
double valueTest;
{
std::stringstream s;
s.precision(g_precision);
s << binder.operator()(&sequence);
s >> valueTest;
}
rbool check = valueOriginal == valueTest;
BOOST_CHECK(check);
if (!check)
{
std::cout.precision(g_precision);
std::cout << valueOriginal << " != " << valueTest << std::endl;
}
}
}
}
template <class T,class F>
double area (F binder, double n, double m)
{
double k = 1;
double S1 = 1;
double S2 = 0;
ruint t = 10;
while (fabs(S1-S2)/S1 > 0.01)
{
S2 = S1;
S1 = 0;
for (ruint g = 0; g < t + 1; ++g)
{
if ((g == 0) || (g == t - 1))
k = 0.5;
S1 += k*(binder.operator()(n + g*(m-n)/t));
k = 1;
}
S1 *= (m-n)/t;
t *= 10;
}
return S1;
}
template <class T, class G, class F, class S>
void onCheckKsi(F binder, S binderSeq, double left, double right)
{
Container x;
x.reserve(g_countOfR + 1);
double elem = (right-left)/(g_countOfR*1.0); //расстояние между точками на прямой
for (ruint i = 0; i < g_countOfR + 1; ++i)
{
x.push_back(left + elem*i);
}
Container vb; //контейнер для хранения выборки
vb.reserve(g_countOfExamples);
G sequence(g_seed); //выборка
for (ruint i = 0; i < g_countOfExamples; ++i)
{
vb.push_back(binderSeq.operator()(&sequence));
}
Container f_vb; //контейнер для храниения количества попаданий на интервал
f_vb.reserve(g_countOfR);
for(ruint i = 0; i < g_countOfR; ++i) //нахождение количества попаданий на интервал
{
ruint freq = 0;
for(ruint k = 0; k < g_countOfExamples; ++k)
{
if((vb[k] > x[i]) & (vb[k] <= x[i+1]))
{
++freq;
}
}
f_vb.push_back(freq);
}
Container F_etalon;
F_etalon.reserve(g_countOfR);
for (ruint i = 0; i < g_countOfR; ++i)
{
F_etalon.push_back(area<T>(binder, x[i], x[i+1]));
}
double ksi = 0;
for(ruint i = 0; i < g_countOfR; ++i)
{
double ksiTemp = F_etalon[i]*g_countOfExamples;
ksi += (f_vb[i] - ksiTemp)*(f_vb[i] - ksiTemp)/ksiTemp;
}
BOOST_CHECK(ksi <= g_ksiEtalon);
if (ksi > g_ksiEtalon)
{
std::cout << ksi << std::endl;
}
}
// --------------------------------------------------------------------------------
class SequenceNormal
{
public:
SequenceNormal(double main, double var)
: m_main(main)
, m_var (var )
{}
double get(double x) const
{
return 1/(sqrt(2*pi)*m_var*exp((x - m_main)*(x - m_main)/(2*m_var*m_var)));
}
private:
double m_main;
double m_var;
};
class SequenceExponential
{
public:
SequenceExponential(double main)
: m_main(main)
{}
double get(double x) const
{
return 1/(m_main*exp(x/m_main));
}
private:
double m_main;
};
class SequenceUniform
{
public:
SequenceUniform(double min, double max)
: m_min(min)
, m_max(max)
{}
double get(double x) const
{
UNUSED(x);
return 1/(m_max-m_min);
}
private:
double m_min;
double m_max;
};
class SequenceTriangular
{
public:
SequenceTriangular(double min, double top, double max)
: m_min(min-top)
, m_top(top)
, m_max(max-top)
{}
double get(double x) const
{
x -= m_top;
double temp;
if (x < 0)
{
temp = -2*x/((m_max - m_min)*m_min) + 2/(m_max - m_min);
}
else
{
temp = -2*x/((m_max - m_min)*m_max) + 2/(m_max - m_min);
}
return temp;
}
private:
double m_min;
double m_top;
double m_max;
};
BOOST_AUTO_TEST_SUITE(RDOSequencesTest)
// --------------------------------------------------------------------------------
// -------Normal sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDONormalTestCreate)
{
rdo::locale::init();
onGenerateData<rdo::runtime::RandGeneratorNormal>
(boost::bind(&rdo::runtime::RandGeneratorNormal::next, _1, g_main, g_var), g_filePath + g_fileNormalName);
}
BOOST_AUTO_TEST_CASE(RDONormalTestCheck)
{
onCheckData<rdo::runtime::RandGeneratorNormal>
(boost::bind(&rdo::runtime::RandGeneratorNormal::next, _1, g_main, g_var), g_filePath + g_fileNormalName);
SequenceNormal normal(g_main, g_var);
onCheckKsi<SequenceNormal, rdo::runtime::RandGeneratorNormal>
(boost::bind(&SequenceNormal::get, normal, _1),
boost::bind(&rdo::runtime::RandGeneratorNormal::next, _1, g_main, g_var),
g_main-4*g_var,
g_main+4*g_var);
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// -------Uniform sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDOUniformTestCreate)
{
onGenerateData<rdo::runtime::RandGeneratorUniform>
(boost::bind(&rdo::runtime::RandGeneratorUniform::next, _1, g_from, g_to), g_filePath + g_fileUniformName);
}
BOOST_AUTO_TEST_CASE(RDOUniformTestCheck)
{
onCheckData<rdo::runtime::RandGeneratorUniform>
(boost::bind(&rdo::runtime::RandGeneratorUniform::next, _1, g_from, g_to), g_filePath + g_fileUniformName);
SequenceUniform uniform(g_from, g_to);
onCheckKsi<SequenceUniform, rdo::runtime::RandGeneratorUniform>
(boost::bind(&SequenceUniform::get, uniform, _1),
boost::bind(&rdo::runtime::RandGeneratorUniform::next, _1, g_from, g_to),
g_from,
g_to);
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// -------Exponential sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDOExponentialTestCreate)
{
onGenerateData<rdo::runtime::RandGeneratorExponential>
(boost::bind(&rdo::runtime::RandGeneratorExponential::next, _1, g_main), g_filePath + g_fileExponentialName);
}
BOOST_AUTO_TEST_CASE(RDOExponentialTestCheck)
{
onCheckData<rdo::runtime::RandGeneratorExponential>
(boost::bind(&rdo::runtime::RandGeneratorExponential::next, _1, g_main), g_filePath + g_fileExponentialName);
SequenceExponential exponential(g_main);
onCheckKsi<SequenceExponential, rdo::runtime::RandGeneratorExponential>
(boost::bind(&SequenceExponential::get, exponential, _1),
boost::bind(&rdo::runtime::RandGeneratorExponential::next, _1, g_main),
0,
7*g_main);
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// -------Triangular sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDOTriangularTestCreate)
{
onGenerateData<rdo::runtime::RandGeneratorTriangular>
(boost::bind(&rdo::runtime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to), g_filePath + g_fileTriangularName);
}
BOOST_AUTO_TEST_CASE(RDOTriangularTestCheck)
{
onCheckData<rdo::runtime::RandGeneratorTriangular>
(boost::bind(&rdo::runtime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to), g_filePath + g_fileTriangularName);
SequenceTriangular triangular(g_from, g_top, g_to);
onCheckKsi<SequenceTriangular, rdo::runtime::RandGeneratorTriangular>
(boost::bind(&SequenceTriangular::get, triangular, _1),
boost::bind(&rdo::runtime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to),
g_from,
g_to);
}
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: imgdef.hxx,v $
* $Revision: 1.7 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _SVTOOLS_IMGDEF_HXX
#define _SVTOOLS_IMGDEF_HXX
enum SfxSymbolsSize
{
SFX_SYMBOLS_SIZE_SMALL,
SFX_SYMBOLS_SIZE_LARGE,
SFX_SYMBOLS_SIZE_AUTO
};
enum SfxSymbolsStyle
{
SFX_SYMBOLS_STYLE_AUTO,
SFX_SYMBOLS_STYLE_DEFAULT,
SFX_SYMBOLS_STYLE_HICONTRAST,
SFX_SYMBOLS_STYLE_INDUSTRIAL,
SFX_SYMBOLS_STYLE_CRYSTAL,
SFX_SYMBOLS_STYLE_TANGO
};
#define SFX_TOOLBOX_CHANGESYMBOLSET 0x0001
#define SFX_TOOLBOX_CHANGEOUTSTYLE 0x0002
#define SFX_TOOLBOX_CHANGEBUTTONTYPE 0x0004
#endif // _SVTOOLS_IMGDEF_HXX
<commit_msg>INTEGRATION: CWS iconupdate300u1 (1.7.48); FILE MERGED 2008/05/14 14:39:45 ka 1.7.48.1: #i89469#: added Classic theme<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: imgdef.hxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _SVTOOLS_IMGDEF_HXX
#define _SVTOOLS_IMGDEF_HXX
enum SfxSymbolsSize
{
SFX_SYMBOLS_SIZE_SMALL,
SFX_SYMBOLS_SIZE_LARGE,
SFX_SYMBOLS_SIZE_AUTO
};
enum SfxSymbolsStyle
{
SFX_SYMBOLS_STYLE_AUTO,
SFX_SYMBOLS_STYLE_DEFAULT,
SFX_SYMBOLS_STYLE_HICONTRAST,
SFX_SYMBOLS_STYLE_INDUSTRIAL,
SFX_SYMBOLS_STYLE_CRYSTAL,
SFX_SYMBOLS_STYLE_TANGO,
SFX_SYMBOLS_STYLE_CLASSIC
};
#define SFX_TOOLBOX_CHANGESYMBOLSET 0x0001
#define SFX_TOOLBOX_CHANGEOUTSTYLE 0x0002
#define SFX_TOOLBOX_CHANGEBUTTONTYPE 0x0004
#endif // _SVTOOLS_IMGDEF_HXX
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.