text
stringlengths 54
60.6k
|
|---|
<commit_before>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <string>
#include <vector>
#include <map>
#include "common.h"
#include "bzfio.h"
#include "version.h"
#include "TextUtils.h"
#include "commands.h"
#include "bzfsAPI.h"
#include "DirectoryNames.h"
#ifdef _WIN32
std::string extension = ".dll";
std::string globalPluginDir = ".\\plugins\\";
#else
std::string extension = ".so";
std::string globalPluginDir = "$(prefix)/lib/bzflag/";
#endif
typedef std::map<std::string, bz_APIPluginHandler*> tmCustomPluginMap;
tmCustomPluginMap customPluginMap;
typedef struct
{
std::string plugin;
#ifdef _WIN32
HINSTANCE handle;
#else
void* handle;
#endif
}trPluginRecord;
std::string findPlugin ( std::string pluginName )
{
// see if we can just open the bloody thing
FILE *fp = fopen(pluginName.c_str(),"rb");
if (fp)
{
fclose(fp);
return pluginName;
}
// now try it with the standard extension
std::string name = pluginName + extension;
fp = fopen(name.c_str(),"rb");
if (fp)
{
fclose(fp);
return name;
}
// check the local users plugins dir
name = getConfigDirName(BZ_CONFIG_DIR_VERSION) + pluginName + extension;
fp = fopen(name.c_str(),"rb");
if (fp)
{
fclose(fp);
return name;
}
// check the global plugins dir
name = globalPluginDir + pluginName + extension;
fp = fopen(name.c_str(),"rb");
if (fp)
{
fclose(fp);
return name;
}
return std::string("");
}
std::vector<trPluginRecord> vPluginList;
void unload1Plugin ( int iPluginID );
#ifdef _WIN32
#include <windows.h>
int getPluginVersion ( HINSTANCE hLib )
{
int (*lpProc)(void);
lpProc = (int (__cdecl *)(void))GetProcAddress(hLib, "bz_GetVersion");
if (lpProc)
return lpProc();
return 2;
}
void load1Plugin ( std::string plugin, std::string config )
{
int (*lpProc)(const char*);
std::string realPluginName = findPlugin(plugin);
HINSTANCE hLib = LoadLibrary(realPluginName.c_str());
if (hLib)
{
if (getPluginVersion(hLib) < BZ_API_VERSION)
{
DEBUG1("Plugin:%s found but expects an older API version (%d), upgrade it\n",plugin.c_str(),getPluginVersion(hLib));
FreeLibrary(hLib);
}
else
{
lpProc = (int (__cdecl *)(const char*))GetProcAddress(hLib, "bz_Load");
if (lpProc)
{
lpProc(config.c_str());
DEBUG1("Plugin:%s loaded\n",plugin.c_str());
trPluginRecord pluginRecord;
pluginRecord.handle = hLib;
pluginRecord.plugin = plugin;
vPluginList.push_back(pluginRecord);
}
else
{
DEBUG1("Plugin:%s found but does not contain bz_Load method\n",plugin.c_str());
FreeLibrary(hLib);
}
}
}
else
DEBUG1("Plugin:%s not found\n",plugin.c_str());
}
void unload1Plugin ( int iPluginID )
{
int (*lpProc)(void);
trPluginRecord &plugin = vPluginList[iPluginID];
lpProc = (int (__cdecl *)(void))GetProcAddress(plugin.handle, "bz_Unload");
if (lpProc)
lpProc();
else
DEBUG1("Plugin does not contain bz_UnLoad method\n");
FreeLibrary(plugin.handle);
plugin.handle = NULL;
}
#else
#include <dlfcn.h>
std::vector<void*> vLibHandles;
int getPluginVersion ( void* hLib )
{
int (*lpProc)(void);
*(void**) &lpProc = dlsym(hLib,"bz_GetVersion");
if (lpProc)
return (*lpProc)();
return 0;
}
void load1Plugin ( std::string plugin, std::string config )
{
int (*lpProc)(const char*);
std::string realPluginName = findPlugin(plugin);
void *hLib = dlopen(realPluginName.c_str(), RTLD_LAZY | RTLD_GLOBAL);
if (hLib)
{
if (dlsym(hLib, "bz_Load") == NULL) {
DEBUG1("Plugin:%s found but does not contain bz_Load method, error %s\n",plugin.c_str(),dlerror());
dlclose(hLib);
return;
}
int version = getPluginVersion(hLib);
if (version < BZ_API_VERSION)
{
DEBUG1("Plugin:%s found but expects an older API version (%d), upgrade it\n", plugin.c_str(), version);
dlclose(hLib);
}
else
{
*(void**) &lpProc = dlsym(hLib,"bz_Load");
if (lpProc)
{
(*lpProc)(config.c_str());
DEBUG1("Plugin:%s loaded\n",plugin.c_str());
trPluginRecord pluginRecord;
pluginRecord.handle = hLib;
pluginRecord.plugin = plugin;
vPluginList.push_back(pluginRecord);
}
}
}
else
DEBUG1("Plugin:%s not found, error %s\n",plugin.c_str(), dlerror());
}
void unload1Plugin ( int iPluginID )
{
int (*lpProc)(void);
trPluginRecord &plugin = vPluginList[iPluginID];
*(void**) &lpProc = dlsym(plugin.handle, "bz_Unload");
if (lpProc)
(*lpProc)();
else
DEBUG1("Plugin does not contain bz_UnLoad method, error %s\n",dlerror());
dlclose(plugin.handle);
plugin.handle = NULL;
}
#endif
void loadPlugin ( std::string plugin, std::string config )
{
// check and see if it's an extension we have a handler for
std::string ext;
std::vector<std::string> parts = TextUtils::tokenize(plugin,std::string("."));
ext = parts[parts.size()-1];
tmCustomPluginMap::iterator itr = customPluginMap.find(TextUtils::tolower(extension));
if (itr != customPluginMap.end() && itr->second)
{
bz_APIPluginHandler *handler = itr->second;
handler->handle(plugin,config);
}
else
load1Plugin(plugin,config);
}
void unloadPlugin ( std::string plugin )
{
// unload the first one of the name we find
for (unsigned int i = 0; i < vPluginList.size();i++)
{
if ( vPluginList[i].plugin == plugin )
{
unload1Plugin(i);
vPluginList.erase(vPluginList.begin()+i);
return;
}
}
}
void unloadPlugins ( void )
{
for (unsigned int i = 0; i < vPluginList.size();i++)
unload1Plugin(i);
vPluginList.clear();
removeCustomSlashCommand("loadplugin");
removeCustomSlashCommand("unloadplugin");
removeCustomSlashCommand("listplugins");
}
std::vector<std::string> getPluginList ( void )
{
std::vector<std::string> plugins;
for (unsigned int i = 0; i < vPluginList.size();i++)
plugins.push_back(vPluginList[i].plugin);
return plugins;
}
void parseServerCommand(const char *message, int dstPlayerId);
class DynamicPluginCommands : public bz_CustomSlashCommandHandler
{
public:
virtual ~DynamicPluginCommands(){};
virtual bool handle ( int playerID, bzApiString _command, bzApiString _message )
{
bz_PlayerRecord record;
std::string command = _command.c_str();
std::string message = _message.c_str();
bz_PlayerRecord *p = bz_getPlayerByIndex(playerID);
if (!p)
return false;
record = *p;
bz_freePlayerRecord(p);
if ( !record.admin )
{
bz_sendTextMessage(BZ_SERVER,playerID,"Permision denied: ADMIN");
return true;
}
if ( !message.size() )
{
bz_sendTextMessage(BZ_SERVER,playerID,"Error: Command must have a plugin name");
return true;
}
if ( TextUtils::tolower(command) == "loadplugin" )
{
std::vector<std::string> params = TextUtils::tokenize(message,std::string(","));
std::string config;
if ( params.size() >1)
config = params[1];
loadPlugin(params[0],config);
bz_sendTextMessage(BZ_SERVER,playerID,"Plug-in loaded");
return true;
}
if ( TextUtils::tolower(command) == "unloadplugin" )
{
unloadPlugin(message);
bz_sendTextMessage(BZ_SERVER,playerID,"Plug-in unloaded");
return true;
}
if ( TextUtils::tolower(command) == "listplugins" )
{
std::vector<std::string> plugins = getPluginList();
if (!plugins.size())
bz_sendTextMessage(BZ_SERVER,playerID,"No Plug-ins loaded;");
else
{
bz_sendTextMessage(BZ_SERVER,playerID,"Plug-isn loaded;");
for ( unsigned int i = 0; i < plugins.size(); i++)
bz_sendTextMessage(BZ_SERVER,playerID,plugins[i].c_str());
}
return true;
}
return true;
}
};
DynamicPluginCommands command;
void initPlugins ( void )
{
customPluginMap.clear();
registerCustomSlashCommand("loadplugin",&command);
registerCustomSlashCommand("unloadplugin",&command);
registerCustomSlashCommand("listplugins",&command);
}
bool registerCustomPluginHandler ( std::string exte, bz_APIPluginHandler *handler )
{
std::string ext = TextUtils::tolower(exte);
customPluginMap[ext] = handler;
return true;
}
bool removeCustomPluginHandler ( std::string ext, bz_APIPluginHandler *handler )
{
tmCustomPluginMap::iterator itr = customPluginMap.find(TextUtils::tolower(ext));
if (itr == customPluginMap.end() || itr->second != handler)
return false;
customPluginMap.erase(itr);
return true;
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>s/extension/ext/ in loadPlugin. this compiled before because apparently 'extension' is a global variable which contains 'so' or 'dll', which isn't what we want<commit_after>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <string>
#include <vector>
#include <map>
#include "common.h"
#include "bzfio.h"
#include "version.h"
#include "TextUtils.h"
#include "commands.h"
#include "bzfsAPI.h"
#include "DirectoryNames.h"
#ifdef _WIN32
std::string extension = ".dll";
std::string globalPluginDir = ".\\plugins\\";
#else
std::string extension = ".so";
std::string globalPluginDir = "$(prefix)/lib/bzflag/";
#endif
typedef std::map<std::string, bz_APIPluginHandler*> tmCustomPluginMap;
tmCustomPluginMap customPluginMap;
typedef struct
{
std::string plugin;
#ifdef _WIN32
HINSTANCE handle;
#else
void* handle;
#endif
}trPluginRecord;
std::string findPlugin ( std::string pluginName )
{
// see if we can just open the bloody thing
FILE *fp = fopen(pluginName.c_str(),"rb");
if (fp)
{
fclose(fp);
return pluginName;
}
// now try it with the standard extension
std::string name = pluginName + extension;
fp = fopen(name.c_str(),"rb");
if (fp)
{
fclose(fp);
return name;
}
// check the local users plugins dir
name = getConfigDirName(BZ_CONFIG_DIR_VERSION) + pluginName + extension;
fp = fopen(name.c_str(),"rb");
if (fp)
{
fclose(fp);
return name;
}
// check the global plugins dir
name = globalPluginDir + pluginName + extension;
fp = fopen(name.c_str(),"rb");
if (fp)
{
fclose(fp);
return name;
}
return std::string("");
}
std::vector<trPluginRecord> vPluginList;
void unload1Plugin ( int iPluginID );
#ifdef _WIN32
#include <windows.h>
int getPluginVersion ( HINSTANCE hLib )
{
int (*lpProc)(void);
lpProc = (int (__cdecl *)(void))GetProcAddress(hLib, "bz_GetVersion");
if (lpProc)
return lpProc();
return 2;
}
void load1Plugin ( std::string plugin, std::string config )
{
int (*lpProc)(const char*);
std::string realPluginName = findPlugin(plugin);
HINSTANCE hLib = LoadLibrary(realPluginName.c_str());
if (hLib)
{
if (getPluginVersion(hLib) < BZ_API_VERSION)
{
DEBUG1("Plugin:%s found but expects an older API version (%d), upgrade it\n",plugin.c_str(),getPluginVersion(hLib));
FreeLibrary(hLib);
}
else
{
lpProc = (int (__cdecl *)(const char*))GetProcAddress(hLib, "bz_Load");
if (lpProc)
{
lpProc(config.c_str());
DEBUG1("Plugin:%s loaded\n",plugin.c_str());
trPluginRecord pluginRecord;
pluginRecord.handle = hLib;
pluginRecord.plugin = plugin;
vPluginList.push_back(pluginRecord);
}
else
{
DEBUG1("Plugin:%s found but does not contain bz_Load method\n",plugin.c_str());
FreeLibrary(hLib);
}
}
}
else
DEBUG1("Plugin:%s not found\n",plugin.c_str());
}
void unload1Plugin ( int iPluginID )
{
int (*lpProc)(void);
trPluginRecord &plugin = vPluginList[iPluginID];
lpProc = (int (__cdecl *)(void))GetProcAddress(plugin.handle, "bz_Unload");
if (lpProc)
lpProc();
else
DEBUG1("Plugin does not contain bz_UnLoad method\n");
FreeLibrary(plugin.handle);
plugin.handle = NULL;
}
#else
#include <dlfcn.h>
std::vector<void*> vLibHandles;
int getPluginVersion ( void* hLib )
{
int (*lpProc)(void);
*(void**) &lpProc = dlsym(hLib,"bz_GetVersion");
if (lpProc)
return (*lpProc)();
return 0;
}
void load1Plugin ( std::string plugin, std::string config )
{
int (*lpProc)(const char*);
std::string realPluginName = findPlugin(plugin);
void *hLib = dlopen(realPluginName.c_str(), RTLD_LAZY | RTLD_GLOBAL);
if (hLib)
{
if (dlsym(hLib, "bz_Load") == NULL) {
DEBUG1("Plugin:%s found but does not contain bz_Load method, error %s\n",plugin.c_str(),dlerror());
dlclose(hLib);
return;
}
int version = getPluginVersion(hLib);
if (version < BZ_API_VERSION)
{
DEBUG1("Plugin:%s found but expects an older API version (%d), upgrade it\n", plugin.c_str(), version);
dlclose(hLib);
}
else
{
*(void**) &lpProc = dlsym(hLib,"bz_Load");
if (lpProc)
{
(*lpProc)(config.c_str());
DEBUG1("Plugin:%s loaded\n",plugin.c_str());
trPluginRecord pluginRecord;
pluginRecord.handle = hLib;
pluginRecord.plugin = plugin;
vPluginList.push_back(pluginRecord);
}
}
}
else
DEBUG1("Plugin:%s not found, error %s\n",plugin.c_str(), dlerror());
}
void unload1Plugin ( int iPluginID )
{
int (*lpProc)(void);
trPluginRecord &plugin = vPluginList[iPluginID];
*(void**) &lpProc = dlsym(plugin.handle, "bz_Unload");
if (lpProc)
(*lpProc)();
else
DEBUG1("Plugin does not contain bz_UnLoad method, error %s\n",dlerror());
dlclose(plugin.handle);
plugin.handle = NULL;
}
#endif
void loadPlugin ( std::string plugin, std::string config )
{
// check and see if it's an extension we have a handler for
std::string ext;
std::vector<std::string> parts = TextUtils::tokenize(plugin,std::string("."));
ext = parts[parts.size()-1];
tmCustomPluginMap::iterator itr = customPluginMap.find(TextUtils::tolower(ext));
if (itr != customPluginMap.end() && itr->second)
{
bz_APIPluginHandler *handler = itr->second;
handler->handle(plugin,config);
}
else
load1Plugin(plugin,config);
}
void unloadPlugin ( std::string plugin )
{
// unload the first one of the name we find
for (unsigned int i = 0; i < vPluginList.size();i++)
{
if ( vPluginList[i].plugin == plugin )
{
unload1Plugin(i);
vPluginList.erase(vPluginList.begin()+i);
return;
}
}
}
void unloadPlugins ( void )
{
for (unsigned int i = 0; i < vPluginList.size();i++)
unload1Plugin(i);
vPluginList.clear();
removeCustomSlashCommand("loadplugin");
removeCustomSlashCommand("unloadplugin");
removeCustomSlashCommand("listplugins");
}
std::vector<std::string> getPluginList ( void )
{
std::vector<std::string> plugins;
for (unsigned int i = 0; i < vPluginList.size();i++)
plugins.push_back(vPluginList[i].plugin);
return plugins;
}
void parseServerCommand(const char *message, int dstPlayerId);
class DynamicPluginCommands : public bz_CustomSlashCommandHandler
{
public:
virtual ~DynamicPluginCommands(){};
virtual bool handle ( int playerID, bzApiString _command, bzApiString _message )
{
bz_PlayerRecord record;
std::string command = _command.c_str();
std::string message = _message.c_str();
bz_PlayerRecord *p = bz_getPlayerByIndex(playerID);
if (!p)
return false;
record = *p;
bz_freePlayerRecord(p);
if ( !record.admin )
{
bz_sendTextMessage(BZ_SERVER,playerID,"Permision denied: ADMIN");
return true;
}
if ( !message.size() )
{
bz_sendTextMessage(BZ_SERVER,playerID,"Error: Command must have a plugin name");
return true;
}
if ( TextUtils::tolower(command) == "loadplugin" )
{
std::vector<std::string> params = TextUtils::tokenize(message,std::string(","));
std::string config;
if ( params.size() >1)
config = params[1];
loadPlugin(params[0],config);
bz_sendTextMessage(BZ_SERVER,playerID,"Plug-in loaded");
return true;
}
if ( TextUtils::tolower(command) == "unloadplugin" )
{
unloadPlugin(message);
bz_sendTextMessage(BZ_SERVER,playerID,"Plug-in unloaded");
return true;
}
if ( TextUtils::tolower(command) == "listplugins" )
{
std::vector<std::string> plugins = getPluginList();
if (!plugins.size())
bz_sendTextMessage(BZ_SERVER,playerID,"No Plug-ins loaded;");
else
{
bz_sendTextMessage(BZ_SERVER,playerID,"Plug-isn loaded;");
for ( unsigned int i = 0; i < plugins.size(); i++)
bz_sendTextMessage(BZ_SERVER,playerID,plugins[i].c_str());
}
return true;
}
return true;
}
};
DynamicPluginCommands command;
void initPlugins ( void )
{
customPluginMap.clear();
registerCustomSlashCommand("loadplugin",&command);
registerCustomSlashCommand("unloadplugin",&command);
registerCustomSlashCommand("listplugins",&command);
}
bool registerCustomPluginHandler ( std::string exte, bz_APIPluginHandler *handler )
{
std::string ext = TextUtils::tolower(exte);
customPluginMap[ext] = handler;
return true;
}
bool removeCustomPluginHandler ( std::string ext, bz_APIPluginHandler *handler )
{
tmCustomPluginMap::iterator itr = customPluginMap.find(TextUtils::tolower(ext));
if (itr == customPluginMap.end() || itr->second != handler)
return false;
customPluginMap.erase(itr);
return true;
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: Currency.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: hr $ $Date: 2006-06-19 12:46:41 $
*
* 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 _FORMS_CURRENCY_HXX_
#include "Currency.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _UNOTOOLS_LOCALEDATAWRAPPER_HXX
#include <unotools/localedatawrapper.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_SYSLOCALE_HXX
#include <svtools/syslocale.hxx>
#endif
//.........................................................................
namespace frm
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::form;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::util;
//==================================================================
// OCurrencyControl
//==================================================================
//------------------------------------------------------------------
OCurrencyControl::OCurrencyControl(const Reference<XMultiServiceFactory>& _rxFactory)
:OBoundControl(_rxFactory, VCL_CONTROL_CURRENCYFIELD)
{
}
//------------------------------------------------------------------
InterfaceRef SAL_CALL OCurrencyControl_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory)
{
return *(new OCurrencyControl(_rxFactory));
}
//------------------------------------------------------------------------------
Sequence<Type> OCurrencyControl::_getTypes()
{
return OBoundControl::_getTypes();
}
//------------------------------------------------------------------------------
StringSequence SAL_CALL OCurrencyControl::getSupportedServiceNames() throw()
{
StringSequence aSupported = OBoundControl::getSupportedServiceNames();
aSupported.realloc(aSupported.getLength() + 1);
::rtl::OUString*pArray = aSupported.getArray();
pArray[aSupported.getLength()-1] = FRM_SUN_CONTROL_CURRENCYFIELD;
return aSupported;
}
//==================================================================
// OCurrencyModel
//==================================================================
//------------------------------------------------------------------
InterfaceRef SAL_CALL OCurrencyModel_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory)
{
return *(new OCurrencyModel(_rxFactory));
}
//------------------------------------------------------------------------------
Sequence<Type> OCurrencyModel::_getTypes()
{
return OEditBaseModel::_getTypes();
}
//------------------------------------------------------------------
void OCurrencyModel::implConstruct()
{
if (m_xAggregateSet.is())
{
try
{
// get the system international informations
const LocaleDataWrapper& aLocaleInfo = SvtSysLocale().GetLocaleData();
::rtl::OUString sCurrencySymbol;
sal_Bool bPrependCurrencySymbol;
switch ( aLocaleInfo.getCurrPositiveFormat() )
{
case 0: // $1
sCurrencySymbol = String(aLocaleInfo.getCurrSymbol());
bPrependCurrencySymbol = sal_True;
break;
case 1: // 1$
sCurrencySymbol = String(aLocaleInfo.getCurrSymbol());
bPrependCurrencySymbol = sal_False;
break;
case 2: // $ 1
sCurrencySymbol = ::rtl::OUString(String(aLocaleInfo.getCurrSymbol())) + ::rtl::OUString::createFromAscii(" ");
bPrependCurrencySymbol = sal_True;
break;
case 3: // 1 $
sCurrencySymbol = ::rtl::OUString::createFromAscii(" ") + ::rtl::OUString(String(aLocaleInfo.getCurrSymbol()));
bPrependCurrencySymbol = sal_False;
break;
}
if (sCurrencySymbol.getLength())
{
m_xAggregateSet->setPropertyValue(PROPERTY_CURRENCYSYMBOL, makeAny(sCurrencySymbol));
m_xAggregateSet->setPropertyValue(PROPERTY_CURRSYM_POSITION, makeAny(bPrependCurrencySymbol));
}
}
catch(Exception&)
{
DBG_ERROR( "OCurrencyModel::implConstruct: caught an exception while initializing the aggregate!" );
}
}
}
//------------------------------------------------------------------
DBG_NAME( OCurrencyModel )
//------------------------------------------------------------------
OCurrencyModel::OCurrencyModel(const Reference<XMultiServiceFactory>& _rxFactory)
:OEditBaseModel( _rxFactory, VCL_CONTROLMODEL_CURRENCYFIELD, FRM_SUN_CONTROL_CURRENCYFIELD, sal_False, sal_True )
// use the old control name for compytibility reasons
{
DBG_CTOR( OCurrencyModel, NULL );
m_nClassId = FormComponentType::CURRENCYFIELD;
initValueProperty( PROPERTY_VALUE, PROPERTY_ID_VALUE );
implConstruct();
}
//------------------------------------------------------------------
OCurrencyModel::OCurrencyModel( const OCurrencyModel* _pOriginal, const Reference<XMultiServiceFactory>& _rxFactory )
:OEditBaseModel( _pOriginal, _rxFactory )
{
DBG_CTOR( OCurrencyModel, NULL );
implConstruct();
}
//------------------------------------------------------------------
OCurrencyModel::~OCurrencyModel()
{
DBG_DTOR( OCurrencyModel, NULL );
}
// XCloneable
//------------------------------------------------------------------------------
IMPLEMENT_DEFAULT_CLONING( OCurrencyModel )
// XServiceInfo
//------------------------------------------------------------------------------
StringSequence SAL_CALL OCurrencyModel::getSupportedServiceNames() throw()
{
StringSequence aSupported = OBoundControlModel::getSupportedServiceNames();
sal_Int32 nOldLen = aSupported.getLength();
aSupported.realloc( nOldLen + 4 );
::rtl::OUString* pStoreTo = aSupported.getArray() + nOldLen;
*pStoreTo++ = DATA_AWARE_CONTROL_MODEL;
*pStoreTo++ = VALIDATABLE_CONTROL_MODEL;
*pStoreTo++ = FRM_SUN_COMPONENT_CURRENCYFIELD;
*pStoreTo++ = FRM_SUN_COMPONENT_DATABASE_CURRENCYFIELD;
return aSupported;
}
//------------------------------------------------------------------------------
Reference<XPropertySetInfo> SAL_CALL OCurrencyModel::getPropertySetInfo() throw( RuntimeException )
{
Reference<XPropertySetInfo> xInfo( createPropertySetInfo( getInfoHelper() ) );
return xInfo;
}
//------------------------------------------------------------------------------
void OCurrencyModel::fillProperties(
Sequence< Property >& _rProps,
Sequence< Property >& _rAggregateProps ) const
{
BEGIN_DESCRIBE_PROPERTIES( 2, OEditBaseModel )
// Value auf transient setzen
// ModifyPropertyAttributes(_rAggregateProps, PROPERTY_VALUE, PropertyAttribute::TRANSIENT, 0);
DECL_PROP3(DEFAULT_VALUE, double, BOUND, MAYBEDEFAULT, MAYBEVOID);
DECL_PROP1(TABINDEX, sal_Int16, BOUND);
END_DESCRIBE_PROPERTIES();
}
//------------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& OCurrencyModel::getInfoHelper()
{
return *const_cast<OCurrencyModel*>(this)->getArrayHelper();
}
//------------------------------------------------------------------------------
::rtl::OUString SAL_CALL OCurrencyModel::getServiceName() throw ( ::com::sun::star::uno::RuntimeException)
{
return FRM_COMPONENT_CURRENCYFIELD; // old (non-sun) name for compatibility !
}
//------------------------------------------------------------------------------
sal_Bool OCurrencyModel::commitControlValueToDbColumn( bool /*_bPostReset*/ )
{
Any aControlValue( m_xAggregateFastSet->getFastPropertyValue( getValuePropertyAggHandle() ) );
if ( !compare( aControlValue, m_aSaveValue ) )
{
if ( aControlValue.getValueType().getTypeClass() == TypeClass_VOID )
m_xColumnUpdate->updateNull();
else
{
try
{
m_xColumnUpdate->updateDouble( getDouble( aControlValue ) );
}
catch(Exception&)
{
return sal_False;
}
}
m_aSaveValue = aControlValue;
}
return sal_True;
}
//------------------------------------------------------------------------------
Any OCurrencyModel::translateDbColumnToControlValue()
{
m_aSaveValue <<= m_xColumn->getDouble();
if ( m_xColumn->wasNull() )
m_aSaveValue.clear();
return m_aSaveValue;
}
// XReset
//------------------------------------------------------------------------------
Any OCurrencyModel::getDefaultForReset() const
{
Any aValue;
if ( m_aDefault.getValueType().getTypeClass() == TypeClass_DOUBLE )
aValue = m_aDefault;
return aValue;
}
//.........................................................................
} // namespace frm
//.........................................................................
<commit_msg>INTEGRATION: CWS pchfix02 (1.14.26); FILE MERGED 2006/09/01 17:27:33 kaib 1.14.26.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: Currency.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: obo $ $Date: 2006-09-16 23:47:46 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_forms.hxx"
#ifndef _FORMS_CURRENCY_HXX_
#include "Currency.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _UNOTOOLS_LOCALEDATAWRAPPER_HXX
#include <unotools/localedatawrapper.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_SYSLOCALE_HXX
#include <svtools/syslocale.hxx>
#endif
//.........................................................................
namespace frm
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::form;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::util;
//==================================================================
// OCurrencyControl
//==================================================================
//------------------------------------------------------------------
OCurrencyControl::OCurrencyControl(const Reference<XMultiServiceFactory>& _rxFactory)
:OBoundControl(_rxFactory, VCL_CONTROL_CURRENCYFIELD)
{
}
//------------------------------------------------------------------
InterfaceRef SAL_CALL OCurrencyControl_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory)
{
return *(new OCurrencyControl(_rxFactory));
}
//------------------------------------------------------------------------------
Sequence<Type> OCurrencyControl::_getTypes()
{
return OBoundControl::_getTypes();
}
//------------------------------------------------------------------------------
StringSequence SAL_CALL OCurrencyControl::getSupportedServiceNames() throw()
{
StringSequence aSupported = OBoundControl::getSupportedServiceNames();
aSupported.realloc(aSupported.getLength() + 1);
::rtl::OUString*pArray = aSupported.getArray();
pArray[aSupported.getLength()-1] = FRM_SUN_CONTROL_CURRENCYFIELD;
return aSupported;
}
//==================================================================
// OCurrencyModel
//==================================================================
//------------------------------------------------------------------
InterfaceRef SAL_CALL OCurrencyModel_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory)
{
return *(new OCurrencyModel(_rxFactory));
}
//------------------------------------------------------------------------------
Sequence<Type> OCurrencyModel::_getTypes()
{
return OEditBaseModel::_getTypes();
}
//------------------------------------------------------------------
void OCurrencyModel::implConstruct()
{
if (m_xAggregateSet.is())
{
try
{
// get the system international informations
const LocaleDataWrapper& aLocaleInfo = SvtSysLocale().GetLocaleData();
::rtl::OUString sCurrencySymbol;
sal_Bool bPrependCurrencySymbol;
switch ( aLocaleInfo.getCurrPositiveFormat() )
{
case 0: // $1
sCurrencySymbol = String(aLocaleInfo.getCurrSymbol());
bPrependCurrencySymbol = sal_True;
break;
case 1: // 1$
sCurrencySymbol = String(aLocaleInfo.getCurrSymbol());
bPrependCurrencySymbol = sal_False;
break;
case 2: // $ 1
sCurrencySymbol = ::rtl::OUString(String(aLocaleInfo.getCurrSymbol())) + ::rtl::OUString::createFromAscii(" ");
bPrependCurrencySymbol = sal_True;
break;
case 3: // 1 $
sCurrencySymbol = ::rtl::OUString::createFromAscii(" ") + ::rtl::OUString(String(aLocaleInfo.getCurrSymbol()));
bPrependCurrencySymbol = sal_False;
break;
}
if (sCurrencySymbol.getLength())
{
m_xAggregateSet->setPropertyValue(PROPERTY_CURRENCYSYMBOL, makeAny(sCurrencySymbol));
m_xAggregateSet->setPropertyValue(PROPERTY_CURRSYM_POSITION, makeAny(bPrependCurrencySymbol));
}
}
catch(Exception&)
{
DBG_ERROR( "OCurrencyModel::implConstruct: caught an exception while initializing the aggregate!" );
}
}
}
//------------------------------------------------------------------
DBG_NAME( OCurrencyModel )
//------------------------------------------------------------------
OCurrencyModel::OCurrencyModel(const Reference<XMultiServiceFactory>& _rxFactory)
:OEditBaseModel( _rxFactory, VCL_CONTROLMODEL_CURRENCYFIELD, FRM_SUN_CONTROL_CURRENCYFIELD, sal_False, sal_True )
// use the old control name for compytibility reasons
{
DBG_CTOR( OCurrencyModel, NULL );
m_nClassId = FormComponentType::CURRENCYFIELD;
initValueProperty( PROPERTY_VALUE, PROPERTY_ID_VALUE );
implConstruct();
}
//------------------------------------------------------------------
OCurrencyModel::OCurrencyModel( const OCurrencyModel* _pOriginal, const Reference<XMultiServiceFactory>& _rxFactory )
:OEditBaseModel( _pOriginal, _rxFactory )
{
DBG_CTOR( OCurrencyModel, NULL );
implConstruct();
}
//------------------------------------------------------------------
OCurrencyModel::~OCurrencyModel()
{
DBG_DTOR( OCurrencyModel, NULL );
}
// XCloneable
//------------------------------------------------------------------------------
IMPLEMENT_DEFAULT_CLONING( OCurrencyModel )
// XServiceInfo
//------------------------------------------------------------------------------
StringSequence SAL_CALL OCurrencyModel::getSupportedServiceNames() throw()
{
StringSequence aSupported = OBoundControlModel::getSupportedServiceNames();
sal_Int32 nOldLen = aSupported.getLength();
aSupported.realloc( nOldLen + 4 );
::rtl::OUString* pStoreTo = aSupported.getArray() + nOldLen;
*pStoreTo++ = DATA_AWARE_CONTROL_MODEL;
*pStoreTo++ = VALIDATABLE_CONTROL_MODEL;
*pStoreTo++ = FRM_SUN_COMPONENT_CURRENCYFIELD;
*pStoreTo++ = FRM_SUN_COMPONENT_DATABASE_CURRENCYFIELD;
return aSupported;
}
//------------------------------------------------------------------------------
Reference<XPropertySetInfo> SAL_CALL OCurrencyModel::getPropertySetInfo() throw( RuntimeException )
{
Reference<XPropertySetInfo> xInfo( createPropertySetInfo( getInfoHelper() ) );
return xInfo;
}
//------------------------------------------------------------------------------
void OCurrencyModel::fillProperties(
Sequence< Property >& _rProps,
Sequence< Property >& _rAggregateProps ) const
{
BEGIN_DESCRIBE_PROPERTIES( 2, OEditBaseModel )
// Value auf transient setzen
// ModifyPropertyAttributes(_rAggregateProps, PROPERTY_VALUE, PropertyAttribute::TRANSIENT, 0);
DECL_PROP3(DEFAULT_VALUE, double, BOUND, MAYBEDEFAULT, MAYBEVOID);
DECL_PROP1(TABINDEX, sal_Int16, BOUND);
END_DESCRIBE_PROPERTIES();
}
//------------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& OCurrencyModel::getInfoHelper()
{
return *const_cast<OCurrencyModel*>(this)->getArrayHelper();
}
//------------------------------------------------------------------------------
::rtl::OUString SAL_CALL OCurrencyModel::getServiceName() throw ( ::com::sun::star::uno::RuntimeException)
{
return FRM_COMPONENT_CURRENCYFIELD; // old (non-sun) name for compatibility !
}
//------------------------------------------------------------------------------
sal_Bool OCurrencyModel::commitControlValueToDbColumn( bool /*_bPostReset*/ )
{
Any aControlValue( m_xAggregateFastSet->getFastPropertyValue( getValuePropertyAggHandle() ) );
if ( !compare( aControlValue, m_aSaveValue ) )
{
if ( aControlValue.getValueType().getTypeClass() == TypeClass_VOID )
m_xColumnUpdate->updateNull();
else
{
try
{
m_xColumnUpdate->updateDouble( getDouble( aControlValue ) );
}
catch(Exception&)
{
return sal_False;
}
}
m_aSaveValue = aControlValue;
}
return sal_True;
}
//------------------------------------------------------------------------------
Any OCurrencyModel::translateDbColumnToControlValue()
{
m_aSaveValue <<= m_xColumn->getDouble();
if ( m_xColumn->wasNull() )
m_aSaveValue.clear();
return m_aSaveValue;
}
// XReset
//------------------------------------------------------------------------------
Any OCurrencyModel::getDefaultForReset() const
{
Any aValue;
if ( m_aDefault.getValueType().getTypeClass() == TypeClass_DOUBLE )
aValue = m_aDefault;
return aValue;
}
//.........................................................................
} // namespace frm
//.........................................................................
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <jobs/jobresult.hxx>
#include <jobs/jobconst.hxx>
#include <threadhelp/readguard.hxx>
#include <threadhelp/writeguard.hxx>
#include <general.h>
#include <services.h>
#include <rtl/ustrbuf.hxx>
#include <vcl/svapp.hxx>
#include <comphelper/sequenceashashmap.hxx>
namespace framework{
/**
@short standard dtor
@descr It does nothing else ...
but it marks this new instance as non valid!
*/
JobResult::JobResult()
: ThreadHelpBase(&Application::GetSolarMutex())
{
// reset the flag mask!
// It will reset the accessible state of this object.
// That can be useful if something will fail here ...
m_eParts = E_NOPART;
}
/**
@short special ctor
@descr It initialize this new instance with a pure job execution result
and analyze it. Doing so, we update our other members.
<p>
It's a list of named values, packed inside this any.
Following protocol is used:
<p>
<ul>
<li>
"SaveArguments" [sequence< css.beans.NamedValue >]
<br>
The returned list of (for this generic implementation unknown!)
properties, will be written directly to the configuration and replace
any old values there. There will no check for changes and we don't
support any mege feature here. They are written only. The job has
to modify this list.
</li>
<li>
"SendDispatchResult" [css.frame.DispatchResultEvent]
<br>
The given event is send to all current registered listener.
But it's not guaranteed. In case no listener are available or
this job isn't part of the dispatch environment (because it was used
by the css..task.XJobExecutor->trigger() implementation) this option
will be ignored.
</li>
<li>
"Deactivate" [boolean]
<br>
The job wish to be disabled. But note: There is no way, to enable it later
again by using this implementation. It can be done by using the configuration
only. (Means to register this job again.)
If a job knows, that there exist some status or result listener, it must use
the options "SendDispatchStatus" and "SendDispatchResult" (see before) too, to
inform it about the deactivation of this service.
</li>
</ul>
@param aResult
the job result
*/
JobResult::JobResult( /*IN*/ const css::uno::Any& aResult )
: ThreadHelpBase(&Application::GetSolarMutex())
, m_bDeactivate(false)
{
// safe the pure result
// May someone need it later ...
m_aPureResult = aResult;
// reset the flag mask!
// It will reset the accessible state of this object.
// That can be useful if something will fail here ...
m_eParts = E_NOPART;
// analyze the result and update our other members
::comphelper::SequenceAsHashMap aProtocol(aResult);
if ( aProtocol.empty() )
return;
::comphelper::SequenceAsHashMap::const_iterator pIt = aProtocol.find(JobConst::ANSWER_DEACTIVATE_JOB());
if (pIt != aProtocol.end())
{
pIt->second >>= m_bDeactivate;
if (m_bDeactivate)
m_eParts |= E_DEACTIVATE;
}
pIt = aProtocol.find(JobConst::ANSWER_SAVE_ARGUMENTS());
if (pIt != aProtocol.end())
{
pIt->second >>= m_lArguments;
if (m_lArguments.getLength() > 0)
m_eParts |= E_ARGUMENTS;
}
pIt = aProtocol.find(JobConst::ANSWER_SEND_DISPATCHRESULT());
if (pIt != aProtocol.end())
{
if (pIt->second >>= m_aDispatchResult)
m_eParts |= E_DISPATCHRESULT;
}
}
/**
@short copy dtor
@descr -
*/
JobResult::JobResult( const JobResult& rCopy )
: ThreadHelpBase(&Application::GetSolarMutex())
{
m_aPureResult = rCopy.m_aPureResult ;
m_eParts = rCopy.m_eParts ;
m_lArguments = rCopy.m_lArguments ;
m_bDeactivate = rCopy.m_bDeactivate ;
m_aDispatchResult = rCopy.m_aDispatchResult ;
}
/**
@short standard dtor
@descr Free all internally used resources at the end of living.
*/
JobResult::~JobResult()
{
// Nothing really to do here.
}
/**
@short =operator
@descr Must be implemented to overwrite this instance with another one.
@param rCopy
reference to the other instance, which should be used for copying.
*/
void JobResult::operator=( const JobResult& rCopy )
{
/* SAFE { */
WriteGuard aWriteLock(m_aLock);
m_aPureResult = rCopy.m_aPureResult ;
m_eParts = rCopy.m_eParts ;
m_lArguments = rCopy.m_lArguments ;
m_bDeactivate = rCopy.m_bDeactivate ;
m_aDispatchResult = rCopy.m_aDispatchResult ;
aWriteLock.unlock();
/* } SAFE */
}
/**
@short checks for existing parts of the analyzed result
@descr The internal flag mask was set after analyzing of the pure result.
An user of us can check here, if the required part was really part
of this result. Otherwhise it would use invalid information ...
by using our other members!
@param eParts
a flag mask too, which will be compared with our internally set one.
@return We return true only, if any set flag of the given mask match.
*/
sal_Bool JobResult::existPart( sal_uInt32 eParts ) const
{
/* SAFE { */
ReadGuard aReadLock(m_aLock);
return ((m_eParts & eParts) == eParts);
/* } SAFE */
}
/**
@short provides access to our internal members
@descr The return value will be valid only in case a call of
existPart(E_...) before returned true!
@return It returns the state of the internal member
without any checks!
*/
css::uno::Sequence< css::beans::NamedValue > JobResult::getArguments() const
{
/* SAFE { */
ReadGuard aReadLock(m_aLock);
return m_lArguments;
/* } SAFE */
}
css::frame::DispatchResultEvent JobResult::getDispatchResult() const
{
/* SAFE { */
ReadGuard aReadLock(m_aLock);
return m_aDispatchResult;
/* } SAFE */
}
} // namespace framework
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#707878 Uninitialized scalar field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <jobs/jobresult.hxx>
#include <jobs/jobconst.hxx>
#include <threadhelp/readguard.hxx>
#include <threadhelp/writeguard.hxx>
#include <general.h>
#include <services.h>
#include <rtl/ustrbuf.hxx>
#include <vcl/svapp.hxx>
#include <comphelper/sequenceashashmap.hxx>
namespace framework{
/**
@short standard dtor
@descr It does nothing else ...
but it marks this new instance as non valid!
*/
JobResult::JobResult()
: ThreadHelpBase(&Application::GetSolarMutex())
, m_bDeactivate(false)
{
// reset the flag mask!
// It will reset the accessible state of this object.
// That can be useful if something will fail here ...
m_eParts = E_NOPART;
}
/**
@short special ctor
@descr It initialize this new instance with a pure job execution result
and analyze it. Doing so, we update our other members.
<p>
It's a list of named values, packed inside this any.
Following protocol is used:
<p>
<ul>
<li>
"SaveArguments" [sequence< css.beans.NamedValue >]
<br>
The returned list of (for this generic implementation unknown!)
properties, will be written directly to the configuration and replace
any old values there. There will no check for changes and we don't
support any mege feature here. They are written only. The job has
to modify this list.
</li>
<li>
"SendDispatchResult" [css.frame.DispatchResultEvent]
<br>
The given event is send to all current registered listener.
But it's not guaranteed. In case no listener are available or
this job isn't part of the dispatch environment (because it was used
by the css..task.XJobExecutor->trigger() implementation) this option
will be ignored.
</li>
<li>
"Deactivate" [boolean]
<br>
The job wish to be disabled. But note: There is no way, to enable it later
again by using this implementation. It can be done by using the configuration
only. (Means to register this job again.)
If a job knows, that there exist some status or result listener, it must use
the options "SendDispatchStatus" and "SendDispatchResult" (see before) too, to
inform it about the deactivation of this service.
</li>
</ul>
@param aResult
the job result
*/
JobResult::JobResult( /*IN*/ const css::uno::Any& aResult )
: ThreadHelpBase(&Application::GetSolarMutex())
, m_bDeactivate(false)
{
// safe the pure result
// May someone need it later ...
m_aPureResult = aResult;
// reset the flag mask!
// It will reset the accessible state of this object.
// That can be useful if something will fail here ...
m_eParts = E_NOPART;
// analyze the result and update our other members
::comphelper::SequenceAsHashMap aProtocol(aResult);
if ( aProtocol.empty() )
return;
::comphelper::SequenceAsHashMap::const_iterator pIt = aProtocol.find(JobConst::ANSWER_DEACTIVATE_JOB());
if (pIt != aProtocol.end())
{
pIt->second >>= m_bDeactivate;
if (m_bDeactivate)
m_eParts |= E_DEACTIVATE;
}
pIt = aProtocol.find(JobConst::ANSWER_SAVE_ARGUMENTS());
if (pIt != aProtocol.end())
{
pIt->second >>= m_lArguments;
if (m_lArguments.getLength() > 0)
m_eParts |= E_ARGUMENTS;
}
pIt = aProtocol.find(JobConst::ANSWER_SEND_DISPATCHRESULT());
if (pIt != aProtocol.end())
{
if (pIt->second >>= m_aDispatchResult)
m_eParts |= E_DISPATCHRESULT;
}
}
/**
@short copy dtor
@descr -
*/
JobResult::JobResult( const JobResult& rCopy )
: ThreadHelpBase(&Application::GetSolarMutex())
{
m_aPureResult = rCopy.m_aPureResult ;
m_eParts = rCopy.m_eParts ;
m_lArguments = rCopy.m_lArguments ;
m_bDeactivate = rCopy.m_bDeactivate ;
m_aDispatchResult = rCopy.m_aDispatchResult ;
}
/**
@short standard dtor
@descr Free all internally used resources at the end of living.
*/
JobResult::~JobResult()
{
// Nothing really to do here.
}
/**
@short =operator
@descr Must be implemented to overwrite this instance with another one.
@param rCopy
reference to the other instance, which should be used for copying.
*/
void JobResult::operator=( const JobResult& rCopy )
{
/* SAFE { */
WriteGuard aWriteLock(m_aLock);
m_aPureResult = rCopy.m_aPureResult ;
m_eParts = rCopy.m_eParts ;
m_lArguments = rCopy.m_lArguments ;
m_bDeactivate = rCopy.m_bDeactivate ;
m_aDispatchResult = rCopy.m_aDispatchResult ;
aWriteLock.unlock();
/* } SAFE */
}
/**
@short checks for existing parts of the analyzed result
@descr The internal flag mask was set after analyzing of the pure result.
An user of us can check here, if the required part was really part
of this result. Otherwhise it would use invalid information ...
by using our other members!
@param eParts
a flag mask too, which will be compared with our internally set one.
@return We return true only, if any set flag of the given mask match.
*/
sal_Bool JobResult::existPart( sal_uInt32 eParts ) const
{
/* SAFE { */
ReadGuard aReadLock(m_aLock);
return ((m_eParts & eParts) == eParts);
/* } SAFE */
}
/**
@short provides access to our internal members
@descr The return value will be valid only in case a call of
existPart(E_...) before returned true!
@return It returns the state of the internal member
without any checks!
*/
css::uno::Sequence< css::beans::NamedValue > JobResult::getArguments() const
{
/* SAFE { */
ReadGuard aReadLock(m_aLock);
return m_lArguments;
/* } SAFE */
}
css::frame::DispatchResultEvent JobResult::getDispatchResult() const
{
/* SAFE { */
ReadGuard aReadLock(m_aLock);
return m_aDispatchResult;
/* } SAFE */
}
} // namespace framework
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>#include <stingray/toolkit/Factory.h>
#include <stingray/toolkit/any.h>
#include <stingray/app/PushVideoOnDemand.h>
#include <stingray/app/application_context/AppChannel.h>
#include <stingray/app/application_context/ChannelList.h>
#include <stingray/app/scheduler/ScheduledEvents.h>
#include <stingray/app/tests/AutoFilter.h>
#include <stingray/app/zapper/User.h>
#include <stingray/ca/BasicSubscription.h>
#include <stingray/hdmi/IHDMI.h>
#include <stingray/media/ImageFileMediaData.h>
#include <stingray/media/MediaInfoBase.h>
#include <stingray/media/Mp3MediaInfo.h>
#include <stingray/media/formats/flv/MediaInfo.h>
#include <stingray/media/formats/mp4/MediaInfo.h>
#include <stingray/media/formats/mp4/Stream.h>
#include <stingray/media/formats/mp4/StreamDescriptors.h>
#include <stingray/mpeg/Stream.h>
#include <stingray/net/DHCPInterfaceConfiguration.h>
#include <stingray/net/IgnoredInterfaceConfiguration.h>
#include <stingray/net/LinkLocalInterfaceConfiguration.h>
#include <stingray/net/ManualInterfaceConfiguration.h>
#include <stingray/parentalcontrol/AgeRating.h>
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#include <stingray/records/FileSystemRecord.h>
#include <stingray/rpc/UrlObjectId.h>
#include <stingray/scanner/DVBServiceId.h>
#include <stingray/scanner/DefaultDVBTBandInfo.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegStreamDescriptor.h>
#include <stingray/scanner/DefaultScanParams.h>
#include <stingray/scanner/DreCasGeographicRegion.h>
#include <stingray/scanner/IServiceId.h>
#include <stingray/scanner/LybidScanParams.h>
#include <stingray/scanner/TricolorGeographicRegion.h>
#include <stingray/scanner/TricolorScanParams.h>
#include <stingray/scanner/lybid/LybidServiceMetaInfo.h>
#include <stingray/scanner/tricolor/TricolorServiceMetaInfo.h>
#include <stingray/streams/PlaybackStreamContent.h>
#include <stingray/streams/RecordStreamContent.h>
#include <stingray/streams/RecordStreamMetaInfo.h>
#include <stingray/tuners/TunerState.h>
#include <stingray/tuners/dvbs/Antenna.h>
#include <stingray/tuners/dvbs/DefaultDVBSTransport.h>
#include <stingray/tuners/dvbs/Satellite.h>
#include <stingray/tuners/dvbt/DVBTTransport.h>
#include <stingray/tuners/ip/TsOverIpTransport.h>
#include <stingray/update/DefaultUpdateRequirement.h>
#include <stingray/update/system/CheckImageSignature.h>
#include <stingray/update/system/EraseFlashPartition.h>
#include <stingray/update/system/WriteFlashPartition.h>
/* WARNING! This is autogenerated file, DO NOT EDIT! */
namespace stingray { namespace Detail
{
void Factory::RegisterTypes()
{
#ifdef BUILD_SHARED_LIB
/*nothing*/
#else
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PVODVideoInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(::stingray::Detail::any::ObjectHolder<stingray::app::AppChannelPtr>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::CinemaHallScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AutoFilter);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::User);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscriptionProvider);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(InMemoryImageMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MediaInfoBase);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Mp3MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(flv::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaAudioStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaVideoStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DHCPInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(IgnoredInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LinkLocalInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ManualInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating);
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::StreamDescriptor);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel);
#endif
TOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(rpc::UrlObjectId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTBandInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegDataCarouselStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DreCasGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(::stingray::Detail::any::ObjectHolder<stingray::ServiceId>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(PlaybackStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CircuitedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(UnlockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TsOverIpTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMinimalVersionRequirement);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CheckImageSignature);
TOOLKIT_REGISTER_CLASS_EXPLICIT(EraseFlashPartition);
TOOLKIT_REGISTER_CLASS_EXPLICIT(WriteFlashPartition);
#endif
}
}}
<commit_msg>Added serialization and factory object stubs to ICipherKeys<commit_after>#include <stingray/toolkit/Factory.h>
#include <stingray/toolkit/any.h>
#include <stingray/app/PushVideoOnDemand.h>
#include <stingray/app/application_context/AppChannel.h>
#include <stingray/app/application_context/ChannelList.h>
#include <stingray/app/scheduler/ScheduledEvents.h>
#include <stingray/app/tests/AutoFilter.h>
#include <stingray/app/zapper/User.h>
#include <stingray/ca/BasicSubscription.h>
#include <stingray/crypto/HdcpKey.h>
#include <stingray/crypto/SymmetricKey.h>
#include <stingray/hdmi/IHDMI.h>
#include <stingray/media/ImageFileMediaData.h>
#include <stingray/media/MediaInfoBase.h>
#include <stingray/media/Mp3MediaInfo.h>
#include <stingray/media/formats/flv/MediaInfo.h>
#include <stingray/media/formats/mp4/MediaInfo.h>
#include <stingray/media/formats/mp4/Stream.h>
#include <stingray/media/formats/mp4/StreamDescriptors.h>
#include <stingray/mpeg/Stream.h>
#include <stingray/net/DHCPInterfaceConfiguration.h>
#include <stingray/net/IgnoredInterfaceConfiguration.h>
#include <stingray/net/LinkLocalInterfaceConfiguration.h>
#include <stingray/net/ManualInterfaceConfiguration.h>
#include <stingray/parentalcontrol/AgeRating.h>
#ifdef PLATFORM_EMU
# include <stingray/platform/emu/scanner/Channel.h>
#endif
#ifdef PLATFORM_MSTAR
# include <stingray/platform/mstar/crypto/HardwareCipherKey.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/Certificate.h>
#endif
#ifdef PLATFORM_OPENSSL
# include <stingray/platform/openssl/crypto/EvpKey.h>
#endif
#include <stingray/records/FileSystemRecord.h>
#include <stingray/rpc/UrlObjectId.h>
#include <stingray/scanner/DVBServiceId.h>
#include <stingray/scanner/DefaultDVBTBandInfo.h>
#include <stingray/scanner/DefaultMpegService.h>
#include <stingray/scanner/DefaultMpegStreamDescriptor.h>
#include <stingray/scanner/DefaultScanParams.h>
#include <stingray/scanner/DreCasGeographicRegion.h>
#include <stingray/scanner/IServiceId.h>
#include <stingray/scanner/LybidScanParams.h>
#include <stingray/scanner/TricolorGeographicRegion.h>
#include <stingray/scanner/TricolorScanParams.h>
#include <stingray/scanner/lybid/LybidServiceMetaInfo.h>
#include <stingray/scanner/tricolor/TricolorServiceMetaInfo.h>
#include <stingray/streams/PlaybackStreamContent.h>
#include <stingray/streams/RecordStreamContent.h>
#include <stingray/streams/RecordStreamMetaInfo.h>
#include <stingray/tuners/TunerState.h>
#include <stingray/tuners/dvbs/Antenna.h>
#include <stingray/tuners/dvbs/DefaultDVBSTransport.h>
#include <stingray/tuners/dvbs/Satellite.h>
#include <stingray/tuners/dvbt/DVBTTransport.h>
#include <stingray/tuners/ip/TsOverIpTransport.h>
#include <stingray/update/DefaultUpdateRequirement.h>
#include <stingray/update/system/CheckImageSignature.h>
#include <stingray/update/system/EraseFlashPartition.h>
#include <stingray/update/system/WriteFlashPartition.h>
/* WARNING! This is autogenerated file, DO NOT EDIT! */
namespace stingray { namespace Detail
{
void Factory::RegisterTypes()
{
#ifdef BUILD_SHARED_LIB
/*nothing*/
#else
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::PVODVideoInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(::stingray::Detail::any::ObjectHolder<stingray::app::AppChannelPtr>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::CinemaHallScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::AutoFilter);
TOOLKIT_REGISTER_CLASS_EXPLICIT(app::User);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscription);
TOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscriptionProvider);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HdcpKey);
TOOLKIT_REGISTER_CLASS_EXPLICIT(SymmetricKey);
TOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(InMemoryImageMediaPreview);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MediaInfoBase);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Mp3MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(flv::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::MediaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaAudioStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaVideoStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DHCPInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(IgnoredInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LinkLocalInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(ManualInterfaceConfiguration);
TOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating);
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::StreamDescriptor);
#endif
#ifdef PLATFORM_EMU
TOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel);
#endif
#ifdef PLATFORM_MSTAR
TOOLKIT_REGISTER_CLASS_EXPLICIT(mstar::HardwareCipherKey);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::Certificate);
#endif
#ifdef PLATFORM_OPENSSL
TOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::EvpKey);
#endif
TOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord);
TOOLKIT_REGISTER_CLASS_EXPLICIT(rpc::UrlObjectId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTBandInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegDataCarouselStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoStreamDescriptor);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DreCasGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(::stingray::Detail::any::ObjectHolder<stingray::ServiceId>);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorGeographicRegion);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanParams);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LybidServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorServiceMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(PlaybackStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamContent);
TOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CircuitedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(LockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(UnlockedTunerState);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(TsOverIpTransport);
TOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMinimalVersionRequirement);
TOOLKIT_REGISTER_CLASS_EXPLICIT(CheckImageSignature);
TOOLKIT_REGISTER_CLASS_EXPLICIT(EraseFlashPartition);
TOOLKIT_REGISTER_CLASS_EXPLICIT(WriteFlashPartition);
#endif
}
}}
<|endoftext|>
|
<commit_before>/***************************************************************************
knarticlewindow.cpp - description
-------------------
copyright : (C) 2000 by Christian Thurner
email : cthurner@freepage.de
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include <kstdaction.h>
#include <klocale.h>
#include <kedittoolbar.h>
#include <kkeydialog.h>
#include <khtml_part.h>
#include "kngroup.h"
#include "knsavedarticle.h"
#include "knfetcharticle.h"
#include "knarticlewidget.h"
#include "knsavedarticlemanager.h"
#include "utilities.h"
#include "knglobals.h"
#include "knode.h"
#include "knarticlewindow.h"
KNArticleWindow::KNArticleWindow(KNArticle *art, KNArticleCollection *col, const char *name )
: KMainWindow(0, name)
{
if(art)
setCaption(art->subject());
//setIcon(UserIcon("posting"));
artW=new KNArticleWidget(this);
artW->setData(art, col);
setCentralWidget(artW);
connect(artW, SIGNAL(articleLoaded()), SLOT(slotArticleLoaded()));
*actionCollection() += artW->actions(); // include the actions of the article widget
// file menu
KStdAction::close(this, SLOT(slotFileClose()),actionCollection());
// article menu
actPostReply = new KAction(i18n("Post &reply"),"reply", Key_R , this, SLOT(slotArtReply()),
actionCollection(), "article_postReply");
actPostReply->setEnabled(false);
actMailReply = new KAction(i18n("&Mail reply"),"remail", Key_A , this, SLOT(slotArtRemail()),
actionCollection(), "article_mailReply");
actMailReply->setEnabled(false);
actForward = new KAction(i18n("&Forward"),"fwd", Key_F , this, SLOT(slotArtForward()),
actionCollection(), "article_forward");
actForward->setEnabled(false);
actCancel = new KAction(i18n("article","&Cancel"), 0 , this, SLOT(slotArtCancel()),
actionCollection(), "article_cancel");
actCancel->setEnabled(false);
actSupersede = new KAction(i18n("&Supersede"), 0 , this, SLOT(slotArtSupersede()),
actionCollection(), "article_supersede");
actSupersede->setEnabled(false);
// settings menu
KStdAction::showToolbar(this, SLOT(slotToggleToolBar()), actionCollection());
KStdAction::keyBindings(this, SLOT(slotConfKeys()), actionCollection());
KStdAction::configureToolbars(this, SLOT(slotConfToolbar()), actionCollection());
KStdAction::preferences(knGlobals.top, SLOT(slotSettings()), actionCollection());
createGUI("knreaderui.rc");
restoreWindowSize("reader", this, QSize(500,400));
}
KNArticleWindow::~KNArticleWindow()
{
saveWindowSize("reader", size());
}
void KNArticleWindow::slotArticleLoaded()
{
actPostReply->setEnabled(true);
actMailReply->setEnabled(true);
actForward->setEnabled(true);
actCancel->setEnabled(true);
actSupersede->setEnabled(true);
}
void KNArticleWindow::slotFileClose()
{
close();
}
void KNArticleWindow::slotArtReply()
{
knGlobals.sArtManager->reply(artW->article(),static_cast<KNGroup*>(artW->collection()));
}
void KNArticleWindow::slotArtRemail()
{
knGlobals.sArtManager->reply(artW->article(), 0);
}
void KNArticleWindow::slotArtForward()
{
knGlobals.sArtManager->forward(artW->article());
}
void KNArticleWindow::slotArtCancel()
{
knGlobals.sArtManager->cancel(static_cast<KNFetchArticle*>(artW->article()),static_cast<KNGroup*>(artW->collection()));
}
void KNArticleWindow::slotArtSupersede()
{
knGlobals.sArtManager->supersede(static_cast<KNFetchArticle*>(artW->article()),static_cast<KNGroup*>(artW->collection()));
}
void KNArticleWindow::slotToggleToolBar()
{
if(toolBar("mainToolBar")->isVisible())
toolBar("mainToolBar")->hide();
else
toolBar("mainToolBar")->show();
}
void KNArticleWindow::slotConfKeys()
{
KKeyDialog::configureKeys(actionCollection(), xmlFile(), true, this);
}
void KNArticleWindow::slotConfToolbar()
{
KEditToolbar *dlg = new KEditToolbar(guiFactory(),this);
if (dlg->exec()) {
//guiFactory()->removeClient(artW->part());
createGUI("knreaderui.rc",false);
//guiFactory()->addClient(artW->part());
conserveMemory();
}
delete dlg;
}
//--------------------------------
#include "knarticlewindow.moc"
<commit_msg>new icons here, too.<commit_after>/***************************************************************************
knarticlewindow.cpp - description
-------------------
copyright : (C) 2000 by Christian Thurner
email : cthurner@freepage.de
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include <kstdaction.h>
#include <klocale.h>
#include <kedittoolbar.h>
#include <kkeydialog.h>
#include <khtml_part.h>
#include "kngroup.h"
#include "knsavedarticle.h"
#include "knfetcharticle.h"
#include "knarticlewidget.h"
#include "knsavedarticlemanager.h"
#include "utilities.h"
#include "knglobals.h"
#include "knode.h"
#include "knarticlewindow.h"
KNArticleWindow::KNArticleWindow(KNArticle *art, KNArticleCollection *col, const char *name )
: KMainWindow(0, name)
{
if(art)
setCaption(art->subject());
//setIcon(UserIcon("posting"));
artW=new KNArticleWidget(this);
artW->setData(art, col);
setCentralWidget(artW);
connect(artW, SIGNAL(articleLoaded()), SLOT(slotArticleLoaded()));
*actionCollection() += artW->actions(); // include the actions of the article widget
// file menu
KStdAction::close(this, SLOT(slotFileClose()),actionCollection());
// article menu
actPostReply = new KAction(i18n("Post &reply"),"reply", Key_R , this, SLOT(slotArtReply()),
actionCollection(), "article_postReply");
actPostReply->setEnabled(false);
actMailReply = new KAction(i18n("&Mail reply"),"mail_reply", Key_A , this, SLOT(slotArtRemail()),
actionCollection(), "article_mailReply");
actMailReply->setEnabled(false);
actForward = new KAction(i18n("&Forward"), "mail_forward", Key_F , this, SLOT(slotArtForward()),
actionCollection(), "article_forward");
actForward->setEnabled(false);
actCancel = new KAction(i18n("article","&Cancel"), 0 , this, SLOT(slotArtCancel()),
actionCollection(), "article_cancel");
actCancel->setEnabled(false);
actSupersede = new KAction(i18n("&Supersede"), 0 , this, SLOT(slotArtSupersede()),
actionCollection(), "article_supersede");
actSupersede->setEnabled(false);
// settings menu
KStdAction::showToolbar(this, SLOT(slotToggleToolBar()), actionCollection());
KStdAction::keyBindings(this, SLOT(slotConfKeys()), actionCollection());
KStdAction::configureToolbars(this, SLOT(slotConfToolbar()), actionCollection());
KStdAction::preferences(knGlobals.top, SLOT(slotSettings()), actionCollection());
createGUI("knreaderui.rc");
restoreWindowSize("reader", this, QSize(500,400));
}
KNArticleWindow::~KNArticleWindow()
{
saveWindowSize("reader", size());
}
void KNArticleWindow::slotArticleLoaded()
{
actPostReply->setEnabled(true);
actMailReply->setEnabled(true);
actForward->setEnabled(true);
actCancel->setEnabled(true);
actSupersede->setEnabled(true);
}
void KNArticleWindow::slotFileClose()
{
close();
}
void KNArticleWindow::slotArtReply()
{
knGlobals.sArtManager->reply(artW->article(),static_cast<KNGroup*>(artW->collection()));
}
void KNArticleWindow::slotArtRemail()
{
knGlobals.sArtManager->reply(artW->article(), 0);
}
void KNArticleWindow::slotArtForward()
{
knGlobals.sArtManager->forward(artW->article());
}
void KNArticleWindow::slotArtCancel()
{
knGlobals.sArtManager->cancel(static_cast<KNFetchArticle*>(artW->article()),static_cast<KNGroup*>(artW->collection()));
}
void KNArticleWindow::slotArtSupersede()
{
knGlobals.sArtManager->supersede(static_cast<KNFetchArticle*>(artW->article()),static_cast<KNGroup*>(artW->collection()));
}
void KNArticleWindow::slotToggleToolBar()
{
if(toolBar("mainToolBar")->isVisible())
toolBar("mainToolBar")->hide();
else
toolBar("mainToolBar")->show();
}
void KNArticleWindow::slotConfKeys()
{
KKeyDialog::configureKeys(actionCollection(), xmlFile(), true, this);
}
void KNArticleWindow::slotConfToolbar()
{
KEditToolbar *dlg = new KEditToolbar(guiFactory(),this);
if (dlg->exec()) {
//guiFactory()->removeClient(artW->part());
createGUI("knreaderui.rc",false);
//guiFactory()->addClient(artW->part());
conserveMemory();
}
delete dlg;
}
//--------------------------------
#include "knarticlewindow.moc"
<|endoftext|>
|
<commit_before>AliAnalysisTaskCFTree *AddTaskCFTree(
Int_t analysisMode = 0,
UInt_t selectionBit = AliVEvent::kMB,
Double_t zVtxMax = 10,
Double_t etaMax = 1,
Double_t ptMin = 0.15,
const char* outputFileName = 0,
const char* folderName = "CorrelationTree")
{
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskPhiCorrelations", "No analysis manager to connect to.");
return NULL;
}
AliAnalysisTaskCFTree* ana = new AliAnalysisTaskCFTree();
ana->SetMode(analysisMode);
ana->SetEventSelectionBit(AliVEvent::kMB);
ana->SetZVertex(zVtxMax);
ana->SetTrackEtaCut(etaMax);
ana->SetPtMin(ptMin);
mgr->AddTask(ana);
if (!outputFileName) outputFileName = AliAnalysisManager::GetCommonFileName();
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("histos", TList::Class(),AliAnalysisManager::kOutputContainer,Form("%s:%s", outputFileName, folderName));
AliAnalysisDataContainer *coutput2 = mgr->CreateContainer("events", TTree::Class(),AliAnalysisManager::kOutputContainer,Form("%s:%s", outputFileName, folderName));
mgr->ConnectInput (ana, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput (ana, 0, coutput1);
mgr->ConnectOutput (ana, 1, coutput2);
return ana;
}
<commit_msg>Modified input parameters<commit_after>AliAnalysisTaskCFTree *AddTaskCFTree(
Int_t analysisMode = 0,
UInt_t selectionBit = AliVEvent::kMB,
Double_t zVtxMax = 10,
Double_t etaMax = 1,
Double_t ptMin = 0.15,
const char* outputFileName = 0,
const char* folderName = "CorrelationTree")
{
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskPhiCorrelations", "No analysis manager to connect to.");
return NULL;
}
AliAnalysisTaskCFTree* ana = new AliAnalysisTaskCFTree();
ana->SetMode(analysisMode);
ana->SetEventSelectionBit(selectionBit);
ana->SetZVertex(zVtxMax);
ana->SetTrackEtaCut(etaMax);
ana->SetPtMin(ptMin);
mgr->AddTask(ana);
if (!outputFileName) outputFileName = AliAnalysisManager::GetCommonFileName();
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("histos", TList::Class(),AliAnalysisManager::kOutputContainer,Form("%s:%s", outputFileName, folderName));
AliAnalysisDataContainer *coutput2 = mgr->CreateContainer("events", TTree::Class(),AliAnalysisManager::kOutputContainer,Form("%s:%s", outputFileName, folderName));
mgr->ConnectInput (ana, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput (ana, 0, coutput1);
mgr->ConnectOutput (ana, 1, coutput2);
return ana;
}
<|endoftext|>
|
<commit_before>// $Id$
//
// Jet model task to merge to existing branches
// only implemented for track branches
//
// Author: M. Verweij
#include "AliJetModelMergeBranches.h"
#include <TClonesArray.h>
#include <TFolder.h>
#include <TLorentzVector.h>
#include <TParticle.h>
#include <TParticlePDG.h>
#include <TRandom3.h>
#include <TProfile.h>
#include "AliAnalysisManager.h"
#include "AliEMCALDigit.h"
#include "AliEMCALGeometry.h"
#include "AliEMCALRecPoint.h"
#include "AliGenerator.h"
#include "AliHeader.h"
#include "AliLog.h"
#include "AliPicoTrack.h"
#include "AliRun.h"
#include "AliRunLoader.h"
#include "AliStack.h"
#include "AliStack.h"
#include "AliVCluster.h"
#include "AliVEvent.h"
ClassImp(AliJetModelMergeBranches)
//________________________________________________________________________
AliJetModelMergeBranches::AliJetModelMergeBranches() :
AliJetModelBaseTask("AliJetModelMergeBranches"),
fTracksMergeName(),
fTracksMerge(0)
{
// Default constructor.
SetSuffix("Merged");
SetCopyArray(kTRUE);
}
//________________________________________________________________________
AliJetModelMergeBranches::AliJetModelMergeBranches(const char *name) :
AliJetModelBaseTask(name),
fTracksMergeName(),
fTracksMerge(0)
{
// Standard constructor.
SetSuffix("Merged");
SetCopyArray(kTRUE);
}
//________________________________________________________________________
AliJetModelMergeBranches::~AliJetModelMergeBranches()
{
// Destructor
}
//________________________________________________________________________
Bool_t AliJetModelMergeBranches::ExecOnce()
{
// Exec only once.
AliJetModelBaseTask::ExecOnce();
if (!fTracksMergeName.IsNull()) {
fTracksMerge = dynamic_cast<TClonesArray*>(InputEvent()->FindListObject(fTracksMergeName));
if (!fTracksMerge) {
AliWarning(Form("%s: Couldn't retrieve tracks with name %s!", GetName(), fTracksMergeName.Data()));
}
else if (!fTracksMerge->GetClass()->GetBaseClass("AliPicoTrack")) {
AliError(Form("%s: Collection %s does not contain AliPicoTrack objects!", GetName(), fTracksMergeName.Data()));
fTracksMerge = 0;
return kFALSE;
}
}
return kTRUE;
}
//________________________________________________________________________
void AliJetModelMergeBranches::Run()
{
// Merge two branches into a new one
CopyTracks();
MergeTracks();
}
//________________________________________________________________________
void AliJetModelMergeBranches::MergeTracks()
{
// Copy all the tracks in the new collection
if (!fTracksMerge)
return;
const Int_t nTracks = fTracksMerge->GetEntriesFast();
Int_t nCopiedTracks = fOutTracks->GetEntriesFast();
for (Int_t i = 0; i < nTracks; ++i) {
AliPicoTrack *picotrack = static_cast<AliPicoTrack*>(fTracksMerge->At(i));
if (!picotrack)
continue;
AliPicoTrack *track = new ((*fOutTracks)[nCopiedTracks]) AliPicoTrack(*picotrack);
if (!fIsMC && track->GetLabel() != 0)
track->SetLabel(0);
nCopiedTracks++;
}
}
<commit_msg>set bit for tracks in 2nd merge branch<commit_after>// $Id$
//
// Jet model task to merge to existing branches
// only implemented for track branches
//
// Author: M. Verweij
#include "AliJetModelMergeBranches.h"
#include <TClonesArray.h>
#include <TFolder.h>
#include <TLorentzVector.h>
#include <TParticle.h>
#include <TParticlePDG.h>
#include <TRandom3.h>
#include <TProfile.h>
#include "AliAnalysisManager.h"
#include "AliEMCALDigit.h"
#include "AliEMCALGeometry.h"
#include "AliEMCALRecPoint.h"
#include "AliGenerator.h"
#include "AliHeader.h"
#include "AliLog.h"
#include "AliPicoTrack.h"
#include "AliRun.h"
#include "AliRunLoader.h"
#include "AliStack.h"
#include "AliStack.h"
#include "AliVCluster.h"
#include "AliVEvent.h"
ClassImp(AliJetModelMergeBranches)
//________________________________________________________________________
AliJetModelMergeBranches::AliJetModelMergeBranches() :
AliJetModelBaseTask("AliJetModelMergeBranches"),
fTracksMergeName(),
fTracksMerge(0)
{
// Default constructor.
SetSuffix("Merged");
SetCopyArray(kTRUE);
}
//________________________________________________________________________
AliJetModelMergeBranches::AliJetModelMergeBranches(const char *name) :
AliJetModelBaseTask(name),
fTracksMergeName(),
fTracksMerge(0)
{
// Standard constructor.
SetSuffix("Merged");
SetCopyArray(kTRUE);
}
//________________________________________________________________________
AliJetModelMergeBranches::~AliJetModelMergeBranches()
{
// Destructor
}
//________________________________________________________________________
Bool_t AliJetModelMergeBranches::ExecOnce()
{
// Exec only once.
AliJetModelBaseTask::ExecOnce();
if (!fTracksMergeName.IsNull()) {
fTracksMerge = dynamic_cast<TClonesArray*>(InputEvent()->FindListObject(fTracksMergeName));
if (!fTracksMerge) {
AliWarning(Form("%s: Couldn't retrieve tracks with name %s!", GetName(), fTracksMergeName.Data()));
}
else if (!fTracksMerge->GetClass()->GetBaseClass("AliPicoTrack")) {
AliError(Form("%s: Collection %s does not contain AliPicoTrack objects!", GetName(), fTracksMergeName.Data()));
fTracksMerge = 0;
return kFALSE;
}
}
return kTRUE;
}
//________________________________________________________________________
void AliJetModelMergeBranches::Run()
{
// Merge two branches into a new one
CopyTracks();
MergeTracks();
}
//________________________________________________________________________
void AliJetModelMergeBranches::MergeTracks()
{
// Copy all the tracks in the new collection
if (!fTracksMerge)
return;
const Int_t nTracks = fTracksMerge->GetEntriesFast();
Int_t nCopiedTracks = fOutTracks->GetEntriesFast();
for (Int_t i = 0; i < nTracks; ++i) {
AliPicoTrack *picotrack = static_cast<AliPicoTrack*>(fTracksMerge->At(i));
if (!picotrack)
continue;
AliPicoTrack *track = new ((*fOutTracks)[nCopiedTracks]) AliPicoTrack(*picotrack);
track->SetBit(TObject::kBitMask,1);
nCopiedTracks++;
}
}
<|endoftext|>
|
<commit_before>/*
* HyPerCol.h
*
* Created on: Jul 30, 2008
* Author: Craig Rasmussen
*/
#ifndef HYPERCOL_HPP_
#define HYPERCOL_HPP_
#include "HyPerColRunDelegate.hpp"
#include "../layers/PVLayer.h"
#include "../connections/HyPerConn.hpp"
#include "../io/PVParams.hpp"
#include "../include/pv_types.h"
#include <time.h>
namespace PV {
class HyPerLayer;
class InterColComm;
class HyPerConn;
class HyPerCol {
public:
HyPerCol(const char* name, int argc, char* argv[]);
virtual ~HyPerCol();
int initFinish(void); // call after all layers/connections have been added
int initializeThreads();
int finalizeThreads();
int run() {return run(numSteps);}
int run(int nTimeSteps);
float advanceTime(float time);
int exitRunLoop(bool exitOnFinish);
int loadState();
int writeState();
int columnId();
// int deliver(PVConnection* conn, PVRect preRegion, int count, float* buf);
int addLayer(HyPerLayer * l);
int addConnection(HyPerConn * conn);
HyPerLayer * getLayer(int which) {return layers[which];}
HyPerConn * getConnection(int which) {return connections[which];}
InterColComm * icCommunicator() {return icComm;}
PVParams * parameters() {return params;}
bool warmStartup() {return warmStart;}
float getDeltaTime() {return deltaTime;}
float simulationTime() {return simTime;}
PVLayerLoc getImageLoc() {return imageLoc;}
int width() {return imageLoc.nxGlobal;}
int height() {return imageLoc.nyGlobal;}
int localWidth() {return imageLoc.nx;}
int localHeight() {return imageLoc.ny;}
int setLayerLoc(PVLayerLoc * layerLoc, float nxScale, float nyScale, int margin, int nf);
const char * inputFile() {return image_file;}
int numberOfTimeSteps() {return numSteps;}
int numberOfColumns();
int numberOfConnections() {return numConnections;}
/** returns the number of border regions, either an actual image border or a neighbor **/
int numberOfBorderRegions() {return MAX_NEIGHBORS;}
int commColumn(int colId);
int commRow(int colId);
int numCommColumns() {return icComm->numCommColumns();}
int numCommRows() {return icComm->numCommRows();}
// a random seed based on column id
unsigned long getRandomSeed()
{return (unsigned long) time((time_t *) NULL) / (1 + columnId());}
void setDelegate(HyPerColRunDelegate * delegate) {runDelegate = delegate;}
private:
int numSteps;
int maxLayers;
int numLayers;
int maxConnections;
int numConnections;
bool warmStart;
bool isInitialized; // true when all initialization has been completed
float simTime; // current time in milliseconds
float deltaTime; // time step interval
HyPerLayer ** layers;
HyPerConn ** connections;
int numThreads;
PVLayer* threadCLayers;
char * name;
char * image_file;
PVLayerLoc imageLoc;
PVParams * params; // manages input parameters
InterColComm * icComm; // manages communication between HyPerColumns};
HyPerColRunDelegate * runDelegate; // runs time loop
}; // class HyPerCol
} // namespace PV
#ifdef OBSOLETE
extern "C" {
void *run1connection(void * arg); // generic prototype suitable for fork() : actually takes a run_struct
void *update1layer(void * arg); // generic prototype suitable for fork() : actually takes a run_struct
}
#endif
#endif /* HYPERCOL_HPP_ */
<commit_msg>Added construction of a CLDevice to run threads.<commit_after>/*
* HyPerCol.h
*
* Created on: Jul 30, 2008
* Author: Craig Rasmussen
*/
#ifndef HYPERCOL_HPP_
#define HYPERCOL_HPP_
#include "HyPerColRunDelegate.hpp"
#include "../layers/PVLayer.h"
#include "../connections/HyPerConn.hpp"
#include "../io/PVParams.hpp"
#include "../include/pv_types.h"
#include <time.h>
#include "../arch/opencl/CLDevice.hpp"
namespace PV {
class HyPerLayer;
class InterColComm;
class HyPerConn;
class HyPerCol {
public:
HyPerCol(const char* name, int argc, char* argv[]);
virtual ~HyPerCol();
int initFinish(void); // call after all layers/connections have been added
int initializeThreads(int device);
int finalizeThreads();
int run() {return run(numSteps);}
int run(int nTimeSteps);
float advanceTime(float time);
int exitRunLoop(bool exitOnFinish);
int loadState();
int writeState();
int columnId();
// int deliver(PVConnection* conn, PVRect preRegion, int count, float* buf);
int addLayer(HyPerLayer * l);
int addConnection(HyPerConn * conn);
HyPerLayer * getLayer(int which) {return layers[which];}
HyPerConn * getConnection(int which) {return connections[which];}
CLDevice * getCLDevice() {return clDevice;}
InterColComm * icCommunicator() {return icComm;}
PVParams * parameters() {return params;}
bool warmStartup() {return warmStart;}
float getDeltaTime() {return deltaTime;}
float simulationTime() {return simTime;}
PVLayerLoc getImageLoc() {return imageLoc;}
int width() {return imageLoc.nxGlobal;}
int height() {return imageLoc.nyGlobal;}
int localWidth() {return imageLoc.nx;}
int localHeight() {return imageLoc.ny;}
int setLayerLoc(PVLayerLoc * layerLoc, float nxScale, float nyScale, int margin, int nf);
const char * inputFile() {return image_file;}
int numberOfTimeSteps() {return numSteps;}
int numberOfColumns();
int numberOfConnections() {return numConnections;}
/** returns the number of border regions, either an actual image border or a neighbor **/
int numberOfBorderRegions() {return MAX_NEIGHBORS;}
int commColumn(int colId);
int commRow(int colId);
int numCommColumns() {return icComm->numCommColumns();}
int numCommRows() {return icComm->numCommRows();}
// a random seed based on column id
unsigned long getRandomSeed()
{return (unsigned long) time((time_t *) NULL) / (1 + columnId());}
void setDelegate(HyPerColRunDelegate * delegate) {runDelegate = delegate;}
private:
int numSteps;
int maxLayers;
int numLayers;
int maxConnections;
int numConnections;
bool warmStart;
bool isInitialized; // true when all initialization has been completed
float simTime; // current time in milliseconds
float deltaTime; // time step interval
CLDevice * clDevice; // object for running kernels on OpenCL device
HyPerLayer ** layers;
HyPerConn ** connections;
char * name;
char * image_file;
PVLayerLoc imageLoc;
PVParams * params; // manages input parameters
InterColComm * icComm; // manages communication between HyPerColumns};
HyPerColRunDelegate * runDelegate; // runs time loop
}; // class HyPerCol
} // namespace PV
#endif /* HYPERCOL_HPP_ */
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
// taskwarrior - a command line task list manager.
//
// Copyright 2006 - 2011, Paul Beckingham, Federico Hernandez.
// All rights reserved.
//
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation; either version 2 of the License, or (at your option) any later
// version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the
//
// Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor,
// Boston, MA
// 02110-1301
// USA
//
////////////////////////////////////////////////////////////////////////////////
#include <vector>
#include <sstream>
#include <algorithm>
#include <text.h>
#include <i18n.h>
#include <Context.h>
#include <Directory.h>
#include <ViewText.h>
#include <CmdShow.h>
#define L10N // Localization complete.
extern Context context;
////////////////////////////////////////////////////////////////////////////////
CmdShow::CmdShow ()
{
_keyword = "show";
_usage = "task show [all | substring]";
_description = STRING_CMD_SHOW;
_read_only = true;
_displays_id = false;
}
////////////////////////////////////////////////////////////////////////////////
int CmdShow::execute (std::string& output)
{
int rc = 0;
std::stringstream out;
// Obtain the arguments from the description. That way, things like '--'
// have already been handled.
std::vector <std::string> words = context.a3.extract_words ();
if (words.size () > 2)
throw std::string (STRING_CMD_SHOW_ARGS);
int width = context.getWidth ();
// Complain about configuration variables that are not recognized.
// These are the regular configuration variables.
// Note that there is a leading and trailing space, to make it easier to
// search for whole words.
std::string recognized =
" abbreviation.minimum"
" active.indicator"
" annotations"
" avoidlastcolumn"
" bulk"
" burndown.bias"
" calendar.details"
" calendar.details.report"
" calendar.holidays"
" calendar.legend"
" calendar.offset"
" calendar.offset.value"
" color"
" color.active"
" color.alternate"
" color.blocked"
" color.burndown.done"
" color.burndown.pending"
" color.burndown.started"
" color.calendar.due"
" color.calendar.due.today"
" color.calendar.holiday"
" color.calendar.overdue"
" color.calendar.today"
" color.calendar.weekend"
" color.calendar.weeknumber"
" color.completed"
" color.debug"
" color.deleted"
" color.due"
" color.due.today"
" color.footnote"
" color.header"
" color.history.add"
" color.history.delete"
" color.history.done"
" color.label"
" color.overdue"
" color.pri.H"
" color.pri.L"
" color.pri.M"
" color.pri.none"
" color.recurring"
" color.summary.background"
" color.summary.bar"
" color.sync.added"
" color.sync.changed"
" color.sync.rejected"
" color.tagged"
" color.undo.after"
" color.undo.before"
" column.padding"
" column.spacing"
" complete.all.projects"
" complete.all.tags"
" confirmation"
" data.location"
" dateformat"
" dateformat.annotation"
" dateformat.holiday"
" dateformat.report"
" debug"
" default.command"
" default.due"
" default.priority"
" default.project"
" defaultheight"
" defaultwidth"
" dependency.confirmation"
" dependency.indicator"
" dependency.reminder"
" detection"
" displayweeknumber"
" dom"
" due"
" echo.command"
" edit.verbose"
" editor"
" exit.on.missing.db"
" export.ical.class"
" expressions"
" extensions"
" fontunderline"
" gc"
" hyphenate"
" indent.annotation"
" indent.report"
" journal.info"
" journal.time"
" journal.time.start.annotation"
" journal.time.stop.annotation"
" json.array"
" list.all.projects"
" list.all.tags"
" locale"
" locking"
" merge.autopush"
" merge.default.uri"
" monthsperline"
" nag"
" patterns"
" project"
" pull.default.uri"
" push.default.uri"
" recurrence.indicator"
" recurrence.limit"
" regex"
" row.padding"
" rule.precedence.color"
" search.case.sensitive"
" shadow.command"
" shadow.file"
" shadow.notify"
" shell.prompt"
" tag.indicator"
" undo.style"
" urgency.active.coefficient"
" urgency.annotations.coefficient"
" urgency.blocked.coefficient"
" urgency.blocking.coefficient"
" urgency.due.coefficient"
" urgency.next.coefficient"
" urgency.priority.coefficient"
" urgency.project.coefficient"
" urgency.tags.coefficient"
" urgency.waiting.coefficient"
" verbose"
" weekstart"
" xterm.title"
" ";
// This configuration variable is supported, but not documented. It exists
// so that unit tests can force color to be on even when the output from task
// is redirected to a file, or stdout is not a tty.
recognized += "_forcecolor ";
std::vector <std::string> all;
context.config.all (all);
std::vector <std::string> unrecognized;
std::vector <std::string>::iterator i;
for (i = all.begin (); i != all.end (); ++i)
{
// Disallow partial matches by tacking a leading and trailing space on each
// variable name.
std::string pattern = " " + *i + " ";
if (recognized.find (pattern) == std::string::npos)
{
// These are special configuration variables, because their name is
// dynamic.
if (i->substr (0, 14) != "color.keyword." &&
i->substr (0, 14) != "color.project." &&
i->substr (0, 10) != "color.tag." &&
i->substr (0, 8) != "holiday." &&
i->substr (0, 7) != "report." &&
i->substr (0, 6) != "alias." &&
i->substr (0, 5) != "hook." &&
i->substr (0, 21) != "urgency.user.project." &&
i->substr (0, 17) != "urgency.user.tag.")
{
unrecognized.push_back (*i);
}
}
}
// Find all the values that match the defaults, for highlighting.
std::vector <std::string> default_values;
Config default_config;
default_config.setDefaults ();
for (i = all.begin (); i != all.end (); ++i)
if (context.config.get (*i) != default_config.get (*i))
default_values.push_back (*i);
// Create output view.
ViewText view;
view.width (width);
view.add (Column::factory ("string", STRING_CMD_SHOW_CONF_VAR));
view.add (Column::factory ("string", STRING_CMD_SHOW_CONF_VALUE));
Color error ("bold white on red");
Color warning ("black on yellow");
std::string section;
// Look for the first plausible argument which could be a pattern
if (words.size ())
section = words[0];
if (section == "all")
section = "";
for (i = all.begin (); i != all.end (); ++i)
{
std::string::size_type loc = i->find (section, 0);
if (loc != std::string::npos)
{
// Look for unrecognized.
Color color;
if (std::find (unrecognized.begin (), unrecognized.end (), *i) != unrecognized.end ())
color = error;
else if (std::find (default_values.begin (), default_values.end (), *i) != default_values.end ())
color = warning;
int row = view.addRow ();
view.set (row, 0, *i, color);
view.set (row, 1, context.config.get (*i), color);
}
}
out << "\n"
<< view.render ()
<< (view.rows () == 0 ? STRING_CMD_SHOW_NONE : "")
<< (view.rows () == 0 ? "\n\n" : "\n");
// Display the unrecognized variables.
if (unrecognized.size ())
{
out << STRING_CMD_SHOW_UNREC << "\n";
for (i = unrecognized.begin (); i != unrecognized.end (); ++i)
out << " " << *i << "\n";
if (context.color ())
out << "\n " << format (STRING_CMD_SHOW_DIFFER_COLOR, error.colorize ("color"));
out << "\n\n";
}
if (default_values.size ())
{
out << STRING_CMD_SHOW_DIFFER;
if (context.color ())
out << " " << format (STRING_CMD_SHOW_DIFFER_COLOR, warning.colorize ("color"));
}
out << context.config.checkForDeprecatedColor ();
out << context.config.checkForDeprecatedColumns ();
// TODO Check for referenced but missing theme files.
// TODO Check for referenced but missing string files.
// TODO Check for referenced but missing tips files.
// Check for referenced but missing hook scripts.
#ifdef HAVE_LIBLUA
std::vector <std::string> missing_scripts;
for (i = all.begin (); i != all.end (); ++i)
{
if (i->substr (0, 5) == "hook.")
{
std::string value = context.config.get (*i);
Nibbler n (value);
// <path>:<function> [, ...]
while (!n.depleted ())
{
std::string file;
std::string function;
if (n.getUntil (':', file) &&
n.skip (':') &&
n.getUntil (',', function))
{
Path script (file);
if (!script.exists () || !script.readable ())
missing_scripts.push_back (file);
(void) n.skip (',');
}
}
}
}
if (missing_scripts.size ())
{
out << STRING_CMD_SHOW_HOOKS << "\n";
for (i = missing_scripts.begin (); i != missing_scripts.end (); ++i)
out << " " << *i << "\n";
out << "\n";
}
#endif
// Check for bad values in rc.annotations.
std::string annotations = context.config.get ("annotations");
if (annotations != "full" &&
annotations != "sparse" &&
annotations != "none")
out << format (STRING_CMD_SHOW_CONFIG_ERROR, "annotations", annotations)
<< "\n";
// Check for bad values in rc.calendar.details.
std::string calendardetails = context.config.get ("calendar.details");
if (calendardetails != "full" &&
calendardetails != "sparse" &&
calendardetails != "none")
out << format (STRING_CMD_SHOW_CONFIG_ERROR, "calendar.details", calendardetails)
<< "\n";
// Check for bad values in rc.calendar.holidays.
std::string calendarholidays = context.config.get ("calendar.holidays");
if (calendarholidays != "full" &&
calendarholidays != "sparse" &&
calendarholidays != "none")
out << format (STRING_CMD_SHOW_CONFIG_ERROR, "calendar.holidays", calendarholidays)
<< "\n";
// Check for bad values in rc.default.priority.
std::string defaultPriority = context.config.get ("default.priority");
if (defaultPriority != "H" &&
defaultPriority != "M" &&
defaultPriority != "L" &&
defaultPriority != "")
out << format (STRING_CMD_SHOW_CONFIG_ERROR, "default.priority", defaultPriority)
<< "\n";
// Verify installation. This is mentioned in the documentation as the way
// to ensure everything is properly installed.
if (all.size () == 0)
{
out << STRING_CMD_SHOW_EMPTY << "\n";
rc = 1;
}
else
{
Directory location (context.config.get ("data.location"));
if (location._data == "")
out << STRING_CMD_SHOW_NO_LOCATION << "\n";
if (! location.exists ())
out << STRING_CMD_SHOW_LOC_EXIST << "\n";
}
output = out.str ();
return rc;
}
////////////////////////////////////////////////////////////////////////////////
<commit_msg>Code Cleanup<commit_after>////////////////////////////////////////////////////////////////////////////////
// taskwarrior - a command line task list manager.
//
// Copyright 2006 - 2011, Paul Beckingham, Federico Hernandez.
// All rights reserved.
//
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation; either version 2 of the License, or (at your option) any later
// version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the
//
// Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor,
// Boston, MA
// 02110-1301
// USA
//
////////////////////////////////////////////////////////////////////////////////
#include <vector>
#include <sstream>
#include <algorithm>
#include <text.h>
#include <i18n.h>
#include <Context.h>
#include <Directory.h>
#include <ViewText.h>
#include <CmdShow.h>
#define L10N // Localization complete.
extern Context context;
////////////////////////////////////////////////////////////////////////////////
CmdShow::CmdShow ()
{
_keyword = "show";
_usage = "task show [all | substring]";
_description = STRING_CMD_SHOW;
_read_only = true;
_displays_id = false;
}
////////////////////////////////////////////////////////////////////////////////
int CmdShow::execute (std::string& output)
{
int rc = 0;
std::stringstream out;
// Obtain the arguments from the description. That way, things like '--'
// have already been handled.
std::vector <std::string> words = context.a3.extract_words ();
if (words.size () > 2)
throw std::string (STRING_CMD_SHOW_ARGS);
int width = context.getWidth ();
// Complain about configuration variables that are not recognized.
// These are the regular configuration variables.
// Note that there is a leading and trailing space, to make it easier to
// search for whole words.
std::string recognized =
" abbreviation.minimum"
" active.indicator"
" annotations"
" avoidlastcolumn"
" bulk"
" burndown.bias"
" calendar.details"
" calendar.details.report"
" calendar.holidays"
" calendar.legend"
" calendar.offset"
" calendar.offset.value"
" color"
" color.active"
" color.alternate"
" color.blocked"
" color.burndown.done"
" color.burndown.pending"
" color.burndown.started"
" color.calendar.due"
" color.calendar.due.today"
" color.calendar.holiday"
" color.calendar.overdue"
" color.calendar.today"
" color.calendar.weekend"
" color.calendar.weeknumber"
" color.completed"
" color.debug"
" color.deleted"
" color.due"
" color.due.today"
" color.footnote"
" color.header"
" color.history.add"
" color.history.delete"
" color.history.done"
" color.label"
" color.overdue"
" color.pri.H"
" color.pri.L"
" color.pri.M"
" color.pri.none"
" color.recurring"
" color.summary.background"
" color.summary.bar"
" color.sync.added"
" color.sync.changed"
" color.sync.rejected"
" color.tagged"
" color.undo.after"
" color.undo.before"
" column.padding"
" column.spacing"
" complete.all.projects"
" complete.all.tags"
" confirmation"
" data.location"
" dateformat"
" dateformat.annotation"
" dateformat.holiday"
" dateformat.report"
" debug"
" default.command"
" default.due"
" default.priority"
" default.project"
" defaultheight"
" defaultwidth"
" dependency.confirmation"
" dependency.indicator"
" dependency.reminder"
" detection"
" displayweeknumber"
" dom"
" due"
" echo.command"
" edit.verbose"
" editor"
" exit.on.missing.db"
" export.ical.class"
" expressions"
" extensions"
" fontunderline"
" gc"
" hyphenate"
" indent.annotation"
" indent.report"
" journal.info"
" journal.time"
" journal.time.start.annotation"
" journal.time.stop.annotation"
" json.array"
" list.all.projects"
" list.all.tags"
" locale"
" locking"
" merge.autopush"
" merge.default.uri"
" monthsperline"
" nag"
" patterns"
" project"
" pull.default.uri"
" push.default.uri"
" recurrence.indicator"
" recurrence.limit"
" regex"
" row.padding"
" rule.precedence.color"
" search.case.sensitive"
" shadow.command"
" shadow.file"
" shadow.notify"
" shell.prompt"
" tag.indicator"
" undo.style"
" urgency.active.coefficient"
" urgency.annotations.coefficient"
" urgency.blocked.coefficient"
" urgency.blocking.coefficient"
" urgency.due.coefficient"
" urgency.next.coefficient"
" urgency.priority.coefficient"
" urgency.project.coefficient"
" urgency.tags.coefficient"
" urgency.waiting.coefficient"
" verbose"
" weekstart"
" xterm.title"
" ";
// This configuration variable is supported, but not documented. It exists
// so that unit tests can force color to be on even when the output from task
// is redirected to a file, or stdout is not a tty.
recognized += "_forcecolor ";
std::vector <std::string> all;
context.config.all (all);
std::vector <std::string> unrecognized;
std::vector <std::string>::iterator i;
for (i = all.begin (); i != all.end (); ++i)
{
// Disallow partial matches by tacking a leading and trailing space on each
// variable name.
std::string pattern = " " + *i + " ";
if (recognized.find (pattern) == std::string::npos)
{
// These are special configuration variables, because their name is
// dynamic.
if (i->substr (0, 14) != "color.keyword." &&
i->substr (0, 14) != "color.project." &&
i->substr (0, 10) != "color.tag." &&
i->substr (0, 8) != "holiday." &&
i->substr (0, 7) != "report." &&
i->substr (0, 6) != "alias." &&
i->substr (0, 5) != "hook." &&
i->substr (0, 21) != "urgency.user.project." &&
i->substr (0, 17) != "urgency.user.tag.")
{
unrecognized.push_back (*i);
}
}
}
// Find all the values that match the defaults, for highlighting.
std::vector <std::string> default_values;
Config default_config;
default_config.setDefaults ();
for (i = all.begin (); i != all.end (); ++i)
if (context.config.get (*i) != default_config.get (*i))
default_values.push_back (*i);
// Create output view.
ViewText view;
view.width (width);
view.add (Column::factory ("string", STRING_CMD_SHOW_CONF_VAR));
view.add (Column::factory ("string", STRING_CMD_SHOW_CONF_VALUE));
Color error ("bold white on red");
Color warning ("black on yellow");
std::string section;
// Look for the first plausible argument which could be a pattern
if (words.size ())
section = words[0];
if (section == "all")
section = "";
for (i = all.begin (); i != all.end (); ++i)
{
std::string::size_type loc = i->find (section, 0);
if (loc != std::string::npos)
{
// Look for unrecognized.
Color color;
if (std::find (unrecognized.begin (), unrecognized.end (), *i) != unrecognized.end ())
color = error;
else if (std::find (default_values.begin (), default_values.end (), *i) != default_values.end ())
color = warning;
int row = view.addRow ();
view.set (row, 0, *i, color);
view.set (row, 1, context.config.get (*i), color);
}
}
out << "\n"
<< view.render ()
<< (view.rows () == 0 ? STRING_CMD_SHOW_NONE : "")
<< (view.rows () == 0 ? "\n\n" : "\n");
// Display the unrecognized variables.
if (unrecognized.size ())
{
out << STRING_CMD_SHOW_UNREC << "\n";
for (i = unrecognized.begin (); i != unrecognized.end (); ++i)
out << " " << *i << "\n";
if (context.color ())
out << "\n " << format (STRING_CMD_SHOW_DIFFER_COLOR, error.colorize ("color"));
out << "\n\n";
}
if (default_values.size ())
{
out << STRING_CMD_SHOW_DIFFER;
if (context.color ())
out << " " << format (STRING_CMD_SHOW_DIFFER_COLOR, warning.colorize ("color"));
}
out << context.config.checkForDeprecatedColor ();
out << context.config.checkForDeprecatedColumns ();
// TODO Check for referenced but missing theme files.
// TODO Check for referenced but missing string files.
// TODO Check for referenced but missing tips files.
// Check for referenced but missing hook scripts.
#ifdef HAVE_LIBLUA
std::vector <std::string> missing_scripts;
for (i = all.begin (); i != all.end (); ++i)
{
if (i->substr (0, 5) == "hook.")
{
std::string value = context.config.get (*i);
Nibbler n (value);
// <path>:<function> [, ...]
while (!n.depleted ())
{
std::string file;
std::string function;
if (n.getUntil (':', file) &&
n.skip (':') &&
n.getUntil (',', function))
{
Path script (file);
if (!script.exists () || !script.readable ())
missing_scripts.push_back (file);
(void) n.skip (',');
}
}
}
}
if (missing_scripts.size ())
{
out << STRING_CMD_SHOW_HOOKS << "\n";
for (i = missing_scripts.begin (); i != missing_scripts.end (); ++i)
out << " " << *i << "\n";
out << "\n";
}
#endif
// Check for bad values in rc.annotations.
// TODO Reconsider this.
std::string annotations = context.config.get ("annotations");
if (annotations != "full" &&
annotations != "sparse" &&
annotations != "none")
out << format (STRING_CMD_SHOW_CONFIG_ERROR, "annotations", annotations)
<< "\n";
// Check for bad values in rc.calendar.details.
std::string calendardetails = context.config.get ("calendar.details");
if (calendardetails != "full" &&
calendardetails != "sparse" &&
calendardetails != "none")
out << format (STRING_CMD_SHOW_CONFIG_ERROR, "calendar.details", calendardetails)
<< "\n";
// Check for bad values in rc.calendar.holidays.
std::string calendarholidays = context.config.get ("calendar.holidays");
if (calendarholidays != "full" &&
calendarholidays != "sparse" &&
calendarholidays != "none")
out << format (STRING_CMD_SHOW_CONFIG_ERROR, "calendar.holidays", calendarholidays)
<< "\n";
// Check for bad values in rc.default.priority.
std::string defaultPriority = context.config.get ("default.priority");
if (defaultPriority != "H" &&
defaultPriority != "M" &&
defaultPriority != "L" &&
defaultPriority != "")
out << format (STRING_CMD_SHOW_CONFIG_ERROR, "default.priority", defaultPriority)
<< "\n";
// Verify installation. This is mentioned in the documentation as the way
// to ensure everything is properly installed.
if (all.size () == 0)
{
out << STRING_CMD_SHOW_EMPTY << "\n";
rc = 1;
}
else
{
Directory location (context.config.get ("data.location"));
if (location._data == "")
out << STRING_CMD_SHOW_NO_LOCATION << "\n";
if (! location.exists ())
out << STRING_CMD_SHOW_LOC_EXIST << "\n";
}
output = out.str ();
return rc;
}
////////////////////////////////////////////////////////////////////////////////
<|endoftext|>
|
<commit_before>#ifdef WIN32
#pragma warning(4:4786)
#endif
#if (!defined(_WIN32) && !defined(WIN32))
#include <sys/types.h>
#include <dirent.h>
#else
#include <windows.h>
#endif
#include <string>
#include "BundleMgr.h"
#include "Bundle.h"
Bundle *BundleMgr::currentBundle = NULL;
std::string BundleMgr::bundlePath = "./data";
BundleMgr::BundleMgr(const std::string &path, const std::string &name)
{
bundlePath = path;
bundleName = name;
}
BundleMgr::~BundleMgr()
{
for (BundleMap::iterator it = bundles.begin(); it != bundles.end(); ++it)
delete it->second;
bundles.clear();
}
Bundle *BundleMgr::getBundle(const std::string &locale, bool setcur /*= true*/)
{
BundleMap::iterator it = bundles.find(locale);
if (it != bundles.end()) {
if (setcur) currentBundle = it->second;
return it->second;
}
Bundle *parentBundle = NULL;
if (locale.length() > 0) {
std::string parentLocale = locale;
int underPos = parentLocale.find_last_of('_');
if (underPos >= 0)
parentLocale = parentLocale.substr(0,underPos);
else
parentLocale.resize(0);
parentBundle = getBundle(parentLocale);
}
Bundle *pB = new Bundle(parentBundle);
std::string path = bundlePath + "/l10n/" + bundleName;
if (locale.length() > 0)
path += "_" + locale;
path += ".po";
pB->load(path);
bundles.insert(std::pair<std::string,Bundle*>(locale, pB));
if (setcur) currentBundle = pB;
return pB;
}
Bundle *BundleMgr::getCurrentBundle()
{
return currentBundle;
}
bool BundleMgr::getLocaleList(std::vector<std::string> *list) {
if (list == NULL) return false;
// There could have been stuff added to the list
// prior to this call. Save the list count.
int initSize = list->size();
char fileName[255], *end = NULL;
do {
#if (defined(_WIN32) || defined(WIN32))
// Prepare the wildcarded file path to search for and copy it to fileName
sprintf(fileName, "%s\\l10n\\bzflag_*.po", bundlePath.c_str());
HANDLE hFoundFile = NULL;
WIN32_FIND_DATA data;
hFoundFile = FindFirstFile((LPCTSTR) fileName, &data);
if (hFoundFile == INVALID_HANDLE_VALUE) break; // Invalid path
do {
strcpy(fileName, &(data.cFileName[7]));
if (strcmp(&(fileName[strlen(fileName) - 3]), ".po") != 0)
continue; // Doesnt end in ".po". Should not happen
fileName[strlen(fileName) - 3] = '\0';
if (strcmp(fileName, "xx") != 0) // Dont add the xx locale
list->push_back(fileName);
} while (FindNextFile(hFoundFile, &data) == TRUE);
FindClose(hFoundFile);
break;
#else
// This should work for most of the currently supported
// non Windows platforms i believe.
DIR *localedir = opendir((bundlePath + "/l10n/").c_str());
if (localedir == NULL) break;
struct dirent *dirinfo = NULL;
while ((dirinfo = readdir(localedir)) != NULL) {
// dirinfo points to an item in the directory
const int length = strlen(dirinfo->d_name);
if (length < 11) continue; // Name is to short to contain bzflag_...po
if (strncmp(dirinfo->d_name, "bzflag_", 7) ||
strncmp(dirinfo->d_name + length - 3, ".po", 3))
continue; // The name doesnt start with bzflag_ or end with .po
// This is a (hopefully) valid bzflag locale file
// Copy the filename and strip out the trailing .po
strncpy(fileName, &(dirinfo->d_name[7]), length - 7);
fileName[length - 7] = '\0';
end = strrchr(fileName, '.');
if (end == NULL) continue; // This should not be able to happen
*end = '\0';
// fileName should now contain our locale name
if (strcmp(fileName, "xx") != 0) // Dont add the xx locale
list->push_back(fileName);
}
closedir(localedir);
#endif
} while (0);
return ((int)list->size() > initSize) ? true : false;
}
// ex: shiftwidth=2 tabstop=8
<commit_msg>cleanup po file name parsing<commit_after>#ifdef WIN32
#pragma warning(4:4786)
#endif
#if (!defined(_WIN32) && !defined(WIN32))
#include <sys/types.h>
#include <dirent.h>
#else
#include <windows.h>
#endif
#include <string>
#include "BundleMgr.h"
#include "Bundle.h"
Bundle *BundleMgr::currentBundle = NULL;
std::string BundleMgr::bundlePath = "./data";
BundleMgr::BundleMgr(const std::string &path, const std::string &name)
{
bundlePath = path;
bundleName = name;
}
BundleMgr::~BundleMgr()
{
for (BundleMap::iterator it = bundles.begin(); it != bundles.end(); ++it)
delete it->second;
bundles.clear();
}
Bundle *BundleMgr::getBundle(const std::string &locale, bool setcur /*= true*/)
{
BundleMap::iterator it = bundles.find(locale);
if (it != bundles.end()) {
if (setcur) currentBundle = it->second;
return it->second;
}
Bundle *parentBundle = NULL;
if (locale.length() > 0) {
std::string parentLocale = locale;
int underPos = parentLocale.find_last_of('_');
if (underPos >= 0)
parentLocale = parentLocale.substr(0,underPos);
else
parentLocale.resize(0);
parentBundle = getBundle(parentLocale);
}
Bundle *pB = new Bundle(parentBundle);
std::string path = bundlePath + "/l10n/" + bundleName;
if (locale.length() > 0)
path += "_" + locale;
path += ".po";
pB->load(path);
bundles.insert(std::pair<std::string,Bundle*>(locale, pB));
if (setcur) currentBundle = pB;
return pB;
}
Bundle *BundleMgr::getCurrentBundle()
{
return currentBundle;
}
bool BundleMgr::getLocaleList(std::vector<std::string> *list) {
if (list == NULL) return false;
// There could have been stuff added to the list
// prior to this call. Save the list count.
int initSize = list->size();
char fileName[255], *end = NULL;
do {
#if (defined(_WIN32) || defined(WIN32))
// Prepare the wildcarded file path to search for and copy it to fileName
sprintf(fileName, "%s\\l10n\\bzflag_*.po", bundlePath.c_str());
HANDLE hFoundFile = NULL;
WIN32_FIND_DATA data;
hFoundFile = FindFirstFile((LPCTSTR) fileName, &data);
if (hFoundFile == INVALID_HANDLE_VALUE) break; // Invalid path
do {
std::string poFile = data.cFileName;
int dotPos = poFile.find_first_of('.');
if ((dotPos >= 0) && (poFile.substr(dotPos+1) == "po")) {
int underPos = poFile.find_first_of('_');
if (underPos >= 0) {
std::string locale = poFile.substr(underPos+1, dotPos-underPos-1);
if (locale != "xx")
list->push_back(locale);
}
}
} while (FindNextFile(hFoundFile, &data) == TRUE);
FindClose(hFoundFile);
break;
#else
// This should work for most of the currently supported
// non Windows platforms i believe.
DIR *localedir = opendir((bundlePath + "/l10n/").c_str());
if (localedir == NULL) break;
struct dirent *dirinfo = NULL;
while ((dirinfo = readdir(localedir)) != NULL) {
std::string poFile = dirinfo->d_name;
int dotPos = poFile.find_first_of('.');
if ((dotPos >= 0) && (poFile.substr(dotPos+1) == "po")) {
int underPos = poFile.find_first_of('_');
if (underPos >= 0) {
std::string locale = poFile.substr(underPos+1, dotPos-underPos-1);
if (locale != "xx")
list->push_back(locale);
}
}
}
closedir(localedir);
#endif
} while (0);
return ((int)list->size() > initSize) ? true : false;
}
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <cstdint>
#include <fstream>
#include <iostream>
#include <ostream>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include "hdr_image.h"
namespace visionaray
{
bool hdr_image::load(std::string const& filename)
{
std::ifstream file(filename);
// parse information header ---------------------------
std::string line;
std::getline(file, line);
if (line != "#?RADIANCE")
{
std::cerr << "Invalid Radiance picture file\n";
return false;
}
enum cformat { RGBE, XYZE };
cformat format = RGBE;
while (!line.empty())
{
std::getline(file, line);
std::vector<std::string> vars;
boost::split(vars, line, boost::is_any_of("="));
if (vars.size() >= 2)
{
std::string key = vars[0];
boost::trim(vars[0]);
vars.erase(vars.begin());
std::string value = boost::algorithm::join(vars, "");
if (key == "FORMAT" && value == "32-bit_rle_rgbe")
{
format = RGBE;
}
else if (key == "FORMAT" && value == "32-bit_rle_xyze")
{
format = XYZE;
std::cerr << "Error: XYZE format in HDR files not yet supported\n";
return false;
}
else if (key == "FORMAT")
{
std::cerr << "Error: unsupported format string in HDR file\n";
return false;
}
}
}
// resolution string ----------------------------------
std::getline(file, line);
std::cout << "Line: " << line << std::endl;
std::vector<std::string> res;
boost::split(res, line, boost::is_any_of("\t "));
if (res.size() != 4)
{
std::cout << "Error: invalid resolution string in HDR file\n";
}
if (res[0] == "-Y" && res[2] == "+X")
{
width_ = boost::lexical_cast<size_t>(res[3]);
height_ = boost::lexical_cast<size_t>(res[1]);
}
else
{
std::cout << "Error: unsupported resolution string in HDR file\n";
}
// scanlines ------------------------------------------
//while (std::getline(file, line))
for (size_t h = 0; h < height_; ++h)
{
std::getline(file, line);
auto bytes = reinterpret_cast<uint8_t const*>(line.c_str());
for (size_t w = 0; w < width_; ++w)
{
uint8_t r = bytes[w * 4];
uint8_t g = bytes[w * 4 + 1];
uint8_t b = bytes[w * 4 + 2];
uint8_t e = bytes[w * 4 + 3];
size_t rl = 1;
if (r == 2 && g == 2)
{
}
}
}
return true;
}
} // visionaray
<commit_msg>HDR temp<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <cstdint>
#include <fstream>
#include <iostream>
#include <ostream>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <visionaray/math/vector.h>
#include "hdr_image.h"
namespace visionaray
{
bool hdr_image::load(std::string const& filename)
{
std::ifstream file(filename);
if (!file.good())
{
std::cerr << "Cannot open HDR file: " << filename << '\n';
return false;
}
// parse information header ---------------------------
std::string line;
std::getline(file, line);
if (line != "#?RADIANCE")
{
std::cerr << "Invalid Radiance picture file\n";
return false;
}
enum cformat { RGBE, XYZE };
cformat format = RGBE;
while (!line.empty())
{
std::getline(file, line);
std::vector<std::string> vars;
boost::split(vars, line, boost::is_any_of("="));
if (vars.size() >= 2)
{
std::string key = vars[0];
boost::trim(vars[0]);
vars.erase(vars.begin());
std::string value = boost::algorithm::join(vars, "");
if (key == "FORMAT" && value == "32-bit_rle_rgbe")
{
format = RGBE;
}
else if (key == "FORMAT" && value == "32-bit_rle_xyze")
{
format = XYZE;
std::cerr << "Error: XYZE format in HDR files not yet supported\n";
return false;
}
else if (key == "FORMAT")
{
std::cerr << "Error: unsupported format string in HDR file\n";
return false;
}
}
}
// resolution string ----------------------------------
std::getline(file, line);
std::cout << "Line: " << line << std::endl;
std::vector<std::string> res;
boost::split(res, line, boost::is_any_of("\t "));
if (res.size() != 4)
{
std::cerr << "Error: invalid resolution string in HDR file\n";
return false;
}
if (res[0] == "-Y" && res[2] == "+X")
{
width_ = boost::lexical_cast<size_t>(res[3]);
height_ = boost::lexical_cast<size_t>(res[1]);
}
else
{
std::cerr << "Error: unsupported resolution string in HDR file\n";
return false;
}
// scanlines ------------------------------------------
std::vector<vec4> rgbe_line(width_);
for (size_t h = 0; h < height_; ++h)
{
std::getline(file, line);
auto bytes = reinterpret_cast<uint8_t const*>(line.c_str());
// Read the first four bytes of each scaline
// Radiance's new RLE: 0x2 0x2 means RLE
uint8_t r = *bytes++;
uint8_t g = *bytes++;
uint8_t b = *bytes++;
uint8_t e = *bytes++;
if (r == 2 && g == 2)
{
// Component-wise RLE
for (size_t c = 0; c < 4; ++c)
{
size_t x = 0;
while (x < width_)
{
uint8_t runlength = *bytes++;
if (runlength <= 128) // no run!
{
for (size_t i = 0; i < runlength; ++i)
{
rgbe_line[i][c] = *bytes++;
}
}
else
{
runlength -= 128;
for (size_t i = 0; i < runlength; ++i)
{
}
}
x += runlength;
}
std::cout << x << '\n';
}
}
}
return true;
}
} // visionaray
<|endoftext|>
|
<commit_before>
#include <gtest/gtest.h>
#include <boost/any.hpp>
#include "CoinModel.hpp"
#include "cyclopts/cbc_solver.h"
#include "cyclopts/function.h"
#include "cyclopts/solver.h"
#include "cyclopts/solver_interface.h"
#include "cyclopts/variable.h"
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CycloptsCBCSolverTests, 1VarIPUnbounded) {
// usings
using boost::any_cast;
using cyclus::cyclopts::SolverPtr;
using cyclus::cyclopts::CBCSolver;
using cyclus::cyclopts::Constraint;
using cyclus::cyclopts::ConstraintPtr;
using cyclus::cyclopts::ObjFuncPtr;
using cyclus::cyclopts::SolverInterface;
using cyclus::cyclopts::Variable;
using cyclus::cyclopts::VariablePtr;
using cyclus::cyclopts::IntegerVariable;
using cyclus::cyclopts::ObjectiveFunction;
// problem instance values
int x_exp = 0;
int upper = 1;
int lower = 0;
double obj_mod = 1.0;
// set up solver and interface
SolverPtr solver(new CBCSolver());
SolverInterface csi(solver);
// set up objective function
ObjFuncPtr obj(new ObjectiveFunction(ObjectiveFunction::MIN));
csi.RegisterObjFunction(obj);
// set up variables
VariablePtr x(new IntegerVariable(lower, Variable::INF));
csi.RegisterVariable(x);
// objective function
csi.AddVarToObjFunction(x, obj_mod);
// solve and get solution
csi.Solve();
// check
EXPECT_EQ(x_exp, any_cast<int>(x->value()));
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CycloptsCBCSolverTests, 2VarIP) {
// usings
using boost::any_cast;
using cyclus::cyclopts::SolverPtr;
using cyclus::cyclopts::CBCSolver;
using cyclus::cyclopts::Constraint;
using cyclus::cyclopts::ConstraintPtr;
using cyclus::cyclopts::ObjFuncPtr;
using cyclus::cyclopts::SolverInterface;
using cyclus::cyclopts::Variable;
using cyclus::cyclopts::VariablePtr;
using cyclus::cyclopts::IntegerVariable;
using cyclus::cyclopts::ObjectiveFunction;
// problem instance values
int x_exp = 1, y_exp = 2;
double cap_x = 3.0, cap_y = 10.0, cost_x = 1.0, cost_y = 2.0;
double unmet_demand = 22.0;
// set up solver and interface
SolverPtr solver(new CBCSolver());
SolverInterface csi(solver);
// set up objective function
ObjFuncPtr obj(new ObjectiveFunction(ObjectiveFunction::MIN));
csi.RegisterObjFunction(obj);
// set up constraint
ConstraintPtr c(new Constraint(Constraint::GTEQ, unmet_demand));
csi.RegisterConstraint(c);
// set up variables
VariablePtr x(new IntegerVariable(0, Variable::INF));
csi.RegisterVariable(x);
VariablePtr y(new IntegerVariable(0, Variable::INF));
csi.RegisterVariable(y);
// configure constraint and objective function
csi.AddVarToConstraint(x, cap_x, c);
csi.AddVarToConstraint(y, cap_y, c);
csi.AddVarToObjFunction(x, cost_x);
csi.AddVarToObjFunction(y, cost_y);
// solve and get solution
csi.Solve();
// check
EXPECT_EQ(x_exp, any_cast<int>(x->value()));
EXPECT_EQ(y_exp, any_cast<int>(y->value()));
}
<commit_msg>added some more simple tests for the cbc solver. two have been intentionally disabled because the maximization direction for the objective function does not appear to be working. I have double checked that the optimization direction for maximization is correct (it's 1.0) from the coin documentation. I'll investigate further.<commit_after>
#include <gtest/gtest.h>
#include <boost/any.hpp>
#include "CoinModel.hpp"
#include "cyclopts/cbc_solver.h"
#include "cyclopts/function.h"
#include "cyclopts/solver.h"
#include "cyclopts/solver_interface.h"
#include "cyclopts/variable.h"
// usings
using boost::any_cast;
using cyclus::cyclopts::SolverPtr;
using cyclus::cyclopts::CBCSolver;
using cyclus::cyclopts::Constraint;
using cyclus::cyclopts::ConstraintPtr;
using cyclus::cyclopts::ObjFuncPtr;
using cyclus::cyclopts::SolverInterface;
using cyclus::cyclopts::Variable;
using cyclus::cyclopts::VariablePtr;
using cyclus::cyclopts::IntegerVariable;
using cyclus::cyclopts::ObjectiveFunction;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CycloptsCBCSolverTests, 1VarIPLowerBoundMin) {
// problem instance values
int x_exp = 0;
int lower = 0;
double obj_mod = 1.0;
// set up solver and interface
SolverPtr solver(new CBCSolver());
SolverInterface csi(solver);
// set up objective function
ObjFuncPtr obj(new ObjectiveFunction(ObjectiveFunction::MIN));
csi.RegisterObjFunction(obj);
// set up variables
VariablePtr x(new IntegerVariable(lower, Variable::INF));
csi.RegisterVariable(x);
// objective function
csi.AddVarToObjFunction(x, obj_mod);
// solve and get solution
csi.Solve();
// check
EXPECT_EQ(x_exp, any_cast<int>(x->value()));
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CycloptsCBCSolverTests, 1VarIPBothBoundsMin) {
// problem instance values
int x_exp = 0;
int upper = 1;
int lower = 0;
double obj_mod = 1.0;
// set up solver and interface
SolverPtr solver(new CBCSolver());
SolverInterface csi(solver);
// set up objective function
ObjFuncPtr obj(new ObjectiveFunction(ObjectiveFunction::MIN));
csi.RegisterObjFunction(obj);
// set up variables
VariablePtr x(new IntegerVariable(lower, upper));
csi.RegisterVariable(x);
// objective function
csi.AddVarToObjFunction(x, obj_mod);
// solve and get solution
csi.Solve();
// check
EXPECT_EQ(x_exp, any_cast<int>(x->value()));
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CycloptsCBCSolverTests, DISABLED_1VarIPUpperBoundMax) {
// problem instance values
int x_exp = 1;
int upper = 1;
double obj_mod = 1.0;
// set up solver and interface
SolverPtr solver(new CBCSolver());
SolverInterface csi(solver);
// set up objective function
ObjFuncPtr obj(new ObjectiveFunction(ObjectiveFunction::MAX));
csi.RegisterObjFunction(obj);
// set up variables
VariablePtr x(new IntegerVariable(Variable::NEG_INF, upper));
csi.RegisterVariable(x);
// objective function
csi.AddVarToObjFunction(x, obj_mod);
// solve and get solution
csi.Solve();
// check
EXPECT_EQ(x_exp, any_cast<int>(x->value()));
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CycloptsCBCSolverTests, DISABLED_1VarIPBothBoundsMax) {
// problem instance values
int x_exp = 1;
int lower = 0;
int upper = 1;
double obj_mod = 1.0;
// set up solver and interface
SolverPtr solver(new CBCSolver());
SolverInterface csi(solver);
// set up objective function
ObjFuncPtr obj(new ObjectiveFunction(ObjectiveFunction::MAX));
csi.RegisterObjFunction(obj);
// set up variables
VariablePtr x(new IntegerVariable(lower, upper));
csi.RegisterVariable(x);
// objective function
csi.AddVarToObjFunction(x, obj_mod);
// solve and get solution
csi.Solve();
// check
EXPECT_EQ(x_exp, any_cast<int>(x->value()));
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST(CycloptsCBCSolverTests, 2VarIP) {
// usings
using boost::any_cast;
using cyclus::cyclopts::SolverPtr;
using cyclus::cyclopts::CBCSolver;
using cyclus::cyclopts::Constraint;
using cyclus::cyclopts::ConstraintPtr;
using cyclus::cyclopts::ObjFuncPtr;
using cyclus::cyclopts::SolverInterface;
using cyclus::cyclopts::Variable;
using cyclus::cyclopts::VariablePtr;
using cyclus::cyclopts::IntegerVariable;
using cyclus::cyclopts::ObjectiveFunction;
// problem instance values
int x_exp = 1, y_exp = 2;
double cap_x = 3.0, cap_y = 10.0, cost_x = 1.0, cost_y = 2.0;
double unmet_demand = 22.0;
// set up solver and interface
SolverPtr solver(new CBCSolver());
SolverInterface csi(solver);
// set up objective function
ObjFuncPtr obj(new ObjectiveFunction(ObjectiveFunction::MIN));
csi.RegisterObjFunction(obj);
// set up constraint
ConstraintPtr c(new Constraint(Constraint::GTEQ, unmet_demand));
csi.RegisterConstraint(c);
// set up variables
VariablePtr x(new IntegerVariable(0, Variable::INF));
csi.RegisterVariable(x);
VariablePtr y(new IntegerVariable(0, Variable::INF));
csi.RegisterVariable(y);
// configure constraint and objective function
csi.AddVarToConstraint(x, cap_x, c);
csi.AddVarToConstraint(y, cap_y, c);
csi.AddVarToObjFunction(x, cost_x);
csi.AddVarToObjFunction(y, cost_y);
// solve and get solution
csi.Solve();
// check
EXPECT_EQ(x_exp, any_cast<int>(x->value()));
EXPECT_EQ(y_exp, any_cast<int>(y->value()));
}
<|endoftext|>
|
<commit_before><commit_msg>in case someone gets the same spam mail as I did: bool partNode::isAttachment() const { + if (!dwPart()) + return false;<commit_after><|endoftext|>
|
<commit_before><<<<<<< HEAD:library/max-sdk/c74support/max-includes/common/commonsyms.cpp
// This wraps commonsyms.c as a C++ file to avoid dumb warnings in Xcode
=======
// This wrapps commonsyms.c as a C++ file to avoid dumb warnings in Xcode
>>>>>>> active:library/max-sdk/c74support/max-includes/common/commonsyms.cpp
#include "commonsyms.c"
<commit_msg>resolving conflict<commit_after>#include "commonsyms.c"
<|endoftext|>
|
<commit_before>// UjoImro, 2013
// Experimental Research Code for the CARP Project
#ifndef __CARP__MEMORY__HPP__
#define __CARP__MEMORY__HPP__
#include <bitset>
#include <memory>
#include <cstddef>
#include <utility>
namespace carp {
template <class T0>
class memory {
private:
int64_t m_size;
// three statuses:
// free - the block is not allocated
// broken - the block is broken into subblocks (left and right are not empty)
// allocated - the block is used for allocation
enum status_t { free, broken, allocated };
class block_t {
public:
status_t m_status;
int64_t m_level;
std::shared_ptr<block_t> m_left;
std::shared_ptr<block_t> m_right;
block_t( const int64_t & level ) : m_status(free), m_level(level) { assert(level>=0); };
std::pair<bool, int64_t>
acquire( const int64_t & level ) {
assert( m_level >= level );
if ( m_status == allocated )
return make_pair(false, 0);
if ( m_status == free ) {
if ( m_level == level ) { // we are allocating this block for the request
m_status = allocated;
return std::make_pair( true, 0 );
}
else // NOT m_level == level (m_level > level )
assert(m_level>level);
split();
} // m_status == free
// if we have got here then m_status == broken AND m_level>level (so m_level>0)
assert(m_level > level);
auto left_node = left->acquire(level);
if (left_node.first)
return std::make_pair( true, left_node.second );
auto right_node = right->acquire(level);
if (right_node.first)
return std::make_pair( true, (1<<level) + right_node.second );
return std::make_paid(false, 0);
} // acquire
bool split() {
assert(m_level>0);
assert(m_status==free);
m_status = broken;
m_left.reset( new block(m_level-1) );
m_right.reset( new block(m_level-1) );
} // split
void merge() {
if ( ( m_status == broken ) and
( left.status == free ) and
( right.status == free ) ) {
left.reset();
right.reset();
m_status = free;
}
} // merge
void release( const std::bitsetint64_t & pos ) throw ( memory::exception& ){
if (m_status == free) throw memory::exception(FREEING_UNALLOCATED_MEMORY);
if (m_status == allocated) {
m_status == free;
return;
}
// here the status is broken
assert(m_status==broken);
if (pos.test(m_level))
left->release();
else // NOT nextbig
right->release();
merge(); // we merge the blocks if it's possible
return;
} // release
}; // class block
block pool;
public:
typedef T0 value_type;
static const int64_t memsize = 128;
static const int64_t granularity = memsize / 8;
enum error_t { INSUFFICIENT_MEMORY, FREEING_UNALLOCATED_MEMORY };
class exception {
public error_t error;
}; // class exception
memory ( const int64_t & numel )
: m_size( sizeof(value_type) * size ),
pool( log2ceil(m_size) ){ } // memory
int64_t
allocate( const int64_t & numel ) throw( memory::exception& ) {
int64_t size = numel * sizeof(value_type);
level = log2ceil(size);
auto node = pool.allocate(level);
if (!node.first) throw memory::exception(INSUFFICIENT_MEMORY);
return node.second;
} // allocate
void
release( const int64_t & elpos ) throw ( memory::exception& ) {
// int64_t size = elpos * sizeof(value_type);
std::setbit<memsize> position(elpos);
pool.release(position);
return;
} // release
}; // memory
} // namespace CARP
#endif /* __CARP__MEMORY__HPP__ */
// LuM end of file
<commit_msg>memory allocator<commit_after>// UjoImro, 2013
// Experimental Research Code for the CARP Project
#ifndef __CARP__MEMORY__HPP__
#define __CARP__MEMORY__HPP__
#include <bitset>
#include <memory>
#include <cstddef>
#include <utility>
namespace carp {
template <class T0>
class memory {
private:
typedef std::bitset<8*sizeof(int64_t)> position_t;
int64_t m_size;
// three statuses:
// free - the block is not allocated
// broken - the block is broken into subblocks (left and right are not NULL)
// allocated - the block is used for allocation
enum status_t { free, broken, allocated };
int64_t
log2ceil( const int64_t & val ) {
int64_t result;
for ( int64_t = 0; (1ul<<result) < val; result++);
return result;
} // log2ceil
class block_t {
public:
status_t m_status;
int64_t m_level;
std::shared_ptr<block_t> m_left;
std::shared_ptr<block_t> m_right;
block_t( const int64_t & level ) : m_status(free), m_level(level) { assert(level>=0); };
std::pair<bool, int64_t>
acquire( const int64_t & level ) {
if ( m_level < level )
return make_pair(false, 0);
if ( m_status == allocated )
return make_pair(false, 0);
if ( m_status == free ) {
if ( m_level == level ) { // we are allocating this block for the request
m_status = allocated;
return std::make_pair( true, 0 );
}
else { // NOT m_level == level (m_level > level )
assert(m_level>level);
split();
}
} // m_status == free
// if we have got here then m_status == broken AND m_level>level (so m_level>0)
assert(m_level > level);
auto left_node = left->acquire(level);
if (left_node.first)
return std::make_pair( true, left_node.second );
auto right_node = right->acquire(level);
if (right_node.first)
return std::make_pair( true, (1<<level) + right_node.second );
return std::make_paid(false, 0);
} // acquire
bool split() {
assert( m_level > 0 );
assert( m_status == free );
m_status = broken;
m_left.reset( new block(m_level-1) );
m_right.reset( new block(m_level-1) );
} // split
void merge() {
if ( ( m_status == broken ) and
( left.status == free ) and
( right.status == free ) ) {
left.reset();
right.reset();
m_status = free;
} // if
} // merge
void release( const position_t & pos ) throw ( memory::exception& ){
if (m_status == free) throw memory::exception(FREEING_UNALLOCATED_MEMORY);
if (m_status == allocated) {
m_status == free;
return;
}
// here the status is broken
assert(m_status==broken);
if (pos.test(m_level))
left->release();
else // NOT nextbig
right->release();
merge(); // we merge the blocks if it's possible
return;
} // release
}; // class block
block pool;
public:
typedef T0 value_type;
static const int64_t memsize = 128;
static const int64_t granularity = memsize / 8;
enum error_t { INSUFFICIENT_MEMORY, FREEING_UNALLOCATED_MEMORY };
class exception {
public error_t error;
}; // class exception
memory ( const int64_t & numel )
: m_size( sizeof(value_type) * size ),
pool( log2ceil(m_size) ) { } // memory
int64_t
allocate( const int64_t & numel ) throw( memory::exception& ) {
int64_t size = numel * sizeof(value_type);
level = log2ceil( size / memsize );
auto node = pool.allocate(level);
if (!node.first) throw memory::exception(INSUFFICIENT_MEMORY);
return 128 * node.second / sizeof(value_type);
} // allocate
void
release( const int64_t & elpos ) throw ( memory::exception& ) {
// int64_t size = elpos * sizeof(value_type);
assert( elpos * sizeof(value_type) % 128 == 0 );
position_t position( elpos * sizeof(value_type) / 128 );
pool.release(position);
return;
} // release
}; // memory
} // namespace CARP
#endif /* __CARP__MEMORY__HPP__ */
// LuM end of file
<|endoftext|>
|
<commit_before>#pragma once
namespace puro {
/** A Wrapper around audio buffer data with helper functions for accessing and debug checks. Does not own the data. */
template <int NumChannels, typename T=float>
struct buffer
{
typedef T value_type;
static constexpr int number_of_channels = NumChannels;
int num_samples;
std::array<T*, NumChannels> ptrs;
int length() const noexcept { return num_samples; }
static constexpr int num_channels() noexcept { return NumChannels; }
T* operator[] (int ch) const
{
errorif(ch < 0 || ch >= num_channels(), "channel out of range");
return ptrs[ch];
}
// numpy-style slice operator
buffer operator() (int start, int end)
{
return buffer_slice(*this, start, end);
}
// ctors
buffer(int length) : num_samples(length) {};
buffer(int length, T** channelPtrs) : num_samples(length)
{
for (auto ch = 0; ch < num_channels(); ++ch)
ptrs[ch] = channelPtrs[ch];
}
};
/** Dynamic wrapper around audio buffer data with resizeable channel count. Does not own the data. */
template <int MaxChannels=8, typename T=float>
struct dynamic_buffer
{
typedef T value_type;
static constexpr int max_channels = MaxChannels;
int num_samples;
int used_num_channels;
std::array<T*, MaxChannels> ptrs;
int length() const { return num_samples; };
int num_channels() const { return used_num_channels; } // some more advanced class may want to redefine this
T* operator[] (int ch)
{
errorif(ch < 0 || ch >= num_channels(), "channel out of range");
return ptrs[ch];
}
// ctors
dynamic_buffer(int num_channels, int length) : used_num_channels(num_channels), num_samples(length)
{};
dynamic_buffer(int num_channels, int length, T** channelPtrs) : used_num_channels(num_channels), num_samples(length)
{
for (auto ch = 0; ch < num_channels; ++ch)
ptrs[ch] = channelPtrs[ch];
}
};
/*
template <int NumChannels, int NumSamples, typename T=float>
struct fixed_buffer
{
typedef T value_type;
static constexpr int max_channels = NumChannels;
std::array<T*, NumChannels> ptrs;
constexpr int length() const noexcept { return NumSamples; }
constexpr int num_channels() const noexcept { return NumChannels; }
T* operator[] (int ch)
{
errorif(ch < 0 || ch >= num_channels(), "channel out of range");
return ptrs[ch];
}
};
*/
/*
template <class BufferType, class Allocator = std::allocator<typename BufferType::value_type>>
struct mem_owner
{
typedef typename BufferType::value_type value_type;
static constexpr auto num_channels = BufferType::max_channels;
template <typename ...Args>
mem_owner(Args... args) : buffer(args...)
{
for (auto ch=0; ch<buffer.num_channels(); ++ch)
{
vectors[ch].resize(buffer.length());
buffer.ptrs[ch] = vectors[ch].data();
}
}
mem_owner(mem_owner &&) = delete;
mem_owner(const mem_owner &) = delete;
BufferType buffer;
std::array<std::vector<value_type, Allocator>, num_channels> vectors;
};
*/
template <class BufferType, class Allocator = std::allocator<typename BufferType::value_type>>
struct mem_buffer : public BufferType
{
typedef typename BufferType::value_type value_type;
mem_buffer() = default;
mem_buffer(mem_buffer &&) = delete;
mem_buffer(const mem_buffer &) = delete;
mem_buffer(int length) : BufferType(length)
{
for (auto ch=0; ch < BufferType::number_of_channels; ++ch)
{
vectors[ch].resize(BufferType::length());
this->ptrs[ch] = vectors[ch].data();
}
}
BufferType operator* () { return *this; }
BufferType get() { return *this; }
void operator= (BufferType new_buffer)
{
*reinterpret_cast<BufferType*>(this) = new_buffer;
}
std::array<std::vector<value_type, Allocator>, BufferType::number_of_channels> vectors;
};
////////////////////////////////
// Buffer operations
////////////////////////////////
/** Create a Buffer with the data laid out into the provided vector.
The vector may be resized if needed depending on template arg. Number of channels is deducted from the template args. */
template <typename BufferType, typename VectorType, bool resizeIfNeeded = PURO_BUFFER_WRAP_VECTOR_RESIZING>
BufferType buffer_wrap_vector(VectorType& vector, int numSamples) noexcept
{
if (resizeIfNeeded)
{
const auto totLength = BufferType::num_channels * numSamples;
if (vector.size() < totLength)
vector.resize(totLength);
}
return BufferType(numSamples, vector.data());
}
template <typename BufferType>
BufferType buffer_trim_begin(BufferType buffer, int offset) noexcept
{
errorif(offset < 0 || offset > buffer.numSamples, "offset out of bounds");
buffer.numSamples -= offset;
for (int ch = 0; ch < buffer.num_channels(); ++ch)
buffer.channelPtrs[ch] = &buffer.channelPtrs[ch][offset];
return buffer;
}
template <typename BufferType>
BufferType buffer_trim_length(BufferType buffer, int newLength) noexcept
{
errorif(newLength > buffer.numSamples, "new length out of bounds");
buffer.numSamples = math::max(newLength, 0);
return buffer;
}
/** Get a segment of a buffer with given offset and length */
template <typename BufferType>
BufferType buffer_segment(BufferType buffer, int offset, int length) noexcept
{
errorif(offset > buffer.numSamples, "segment offset greater than number of samples available");
errorif(length < 0 || length > (offset + buffer.length()), "segment length out of bounds");
for (int ch = 0; ch < buffer.num_channels(); ++ch)
buffer.channelPtrs[ch] = &buffer.channelPtrs[ch][offset];
buffer.numSamples = length;
return buffer;
}
/** Get a segment of a buffer with given offset and length */
template <typename BufferType>
BufferType buffer_slice(BufferType buffer, int start, int end) noexcept
{
errorif(start < 0, "slice start below zero");
errorif(start > buffer.length(), "slice start greater than number of samples available");
errorif(end < start, "slice end below start");
errorif(end > buffer.length(), "slice end greater than number of samples available");
for (int ch = 0; ch < buffer.num_channels(); ++ch)
buffer.ptrs[ch] = &buffer.ptrs[ch][start];
buffer.num_samples = end - start;
return buffer;
}
/** Split the given buffer into from index. The second buffer starts with index at zeroeth index. */
template <typename BufferType>
std::tuple<BufferType, BufferType> buffer_split(BufferType buffer, int index) noexcept
{
errorif(index <= 0, "split is 0 or below");
errorif(index >= buffer.numSamples, "split greater than number of samples available");
BufferType pre = buffer_trim_length(buffer, index);
BufferType post = buffer_trim_begin(buffer, index);
return std::make_tuple(std::move(pre), std::move(post));
}
/** Create a Buffer with the data laid out into the provided vector.
The vector may be resized if needed depending on template arg. Number of channels is deducted from the template args. */
template <typename BufferType, typename VectorType, bool resizeIfNeeded = PURO_BUFFER_WRAP_VECTOR_RESIZING>
BufferType buffer_wrap_vector_per_channel(std::array<VectorType&, 2> vectors, int numSamples) noexcept
{
if (resizeIfNeeded)
{
for (auto ch=0; ch<vectors.size(); ++ch)
{
if (vectors[ch].size() < numSamples)
vectors[ch].resize(numSamples);
}
}
BufferType buffer (numSamples);
for (auto ch=0; ch<vectors.size(); ++ch)
{
buffer.channelPtr[ch] = vectors[ch].data();
}
return buffer;
}
template <typename ToBufferType, typename FromBufferType>
ToBufferType buffer_convert_to_type(FromBufferType src) noexcept
{
ToBufferType dst (src.length());
for (int ch=0; ch < dst.num_channels(); ++ch)
{
errorif (ch >= src.num_channels(), "trying to convert from less channels to a larger one");
dst.channelPtrs[ch] = src.channelPtrs[ch];
}
return dst;
}
template <typename BufferType, typename FloatType>
BufferType fit_vector_into_dynamic_buffer(std::vector<FloatType>& vector, int numChannels, int numSamples) noexcept
{
const int totLength = numChannels * numSamples;
// resize if needed
if ((int)vector.size() < totLength)
vector.resize(totLength);
return BufferType(numChannels, numSamples, vector.data());
}
template <typename BufferType, typename MultBufferType>
BufferType buffer_multiply_add(BufferType dst, const BufferType src1, const MultBufferType src2) noexcept
{
errorif(!(dst.length() == src1.length()), "dst and src1 buffer lengths don't match");
errorif(!(dst.length() == src2.length()), "dst and src2 buffer lengths don't match");
// identical channel configs
if (src1.num_channels() == src2.num_channels())
{
for (int ch = 0; ch < dst.num_channels(); ++ch)
{
math::multiply_add(dst.channel(ch), src1.channel(ch), src2.channel(ch), dst.length());
}
}
// src2 is a mono buffer
else if (src1.num_channels() > 1 && src2.num_channels() == 1)
{
for (int ch = 0; ch < dst.num_channels(); ++ch)
{
//math::multiply_add(dst.channel(ch), src1.channel(ch), src2.channel(0), dst.length());
math::multiply_add(dst.channel(ch), src1.channel(ch), src2.channel(0), dst.length());
}
}
else
{
errorif(true, "channel config not implemented");
}
return dst;
}
template <typename BufferType, typename ValueType>
BufferType buffer_multiply_with_constant_and_add(BufferType dst, const BufferType src, const ValueType multiplier) noexcept
{
errorif(dst.num_channels() != src.num_channels(), "dst and src channel number doesn't match");
errorif(dst.length() != src.length(), "dst and src1 buffer lengths don't match");
// identical channel configs
for (int ch = 0; ch < dst.num_channels(); ++ch)
{
math::multiply_add(dst.channel(ch), src.channel(ch), multiplier, dst.length());
}
return dst;
}
template <typename BufferType>
void buffer_scale(BufferType dst, const typename BufferType::value_type value) noexcept
{
for (int ch = 0; ch < dst.num_channels(); ++ch)
{
math::multiply(dst[ch], value, dst.length());
}
}
template <typename BufferType, typename MultBufferType>
BufferType buffer_multiply(BufferType dst, const MultBufferType src) noexcept
{
errorif(dst.length() != src.length(), "dst and src buffer lengths don't match");
// identical channel config
if (dst.num_channels() == src.num_channels())
{
for (int ch = 0; ch < dst.num_channels(); ++ch)
{
math::multiply(dst.channel(ch), src.channel(ch), dst.length());
}
}
// mono src, multichannel dst
else if (dst.num_channels() != src.num_channels() && src.num_channels() == 1)
{
for (int ch = 0; ch < dst.num_channels(); ++ch)
{
math::multiply(dst.channel(ch), src.channel(0), dst.length());
}
}
return dst;
}
template <typename BufferType, typename AddBufferType>
BufferType buffer_add(BufferType dst, const AddBufferType src) noexcept
{
errorif(dst.length() != src.length(), "dst and src buffer lengths don't match");
// identical channel config
if (dst.num_channels() == src.num_channels())
{
for (int ch = 0; ch < dst.num_channels(); ++ch)
{
math::add(dst[ch], src[ch], dst.length());
}
}
// mono src, multichannel dst
else if (dst.num_channels() != src.num_channels() && src.num_channels() == 1)
{
for (int ch = 0; ch < dst.num_channels(); ++ch)
{
math::add(dst[ch], src[0], dst.length());
}
}
return dst;
}
template <typename BufferType, typename SubstBufferType>
BufferType buffer_substract(BufferType dst, const SubstBufferType src) noexcept
{
errorif(dst.length() != src.length(), "dst and src buffer lengths don't match");
// identical channel config
if (dst.num_channels() == src.num_channels())
{
for (int ch = 0; ch < dst.num_channels(); ++ch)
{
math::substract(dst.channel(ch), src.channel(ch), dst.length());
}
}
// mono src, multichannel dst
else if (dst.num_channels() != src.num_channels() && src.num_channels() == 1)
{
for (int ch = 0; ch < dst.num_channels(); ++ch)
{
math::substract(dst.channel(ch), src.channel(0), dst.length());
}
}
return dst;
}
template <typename BufferType>
void buffer_copy(BufferType dst, BufferType src) noexcept
{
errorif(dst.length() != src.length(), "dst and src lengths don't match");
for (int ch=0; ch<dst.num_channels(); ++ch)
{
math::copy(dst[ch], src[ch], dst.length());
}
}
template <typename BufferType>
void buffer_copy_decimating(BufferType dst, BufferType src, int ratio) noexcept
{
errorif(dst.length() != src.length() / ratio, "dst.length (" << dst.length() << ") should be src.length/ratio (" << src.length() << "/" << ratio << ")");
errorif(src.length() % ratio != 0, "src.length should be divisible by ratio");
for (int ch=0; ch<dst.num_channels(); ++ch)
{
math::copy_decimating(dst[ch], src[ch], ratio, src.length());
}
}
template <typename BufferType>
void buffer_clear(BufferType buffer) noexcept
{
for (int ch=0; ch<buffer.num_channels(); ++ch)
{
math::set<typename BufferType::value_type>(buffer[ch], 0, buffer.length());
}
}
template <typename BufferType>
void buffer_normalise(BufferType buf)
{
using T = typename BufferType::value_type;
T max = 0;
for (auto ch=0; ch<buf.num_channels(); ++ch)
{
T* ptr = buf.channel(ch);
for (int i=0; i<buf.length(); ++i)
{
max = puro::math::max(abs(ptr[i]), max);
}
}
if (max > 0)
{
for (auto ch=0; ch<buf.num_channels(); ++ch)
{
T* ptr = buf.channel(ch);
for (auto ch=0; ch<buf.num_channels(); ++ch)
{
math::multiply(ptr, 1/max, buf.length());
}
}
}
}
} // namespace puro
<commit_msg>Buffer syntax fixes<commit_after>#pragma once
namespace puro {
/** A Wrapper around audio buffer data with helper functions for accessing and debug checks. Does not own the data. */
template <int NumChannels, typename T=float>
struct buffer
{
typedef T value_type;
static constexpr int number_of_channels = NumChannels;
int num_samples;
std::array<T*, NumChannels> ptrs;
int length() const noexcept { return num_samples; }
static constexpr int num_channels() noexcept { return NumChannels; }
T* operator[] (int ch) const
{
errorif(ch < 0 || ch >= num_channels(), "channel out of range");
return ptrs[ch];
}
// numpy-style slice operator
buffer operator() (int start, int end)
{
return buffer_slice(*this, start, end);
}
// ctors
buffer(int length) : num_samples(length) {};
buffer(int length, T** channelPtrs) : num_samples(length)
{
for (auto ch = 0; ch < num_channels(); ++ch)
ptrs[ch] = channelPtrs[ch];
}
};
/** Dynamic wrapper around audio buffer data with resizeable channel count. Does not own the data. */
template <int MaxChannels=8, typename T=float>
struct dynamic_buffer
{
typedef T value_type;
static constexpr int max_channels = MaxChannels;
int num_samples;
int used_num_channels;
std::array<T*, MaxChannels> ptrs;
int length() const { return num_samples; };
int num_channels() const { return used_num_channels; } // some more advanced class may want to redefine this
T* operator[] (int ch)
{
errorif(ch < 0 || ch >= num_channels(), "channel out of range");
return ptrs[ch];
}
// ctors
dynamic_buffer(int num_channels, int length) : used_num_channels(num_channels), num_samples(length)
{};
dynamic_buffer(int num_channels, int length, T** channelPtrs) : used_num_channels(num_channels), num_samples(length)
{
for (auto ch = 0; ch < num_channels; ++ch)
ptrs[ch] = channelPtrs[ch];
}
};
/*
template <int NumChannels, int NumSamples, typename T=float>
struct fixed_buffer
{
typedef T value_type;
static constexpr int max_channels = NumChannels;
std::array<T*, NumChannels> ptrs;
constexpr int length() const noexcept { return NumSamples; }
constexpr int num_channels() const noexcept { return NumChannels; }
T* operator[] (int ch)
{
errorif(ch < 0 || ch >= num_channels(), "channel out of range");
return ptrs[ch];
}
};
*/
/*
template <class BufferType, class Allocator = std::allocator<typename BufferType::value_type>>
struct mem_owner
{
typedef typename BufferType::value_type value_type;
static constexpr auto num_channels = BufferType::max_channels;
template <typename ...Args>
mem_owner(Args... args) : buffer(args...)
{
for (auto ch=0; ch<buffer.num_channels(); ++ch)
{
vectors[ch].resize(buffer.length());
buffer.ptrs[ch] = vectors[ch].data();
}
}
mem_owner(mem_owner &&) = delete;
mem_owner(const mem_owner &) = delete;
BufferType buffer;
std::array<std::vector<value_type, Allocator>, num_channels> vectors;
};
*/
template <class BufferType, class Allocator = std::allocator<typename BufferType::value_type>>
struct mem_buffer : public BufferType
{
typedef typename BufferType::value_type value_type;
mem_buffer() = default;
mem_buffer(mem_buffer &&) = delete;
mem_buffer(const mem_buffer &) = delete;
mem_buffer(int length) : BufferType(length)
{
for (auto ch=0; ch < BufferType::number_of_channels; ++ch)
{
vectors[ch].resize(BufferType::length());
this->ptrs[ch] = vectors[ch].data();
}
}
BufferType operator* () { return *this; }
BufferType get() { return *this; }
void operator= (BufferType new_buffer)
{
*reinterpret_cast<BufferType*>(this) = new_buffer;
}
std::array<std::vector<value_type, Allocator>, BufferType::number_of_channels> vectors;
};
////////////////////////////////
// Buffer operations
////////////////////////////////
/** Create a Buffer with the data laid out into the provided vector.
The vector may be resized if needed depending on template arg. Number of channels is deducted from the template args. */
template <typename BufferType, typename VectorType, bool resizeIfNeeded = PURO_BUFFER_WRAP_VECTOR_RESIZING>
BufferType buffer_wrap_vector(VectorType& vector, int numSamples) noexcept
{
if (resizeIfNeeded)
{
const auto totLength = BufferType::num_channels * numSamples;
if (vector.size() < totLength)
vector.resize(totLength);
}
return BufferType(numSamples, vector.data());
}
template <typename BufferType>
BufferType buffer_trim_begin(BufferType buffer, int offset) noexcept
{
errorif(offset < 0 || offset > buffer.numSamples, "offset out of bounds");
buffer.numSamples -= offset;
for (int ch = 0; ch < buffer.num_channels(); ++ch)
buffer.channelPtrs[ch] = &buffer.channelPtrs[ch][offset];
return buffer;
}
template <typename BufferType>
BufferType buffer_trim_length(BufferType buffer, int newLength) noexcept
{
errorif(newLength > buffer.numSamples, "new length out of bounds");
buffer.numSamples = math::max(newLength, 0);
return buffer;
}
/** Get a segment of a buffer with given offset and length */
template <typename BufferType>
BufferType buffer_segment(BufferType buffer, int offset, int length) noexcept
{
errorif(offset > buffer.numSamples, "segment offset greater than number of samples available");
errorif(length < 0 || length > (offset + buffer.length()), "segment length out of bounds");
for (int ch = 0; ch < buffer.num_channels(); ++ch)
buffer.channelPtrs[ch] = &buffer.channelPtrs[ch][offset];
buffer.numSamples = length;
return buffer;
}
/** Get a segment of a buffer with given offset and length */
template <typename BufferType>
BufferType buffer_slice(BufferType buffer, int start, int end) noexcept
{
errorif(start < 0, "slice start below zero");
errorif(start > buffer.length(), "slice start greater than number of samples available");
errorif(end < start, "slice end below start");
errorif(end > buffer.length(), "slice end greater than number of samples available");
for (int ch = 0; ch < buffer.num_channels(); ++ch)
buffer.ptrs[ch] = &buffer.ptrs[ch][start];
buffer.num_samples = end - start;
return buffer;
}
/** Split the given buffer into from index. The second buffer starts with index at zeroeth index. */
template <typename BufferType>
std::tuple<BufferType, BufferType> buffer_split(BufferType buffer, int index) noexcept
{
errorif(index <= 0, "split is 0 or below");
errorif(index >= buffer.numSamples, "split greater than number of samples available");
BufferType pre = buffer_trim_length(buffer, index);
BufferType post = buffer_trim_begin(buffer, index);
return std::make_tuple(std::move(pre), std::move(post));
}
/** Create a Buffer with the data laid out into the provided vector.
The vector may be resized if needed depending on template arg. Number of channels is deducted from the template args. */
template <typename BufferType, typename VectorType, bool resizeIfNeeded = PURO_BUFFER_WRAP_VECTOR_RESIZING>
BufferType buffer_wrap_vector_per_channel(std::array<VectorType&, 2> vectors, int numSamples) noexcept
{
if (resizeIfNeeded)
{
for (auto ch=0; ch<vectors.size(); ++ch)
{
if (vectors[ch].size() < numSamples)
vectors[ch].resize(numSamples);
}
}
BufferType buffer (numSamples);
for (auto ch=0; ch<vectors.size(); ++ch)
{
buffer.channelPtr[ch] = vectors[ch].data();
}
return buffer;
}
template <typename ToBufferType, typename FromBufferType>
ToBufferType buffer_convert_to_type(FromBufferType src) noexcept
{
ToBufferType dst (src.length());
for (int ch=0; ch < dst.num_channels(); ++ch)
{
errorif (ch >= src.num_channels(), "trying to convert from less channels to a larger one");
dst.channelPtrs[ch] = src.channelPtrs[ch];
}
return dst;
}
template <typename BufferType, typename FloatType>
BufferType fit_vector_into_dynamic_buffer(std::vector<FloatType>& vector, int numChannels, int numSamples) noexcept
{
const int totLength = numChannels * numSamples;
// resize if needed
if ((int)vector.size() < totLength)
vector.resize(totLength);
return BufferType(numChannels, numSamples, vector.data());
}
template <typename BufferType, typename MultBufferType>
BufferType buffer_multiply_add(BufferType dst, const BufferType src1, const MultBufferType src2) noexcept
{
errorif(!(dst.length() == src1.length()), "dst and src1 buffer lengths don't match");
errorif(!(dst.length() == src2.length()), "dst and src2 buffer lengths don't match");
// identical channel configs
if (src1.num_channels() == src2.num_channels())
{
for (int ch = 0; ch < dst.num_channels(); ++ch)
{
math::multiply_add(dst.channel(ch), src1.channel(ch), src2.channel(ch), dst.length());
}
}
// src2 is a mono buffer
else if (src1.num_channels() > 1 && src2.num_channels() == 1)
{
for (int ch = 0; ch < dst.num_channels(); ++ch)
{
//math::multiply_add(dst.channel(ch), src1.channel(ch), src2.channel(0), dst.length());
math::multiply_add(dst.channel(ch), src1.channel(ch), src2.channel(0), dst.length());
}
}
else
{
errorif(true, "channel config not implemented");
}
return dst;
}
template <typename BufferType, typename ValueType>
BufferType buffer_multiply_with_constant_and_add(BufferType dst, const BufferType src, const ValueType multiplier) noexcept
{
errorif(dst.num_channels() != src.num_channels(), "dst and src channel number doesn't match");
errorif(dst.length() != src.length(), "dst and src1 buffer lengths don't match");
// identical channel configs
for (int ch = 0; ch < dst.num_channels(); ++ch)
{
math::multiply_add(dst.channel(ch), src.channel(ch), multiplier, dst.length());
}
return dst;
}
template <typename BufferType>
void buffer_scale(BufferType dst, const typename BufferType::value_type value) noexcept
{
for (int ch = 0; ch < dst.num_channels(); ++ch)
{
math::multiply(dst[ch], value, dst.length());
}
}
template <typename BufferType, typename MultBufferType>
BufferType buffer_multiply(BufferType dst, const MultBufferType src) noexcept
{
errorif(dst.length() != src.length(), "dst and src buffer lengths don't match");
// identical channel config
if (dst.num_channels() == src.num_channels())
{
for (int ch = 0; ch < dst.num_channels(); ++ch)
{
math::multiply(dst.channel(ch), src.channel(ch), dst.length());
}
}
// mono src, multichannel dst
else if (dst.num_channels() != src.num_channels() && src.num_channels() == 1)
{
for (int ch = 0; ch < dst.num_channels(); ++ch)
{
math::multiply(dst.channel(ch), src.channel(0), dst.length());
}
}
return dst;
}
template <typename BufferType, typename AddBufferType>
BufferType buffer_add(BufferType dst, const AddBufferType src) noexcept
{
errorif(dst.length() != src.length(), "dst and src buffer lengths don't match");
// identical channel config
if (dst.num_channels() == src.num_channels())
{
for (int ch = 0; ch < dst.num_channels(); ++ch)
{
math::add(dst[ch], src[ch], dst.length());
}
}
// mono src, multichannel dst
else if (dst.num_channels() != src.num_channels() && src.num_channels() == 1)
{
for (int ch = 0; ch < dst.num_channels(); ++ch)
{
math::add(dst[ch], src[0], dst.length());
}
}
return dst;
}
template <typename BufferType, typename SubstBufferType>
BufferType buffer_substract(BufferType dst, const SubstBufferType src) noexcept
{
errorif(dst.length() != src.length(), "dst and src buffer lengths don't match");
// identical channel config
if (dst.num_channels() == src.num_channels())
{
for (int ch = 0; ch < dst.num_channels(); ++ch)
{
math::substract(dst.channel(ch), src.channel(ch), dst.length());
}
}
// mono src, multichannel dst
else if (dst.num_channels() != src.num_channels() && src.num_channels() == 1)
{
for (int ch = 0; ch < dst.num_channels(); ++ch)
{
math::substract(dst.channel(ch), src.channel(0), dst.length());
}
}
return dst;
}
template <typename BufferType>
void buffer_copy(BufferType dst, BufferType src) noexcept
{
errorif(dst.length() != src.length(), "dst and src lengths don't match");
for (int ch=0; ch<dst.num_channels(); ++ch)
{
math::copy(dst[ch], src[ch], dst.length());
}
}
template <typename BufferType>
void buffer_copy_decimating(BufferType dst, BufferType src, int ratio) noexcept
{
errorif(dst.length() != src.length() / ratio, "dst.length (" << dst.length() << ") should be src.length/ratio (" << src.length() << "/" << ratio << ")");
errorif(src.length() % ratio != 0, "src.length should be divisible by ratio");
for (int ch=0; ch<dst.num_channels(); ++ch)
{
math::copy_decimating(dst[ch], src[ch], ratio, src.length());
}
}
template <typename BufferType>
void buffer_clear(BufferType buffer) noexcept
{
for (int ch=0; ch<buffer.num_channels(); ++ch)
{
math::set<typename BufferType::value_type>(buffer[ch], 0, buffer.length());
}
}
template <typename BufferType>
void buffer_normalise(BufferType buf)
{
using T = typename BufferType::value_type;
T max = 0;
for (auto ch=0; ch<buf.num_channels(); ++ch)
{
T* ptr = buf[ch];
for (int i=0; i<buf.length(); ++i)
{
max = puro::math::max(abs(ptr[i]), max);
}
}
if (max > 0)
{
for (auto ch=0; ch<buf.num_channels(); ++ch)
{
T* ptr = buf[ch];
for (auto ch=0; ch<buf.num_channels(); ++ch)
{
math::multiply(ptr, 1/max, buf.length());
}
}
}
}
} // namespace puro
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2001 The Apache Software Foundation. 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include "FunctionEvaluate.hpp"
#include <DOMSupport/PrefixResolver.hpp>
#include <XPath/XObjectFactory.hpp>
#include <XPath/XPath.hpp>
#include <XPath/XPathProcessorImpl.hpp>
FunctionEvaluate::FunctionEvaluate()
{
}
FunctionEvaluate::~FunctionEvaluate()
{
}
XObjectPtr
FunctionEvaluate::execute(
XPathExecutionContext& executionContext,
XalanNode* context)
{
executionContext.error(getError(), context);
return XObjectPtr(0);
}
XObjectPtr
FunctionEvaluate::execute(
XPathExecutionContext& executionContext,
XalanNode* context,
const XObjectPtr arg1)
{
assert(arg1.null() == false);
const PrefixResolver* const theResolver =
executionContext.getPrefixResolver();
if (theResolver == 0)
{
executionContext.warn(
"No prefix resolver available in evaluate()!",
context);
return arg1;
}
else
{
const XalanDOMString& theString =
arg1->str();
if (length(theString) == 0)
{
return XObjectPtr(0);
}
else
{
XPathProcessorImpl theProcessor;
XPath theXPath;
theProcessor.initXPath(
theXPath,
theString,
*theResolver);
return theXPath.execute(context, *theResolver, executionContext);
}
}
}
XObjectPtr
FunctionEvaluate::execute(
XPathExecutionContext& executionContext,
XalanNode* context,
const XObjectPtr /* arg1 */,
const XObjectPtr /* arg2 */)
{
executionContext.error(getError(), context);
return XObjectPtr(0);
}
XObjectPtr
FunctionEvaluate::execute(
XPathExecutionContext& executionContext,
XalanNode* context,
const XObjectPtr /* arg1 */,
const XObjectPtr /* arg2 */,
const XObjectPtr /* arg3 */)
{
executionContext.error(getError(), context);
return XObjectPtr(0);
}
XObjectPtr
FunctionEvaluate::execute(
XPathExecutionContext& executionContext,
XalanNode* context,
int /* opPos */,
const XObjectArgVectorType& args)
{
if (args.size() != 1)
{
executionContext.error(getError(), context);
return XObjectPtr(0);
}
else
{
return execute(executionContext, context, args[0]);
}
}
#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)
Function*
#else
FunctionEvaluate*
#endif
FunctionEvaluate::clone() const
{
return new FunctionEvaluate(*this);
}
const XalanDOMString
FunctionEvaluate::getError() const
{
return XALAN_STATIC_UCODE_STRING("The evaluate() function takes one argument");
}
<commit_msg>Fixed include file problem.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2001 The Apache Software Foundation. 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include "FunctionEvaluate.hpp"
#include <PlatformSupport/PrefixResolver.hpp>
#include <XPath/XObjectFactory.hpp>
#include <XPath/XPath.hpp>
#include <XPath/XPathProcessorImpl.hpp>
FunctionEvaluate::FunctionEvaluate()
{
}
FunctionEvaluate::~FunctionEvaluate()
{
}
XObjectPtr
FunctionEvaluate::execute(
XPathExecutionContext& executionContext,
XalanNode* context)
{
executionContext.error(getError(), context);
return XObjectPtr(0);
}
XObjectPtr
FunctionEvaluate::execute(
XPathExecutionContext& executionContext,
XalanNode* context,
const XObjectPtr arg1)
{
assert(arg1.null() == false);
const PrefixResolver* const theResolver =
executionContext.getPrefixResolver();
if (theResolver == 0)
{
executionContext.warn(
"No prefix resolver available in evaluate()!",
context);
return arg1;
}
else
{
const XalanDOMString& theString =
arg1->str();
if (length(theString) == 0)
{
return XObjectPtr(0);
}
else
{
XPathProcessorImpl theProcessor;
XPath theXPath;
theProcessor.initXPath(
theXPath,
theString,
*theResolver);
return theXPath.execute(context, *theResolver, executionContext);
}
}
}
XObjectPtr
FunctionEvaluate::execute(
XPathExecutionContext& executionContext,
XalanNode* context,
const XObjectPtr /* arg1 */,
const XObjectPtr /* arg2 */)
{
executionContext.error(getError(), context);
return XObjectPtr(0);
}
XObjectPtr
FunctionEvaluate::execute(
XPathExecutionContext& executionContext,
XalanNode* context,
const XObjectPtr /* arg1 */,
const XObjectPtr /* arg2 */,
const XObjectPtr /* arg3 */)
{
executionContext.error(getError(), context);
return XObjectPtr(0);
}
XObjectPtr
FunctionEvaluate::execute(
XPathExecutionContext& executionContext,
XalanNode* context,
int /* opPos */,
const XObjectArgVectorType& args)
{
if (args.size() != 1)
{
executionContext.error(getError(), context);
return XObjectPtr(0);
}
else
{
return execute(executionContext, context, args[0]);
}
}
#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)
Function*
#else
FunctionEvaluate*
#endif
FunctionEvaluate::clone() const
{
return new FunctionEvaluate(*this);
}
const XalanDOMString
FunctionEvaluate::getError() const
{
return XALAN_STATIC_UCODE_STRING("The evaluate() function takes one argument");
}
<|endoftext|>
|
<commit_before>/*
* Vulkan
*
* Copyright (C) 2015 LunarG, Inc.
*
* 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 <string.h>
#include <stdlib.h>
#include <assert.h>
#include <map>
#include <unordered_map>
#include <map>
#include <vector>
#include "loader_platform.h"
#include "vk_dispatch_table_helper.h"
#include "vkLayer.h"
// The following is #included again to catch certain OS-specific functions
// being used:
#include "loader_platform.h"
#include "SPIRV/spirv.h"
static std::unordered_map<void *, VkLayerDispatchTable *> tableMap;
struct shader_source {
std::vector<uint32_t> words;
shader_source(VkShaderCreateInfo const *pCreateInfo) :
words((uint32_t *)pCreateInfo->pCode, (uint32_t *)pCreateInfo->pCode + pCreateInfo->codeSize / sizeof(uint32_t)) {
}
};
static std::unordered_map<void *, shader_source *> shader_map;
static VkLayerDispatchTable * initLayerTable(const VkBaseLayerObject *gpuw)
{
VkLayerDispatchTable *pTable;
assert(gpuw);
std::unordered_map<void *, VkLayerDispatchTable *>::const_iterator it = tableMap.find((void *) gpuw->baseObject);
if (it == tableMap.end())
{
pTable = new VkLayerDispatchTable;
tableMap[(void *) gpuw->baseObject] = pTable;
} else
{
return it->second;
}
layer_initialize_dispatch_table(pTable, gpuw->pGPA, (VkPhysicalGpu) gpuw->nextObject);
return pTable;
}
VK_LAYER_EXPORT VkResult VKAPI vkCreateDevice(VkPhysicalGpu gpu, const VkDeviceCreateInfo* pCreateInfo, VkDevice* pDevice)
{
VkLayerDispatchTable* pTable = tableMap[gpu];
VkResult result = pTable->CreateDevice(gpu, pCreateInfo, pDevice);
// create a mapping for the device object into the dispatch table
tableMap.emplace(*pDevice, pTable);
return result;
}
VK_LAYER_EXPORT VkResult VKAPI vkEnumerateLayers(VkPhysicalGpu gpu, size_t maxLayerCount, size_t maxStringSize, size_t* pOutLayerCount, char* const* pOutLayers, void* pReserved)
{
if (pOutLayerCount == NULL || pOutLayers == NULL || pOutLayers[0] == NULL || pOutLayers[1] == NULL || pReserved == NULL)
return VK_ERROR_INVALID_POINTER;
if (maxLayerCount < 1)
return VK_ERROR_INITIALIZATION_FAILED;
*pOutLayerCount = 1;
strncpy((char *) pOutLayers[0], "ShaderChecker", maxStringSize);
return VK_SUCCESS;
}
struct extProps {
uint32_t version;
const char * const name;
};
#define SHADER_CHECKER_LAYER_EXT_ARRAY_SIZE 1
static const struct extProps shaderCheckerExts[SHADER_CHECKER_LAYER_EXT_ARRAY_SIZE] = {
// TODO what is the version?
0x10, "ShaderChecker",
};
VK_LAYER_EXPORT VkResult VKAPI vkGetGlobalExtensionInfo(
VkExtensionInfoType infoType,
uint32_t extensionIndex,
size_t* pDataSize,
void* pData)
{
VkResult result;
/* This entrypoint is NOT going to init it's own dispatch table since loader calls here early */
VkExtensionProperties *ext_props;
uint32_t *count;
if (pDataSize == NULL)
return VK_ERROR_INVALID_POINTER;
switch (infoType) {
case VK_EXTENSION_INFO_TYPE_COUNT:
*pDataSize = sizeof(uint32_t);
if (pData == NULL)
return VK_SUCCESS;
count = (uint32_t *) pData;
*count = SHADER_CHECKER_LAYER_EXT_ARRAY_SIZE;
break;
case VK_EXTENSION_INFO_TYPE_PROPERTIES:
*pDataSize = sizeof(VkExtensionProperties);
if (pData == NULL)
return VK_SUCCESS;
if (extensionIndex >= SHADER_CHECKER_LAYER_EXT_ARRAY_SIZE)
return VK_ERROR_INVALID_VALUE;
ext_props = (VkExtensionProperties *) pData;
ext_props->version = shaderCheckerExts[extensionIndex].version;
strncpy(ext_props->extName, shaderCheckerExts[extensionIndex].name,
VK_MAX_EXTENSION_NAME);
ext_props->extName[VK_MAX_EXTENSION_NAME - 1] = '\0';
break;
default:
return VK_ERROR_INVALID_VALUE;
};
return VK_SUCCESS;
}
static int
value_or_default(std::unordered_map<unsigned, unsigned> const &map, unsigned id, int def)
{
auto it = map.find(id);
if (it == map.end())
return def;
else
return it->second;
}
struct interface_var {
uint32_t id;
uint32_t type_id;
/* TODO: collect the name, too? Isn't required to be present. */
};
static void
collect_interface_by_location(shader_source const *src, spv::StorageClass interface,
std::map<uint32_t, interface_var> &out,
std::map<uint32_t, interface_var> &builtins_out)
{
unsigned int const *code = (unsigned int const *)&src->words[0];
size_t size = src->words.size();
if (code[0] != spv::MagicNumber) {
printf("Invalid magic.\n");
return;
}
std::unordered_map<unsigned, unsigned> var_locations;
std::unordered_map<unsigned, unsigned> var_builtins;
unsigned word = 5;
while (word < size) {
unsigned opcode = code[word] & 0x0ffffu;
unsigned oplen = (code[word] & 0xffff0000u) >> 16;
/* We consider two interface models: SSO rendezvous-by-location, and
* builtins. Complain about anything that fits neither model.
*/
if (opcode == spv::OpDecorate) {
if (code[word+2] == spv::DecLocation) {
var_locations[code[word+1]] = code[word+3];
}
if (code[word+2] == spv::DecBuiltIn) {
var_builtins[code[word+1]] = code[word+3];
}
}
/* TODO: handle grouped decorations */
/* TODO: handle index=1 dual source outputs from FS -- two vars will
* have the same location, and we DONT want to clobber. */
if (opcode == spv::OpVariable && code[word+3] == interface) {
int location = value_or_default(var_locations, code[word+2], -1);
int builtin = value_or_default(var_builtins, code[word+2], -1);
if (location == -1 && builtin == -1) {
/* No location defined, and not bound to an API builtin.
* The spec says nothing about how this case works (or doesn't)
* for interface matching.
*/
printf("WARN: var %d (type %d) in %s interface has no Location or Builtin decoration\n",
code[word+2], code[word+1], interface == spv::StorageInput ? "input" : "output");
}
else if (location != -1) {
/* A user-defined interface variable, with a location. */
interface_var v;
v.id = code[word+2];
v.type_id = code[word+1];
out[location] = v;
}
else {
/* A builtin interface variable */
interface_var v;
v.id = code[word+2];
v.type_id = code[word+1];
builtins_out[builtin] = v;
}
}
word += oplen;
}
}
VK_LAYER_EXPORT VkResult VKAPI vkCreateShader(VkDevice device, const VkShaderCreateInfo *pCreateInfo,
VkShader *pShader)
{
VkLayerDispatchTable* pTable = tableMap[(VkBaseLayerObject *)device];
VkResult res = pTable->CreateShader(device, pCreateInfo, pShader);
shader_map[(VkBaseLayerObject *) *pShader] = new shader_source(pCreateInfo);
return res;
}
static void
validate_interface_between_stages(shader_source const *producer, char const *producer_name,
shader_source const *consumer, char const *consumer_name)
{
std::map<uint32_t, interface_var> outputs;
std::map<uint32_t, interface_var> inputs;
std::map<uint32_t, interface_var> builtin_outputs;
std::map<uint32_t, interface_var> builtin_inputs;
printf("Begin validate_interface_between_stages %s -> %s\n",
producer_name, consumer_name);
collect_interface_by_location(producer, spv::StorageOutput, outputs, builtin_outputs);
collect_interface_by_location(consumer, spv::StorageInput, inputs, builtin_inputs);
auto a_it = outputs.begin();
auto b_it = inputs.begin();
/* maps sorted by key (location); walk them together to find mismatches */
while (a_it != outputs.end() || b_it != inputs.end()) {
if (b_it == inputs.end() || a_it->first < b_it->first) {
printf(" WARN: %s writes to output location %d which is not consumed by %s\n",
producer_name, a_it->first, consumer_name);
a_it++;
}
else if (a_it == outputs.end() || a_it->first > b_it->first) {
printf(" ERR: %s consumes input location %d which is not written by %s\n",
consumer_name, b_it->first, producer_name);
b_it++;
}
else {
printf(" OK: match on location %d\n",
a_it->first);
/* TODO: typecheck */
a_it++;
b_it++;
}
}
printf("End validate_interface_between_stages\n");
}
VK_LAYER_EXPORT VkResult VKAPI vkCreateGraphicsPipeline(VkDevice device,
const VkGraphicsPipelineCreateInfo *pCreateInfo,
VkPipeline *pPipeline)
{
/* TODO: run cross-stage validation */
/* - Validate vertex fetch -> VS interface */
/* - Validate FS output -> CB */
/* - Support GS, TCS, TES stages */
/* We seem to allow pipeline stages to be specified out of order, so collect and identify them
* before trying to do anything more: */
shader_source const *vs_source = 0;
shader_source const *fs_source = 0;
VkPipelineCbStateCreateInfo const *cb = 0;
VkPipelineVertexInputCreateInfo const *vi = 0;
for (auto stage = pCreateInfo; stage; stage = (decltype(stage))stage->pNext) {
if (stage->sType == VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO) {
auto shader_stage = (VkPipelineShaderStageCreateInfo const *)stage;
if (shader_stage->shader.stage == VK_SHADER_STAGE_VERTEX)
vs_source = shader_map[(void *)(shader_stage->shader.shader)];
else if (shader_stage->shader.stage == VK_SHADER_STAGE_FRAGMENT)
fs_source = shader_map[(void *)(shader_stage->shader.shader)];
else
printf("Unknown shader stage %d\n", shader_stage->shader.stage);
}
else if (stage->sType == VK_STRUCTURE_TYPE_PIPELINE_CB_STATE_CREATE_INFO) {
cb = (VkPipelineCbStateCreateInfo const *)stage;
}
else if (stage->sType == VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_CREATE_INFO) {
vi = (VkPipelineVertexInputCreateInfo const *)stage;
}
}
printf("Pipeline: vi=%p vs=%p fs=%p cb=%p\n", vi, vs_source, fs_source, cb);
if (vs_source && fs_source) {
validate_interface_between_stages(vs_source, "vertex shader",
fs_source, "fragment shader");
}
VkLayerDispatchTable *pTable = tableMap[(VkBaseLayerObject *)device];
VkResult res = pTable->CreateGraphicsPipeline(device, pCreateInfo, pPipeline);
return res;
}
VK_LAYER_EXPORT void * VKAPI vkGetProcAddr(VkPhysicalGpu gpu, const char* pName)
{
if (gpu == NULL)
return NULL;
initLayerTable((const VkBaseLayerObject *) gpu);
#define ADD_HOOK(fn) \
if (!strncmp(#fn, pName, sizeof(#fn))) \
return (void *) fn
ADD_HOOK(vkGetProcAddr);
ADD_HOOK(vkEnumerateLayers);
ADD_HOOK(vkCreateDevice);
ADD_HOOK(vkCreateShader);
ADD_HOOK(vkCreateGraphicsPipeline);
VkBaseLayerObject* gpuw = (VkBaseLayerObject *) gpu;
if (gpuw->pGPA == NULL)
return NULL;
return gpuw->pGPA((VkPhysicalGpu) gpuw->nextObject, pName);
}
<commit_msg>shader_checker: validate vertex attribs against vs inputs<commit_after>/*
* Vulkan
*
* Copyright (C) 2015 LunarG, Inc.
*
* 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 <string.h>
#include <stdlib.h>
#include <assert.h>
#include <map>
#include <unordered_map>
#include <map>
#include <vector>
#include "loader_platform.h"
#include "vk_dispatch_table_helper.h"
#include "vkLayer.h"
// The following is #included again to catch certain OS-specific functions
// being used:
#include "loader_platform.h"
#include "SPIRV/spirv.h"
static std::unordered_map<void *, VkLayerDispatchTable *> tableMap;
struct shader_source {
std::vector<uint32_t> words;
shader_source(VkShaderCreateInfo const *pCreateInfo) :
words((uint32_t *)pCreateInfo->pCode, (uint32_t *)pCreateInfo->pCode + pCreateInfo->codeSize / sizeof(uint32_t)) {
}
};
static std::unordered_map<void *, shader_source *> shader_map;
static VkLayerDispatchTable * initLayerTable(const VkBaseLayerObject *gpuw)
{
VkLayerDispatchTable *pTable;
assert(gpuw);
std::unordered_map<void *, VkLayerDispatchTable *>::const_iterator it = tableMap.find((void *) gpuw->baseObject);
if (it == tableMap.end())
{
pTable = new VkLayerDispatchTable;
tableMap[(void *) gpuw->baseObject] = pTable;
} else
{
return it->second;
}
layer_initialize_dispatch_table(pTable, gpuw->pGPA, (VkPhysicalGpu) gpuw->nextObject);
return pTable;
}
VK_LAYER_EXPORT VkResult VKAPI vkCreateDevice(VkPhysicalGpu gpu, const VkDeviceCreateInfo* pCreateInfo, VkDevice* pDevice)
{
VkLayerDispatchTable* pTable = tableMap[gpu];
VkResult result = pTable->CreateDevice(gpu, pCreateInfo, pDevice);
// create a mapping for the device object into the dispatch table
tableMap.emplace(*pDevice, pTable);
return result;
}
VK_LAYER_EXPORT VkResult VKAPI vkEnumerateLayers(VkPhysicalGpu gpu, size_t maxLayerCount, size_t maxStringSize, size_t* pOutLayerCount, char* const* pOutLayers, void* pReserved)
{
if (pOutLayerCount == NULL || pOutLayers == NULL || pOutLayers[0] == NULL || pOutLayers[1] == NULL || pReserved == NULL)
return VK_ERROR_INVALID_POINTER;
if (maxLayerCount < 1)
return VK_ERROR_INITIALIZATION_FAILED;
*pOutLayerCount = 1;
strncpy((char *) pOutLayers[0], "ShaderChecker", maxStringSize);
return VK_SUCCESS;
}
struct extProps {
uint32_t version;
const char * const name;
};
#define SHADER_CHECKER_LAYER_EXT_ARRAY_SIZE 1
static const struct extProps shaderCheckerExts[SHADER_CHECKER_LAYER_EXT_ARRAY_SIZE] = {
// TODO what is the version?
0x10, "ShaderChecker",
};
VK_LAYER_EXPORT VkResult VKAPI vkGetGlobalExtensionInfo(
VkExtensionInfoType infoType,
uint32_t extensionIndex,
size_t* pDataSize,
void* pData)
{
VkResult result;
/* This entrypoint is NOT going to init it's own dispatch table since loader calls here early */
VkExtensionProperties *ext_props;
uint32_t *count;
if (pDataSize == NULL)
return VK_ERROR_INVALID_POINTER;
switch (infoType) {
case VK_EXTENSION_INFO_TYPE_COUNT:
*pDataSize = sizeof(uint32_t);
if (pData == NULL)
return VK_SUCCESS;
count = (uint32_t *) pData;
*count = SHADER_CHECKER_LAYER_EXT_ARRAY_SIZE;
break;
case VK_EXTENSION_INFO_TYPE_PROPERTIES:
*pDataSize = sizeof(VkExtensionProperties);
if (pData == NULL)
return VK_SUCCESS;
if (extensionIndex >= SHADER_CHECKER_LAYER_EXT_ARRAY_SIZE)
return VK_ERROR_INVALID_VALUE;
ext_props = (VkExtensionProperties *) pData;
ext_props->version = shaderCheckerExts[extensionIndex].version;
strncpy(ext_props->extName, shaderCheckerExts[extensionIndex].name,
VK_MAX_EXTENSION_NAME);
ext_props->extName[VK_MAX_EXTENSION_NAME - 1] = '\0';
break;
default:
return VK_ERROR_INVALID_VALUE;
};
return VK_SUCCESS;
}
static int
value_or_default(std::unordered_map<unsigned, unsigned> const &map, unsigned id, int def)
{
auto it = map.find(id);
if (it == map.end())
return def;
else
return it->second;
}
struct interface_var {
uint32_t id;
uint32_t type_id;
/* TODO: collect the name, too? Isn't required to be present. */
};
static void
collect_interface_by_location(shader_source const *src, spv::StorageClass interface,
std::map<uint32_t, interface_var> &out,
std::map<uint32_t, interface_var> &builtins_out)
{
unsigned int const *code = (unsigned int const *)&src->words[0];
size_t size = src->words.size();
if (code[0] != spv::MagicNumber) {
printf("Invalid magic.\n");
return;
}
std::unordered_map<unsigned, unsigned> var_locations;
std::unordered_map<unsigned, unsigned> var_builtins;
unsigned word = 5;
while (word < size) {
unsigned opcode = code[word] & 0x0ffffu;
unsigned oplen = (code[word] & 0xffff0000u) >> 16;
/* We consider two interface models: SSO rendezvous-by-location, and
* builtins. Complain about anything that fits neither model.
*/
if (opcode == spv::OpDecorate) {
if (code[word+2] == spv::DecLocation) {
var_locations[code[word+1]] = code[word+3];
}
if (code[word+2] == spv::DecBuiltIn) {
var_builtins[code[word+1]] = code[word+3];
}
}
/* TODO: handle grouped decorations */
/* TODO: handle index=1 dual source outputs from FS -- two vars will
* have the same location, and we DONT want to clobber. */
if (opcode == spv::OpVariable && code[word+3] == interface) {
int location = value_or_default(var_locations, code[word+2], -1);
int builtin = value_or_default(var_builtins, code[word+2], -1);
if (location == -1 && builtin == -1) {
/* No location defined, and not bound to an API builtin.
* The spec says nothing about how this case works (or doesn't)
* for interface matching.
*/
printf("WARN: var %d (type %d) in %s interface has no Location or Builtin decoration\n",
code[word+2], code[word+1], interface == spv::StorageInput ? "input" : "output");
}
else if (location != -1) {
/* A user-defined interface variable, with a location. */
interface_var v;
v.id = code[word+2];
v.type_id = code[word+1];
out[location] = v;
}
else {
/* A builtin interface variable */
interface_var v;
v.id = code[word+2];
v.type_id = code[word+1];
builtins_out[builtin] = v;
}
}
word += oplen;
}
}
VK_LAYER_EXPORT VkResult VKAPI vkCreateShader(VkDevice device, const VkShaderCreateInfo *pCreateInfo,
VkShader *pShader)
{
VkLayerDispatchTable* pTable = tableMap[(VkBaseLayerObject *)device];
VkResult res = pTable->CreateShader(device, pCreateInfo, pShader);
shader_map[(VkBaseLayerObject *) *pShader] = new shader_source(pCreateInfo);
return res;
}
static void
validate_interface_between_stages(shader_source const *producer, char const *producer_name,
shader_source const *consumer, char const *consumer_name)
{
std::map<uint32_t, interface_var> outputs;
std::map<uint32_t, interface_var> inputs;
std::map<uint32_t, interface_var> builtin_outputs;
std::map<uint32_t, interface_var> builtin_inputs;
printf("Begin validate_interface_between_stages %s -> %s\n",
producer_name, consumer_name);
collect_interface_by_location(producer, spv::StorageOutput, outputs, builtin_outputs);
collect_interface_by_location(consumer, spv::StorageInput, inputs, builtin_inputs);
auto a_it = outputs.begin();
auto b_it = inputs.begin();
/* maps sorted by key (location); walk them together to find mismatches */
while (a_it != outputs.end() || b_it != inputs.end()) {
if (b_it == inputs.end() || a_it->first < b_it->first) {
printf(" WARN: %s writes to output location %d which is not consumed by %s\n",
producer_name, a_it->first, consumer_name);
a_it++;
}
else if (a_it == outputs.end() || a_it->first > b_it->first) {
printf(" ERR: %s consumes input location %d which is not written by %s\n",
consumer_name, b_it->first, producer_name);
b_it++;
}
else {
printf(" OK: match on location %d\n",
a_it->first);
/* TODO: typecheck */
a_it++;
b_it++;
}
}
printf("End validate_interface_between_stages\n");
}
static void
validate_vi_against_vs_inputs(VkPipelineVertexInputCreateInfo const *vi, shader_source const *vs)
{
std::map<uint32_t, interface_var> inputs;
/* we collect builtin inputs, but they will never appear in the VI state --
* the vs builtin inputs are generated in the pipeline, not sourced from buffers (VertexID, etc)
*/
std::map<uint32_t, interface_var> builtin_inputs;
printf("Begin validate_vi_against_vs_inputs\n");
collect_interface_by_location(vs, spv::StorageInput, inputs, builtin_inputs);
/* Build index by location */
std::map<uint32_t, VkVertexInputAttributeDescription const *> attribs;
for (int i = 0; i < vi->attributeCount; i++)
attribs[vi->pVertexAttributeDescriptions[i].location] = &vi->pVertexAttributeDescriptions[i];
auto it_a = attribs.begin();
auto it_b = inputs.begin();
while (it_a != attribs.end() || it_b != inputs.end()) {
if (it_b == inputs.end() || it_a->first < it_b->first) {
printf(" WARN: attribute at location %d not consumed by the vertex shader\n",
it_a->first);
it_a++;
}
else if (it_a == attribs.end() || it_b->first < it_a->first) {
printf(" ERR: vertex shader consumes input at location %d but not provided\n",
it_b->first);
it_b++;
}
else {
/* TODO: type check */
printf(" OK: match on attribute location %d\n",
it_a->first);
it_a++;
it_b++;
}
}
printf("End validate_vi_against_vs_inputs\n");
}
VK_LAYER_EXPORT VkResult VKAPI vkCreateGraphicsPipeline(VkDevice device,
const VkGraphicsPipelineCreateInfo *pCreateInfo,
VkPipeline *pPipeline)
{
/* TODO: run cross-stage validation */
/* - Validate FS output -> CB */
/* - Support GS, TCS, TES stages */
/* We seem to allow pipeline stages to be specified out of order, so collect and identify them
* before trying to do anything more: */
shader_source const *vs_source = 0;
shader_source const *fs_source = 0;
VkPipelineCbStateCreateInfo const *cb = 0;
VkPipelineVertexInputCreateInfo const *vi = 0;
for (auto stage = pCreateInfo; stage; stage = (decltype(stage))stage->pNext) {
if (stage->sType == VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO) {
auto shader_stage = (VkPipelineShaderStageCreateInfo const *)stage;
if (shader_stage->shader.stage == VK_SHADER_STAGE_VERTEX)
vs_source = shader_map[(void *)(shader_stage->shader.shader)];
else if (shader_stage->shader.stage == VK_SHADER_STAGE_FRAGMENT)
fs_source = shader_map[(void *)(shader_stage->shader.shader)];
else
printf("Unknown shader stage %d\n", shader_stage->shader.stage);
}
else if (stage->sType == VK_STRUCTURE_TYPE_PIPELINE_CB_STATE_CREATE_INFO) {
cb = (VkPipelineCbStateCreateInfo const *)stage;
}
else if (stage->sType == VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_CREATE_INFO) {
vi = (VkPipelineVertexInputCreateInfo const *)stage;
}
}
printf("Pipeline: vi=%p vs=%p fs=%p cb=%p\n", vi, vs_source, fs_source, cb);
if (vi && vs_source) {
validate_vi_against_vs_inputs(vi, vs_source);
}
if (vs_source && fs_source) {
validate_interface_between_stages(vs_source, "vertex shader",
fs_source, "fragment shader");
}
VkLayerDispatchTable *pTable = tableMap[(VkBaseLayerObject *)device];
VkResult res = pTable->CreateGraphicsPipeline(device, pCreateInfo, pPipeline);
return res;
}
VK_LAYER_EXPORT void * VKAPI vkGetProcAddr(VkPhysicalGpu gpu, const char* pName)
{
if (gpu == NULL)
return NULL;
initLayerTable((const VkBaseLayerObject *) gpu);
#define ADD_HOOK(fn) \
if (!strncmp(#fn, pName, sizeof(#fn))) \
return (void *) fn
ADD_HOOK(vkGetProcAddr);
ADD_HOOK(vkEnumerateLayers);
ADD_HOOK(vkCreateDevice);
ADD_HOOK(vkCreateShader);
ADD_HOOK(vkCreateGraphicsPipeline);
VkBaseLayerObject* gpuw = (VkBaseLayerObject *) gpu;
if (gpuw->pGPA == NULL)
return NULL;
return gpuw->pGPA((VkPhysicalGpu) gpuw->nextObject, pName);
}
<|endoftext|>
|
<commit_before>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "Backend.h"
JITOutput::JITOutput(JITOutputIDL * outputData) :
m_outputData(outputData)
{
}
void
JITOutput::SetHasJITStackClosure()
{
m_outputData->hasJittedStackClosure = true;
}
void
JITOutput::SetVarSlotsOffset(int32 offset)
{
m_outputData->localVarSlotsOffset = offset;
}
void
JITOutput::SetVarChangedOffset(int32 offset)
{
m_outputData->localVarChangedOffset = offset;
}
void
JITOutput::SetHasBailoutInstr(bool val)
{
m_outputData->hasBailoutInstr = val;
}
void
JITOutput::SetArgUsedForBranch(uint8 param)
{
Assert(param > 0);
Assert(param < Js::Constants::MaximumArgumentCountForConstantArgumentInlining);
m_outputData->argUsedForBranch |= (1 << (param - 1));
}
void
JITOutput::SetFrameHeight(uint val)
{
m_outputData->frameHeight = val;
}
void
JITOutput::RecordThrowMap(Js::ThrowMapEntry * throwMap, uint mapCount)
{
m_outputData->throwMapOffset = NativeCodeData::GetDataTotalOffset(throwMap);
m_outputData->throwMapCount = mapCount;
}
uint16
JITOutput::GetArgUsedForBranch() const
{
return m_outputData->argUsedForBranch;
}
intptr_t
JITOutput::GetCodeAddress() const
{
return (intptr_t)m_outputData->codeAddress;
}
void
JITOutput::SetCodeAddress(intptr_t addr)
{
m_outputData->codeAddress = addr;
}
size_t
JITOutput::GetCodeSize() const
{
return (size_t)m_outputData->codeSize;
}
ushort
JITOutput::GetPdataCount() const
{
return m_outputData->pdataCount;
}
ushort
JITOutput::GetXdataSize() const
{
return m_outputData->xdataSize;
}
EmitBufferAllocation *
JITOutput::RecordNativeCodeSize(Func *func, uint32 bytes, ushort pdataCount, ushort xdataSize)
{
BYTE *buffer;
#if defined(_M_ARM32_OR_ARM64)
bool canAllocInPreReservedHeapPageSegment = false;
#else
bool canAllocInPreReservedHeapPageSegment = func->CanAllocInPreReservedHeapPageSegment();
#endif
EmitBufferAllocation *allocation = func->GetEmitBufferManager()->AllocateBuffer(bytes, &buffer, pdataCount, xdataSize, canAllocInPreReservedHeapPageSegment, true);
#if DBG
MEMORY_BASIC_INFORMATION memBasicInfo;
size_t resultBytes = VirtualQueryEx(func->GetThreadContextInfo()->GetProcessHandle(), allocation->allocation->address, &memBasicInfo, sizeof(memBasicInfo));
Assert(resultBytes != 0 && memBasicInfo.Protect == PAGE_EXECUTE);
#endif
Assert(allocation != nullptr);
if (buffer == nullptr)
Js::Throw::OutOfMemory();
m_outputData->codeAddress = (intptr_t)buffer;
m_outputData->codeSize = bytes;
m_outputData->pdataCount = pdataCount;
m_outputData->xdataSize = xdataSize;
m_outputData->isInPrereservedRegion = allocation->inPrereservedRegion;
return allocation;
}
void
JITOutput::RecordNativeCode(Func *func, const BYTE* sourceBuffer, EmitBufferAllocation * alloc)
{
Assert(m_outputData->codeAddress == (intptr_t)alloc->allocation->address);
if (!func->GetEmitBufferManager()->CommitBuffer(alloc, (BYTE *)m_outputData->codeAddress, m_outputData->codeSize, sourceBuffer))
{
Js::Throw::OutOfMemory();
}
#if DBG_DUMP
if (func->IsLoopBody())
{
func->GetEmitBufferManager()->totalBytesLoopBody += m_outputData->codeSize;
}
#endif
}
void
JITOutput::RecordInlineeFrameOffsetsInfo(unsigned int offsetsArrayOffset, unsigned int offsetsArrayCount)
{
m_outputData->inlineeFrameOffsetArrayOffset = offsetsArrayOffset;
m_outputData->inlineeFrameOffsetArrayCount = offsetsArrayCount;
}
#if _M_X64
size_t
JITOutput::RecordUnwindInfo(size_t offset, BYTE *unwindInfo, size_t size, BYTE * xdataAddr, HANDLE processHandle)
{
Assert(offset == 0);
Assert(XDATA_SIZE >= size);
ChakraMemCopy(xdataAddr, XDATA_SIZE, unwindInfo, size, processHandle);
m_outputData->xdataAddr = (intptr_t)xdataAddr;
return 0;
}
#elif _M_ARM
size_t
JITOutput::RecordUnwindInfo(size_t offset, BYTE *unwindInfo, size_t size, BYTE * xdataAddr, HANDLE processHandle)
{
BYTE *xdataFinal = xdataAddr + offset;
Assert(xdataFinal);
Assert(((DWORD)xdataFinal & 0x3) == 0); // 4 byte aligned
memcpy_s(xdataFinal, size, unwindInfo, size);
return (size_t)xdataFinal;
}
void
JITOutput::RecordXData(BYTE * xdata)
{
m_outputData->xdataOffset = NativeCodeData::GetDataTotalOffset(xdata);
}
#endif
void
JITOutput::FinalizeNativeCode(Func *func, EmitBufferAllocation * alloc)
{
func->GetEmitBufferManager()->CompletePreviousAllocation(alloc);
if (!func->IsOOPJIT())
{
func->GetInProcJITEntryPointInfo()->SetInProcJITNativeCodeData(func->GetNativeCodeDataAllocator()->Finalize());
func->GetInProcJITEntryPointInfo()->GetJitTransferData()->SetRawData(func->GetTransferDataAllocator()->Finalize());
#if !FLOATVAR
CodeGenNumberChunk * numberChunks = func->GetNumberAllocator()->Finalize();
func->GetInProcJITEntryPointInfo()->SetNumberChunks(numberChunks);
#endif
}
}
JITOutputIDL *
JITOutput::GetOutputData()
{
return m_outputData;
}
<commit_msg>remove invalid assert for jit page state<commit_after>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "Backend.h"
JITOutput::JITOutput(JITOutputIDL * outputData) :
m_outputData(outputData)
{
}
void
JITOutput::SetHasJITStackClosure()
{
m_outputData->hasJittedStackClosure = true;
}
void
JITOutput::SetVarSlotsOffset(int32 offset)
{
m_outputData->localVarSlotsOffset = offset;
}
void
JITOutput::SetVarChangedOffset(int32 offset)
{
m_outputData->localVarChangedOffset = offset;
}
void
JITOutput::SetHasBailoutInstr(bool val)
{
m_outputData->hasBailoutInstr = val;
}
void
JITOutput::SetArgUsedForBranch(uint8 param)
{
Assert(param > 0);
Assert(param < Js::Constants::MaximumArgumentCountForConstantArgumentInlining);
m_outputData->argUsedForBranch |= (1 << (param - 1));
}
void
JITOutput::SetFrameHeight(uint val)
{
m_outputData->frameHeight = val;
}
void
JITOutput::RecordThrowMap(Js::ThrowMapEntry * throwMap, uint mapCount)
{
m_outputData->throwMapOffset = NativeCodeData::GetDataTotalOffset(throwMap);
m_outputData->throwMapCount = mapCount;
}
uint16
JITOutput::GetArgUsedForBranch() const
{
return m_outputData->argUsedForBranch;
}
intptr_t
JITOutput::GetCodeAddress() const
{
return (intptr_t)m_outputData->codeAddress;
}
void
JITOutput::SetCodeAddress(intptr_t addr)
{
m_outputData->codeAddress = addr;
}
size_t
JITOutput::GetCodeSize() const
{
return (size_t)m_outputData->codeSize;
}
ushort
JITOutput::GetPdataCount() const
{
return m_outputData->pdataCount;
}
ushort
JITOutput::GetXdataSize() const
{
return m_outputData->xdataSize;
}
EmitBufferAllocation *
JITOutput::RecordNativeCodeSize(Func *func, uint32 bytes, ushort pdataCount, ushort xdataSize)
{
BYTE *buffer;
#if defined(_M_ARM32_OR_ARM64)
bool canAllocInPreReservedHeapPageSegment = false;
#else
bool canAllocInPreReservedHeapPageSegment = func->CanAllocInPreReservedHeapPageSegment();
#endif
EmitBufferAllocation *allocation = func->GetEmitBufferManager()->AllocateBuffer(bytes, &buffer, pdataCount, xdataSize, canAllocInPreReservedHeapPageSegment, true);
Assert(allocation != nullptr);
if (buffer == nullptr)
Js::Throw::OutOfMemory();
m_outputData->codeAddress = (intptr_t)buffer;
m_outputData->codeSize = bytes;
m_outputData->pdataCount = pdataCount;
m_outputData->xdataSize = xdataSize;
m_outputData->isInPrereservedRegion = allocation->inPrereservedRegion;
return allocation;
}
void
JITOutput::RecordNativeCode(Func *func, const BYTE* sourceBuffer, EmitBufferAllocation * alloc)
{
Assert(m_outputData->codeAddress == (intptr_t)alloc->allocation->address);
if (!func->GetEmitBufferManager()->CommitBuffer(alloc, (BYTE *)m_outputData->codeAddress, m_outputData->codeSize, sourceBuffer))
{
Js::Throw::OutOfMemory();
}
#if DBG_DUMP
if (func->IsLoopBody())
{
func->GetEmitBufferManager()->totalBytesLoopBody += m_outputData->codeSize;
}
#endif
}
void
JITOutput::RecordInlineeFrameOffsetsInfo(unsigned int offsetsArrayOffset, unsigned int offsetsArrayCount)
{
m_outputData->inlineeFrameOffsetArrayOffset = offsetsArrayOffset;
m_outputData->inlineeFrameOffsetArrayCount = offsetsArrayCount;
}
#if _M_X64
size_t
JITOutput::RecordUnwindInfo(size_t offset, BYTE *unwindInfo, size_t size, BYTE * xdataAddr, HANDLE processHandle)
{
Assert(offset == 0);
Assert(XDATA_SIZE >= size);
ChakraMemCopy(xdataAddr, XDATA_SIZE, unwindInfo, size, processHandle);
m_outputData->xdataAddr = (intptr_t)xdataAddr;
return 0;
}
#elif _M_ARM
size_t
JITOutput::RecordUnwindInfo(size_t offset, BYTE *unwindInfo, size_t size, BYTE * xdataAddr, HANDLE processHandle)
{
BYTE *xdataFinal = xdataAddr + offset;
Assert(xdataFinal);
Assert(((DWORD)xdataFinal & 0x3) == 0); // 4 byte aligned
memcpy_s(xdataFinal, size, unwindInfo, size);
return (size_t)xdataFinal;
}
void
JITOutput::RecordXData(BYTE * xdata)
{
m_outputData->xdataOffset = NativeCodeData::GetDataTotalOffset(xdata);
}
#endif
void
JITOutput::FinalizeNativeCode(Func *func, EmitBufferAllocation * alloc)
{
func->GetEmitBufferManager()->CompletePreviousAllocation(alloc);
if (!func->IsOOPJIT())
{
func->GetInProcJITEntryPointInfo()->SetInProcJITNativeCodeData(func->GetNativeCodeDataAllocator()->Finalize());
func->GetInProcJITEntryPointInfo()->GetJitTransferData()->SetRawData(func->GetTransferDataAllocator()->Finalize());
#if !FLOATVAR
CodeGenNumberChunk * numberChunks = func->GetNumberAllocator()->Finalize();
func->GetInProcJITEntryPointInfo()->SetNumberChunks(numberChunks);
#endif
}
}
JITOutputIDL *
JITOutput::GetOutputData()
{
return m_outputData;
}
<|endoftext|>
|
<commit_before>//===--- CGDeclCXX.cpp - Emit LLVM Code for C++ declarations --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This contains code dealing with code generation of C++ declarations
//
//===----------------------------------------------------------------------===//
#include "CodeGenFunction.h"
using namespace clang;
using namespace CodeGen;
static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
llvm::Constant *DeclPtr) {
assert(D.hasGlobalStorage() && "VarDecl must have global storage!");
assert(!D.getType()->isReferenceType() &&
"Should not call EmitDeclInit on a reference!");
CodeGenModule &CGM = CGF.CGM;
ASTContext &Context = CGF.getContext();
const Expr *Init = D.getInit();
QualType T = D.getType();
bool isVolatile = Context.getCanonicalType(T).isVolatileQualified();
if (!CGF.hasAggregateLLVMType(T)) {
llvm::Value *V = CGF.EmitScalarExpr(Init);
CGF.EmitStoreOfScalar(V, DeclPtr, isVolatile, T);
} else if (T->isAnyComplexType()) {
CGF.EmitComplexExprIntoAddr(Init, DeclPtr, isVolatile);
} else {
CGF.EmitAggExpr(Init, DeclPtr, isVolatile);
// Avoid generating destructor(s) for initialized objects.
if (!isa<CXXConstructExpr>(Init))
return;
const ConstantArrayType *Array = Context.getAsConstantArrayType(T);
if (Array)
T = Context.getBaseElementType(Array);
const RecordType *RT = T->getAs<RecordType>();
if (!RT)
return;
CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
if (RD->hasTrivialDestructor())
return;
CXXDestructorDecl *Dtor = RD->getDestructor(Context);
llvm::Constant *DtorFn;
if (Array) {
DtorFn =
CodeGenFunction(CGM).GenerateCXXAggrDestructorHelper(Dtor,
Array,
DeclPtr);
const llvm::Type *Int8PtrTy =
llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
DeclPtr = llvm::Constant::getNullValue(Int8PtrTy);
} else
DtorFn = CGM.GetAddrOfCXXDestructor(Dtor, Dtor_Complete);
CGF.EmitCXXGlobalDtorRegistration(DtorFn, DeclPtr);
}
}
void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
llvm::Constant *DeclPtr) {
const Expr *Init = D.getInit();
QualType T = D.getType();
if (!T->isReferenceType()) {
EmitDeclInit(*this, D, DeclPtr);
return;
}
RValue RV = EmitReferenceBindingToExpr(Init, T, /*IsInitializer=*/true);
EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, T);
}
void
CodeGenFunction::EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
llvm::Constant *DeclPtr) {
const llvm::Type *Int8PtrTy =
llvm::Type::getInt8Ty(VMContext)->getPointerTo();
std::vector<const llvm::Type *> Params;
Params.push_back(Int8PtrTy);
// Get the destructor function type
const llvm::Type *DtorFnTy =
llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
DtorFnTy = llvm::PointerType::getUnqual(DtorFnTy);
Params.clear();
Params.push_back(DtorFnTy);
Params.push_back(Int8PtrTy);
Params.push_back(Int8PtrTy);
// Get the __cxa_atexit function type
// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
const llvm::FunctionType *AtExitFnTy =
llvm::FunctionType::get(ConvertType(getContext().IntTy), Params, false);
llvm::Constant *AtExitFn = CGM.CreateRuntimeFunction(AtExitFnTy,
"__cxa_atexit");
llvm::Constant *Handle = CGM.CreateRuntimeVariable(Int8PtrTy,
"__dso_handle");
llvm::Value *Args[3] = { llvm::ConstantExpr::getBitCast(DtorFn, DtorFnTy),
llvm::ConstantExpr::getBitCast(DeclPtr, Int8PtrTy),
llvm::ConstantExpr::getBitCast(Handle, Int8PtrTy) };
Builder.CreateCall(AtExitFn, &Args[0], llvm::array_endof(Args));
}
void
CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D) {
const llvm::FunctionType *FTy
= llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
false);
// Create a variable initialization function.
llvm::Function *Fn =
llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
"__cxx_global_var_init", &TheModule);
CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D);
CXXGlobalInits.push_back(Fn);
}
void
CodeGenModule::EmitCXXGlobalInitFunc() {
if (CXXGlobalInits.empty())
return;
const llvm::FunctionType *FTy
= llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
false);
// Create our global initialization function.
// FIXME: Should this be tweakable by targets?
llvm::Function *Fn =
llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
"__cxx_global_initialization", &TheModule);
CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
&CXXGlobalInits[0],
CXXGlobalInits.size());
AddGlobalCtor(Fn);
}
void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
const VarDecl *D) {
StartFunction(GlobalDecl(), getContext().VoidTy, Fn, FunctionArgList(),
SourceLocation());
llvm::Constant *DeclPtr = CGM.GetAddrOfGlobalVar(D);
EmitCXXGlobalVarDeclInit(*D, DeclPtr);
FinishFunction();
}
void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
llvm::Constant **Decls,
unsigned NumDecls) {
StartFunction(GlobalDecl(), getContext().VoidTy, Fn, FunctionArgList(),
SourceLocation());
for (unsigned i = 0; i != NumDecls; ++i)
Builder.CreateCall(Decls[i]);
FinishFunction();
}
void
CodeGenFunction::EmitStaticCXXBlockVarDeclInit(const VarDecl &D,
llvm::GlobalVariable *GV) {
// FIXME: This should use __cxa_guard_{acquire,release}?
assert(!getContext().getLangOptions().ThreadsafeStatics &&
"thread safe statics are currently not supported!");
llvm::SmallString<256> GuardVName;
CGM.getMangleContext().mangleGuardVariable(&D, GuardVName);
// Create the guard variable.
llvm::GlobalValue *GuardV =
new llvm::GlobalVariable(CGM.getModule(), llvm::Type::getInt64Ty(VMContext),
false, GV->getLinkage(),
llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext)),
GuardVName.str());
// Load the first byte of the guard variable.
const llvm::Type *PtrTy
= llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
llvm::Value *V = Builder.CreateLoad(Builder.CreateBitCast(GuardV, PtrTy),
"tmp");
// Compare it against 0.
llvm::Value *nullValue
= llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext));
llvm::Value *ICmp = Builder.CreateICmpEQ(V, nullValue , "tobool");
llvm::BasicBlock *InitBlock = createBasicBlock("init");
llvm::BasicBlock *EndBlock = createBasicBlock("init.end");
// If the guard variable is 0, jump to the initializer code.
Builder.CreateCondBr(ICmp, InitBlock, EndBlock);
EmitBlock(InitBlock);
if (D.getType()->isReferenceType()) {
QualType T = D.getType();
// We don't want to pass true for IsInitializer here, because a static
// reference to a temporary does not extend its lifetime.
RValue RV = EmitReferenceBindingToExpr(D.getInit(), T,
/*IsInitializer=*/false);
EmitStoreOfScalar(RV.getScalarVal(), GV, /*Volatile=*/false, T);
} else
EmitDeclInit(*this, D, GV);
Builder.CreateStore(llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext),
1),
Builder.CreateBitCast(GuardV, PtrTy));
EmitBlock(EndBlock);
}
<commit_msg>global variable that binds reference to a non-lvalue reproted as NYI now.<commit_after>//===--- CGDeclCXX.cpp - Emit LLVM Code for C++ declarations --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This contains code dealing with code generation of C++ declarations
//
//===----------------------------------------------------------------------===//
#include "CodeGenFunction.h"
using namespace clang;
using namespace CodeGen;
static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
llvm::Constant *DeclPtr) {
assert(D.hasGlobalStorage() && "VarDecl must have global storage!");
assert(!D.getType()->isReferenceType() &&
"Should not call EmitDeclInit on a reference!");
CodeGenModule &CGM = CGF.CGM;
ASTContext &Context = CGF.getContext();
const Expr *Init = D.getInit();
QualType T = D.getType();
bool isVolatile = Context.getCanonicalType(T).isVolatileQualified();
if (!CGF.hasAggregateLLVMType(T)) {
llvm::Value *V = CGF.EmitScalarExpr(Init);
CGF.EmitStoreOfScalar(V, DeclPtr, isVolatile, T);
} else if (T->isAnyComplexType()) {
CGF.EmitComplexExprIntoAddr(Init, DeclPtr, isVolatile);
} else {
CGF.EmitAggExpr(Init, DeclPtr, isVolatile);
// Avoid generating destructor(s) for initialized objects.
if (!isa<CXXConstructExpr>(Init))
return;
const ConstantArrayType *Array = Context.getAsConstantArrayType(T);
if (Array)
T = Context.getBaseElementType(Array);
const RecordType *RT = T->getAs<RecordType>();
if (!RT)
return;
CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
if (RD->hasTrivialDestructor())
return;
CXXDestructorDecl *Dtor = RD->getDestructor(Context);
llvm::Constant *DtorFn;
if (Array) {
DtorFn =
CodeGenFunction(CGM).GenerateCXXAggrDestructorHelper(Dtor,
Array,
DeclPtr);
const llvm::Type *Int8PtrTy =
llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
DeclPtr = llvm::Constant::getNullValue(Int8PtrTy);
} else
DtorFn = CGM.GetAddrOfCXXDestructor(Dtor, Dtor_Complete);
CGF.EmitCXXGlobalDtorRegistration(DtorFn, DeclPtr);
}
}
void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
llvm::Constant *DeclPtr) {
const Expr *Init = D.getInit();
QualType T = D.getType();
if (!T->isReferenceType()) {
EmitDeclInit(*this, D, DeclPtr);
return;
}
if (Init->isLvalue(getContext()) == Expr::LV_Valid) {
RValue RV = EmitReferenceBindingToExpr(Init, T, /*IsInitializer=*/true);
EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, T);
return;
}
ErrorUnsupported(Init,
"global variable that binds reference to a non-lvalue");
}
void
CodeGenFunction::EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
llvm::Constant *DeclPtr) {
const llvm::Type *Int8PtrTy =
llvm::Type::getInt8Ty(VMContext)->getPointerTo();
std::vector<const llvm::Type *> Params;
Params.push_back(Int8PtrTy);
// Get the destructor function type
const llvm::Type *DtorFnTy =
llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
DtorFnTy = llvm::PointerType::getUnqual(DtorFnTy);
Params.clear();
Params.push_back(DtorFnTy);
Params.push_back(Int8PtrTy);
Params.push_back(Int8PtrTy);
// Get the __cxa_atexit function type
// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
const llvm::FunctionType *AtExitFnTy =
llvm::FunctionType::get(ConvertType(getContext().IntTy), Params, false);
llvm::Constant *AtExitFn = CGM.CreateRuntimeFunction(AtExitFnTy,
"__cxa_atexit");
llvm::Constant *Handle = CGM.CreateRuntimeVariable(Int8PtrTy,
"__dso_handle");
llvm::Value *Args[3] = { llvm::ConstantExpr::getBitCast(DtorFn, DtorFnTy),
llvm::ConstantExpr::getBitCast(DeclPtr, Int8PtrTy),
llvm::ConstantExpr::getBitCast(Handle, Int8PtrTy) };
Builder.CreateCall(AtExitFn, &Args[0], llvm::array_endof(Args));
}
void
CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D) {
const llvm::FunctionType *FTy
= llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
false);
// Create a variable initialization function.
llvm::Function *Fn =
llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
"__cxx_global_var_init", &TheModule);
CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D);
CXXGlobalInits.push_back(Fn);
}
void
CodeGenModule::EmitCXXGlobalInitFunc() {
if (CXXGlobalInits.empty())
return;
const llvm::FunctionType *FTy
= llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
false);
// Create our global initialization function.
// FIXME: Should this be tweakable by targets?
llvm::Function *Fn =
llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
"__cxx_global_initialization", &TheModule);
CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
&CXXGlobalInits[0],
CXXGlobalInits.size());
AddGlobalCtor(Fn);
}
void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
const VarDecl *D) {
StartFunction(GlobalDecl(), getContext().VoidTy, Fn, FunctionArgList(),
SourceLocation());
llvm::Constant *DeclPtr = CGM.GetAddrOfGlobalVar(D);
EmitCXXGlobalVarDeclInit(*D, DeclPtr);
FinishFunction();
}
void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
llvm::Constant **Decls,
unsigned NumDecls) {
StartFunction(GlobalDecl(), getContext().VoidTy, Fn, FunctionArgList(),
SourceLocation());
for (unsigned i = 0; i != NumDecls; ++i)
Builder.CreateCall(Decls[i]);
FinishFunction();
}
void
CodeGenFunction::EmitStaticCXXBlockVarDeclInit(const VarDecl &D,
llvm::GlobalVariable *GV) {
// FIXME: This should use __cxa_guard_{acquire,release}?
assert(!getContext().getLangOptions().ThreadsafeStatics &&
"thread safe statics are currently not supported!");
llvm::SmallString<256> GuardVName;
CGM.getMangleContext().mangleGuardVariable(&D, GuardVName);
// Create the guard variable.
llvm::GlobalValue *GuardV =
new llvm::GlobalVariable(CGM.getModule(), llvm::Type::getInt64Ty(VMContext),
false, GV->getLinkage(),
llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext)),
GuardVName.str());
// Load the first byte of the guard variable.
const llvm::Type *PtrTy
= llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
llvm::Value *V = Builder.CreateLoad(Builder.CreateBitCast(GuardV, PtrTy),
"tmp");
// Compare it against 0.
llvm::Value *nullValue
= llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext));
llvm::Value *ICmp = Builder.CreateICmpEQ(V, nullValue , "tobool");
llvm::BasicBlock *InitBlock = createBasicBlock("init");
llvm::BasicBlock *EndBlock = createBasicBlock("init.end");
// If the guard variable is 0, jump to the initializer code.
Builder.CreateCondBr(ICmp, InitBlock, EndBlock);
EmitBlock(InitBlock);
if (D.getType()->isReferenceType()) {
QualType T = D.getType();
// We don't want to pass true for IsInitializer here, because a static
// reference to a temporary does not extend its lifetime.
RValue RV = EmitReferenceBindingToExpr(D.getInit(), T,
/*IsInitializer=*/false);
EmitStoreOfScalar(RV.getScalarVal(), GV, /*Volatile=*/false, T);
} else
EmitDeclInit(*this, D, GV);
Builder.CreateStore(llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext),
1),
Builder.CreateBitCast(GuardV, PtrTy));
EmitBlock(EndBlock);
}
<|endoftext|>
|
<commit_before>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <fnord-msg/MessagePrinter.h>
#include <fnord-base/stringutil.h>
namespace fnord {
namespace msg {
String MessagePrinter::print(
const MessageObject& msg,
const MessageSchema& schema) {
return printObject(0, msg, schema);
}
String MessagePrinter::printObject(
size_t level,
const MessageObject& msg,
const MessageSchema& schema) {
String ws(level * 2, ' ');
switch (schema.type(msg.id)) {
case FieldType::OBJECT: {
String str;
str.append(StringUtil::format("$0$1 {\n", ws, schema.name(msg.id)));
for (const auto& o : msg.asObject()) {
str.append(printObject(level + 1, o, schema));
}
str.append(ws + "}\n");
return str;
}
case FieldType::BOOLEAN:
return StringUtil::format(
"$0$1 = $2\n",
ws,
schema.name(msg.id),
msg.asBool());
case FieldType::STRING:
return StringUtil::format(
"$0$1 = $2\n",
ws,
schema.name(msg.id),
msg.asString());
case FieldType::UINT32:
return StringUtil::format(
"$0$1 = $2\n",
ws,
schema.name(msg.id),
msg.asUInt32());
}
}
} // namespace msg
} // namespace fnord
<commit_msg>MessagePrinter<commit_after>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <fnord-msg/MessagePrinter.h>
#include <fnord-base/stringutil.h>
namespace fnord {
namespace msg {
String MessagePrinter::print(
const MessageObject& msg,
const MessageSchema& schema) {
return printObject(0, msg, schema);
}
String MessagePrinter::printObject(
size_t level,
const MessageObject& msg,
const MessageSchema& schema) {
String ws(level * 2, ' ');
switch (schema.type(msg.id)) {
case FieldType::OBJECT: {
String str;
str.append(StringUtil::format("$0$1 {\n", ws, schema.name(msg.id)));
for (const auto& o : msg.asObject()) {
str.append(printObject(level + 1, o, schema));
}
str.append(ws + "}\n");
return str;
}
case FieldType::BOOLEAN:
return StringUtil::format(
"$0$1 = $2\n",
ws,
schema.name(msg.id),
msg.asBool());
case FieldType::STRING:
return StringUtil::format(
"$0$1 = \"$2\"\n",
ws,
schema.name(msg.id),
msg.asString());
case FieldType::UINT32:
return StringUtil::format(
"$0$1 = $2\n",
ws,
schema.name(msg.id),
msg.asUInt32());
}
}
} // namespace msg
} // namespace fnord
<|endoftext|>
|
<commit_before>//===- SymbolSize.cpp -----------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Object/SymbolSize.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Object/ELFObjectFile.h"
using namespace llvm;
using namespace object;
namespace {
struct SymEntry {
symbol_iterator I;
uint64_t Address;
unsigned Number;
SectionRef Section;
};
}
static int compareAddress(const SymEntry *A, const SymEntry *B) {
if (A->Section == B->Section)
return A->Address - B->Address;
if (A->Section < B->Section)
return -1;
if (A->Section == B->Section)
return 0;
return 1;
}
static int compareNumber(const SymEntry *A, const SymEntry *B) {
return A->Number - B->Number;
}
ErrorOr<std::vector<std::pair<SymbolRef, uint64_t>>>
llvm::object::computeSymbolSizes(const ObjectFile &O) {
std::vector<std::pair<SymbolRef, uint64_t>> Ret;
if (const auto *E = dyn_cast<ELFObjectFileBase>(&O)) {
for (SymbolRef Sym : E->symbols())
Ret.push_back({Sym, E->getSymbolSize(Sym)});
return Ret;
}
// Collect sorted symbol addresses. Include dummy addresses for the end
// of each section.
std::vector<SymEntry> Addresses;
unsigned SymNum = 0;
for (symbol_iterator I = O.symbol_begin(), E = O.symbol_end(); I != E; ++I) {
SymbolRef Sym = *I;
uint64_t Address;
if (std::error_code EC = Sym.getAddress(Address))
return EC;
section_iterator SecI = O.section_end();
if (std::error_code EC = Sym.getSection(SecI))
return EC;
Addresses.push_back({I, Address, SymNum, *SecI});
++SymNum;
}
for (const SectionRef Sec : O.sections()) {
uint64_t Address = Sec.getAddress();
uint64_t Size = Sec.getSize();
Addresses.push_back({O.symbol_end(), Address + Size, 0, Sec});
}
array_pod_sort(Addresses.begin(), Addresses.end(), compareAddress);
// Compute the size as the gap to the next symbol
for (unsigned I = 0, N = Addresses.size() - 1; I < N; ++I) {
auto &P = Addresses[I];
if (P.I == O.symbol_end())
continue;
// If multiple symbol have the same address, give both the same size.
unsigned NextI = I + 1;
while (NextI < N && Addresses[NextI].Address == P.Address)
++NextI;
uint64_t Size = Addresses[NextI].Address - P.Address;
P.Address = Size;
}
// Put back in the original order and copy the result
array_pod_sort(Addresses.begin(), Addresses.end(), compareNumber);
for (SymEntry &P : Addresses) {
if (P.I == O.symbol_end())
continue;
Ret.push_back({*P.I, P.Address});
}
return Ret;
}
<commit_msg>Use Symbol::getValue to simplify object::computeSymbolSizes. NFC.<commit_after>//===- SymbolSize.cpp -----------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Object/SymbolSize.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Object/ELFObjectFile.h"
using namespace llvm;
using namespace object;
namespace {
struct SymEntry {
symbol_iterator I;
uint64_t Address;
unsigned Number;
SectionRef Section;
};
}
static int compareAddress(const SymEntry *A, const SymEntry *B) {
if (A->Section == B->Section)
return A->Address - B->Address;
if (A->Section < B->Section)
return -1;
if (A->Section == B->Section)
return 0;
return 1;
}
static int compareNumber(const SymEntry *A, const SymEntry *B) {
return A->Number - B->Number;
}
ErrorOr<std::vector<std::pair<SymbolRef, uint64_t>>>
llvm::object::computeSymbolSizes(const ObjectFile &O) {
std::vector<std::pair<SymbolRef, uint64_t>> Ret;
if (const auto *E = dyn_cast<ELFObjectFileBase>(&O)) {
for (SymbolRef Sym : E->symbols())
Ret.push_back({Sym, E->getSymbolSize(Sym)});
return Ret;
}
// Collect sorted symbol addresses. Include dummy addresses for the end
// of each section.
std::vector<SymEntry> Addresses;
unsigned SymNum = 0;
for (symbol_iterator I = O.symbol_begin(), E = O.symbol_end(); I != E; ++I) {
SymbolRef Sym = *I;
uint64_t Value = Sym.getValue();
section_iterator SecI = O.section_end();
if (std::error_code EC = Sym.getSection(SecI))
return EC;
Addresses.push_back({I, Value, SymNum, *SecI});
++SymNum;
}
for (const SectionRef Sec : O.sections()) {
uint64_t Address = Sec.getAddress();
uint64_t Size = Sec.getSize();
Addresses.push_back({O.symbol_end(), Address + Size, 0, Sec});
}
array_pod_sort(Addresses.begin(), Addresses.end(), compareAddress);
// Compute the size as the gap to the next symbol
for (unsigned I = 0, N = Addresses.size() - 1; I < N; ++I) {
auto &P = Addresses[I];
if (P.I == O.symbol_end())
continue;
// If multiple symbol have the same address, give both the same size.
unsigned NextI = I + 1;
while (NextI < N && Addresses[NextI].Address == P.Address)
++NextI;
uint64_t Size = Addresses[NextI].Address - P.Address;
P.Address = Size;
}
// Put back in the original order and copy the result
array_pod_sort(Addresses.begin(), Addresses.end(), compareNumber);
for (SymEntry &P : Addresses) {
if (P.I == O.symbol_end())
continue;
Ret.push_back({*P.I, P.Address});
}
return Ret;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "bindings/v8/ScriptPromiseResolver.h"
#include "bindings/v8/V8Binding.h"
#include "bindings/v8/custom/V8PromiseCustom.h"
#include <gtest/gtest.h>
#include <v8.h>
namespace WebCore {
namespace {
class ScriptPromiseResolverTest : public testing::Test {
public:
ScriptPromiseResolverTest() : m_scope(v8::Isolate::GetCurrent())
{
}
void SetUp()
{
m_isolate = v8::Isolate::GetCurrent();
v8::Local<v8::Context> context = v8::Context::New(m_isolate);
m_context.set(m_isolate, context);
context->Enter();
m_perContextData = V8PerContextData::create(context);
m_perContextData->init();
m_resolver = ScriptPromiseResolver::create();
m_promise = m_resolver->promise();
}
void TearDown()
{
m_resolver = 0;
m_promise.clear();
m_perContextData.clear();
m_context.newLocal(m_isolate)->Exit();
}
V8PromiseCustom::PromiseState state()
{
return V8PromiseCustom::getState(V8PromiseCustom::getInternal(promise()));
}
v8::Local<v8::Value> result()
{
return V8PromiseCustom::getInternal(promise())->GetInternalField(V8PromiseCustom::InternalResultIndex);
}
v8::Local<v8::Object> promise()
{
ASSERT(!m_promise.hasNoValue());
return m_promise.v8Object();
}
protected:
RefPtr<ScriptPromiseResolver> m_resolver;
ScriptObject m_promise;
v8::HandleScope m_scope;
OwnPtr<V8PerContextData> m_perContextData;
ScopedPersistent<v8::Context> m_context;
v8::Isolate* m_isolate;
};
TEST_F(ScriptPromiseResolverTest, initialState)
{
EXPECT_TRUE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Pending, state());
EXPECT_TRUE(result()->IsUndefined());
}
TEST_F(ScriptPromiseResolverTest, fulfill)
{
EXPECT_TRUE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Pending, state());
EXPECT_TRUE(result()->IsUndefined());
m_resolver->fulfill(ScriptValue(v8::Integer::New(3)));
EXPECT_FALSE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Fulfilled, state());
ASSERT_TRUE(result()->IsNumber());
EXPECT_EQ(3, result().As<v8::Integer>()->Value());
}
TEST_F(ScriptPromiseResolverTest, resolve)
{
EXPECT_TRUE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Pending, state());
EXPECT_TRUE(result()->IsUndefined());
m_resolver->resolve(ScriptValue(v8::Integer::New(3)));
EXPECT_FALSE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Fulfilled, state());
ASSERT_TRUE(result()->IsNumber());
EXPECT_EQ(3, result().As<v8::Integer>()->Value());
}
TEST_F(ScriptPromiseResolverTest, reject)
{
EXPECT_TRUE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Pending, state());
EXPECT_TRUE(result()->IsUndefined());
m_resolver->reject(ScriptValue(v8::Integer::New(3)));
EXPECT_FALSE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Rejected, state());
ASSERT_TRUE(result()->IsNumber());
EXPECT_EQ(3, result().As<v8::Integer>()->Value());
}
TEST_F(ScriptPromiseResolverTest, fulfillOverFulfill)
{
EXPECT_TRUE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Pending, state());
EXPECT_TRUE(result()->IsUndefined());
m_resolver->fulfill(ScriptValue(v8::Integer::New(3)));
EXPECT_FALSE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Fulfilled, state());
ASSERT_TRUE(result()->IsNumber());
EXPECT_EQ(3, result().As<v8::Integer>()->Value());
m_resolver->fulfill(ScriptValue(v8::Integer::New(4)));
EXPECT_FALSE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Fulfilled, state());
ASSERT_TRUE(result()->IsNumber());
EXPECT_EQ(3, result().As<v8::Integer>()->Value());
}
TEST_F(ScriptPromiseResolverTest, rejectOverFulfill)
{
EXPECT_TRUE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Pending, state());
EXPECT_TRUE(result()->IsUndefined());
m_resolver->fulfill(ScriptValue(v8::Integer::New(3)));
EXPECT_FALSE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Fulfilled, state());
ASSERT_TRUE(result()->IsNumber());
EXPECT_EQ(3, result().As<v8::Integer>()->Value());
m_resolver->reject(ScriptValue(v8::Integer::New(4)));
EXPECT_FALSE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Fulfilled, state());
ASSERT_TRUE(result()->IsNumber());
EXPECT_EQ(3, result().As<v8::Integer>()->Value());
}
TEST_F(ScriptPromiseResolverTest, detach)
{
EXPECT_TRUE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Pending, state());
EXPECT_TRUE(result()->IsUndefined());
m_resolver->detach();
EXPECT_FALSE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Rejected, state());
EXPECT_TRUE(result()->IsUndefined());
}
} // namespace
} // namespace WebCore
<commit_msg>Replace explicit Enter/Exit calls with v8::Context::Scope in unit test.<commit_after>/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "bindings/v8/ScriptPromiseResolver.h"
#include "bindings/v8/V8Binding.h"
#include "bindings/v8/custom/V8PromiseCustom.h"
#include <gtest/gtest.h>
#include <v8.h>
namespace WebCore {
namespace {
class ScriptPromiseResolverTest : public testing::Test {
public:
ScriptPromiseResolverTest()
: m_isolate(v8::Isolate::GetCurrent())
, m_handleScope(m_isolate)
, m_context(v8::Context::New(m_isolate))
, m_contextScope(m_context.newLocal(m_isolate))
{
}
void SetUp()
{
m_perContextData = V8PerContextData::create(m_context.newLocal(m_isolate));
m_perContextData->init();
m_resolver = ScriptPromiseResolver::create();
m_promise = m_resolver->promise();
}
void TearDown()
{
m_resolver = 0;
m_promise.clear();
m_perContextData.clear();
}
V8PromiseCustom::PromiseState state()
{
return V8PromiseCustom::getState(V8PromiseCustom::getInternal(promise()));
}
v8::Local<v8::Value> result()
{
return V8PromiseCustom::getInternal(promise())->GetInternalField(V8PromiseCustom::InternalResultIndex);
}
v8::Local<v8::Object> promise()
{
ASSERT(!m_promise.hasNoValue());
return m_promise.v8Object();
}
protected:
v8::Isolate* m_isolate;
v8::HandleScope m_handleScope;
ScopedPersistent<v8::Context> m_context;
v8::Context::Scope m_contextScope;
RefPtr<ScriptPromiseResolver> m_resolver;
ScriptObject m_promise;
OwnPtr<V8PerContextData> m_perContextData;
};
TEST_F(ScriptPromiseResolverTest, initialState)
{
EXPECT_TRUE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Pending, state());
EXPECT_TRUE(result()->IsUndefined());
}
TEST_F(ScriptPromiseResolverTest, fulfill)
{
EXPECT_TRUE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Pending, state());
EXPECT_TRUE(result()->IsUndefined());
m_resolver->fulfill(ScriptValue(v8::Integer::New(3)));
EXPECT_FALSE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Fulfilled, state());
ASSERT_TRUE(result()->IsNumber());
EXPECT_EQ(3, result().As<v8::Integer>()->Value());
}
TEST_F(ScriptPromiseResolverTest, resolve)
{
EXPECT_TRUE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Pending, state());
EXPECT_TRUE(result()->IsUndefined());
m_resolver->resolve(ScriptValue(v8::Integer::New(3)));
EXPECT_FALSE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Fulfilled, state());
ASSERT_TRUE(result()->IsNumber());
EXPECT_EQ(3, result().As<v8::Integer>()->Value());
}
TEST_F(ScriptPromiseResolverTest, reject)
{
EXPECT_TRUE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Pending, state());
EXPECT_TRUE(result()->IsUndefined());
m_resolver->reject(ScriptValue(v8::Integer::New(3)));
EXPECT_FALSE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Rejected, state());
ASSERT_TRUE(result()->IsNumber());
EXPECT_EQ(3, result().As<v8::Integer>()->Value());
}
TEST_F(ScriptPromiseResolverTest, fulfillOverFulfill)
{
EXPECT_TRUE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Pending, state());
EXPECT_TRUE(result()->IsUndefined());
m_resolver->fulfill(ScriptValue(v8::Integer::New(3)));
EXPECT_FALSE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Fulfilled, state());
ASSERT_TRUE(result()->IsNumber());
EXPECT_EQ(3, result().As<v8::Integer>()->Value());
m_resolver->fulfill(ScriptValue(v8::Integer::New(4)));
EXPECT_FALSE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Fulfilled, state());
ASSERT_TRUE(result()->IsNumber());
EXPECT_EQ(3, result().As<v8::Integer>()->Value());
}
TEST_F(ScriptPromiseResolverTest, rejectOverFulfill)
{
EXPECT_TRUE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Pending, state());
EXPECT_TRUE(result()->IsUndefined());
m_resolver->fulfill(ScriptValue(v8::Integer::New(3)));
EXPECT_FALSE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Fulfilled, state());
ASSERT_TRUE(result()->IsNumber());
EXPECT_EQ(3, result().As<v8::Integer>()->Value());
m_resolver->reject(ScriptValue(v8::Integer::New(4)));
EXPECT_FALSE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Fulfilled, state());
ASSERT_TRUE(result()->IsNumber());
EXPECT_EQ(3, result().As<v8::Integer>()->Value());
}
TEST_F(ScriptPromiseResolverTest, detach)
{
EXPECT_TRUE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Pending, state());
EXPECT_TRUE(result()->IsUndefined());
m_resolver->detach();
EXPECT_FALSE(m_resolver->isPending());
EXPECT_EQ(V8PromiseCustom::Rejected, state());
EXPECT_TRUE(result()->IsUndefined());
}
} // namespace
} // namespace WebCore
<|endoftext|>
|
<commit_before>// Copyright 2008 Paul Hodge
#include "circa.h"
#define EXTENDED_LOGGING false
namespace circa {
namespace stateful_value_function {
void evaluate(Term* caller)
{
if (EXTENDED_LOGGING)
std::cout << "stateful-value eval" << std::endl;
if (EXTENDED_LOGGING)
if (caller->name == "") std::cout << "caller has no name" << std::endl;
// Copy our value from the bottom of this branch, if it is ready.
Term* bottom = caller->owningBranch->getNamed(caller->name);
if (bottom == caller) {
if (EXTENDED_LOGGING)
std::cout << "bottom is same for:" << caller->name << std::endl;
return;
}
if (!bottom->hasValue()) {
if (EXTENDED_LOGGING)
std::cout << "bottom has no value" << std::endl;
return;
}
if (bottom->needsUpdate) {
if (EXTENDED_LOGGING)
std::cout << "bottom needs update" << std::endl;
return;
}
// Temp, ignore terms with wrong type. This check should be
// removed when we have proper type specialization.
if (bottom->type != caller->type) {
if (EXTENDED_LOGGING)
std::cout << "type doesn't match for: " << caller->name << std::endl;
return;
}
copy_value(bottom, caller);
}
void setup(Branch& kernel)
{
STATEFUL_VALUE_FUNC = import_function(kernel, evaluate, "stateful-value(any) -> any");
}
}
}
<commit_msg>Tiny refactor<commit_after>// Copyright 2008 Paul Hodge
#include "circa.h"
namespace circa {
namespace stateful_value_function {
void evaluate(Term* caller)
{
const bool VERBOSE_LOGGING = false;
if (VERBOSE_LOGGING)
std::cout << "stateful-value eval" << std::endl;
if (VERBOSE_LOGGING)
if (caller->name == "") std::cout << "caller has no name" << std::endl;
// Copy our value from the bottom of this branch, if it is ready.
Term* bottom = caller->owningBranch->getNamed(caller->name);
if (bottom == caller) {
if (VERBOSE_LOGGING)
std::cout << "bottom is same for:" << caller->name << std::endl;
return;
}
if (!bottom->hasValue()) {
if (VERBOSE_LOGGING)
std::cout << "bottom has no value" << std::endl;
return;
}
if (bottom->needsUpdate) {
if (VERBOSE_LOGGING)
std::cout << "bottom needs update" << std::endl;
return;
}
// Temp, ignore terms with wrong type. This check should be
// removed when we have proper type specialization.
if (bottom->type != caller->type) {
if (VERBOSE_LOGGING)
std::cout << "type doesn't match for: " << caller->name << std::endl;
return;
}
copy_value(bottom, caller);
}
void setup(Branch& kernel)
{
STATEFUL_VALUE_FUNC = import_function(kernel, evaluate, "stateful-value(any) -> any");
}
}
}
<|endoftext|>
|
<commit_before>#ifndef COMPOSE_HPP
# define COMPOSE_HPP
# pragma once
#include <type_traits>
#include <utility>
namespace
{
template <typename R, typename ...A>
struct signature
{
};
template <typename R, typename ...A>
constexpr auto extract_signature(R (*const)(A...)) noexcept
{
return signature<R, A...>();
}
template <typename C, typename R, typename ...A>
constexpr auto extract_signature(R (C::* const)(A...)) noexcept
{
return signature<R, A...>();
}
template <typename C, typename R, typename ...A>
constexpr auto extract_signature(R (C::* const)(A...) const) noexcept
{
return signature<R, A...>();
}
template <typename F>
constexpr auto extract_signature(F const&) noexcept ->
decltype(&F::operator(), extract_signature(&F::operator()))
{
return extract_signature(&F::operator());
}
template <typename F1, typename F2, typename R2, typename ...A1>
class composer
{
F1 const f1_;
F2 const f2_;
public:
explicit composer(F1&& f1, F2&& f2) noexcept :
f1_(::std::forward<F1>(f1)),
f2_(::std::forward<F2>(f2))
{
}
R2 operator()(A1&& ...args) const noexcept(
noexcept(f2_(f1_(::std::forward<A1>(args)...)))
)
{
return f2_(f1_(::std::forward<A1>(args)...));
}
};
template <
typename F1, typename R1, typename ...A1,
typename F2, typename R2, typename ...A2
>
inline auto compose(
F1&& f1, signature<R1, A1...> const,
F2&& f2, signature<R2, A2...> const) noexcept(
noexcept(
composer<F1, F2, R2, A1...>(::std::forward<F1>(f1),
::std::forward<F2>(f2)
)
)
)
{
return composer<F1, F2, R2, A1...>(::std::forward<F1>(f1),
::std::forward<F2>(f2)
);
}
}
template <typename F1, typename F2>
inline auto operator|(F1&& f1, F2&& f2) noexcept(
noexcept(
compose(
::std::forward<F1>(f1), extract_signature(f1),
::std::forward<F2>(f2), extract_signature(f2)
)
)
)
{
return compose(
::std::forward<F1>(f1), extract_signature(f1),
::std::forward<F2>(f2), extract_signature(f2)
);
}
#endif // COMPOSE_HPP
<commit_msg>some fixes<commit_after>#ifndef COMPOSE_HPP
# define COMPOSE_HPP
# pragma once
#include <utility>
namespace
{
template <typename R, typename ...A>
struct signature
{
};
template <typename R, typename ...A>
constexpr auto extract_signature(R (*const)(A...)) noexcept
{
return signature<R, A...>();
}
template <typename C, typename R, typename ...A>
constexpr auto extract_signature(R (C::* const)(A...)) noexcept
{
return signature<R, A...>();
}
template <typename C, typename R, typename ...A>
constexpr auto extract_signature(R (C::* const)(A...) const) noexcept
{
return signature<R, A...>();
}
template <typename F>
constexpr auto extract_signature(F const&) noexcept ->
decltype(&F::operator(), extract_signature(&F::operator()))
{
return extract_signature(&F::operator());
}
template <typename F1, typename F2, typename ...A1>
class composer
{
F1 const f1_;
F2 const f2_;
public:
explicit composer(F1&& f1, F2&& f2) noexcept :
f1_(::std::forward<F1>(f1)),
f2_(::std::forward<F2>(f2))
{
}
auto operator()(A1&& ...args) const noexcept(
noexcept(f2_(f1_(::std::forward<A1>(args)...)))
)
{
return f2_(f1_(::std::forward<A1>(args)...));
}
};
template <
typename F1, typename R1, typename ...A1,
typename F2, typename R2, typename ...A2
>
inline auto compose(
F1&& f1, signature<R1, A1...> const,
F2&& f2, signature<R2, A2...> const) noexcept(
noexcept(
composer<F1, F2, A1...>(::std::forward<F1>(f1),
::std::forward<F2>(f2)
)
)
)
{
return composer<F1, F2, A1...>(::std::forward<F1>(f1),
::std::forward<F2>(f2)
);
}
}
template <typename F1, typename F2>
inline auto operator|(F1&& f1, F2&& f2) noexcept(
noexcept(
compose(
::std::forward<F1>(f1), extract_signature(f1),
::std::forward<F2>(f2), extract_signature(f2)
)
)
)
{
return compose(
::std::forward<F1>(f1), extract_signature(f1),
::std::forward<F2>(f2), extract_signature(f2)
);
}
#endif // COMPOSE_HPP
<|endoftext|>
|
<commit_before>/*
* This file is part of the µOS++ distribution.
* (https://github.com/micro-os-plus)
* Copyright (c) 2016 Liviu Ionescu.
*
* µOS++ 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, version 3.
*
* µOS++ 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 program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cmsis-plus/drivers/usart-wrapper.h>
#include <Driver_USART.h>
#include <utility>
#include <stdio.h>
// ----------------------------------------------------------------------------
namespace os
{
namespace cmsis
{
namespace driver
{
// ----------------------------------------------------------------------
Usart_wrapper::Usart_wrapper (ARM_DRIVER_USART* driver,
ARM_USART_SignalEvent_t c_cb_func) noexcept :
driver_ (driver),
c_cb_func_ (c_cb_func)
{
;
}
Usart_wrapper::~Usart_wrapper () noexcept
{
driver_ = nullptr;
}
// ----------------------------------------------------------------------
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Waggregate-return"
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
const Version&
Usart_wrapper::do_get_version (void) noexcept
{
// Overwrite the C++ instance. Assume same layout.
*((ARM_DRIVER_VERSION*) (&version_)) = driver_->GetVersion ();
return version_;
}
const serial::Capabilities&
Usart_wrapper::do_get_capabilities (void) noexcept
{
// Overwrite the C++ instance. Assume same layout.
*((ARM_USART_CAPABILITIES*) (&capa_)) = driver_->GetCapabilities ();
return capa_;
}
serial::Status&
Usart_wrapper::do_get_status (void) noexcept
{
// Overwrite the C++ instance. Assume same layout.
*((ARM_USART_STATUS*) (&status_)) = driver_->GetStatus ();
return status_;
}
serial::Modem_status&
Usart_wrapper::do_get_modem_status (void) noexcept
{
// Overwrite the C++ instance. Assume same layout.
*((ARM_USART_MODEM_STATUS*) (&modem_status_)) =
driver_->GetModemStatus ();
return modem_status_;
}
#pragma GCC diagnostic pop
return_t
Usart_wrapper::do_power (Power state) noexcept
{
return_t status;
if (state == Power::full)
{
status = driver_->Initialize (c_cb_func_);
if (status != ARM_DRIVER_OK)
{
return status;
}
}
status = driver_->PowerControl ((ARM_POWER_STATE) state);
if (state == Power::off)
{
driver_->Uninitialize ();
}
return status;
}
return_t
Usart_wrapper::do_send (const void* data, std::size_t num) noexcept
{
return driver_->Send (data, num);
}
return_t
Usart_wrapper::do_receive (void* data, std::size_t num) noexcept
{
return driver_->Receive (data, num);
}
return_t
Usart_wrapper::do_transfer (const void* data_out, void* data_in,
std::size_t num) noexcept
{
return driver_->Transfer (data_out, data_in, num);
}
std::size_t
Usart_wrapper::do_get_tx_count (void) noexcept
{
return driver_->GetTxCount ();
}
std::size_t
Usart_wrapper::do_get_rx_count (void) noexcept
{
return driver_->GetRxCount ();
}
return_t
Usart_wrapper::do_configure (serial::config_t cfg,
serial::config_arg_t arg) noexcept
{
return driver_->Control (cfg, arg);
}
return_t
Usart_wrapper::do_control (serial::control_t ctrl) noexcept
{
switch (ctrl)
{
case serial::Control::disable_tx:
case serial::Control::disable_rx:
case serial::Control::disable_break:
return driver_->Control (
ctrl
- (serial::Control::disable_tx - serial::Control::enable_tx),
0);
}
return driver_->Control (ctrl, 1);
}
return_t
Usart_wrapper::do_control_modem_line (serial::Modem_control ctrl) noexcept
{
return driver_->SetModemControl ((ARM_USART_MODEM_CONTROL) ctrl);
}
} /* namespace driver */
} /* namespace cmsis */
} /* namespace os */
<commit_msg>usart-wrapper: casts to avoid warnings<commit_after>/*
* This file is part of the µOS++ distribution.
* (https://github.com/micro-os-plus)
* Copyright (c) 2016 Liviu Ionescu.
*
* µOS++ 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, version 3.
*
* µOS++ 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 program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cmsis-plus/drivers/usart-wrapper.h>
#include <Driver_USART.h>
#include <utility>
#include <stdio.h>
// ----------------------------------------------------------------------------
namespace os
{
namespace cmsis
{
namespace driver
{
// ----------------------------------------------------------------------
Usart_wrapper::Usart_wrapper (ARM_DRIVER_USART* driver,
ARM_USART_SignalEvent_t c_cb_func) noexcept :
driver_ (driver),
c_cb_func_ (c_cb_func)
{
;
}
Usart_wrapper::~Usart_wrapper () noexcept
{
driver_ = nullptr;
}
// ----------------------------------------------------------------------
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Waggregate-return"
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
const Version&
Usart_wrapper::do_get_version (void) noexcept
{
// Overwrite the C++ instance. Assume same layout.
*((ARM_DRIVER_VERSION*) (&version_)) = driver_->GetVersion ();
return version_;
}
const serial::Capabilities&
Usart_wrapper::do_get_capabilities (void) noexcept
{
// Overwrite the C++ instance. Assume same layout.
*((ARM_USART_CAPABILITIES*) (&capa_)) = driver_->GetCapabilities ();
return capa_;
}
serial::Status&
Usart_wrapper::do_get_status (void) noexcept
{
// Overwrite the C++ instance. Assume same layout.
*((ARM_USART_STATUS*) (&status_)) = driver_->GetStatus ();
return status_;
}
serial::Modem_status&
Usart_wrapper::do_get_modem_status (void) noexcept
{
// Overwrite the C++ instance. Assume same layout.
*((ARM_USART_MODEM_STATUS*) (&modem_status_)) =
driver_->GetModemStatus ();
return modem_status_;
}
#pragma GCC diagnostic pop
return_t
Usart_wrapper::do_power (Power state) noexcept
{
return_t status;
if (state == Power::full)
{
status = driver_->Initialize (c_cb_func_);
if (status != ARM_DRIVER_OK)
{
return status;
}
}
status = driver_->PowerControl ((ARM_POWER_STATE) state);
if (state == Power::off)
{
driver_->Uninitialize ();
}
return status;
}
return_t
Usart_wrapper::do_send (const void* data, std::size_t num) noexcept
{
return driver_->Send (data, static_cast<uint32_t> (num));
}
return_t
Usart_wrapper::do_receive (void* data, std::size_t num) noexcept
{
return driver_->Receive (data, static_cast<uint32_t> (num));
}
return_t
Usart_wrapper::do_transfer (const void* data_out, void* data_in,
std::size_t num) noexcept
{
return driver_->Transfer (data_out, data_in,
static_cast<uint32_t> (num));
}
std::size_t
Usart_wrapper::do_get_tx_count (void) noexcept
{
return driver_->GetTxCount ();
}
std::size_t
Usart_wrapper::do_get_rx_count (void) noexcept
{
return driver_->GetRxCount ();
}
return_t
Usart_wrapper::do_configure (serial::config_t cfg,
serial::config_arg_t arg) noexcept
{
return driver_->Control (cfg, arg);
}
return_t
Usart_wrapper::do_control (serial::control_t ctrl) noexcept
{
switch (ctrl)
{
case serial::Control::disable_tx:
case serial::Control::disable_rx:
case serial::Control::disable_break:
return driver_->Control (
ctrl
- (serial::Control::disable_tx - serial::Control::enable_tx),
0);
}
return driver_->Control (ctrl, 1);
}
return_t
Usart_wrapper::do_control_modem_line (serial::Modem_control ctrl) noexcept
{
return driver_->SetModemControl ((ARM_USART_MODEM_CONTROL) ctrl);
}
} /* namespace driver */
} /* namespace cmsis */
} /* namespace os */
<|endoftext|>
|
<commit_before>#ifndef VIENNAGRID_STORAGE_ID_HPP
#define VIENNAGRID_STORAGE_ID_HPP
namespace viennagrid
{
namespace storage
{
template<typename id_type>
struct id_tag;
template<typename base_id_type>
struct smart_id_tag;
template<typename value_type_, typename base_id_type_>
class smart_id_t
{
public:
typedef smart_id_t self_type;
typedef value_type_ value_type;
typedef base_id_type_ base_id_type;
typedef smart_id_t<const value_type, base_id_type> self_const_type;
smart_id_t() : internal_id(-1) {}
explicit smart_id_t( base_id_type internal_id_ ) : internal_id(internal_id_) {}
base_id_type get() const { return internal_id; }
void set( base_id_type internal_id_ ) { internal_id =internal_id_; }
bool operator== ( self_type rhs ) const { return internal_id == rhs.get(); }
bool operator< ( self_type rhs ) const { return internal_id < rhs.get(); }
bool operator<= ( self_type rhs ) const { return internal_id <= rhs.get(); }
bool operator> ( self_type rhs ) const { return internal_id > rhs.get(); }
bool operator>= (self_type rhs ) const { return internal_id >= rhs.get(); }
bool operator== ( self_const_type rhs ) const { return internal_id == rhs.get(); }
bool operator< ( self_const_type rhs ) const { return internal_id < rhs.get(); }
bool operator<= ( self_const_type rhs ) const { return internal_id <= rhs.get(); }
bool operator> ( self_const_type rhs ) const { return internal_id > rhs.get(); }
bool operator>= (self_const_type rhs ) const { return internal_id >= rhs.get(); }
self_type & operator++() { ++internal_id; return *this; }
self_type operator++(int) { self_type tmp(*this); ++*this; return tmp; }
private:
base_id_type internal_id;
};
template<typename value_type_, typename base_id_type_>
class smart_id_t<const value_type_, base_id_type_>
{
public:
typedef smart_id_t self_type;
typedef value_type_ value_type;
typedef base_id_type_ base_id_type;
typedef smart_id_t<value_type, base_id_type> self_non_const_type;
smart_id_t() : internal_id(-1) {}
smart_id_t( smart_id_t<value_type_, base_id_type> const & id_ ) : internal_id(id_.get()) {}
explicit smart_id_t( base_id_type internal_id_ ) : internal_id(internal_id_) {}
base_id_type get() const { return internal_id; }
void set( base_id_type internal_id_ ) { internal_id =internal_id_; }
bool operator== ( self_type rhs ) const { return internal_id == rhs.get(); }
bool operator< ( self_type rhs ) const { return internal_id < rhs.get(); }
bool operator<= ( self_type rhs ) const { return internal_id <= rhs.get(); }
bool operator> ( self_type rhs ) const { return internal_id > rhs.get(); }
bool operator>= (self_type rhs ) const { return internal_id >= rhs.get(); }
bool operator== ( self_non_const_type rhs ) const { return internal_id == rhs.get(); }
bool operator< ( self_non_const_type rhs ) const { return internal_id < rhs.get(); }
bool operator<= ( self_non_const_type rhs ) const { return internal_id <= rhs.get(); }
bool operator> ( self_non_const_type rhs ) const { return internal_id > rhs.get(); }
bool operator>= (self_non_const_type rhs ) const { return internal_id >= rhs.get(); }
self_type & operator++() { ++internal_id; return *this; }
self_type operator++(int) { self_type tmp(*this); ++*this; return tmp; }
private:
base_id_type internal_id;
};
template<typename value_type, typename base_id_type>
bool operator<( smart_id_t<value_type, base_id_type> const & lhs, smart_id_t<value_type, base_id_type> const & rhs )
{ return lhs.get() < rhs.get(); }
template<typename value_type, typename base_id_type>
bool operator<( smart_id_t<const value_type, base_id_type> const & lhs, smart_id_t<value_type, base_id_type> const & rhs )
{ return lhs.get() < rhs.get(); }
template<typename value_type, typename base_id_type>
bool operator<( smart_id_t<value_type, base_id_type> const & lhs, smart_id_t<const value_type, base_id_type> const & rhs )
{ return lhs.get() < rhs.get(); }
template<typename value_type, typename base_id_type>
bool operator<( smart_id_t<const value_type, base_id_type> const & lhs, smart_id_t<const value_type, base_id_type> const & rhs )
{ return lhs.get() < rhs.get(); }
template<typename value_type_, typename base_id_type>
std::ostream & operator<< (std::ostream & os, smart_id_t<value_type_, base_id_type> id)
{
os << id.get();
return os;
}
namespace result_of
{
template<typename value_type, typename id_tag>
struct id;
template<typename value_type, typename id_type>
struct id<value_type, id_tag<id_type> >
{
typedef id_type type;
};
template<typename value_type, typename base_id_type>
struct id<value_type, smart_id_tag<base_id_type> >
{
typedef smart_id_t<value_type, base_id_type> type;
};
template<typename id_type>
struct const_id
{
typedef const id_type type;
};
template<typename value_type, typename id_type>
struct const_id< smart_id_t<value_type, id_type> >
{
typedef smart_id_t<const value_type, id_type> type;
};
}
template<typename id_type_>
class id_handler
{
public:
typedef id_type_ id_type;
typedef typename result_of::const_id<id_type>::type const_id_type;
id_handler() {}
id_handler(const id_handler & rhs) : id_(rhs.id_) {}
void id(id_type id) { id_ = id; }
id_type id() const { return id_; }
private:
id_type id_;
};
namespace result_of
{
template<typename some_type>
struct id_type
{
typedef typename some_type::id_type type;
};
}
template<typename id_type_>
class id_compare
{
public:
typedef id_type_ id_type;
typedef typename result_of::const_id<id_type>::type const_id_type;
id_compare(const_id_type id_) : id(id_) {}
template<typename type>
bool operator() ( const type & to_compare )
{
return to_compare.id() == id;
}
private:
const_id_type id;
};
namespace id
{
template<typename element_type, typename id_type>
void set_id( element_type & element, id_type id )
{
element.id(id);
}
template<typename id_type> void set_id( bool &, id_type ) {}
template<typename id_type> void set_id( char &, id_type ) {}
template<typename id_type> void set_id( unsigned char &, id_type ) {}
template<typename id_type> void set_id( short &, id_type ) {}
template<typename id_type> void set_id( unsigned short &, id_type ) {}
template<typename id_type> void set_id( int &, id_type ) {}
template<typename id_type> void set_id( unsigned int &, id_type ) {}
template<typename id_type> void set_id( long &, id_type ) {}
template<typename id_type> void set_id( unsigned long &, id_type ) {}
template<typename id_type> void set_id( float &, id_type ) {}
template<typename id_type> void set_id( double &, id_type ) {}
}
}
}
#endif
<commit_msg>added opterator!= for smart_id_t<commit_after>#ifndef VIENNAGRID_STORAGE_ID_HPP
#define VIENNAGRID_STORAGE_ID_HPP
namespace viennagrid
{
namespace storage
{
template<typename id_type>
struct id_tag;
template<typename base_id_type>
struct smart_id_tag;
template<typename value_type_, typename base_id_type_>
class smart_id_t
{
public:
typedef smart_id_t self_type;
typedef value_type_ value_type;
typedef base_id_type_ base_id_type;
typedef smart_id_t<const value_type, base_id_type> self_const_type;
smart_id_t() : internal_id(-1) {}
explicit smart_id_t( base_id_type internal_id_ ) : internal_id(internal_id_) {}
base_id_type get() const { return internal_id; }
void set( base_id_type internal_id_ ) { internal_id =internal_id_; }
bool operator== ( self_type rhs ) const { return internal_id == rhs.get(); }
bool operator!= ( self_type rhs ) const { return !(*this == rhs); }
bool operator< ( self_type rhs ) const { return internal_id < rhs.get(); }
bool operator<= ( self_type rhs ) const { return internal_id <= rhs.get(); }
bool operator> ( self_type rhs ) const { return internal_id > rhs.get(); }
bool operator>= (self_type rhs ) const { return internal_id >= rhs.get(); }
bool operator== ( self_const_type rhs ) const { return internal_id == rhs.get(); }
bool operator!= ( self_const_type rhs ) const { return !(*this == rhs); }
bool operator< ( self_const_type rhs ) const { return internal_id < rhs.get(); }
bool operator<= ( self_const_type rhs ) const { return internal_id <= rhs.get(); }
bool operator> ( self_const_type rhs ) const { return internal_id > rhs.get(); }
bool operator>= (self_const_type rhs ) const { return internal_id >= rhs.get(); }
self_type & operator++() { ++internal_id; return *this; }
self_type operator++(int) { self_type tmp(*this); ++*this; return tmp; }
private:
base_id_type internal_id;
};
template<typename value_type_, typename base_id_type_>
class smart_id_t<const value_type_, base_id_type_>
{
public:
typedef smart_id_t self_type;
typedef value_type_ value_type;
typedef base_id_type_ base_id_type;
typedef smart_id_t<value_type, base_id_type> self_non_const_type;
smart_id_t() : internal_id(-1) {}
smart_id_t( smart_id_t<value_type_, base_id_type> const & id_ ) : internal_id(id_.get()) {}
explicit smart_id_t( base_id_type internal_id_ ) : internal_id(internal_id_) {}
base_id_type get() const { return internal_id; }
void set( base_id_type internal_id_ ) { internal_id =internal_id_; }
bool operator== ( self_type rhs ) const { return internal_id == rhs.get(); }
bool operator!= ( self_type rhs ) const { return !(*this == rhs); }
bool operator< ( self_type rhs ) const { return internal_id < rhs.get(); }
bool operator<= ( self_type rhs ) const { return internal_id <= rhs.get(); }
bool operator> ( self_type rhs ) const { return internal_id > rhs.get(); }
bool operator>= (self_type rhs ) const { return internal_id >= rhs.get(); }
bool operator== ( self_non_const_type rhs ) const { return internal_id == rhs.get(); }
bool operator!= ( self_non_const_type rhs ) const { return !(*this == rhs); }
bool operator< ( self_non_const_type rhs ) const { return internal_id < rhs.get(); }
bool operator<= ( self_non_const_type rhs ) const { return internal_id <= rhs.get(); }
bool operator> ( self_non_const_type rhs ) const { return internal_id > rhs.get(); }
bool operator>= (self_non_const_type rhs ) const { return internal_id >= rhs.get(); }
self_type & operator++() { ++internal_id; return *this; }
self_type operator++(int) { self_type tmp(*this); ++*this; return tmp; }
private:
base_id_type internal_id;
};
template<typename value_type, typename base_id_type>
bool operator<( smart_id_t<value_type, base_id_type> const & lhs, smart_id_t<value_type, base_id_type> const & rhs )
{ return lhs.get() < rhs.get(); }
template<typename value_type, typename base_id_type>
bool operator<( smart_id_t<const value_type, base_id_type> const & lhs, smart_id_t<value_type, base_id_type> const & rhs )
{ return lhs.get() < rhs.get(); }
template<typename value_type, typename base_id_type>
bool operator<( smart_id_t<value_type, base_id_type> const & lhs, smart_id_t<const value_type, base_id_type> const & rhs )
{ return lhs.get() < rhs.get(); }
template<typename value_type, typename base_id_type>
bool operator<( smart_id_t<const value_type, base_id_type> const & lhs, smart_id_t<const value_type, base_id_type> const & rhs )
{ return lhs.get() < rhs.get(); }
template<typename value_type_, typename base_id_type>
std::ostream & operator<< (std::ostream & os, smart_id_t<value_type_, base_id_type> id)
{
os << id.get();
return os;
}
namespace result_of
{
template<typename value_type, typename id_tag>
struct id;
template<typename value_type, typename id_type>
struct id<value_type, id_tag<id_type> >
{
typedef id_type type;
};
template<typename value_type, typename base_id_type>
struct id<value_type, smart_id_tag<base_id_type> >
{
typedef smart_id_t<value_type, base_id_type> type;
};
template<typename id_type>
struct const_id
{
typedef const id_type type;
};
template<typename value_type, typename id_type>
struct const_id< smart_id_t<value_type, id_type> >
{
typedef smart_id_t<const value_type, id_type> type;
};
}
template<typename id_type_>
class id_handler
{
public:
typedef id_type_ id_type;
typedef typename result_of::const_id<id_type>::type const_id_type;
id_handler() {}
id_handler(const id_handler & rhs) : id_(rhs.id_) {}
void id(id_type id) { id_ = id; }
id_type id() const { return id_; }
private:
id_type id_;
};
namespace result_of
{
template<typename some_type>
struct id_type
{
typedef typename some_type::id_type type;
};
}
template<typename id_type_>
class id_compare
{
public:
typedef id_type_ id_type;
typedef typename result_of::const_id<id_type>::type const_id_type;
id_compare(const_id_type id_) : id(id_) {}
template<typename type>
bool operator() ( const type & to_compare )
{
return to_compare.id() == id;
}
private:
const_id_type id;
};
namespace id
{
template<typename element_type, typename id_type>
void set_id( element_type & element, id_type id )
{
element.id(id);
}
template<typename id_type> void set_id( bool &, id_type ) {}
template<typename id_type> void set_id( char &, id_type ) {}
template<typename id_type> void set_id( unsigned char &, id_type ) {}
template<typename id_type> void set_id( short &, id_type ) {}
template<typename id_type> void set_id( unsigned short &, id_type ) {}
template<typename id_type> void set_id( int &, id_type ) {}
template<typename id_type> void set_id( unsigned int &, id_type ) {}
template<typename id_type> void set_id( long &, id_type ) {}
template<typename id_type> void set_id( unsigned long &, id_type ) {}
template<typename id_type> void set_id( float &, id_type ) {}
template<typename id_type> void set_id( double &, id_type ) {}
}
}
}
#endif
<|endoftext|>
|
<commit_before>//
// Copyright (c) .NET Foundation and Contributors
// See LICENSE file in the project root for full license information.
//
// This file includes the board specific Ethernet Initialisation
#include "NF_ESP32_Network.h"
#include "esp_netif_net_stack.h"
static const char *TAG = "wifi";
static wifi_mode_t wifiMode;
// flag to store if Wi-Fi has been initialized
static bool IsWifiInitialised = false;
// flag to signal if connect is to happen
bool NF_ESP32_IsToConnect = false;
//
// Check what is the required Wi-Fi mode
// Station only or AP only or Station and AP
//
// See what network interfaces are enabled
//
wifi_mode_t NF_ESP32_CheckExpectedWifiMode()
{
wifi_mode_t mode = WIFI_MODE_NULL;
HAL_Configuration_Wireless80211 *wirelessConfig = NULL;
HAL_Configuration_NetworkInterface *networkConfig =
(HAL_Configuration_NetworkInterface *)platform_malloc(sizeof(HAL_Configuration_NetworkInterface));
// check allocation
if (networkConfig == NULL)
{
return WIFI_MODE_NULL;
}
// Check Wi-Fi station available
if (g_TargetConfiguration.NetworkInterfaceConfigs->Count >= 1)
{
// get config Index 0 (Wireless station config in ESP32)
if (ConfigurationManager_GetConfigurationBlock(networkConfig, DeviceConfigurationOption_Network, 0))
{
// Wireless Config with SSID setup
if (networkConfig->InterfaceType == NetworkInterfaceType::NetworkInterfaceType_Wireless80211)
{
wirelessConfig = ConfigurationManager_GetWirelessConfigurationFromId(networkConfig->SpecificConfigId);
if (wirelessConfig != NULL)
{
if (wirelessConfig->Options & Wireless80211Configuration_ConfigurationOptions_Enable)
{
mode = WIFI_MODE_STA;
}
}
}
}
}
// Check if AP config available
if (g_TargetConfiguration.NetworkInterfaceConfigs->Count >= 2)
{
// get config Index 1 (Wireless AP config in ESP32)
if (ConfigurationManager_GetConfigurationBlock(networkConfig, DeviceConfigurationOption_Network, 1))
{
// Wireless Config with SSID setup
if (networkConfig->InterfaceType == NetworkInterfaceType::NetworkInterfaceType_WirelessAP)
{
wirelessConfig = ConfigurationManager_GetWirelessConfigurationFromId(networkConfig->SpecificConfigId);
if (wirelessConfig != NULL)
{
if (wirelessConfig->Options & WirelessAPConfiguration_ConfigurationOptions_Enable)
{
// Use STATION + AP or just AP
mode = (mode == WIFI_MODE_STA) ? WIFI_MODE_APSTA : WIFI_MODE_AP;
}
}
}
}
}
// this one is always set
platform_free(networkConfig);
// free this one, if it was allocated
if (wirelessConfig)
{
platform_free(wirelessConfig);
}
return mode;
}
wifi_mode_t NF_ESP32_GetCurrentWifiMode()
{
wifi_mode_t current_wifi_mode;
esp_wifi_get_mode(¤t_wifi_mode);
return current_wifi_mode;
}
void NF_ESP32_DeinitWifi()
{
// clear flags
IsWifiInitialised = false;
NF_ESP32_IsToConnect = false;
esp_wifi_stop();
esp_wifi_deinit();
}
esp_err_t NF_ESP32_InitaliseWifi()
{
esp_err_t ec = ESP_OK;
wifi_mode_t expectedWifiMode = NF_ESP32_CheckExpectedWifiMode();
if (IsWifiInitialised)
{
// Check if we are running correct mode
if (NF_ESP32_GetCurrentWifiMode() != expectedWifiMode)
{
// if not force a new initialization
NF_ESP32_DeinitWifi();
}
}
// Don't init if Wi-Fi Mode null (Disabled)
if (expectedWifiMode == WIFI_MODE_NULL)
{
return ESP_FAIL;
}
if (!IsWifiInitialised)
{
// create Wi-Fi STA (ignoring return)
esp_netif_create_default_wifi_sta();
// We need to start the WIFI stack before the station can Connect
// Also we can only get the NetIf number used by ESP IDF after it has been started.
// Starting will also start the Soft- AP (if we have enabled it).
// So make sure it configured as per wireless config otherwise we will get the default SSID
if (expectedWifiMode & WIFI_MODE_AP)
{
// create AP (ignoring return)
esp_netif_create_default_wifi_ap();
}
// Initialise WiFi, allocate resource for WiFi driver, such as WiFi control structure,
// RX/TX buffer, WiFi NVS structure etc, this WiFi also start WiFi task.
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ec = esp_wifi_init(&cfg);
if (ec != ESP_OK)
{
return ec;
}
// set Wi-Fi mode
ec = esp_wifi_set_mode(expectedWifiMode);
if (ec != ESP_OK)
{
return ec;
}
// start Wi-Fi
ec = esp_wifi_start();
if (ec != ESP_OK)
{
return ec;
}
// if need, config the AP
// this can only be performed after Wi-Fi is started
if (expectedWifiMode & WIFI_MODE_AP)
{
HAL_Configuration_NetworkInterface *networkConfig =
(HAL_Configuration_NetworkInterface *)platform_malloc(sizeof(HAL_Configuration_NetworkInterface));
if (networkConfig == NULL)
{
return ESP_FAIL;
}
if (ConfigurationManager_GetConfigurationBlock(networkConfig, DeviceConfigurationOption_Network, 1))
{
// take care of configuring Soft AP
ec = NF_ESP32_WirelessAP_Configure(networkConfig);
platform_free(networkConfig);
}
if (ec != ESP_OK)
{
return ec;
}
}
IsWifiInitialised = true;
}
return ec;
}
esp_err_t NF_ESP32_Wireless_Start_Connect(HAL_Configuration_Wireless80211 *config)
{
esp_err_t ec;
// Connect directly
wifi_config_t sta_config = {};
hal_strncpy_s(
(char *)sta_config.sta.ssid,
sizeof(sta_config.sta.ssid),
(char *)config->Ssid,
hal_strlen_s((char *)config->Ssid));
hal_strncpy_s(
(char *)sta_config.sta.password,
sizeof(sta_config.sta.password),
(char *)config->Password,
hal_strlen_s((char *)config->Password));
sta_config.sta.bssid_set = false;
ec = esp_wifi_set_config(WIFI_IF_STA, &sta_config);
if (ec != ESP_OK)
{
return ec;
}
// set flag
NF_ESP32_IsToConnect = true;
// call disconnect to be sure that connect event is raised again
esp_wifi_disconnect();
// call connect
esp_wifi_connect();
return ESP_OK;
}
esp_err_t NF_ESP32_Wireless_Disconnect()
{
esp_err_t ec;
ec = esp_wifi_disconnect();
if (ec != ESP_OK)
{
return ec;
}
return ESP_OK;
}
int NF_ESP32_Wireless_Open(HAL_Configuration_NetworkInterface *config)
{
esp_err_t ec;
bool okToStartSmartConnect = false;
ec = NF_ESP32_InitaliseWifi();
if (ec != ESP_OK)
{
return SOCK_SOCKET_ERROR;
}
// Get Wireless config
HAL_Configuration_Wireless80211 *wirelessConfig =
ConfigurationManager_GetWirelessConfigurationFromId(config->SpecificConfigId);
if (wirelessConfig == NULL)
{
return SOCK_SOCKET_ERROR;
}
// Wireless station not enabled
if (!(NF_ESP32_GetCurrentWifiMode() & WIFI_MODE_STA))
{
return SOCK_SOCKET_ERROR;
}
// sanity check for Wireless station disabled
if (wirelessConfig->Options & Wireless80211Configuration_ConfigurationOptions_Disable)
{
return SOCK_SOCKET_ERROR;
}
// Connect if Auto connect and we have an SSID
if ((wirelessConfig->Options & Wireless80211Configuration_ConfigurationOptions_AutoConnect) &&
(hal_strlen_s((const char *)wirelessConfig->Ssid) > 0))
{
NF_ESP32_Wireless_Start_Connect(wirelessConfig);
// don't start smart connect
okToStartSmartConnect = false;
}
else
{
// clear flag
NF_ESP32_IsToConnect = false;
}
if (okToStartSmartConnect &&
(wirelessConfig->Options & Wireless80211Configuration_ConfigurationOptions_SmartConfig))
{
// Start Smart config (if enabled)
NF_ESP32_Start_wifi_smart_config();
// clear flag
NF_ESP32_IsToConnect = false;
}
return NF_ESP32_Wait_NetNumber(IDF_WIFI_STA_DEF);
}
bool NF_ESP32_Wireless_Close()
{
if (IsWifiInitialised)
{
esp_wifi_stop();
esp_wifi_deinit();
// clear flags
IsWifiInitialised = false;
NF_ESP32_IsToConnect = false;
}
return false;
}
// Start a scan
int NF_ESP32_Wireless_Scan()
{
wifi_scan_config_t config = {};
config.scan_type = WIFI_SCAN_TYPE_PASSIVE;
// 500ms
config.scan_time.passive = 500;
// Start a Wi-Fi scan
// When complete a Scan Complete event will be fired
esp_err_t res = esp_wifi_scan_start(&config, false);
return (int)res;
}
wifi_auth_mode_t MapAuthentication(AuthenticationType type)
{
wifi_auth_mode_t mapAuth[] = {
WIFI_AUTH_OPEN, // 0 None
WIFI_AUTH_OPEN, // 1 EAP
WIFI_AUTH_OPEN, // 2 PEAP
WIFI_AUTH_OPEN, // 3 WCN
WIFI_AUTH_OPEN, // 4 Open
WIFI_AUTH_OPEN, // 5 Shared
WIFI_AUTH_WEP, // 6 WEP
WIFI_AUTH_WPA_PSK, // 7 WPA
WIFI_AUTH_WPA_WPA2_PSK // 8 WPA2
};
return mapAuth[type];
}
esp_err_t NF_ESP32_WirelessAP_Configure(HAL_Configuration_NetworkInterface *config)
{
esp_err_t ec;
esp_netif_ip_info_t ip_info;
esp_netif_t *espNetif = esp_netif_get_handle_from_ifkey("WIFI_AP_DEF");
ec = esp_netif_get_ip_info(espNetif, &ip_info);
if (config->IPv4Address != 0)
{
ip_info.ip.addr = config->IPv4Address;
ip_info.netmask.addr = config->IPv4NetMask;
ip_info.gw.addr = config->IPv4GatewayAddress;
ec = esp_netif_set_ip_info(espNetif, &ip_info);
}
else
{
config->IPv4Address = ip_info.ip.addr;
config->IPv4NetMask = ip_info.netmask.addr;
config->IPv4GatewayAddress = ip_info.gw.addr;
}
HAL_Configuration_WirelessAP *apConfig =
ConfigurationManager_GetWirelessAPConfigurationFromId(config->SpecificConfigId);
if (apConfig == 0)
{
return ESP_FAIL;
}
wifi_config_t ap_config = {0};
hal_strncpy_s(
(char *)ap_config.ap.ssid,
sizeof(ap_config.ap.ssid),
(char *)apConfig->Ssid,
hal_strlen_s((char *)apConfig->Ssid));
hal_strncpy_s(
(char *)ap_config.ap.password,
sizeof(ap_config.ap.password),
(char *)apConfig->Password,
hal_strlen_s((char *)apConfig->Password));
ap_config.ap.ssid_len = hal_strlen_s((char *)apConfig->Ssid);
ap_config.ap.channel = apConfig->Channel;
ap_config.ap.ssid_hidden = (apConfig->Options & WirelessAPConfiguration_ConfigurationOptions_HiddenSSID) ? 1 : 0;
ap_config.ap.authmode = MapAuthentication(apConfig->Authentication);
if (hal_strlen_s((char *)ap_config.ap.password) == 0)
{
ap_config.ap.authmode = WIFI_AUTH_OPEN;
}
// Max connections for ESP32
ap_config.ap.max_connection = apConfig->MaxConnections;
if (ap_config.ap.max_connection > ESP_WIFI_MAX_CONN_NUM)
{
ap_config.ap.max_connection = ESP_WIFI_MAX_CONN_NUM;
}
ap_config.ap.beacon_interval = 100;
ec = esp_wifi_set_config(WIFI_IF_AP, &ap_config);
if (ec != ESP_OK)
{
ESP_LOGE(TAG, "WiFi set AP config - result %d", ec);
}
return ec;
}
//
// Open Wireless Soft AP
//
// If AP is enabled it will have been configured and started running when the WiFI stack is initialised
// All we need to do here is return the NetIf number used by ESP IDF
// Also make sure Wi-Fi in initialised correctly if config is changed
int IRAM_ATTR NF_ESP32_WirelessAP_Open(HAL_Configuration_NetworkInterface *config)
{
esp_err_t ec;
// Initialise Wi-Fi stack if required
ec = NF_ESP32_InitaliseWifi();
if (ec != ESP_OK)
{
return SOCK_SOCKET_ERROR;
}
// AP mode enabled ?
if (!(NF_ESP32_GetCurrentWifiMode() & WIFI_MODE_AP))
{
return SOCK_SOCKET_ERROR;
}
// Return NetIf number
// FIXME find a better way to get the netif ptr
// This becomes available on the event AP STARTED
// for the moment we just wait for it
return NF_ESP32_Wait_NetNumber(IDF_WIFI_AP_DEF);
}
//
// Closing down AP
//
// Either config being updated or shutdown
// Closing AP will also stop Station
//
bool NF_ESP32_WirelessAP_Close()
{
NF_ESP32_DeinitWifi();
return true;
}
// Wait for the network interface to become available
int NF_ESP32_Wait_NetNumber(int num)
{
int number = 0;
esp_netif_t *espNetif;
while (true)
{
switch (num)
{
case IDF_WIFI_STA_DEF:
espNetif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF");
break;
case IDF_WIFI_AP_DEF:
espNetif = esp_netif_get_handle_from_ifkey("WIFI_AP_DEF");
break;
case IDF_ETH_DEF:
espNetif = esp_netif_get_handle_from_ifkey("ETH_DEF");
break;
default:
// can't reach here
HAL_AssertEx();
break;
}
if (espNetif != NULL)
{
break;
}
vTaskDelay(20 / portTICK_PERIOD_MS);
}
return espNetif->lwip_netif->num;
}
<commit_msg>Using wrong config for AP (#2196)<commit_after>//
// Copyright (c) .NET Foundation and Contributors
// See LICENSE file in the project root for full license information.
//
// This file includes the board specific Ethernet Initialisation
#include "NF_ESP32_Network.h"
#include "esp_netif_net_stack.h"
static const char *TAG = "wifi";
static wifi_mode_t wifiMode;
// flag to store if Wi-Fi has been initialized
static bool IsWifiInitialised = false;
// flag to signal if connect is to happen
bool NF_ESP32_IsToConnect = false;
//
// Check what is the required Wi-Fi mode
// Station only or AP only or Station and AP
//
// See what network interfaces are enabled
//
wifi_mode_t NF_ESP32_CheckExpectedWifiMode()
{
wifi_mode_t mode = WIFI_MODE_NULL;
HAL_Configuration_Wireless80211 *wirelessConfig = NULL;
HAL_Configuration_WirelessAP *wirelessAPConfig = NULL;
HAL_Configuration_NetworkInterface *networkConfig =
(HAL_Configuration_NetworkInterface *)platform_malloc(sizeof(HAL_Configuration_NetworkInterface));
// check allocation
if (networkConfig == NULL)
{
return WIFI_MODE_NULL;
}
// Check Wi-Fi station available
if (g_TargetConfiguration.NetworkInterfaceConfigs->Count >= 1)
{
// get config Index 0 (Wireless station config in ESP32)
if (ConfigurationManager_GetConfigurationBlock(networkConfig, DeviceConfigurationOption_Network, 0))
{
// Wireless Config with SSID setup
if (networkConfig->InterfaceType == NetworkInterfaceType::NetworkInterfaceType_Wireless80211)
{
wirelessConfig = ConfigurationManager_GetWirelessConfigurationFromId(networkConfig->SpecificConfigId);
if (wirelessConfig != NULL)
{
if (wirelessConfig->Options & Wireless80211Configuration_ConfigurationOptions_Enable)
{
mode = WIFI_MODE_STA;
}
}
}
}
}
// Check if AP config available
if (g_TargetConfiguration.NetworkInterfaceConfigs->Count >= 2)
{
// get config Index 1 (Wireless AP config in ESP32)
if (ConfigurationManager_GetConfigurationBlock(networkConfig, DeviceConfigurationOption_Network, 1))
{
// Wireless Config with SSID setup
if (networkConfig->InterfaceType == NetworkInterfaceType::NetworkInterfaceType_WirelessAP)
{
wirelessAPConfig =
ConfigurationManager_GetWirelessAPConfigurationFromId(networkConfig->SpecificConfigId);
if (wirelessAPConfig != NULL)
{
if (wirelessAPConfig->Options & WirelessAPConfiguration_ConfigurationOptions_Enable)
{
// Use STATION + AP or just AP
mode = (mode == WIFI_MODE_STA) ? WIFI_MODE_APSTA : WIFI_MODE_AP;
}
}
}
}
}
// this one is always set
platform_free(networkConfig);
// free this one, if it was allocated
if (wirelessConfig)
{
platform_free(wirelessConfig);
}
return mode;
}
wifi_mode_t NF_ESP32_GetCurrentWifiMode()
{
wifi_mode_t current_wifi_mode;
esp_wifi_get_mode(¤t_wifi_mode);
return current_wifi_mode;
}
void NF_ESP32_DeinitWifi()
{
// clear flags
IsWifiInitialised = false;
NF_ESP32_IsToConnect = false;
esp_wifi_stop();
esp_wifi_deinit();
}
esp_err_t NF_ESP32_InitaliseWifi()
{
esp_err_t ec = ESP_OK;
wifi_mode_t expectedWifiMode = NF_ESP32_CheckExpectedWifiMode();
if (IsWifiInitialised)
{
// Check if we are running correct mode
if (NF_ESP32_GetCurrentWifiMode() != expectedWifiMode)
{
// if not force a new initialization
NF_ESP32_DeinitWifi();
}
}
// Don't init if Wi-Fi Mode null (Disabled)
if (expectedWifiMode == WIFI_MODE_NULL)
{
return ESP_FAIL;
}
if (!IsWifiInitialised)
{
// create Wi-Fi STA (ignoring return)
esp_netif_create_default_wifi_sta();
// We need to start the WIFI stack before the station can Connect
// Also we can only get the NetIf number used by ESP IDF after it has been started.
// Starting will also start the Soft- AP (if we have enabled it).
// So make sure it configured as per wireless config otherwise we will get the default SSID
if (expectedWifiMode & WIFI_MODE_AP)
{
// create AP (ignoring return)
esp_netif_create_default_wifi_ap();
}
// Initialise WiFi, allocate resource for WiFi driver, such as WiFi control structure,
// RX/TX buffer, WiFi NVS structure etc, this WiFi also start WiFi task.
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ec = esp_wifi_init(&cfg);
if (ec != ESP_OK)
{
return ec;
}
// set Wi-Fi mode
ec = esp_wifi_set_mode(expectedWifiMode);
if (ec != ESP_OK)
{
return ec;
}
// start Wi-Fi
ec = esp_wifi_start();
if (ec != ESP_OK)
{
return ec;
}
// if need, config the AP
// this can only be performed after Wi-Fi is started
if (expectedWifiMode & WIFI_MODE_AP)
{
HAL_Configuration_NetworkInterface *networkConfig =
(HAL_Configuration_NetworkInterface *)platform_malloc(sizeof(HAL_Configuration_NetworkInterface));
if (networkConfig == NULL)
{
return ESP_FAIL;
}
if (ConfigurationManager_GetConfigurationBlock(networkConfig, DeviceConfigurationOption_Network, 1))
{
// take care of configuring Soft AP
ec = NF_ESP32_WirelessAP_Configure(networkConfig);
platform_free(networkConfig);
}
if (ec != ESP_OK)
{
return ec;
}
}
IsWifiInitialised = true;
}
return ec;
}
esp_err_t NF_ESP32_Wireless_Start_Connect(HAL_Configuration_Wireless80211 *config)
{
esp_err_t ec;
// Connect directly
wifi_config_t sta_config = {};
hal_strncpy_s(
(char *)sta_config.sta.ssid,
sizeof(sta_config.sta.ssid),
(char *)config->Ssid,
hal_strlen_s((char *)config->Ssid));
hal_strncpy_s(
(char *)sta_config.sta.password,
sizeof(sta_config.sta.password),
(char *)config->Password,
hal_strlen_s((char *)config->Password));
sta_config.sta.bssid_set = false;
ec = esp_wifi_set_config(WIFI_IF_STA, &sta_config);
if (ec != ESP_OK)
{
return ec;
}
// set flag
NF_ESP32_IsToConnect = true;
// call disconnect to be sure that connect event is raised again
esp_wifi_disconnect();
// call connect
esp_wifi_connect();
return ESP_OK;
}
esp_err_t NF_ESP32_Wireless_Disconnect()
{
esp_err_t ec;
ec = esp_wifi_disconnect();
if (ec != ESP_OK)
{
return ec;
}
return ESP_OK;
}
int NF_ESP32_Wireless_Open(HAL_Configuration_NetworkInterface *config)
{
esp_err_t ec;
bool okToStartSmartConnect = false;
ec = NF_ESP32_InitaliseWifi();
if (ec != ESP_OK)
{
return SOCK_SOCKET_ERROR;
}
// Get Wireless config
HAL_Configuration_Wireless80211 *wirelessConfig =
ConfigurationManager_GetWirelessConfigurationFromId(config->SpecificConfigId);
if (wirelessConfig == NULL)
{
return SOCK_SOCKET_ERROR;
}
// Wireless station not enabled
if (!(NF_ESP32_GetCurrentWifiMode() & WIFI_MODE_STA))
{
return SOCK_SOCKET_ERROR;
}
// sanity check for Wireless station disabled
if (wirelessConfig->Options & Wireless80211Configuration_ConfigurationOptions_Disable)
{
return SOCK_SOCKET_ERROR;
}
// Connect if Auto connect and we have an SSID
if ((wirelessConfig->Options & Wireless80211Configuration_ConfigurationOptions_AutoConnect) &&
(hal_strlen_s((const char *)wirelessConfig->Ssid) > 0))
{
NF_ESP32_Wireless_Start_Connect(wirelessConfig);
// don't start smart connect
okToStartSmartConnect = false;
}
else
{
// clear flag
NF_ESP32_IsToConnect = false;
}
if (okToStartSmartConnect &&
(wirelessConfig->Options & Wireless80211Configuration_ConfigurationOptions_SmartConfig))
{
// Start Smart config (if enabled)
NF_ESP32_Start_wifi_smart_config();
// clear flag
NF_ESP32_IsToConnect = false;
}
return NF_ESP32_Wait_NetNumber(IDF_WIFI_STA_DEF);
}
bool NF_ESP32_Wireless_Close()
{
if (IsWifiInitialised)
{
esp_wifi_stop();
esp_wifi_deinit();
// clear flags
IsWifiInitialised = false;
NF_ESP32_IsToConnect = false;
}
return false;
}
// Start a scan
int NF_ESP32_Wireless_Scan()
{
wifi_scan_config_t config = {};
config.scan_type = WIFI_SCAN_TYPE_PASSIVE;
// 500ms
config.scan_time.passive = 500;
// Start a Wi-Fi scan
// When complete a Scan Complete event will be fired
esp_err_t res = esp_wifi_scan_start(&config, false);
return (int)res;
}
wifi_auth_mode_t MapAuthentication(AuthenticationType type)
{
wifi_auth_mode_t mapAuth[] = {
WIFI_AUTH_OPEN, // 0 None
WIFI_AUTH_OPEN, // 1 EAP
WIFI_AUTH_OPEN, // 2 PEAP
WIFI_AUTH_OPEN, // 3 WCN
WIFI_AUTH_OPEN, // 4 Open
WIFI_AUTH_OPEN, // 5 Shared
WIFI_AUTH_WEP, // 6 WEP
WIFI_AUTH_WPA_PSK, // 7 WPA
WIFI_AUTH_WPA_WPA2_PSK // 8 WPA2
};
return mapAuth[type];
}
esp_err_t NF_ESP32_WirelessAP_Configure(HAL_Configuration_NetworkInterface *config)
{
esp_err_t ec;
esp_netif_ip_info_t ip_info;
esp_netif_t *espNetif = esp_netif_get_handle_from_ifkey("WIFI_AP_DEF");
ec = esp_netif_get_ip_info(espNetif, &ip_info);
if (config->IPv4Address != 0)
{
ip_info.ip.addr = config->IPv4Address;
ip_info.netmask.addr = config->IPv4NetMask;
ip_info.gw.addr = config->IPv4GatewayAddress;
ec = esp_netif_set_ip_info(espNetif, &ip_info);
}
else
{
config->IPv4Address = ip_info.ip.addr;
config->IPv4NetMask = ip_info.netmask.addr;
config->IPv4GatewayAddress = ip_info.gw.addr;
}
HAL_Configuration_WirelessAP *apConfig =
ConfigurationManager_GetWirelessAPConfigurationFromId(config->SpecificConfigId);
if (apConfig == 0)
{
return ESP_FAIL;
}
wifi_config_t ap_config = {0};
hal_strncpy_s(
(char *)ap_config.ap.ssid,
sizeof(ap_config.ap.ssid),
(char *)apConfig->Ssid,
hal_strlen_s((char *)apConfig->Ssid));
hal_strncpy_s(
(char *)ap_config.ap.password,
sizeof(ap_config.ap.password),
(char *)apConfig->Password,
hal_strlen_s((char *)apConfig->Password));
ap_config.ap.ssid_len = hal_strlen_s((char *)apConfig->Ssid);
ap_config.ap.channel = apConfig->Channel;
ap_config.ap.ssid_hidden = (apConfig->Options & WirelessAPConfiguration_ConfigurationOptions_HiddenSSID) ? 1 : 0;
ap_config.ap.authmode = MapAuthentication(apConfig->Authentication);
if (hal_strlen_s((char *)ap_config.ap.password) == 0)
{
ap_config.ap.authmode = WIFI_AUTH_OPEN;
}
// Max connections for ESP32
ap_config.ap.max_connection = apConfig->MaxConnections;
if (ap_config.ap.max_connection > ESP_WIFI_MAX_CONN_NUM)
{
ap_config.ap.max_connection = ESP_WIFI_MAX_CONN_NUM;
}
ap_config.ap.beacon_interval = 100;
ec = esp_wifi_set_config(WIFI_IF_AP, &ap_config);
if (ec != ESP_OK)
{
ESP_LOGE(TAG, "WiFi set AP config - result %d", ec);
}
return ec;
}
//
// Open Wireless Soft AP
//
// If AP is enabled it will have been configured and started running when the WiFI stack is initialised
// All we need to do here is return the NetIf number used by ESP IDF
// Also make sure Wi-Fi in initialised correctly if config is changed
int IRAM_ATTR NF_ESP32_WirelessAP_Open(HAL_Configuration_NetworkInterface *config)
{
esp_err_t ec;
// Initialise Wi-Fi stack if required
ec = NF_ESP32_InitaliseWifi();
if (ec != ESP_OK)
{
return SOCK_SOCKET_ERROR;
}
// AP mode enabled ?
if (!(NF_ESP32_GetCurrentWifiMode() & WIFI_MODE_AP))
{
return SOCK_SOCKET_ERROR;
}
// Return NetIf number
// FIXME find a better way to get the netif ptr
// This becomes available on the event AP STARTED
// for the moment we just wait for it
return NF_ESP32_Wait_NetNumber(IDF_WIFI_AP_DEF);
}
//
// Closing down AP
//
// Either config being updated or shutdown
// Closing AP will also stop Station
//
bool NF_ESP32_WirelessAP_Close()
{
NF_ESP32_DeinitWifi();
return true;
}
// Wait for the network interface to become available
int NF_ESP32_Wait_NetNumber(int num)
{
int number = 0;
esp_netif_t *espNetif;
while (true)
{
switch (num)
{
case IDF_WIFI_STA_DEF:
espNetif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF");
break;
case IDF_WIFI_AP_DEF:
espNetif = esp_netif_get_handle_from_ifkey("WIFI_AP_DEF");
break;
case IDF_ETH_DEF:
espNetif = esp_netif_get_handle_from_ifkey("ETH_DEF");
break;
default:
// can't reach here
HAL_AssertEx();
break;
}
if (espNetif != NULL)
{
break;
}
vTaskDelay(20 / portTICK_PERIOD_MS);
}
return espNetif->lwip_netif->num;
}
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2012 The ANGLE Project 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 <stdlib.h>
#include <string.h>
extern "C" {
#include "compiler/preprocessor/lexer_glue.h"
#include "compiler/preprocessor/slglobals.h"
#include "compiler/preprocessor/scanner.h"
}
#include "compiler/preprocessor/new/Lexer.h"
struct InputSrcLexer
{
InputSrc base;
pp::Lexer* lexer;
};
static bool CopySymbolName(const std::string& name, yystypepp* yylvalpp)
{
if (name.length() > MAX_SYMBOL_NAME_LEN)
{
CPPErrorToInfoLog("BUFFER OVERFLOW");
return false;
}
strcpy(yylvalpp->symbol_name, name.c_str());
return true;
}
static int lex(InputSrc* in, yystypepp* yylvalpp)
{
InputSrcLexer* src = ((InputSrcLexer *)in);
pp::Token token;
int ret = src->lexer->lex(&token);
switch (ret)
{
case 0: // EOF
delete src->lexer;
free(src);
cpp->currentInput = 0;
ret = EOF;
break;
case pp::Token::IDENTIFIER:
if (CopySymbolName(token.value, yylvalpp))
{
yylvalpp->sc_ident = LookUpAddString(atable, token.value.c_str());
}
ret = CPP_IDENTIFIER;
break;
case pp::Token::CONST_INT:
if (CopySymbolName(token.value, yylvalpp))
{
yylvalpp->sc_int = atoi(token.value.c_str());
}
ret = CPP_INTCONSTANT;
break;
case pp::Token::CONST_FLOAT:
CopySymbolName(token.value, yylvalpp);
ret = CPP_FLOATCONSTANT;
break;
case pp::Token::OP_INC:
ret = CPP_INC_OP;
break;
case pp::Token::OP_DEC:
ret = CPP_DEC_OP;
break;
case pp::Token::OP_RIGHT:
ret = CPP_RIGHT_OP;
break;
case pp::Token::OP_LE:
ret = CPP_LE_OP;
break;
case pp::Token::OP_GE:
ret = CPP_GE_OP;
break;
case pp::Token::OP_EQ:
ret = CPP_EQ_OP;
break;
case pp::Token::OP_NE:
ret = CPP_NE_OP;
break;
case pp::Token::OP_AND:
ret = CPP_AND_OP;
break;
case pp::Token::OP_XOR:
ret = CPP_XOR_OP;
break;
case pp::Token::OP_OR:
ret = CPP_OR_OP;
break;
case pp::Token::OP_ADD_ASSIGN:
ret = CPP_ADD_ASSIGN;
break;
case pp::Token::OP_SUB_ASSIGN:
ret = CPP_SUB_ASSIGN;
break;
case pp::Token::OP_MUL_ASSIGN:
ret = CPP_MUL_ASSIGN;
break;
case pp::Token::OP_DIV_ASSIGN:
ret = CPP_DIV_ASSIGN;
break;
case pp::Token::OP_MOD_ASSIGN:
ret = CPP_MOD_ASSIGN;
break;
case pp::Token::OP_LEFT_ASSIGN:
ret = CPP_LEFT_ASSIGN;
break;
case pp::Token::OP_RIGHT_ASSIGN:
ret = CPP_RIGHT_ASSIGN;
break;
case pp::Token::OP_AND_ASSIGN:
ret = CPP_AND_ASSIGN;
break;
case pp::Token::OP_XOR_ASSIGN:
ret = CPP_XOR_ASSIGN;
break;
case pp::Token::OP_OR_ASSIGN:
ret = CPP_OR_ASSIGN;
break;
default:
break;
}
SetLineNumber(token.location.line);
SetStringNumber(token.location.string);
return ret;
}
InputSrc* LexerInputSrc(int count, const char* const string[], const int length[])
{
pp::Lexer* lexer = new pp::Lexer;
if (!lexer->init(count, string, length))
{
delete lexer;
return 0;
}
InputSrcLexer* in = (InputSrcLexer *) malloc(sizeof(InputSrcLexer));
memset(in, 0, sizeof(InputSrcLexer));
in->base.line = 1;
in->base.scan = lex;
in->lexer = lexer;
return &in->base;
}
<commit_msg>Fixed compile error in lexer_glue.cpp. TBR=zmo@chromium.org Review URL: https://codereview.appspot.com/6035044<commit_after>//
// Copyright (c) 2012 The ANGLE Project 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 <stdlib.h>
#include <string.h>
extern "C" {
#include "compiler/preprocessor/lexer_glue.h"
#include "compiler/preprocessor/slglobals.h"
#include "compiler/preprocessor/scanner.h"
}
#include "compiler/preprocessor/new/Lexer.h"
#include "compiler/preprocessor/new/Token.h"
struct InputSrcLexer
{
InputSrc base;
pp::Lexer* lexer;
};
static bool CopySymbolName(const std::string& name, yystypepp* yylvalpp)
{
if (name.length() > MAX_SYMBOL_NAME_LEN)
{
CPPErrorToInfoLog("BUFFER OVERFLOW");
return false;
}
strcpy(yylvalpp->symbol_name, name.c_str());
return true;
}
static int lex(InputSrc* in, yystypepp* yylvalpp)
{
InputSrcLexer* src = ((InputSrcLexer *)in);
pp::Token token;
int ret = src->lexer->lex(&token);
switch (ret)
{
case 0: // EOF
delete src->lexer;
free(src);
cpp->currentInput = 0;
ret = EOF;
break;
case pp::Token::IDENTIFIER:
if (CopySymbolName(token.value, yylvalpp))
{
yylvalpp->sc_ident = LookUpAddString(atable, token.value.c_str());
}
ret = CPP_IDENTIFIER;
break;
case pp::Token::CONST_INT:
if (CopySymbolName(token.value, yylvalpp))
{
yylvalpp->sc_int = atoi(token.value.c_str());
}
ret = CPP_INTCONSTANT;
break;
case pp::Token::CONST_FLOAT:
CopySymbolName(token.value, yylvalpp);
ret = CPP_FLOATCONSTANT;
break;
case pp::Token::OP_INC:
ret = CPP_INC_OP;
break;
case pp::Token::OP_DEC:
ret = CPP_DEC_OP;
break;
case pp::Token::OP_RIGHT:
ret = CPP_RIGHT_OP;
break;
case pp::Token::OP_LE:
ret = CPP_LE_OP;
break;
case pp::Token::OP_GE:
ret = CPP_GE_OP;
break;
case pp::Token::OP_EQ:
ret = CPP_EQ_OP;
break;
case pp::Token::OP_NE:
ret = CPP_NE_OP;
break;
case pp::Token::OP_AND:
ret = CPP_AND_OP;
break;
case pp::Token::OP_XOR:
ret = CPP_XOR_OP;
break;
case pp::Token::OP_OR:
ret = CPP_OR_OP;
break;
case pp::Token::OP_ADD_ASSIGN:
ret = CPP_ADD_ASSIGN;
break;
case pp::Token::OP_SUB_ASSIGN:
ret = CPP_SUB_ASSIGN;
break;
case pp::Token::OP_MUL_ASSIGN:
ret = CPP_MUL_ASSIGN;
break;
case pp::Token::OP_DIV_ASSIGN:
ret = CPP_DIV_ASSIGN;
break;
case pp::Token::OP_MOD_ASSIGN:
ret = CPP_MOD_ASSIGN;
break;
case pp::Token::OP_LEFT_ASSIGN:
ret = CPP_LEFT_ASSIGN;
break;
case pp::Token::OP_RIGHT_ASSIGN:
ret = CPP_RIGHT_ASSIGN;
break;
case pp::Token::OP_AND_ASSIGN:
ret = CPP_AND_ASSIGN;
break;
case pp::Token::OP_XOR_ASSIGN:
ret = CPP_XOR_ASSIGN;
break;
case pp::Token::OP_OR_ASSIGN:
ret = CPP_OR_ASSIGN;
break;
default:
break;
}
SetLineNumber(token.location.line);
SetStringNumber(token.location.string);
return ret;
}
InputSrc* LexerInputSrc(int count, const char* const string[], const int length[])
{
pp::Lexer* lexer = new pp::Lexer;
if (!lexer->init(count, string, length))
{
delete lexer;
return 0;
}
InputSrcLexer* in = (InputSrcLexer *) malloc(sizeof(InputSrcLexer));
memset(in, 0, sizeof(InputSrcLexer));
in->base.line = 1;
in->base.scan = lex;
in->lexer = lexer;
return &in->base;
}
<|endoftext|>
|
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file createRandomTest.cpp
* @author Christoph Jentzsch <jentzsch.simulationsoftware@gmail.com>
* @date 2014
* Creating a random virtual machine test.
*/
#include <string>
#include <iostream>
#include <chrono>
#include <boost/random.hpp>
#include <boost/filesystem/path.hpp>
#pragma GCC diagnostic ignored "-Wunused-parameter"
#include <json_spirit/json_spirit.h>
#include <json_spirit/json_spirit_reader_template.h>
#include <json_spirit/json_spirit_writer_template.h>
#include <libdevcore/CommonIO.h>
#include <libdevcore/CommonData.h>
#include <libevmface/Instruction.h>
#include "vm.h"
using namespace std;
using namespace json_spirit;
using namespace dev;
void doMyTests(json_spirit::mValue& v);
int main(int argc, char *argv[])
{
// if (argc != 2)
// {
// cout << "usage: createRandomTest <filename>\n";
// return 0;
// }
// create random code
boost::random::mt19937 gen;
auto now = chrono::steady_clock::now().time_since_epoch();
auto timeSinceEpoch = chrono::duration_cast<chrono::nanoseconds>(now).count();
gen.seed(static_cast<unsigned int>(timeSinceEpoch));
boost::random::uniform_int_distribution<> lengthOfCodeDist(2, 16);
boost::random::uniform_int_distribution<> opcodeDist(0, 255);
boost::random::variate_generator<boost::mt19937&,
boost::random::uniform_int_distribution<> > randGen(gen, opcodeDist);
int lengthOfCode = lengthOfCodeDist(gen);
string randomCode;
for (int i = 0; i < lengthOfCode; ++i)
{
uint8_t opcode = randGen();
// disregard all invalid commands, except of one (0x10)
if (dev::eth::isValidInstruction(dev::eth::Instruction(opcode)) || opcode == 0x10)
randomCode += toHex(toCompactBigEndian(opcode));
else
i--;
}
const string s =\
"{\n\
\"randomVMtest\": {\n\
\"env\" : {\n\
\"previousHash\" : \"5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6\",\n\
\"currentNumber\" : \"0\",\n\
\"currentGasLimit\" : \"1000000\",\n\
\"currentDifficulty\" : \"256\",\n\
\"currentTimestamp\" : 1,\n\
\"currentCoinbase\" : \"2adc25665018aa1fe0e6bc666dac8fc2697ff9ba\"\n\
},\n\
\"pre\" : {\n\
\"0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6\" : {\n\
\"balance\" : \"1000000000000000000\",\n\
\"nonce\" : 0,\n\
\"code\" : \"random\",\n\
\"storage\": {}\n\
}\n\
},\n\
\"exec\" : {\n\
\"address\" : \"0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6\",\n\
\"origin\" : \"cd1722f3947def4cf144679da39c4c32bdc35681\",\n\
\"caller\" : \"cd1722f3947def4cf144679da39c4c32bdc35681\",\n\
\"value\" : \"1000000000000000000\",\n\
\"data\" : \"\",\n\
\"gasPrice\" : \"100000000000000\",\n\
\"gas\" : \"10000\"\n\
}\n\
}\n\
}";
mValue v;
read_string(s, v);
// insert new random code
v.get_obj().find("randomVMtest")->second.get_obj().find("pre")->second.get_obj().begin()->second.get_obj()["code"] = "0x" + randomCode;
// execute code in vm
doMyTests(v);
// // write new test
// string filename = argv[1];
// writeFile(filename, asBytes(json_spirit::write_string(v, true)));
// write resultsing test to envirnoment variable
string str = "ETHEREUM_RANDOM_TEST=" + json_spirit::write_string(v, true);
char *cstr = new char[str.length() + 1];
strcpy(cstr, str.c_str());
putenv(cstr);
delete [] cstr;
return 0;
}
void doMyTests(json_spirit::mValue& v)
{
for (auto& i: v.get_obj())
{
mObject& o = i.second.get_obj();
assert(o.count("env") > 0);
assert(o.count("pre") > 0);
assert(o.count("exec") > 0);
eth::VM vm;
test::FakeExtVM fev;
fev.importEnv(o["env"].get_obj());
fev.importState(o["pre"].get_obj());
o["pre"] = mValue(fev.exportState());
fev.importExec(o["exec"].get_obj());
if (!fev.code)
{
fev.thisTxCode = get<3>(fev.addresses.at(fev.myAddress));
fev.code = &fev.thisTxCode;
}
vm.reset(fev.gas);
bytes output;
try
{
output = vm.go(fev).toBytes();
}
catch (Exception const& _e)
{
cnote << "VM did throw an exception: " << diagnostic_information(_e);
}
catch (std::exception const& _e)
{
cnote << "VM did throw an exception: " << _e.what();
}
// delete null entries in storage for the sake of comparison
for (auto &a: fev.addresses)
{
vector<u256> keystoDelete;
for (auto &s: get<2>(a.second))
{
if (s.second == 0)
keystoDelete.push_back(s.first);
}
for (auto const key: keystoDelete )
{
get<2>(a.second).erase(key);
}
}
o["env"] = mValue(fev.exportEnv());
o["exec"] = mValue(fev.exportExec());
o["post"] = mValue(fev.exportState());
o["callcreates"] = fev.exportCallCreates();
o["out"] = "0x" + toHex(output);
fev.push(o, "gas", vm.gas());
}
}
<commit_msg>Change output of random test to std::out instead of file<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file createRandomTest.cpp
* @author Christoph Jentzsch <jentzsch.simulationsoftware@gmail.com>
* @date 2014
* Creating a random virtual machine test.
*/
#include <string>
#include <iostream>
#include <chrono>
#include <boost/random.hpp>
#include <boost/filesystem/path.hpp>
#pragma GCC diagnostic ignored "-Wunused-parameter"
#include <json_spirit/json_spirit.h>
#include <json_spirit/json_spirit_reader_template.h>
#include <json_spirit/json_spirit_writer_template.h>
#include <libdevcore/CommonIO.h>
#include <libdevcore/CommonData.h>
#include <libevmface/Instruction.h>
#include "vm.h"
using namespace std;
using namespace json_spirit;
using namespace dev;
void doMyTests(json_spirit::mValue& v);
int main(int argc, char *argv[])
{
g_logVerbosity = 0;
// create random code
boost::random::mt19937 gen;
auto now = chrono::steady_clock::now().time_since_epoch();
auto timeSinceEpoch = chrono::duration_cast<chrono::nanoseconds>(now).count();
gen.seed(static_cast<unsigned int>(timeSinceEpoch));
boost::random::uniform_int_distribution<> lengthOfCodeDist(2, 16);
boost::random::uniform_int_distribution<> opcodeDist(0, 255);
boost::random::variate_generator<boost::mt19937&,
boost::random::uniform_int_distribution<> > randGen(gen, opcodeDist);
int lengthOfCode = lengthOfCodeDist(gen);
string randomCode;
for (int i = 0; i < lengthOfCode; ++i)
{
uint8_t opcode = randGen();
// disregard all invalid commands, except of one (0x10)
if (dev::eth::isValidInstruction(dev::eth::Instruction(opcode)) || opcode == 0x10)
randomCode += toHex(toCompactBigEndian(opcode));
else
i--;
}
const string s =\
"{\n\
\"randomVMtest\": {\n\
\"env\" : {\n\
\"previousHash\" : \"5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6\",\n\
\"currentNumber\" : \"0\",\n\
\"currentGasLimit\" : \"1000000\",\n\
\"currentDifficulty\" : \"256\",\n\
\"currentTimestamp\" : 1,\n\
\"currentCoinbase\" : \"2adc25665018aa1fe0e6bc666dac8fc2697ff9ba\"\n\
},\n\
\"pre\" : {\n\
\"0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6\" : {\n\
\"balance\" : \"1000000000000000000\",\n\
\"nonce\" : 0,\n\
\"code\" : \"random\",\n\
\"storage\": {}\n\
}\n\
},\n\
\"exec\" : {\n\
\"address\" : \"0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6\",\n\
\"origin\" : \"cd1722f3947def4cf144679da39c4c32bdc35681\",\n\
\"caller\" : \"cd1722f3947def4cf144679da39c4c32bdc35681\",\n\
\"value\" : \"1000000000000000000\",\n\
\"data\" : \"\",\n\
\"gasPrice\" : \"100000000000000\",\n\
\"gas\" : \"10000\"\n\
}\n\
}\n\
}";
mValue v;
read_string(s, v);
// insert new random code
v.get_obj().find("randomVMtest")->second.get_obj().find("pre")->second.get_obj().begin()->second.get_obj()["code"] = "0x" + randomCode;
// execute code in vm
doMyTests(v);
// stream to output for further handling by the bash script
cout << json_spirit::write_string(v, true);
return 0;
}
void doMyTests(json_spirit::mValue& v)
{
for (auto& i: v.get_obj())
{
mObject& o = i.second.get_obj();
assert(o.count("env") > 0);
assert(o.count("pre") > 0);
assert(o.count("exec") > 0);
eth::VM vm;
test::FakeExtVM fev;
fev.importEnv(o["env"].get_obj());
fev.importState(o["pre"].get_obj());
o["pre"] = mValue(fev.exportState());
fev.importExec(o["exec"].get_obj());
if (!fev.code)
{
fev.thisTxCode = get<3>(fev.addresses.at(fev.myAddress));
fev.code = &fev.thisTxCode;
}
vm.reset(fev.gas);
bytes output;
try
{
output = vm.go(fev).toBytes();
}
catch (Exception const& _e)
{
cnote << "VM did throw an exception: " << diagnostic_information(_e);
}
catch (std::exception const& _e)
{
cnote << "VM did throw an exception: " << _e.what();
}
// delete null entries in storage for the sake of comparison
for (auto &a: fev.addresses)
{
vector<u256> keystoDelete;
for (auto &s: get<2>(a.second))
{
if (s.second == 0)
keystoDelete.push_back(s.first);
}
for (auto const key: keystoDelete )
{
get<2>(a.second).erase(key);
}
}
o["env"] = mValue(fev.exportEnv());
o["exec"] = mValue(fev.exportExec());
o["post"] = mValue(fev.exportState());
o["callcreates"] = fev.exportCallCreates();
o["out"] = "0x" + toHex(output);
fev.push(o, "gas", vm.gas());
}
}
<|endoftext|>
|
<commit_before>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_debug.h"
#include "condor_config.h"
#include "condor_string.h"
#include "daemon_list.h"
#include "dc_collector.h"
#include "internet.h"
DaemonList::DaemonList()
{
}
DaemonList::~DaemonList( void )
{
Daemon* tmp;
list.Rewind();
while( list.Next(tmp) ) {
delete tmp;
}
}
void
DaemonList::init( daemon_t type, const char* host_list, const char* pool_list )
{
Daemon* tmp;
char* host;
char const *pool = NULL;
StringList foo;
StringList pools;
foo.initializeFromString( host_list );
foo.rewind();
if( pool_list ) {
pools.initializeFromString( pool_list );
pools.rewind();
}
while( (host = foo.next()) ) {
if( pool_list ) {
pool = pools.next();
}
tmp = buildDaemon( type, host, pool );
append( tmp );
}
}
Daemon*
DaemonList::buildDaemon( daemon_t type, const char* host, char const *pool )
{
Daemon* tmp;
switch( type ) {
case DT_COLLECTOR:
tmp = new DCCollector( host );
break;
default:
tmp = new Daemon( type, host, pool );
break;
}
return tmp;
}
/*************************************************************
** SimpleList API
************************************************************/
bool
DaemonList::append( Daemon* d) { return list.Append(d); }
bool
DaemonList::Append( Daemon* d) { return list.Append(d); }
bool
DaemonList::isEmpty( void ) { return list.IsEmpty(); }
bool
DaemonList::IsEmpty( void ) { return list.IsEmpty(); }
int
DaemonList::number( void ) { return list.Number(); }
int
DaemonList::Number( void ) { return list.Number(); }
void
DaemonList::rewind( void ) { list.Rewind(); }
void
DaemonList::Rewind( void ) { list.Rewind(); }
bool
DaemonList::current( Daemon* & d ) { return list.Current(d); }
bool
DaemonList::Current( Daemon* & d ) { return list.Current(d); }
bool
DaemonList::next( Daemon* & d ) { return list.Next(d); }
bool
DaemonList::Next( Daemon* & d ) { return list.Next(d); }
bool
DaemonList::atEnd() { return list.AtEnd(); }
bool
DaemonList::AtEnd() { return list.AtEnd(); }
void
DaemonList::deleteCurrent() { this->DeleteCurrent(); }
/*
NOTE: SimpleList does NOT delete the Daemon objects themselves,
DeleteCurrent() is only going to delete the pointer itself. Since
we're responsible for all this memory (we create the Daemon objects
in DaemonList::init() and DaemonList::buildDaemon()), we have to be
responsbile to deallocate it when we're done. We're already doing
this correctly in the DaemonList destructor, and we have to do it
here in the DeleteCurrent() interface, too.
*/
void
DaemonList::DeleteCurrent() {
Daemon* cur = NULL;
if( list.Current(cur) && cur ) {
delete cur;
}
list.DeleteCurrent();
}
CollectorList::CollectorList() {
}
CollectorList::~CollectorList() {
}
CollectorList *
CollectorList::create( const char * pool )
{
CollectorList * result = new CollectorList();
DCCollector * collector = NULL;
if (pool) {
// Eventually we might want to query this collector
// for all the other collectors in the pool....
result->append (new DCCollector (pool));
return result;
}
// Read the new names from config file
StringList collector_name_list;
char * collector_name_param = NULL;
collector_name_param = getCmHostFromConfig( "COLLECTOR" );
if( collector_name_param ) {
collector_name_list.initializeFromString(collector_name_param);
// Create collector objects
collector_name_list.rewind();
char * collector_name = NULL;
while ((collector_name = collector_name_list.next()) != NULL) {
collector = new DCCollector (collector_name);
result->append (collector);
}
} else {
// Otherwise, just return an empty list
dprintf( D_ALWAYS, "Warning: Collector information was not found in the configuration file. ClassAds will not be sent to the collector and this daemon will not join a larger Condor pool.\n");
}
if( collector_name_param ) {
free( collector_name_param );
}
return result;
}
/***
*
* Resort a collector list for locality;
* prioritize the collector that is best suited for the negotiator
* running on this machine. This minimizes the delay for fetching
* ads from the Collector by the Negotiator, which some people
* consider more critical.
*
***/
int
CollectorList::resortLocal( const char *preferred_collector )
{
// Find the collector in the list that is best suited for
// this host. This is determined either by
// a) preferred_collector passed in
// b) the collector that has the same hostname as this negotiator
char * tmp_preferred_collector = NULL;
if ( !preferred_collector ) {
// figure out our hostname for plan b) above
const char * _hostname = my_full_hostname();
if ((!_hostname) || !(*_hostname)) {
// Can't get our hostname??? fuck off
return -1;
}
tmp_preferred_collector = strdup(_hostname);
preferred_collector = preferred_collector; // So we know to free later
}
// First, pick out collector(s) that is on this host
Daemon *daemon;
SimpleList<Daemon*> prefer_list;
this->list.Rewind();
while ( this->list.Next(daemon) ) {
if ( same_host (preferred_collector, daemon->fullHostname()) ) {
this->list.DeleteCurrent();
prefer_list.Prepend( daemon );
}
}
// Walk through the list of preferred collectors,
// stuff 'em in the main "list"
this->list.Rewind();
prefer_list.Rewind();
while ( prefer_list.Next(daemon) ) {
this->list.Prepend( daemon );
}
free(tmp_preferred_collector); // Warning, preferred_collector (may have) just became invalid, so do this just before returning.
return 0;
}
int
CollectorList::sendUpdates (int cmd, ClassAd * ad1, ClassAd* ad2, bool nonblocking) {
int success_count = 0;
this->rewind();
DCCollector * daemon;
while (this->next(daemon)) {
dprintf( D_FULLDEBUG,
"Trying to update collector %s\n",
daemon->addr() );
if( daemon->sendUpdate(cmd, ad1, ad2, nonblocking) ) {
success_count++;
}
}
return success_count;
}
QueryResult
CollectorList::query(CondorQuery & cQuery, ClassAdList & adList, CondorError *errstack) {
int num_collectors = this->number();
if (num_collectors < 1) {
return Q_NO_COLLECTOR_HOST;
}
SimpleList<DCCollector *> sorted_collectors;
DCCollector * daemon;
QueryResult result;
int pass = 0;
bool problems_resolving = false;
for( pass = 1; pass <= 2; pass++ ) {
this->rewind();
while (this->next(daemon)) {
// Only try blacklisted collectors on the second pass
if( daemon->isBlacklisted() ) {
if( pass == 1 ) {
dprintf( D_ALWAYS,
"Collector %s %s is still being avoided if "
"an alternative succeeds.\n",
daemon->name(),
daemon->addr() );
continue;
}
}
else {
if( pass == 2 ) {
continue;
}
}
sorted_collectors.Append( daemon );
}
}
sorted_collectors.Rewind();
while( sorted_collectors.Next( daemon ) ) {
if ( ! daemon->addr() ) {
if ( daemon->name() ) {
dprintf( D_ALWAYS,
"Can't resolve collector %s; skipping\n",
daemon->name() );
} else {
dprintf( D_ALWAYS,
"Can't resolve nameless collector; skipping\n" );
}
problems_resolving = true;
continue;
}
dprintf (D_FULLDEBUG,
"Trying to query collector %s\n",
daemon->addr());
if( num_collectors > 1 ) {
daemon->blacklistMonitorQueryStarted();
}
result =
cQuery.fetchAds (adList, daemon->addr(), errstack);
if( num_collectors > 1 ) {
daemon->blacklistMonitorQueryFinished( result == Q_OK );
}
if (result == Q_OK) {
return result;
}
}
// only push an error if the error stack exists and is currently empty
if(problems_resolving && errstack && !errstack->code(0)) {
MyString errmsg;
char* tmplist = getCmHostFromConfig( "COLLECTOR" );
errmsg.sprintf ("Unable to resolve COLLECTOR_HOST (%s).",tmplist?tmplist:"(null)");
errstack->push("CONDOR_STATUS",1,errmsg.Value());
}
// If we've gotten here, there are no good collectors
return Q_COMMUNICATION_ERROR;
}
bool
CollectorList::next( DCCollector* & d )
{
return DaemonList::Next( (Daemon*&)d );
}
bool
CollectorList::Next( DCCollector* & d )
{
return next( d );
}
bool
CollectorList::next( Daemon* & d )
{
return DaemonList::Next( d );
}
bool
CollectorList::Next( Daemon* & d )
{
return next( d );
}
<commit_msg>Fix solaris problem with dprintf'ing a NULL string in daemon_list.cpp<commit_after>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_debug.h"
#include "condor_config.h"
#include "condor_string.h"
#include "daemon_list.h"
#include "dc_collector.h"
#include "internet.h"
DaemonList::DaemonList()
{
}
DaemonList::~DaemonList( void )
{
Daemon* tmp;
list.Rewind();
while( list.Next(tmp) ) {
delete tmp;
}
}
void
DaemonList::init( daemon_t type, const char* host_list, const char* pool_list )
{
Daemon* tmp;
char* host;
char const *pool = NULL;
StringList foo;
StringList pools;
foo.initializeFromString( host_list );
foo.rewind();
if( pool_list ) {
pools.initializeFromString( pool_list );
pools.rewind();
}
while( (host = foo.next()) ) {
if( pool_list ) {
pool = pools.next();
}
tmp = buildDaemon( type, host, pool );
append( tmp );
}
}
Daemon*
DaemonList::buildDaemon( daemon_t type, const char* host, char const *pool )
{
Daemon* tmp;
switch( type ) {
case DT_COLLECTOR:
tmp = new DCCollector( host );
break;
default:
tmp = new Daemon( type, host, pool );
break;
}
return tmp;
}
/*************************************************************
** SimpleList API
************************************************************/
bool
DaemonList::append( Daemon* d) { return list.Append(d); }
bool
DaemonList::Append( Daemon* d) { return list.Append(d); }
bool
DaemonList::isEmpty( void ) { return list.IsEmpty(); }
bool
DaemonList::IsEmpty( void ) { return list.IsEmpty(); }
int
DaemonList::number( void ) { return list.Number(); }
int
DaemonList::Number( void ) { return list.Number(); }
void
DaemonList::rewind( void ) { list.Rewind(); }
void
DaemonList::Rewind( void ) { list.Rewind(); }
bool
DaemonList::current( Daemon* & d ) { return list.Current(d); }
bool
DaemonList::Current( Daemon* & d ) { return list.Current(d); }
bool
DaemonList::next( Daemon* & d ) { return list.Next(d); }
bool
DaemonList::Next( Daemon* & d ) { return list.Next(d); }
bool
DaemonList::atEnd() { return list.AtEnd(); }
bool
DaemonList::AtEnd() { return list.AtEnd(); }
void
DaemonList::deleteCurrent() { this->DeleteCurrent(); }
/*
NOTE: SimpleList does NOT delete the Daemon objects themselves,
DeleteCurrent() is only going to delete the pointer itself. Since
we're responsible for all this memory (we create the Daemon objects
in DaemonList::init() and DaemonList::buildDaemon()), we have to be
responsbile to deallocate it when we're done. We're already doing
this correctly in the DaemonList destructor, and we have to do it
here in the DeleteCurrent() interface, too.
*/
void
DaemonList::DeleteCurrent() {
Daemon* cur = NULL;
if( list.Current(cur) && cur ) {
delete cur;
}
list.DeleteCurrent();
}
CollectorList::CollectorList() {
}
CollectorList::~CollectorList() {
}
CollectorList *
CollectorList::create( const char * pool )
{
CollectorList * result = new CollectorList();
DCCollector * collector = NULL;
if (pool) {
// Eventually we might want to query this collector
// for all the other collectors in the pool....
result->append (new DCCollector (pool));
return result;
}
// Read the new names from config file
StringList collector_name_list;
char * collector_name_param = NULL;
collector_name_param = getCmHostFromConfig( "COLLECTOR" );
if( collector_name_param ) {
collector_name_list.initializeFromString(collector_name_param);
// Create collector objects
collector_name_list.rewind();
char * collector_name = NULL;
while ((collector_name = collector_name_list.next()) != NULL) {
collector = new DCCollector (collector_name);
result->append (collector);
}
} else {
// Otherwise, just return an empty list
dprintf( D_ALWAYS, "Warning: Collector information was not found in the configuration file. ClassAds will not be sent to the collector and this daemon will not join a larger Condor pool.\n");
}
if( collector_name_param ) {
free( collector_name_param );
}
return result;
}
/***
*
* Resort a collector list for locality;
* prioritize the collector that is best suited for the negotiator
* running on this machine. This minimizes the delay for fetching
* ads from the Collector by the Negotiator, which some people
* consider more critical.
*
***/
int
CollectorList::resortLocal( const char *preferred_collector )
{
// Find the collector in the list that is best suited for
// this host. This is determined either by
// a) preferred_collector passed in
// b) the collector that has the same hostname as this negotiator
char * tmp_preferred_collector = NULL;
if ( !preferred_collector ) {
// figure out our hostname for plan b) above
const char * _hostname = my_full_hostname();
if ((!_hostname) || !(*_hostname)) {
// Can't get our hostname??? fuck off
return -1;
}
tmp_preferred_collector = strdup(_hostname);
preferred_collector = preferred_collector; // So we know to free later
}
// First, pick out collector(s) that is on this host
Daemon *daemon;
SimpleList<Daemon*> prefer_list;
this->list.Rewind();
while ( this->list.Next(daemon) ) {
if ( same_host (preferred_collector, daemon->fullHostname()) ) {
this->list.DeleteCurrent();
prefer_list.Prepend( daemon );
}
}
// Walk through the list of preferred collectors,
// stuff 'em in the main "list"
this->list.Rewind();
prefer_list.Rewind();
while ( prefer_list.Next(daemon) ) {
this->list.Prepend( daemon );
}
free(tmp_preferred_collector); // Warning, preferred_collector (may have) just became invalid, so do this just before returning.
return 0;
}
int
CollectorList::sendUpdates (int cmd, ClassAd * ad1, ClassAd* ad2, bool nonblocking) {
int success_count = 0;
this->rewind();
DCCollector * daemon;
while (this->next(daemon)) {
dprintf( D_FULLDEBUG,
"Trying to update collector %s\n",
daemon->addr() );
if( daemon->sendUpdate(cmd, ad1, ad2, nonblocking) ) {
success_count++;
}
}
return success_count;
}
QueryResult
CollectorList::query(CondorQuery & cQuery, ClassAdList & adList, CondorError *errstack) {
int num_collectors = this->number();
if (num_collectors < 1) {
return Q_NO_COLLECTOR_HOST;
}
SimpleList<DCCollector *> sorted_collectors;
DCCollector * daemon;
QueryResult result;
int pass = 0;
bool problems_resolving = false;
for( pass = 1; pass <= 2; pass++ ) {
this->rewind();
while (this->next(daemon)) {
// Only try blacklisted collectors on the second pass
if( daemon->isBlacklisted() ) {
if( pass == 1 ) {
dprintf( D_ALWAYS,
"Collector %s %s is still being avoided if "
"an alternative succeeds.\n",
daemon->name() ? daemon->name() : "unknown",
daemon->addr() ? daemon->addr() : "unknown");
continue;
}
}
else {
if( pass == 2 ) {
continue;
}
}
sorted_collectors.Append( daemon );
}
}
sorted_collectors.Rewind();
while( sorted_collectors.Next( daemon ) ) {
if ( ! daemon->addr() ) {
if ( daemon->name() ) {
dprintf( D_ALWAYS,
"Can't resolve collector %s; skipping\n",
daemon->name() );
} else {
dprintf( D_ALWAYS,
"Can't resolve nameless collector; skipping\n" );
}
problems_resolving = true;
continue;
}
dprintf (D_FULLDEBUG,
"Trying to query collector %s\n",
daemon->addr());
if( num_collectors > 1 ) {
daemon->blacklistMonitorQueryStarted();
}
result =
cQuery.fetchAds (adList, daemon->addr(), errstack);
if( num_collectors > 1 ) {
daemon->blacklistMonitorQueryFinished( result == Q_OK );
}
if (result == Q_OK) {
return result;
}
}
// only push an error if the error stack exists and is currently empty
if(problems_resolving && errstack && !errstack->code(0)) {
MyString errmsg;
char* tmplist = getCmHostFromConfig( "COLLECTOR" );
errmsg.sprintf ("Unable to resolve COLLECTOR_HOST (%s).",tmplist?tmplist:"(null)");
errstack->push("CONDOR_STATUS",1,errmsg.Value());
}
// If we've gotten here, there are no good collectors
return Q_COMMUNICATION_ERROR;
}
bool
CollectorList::next( DCCollector* & d )
{
return DaemonList::Next( (Daemon*&)d );
}
bool
CollectorList::Next( DCCollector* & d )
{
return next( d );
}
bool
CollectorList::next( Daemon* & d )
{
return DaemonList::Next( d );
}
bool
CollectorList::Next( Daemon* & d )
{
return next( d );
}
<|endoftext|>
|
<commit_before>#include <arbiter/drivers/s3.hpp>
#include <algorithm>
#include <chrono>
#include <cstring>
#include <functional>
#include <iostream>
#include <thread>
#include <arbiter/third/xml/xml.hpp>
#include <openssl/hmac.h>
namespace arbiter
{
namespace
{
const std::string baseUrl(".s3.amazonaws.com/");
std::size_t split(std::string fullPath)
{
// if (fullPath.back() == '/') fullPath.pop_back();
return fullPath.find("/");
}
std::string getBucket(std::string fullPath)
{
return fullPath.substr(0, split(fullPath));
}
std::string getObject(std::string fullPath)
{
std::string object("");
const std::size_t pos(split(fullPath));
if (pos != std::string::npos)
{
object = fullPath.substr(pos + 1);
}
return object;
}
std::string getQueryString(const Query& query)
{
std::string result;
bool first(true);
for (const auto& q : query)
{
result += (first ? "?" : "&") + q.first + "=" + q.second;
first = false;
}
return result;
}
typedef Xml::xml_node<> XmlNode;
const std::string badResponse("Unexpected contents in AWS response");
}
AwsAuth::AwsAuth(const std::string access, const std::string hidden)
: m_access(access)
, m_hidden(hidden)
{ }
std::string AwsAuth::access() const
{
return m_access;
}
std::string AwsAuth::hidden() const
{
return m_hidden;
}
S3Driver::S3Driver(HttpPool& pool, const AwsAuth auth)
: m_pool(pool)
, m_auth(auth)
{ }
std::vector<char> S3Driver::get(const std::string rawPath)
{
return get(rawPath, Query());
}
std::vector<char> S3Driver::get(const std::string rawPath, const Query& query)
{
const std::string bucket(getBucket(rawPath));
const std::string object(getObject(rawPath));
const std::string path(
"http://" + bucket + baseUrl + object + getQueryString(query));
const Headers headers(httpGetHeaders(rawPath));
auto http(m_pool.acquire());
HttpResponse res(http.get(path, headers));
if (res.ok()) return res.data();
else throw std::runtime_error("Couldn't S3 GET " + rawPath);
}
void S3Driver::put(std::string rawPath, const std::vector<char>& data)
{
const std::string bucket(getBucket(rawPath));
const std::string object(getObject(rawPath));
const std::string path("http://" + bucket + baseUrl + object);
const Headers headers(httpPutHeaders(rawPath));
auto http(m_pool.acquire());
if (!http.put(path, data, headers).ok())
{
throw std::runtime_error("Couldn't S3 PUT to " + rawPath);
}
}
std::vector<std::string> S3Driver::glob(std::string path, bool verbose)
{
std::vector<std::string> results;
if (path.size() < 2 || path.substr(path.size() - 2) != "/*")
{
throw std::runtime_error("Invalid glob path: " + path);
}
path.resize(path.size() - 2);
// https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html
const std::string bucket(getBucket(path));
const std::string object(getObject(path));
const std::string prefix(object.empty() ? "" : object + "/");
Query query;
if (prefix.size()) query["prefix"] = prefix;
bool more(false);
do
{
if (verbose) std::cout << "." << std::flush;
auto data = get(bucket + "/", query);
data.push_back('\0');
Xml::xml_document<> xml;
// May throw Xml::parse_error.
xml.parse<0>(data.data());
if (XmlNode* topNode = xml.first_node("ListBucketResult"))
{
if (XmlNode* truncNode = topNode->first_node("IsTruncated"))
{
std::string t(truncNode->value());
std::transform(t.begin(), t.end(), t.begin(), tolower);
more = (t == "true");
}
XmlNode* conNode(topNode->first_node("Contents"));
if (!conNode) throw std::runtime_error(badResponse);
for ( ; conNode; conNode = conNode->next_sibling())
{
if (XmlNode* keyNode = conNode->first_node("Key"))
{
std::string key(keyNode->value());
// The prefix may contain slashes (i.e. is a sub-dir)
// but we only include the top level after that.
if (key.find('/', prefix.size()) == std::string::npos)
{
results.push_back("s3://" + bucket + "/" + key);
if (more)
{
query["marker"] =
(object.size() ? object + "/" : "") +
key.substr(prefix.size());
}
}
}
else
{
throw std::runtime_error(badResponse);
}
}
}
else
{
throw std::runtime_error(badResponse);
}
xml.clear();
}
while (more);
return results;
}
std::vector<std::string> S3Driver::httpGetHeaders(std::string filePath) const
{
const std::string httpDate(getHttpDate());
const std::string signedEncodedString(
getSignedEncodedString(
"GET",
filePath,
httpDate));
const std::string dateHeader("Date: " + httpDate);
const std::string authHeader(
"Authorization: AWS " +
m_auth.access() + ":" +
signedEncodedString);
std::vector<std::string> headers;
headers.push_back(dateHeader);
headers.push_back(authHeader);
return headers;
}
std::vector<std::string> S3Driver::httpPutHeaders(std::string filePath) const
{
const std::string httpDate(getHttpDate());
const std::string signedEncodedString(
getSignedEncodedString(
"PUT",
filePath,
httpDate,
"application/octet-stream"));
const std::string typeHeader("Content-Type: application/octet-stream");
const std::string dateHeader("Date: " + httpDate);
const std::string authHeader(
"Authorization: AWS " +
m_auth.access() + ":" +
signedEncodedString);
std::vector<std::string> headers;
headers.push_back(typeHeader);
headers.push_back(dateHeader);
headers.push_back(authHeader);
headers.push_back("Transfer-Encoding:");
headers.push_back("Expect:");
return headers;
}
std::string S3Driver::getHttpDate() const
{
time_t rawTime;
char charBuf[80];
time(&rawTime);
tm* timeInfo = localtime(&rawTime);
strftime(charBuf, 80, "%a, %d %b %Y %H:%M:%S %z", timeInfo);
std::string stringBuf(charBuf);
return stringBuf;
}
std::string S3Driver::getSignedEncodedString(
std::string command,
std::string file,
std::string httpDate,
std::string contentType) const
{
const std::string toSign(getStringToSign(
command,
file,
httpDate,
contentType));
const std::vector<char> signedData(signString(toSign));
return encodeBase64(signedData);
}
std::string S3Driver::getStringToSign(
std::string command,
std::string file,
std::string httpDate,
std::string contentType) const
{
return
command + "\n" +
"\n" +
contentType + "\n" +
httpDate + "\n" +
"/" + file;
}
std::vector<char> S3Driver::signString(std::string input) const
{
std::vector<char> hash(20, ' ');
unsigned int outLength(0);
HMAC_CTX ctx;
HMAC_CTX_init(&ctx);
HMAC_Init(
&ctx,
m_auth.hidden().data(),
m_auth.hidden().size(),
EVP_sha1());
HMAC_Update(
&ctx,
reinterpret_cast<const uint8_t*>(input.data()),
input.size());
HMAC_Final(
&ctx,
reinterpret_cast<uint8_t*>(hash.data()),
&outLength);
HMAC_CTX_cleanup(&ctx);
return hash;
}
std::string S3Driver::encodeBase64(std::vector<char> data) const
{
std::vector<uint8_t> input;
for (std::size_t i(0); i < data.size(); ++i)
{
char c(data[i]);
input.push_back(*reinterpret_cast<uint8_t*>(&c));
}
const std::string vals(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
std::size_t fullSteps(input.size() / 3);
while (input.size() % 3) input.push_back(0);
uint8_t* pos(input.data());
uint8_t* end(input.data() + fullSteps * 3);
std::string output(fullSteps * 4, '_');
std::size_t outIndex(0);
const uint32_t mask(0x3F);
while (pos != end)
{
uint32_t chunk((*pos) << 16 | *(pos + 1) << 8 | *(pos + 2));
output[outIndex++] = vals[(chunk >> 18) & mask];
output[outIndex++] = vals[(chunk >> 12) & mask];
output[outIndex++] = vals[(chunk >> 6) & mask];
output[outIndex++] = vals[chunk & mask];
pos += 3;
}
if (end != input.data() + input.size())
{
const std::size_t num(pos - end == 1 ? 2 : 3);
uint32_t chunk(*(pos) << 16 | *(pos + 1) << 8 | *(pos + 2));
output.push_back(vals[(chunk >> 18) & mask]);
output.push_back(vals[(chunk >> 12) & mask]);
if (num == 3) output.push_back(vals[(chunk >> 6) & mask]);
}
while (output.size() % 4) output.push_back('=');
return output;
}
} // namespace arbiter
<commit_msg>Simplify S3 path splitting.<commit_after>#include <arbiter/drivers/s3.hpp>
#include <algorithm>
#include <chrono>
#include <cstring>
#include <functional>
#include <iostream>
#include <thread>
#include <arbiter/third/xml/xml.hpp>
#include <openssl/hmac.h>
namespace arbiter
{
namespace
{
const std::string baseUrl(".s3.amazonaws.com/");
std::string getQueryString(const Query& query)
{
std::string result;
bool first(true);
for (const auto& q : query)
{
result += (first ? "?" : "&") + q.first + "=" + q.second;
first = false;
}
return result;
}
struct Resource
{
Resource(std::string fullPath)
{
const std::size_t split(fullPath.find("/"));
bucket = fullPath.substr(0, split);
if (split != std::string::npos)
{
object = fullPath.substr(split + 1);
}
}
std::string buildPath(Query query = Query()) const
{
const std::string queryString(getQueryString(query));
return "http://" + bucket + baseUrl + object + queryString;
}
std::string bucket;
std::string object;
};
typedef Xml::xml_node<> XmlNode;
const std::string badResponse("Unexpected contents in AWS response");
}
AwsAuth::AwsAuth(const std::string access, const std::string hidden)
: m_access(access)
, m_hidden(hidden)
{ }
std::string AwsAuth::access() const
{
return m_access;
}
std::string AwsAuth::hidden() const
{
return m_hidden;
}
S3Driver::S3Driver(HttpPool& pool, const AwsAuth auth)
: m_pool(pool)
, m_auth(auth)
{ }
std::vector<char> S3Driver::get(const std::string rawPath)
{
return get(rawPath, Query());
}
std::vector<char> S3Driver::get(const std::string rawPath, const Query& query)
{
const Resource resource(rawPath);
const std::string path(resource.buildPath(query));
const Headers headers(httpGetHeaders(rawPath));
auto http(m_pool.acquire());
HttpResponse res(http.get(path, headers));
if (res.ok())
{
return res.data();
}
else
{
// TODO If verbose:
std::cout << std::string(res.data().begin(), res.data().end()) <<
std::endl;
throw std::runtime_error("Couldn't S3 GET " + rawPath);
}
}
void S3Driver::put(std::string rawPath, const std::vector<char>& data)
{
const Resource resource(rawPath);
const std::string path(resource.buildPath());
const Headers headers(httpPutHeaders(rawPath));
auto http(m_pool.acquire());
if (!http.put(path, data, headers).ok())
{
throw std::runtime_error("Couldn't S3 PUT to " + rawPath);
}
}
std::vector<std::string> S3Driver::glob(std::string path, bool verbose)
{
std::vector<std::string> results;
if (path.size() < 2 || path.substr(path.size() - 2) != "/*")
{
throw std::runtime_error("Invalid glob path: " + path);
}
path.resize(path.size() - 2);
// https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html
const Resource resource(path);
const std::string& bucket(resource.bucket);
const std::string& object(resource.object);
const std::string prefix(
resource.object.empty() ? "" : resource.object + "/");
Query query;
if (prefix.size()) query["prefix"] = prefix;
bool more(false);
do
{
if (verbose) std::cout << "." << std::flush;
auto data = get(resource.bucket + "/", query);
data.push_back('\0');
Xml::xml_document<> xml;
// May throw Xml::parse_error.
xml.parse<0>(data.data());
if (XmlNode* topNode = xml.first_node("ListBucketResult"))
{
if (XmlNode* truncNode = topNode->first_node("IsTruncated"))
{
std::string t(truncNode->value());
std::transform(t.begin(), t.end(), t.begin(), tolower);
more = (t == "true");
}
XmlNode* conNode(topNode->first_node("Contents"));
if (!conNode) throw std::runtime_error(badResponse);
for ( ; conNode; conNode = conNode->next_sibling())
{
if (XmlNode* keyNode = conNode->first_node("Key"))
{
std::string key(keyNode->value());
// The prefix may contain slashes (i.e. is a sub-dir)
// but we only include the top level after that.
if (key.find('/', prefix.size()) == std::string::npos)
{
results.push_back("s3://" + bucket + "/" + key);
if (more)
{
query["marker"] =
(object.size() ? object + "/" : "") +
key.substr(prefix.size());
}
}
}
else
{
throw std::runtime_error(badResponse);
}
}
}
else
{
throw std::runtime_error(badResponse);
}
xml.clear();
}
while (more);
return results;
}
std::vector<std::string> S3Driver::httpGetHeaders(std::string filePath) const
{
const std::string httpDate(getHttpDate());
const std::string signedEncodedString(
getSignedEncodedString(
"GET",
filePath,
httpDate));
const std::string dateHeader("Date: " + httpDate);
const std::string authHeader(
"Authorization: AWS " +
m_auth.access() + ":" +
signedEncodedString);
std::vector<std::string> headers;
headers.push_back(dateHeader);
headers.push_back(authHeader);
return headers;
}
std::vector<std::string> S3Driver::httpPutHeaders(std::string filePath) const
{
const std::string httpDate(getHttpDate());
const std::string signedEncodedString(
getSignedEncodedString(
"PUT",
filePath,
httpDate,
"application/octet-stream"));
const std::string typeHeader("Content-Type: application/octet-stream");
const std::string dateHeader("Date: " + httpDate);
const std::string authHeader(
"Authorization: AWS " +
m_auth.access() + ":" +
signedEncodedString);
std::vector<std::string> headers;
headers.push_back(typeHeader);
headers.push_back(dateHeader);
headers.push_back(authHeader);
headers.push_back("Transfer-Encoding:");
headers.push_back("Expect:");
return headers;
}
std::string S3Driver::getHttpDate() const
{
time_t rawTime;
char charBuf[80];
time(&rawTime);
tm* timeInfo = localtime(&rawTime);
strftime(charBuf, 80, "%a, %d %b %Y %H:%M:%S %z", timeInfo);
std::string stringBuf(charBuf);
return stringBuf;
}
std::string S3Driver::getSignedEncodedString(
std::string command,
std::string file,
std::string httpDate,
std::string contentType) const
{
const std::string toSign(getStringToSign(
command,
file,
httpDate,
contentType));
const std::vector<char> signedData(signString(toSign));
return encodeBase64(signedData);
}
std::string S3Driver::getStringToSign(
std::string command,
std::string file,
std::string httpDate,
std::string contentType) const
{
return
command + "\n" +
"\n" +
contentType + "\n" +
httpDate + "\n" +
"/" + file;
}
std::vector<char> S3Driver::signString(std::string input) const
{
std::vector<char> hash(20, ' ');
unsigned int outLength(0);
HMAC_CTX ctx;
HMAC_CTX_init(&ctx);
HMAC_Init(
&ctx,
m_auth.hidden().data(),
m_auth.hidden().size(),
EVP_sha1());
HMAC_Update(
&ctx,
reinterpret_cast<const uint8_t*>(input.data()),
input.size());
HMAC_Final(
&ctx,
reinterpret_cast<uint8_t*>(hash.data()),
&outLength);
HMAC_CTX_cleanup(&ctx);
return hash;
}
std::string S3Driver::encodeBase64(std::vector<char> data) const
{
std::vector<uint8_t> input;
for (std::size_t i(0); i < data.size(); ++i)
{
char c(data[i]);
input.push_back(*reinterpret_cast<uint8_t*>(&c));
}
const std::string vals(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
std::size_t fullSteps(input.size() / 3);
while (input.size() % 3) input.push_back(0);
uint8_t* pos(input.data());
uint8_t* end(input.data() + fullSteps * 3);
std::string output(fullSteps * 4, '_');
std::size_t outIndex(0);
const uint32_t mask(0x3F);
while (pos != end)
{
uint32_t chunk((*pos) << 16 | *(pos + 1) << 8 | *(pos + 2));
output[outIndex++] = vals[(chunk >> 18) & mask];
output[outIndex++] = vals[(chunk >> 12) & mask];
output[outIndex++] = vals[(chunk >> 6) & mask];
output[outIndex++] = vals[chunk & mask];
pos += 3;
}
if (end != input.data() + input.size())
{
const std::size_t num(pos - end == 1 ? 2 : 3);
uint32_t chunk(*(pos) << 16 | *(pos + 1) << 8 | *(pos + 2));
output.push_back(vals[(chunk >> 18) & mask]);
output.push_back(vals[(chunk >> 12) & mask]);
if (num == 3) output.push_back(vals[(chunk >> 6) & mask]);
}
while (output.size() % 4) output.push_back('=');
return output;
}
} // namespace arbiter
<|endoftext|>
|
<commit_before>#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <stdlib.h>
#include <cassert>
#include <algorithm>
#include <bitset>
#include <omp.h>
using namespace std;
typedef vector<int>::size_type vint_sz;
typedef vector<vector<int> >::size_type vvint_sz;
typedef vector<int>::const_iterator vint_itr;
typedef vector<vector<int> >::const_iterator vvint_itr;
//vector<int> people;
//vector<int> combination;
//
//as you can see, everything is public for now as I am creating this in 3 hours before the game.
//I will add appropriate abstraction/encapsulation once I get the algorithm correct.
class Player {
public:
Player(){}
Player(string n,float pts,string pos,float sal):name(n),points(pts),position(pos), salary(sal){}
string name;
float points;
string position;
float salary;
};
class Team {
public:
Team(const vector<Player> & p):parray(p){
players.clear();
totalpoints=0.0;
totalsalary=0.0;
}
float getPoints() {
return totalpoints;
}
float points(){
for(vint_sz i=0; i < players.size();i++)
totalpoints+=parray[players[i]].points;
return totalpoints;
}
float salary(){
for(vint_sz i=0; i < players.size();i++)
totalsalary+=parray[players[i]].salary;
return totalsalary;
}
void printinfo(){
cout<<"======"<<endl;
cout<<"points: "<<totalpoints<<endl;
cout<<"salary: "<<totalsalary<<endl;
cout<<"members:"<<endl;
for (vint_sz i=0; i <players.size();i++){
const Player & p=parray[players[i]];
cout<<p.position<<": " <<p.name<<endl;
}
}
void engagebits(){
for(vint_sz i=0; i < players.size(); i++){
assert(players[i] < bs.size());
bs.set(players[i]);
}
}
bitset<200> getbs(void) const {
return bs;
}
int diff(const Team * t) {
return (bs | t->getbs()).count();
}
vector<int> players; //contains index to players
float totalpoints;
float totalsalary;
const vector<Player> & parray;
bitset<200> bs;//bit set for players
};
vector<Player> players;
vector<Team *> teams;
void pretty_print(const vector<int>& v) {
static int count = 0;
cout << "combination no " << (++count) << ": [ ";
for (vector<int>::size_type i = 0; i < v.size(); ++i) { cout << v[i] << " "; }
cout << "] " << endl;
}
void get_1combo(const vector<int>& v, vector<int> & dest) {
for (vector<int>::size_type i = 0; i < v.size(); ++i) {
dest.push_back( v[i]) ;
}
}
void print_comb(vector<int> & comb){
for (vint_itr i=comb.begin(); i!=comb.end(); i++)
cout<<(*i)<<" ";
cout<<endl;
}
void go(int offset, int k, const vector<int>& source, vector<int>& tmp, vector<vector<int> >& combs) {
if (k == 0) {
//pretty_print(tmp);
vector<int> newc;
get_1combo(tmp,newc);
combs.push_back(newc);
return;
}
for (vector<int>::size_type i = offset; i <= source.size() - k; ++i) {
tmp.push_back(source[i]);
go(i+1, k-1, source,tmp, combs);
tmp.pop_back();
}
}
void print_all(const vector<vector<int> > & combs){
for(vector<vector<int> >::const_iterator i = combs.begin() ; i != combs.end(); i++){
for (vint_itr j=i->begin(); j != i->end(); j++){
cout<<*j<<" ";
}
cout<<endl;
}
}
void csv_reader(vector<Player> & players){
std::ifstream data("projections.csv");
std::string line;
while(std::getline(data,line))
{
int i=0;
stringstream lineStream(line);
string cell;
Player p;
while(std::getline(lineStream,cell,','))
{
i++;
if (i == 1){
p.name = cell;
}
else if (i==2){
p.position = cell;
}
else if (i==3){
cell = cell.substr(0, cell.size()-1);
p.salary = atof(cell.c_str())*1000.0;
}
else if (i==4){
p.points = atof(cell.c_str());
}
// cout<<"cell: "<<cell<<" "<<endl;
}
players.push_back(p);
//cout<<endl;
}
}
void print_combs(vector<vector<int> > c,const vector<Player> & p){
int cnt=0;
for(vvint_sz i=0; i < c.size(); i++){
float totalpoints=0.0;
float totalsalary=0.0;
for(vvint_sz j=0; j < c[i].size(); j++){
totalpoints+=p[c[i][j]].points;
totalsalary+=p[c[i][j]].salary;
}
cout<<++cnt<<": "<<(totalpoints/totalsalary)*1000.0<<endl;
}
}
struct myclass {
bool operator() (vector<int> a, vector<int> b){
float tp1=0.0;
float tp2=0.0;
float ts1=0.0;
float ts2=0.0;
for(vint_sz i=0;i<a.size();i++){
tp1+=players[a[i]].points;
ts1+=players[a[i]].salary;
}
for(vint_sz i=0;i<b.size();i++){
tp2+=players[b[i]].points;
ts2+=players[b[i]].salary;
}
return (tp1/ts1 > tp2/ts2);
}
} mysorter;
struct teamsort {
bool operator() (Team *a, Team *b){
return a->getPoints() > b->getPoints();
}
} teamsorter;
static float progress = 0.0;
void progress_bar(float prog, int teamsize){
progress += prog;
//cout<<"progress: "<<progress<<endl;
//while (progress < 1.0) {
int barWidth = 70;
std::cout << "[";
int pos = barWidth * progress;
for (int i = 0; i < barWidth; ++i) {
if (i < pos) std::cout << "=";
else if (i == pos) std::cout << ">";
else std::cout << " ";
}
std::cout << "] " << int(progress * 100.0) << " "<< teamsize <<" %\r";
std::cout.flush();
//progress += 0.16; // for demonstration only
//}
//cout << std::endl;
}
//this function will segregate teams into different buckets which depend on the "hamming distance" with the top team
void Hedge(vector<Team *>& teams, vector<Team *>& a_list){
//put the top team as the seed
assert(!teams.empty());
a_list.push_back(teams[0]);
int unique_players = 10;//there are currently 10 unique players
unsigned int standard=8;//we want another 10 unique playeres to join the group
for (vector<Team *>::size_type i=1; i < teams.size(); i++){//1-pass only
bitset<200> current=0;
bitset<200> newteam=teams[i]->getbs();
for (vector<Team *>::size_type j=0; j < a_list.size(); j++){
current |= a_list[j]->getbs();
}
if ( ((newteam | current).count()-current.count()) >= standard){//if passed
a_list.push_back(teams[i]);
}
}
cout<<"# Hedged positions:"<<a_list.size()<<endl;
cout<<"Range of scores:"<<a_list[0]->getPoints()<<" - " <<a_list[a_list.size()-1]->getPoints()<<endl;
for (vector<Team *>::size_type i=0; i < a_list.size(); i++){
a_list[i]->printinfo();
}
}
int main() {
//int n = 5, k = 3;
vector< vector<int> > combs;
vector<int> source;
vector<int> tmp;//temporary storage needed by algorithm
int cutoff = 100;//limit combinations based on value;
vector<Team *> a_list;
vector<int> Ce;
vector<int> SF;
vector<int> SG;
vector<int> PF;
vector<int> PG;
vector<unsigned long long int> bins(11,0);//0 - <310, 1 - <320, ... , < 420
vector<vector<int> > Ce_comb;
vector<vector<int> > SF_comb;
vector<vector<int> > SG_comb;
vector<vector<int> > PF_comb;
vector<vector<int> > PG_comb;
//for (int i = 0; i < n; ++i) { source.push_back(i*3); }
//go(0, k,source, tmp, combs);
//print_all(combs);
//Scan Player
//
csv_reader(players);
//Segrate Positions
for (vector<int>::size_type i=0; i < players.size();i++){
if (players[i].position == "C")
Ce.push_back(i);
else if (players[i].position == "SF")
SF.push_back(i);
else if (players[i].position == "PF")
PF.push_back(i);
else if (players[i].position == "PG")
PG.push_back(i);
else if (players[i].position == "SG")
SG.push_back(i);
}
//Get Combinations
go(0,1,Ce,tmp,Ce_comb);
go(0,2,SF,tmp,SF_comb);
go(0,2,SG,tmp,SG_comb);
go(0,2,PF,tmp,PF_comb);
go(0,2,PG,tmp,PG_comb);
cout<<"Sizes: "<<endl;
cout<<"Centers: "<<Ce_comb.size()<<endl;
cout<<"SF: "<<SF_comb.size()<<endl;
cout<<"SG: "<<SG_comb.size()<<endl;
cout<<"PF: "<<PF_comb.size()<<endl;
cout<<"PG: "<<PG_comb.size()<<endl;
cout<<endl;
//sort the arrays first
//
sort(Ce_comb.begin(),Ce_comb.end(), mysorter);
sort(SF_comb.begin(),SF_comb.end(), mysorter);
sort(SG_comb.begin(),SG_comb.end(), mysorter);
sort(PF_comb.begin(),PF_comb.end(), mysorter);
sort(PG_comb.begin(),PG_comb.end(), mysorter);
SF_comb.erase(SF_comb.begin()+cutoff, SF_comb.end());
SG_comb.erase(SG_comb.begin()+cutoff, SG_comb.end());
PF_comb.erase(PF_comb.begin()+cutoff, PF_comb.end());
PG_comb.erase(PG_comb.begin()+cutoff, PG_comb.end());
/*print_combs(Ce_comb,players)k
cout<<"centers end"<<endl;
print_combs(SF_comb,players);
cout<<"SF end"<<endl;
print_combs(SG_comb,players);
cout<<"SG end"<<endl;*/
//We need to prune these combinations ...
//Big-Loop, Adding each team that meets the score
//
float teamsize = Ce_comb.size() * SF_comb.size() * SG_comb.size() * PF_comb.size() * PG_comb.size();
cout<<"there are "<< teamsize<<" teams.."<<endl;
cout<<"iterating ... "<<endl;
#pragma omp parallel for
for (vvint_itr i = Ce_comb.begin(); i != Ce_comb.end();i++){
for (vvint_itr j = SF_comb.begin(); j != SF_comb.end();j++){
for (vvint_itr k = SG_comb.begin(); k != SG_comb.end();k++){
for (vvint_itr l = PF_comb.begin(); l != PF_comb.end();l++){
for (vvint_itr m = PG_comb.begin(); m != PG_comb.end();m++){
//5 for loops here for each position
Team *t = new Team(players);
//Centers
for(vint_itr n = i->begin(); n != i->end(); n++)
t->players.push_back(*n);
//SF
for(vint_itr n = j->begin(); n != j->end(); n++)
t->players.push_back(*n);
//SG
for(vint_itr n = k->begin(); n != k->end(); n++)
t->players.push_back(*n);
//PF
for(vint_itr n = l->begin(); n != l->end(); n++)
t->players.push_back(*n);
//PG
for(vint_itr n = m->begin(); n != m->end(); n++)
t->players.push_back(*n);
float salary = t->salary();
float points = t->points();
if (points > 250.0 && salary<=60000 && salary > 58500){
//t->printinfo();
// #pragma omp atomic
teams.push_back(t);
//bins[int((points-300)/10)]++;
}
else
delete t;
}
}
}
}
// cout<<"%\r";
// cout.flush();
progress_bar((teamsize/Ce_comb.size())/teamsize, teams.size());
// cout<<endl;
}
cout<<endl;
//*/
cout<<"There are "<<teams.size()<<" possible teams"<<endl;
cout<<"sorting "<< teams.size()<<" teams .. "<<endl;
sort(teams.begin(), teams.end(), teamsorter);
cout<<"top 20 team points"<<endl;
for (vector<Team *>::size_type i=0; i < 20; i++){
cout<<i<<": "<<teams[i]->getPoints()<<endl;
}
cout<<"Getting ready to hedge positions..."<<endl;
for (vector<Team *>::size_type i=0; i < teams.size(); i++){
teams[i]->engagebits();
}
cout<<"Done bit setting.."<<endl;
/*for (vector<Team *>::size_type i=0; i < 20; i++){
teams[i]->printinfo();
}*/
//
//Sort the team array
//
//Segregate to arrays with Hamming distance
//
//
//for(int i=0; i< 5; i++){
// cout<<players[i].name<<" "<<players[i].salary<<" "<<players[i].points<<endl;
// }
cout<<"Hedging ..."<<endl;
Hedge(teams,a_list);
return 0;
}
<commit_msg>initial<commit_after>#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <stdlib.h>
#include <cassert>
#include <algorithm>
#include <bitset>
#include <omp.h>
using namespace std;
typedef vector<int>::size_type vint_sz;
typedef vector<vector<int> >::size_type vvint_sz;
typedef vector<int>::const_iterator vint_itr;
typedef vector<vector<int> >::const_iterator vvint_itr;
#define BIT 200
//vector<int> people;
//vector<int> combination;
//
//as you can see, everything is public for now as I am creating this in 3 hours before the game.
//I will add appropriate abstraction/encapsulation once I get the algorithm correct.
vector<Player> players;
vector<Team *> teams;
void pretty_print(const vector<int>& v) {
static int count = 0;
cout << "combination no " << (++count) << ": [ ";
for (vector<int>::size_type i = 0; i < v.size(); ++i) { cout << v[i] << " "; }
cout << "] " << endl;
}
void get_1combo(const vector<int>& v, vector<int> & dest) {
for (vector<int>::size_type i = 0; i < v.size(); ++i) {
dest.push_back( v[i]) ;
}
}
void print_comb(vector<int> & comb){
for (vint_itr i=comb.begin(); i!=comb.end(); i++)
cout<<(*i)<<" ";
cout<<endl;
}
void go(int offset, int k, const vector<int>& source, vector<int>& tmp, vector<vector<int> >& combs) {
if (k == 0) {
//pretty_print(tmp);
vector<int> newc;
get_1combo(tmp,newc);
combs.push_back(newc);
return;
}
for (vector<int>::size_type i = offset; i <= source.size() - k; ++i) {
tmp.push_back(source[i]);
go(i+1, k-1, source,tmp, combs);
tmp.pop_back();
}
}
void print_all(const vector<vector<int> > & combs){
for(vector<vector<int> >::const_iterator i = combs.begin() ; i != combs.end(); i++){
for (vint_itr j=i->begin(); j != i->end(); j++){
cout<<*j<<" ";
}
cout<<endl;
}
}
void csv_reader(vector<Player> & players){
std::ifstream data("projections.csv");
std::string line;
while(std::getline(data,line))
{
int i=0;
stringstream lineStream(line);
string cell;
Player p;
while(std::getline(lineStream,cell,','))
{
i++;
if (i == 1){
p.name = cell;
}
else if (i==2){
p.position = cell;
}
else if (i==3){
cell = cell.substr(0, cell.size()-1);
p.salary = atof(cell.c_str())*1000.0;
}
else if (i==4){
p.points = atof(cell.c_str());
}
// cout<<"cell: "<<cell<<" "<<endl;
}
players.push_back(p);
//cout<<endl;
}
}
void print_combs(vector<vector<int> > c,const vector<Player> & p){
int cnt=0;
for(vvint_sz i=0; i < c.size(); i++){
float totalpoints=0.0;
float totalsalary=0.0;
for(vvint_sz j=0; j < c[i].size(); j++){
totalpoints+=p[c[i][j]].points;
totalsalary+=p[c[i][j]].salary;
}
cout<<++cnt<<": "<<(totalpoints/totalsalary)*1000.0<<endl;
}
}
struct myclass {
bool operator() (vector<int> a, vector<int> b){
float tp1=0.0;
float tp2=0.0;
float ts1=0.0;
float ts2=0.0;
for(vint_sz i=0;i<a.size();i++){
tp1+=players[a[i]].points;
ts1+=players[a[i]].salary;
}
for(vint_sz i=0;i<b.size();i++){
tp2+=players[b[i]].points;
ts2+=players[b[i]].salary;
}
return (tp1/ts1 > tp2/ts2);
}
} mysorter;
struct teamsort {
bool operator() (Team *a, Team *b){
return a->getPoints() > b->getPoints();
}
} teamsorter;
static float progress = 0.0;
void progress_bar(float prog, int teamsize){
progress += prog;
//cout<<"progress: "<<progress<<endl;
//while (progress < 1.0) {
int barWidth = 70;
std::cout << "[";
int pos = barWidth * progress;
for (int i = 0; i < barWidth; ++i) {
if (i < pos) std::cout << "=";
else if (i == pos) std::cout << ">";
else std::cout << " ";
}
std::cout << "] " << int(progress * 100.0) << " "<< teamsize <<" %\r";
std::cout.flush();
//progress += 0.16; // for demonstration only
//}
//cout << std::endl;
}
//this function will segregate teams into different buckets which depend on the "hamming distance" with the top team
void Hedge(vector<Team *>& teams, vector<Team *>& a_list){
//put the top team as the seed
assert(!teams.empty());
a_list.push_back(teams[0]);
//int unique_players = 10;//there are currently 10 unique players
unsigned int standard=8;//we want another 10 unique playeres to join the group
for (vector<Team *>::size_type i=1; i < teams.size(); i++){//1-pass only
bitset<BIT> current=0;
bitset<BIT> newteam=teams[i]->getbs();
for (vector<Team *>::size_type j=0; j < a_list.size(); j++){
current |= a_list[j]->getbs();
}
if ( ((newteam | current).count()-current.count()) >= standard){//if passed
a_list.push_back(teams[i]);
}
}
cout<<"# Hedged positions:"<<a_list.size()<<endl;
cout<<"Range of scores:"<<a_list[0]->getPoints()<<" - " <<a_list[a_list.size()-1]->getPoints()<<endl;
for (vector<Team *>::size_type i=0; i < a_list.size(); i++){
a_list[i]->printinfo();
}
}
int main() {
//int n = 5, k = 3;
vector< vector<int> > combs;
vector<int> source;
vector<int> tmp;//temporary storage needed by algorithm
int cutoff = 50;//limit combinations based on value;
int num_threads=4;
vector<Team *> a_list;
vector<vector<Team *> > teams_omp;
vector<int> Ce;
vector<int> SF;
vector<int> SG;
vector<int> PF;
vector<int> PG;
vector<unsigned long long int> bins(11,0);//0 - <310, 1 - <320, ... , < 420
vector<vector<int> > Ce_comb;
vector<vector<int> > SF_comb;
vector<vector<int> > SG_comb;
vector<vector<int> > PF_comb;
vector<vector<int> > PG_comb;
//for (int i = 0; i < n; ++i) { source.push_back(i*3); }
//go(0, k,source, tmp, combs);
//print_all(combs);
//Scan Player
//
csv_reader(players);
//Segrate Positions
for (vector<int>::size_type i=0; i < players.size();i++){
if (players[i].position == "C")
Ce.push_back(i);
else if (players[i].position == "SF")
SF.push_back(i);
else if (players[i].position == "PF")
PF.push_back(i);
else if (players[i].position == "PG")
PG.push_back(i);
else if (players[i].position == "SG")
SG.push_back(i);
}
//Get Combinations
go(0,1,Ce,tmp,Ce_comb);
go(0,2,SF,tmp,SF_comb);
go(0,2,SG,tmp,SG_comb);
go(0,2,PF,tmp,PF_comb);
go(0,2,PG,tmp,PG_comb);
cout<<"Sizes: "<<endl;
cout<<"Centers: "<<Ce_comb.size()<<endl;
cout<<"SF: "<<SF_comb.size()<<endl;
cout<<"SG: "<<SG_comb.size()<<endl;
cout<<"PF: "<<PF_comb.size()<<endl;
cout<<"PG: "<<PG_comb.size()<<endl;
cout<<endl;
//sort the arrays first
//
sort(Ce_comb.begin(),Ce_comb.end(), mysorter);
sort(SF_comb.begin(),SF_comb.end(), mysorter);
sort(SG_comb.begin(),SG_comb.end(), mysorter);
sort(PF_comb.begin(),PF_comb.end(), mysorter);
sort(PG_comb.begin(),PG_comb.end(), mysorter);
SF_comb.erase(SF_comb.begin()+cutoff, SF_comb.end());
SG_comb.erase(SG_comb.begin()+cutoff, SG_comb.end());
PF_comb.erase(PF_comb.begin()+cutoff, PF_comb.end());
PG_comb.erase(PG_comb.begin()+cutoff, PG_comb.end());
/*print_combs(Ce_comb,players)k
cout<<"centers end"<<endl;
print_combs(SF_comb,players);
cout<<"SF end"<<endl;
print_combs(SG_comb,players);
cout<<"SG end"<<endl;*/
//We need to prune these combinations ...
//Big-Loop, Adding each team that meets the score
//
float teamsize = Ce_comb.size() * SF_comb.size() * SG_comb.size() * PF_comb.size() * PG_comb.size();
cout<<"there are "<< teamsize<<" teams.."<<endl;
cout<<"iterating ... "<<endl;
teams_omp.resize(PF_comb.size());
//omp_set_num_threads(4);
for (vvint_sz i = 0;i < Ce_comb.size(); i++){
for (vvint_sz j = 0; j < SF_comb.size(); j++){
for (vvint_sz k = 0; k < SG_comb.size() ; k++){
#pragma omp parallel for
for (vvint_sz l = 0;l < PF_comb.size() ;l++){
for (vvint_sz m = 0 ; m < PG_comb.size() ;m++){
//5 for loops here for each position
Team *t = new Team(players);
//Centers
for(vint_sz n = 0; n < Ce_comb[i].size(); n++)
t->players.push_back(Ce_comb[i][n]);
//SF
for(vint_sz n = 0; n < SF_comb[j].size(); n++)
t->players.push_back(SF_comb[j][n]);
//SG
for(vint_sz n = 0; n < SG_comb[k].size(); n++)
t->players.push_back(SG_comb[k][n]);
//PF
for(vint_sz n = 0; n < PF_comb[l].size(); n++)
t->players.push_back(PF_comb[l][n]);
//PG
for(vint_sz n = 0; n < PG_comb[m].size(); n++)
t->players.push_back(PG_comb[m][n]);
float salary = t->salary();
float points = t->points();
if (points > 250.0 && salary<=60000 && salary > 59000){
//t->printinfo();
//#pragma omp critical
teams_omp[l].push_back(t);
//bins[int((points-300)/10)]++;
}
else
delete t;
}
}
}
}
//progress_bar((teamsize/Ce_comb.size())/teamsize, teams.size());
progress_bar((teamsize/Ce_comb.size())/teamsize, teams.size());
}
cout<<endl;
for(vector<vector<Team *> >::size_type i=0; i < teams_omp.size();i++){
copy(teams_omp[i].begin(), teams_omp[i].end(), back_inserter(teams));
}
cout<<"There are "<<teams.size()<<" possible teams"<<endl;
cout<<"sorting "<< teams.size()<<" teams .. "<<endl;
sort(teams.begin(), teams.end(), teamsorter);
cout<<"top 20 team points"<<endl;
for (vector<Team *>::size_type i=0; i < 20; i++){
cout<<i<<": "<<teams[i]->getPoints()<<endl;
}
cout<<"Getting ready to hedge positions..."<<endl;
for (vector<Team *>::size_type i=0; i < teams.size(); i++){
teams[i]->engagebits();
}
cout<<"Done bit setting.."<<endl;
/*for (vector<Team *>::size_type i=0; i < 20; i++){
teams[i]->printinfo();
}*/
//
//Sort the team array
//
//Segregate to arrays with Hamming distance
//
//
//for(int i=0; i< 5; i++){
// cout<<players[i].name<<" "<<players[i].salary<<" "<<players[i].points<<endl;
// }
cout<<"Hedging ..."<<endl;
Hedge(teams,a_list);
for (vector<Team *>::size_type i=0; i < teams.size(); i++){
delete teams[i];
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <complex>
#include <iostream>
#include <utility>
#include <vector>
#include <fftw3.h>
#include "helpers.h"
using namespace std;
typedef pair<int, int> location;
int main(int argc, char** argv) {
// read program options
if (argc != 5) {
printf("Wrong number of arguments.\n");
return 1;
}
const char* filename = argv[1];
const int n = atoi(argv[2]);
const char* output_filename = argv[3];
const int num_trials = atoi(argv[4]);
vector<double> running_times;
const int n2 = n * n;
const int center_size = n / 16;
const int center_size_sq = center_size * center_size;
const int slab_size = n / 256;
const int total_slab_size = slab_size * n;
// detection threshold
const float threshold = 0.35;
// number of frequencies per bin
const int bsize_slab = n / slab_size;
const int bsize_center = n / center_size;
// read input data (frequency domain)
vector<complexf> data(n2);
if (!read_input(data.data(), filename, n)) {
return 1;
}
// output
vector<complexf> output(n2);
// fftw setup
// center part
complexf* center_data = static_cast<complexf*>(
fftwf_malloc(sizeof(fftwf_complex) * center_size_sq));
fftwf_plan center_plan = fftwf_plan_dft_2d(
center_size, center_size,
reinterpret_cast<fftwf_complex*>(center_data),
reinterpret_cast<fftwf_complex*>(center_data),
FFTW_FORWARD, FFTW_MEASURE);
// horizontal and vertical slabs
complexf* horiz_data = static_cast<complexf*>(
fftwf_malloc(sizeof(fftwf_complex) * total_slab_size));
complexf* vert_data = static_cast<complexf*>(
fftwf_malloc(sizeof(fftwf_complex) * total_slab_size));
fftwf_plan horiz_plan = fftwf_plan_dft_2d(
slab_size, n,
reinterpret_cast<fftwf_complex*>(horiz_data),
reinterpret_cast<fftwf_complex*>(horiz_data),
FFTW_FORWARD, FFTW_MEASURE);
fftwf_plan vert_plan = fftwf_plan_dft_2d(
n, slab_size,
reinterpret_cast<fftwf_complex*>(vert_data),
reinterpret_cast<fftwf_complex*>(vert_data),
FFTW_FORWARD, FFTW_MEASURE);
// diagonal slabs
complexf* diaghi_data = static_cast<complexf*>(
fftwf_malloc(sizeof(fftwf_complex) * total_slab_size));
complexf* diaglo_data = static_cast<complexf*>(
fftwf_malloc(sizeof(fftwf_complex) * total_slab_size));
for (int trial = 0; trial < num_trials; ++trial) {
auto overall_start = chrono::high_resolution_clock::now();
// copy in data
// center part
for (int row = 0; row < center_size; ++row) {
int orig_row = n / 2 - center_size / 2 + row;
memcpy(&(center_data[row * center_size]),
&(data[orig_row * n + n / 2 - center_size / 2]),
center_size * sizeof(complexf));
}
// horizontal and vertical slabs
for (int row = 0; row < slab_size; ++row) {
int orig_row = n / 2 - slab_size / 2 + row;
memcpy(&(horiz_data[row * n]),
&(data[orig_row * n]),
n * sizeof(complexf));
}
for (int row = 0; row < n; ++row) {
memcpy(&(vert_data[row * slab_size]),
&(data[row * n + n / 2 - slab_size / 2]),
slab_size * sizeof(complexf));
}
// diagonal slabs
for (int col = 0; col < n; ++col) {
for (int row = 0; row < slab_size; ++row) {
int orig_row = col - slab_size / 2 + row;
if (orig_row < 0) {
orig_row += n;
}
if (orig_row >= n) {
orig_row -= n;
}
diaghi_data[row * n + col] = data[orig_row * n + col];
}
}
for (int col = 0; col < n; ++col) {
for (int row = 0; row < slab_size; ++row) {
int orig_row = -col + slab_size / 2 - row;
if (orig_row < 0) {
orig_row += n;
}
if (orig_row < 0) {
orig_row += n;
}
if (orig_row >= n) {
orig_row -= n;
}
//if (col == 0 || col == 1) {
// cout << orig_row << endl;
//}
diaglo_data[row * n + col] = data[orig_row * n + col];
}
}
//cout << diaglo_data[0] << " " << diaglo_data[1] << " " << diaglo_data[2]
// << endl;
auto end = chrono::high_resolution_clock::now();
chrono::duration<double> copy_time = end - overall_start;
cout << "Data copy time: " << copy_time.count() << " s" << endl;
// execute fftw
auto start = chrono::high_resolution_clock::now();
// center part
fftwf_execute(center_plan);
//cout << center_data[0] << " " << center_data[1] << " " << center_data[2]
// << endl;
// horizontal and vertical slabs
fftwf_execute(horiz_plan);
fftwf_execute(vert_plan);
//cout << horiz_data[0] << " " << horiz_data[1] << " " << horiz_data[2]
// << endl;
//cout << vert_data[0] << " " << vert_data[1] << " " << vert_data[2]
// << endl;
// diagonal slabs
fftwf_execute_dft(horiz_plan,
reinterpret_cast<fftwf_complex*>(diaghi_data),
reinterpret_cast<fftwf_complex*>(diaghi_data));
fftwf_execute_dft(horiz_plan,
reinterpret_cast<fftwf_complex*>(diaglo_data),
reinterpret_cast<fftwf_complex*>(diaglo_data));
//cout << diaghi_data[0] << " " << diaghi_data[1] << " " << diaghi_data[2]
// << endl;
//cout << diaglo_data[0] << " " << diaglo_data[1] << " " << diaglo_data[2]
// << endl;
end = chrono::high_resolution_clock::now();
chrono::duration<double> fftw_time = end - start;
cout << "FFTW time: " << fftw_time.count() << " s" << endl;
start = chrono::high_resolution_clock::now();
vector<location> large_bins;
for (int row = 0; row < center_size; ++row) {
for (int col = 0; col < center_size; ++col) {
if (abs(center_data[row * center_size + col]) > threshold) {
large_bins.push_back(make_pair(row, col));
}
}
}
end = chrono::high_resolution_clock::now();
chrono::duration<double> selection_time = end - start;
cout << "Peak selection time: " << selection_time.count() << " s" << endl;
/*cout << "Num large: " << large_bins.size() << endl;
for (auto loc : large_bins) {
cout << loc.first << " " << loc.second << endl;
}*/
int inner_iter = 0;
start = chrono::high_resolution_clock::now();
for (auto loc : large_bins) {
int col_bin = loc.second;
int row_bin = loc.first;
int row_start = row_bin * bsize_center - bsize_center / 2 - 1;
int row_end = row_bin * bsize_center + bsize_center / 2 - 1;
int col_start = col_bin * bsize_center - bsize_center / 2 - 1;
int col_end = col_bin * bsize_center + bsize_center / 2 - 1;
for (int row = row_start; row <= row_end; ++row) {
for (int col = col_start; col <= col_end; ++col) {
inner_iter += 1;
/*if (col != 503 || row != 1511) {
continue;
}
cout << row << " " << col << endl;*/
if (row >= n) {
row -= n;
}
if (row < 0) {
row += n;
}
if (col >= n) {
col -= n;
}
if (col < 0) {
col += n;
}
int center_bin_row = (row + 1) / bsize_center;
if (row + 1 - center_bin_row * bsize_center >= bsize_center / 2) {
center_bin_row += 1;
if (center_bin_row >= n) {
center_bin_row -= n;
}
}
int center_bin_col = (col + 1) / bsize_center;
if (col + 1 - center_bin_col * bsize_center >= bsize_center / 2) {
center_bin_col += 1;
if (center_bin_col >= n) {
center_bin_col -= n;
}
}
//cout << center_bin_row << " " << center_bin_col << endl;
float center_value = abs(center_data[
center_bin_row * center_size + center_bin_col]);
int horiz_bin_row = (row + 1) / bsize_slab;
if (row + 1 - horiz_bin_row * bsize_slab >= bsize_slab / 2) {
horiz_bin_row += 1;
if (horiz_bin_row >= n) {
horiz_bin_row -= n;
}
}
//cout << "horiz_bin_row: " << horiz_bin_row << endl;
float horiz_value = abs(horiz_data[horiz_bin_row * n + col]);
int vert_bin_col = (col + 1) / bsize_slab;
if (col + 1 - vert_bin_col * bsize_slab >= bsize_slab / 2) {
vert_bin_col += 1;
if (vert_bin_col >= n) {
vert_bin_col -= n;
}
}
//cout << "vert_bin_col: " << vert_bin_col << endl;
float vert_value = abs(vert_data[row * slab_size + vert_bin_col]);
int diaghi_bin_row = horiz_bin_row;
int diaghi_bin_col = row + col;
if (diaghi_bin_col >= n) {
diaghi_bin_col -= n;
}
//cout << "diaghi_bin_row: " << diaghi_bin_row
// << " diaghi_bin_col: " << diaghi_bin_col << endl;
float diaghi_value =
abs(diaghi_data[diaghi_bin_row * n + diaghi_bin_col]);
int diaglo_bin_row = vert_bin_col;
int diaglo_bin_col = -row + col;
if (diaglo_bin_col < 0) {
diaglo_bin_col += n;
}
//cout << "diaglo_bin_row: " << diaglo_bin_row
// << " diaglo_bin_col: " << diaglo_bin_col << endl;
float diaglo_value =
abs(diaglo_data[diaglo_bin_row * n + diaglo_bin_col]);
float average_value = (center_value + horiz_value + vert_value
+ diaghi_value + diaglo_value) / 5.0f;
output[row * n + col] = average_value;
/*cout << center_value << " " << horiz_value << " "
<< vert_value << " " << diaghi_value << " "
<< diaglo_value << " " << average_value << endl;*/
}
}
}
end = chrono::high_resolution_clock::now();
chrono::duration<double> interpolation_time = end - start;
cout << "Interpolation time: " << interpolation_time.count() << " s"
<< endl;
chrono::duration<double> overall_time = end - overall_start;
cout << "Overall time: " << overall_time.count() << " s" << endl;
cout << "Data copy time: "
<< copy_time.count() / overall_time.count() * 100.0 << "%" << endl;
cout << "FFTW time: "
<< fftw_time.count() / overall_time.count() * 100.0 << "%" << endl;
cout << "Selection time: "
<< selection_time.count() / overall_time.count() * 100.0 << "%"
<< endl;
cout << "Interpolation time: "
<< interpolation_time.count() / overall_time.count() * 100.0 << "%"
<< endl;
cout << "Number of selected large bins: " << large_bins.size() << endl;
cout << "Total inner interpolation iterations: " << inner_iter << endl;
cout << "--------------------------------------------------------" << endl;
running_times.push_back(overall_time.count());
}
// clean-up
fftwf_destroy_plan(center_plan);
fftwf_free(center_data);
fftwf_destroy_plan(horiz_plan);
fftwf_free(horiz_data);
fftwf_destroy_plan(vert_plan);
fftwf_free(vert_data);
fftwf_free(diaghi_data);
fftwf_free(diaglo_data);
if (strcmp(output_filename, "none") != 0) {
if (!write_data(output.data(), output_filename, n)) {
return 1;
}
}
sort(running_times.begin(), running_times.end());
int outliers = 0.1 * running_times.size();
double mean = 0.0;
for (size_t ii = 0; ii < running_times.size() - outliers; ++ii) {
mean += running_times[ii];
}
mean /= (running_times.size() - outliers);
cout << "Mean running time (excluding top " << outliers << " trials): "
<< mean << " s" << endl;
/*
// Compute statistics
complex<float> sum = 0;
for (int ii = 0; ii < n2; ++ii) {
sum += data[ii];
}
cout << "Sum: " << sum << endl;
complex<float> sumsq = 0;
for (int ii = 0; ii < n2; ++ii) {
sumsq += data[ii] * data[ii];
}
cout << "Sum of squares: " << sumsq << endl;
float sumabs = 0;
for (int ii = 0; ii < n2; ++ii) {
sumabs += abs(data[ii]);
}
cout << "Sum of absolute values: " << sumabs << endl;
*/
return 0;
}
<commit_msg>making output a bit more neat<commit_after>#include <algorithm>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <complex>
#include <iostream>
#include <utility>
#include <vector>
#include <fftw3.h>
#include "helpers.h"
using namespace std;
typedef pair<int, int> location;
int main(int argc, char** argv) {
// read program options
if (argc != 5) {
printf("Wrong number of arguments.\n");
return 1;
}
const char* filename = argv[1];
const int n = atoi(argv[2]);
const char* output_filename = argv[3];
const int num_trials = atoi(argv[4]);
vector<double> running_times;
const int n2 = n * n;
const int center_size = n / 16;
const int center_size_sq = center_size * center_size;
const int slab_size = n / 256;
const int total_slab_size = slab_size * n;
// detection threshold
const float threshold = 0.35;
// number of frequencies per bin
const int bsize_slab = n / slab_size;
const int bsize_center = n / center_size;
// read input data (frequency domain)
vector<complexf> data(n2);
if (!read_input(data.data(), filename, n)) {
return 1;
}
// output
vector<complexf> output(n2);
// fftw setup
// center part
complexf* center_data = static_cast<complexf*>(
fftwf_malloc(sizeof(fftwf_complex) * center_size_sq));
fftwf_plan center_plan = fftwf_plan_dft_2d(
center_size, center_size,
reinterpret_cast<fftwf_complex*>(center_data),
reinterpret_cast<fftwf_complex*>(center_data),
FFTW_FORWARD, FFTW_MEASURE);
// horizontal and vertical slabs
complexf* horiz_data = static_cast<complexf*>(
fftwf_malloc(sizeof(fftwf_complex) * total_slab_size));
complexf* vert_data = static_cast<complexf*>(
fftwf_malloc(sizeof(fftwf_complex) * total_slab_size));
fftwf_plan horiz_plan = fftwf_plan_dft_2d(
slab_size, n,
reinterpret_cast<fftwf_complex*>(horiz_data),
reinterpret_cast<fftwf_complex*>(horiz_data),
FFTW_FORWARD, FFTW_MEASURE);
fftwf_plan vert_plan = fftwf_plan_dft_2d(
n, slab_size,
reinterpret_cast<fftwf_complex*>(vert_data),
reinterpret_cast<fftwf_complex*>(vert_data),
FFTW_FORWARD, FFTW_MEASURE);
// diagonal slabs
complexf* diaghi_data = static_cast<complexf*>(
fftwf_malloc(sizeof(fftwf_complex) * total_slab_size));
complexf* diaglo_data = static_cast<complexf*>(
fftwf_malloc(sizeof(fftwf_complex) * total_slab_size));
for (int trial = 0; trial < num_trials; ++trial) {
auto overall_start = chrono::high_resolution_clock::now();
// copy in data
// center part
for (int row = 0; row < center_size; ++row) {
int orig_row = n / 2 - center_size / 2 + row;
memcpy(&(center_data[row * center_size]),
&(data[orig_row * n + n / 2 - center_size / 2]),
center_size * sizeof(complexf));
}
// horizontal and vertical slabs
for (int row = 0; row < slab_size; ++row) {
int orig_row = n / 2 - slab_size / 2 + row;
memcpy(&(horiz_data[row * n]),
&(data[orig_row * n]),
n * sizeof(complexf));
}
for (int row = 0; row < n; ++row) {
memcpy(&(vert_data[row * slab_size]),
&(data[row * n + n / 2 - slab_size / 2]),
slab_size * sizeof(complexf));
}
// diagonal slabs
for (int col = 0; col < n; ++col) {
for (int row = 0; row < slab_size; ++row) {
int orig_row = col - slab_size / 2 + row;
if (orig_row < 0) {
orig_row += n;
}
if (orig_row >= n) {
orig_row -= n;
}
diaghi_data[row * n + col] = data[orig_row * n + col];
}
}
for (int col = 0; col < n; ++col) {
for (int row = 0; row < slab_size; ++row) {
int orig_row = -col + slab_size / 2 - row;
if (orig_row < 0) {
orig_row += n;
}
if (orig_row < 0) {
orig_row += n;
}
if (orig_row >= n) {
orig_row -= n;
}
diaglo_data[row * n + col] = data[orig_row * n + col];
}
}
//cout << diaglo_data[0] << " " << diaglo_data[1] << " " << diaglo_data[2]
// << endl;
auto end = chrono::high_resolution_clock::now();
chrono::duration<double> copy_time = end - overall_start;
// execute fftw
auto start = chrono::high_resolution_clock::now();
// center part
fftwf_execute(center_plan);
//cout << center_data[0] << " " << center_data[1] << " " << center_data[2]
// << endl;
// horizontal and vertical slabs
fftwf_execute(horiz_plan);
fftwf_execute(vert_plan);
//cout << horiz_data[0] << " " << horiz_data[1] << " " << horiz_data[2]
// << endl;
//cout << vert_data[0] << " " << vert_data[1] << " " << vert_data[2]
// << endl;
// diagonal slabs
fftwf_execute_dft(horiz_plan,
reinterpret_cast<fftwf_complex*>(diaghi_data),
reinterpret_cast<fftwf_complex*>(diaghi_data));
fftwf_execute_dft(horiz_plan,
reinterpret_cast<fftwf_complex*>(diaglo_data),
reinterpret_cast<fftwf_complex*>(diaglo_data));
//cout << diaghi_data[0] << " " << diaghi_data[1] << " " << diaghi_data[2]
// << endl;
//cout << diaglo_data[0] << " " << diaglo_data[1] << " " << diaglo_data[2]
// << endl;
end = chrono::high_resolution_clock::now();
chrono::duration<double> fftw_time = end - start;
start = chrono::high_resolution_clock::now();
vector<location> large_bins;
for (int row = 0; row < center_size; ++row) {
for (int col = 0; col < center_size; ++col) {
if (abs(center_data[row * center_size + col]) > threshold) {
large_bins.push_back(make_pair(row, col));
}
}
}
end = chrono::high_resolution_clock::now();
chrono::duration<double> selection_time = end - start;
/*cout << "Num large: " << large_bins.size() << endl;
for (auto loc : large_bins) {
cout << loc.first << " " << loc.second << endl;
}*/
int inner_iter = 0;
start = chrono::high_resolution_clock::now();
for (auto loc : large_bins) {
int col_bin = loc.second;
int row_bin = loc.first;
int row_start = row_bin * bsize_center - bsize_center / 2 - 1;
int row_end = row_bin * bsize_center + bsize_center / 2 - 1;
int col_start = col_bin * bsize_center - bsize_center / 2 - 1;
int col_end = col_bin * bsize_center + bsize_center / 2 - 1;
for (int row = row_start; row <= row_end; ++row) {
for (int col = col_start; col <= col_end; ++col) {
inner_iter += 1;
/*if (col != 503 || row != 1511) {
continue;
}
cout << row << " " << col << endl;*/
if (row >= n) {
row -= n;
}
if (row < 0) {
row += n;
}
if (col >= n) {
col -= n;
}
if (col < 0) {
col += n;
}
int center_bin_row = (row + 1) / bsize_center;
if (row + 1 - center_bin_row * bsize_center >= bsize_center / 2) {
center_bin_row += 1;
if (center_bin_row >= n) {
center_bin_row -= n;
}
}
int center_bin_col = (col + 1) / bsize_center;
if (col + 1 - center_bin_col * bsize_center >= bsize_center / 2) {
center_bin_col += 1;
if (center_bin_col >= n) {
center_bin_col -= n;
}
}
//cout << center_bin_row << " " << center_bin_col << endl;
float center_value = abs(center_data[
center_bin_row * center_size + center_bin_col]);
int horiz_bin_row = (row + 1) / bsize_slab;
if (row + 1 - horiz_bin_row * bsize_slab >= bsize_slab / 2) {
horiz_bin_row += 1;
if (horiz_bin_row >= n) {
horiz_bin_row -= n;
}
}
//cout << "horiz_bin_row: " << horiz_bin_row << endl;
float horiz_value = abs(horiz_data[horiz_bin_row * n + col]);
int vert_bin_col = (col + 1) / bsize_slab;
if (col + 1 - vert_bin_col * bsize_slab >= bsize_slab / 2) {
vert_bin_col += 1;
if (vert_bin_col >= n) {
vert_bin_col -= n;
}
}
//cout << "vert_bin_col: " << vert_bin_col << endl;
float vert_value = abs(vert_data[row * slab_size + vert_bin_col]);
int diaghi_bin_row = horiz_bin_row;
int diaghi_bin_col = row + col;
if (diaghi_bin_col >= n) {
diaghi_bin_col -= n;
}
//cout << "diaghi_bin_row: " << diaghi_bin_row
// << " diaghi_bin_col: " << diaghi_bin_col << endl;
float diaghi_value =
abs(diaghi_data[diaghi_bin_row * n + diaghi_bin_col]);
int diaglo_bin_row = vert_bin_col;
int diaglo_bin_col = -row + col;
if (diaglo_bin_col < 0) {
diaglo_bin_col += n;
}
//cout << "diaglo_bin_row: " << diaglo_bin_row
// << " diaglo_bin_col: " << diaglo_bin_col << endl;
float diaglo_value =
abs(diaglo_data[diaglo_bin_row * n + diaglo_bin_col]);
float average_value = (center_value + horiz_value + vert_value
+ diaghi_value + diaglo_value) / 5.0f;
output[row * n + col] = average_value;
/*cout << center_value << " " << horiz_value << " "
<< vert_value << " " << diaghi_value << " "
<< diaglo_value << " " << average_value << endl;*/
}
}
}
end = chrono::high_resolution_clock::now();
chrono::duration<double> interpolation_time = end - start;
chrono::duration<double> overall_time = end - overall_start;
cout << "Data copy time: " << copy_time.count() << " s ("
<< copy_time.count() / overall_time.count() * 100.0 << "%)" << endl;
cout << "FFTW time: " << fftw_time.count() << " s ("
<< fftw_time.count() / overall_time.count() * 100.0 << "%)" << endl;
cout << "Selection time: " << selection_time.count() << " s ("
<< selection_time.count() / overall_time.count() * 100.0
<< "%)" << endl;
cout << "Interpolation time: " << interpolation_time.count() << " s ("
<< interpolation_time.count() / overall_time.count() * 100.0 << "%)"
<< endl;
cout << "Overall time: " << overall_time.count() << " s" << endl;
cout << "Number of selected large bins: " << large_bins.size() << endl;
cout << "Total inner interpolation iterations: " << inner_iter << endl;
cout << "--------------------------------------------------------" << endl;
running_times.push_back(overall_time.count());
}
// clean-up
fftwf_destroy_plan(center_plan);
fftwf_free(center_data);
fftwf_destroy_plan(horiz_plan);
fftwf_free(horiz_data);
fftwf_destroy_plan(vert_plan);
fftwf_free(vert_data);
fftwf_free(diaghi_data);
fftwf_free(diaglo_data);
if (strcmp(output_filename, "none") != 0) {
if (!write_data(output.data(), output_filename, n)) {
return 1;
}
}
sort(running_times.begin(), running_times.end());
int outliers = 0.1 * running_times.size();
double mean = 0.0;
for (size_t ii = 0; ii < running_times.size() - outliers; ++ii) {
mean += running_times[ii];
}
mean /= (running_times.size() - outliers);
cout << "Mean running time (excluding top " << outliers << " trials): "
<< mean << " s" << endl;
/*
// Compute statistics
complex<float> sum = 0;
for (int ii = 0; ii < n2; ++ii) {
sum += data[ii];
}
cout << "Sum: " << sum << endl;
complex<float> sumsq = 0;
for (int ii = 0; ii < n2; ++ii) {
sumsq += data[ii] * data[ii];
}
cout << "Sum of squares: " << sumsq << endl;
float sumabs = 0;
for (int ii = 0; ii < n2; ++ii) {
sumabs += abs(data[ii]);
}
cout << "Sum of absolute values: " << sumabs << endl;
*/
return 0;
}
<|endoftext|>
|
<commit_before>#include <stdlib.h>
#include <string>
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <queue>
#include "xsi_loader.h"
#include <portal.h>
#include <sock_utils.h>
#include <GeneratedTypes.h>
#include <XsimMemSlaveRequest.h>
#include <XsimMemSlaveIndication.h>
XsimMemSlaveIndicationProxy *memSlaveIndicationProxy;
class XsimMemSlaveRequest;
XsimMemSlaveRequest *memSlaveRequest;
//deleteme
std::string getcurrentdir()
{
return get_current_dir_name();
}
class xsiport {
Xsi::Loader &xsiInstance;
int port;
//int direction;
const char *name;
int width;
s_xsi_vlog_logicval value;
public:
xsiport(Xsi::Loader &loader, const char *name, int bits = 1)
: xsiInstance(loader), port(-1), name(name), width(bits)
{
value = {1, 1};
port = xsiInstance.get_port_number(name);
//width = xsiInstance.get_int_port(port, xsiHDLValueSize);
std::cout << "Port name=" << name << " number=" << port << std::endl;
}
int read();
void write(int val);
int valid() { return port >= 0; }
};
int xsiport::read()
{
xsiInstance.get_value(port, &value);
int mask = (width == 32) ? -1 : ((1 << width) - 1);
if (value.bVal != 0) {
char charval[] = { '0', '1', 'Z', 'X' };
int encoding = (value.aVal & mask) | ((value.bVal & mask) << 1);
fprintf(stderr, "port %2d.%16s value=%08x.%08x mask=%08x width=%2d %c\n", port, name, value.aVal, value.bVal, mask, width, charval[encoding]);
}
return value.aVal & mask;
}
void xsiport::write(int aVal)
{
value.aVal = aVal;
value.bVal = 0;
xsiInstance.put_value(port, &value);
}
class XsimMemSlaveRequest : public XsimMemSlaveRequestWrapper {
struct idInfo {
int number;
int id;
int valid;
} ids[16];
int portal_count;
public:
struct readreq {
uint32_t addr;
};
struct writereq {
uint32_t addr;
uint32_t data;
};
std::queue<readreq> readreqs;
std::queue<uint32_t> readdata;
std::queue<writereq> writereqs;
std::queue<uint32_t> sinkbeats;
int connected;
XsimMemSlaveRequest(int id, PortalItemFunctions *item, void *param, PortalPoller *poller = 0) : XsimMemSlaveRequestWrapper(id, item, param, poller), connected(0) { }
~XsimMemSlaveRequest() {}
virtual void connect () {
connected = 1;
}
virtual void enableint( const uint32_t fpgaId, const uint32_t val);
virtual void read ( const uint32_t fpgaId, const uint32_t addr );
virtual void write ( const uint32_t fpgaId, const uint32_t addr, const uint32_t data );
virtual void msgSink ( const uint32_t data );
void directory( const uint32_t fpgaNumber, const uint32_t fpgaId, const uint32_t last );
int fpgaNumber(int fpgaId);
int fpgaId(int fpgaNumber);
};
void XsimMemSlaveRequest::enableint( const uint32_t fpgaId, const uint32_t val)
{
int number = fpgaNumber(fpgaId);
uint32_t hwaddr = number << 16 | 4;
writereq req = { hwaddr, val };
fprintf(stderr, "[%s:%d] id=%d number=%d addr=%08x\n", __FUNCTION__, __LINE__, fpgaId, number, hwaddr);
writereqs.push(req);
}
void XsimMemSlaveRequest::read ( const uint32_t fpgaId, const uint32_t addr )
{
int number = fpgaNumber(fpgaId);
fprintf(stderr, "[%s:%d] id=%d number=%d addr=%08x\n", __FUNCTION__, __LINE__, fpgaId, number, addr);
uint32_t hwaddr = number << 16 | addr;
readreq req = { hwaddr };
readreqs.push(req);
}
void XsimMemSlaveRequest::write ( const uint32_t fpgaId, const uint32_t addr, const uint32_t data )
{
int number = fpgaNumber(fpgaId);
uint32_t hwaddr = number << 16 | addr;
writereq req = { hwaddr, data };
fprintf(stderr, "[%s:%d] id=%d number=%d addr=%08x/%08x data=%08x\n", __FUNCTION__, __LINE__, fpgaId, fpgaNumber(fpgaId), addr, hwaddr, data);
writereqs.push(req);
}
void XsimMemSlaveRequest::msgSink ( const uint32_t data )
{
fprintf(stderr, "[%s:%d] data=%08x\n", __FUNCTION__, __LINE__, data);
sinkbeats.push(data);
}
void XsimMemSlaveRequest::directory ( const uint32_t fpgaNumber, const uint32_t fpgaId, const uint32_t last )
{
fprintf(stderr, "[%s:%d] fpga=%d id=%d last=%d\n", __FUNCTION__, __LINE__, fpgaNumber, fpgaId, last);
struct idInfo info = { fpgaNumber, fpgaId, 1 };
ids[fpgaNumber] = info;
if (last)
portal_count = fpgaNumber+1;
}
int XsimMemSlaveRequest::fpgaNumber(int fpgaId)
{
for (int i = 0; ids[i].valid; i++)
if (ids[i].id == fpgaId) {
return ids[i].number;
}
PORTAL_PRINTF( "Error: %s: did not find fpga_number %d\n", __FUNCTION__, fpgaId);
PORTAL_PRINTF( " Found fpga numbers:");
for (int i = 0; ids[i].valid; i++)
PORTAL_PRINTF( " %d", ids[i].id);
PORTAL_PRINTF( "\n");
return 0;
}
int XsimMemSlaveRequest::fpgaId(int fpgaNumber)
{
return ids[fpgaNumber].id;
}
enum xsimtop_state {
xt_reset, xt_read_directory, xt_active
};
int main(int argc, char **argv)
{
std::string cwd = getcurrentdir();
std::string simengine_libname = "librdi_simulator_kernel.so";
std::string design_libname = getcurrentdir() + "/xsim.dir/mkXsimTop/xsimk.so";
std::cout << "Design DLL : " << design_libname << std::endl;
std::cout << "Sim Engine DLL : " << simengine_libname << std::endl;
// See xsi.h header for more details on how Verilog values are stored as aVal/bVal pairs
Xsi::Loader xsiInstance(design_libname, simengine_libname);
s_xsi_setup_info info;
info.logFileName = (char *)"xsim.log";
xsiInstance.open(&info);
xsimtop_state state = xt_reset;
xsiport rst_n(xsiInstance, "RST_N");
xsiport clk(xsiInstance, "CLK");
xsiport en_interrupt(xsiInstance, "EN_interrupt");
xsiport rdy_interrupt(xsiInstance, "RDY_interrupt");
xsiport interrupt(xsiInstance, "interrupt", 4);
xsiport en_directoryEntry(xsiInstance, "EN_directoryEntry");
xsiport rdy_directoryEntry(xsiInstance, "RDY_directoryEntry");
xsiport directoryEntry(xsiInstance, "directoryEntry", 32);
xsiport read_addr(xsiInstance, "read_addr", 32);
xsiport en_read(xsiInstance, "EN_read");
xsiport rdy_read(xsiInstance, "RDY_read");
xsiport readData(xsiInstance, "readData", 32);
xsiport en_readData(xsiInstance, "EN_readData");
xsiport rdy_readData(xsiInstance, "RDY_readData");
xsiport write_addr(xsiInstance, "write_addr");
xsiport write_data(xsiInstance, "write_data");
xsiport en_write(xsiInstance, "EN_write");
xsiport rdy_write(xsiInstance, "RDY_write");
xsiport clk_singleClock(xsiInstance, "CLK_singleClock");
xsiport msgSource_src_rdy(xsiInstance, "msgSource_src_rdy");
xsiport msgSource_dst_rdy_b(xsiInstance, "msgSource_dst_rdy_b");
xsiport msgSource_beat(xsiInstance, "msgSource_beat", 32);
xsiport msgSink_dst_rdy(xsiInstance, "msgSink_dst_rdy");
xsiport msgSink_src_rdy_b(xsiInstance, "msgSink_src_rdy_b");
xsiport msgSink_beat_v(xsiInstance, "msgSink_beat_v", 32);
PortalSocketParam paramSocket = {};
PortalMuxParam param = {};
if (msgSource_beat.valid())
fprintf(stderr, "[%s:%d] using BluenocTop\n", __FILE__, __LINE__);
Portal *mcommon = new Portal(0, sizeof(uint32_t), portal_mux_handler, NULL, &socketfuncResp, ¶mSocket, 0);
param.pint = &mcommon->pint;
XsimMemSlaveIndicationProxy *memSlaveIndicationProxy = new XsimMemSlaveIndicationProxy(XsimIfcNames_XsimMemSlaveIndication, &muxfunc, ¶m);
XsimMemSlaveRequest *memSlaveRequest = new XsimMemSlaveRequest(XsimIfcNames_XsimMemSlaveRequest, &muxfunc, ¶m);
portalExec_init();
// start low clock
clk.write(0);
rst_n.write(0);
if (read_addr.valid()) {
read_addr.write(0);
en_read.write(0);
en_readData.write(0);
en_write.write(0);
}
xsiInstance.run(10);
int portal_number = 0;
int waiting_for_read = 0;
int read_dir_val = 0;
int portal_ids[16];
int portal_count = 0;
int offset = 0x00;
for (int i = 0; 1; i++)
{
void *rc = portalExec_poll(1);
if ((long)rc >= 0) {
portalExec_event();
}
if (i > 2) {
rst_n.write(1);
}
// mkConnectalTop
if (!msgSource_beat.valid()) {
if (rdy_directoryEntry.read() && !portal_count) {
fprintf(stderr, "directoryEntry %08x\n", directoryEntry.read());
unsigned int val = directoryEntry.read();
bool last = (val & 0x80000000) != 0;
uint32_t id = val & 0x7fffffff;
memSlaveRequest->directory(portal_number, id, last);
portal_ids[portal_number++] = id;
if (last) {
portal_count = portal_number;
portal_number = 0;
fprintf(stderr, "portal_count=%d\n", portal_count);
state = xt_active;
}
en_directoryEntry.write(1);
} else {
en_directoryEntry.write(0);
}
if (memSlaveRequest->connected && (portal_number < portal_count)) {
memSlaveIndicationProxy->directory(portal_number, portal_ids[portal_number], portal_number == (portal_count-1));
portal_number++;
}
if (state == xt_active) {
if (memSlaveRequest->readreqs.size() && rdy_read.read()) {
XsimMemSlaveRequest::readreq readreq = memSlaveRequest->readreqs.front();
memSlaveRequest->readreqs.pop();
en_read.write(1);
fprintf(stderr, "Reading from addr %08x\n", readreq.addr);
read_addr.write(readreq.addr);
} else {
en_read.write(0);
}
if (rdy_readData.read()) {
en_readData.write(1);
uint32_t data = readData.read();
fprintf(stderr, "Read data %08x\n", data);
memSlaveIndicationProxy->readData(data);
} else {
en_readData.write(0);
}
if (memSlaveRequest->writereqs.size() && rdy_write.read()) {
XsimMemSlaveRequest::writereq writereq = memSlaveRequest->writereqs.front();
memSlaveRequest->writereqs.pop();
en_write.write(1);
fprintf(stderr, "Writing to addr %08x data %08x\n", writereq.addr, writereq.data);
write_addr.write(writereq.addr);
write_data.write(writereq.data);
} else {
en_write.write(0);
}
}
if (memSlaveRequest->connected && rdy_interrupt.read()) {
en_interrupt.write(1);
int intr = interrupt.read();
int id = memSlaveRequest->fpgaId(intr);
fprintf(stderr, "Got interrupt number %d id %d\n", intr, id);
memSlaveIndicationProxy->interrupt(id);
} else {
en_interrupt.write(0);
}
} else {
// mkBluenocTop
//fprintf(stderr, "msgSource ready %d msgSink ready %d\n", msgSource_src_rdy.read(), msgSink_dst_rdy.read());
if (msgSource_src_rdy.read()) {
uint32_t beat = msgSource_beat.read();
msgSource_dst_rdy_b.write(1);
fprintf(stderr, "[%s:%d] source message beat %08x\n", __FUNCTION__, __LINE__, beat);
memSlaveIndicationProxy->msgSource(beat);
} else {
msgSource_dst_rdy_b.write(0);
}
if (msgSink_dst_rdy.read() && memSlaveRequest->sinkbeats.size()) {
uint32_t beat = memSlaveRequest->sinkbeats.front();
memSlaveRequest->sinkbeats.pop();
fprintf(stderr, "[%s:%d] sink message beat %08x\n", __FUNCTION__, __LINE__, beat);
msgSink_beat_v.write(beat);
msgSink_src_rdy_b.write(1);
} else {
msgSink_src_rdy_b.write(0);
}
}
clk.write(1);
xsiInstance.run(10);
if (0) {
// clock is divided by two
clk.write(0);
xsiInstance.run(10);
clk.write(1);
xsiInstance.run(10);
}
clk.write(0);
xsiInstance.run(10);
}
sleep(10);
portalExec_end();
}
<commit_msg>give signals time to propagate before posedge<commit_after>#include <stdlib.h>
#include <string>
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <queue>
#include "xsi_loader.h"
#include <portal.h>
#include <sock_utils.h>
#include <GeneratedTypes.h>
#include <XsimMemSlaveRequest.h>
#include <XsimMemSlaveIndication.h>
XsimMemSlaveIndicationProxy *memSlaveIndicationProxy;
class XsimMemSlaveRequest;
XsimMemSlaveRequest *memSlaveRequest;
//deleteme
std::string getcurrentdir()
{
return get_current_dir_name();
}
class xsiport {
Xsi::Loader &xsiInstance;
int port;
//int direction;
const char *name;
int width;
s_xsi_vlog_logicval value;
public:
xsiport(Xsi::Loader &loader, const char *name, int bits = 1)
: xsiInstance(loader), port(-1), name(name), width(bits)
{
value = {1, 1};
port = xsiInstance.get_port_number(name);
//width = xsiInstance.get_int_port(port, xsiHDLValueSize);
std::cout << "Port name=" << name << " number=" << port << std::endl;
}
int read();
void write(int val);
int valid() { return port >= 0; }
};
int xsiport::read()
{
xsiInstance.get_value(port, &value);
int mask = (width == 32) ? -1 : ((1 << width) - 1);
if (value.bVal != 0) {
char charval[] = { '0', '1', 'Z', 'X' };
int encoding = (value.aVal & mask) | ((value.bVal & mask) << 1);
fprintf(stderr, "port %2d.%16s value=%08x.%08x mask=%08x width=%2d %c\n", port, name, value.aVal, value.bVal, mask, width, charval[encoding]);
}
return value.aVal & mask;
}
void xsiport::write(int aVal)
{
value.aVal = aVal;
value.bVal = 0;
xsiInstance.put_value(port, &value);
}
class XsimMemSlaveRequest : public XsimMemSlaveRequestWrapper {
struct idInfo {
int number;
int id;
int valid;
} ids[16];
int portal_count;
public:
struct readreq {
uint32_t addr;
};
struct writereq {
uint32_t addr;
uint32_t data;
};
std::queue<readreq> readreqs;
std::queue<uint32_t> readdata;
std::queue<writereq> writereqs;
std::queue<uint32_t> sinkbeats;
int connected;
XsimMemSlaveRequest(int id, PortalItemFunctions *item, void *param, PortalPoller *poller = 0) : XsimMemSlaveRequestWrapper(id, item, param, poller), connected(0) { }
~XsimMemSlaveRequest() {}
virtual void connect () {
connected = 1;
}
virtual void enableint( const uint32_t fpgaId, const uint32_t val);
virtual void read ( const uint32_t fpgaId, const uint32_t addr );
virtual void write ( const uint32_t fpgaId, const uint32_t addr, const uint32_t data );
virtual void msgSink ( const uint32_t data );
void directory( const uint32_t fpgaNumber, const uint32_t fpgaId, const uint32_t last );
int fpgaNumber(int fpgaId);
int fpgaId(int fpgaNumber);
};
void XsimMemSlaveRequest::enableint( const uint32_t fpgaId, const uint32_t val)
{
int number = fpgaNumber(fpgaId);
uint32_t hwaddr = number << 16 | 4;
writereq req = { hwaddr, val };
fprintf(stderr, "[%s:%d] id=%d number=%d addr=%08x\n", __FUNCTION__, __LINE__, fpgaId, number, hwaddr);
writereqs.push(req);
}
void XsimMemSlaveRequest::read ( const uint32_t fpgaId, const uint32_t addr )
{
int number = fpgaNumber(fpgaId);
fprintf(stderr, "[%s:%d] id=%d number=%d addr=%08x\n", __FUNCTION__, __LINE__, fpgaId, number, addr);
uint32_t hwaddr = number << 16 | addr;
readreq req = { hwaddr };
readreqs.push(req);
}
void XsimMemSlaveRequest::write ( const uint32_t fpgaId, const uint32_t addr, const uint32_t data )
{
int number = fpgaNumber(fpgaId);
uint32_t hwaddr = number << 16 | addr;
writereq req = { hwaddr, data };
fprintf(stderr, "[%s:%d] id=%d number=%d addr=%08x/%08x data=%08x\n", __FUNCTION__, __LINE__, fpgaId, fpgaNumber(fpgaId), addr, hwaddr, data);
writereqs.push(req);
}
void XsimMemSlaveRequest::msgSink ( const uint32_t data )
{
fprintf(stderr, "[%s:%d] data=%08x\n", __FUNCTION__, __LINE__, data);
sinkbeats.push(data);
}
void XsimMemSlaveRequest::directory ( const uint32_t fpgaNumber, const uint32_t fpgaId, const uint32_t last )
{
fprintf(stderr, "[%s:%d] fpga=%d id=%d last=%d\n", __FUNCTION__, __LINE__, fpgaNumber, fpgaId, last);
struct idInfo info = { fpgaNumber, fpgaId, 1 };
ids[fpgaNumber] = info;
if (last)
portal_count = fpgaNumber+1;
}
int XsimMemSlaveRequest::fpgaNumber(int fpgaId)
{
for (int i = 0; ids[i].valid; i++)
if (ids[i].id == fpgaId) {
return ids[i].number;
}
PORTAL_PRINTF( "Error: %s: did not find fpga_number %d\n", __FUNCTION__, fpgaId);
PORTAL_PRINTF( " Found fpga numbers:");
for (int i = 0; ids[i].valid; i++)
PORTAL_PRINTF( " %d", ids[i].id);
PORTAL_PRINTF( "\n");
return 0;
}
int XsimMemSlaveRequest::fpgaId(int fpgaNumber)
{
return ids[fpgaNumber].id;
}
enum xsimtop_state {
xt_reset, xt_read_directory, xt_active
};
int main(int argc, char **argv)
{
std::string cwd = getcurrentdir();
std::string simengine_libname = "librdi_simulator_kernel.so";
std::string design_libname = getcurrentdir() + "/xsim.dir/mkXsimTop/xsimk.so";
std::cout << "Design DLL : " << design_libname << std::endl;
std::cout << "Sim Engine DLL : " << simengine_libname << std::endl;
// See xsi.h header for more details on how Verilog values are stored as aVal/bVal pairs
Xsi::Loader xsiInstance(design_libname, simengine_libname);
s_xsi_setup_info info;
info.logFileName = (char *)"xsim.log";
xsiInstance.open(&info);
xsimtop_state state = xt_reset;
xsiport rst_n(xsiInstance, "RST_N");
xsiport clk(xsiInstance, "CLK");
xsiport en_interrupt(xsiInstance, "EN_interrupt");
xsiport rdy_interrupt(xsiInstance, "RDY_interrupt");
xsiport interrupt(xsiInstance, "interrupt", 4);
xsiport en_directoryEntry(xsiInstance, "EN_directoryEntry");
xsiport rdy_directoryEntry(xsiInstance, "RDY_directoryEntry");
xsiport directoryEntry(xsiInstance, "directoryEntry", 32);
xsiport read_addr(xsiInstance, "read_addr", 32);
xsiport en_read(xsiInstance, "EN_read");
xsiport rdy_read(xsiInstance, "RDY_read");
xsiport readData(xsiInstance, "readData", 32);
xsiport en_readData(xsiInstance, "EN_readData");
xsiport rdy_readData(xsiInstance, "RDY_readData");
xsiport write_addr(xsiInstance, "write_addr");
xsiport write_data(xsiInstance, "write_data");
xsiport en_write(xsiInstance, "EN_write");
xsiport rdy_write(xsiInstance, "RDY_write");
xsiport clk_singleClock(xsiInstance, "CLK_singleClock");
xsiport msgSource_src_rdy(xsiInstance, "msgSource_src_rdy");
xsiport msgSource_dst_rdy_b(xsiInstance, "msgSource_dst_rdy_b");
xsiport msgSource_beat(xsiInstance, "msgSource_beat", 32);
xsiport msgSink_dst_rdy(xsiInstance, "msgSink_dst_rdy");
xsiport msgSink_src_rdy_b(xsiInstance, "msgSink_src_rdy_b");
xsiport msgSink_beat_v(xsiInstance, "msgSink_beat_v", 32);
PortalSocketParam paramSocket = {};
PortalMuxParam param = {};
if (msgSource_beat.valid())
fprintf(stderr, "[%s:%d] using BluenocTop\n", __FILE__, __LINE__);
Portal *mcommon = new Portal(0, sizeof(uint32_t), portal_mux_handler, NULL, &socketfuncResp, ¶mSocket, 0);
param.pint = &mcommon->pint;
XsimMemSlaveIndicationProxy *memSlaveIndicationProxy = new XsimMemSlaveIndicationProxy(XsimIfcNames_XsimMemSlaveIndication, &muxfunc, ¶m);
XsimMemSlaveRequest *memSlaveRequest = new XsimMemSlaveRequest(XsimIfcNames_XsimMemSlaveRequest, &muxfunc, ¶m);
portalExec_init();
// start low clock
clk.write(0);
rst_n.write(0);
if (read_addr.valid()) {
read_addr.write(0);
en_read.write(0);
en_readData.write(0);
en_write.write(0);
}
xsiInstance.run(10);
int portal_number = 0;
int waiting_for_read = 0;
int read_dir_val = 0;
int portal_ids[16];
int portal_count = 0;
int offset = 0x00;
for (int i = 0; 1; i++)
{
void *rc = portalExec_poll(1);
if ((long)rc >= 0) {
portalExec_event();
}
if (i > 2) {
rst_n.write(1);
}
// mkConnectalTop
if (!msgSource_beat.valid()) {
if (rdy_directoryEntry.read() && !portal_count) {
fprintf(stderr, "directoryEntry %08x\n", directoryEntry.read());
unsigned int val = directoryEntry.read();
bool last = (val & 0x80000000) != 0;
uint32_t id = val & 0x7fffffff;
memSlaveRequest->directory(portal_number, id, last);
portal_ids[portal_number++] = id;
if (last) {
portal_count = portal_number;
portal_number = 0;
fprintf(stderr, "portal_count=%d\n", portal_count);
state = xt_active;
}
en_directoryEntry.write(1);
} else {
en_directoryEntry.write(0);
}
if (memSlaveRequest->connected && (portal_number < portal_count)) {
memSlaveIndicationProxy->directory(portal_number, portal_ids[portal_number], portal_number == (portal_count-1));
portal_number++;
}
if (state == xt_active) {
if (memSlaveRequest->readreqs.size() && rdy_read.read()) {
XsimMemSlaveRequest::readreq readreq = memSlaveRequest->readreqs.front();
memSlaveRequest->readreqs.pop();
en_read.write(1);
fprintf(stderr, "Reading from addr %08x\n", readreq.addr);
read_addr.write(readreq.addr);
} else {
en_read.write(0);
}
if (rdy_readData.read()) {
en_readData.write(1);
uint32_t data = readData.read();
fprintf(stderr, "Read data %08x\n", data);
memSlaveIndicationProxy->readData(data);
} else {
en_readData.write(0);
}
if (memSlaveRequest->writereqs.size() && rdy_write.read()) {
XsimMemSlaveRequest::writereq writereq = memSlaveRequest->writereqs.front();
memSlaveRequest->writereqs.pop();
en_write.write(1);
fprintf(stderr, "Writing to addr %08x data %08x\n", writereq.addr, writereq.data);
write_addr.write(writereq.addr);
write_data.write(writereq.data);
} else {
en_write.write(0);
}
}
if (memSlaveRequest->connected && rdy_interrupt.read()) {
en_interrupt.write(1);
int intr = interrupt.read();
int id = memSlaveRequest->fpgaId(intr);
fprintf(stderr, "Got interrupt number %d id %d\n", intr, id);
memSlaveIndicationProxy->interrupt(id);
} else {
en_interrupt.write(0);
}
} else {
// mkBluenocTop
//fprintf(stderr, "msgSource ready %d msgSink ready %d\n", msgSource_src_rdy.read(), msgSink_dst_rdy.read());
if (msgSource_src_rdy.read()) {
uint32_t beat = msgSource_beat.read();
msgSource_dst_rdy_b.write(1);
fprintf(stderr, "[%s:%d] source message beat %08x\n", __FUNCTION__, __LINE__, beat);
memSlaveIndicationProxy->msgSource(beat);
} else {
msgSource_dst_rdy_b.write(0);
}
if (msgSink_dst_rdy.read() && memSlaveRequest->sinkbeats.size()) {
uint32_t beat = memSlaveRequest->sinkbeats.front();
memSlaveRequest->sinkbeats.pop();
fprintf(stderr, "[%s:%d] sink message beat %08x\n", __FUNCTION__, __LINE__, beat);
msgSink_beat_v.write(beat);
msgSink_src_rdy_b.write(1);
} else {
msgSink_src_rdy_b.write(0);
}
}
// setup time
xsiInstance.run(10);
clk.write(1);
xsiInstance.run(10);
if (0) {
// clock is divided by two
clk.write(0);
xsiInstance.run(10);
clk.write(1);
xsiInstance.run(10);
}
clk.write(0);
xsiInstance.run(10);
}
sleep(10);
portalExec_end();
}
<|endoftext|>
|
<commit_before>
/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#ifndef RASTER_COLORIZER_HPP
#define RASTER_COLORIZER_HPP
#include <mapnik/config.hpp>
#include <mapnik/config_error.hpp>
#include <mapnik/color.hpp>
#include <mapnik/feature.hpp>
#include <vector>
using mapnik::color;
using std::vector;
namespace mapnik
{
struct MAPNIK_DECL color_band
{
float value_;
color color_;
unsigned midpoints_;
bool is_interpolated_;
color_band(float value, color c)
: value_(value),
color_(c),
midpoints_(0),
is_interpolated_(false) {}
const bool is_interpolated() const
{
return is_interpolated_;
}
const unsigned get_midpoints() const
{
return midpoints_;
}
const float get_value() const
{
return value_;
}
const color& get_color() const
{
return color_;
}
bool operator==(color_band const& other) const
{
return value_ == other.value_ && color_ == other.color_;
}
std::string to_string() const
{
std::stringstream ss;
ss << color_.to_string() << " " << value_;
return ss.str();
}
};
typedef vector<color_band> color_bands;
struct MAPNIK_DECL raster_colorizer
{
explicit raster_colorizer()
: colors_() {}
raster_colorizer(const raster_colorizer &ps)
: colors_(ps.colors_) {}
raster_colorizer(color_bands &colors)
: colors_(colors) {}
const color_bands& get_color_bands() const
{
return colors_;
}
void append_band (color_band band)
{
if (colors_.size() > 0 && colors_.back().value_ > band.value_) {
#ifdef MAPNIK_DEBUG
std::clog << "prev.v=" << colors_.back().value_ << ". band.v=" << band.value_ << "\n";
#endif
throw config_error(
"Bands must be appended in ascending value order"
);
}
colors_.push_back(band);
}
void append_band (color_band band, unsigned midpoints)
{
band.midpoints_ = midpoints;
if (colors_.size() > 0 && midpoints > 0) {
color_band lo = colors_.back();
color_band const &hi = band;
int steps = midpoints+1;
float dv = (hi.value_ - lo.value_)/steps;
float da = (float(hi.color_.alpha()) - lo.color_.alpha())/steps;
float dr = (float(hi.color_.red()) - lo.color_.red())/steps;
float dg = (float(hi.color_.green()) - lo.color_.green())/steps;
float db = (float(hi.color_.blue()) - lo.color_.blue())/steps;
#ifdef MAPNIK_DEBUG
std::clog << "lo.v=" << lo.value_ << ", hi.v=" << hi.value_ << ", dv="<<dv<<"\n";
#endif
// interpolate intermediate values and colors
int j;
for (j=1; j<steps; j++) {
color_band b(
lo.get_value() + dv*j,
color(int(float(lo.color_.red()) + dr*j),
int(float(lo.color_.green()) + dg*j),
int(float(lo.color_.blue()) + db*j),
int(float(lo.color_.alpha()) + da*j)
)
);
b.is_interpolated_ = true;
append_band(b);
}
}
append_band(band);
}
void append_band (float value, color c)
{
append_band(color_band(value, c));
}
void append_band (float value, color c, unsigned midpoints)
{
append_band(color_band(value, c), midpoints);
}
/* rgba =
* if cs[pos].value <= value < cs[pos+1].value: cs[pos].color
* otherwise: transparent
* where 0 <= pos < length(bands)-1
* Last band is special, its value represents the upper bound and its
* color will only be used if the value matches its value exactly.
*/
color get_color(float value) const {
int pos=-1, last=(int)colors_.size()-1, lo=0, hi=last;
while (lo<=hi) {
pos = (lo+hi)/2;
if (colors_[pos].value_<value) {
lo = pos+1;
} else if (colors_[pos].value_>value) {
hi = pos-1;
} else {
lo = pos+1;
break;
}
}
lo--;
if ((0 <= lo && lo < last) ||
(lo==last && colors_[last].value_==value))
return colors_[lo].color_;
else
return color(0,0,0,0);
}
void colorize(mapnik::raster_ptr const& raster) const {
float *rasterData = (float*)raster->data_.getBytes();
unsigned *imageData = raster->data_.getData();
unsigned i;
for (i=0; i<raster->data_.width()*raster->data_.height(); i++)
imageData[i] = get_color(rasterData[i]).rgba();
}
private:
color_bands colors_;
};
typedef boost::shared_ptr<mapnik::raster_colorizer> raster_colorizer_ptr;
}
#endif //RASTER_COLORIZER_HPP
<commit_msg>+ remove mapnik:: classification from inside namespace mapnik {} + use c++ style casts!<commit_after>
/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#ifndef RASTER_COLORIZER_HPP
#define RASTER_COLORIZER_HPP
#include <mapnik/config.hpp>
#include <mapnik/config_error.hpp>
#include <mapnik/color.hpp>
#include <mapnik/feature.hpp>
#include <vector>
namespace mapnik
{
struct MAPNIK_DECL color_band
{
float value_;
color color_;
unsigned midpoints_;
bool is_interpolated_;
color_band(float value, color c)
: value_(value),
color_(c),
midpoints_(0),
is_interpolated_(false) {}
const bool is_interpolated() const
{
return is_interpolated_;
}
const unsigned get_midpoints() const
{
return midpoints_;
}
const float get_value() const
{
return value_;
}
const color& get_color() const
{
return color_;
}
bool operator==(color_band const& other) const
{
return value_ == other.value_ && color_ == other.color_;
}
std::string to_string() const
{
std::stringstream ss;
ss << color_.to_string() << " " << value_;
return ss.str();
}
};
typedef std::vector<color_band> color_bands;
struct MAPNIK_DECL raster_colorizer
{
explicit raster_colorizer()
: colors_() {}
raster_colorizer(const raster_colorizer &ps)
: colors_(ps.colors_) {}
raster_colorizer(color_bands &colors)
: colors_(colors) {}
const color_bands& get_color_bands() const
{
return colors_;
}
void append_band (color_band band)
{
if (colors_.size() > 0 && colors_.back().value_ > band.value_) {
#ifdef MAPNIK_DEBUG
std::clog << "prev.v=" << colors_.back().value_ << ". band.v=" << band.value_ << "\n";
#endif
throw config_error(
"Bands must be appended in ascending value order"
);
}
colors_.push_back(band);
}
void append_band (color_band band, unsigned midpoints)
{
band.midpoints_ = midpoints;
if (colors_.size() > 0 && midpoints > 0) {
color_band lo = colors_.back();
color_band const &hi = band;
int steps = midpoints+1;
float dv = (hi.value_ - lo.value_)/steps;
float da = (float(hi.color_.alpha()) - lo.color_.alpha())/steps;
float dr = (float(hi.color_.red()) - lo.color_.red())/steps;
float dg = (float(hi.color_.green()) - lo.color_.green())/steps;
float db = (float(hi.color_.blue()) - lo.color_.blue())/steps;
#ifdef MAPNIK_DEBUG
std::clog << "lo.v=" << lo.value_ << ", hi.v=" << hi.value_ << ", dv="<<dv<<"\n";
#endif
// interpolate intermediate values and colors
int j;
for (j=1; j<steps; j++) {
color_band b(
lo.get_value() + dv*j,
color(int(float(lo.color_.red()) + dr*j),
int(float(lo.color_.green()) + dg*j),
int(float(lo.color_.blue()) + db*j),
int(float(lo.color_.alpha()) + da*j)
)
);
b.is_interpolated_ = true;
append_band(b);
}
}
append_band(band);
}
void append_band (float value, color c)
{
append_band(color_band(value, c));
}
void append_band (float value, color c, unsigned midpoints)
{
append_band(color_band(value, c), midpoints);
}
/* rgba =
* if cs[pos].value <= value < cs[pos+1].value: cs[pos].color
* otherwise: transparent
* where 0 <= pos < length(bands)-1
* Last band is special, its value represents the upper bound and its
* color will only be used if the value matches its value exactly.
*/
color get_color(float value) const {
int pos=-1, last=(int)colors_.size()-1, lo=0, hi=last;
while (lo<=hi) {
pos = (lo+hi)/2;
if (colors_[pos].value_<value) {
lo = pos+1;
} else if (colors_[pos].value_>value) {
hi = pos-1;
} else {
lo = pos+1;
break;
}
}
lo--;
if ((0 <= lo && lo < last) ||
(lo==last && colors_[last].value_==value))
return colors_[lo].color_;
else
return color(0,0,0,0);
}
void colorize(raster_ptr const& raster) const
{
float *rasterData = reinterpret_cast<float*>(raster->data_.getBytes());
unsigned *imageData = raster->data_.getData();
unsigned i;
for (i=0; i<raster->data_.width()*raster->data_.height(); i++)
{
imageData[i] = get_color(rasterData[i]).rgba();
}
}
private:
color_bands colors_;
};
typedef boost::shared_ptr<raster_colorizer> raster_colorizer_ptr;
} // mapnik namespace
#endif //RASTER_COLORIZER_HPP
<|endoftext|>
|
<commit_before>/*
* cam_ZWO.cpp
* PHD Guiding
*
* Created by Robin Glover.
* Copyright (c) 2014 Robin Glover.
* All rights reserved.
*
* This source code is distributed under the following "BSD" license
* 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 Craig Stark, Stark Labs nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "phd.h"
#ifdef ZWO_ASI
#include "cam_ZWO.h"
#include "cameras/ASICamera.h"
Camera_ZWO::Camera_ZWO()
{
Connected = false;
m_hasGuideOutput = true;
HasGainControl = true; // really ought to ask the open camera, but all known ZWO cameras have gain
}
Camera_ZWO::~Camera_ZWO()
{
}
bool Camera_ZWO::Connect()
{
// Find available cameras
wxArrayString USBNames;
int iCameras = getNumberOfConnectedCameras();
if (iCameras == 0)
{
wxMessageBox(_T("No ZWO cameras detected."), _("Error"), wxOK | wxICON_ERROR);
return true;
}
for (int i = 0; i < iCameras; i++)
{
char* name = getCameraModel(i);
USBNames.Add(name);
}
int iSelected = 0;
if (USBNames.Count() > 1)
{
iSelected = wxGetSingleChoiceIndex(_("Select camera"), _("Camera name"), USBNames);
if (iSelected == -1)
{
Disconnect(); return true;
}
}
if (!openCamera(iSelected))
{
wxMessageBox(_T("Failed to open ZWO ASI Camera."), _("Error"), wxOK | wxICON_ERROR);
return true;
}
if (!initCamera())
{
wxMessageBox(_T("Failed to initialize ZWO ASI Camera."), _("Error"), wxOK | wxICON_ERROR);
return true;
}
FullSize.x = getMaxWidth();
FullSize.y = getMaxHeight();
PixelSize = getPixelSize();
if (HasGainControl)
{
GuideCameraGain = (getMax(CONTROL_GAIN) + getMin(CONTROL_GAIN)) / 2;
}
Connected = true;
if (isAvailable(CONTROL_BANDWIDTHOVERLOAD))
setValue(CONTROL_BANDWIDTHOVERLOAD, getMin(CONTROL_BANDWIDTHOVERLOAD), false);
return false;
}
bool Camera_ZWO::Disconnect()
{
closeCamera();
Connected = false;
return false;
}
bool Camera_ZWO::Capture(int duration, usImage& img, wxRect subframe, bool recon)
{
int exposureUS = duration * 1000;
int xsize = getMaxWidth();
int ysize = getMaxHeight();
if (img.NPixels != (xsize*ysize)) {
if (img.Init(xsize, ysize)) {
pFrame->Alert(_("Memory allocation error during capture"));
Disconnect();
return true;
}
}
setStartPos(0, 0);
setImageFormat(xsize, ysize, 1, IMG_Y8);
startCapture();
setValue(CONTROL_EXPOSURE, exposureUS, false);
setValue(CONTROL_GAIN, GuideCameraGain, false);
int bufSize = xsize * ysize;
unsigned char* buffer = new unsigned char[bufSize];
bool gotFrame = getImageData(buffer, bufSize, duration * 2 + 1000);
if (!gotFrame)
return true;
unsigned char* src = buffer;
unsigned short* dest = img.ImageData;
for (int y = 0; y < ysize; y++)
{
for (int x = 0; x < xsize; x++, src++, dest++)
{
*dest = (unsigned short)*src;
}
}
delete[] buffer;
if (recon) SubtractDark(img);
return false;
}
GuideDirections GetDirection(int direction)
{
switch (direction)
{
default:
case NORTH:
return guideNorth;
case EAST:
return guideEast;
case WEST:
return guideWest;
case SOUTH:
return guideSouth;
}
}
bool Camera_ZWO::ST4PulseGuideScope(int direction, int duration)
{
pulseGuide(GetDirection(direction), duration);
return false;
}
void Camera_ZWO::ClearGuidePort()
{
pulseGuide(guideNorth, 0);
}
#endif // ZWO_ASI
<commit_msg>Fix ZWO ASI code to initialize the camera fully in connect, rather than doing it in Capture - seems more robust with some ZWO cameras such as ASI035MC<commit_after>/*
* cam_ZWO.cpp
* PHD Guiding
*
* Created by Robin Glover.
* Copyright (c) 2014 Robin Glover.
* All rights reserved.
*
* This source code is distributed under the following "BSD" license
* 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 Craig Stark, Stark Labs nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "phd.h"
#ifdef ZWO_ASI
#include "cam_ZWO.h"
#include "cameras/ASICamera.h"
Camera_ZWO::Camera_ZWO()
{
Connected = false;
m_hasGuideOutput = true;
HasGainControl = true; // really ought to ask the open camera, but all known ZWO cameras have gain
}
Camera_ZWO::~Camera_ZWO()
{
}
bool Camera_ZWO::Connect()
{
// Find available cameras
wxArrayString USBNames;
int iCameras = getNumberOfConnectedCameras();
if (iCameras == 0)
{
wxMessageBox(_T("No ZWO cameras detected."), _("Error"), wxOK | wxICON_ERROR);
return true;
}
for (int i = 0; i < iCameras; i++)
{
char* name = getCameraModel(i);
USBNames.Add(name);
}
int iSelected = 0;
if (USBNames.Count() > 1)
{
iSelected = wxGetSingleChoiceIndex(_("Select camera"), _("Camera name"), USBNames);
if (iSelected == -1)
{
Disconnect(); return true;
}
}
if (!openCamera(iSelected))
{
wxMessageBox(_T("Failed to open ZWO ASI Camera."), _("Error"), wxOK | wxICON_ERROR);
return true;
}
if (!initCamera())
{
wxMessageBox(_T("Failed to initialize ZWO ASI Camera."), _("Error"), wxOK | wxICON_ERROR);
return true;
}
FullSize.x = getMaxWidth();
FullSize.y = getMaxHeight();
PixelSize = getPixelSize();
if (HasGainControl)
{
GuideCameraGain = (getMax(CONTROL_GAIN) + getMin(CONTROL_GAIN)) / 2;
}
Connected = true;
if (isAvailable(CONTROL_BANDWIDTHOVERLOAD))
setValue(CONTROL_BANDWIDTHOVERLOAD, getMin(CONTROL_BANDWIDTHOVERLOAD), false);
setStartPos(0, 0);
setImageFormat(FullSize.x, FullSize.y, 1, IMG_Y8);
startCapture();
return false;
}
bool Camera_ZWO::Disconnect()
{
stopCapture();
closeCamera();
Connected = false;
return false;
}
bool Camera_ZWO::Capture(int duration, usImage& img, wxRect subframe, bool recon)
{
int exposureUS = duration * 1000;
int xsize = getMaxWidth();
int ysize = getMaxHeight();
if (img.NPixels != (xsize*ysize)) {
if (img.Init(xsize, ysize)) {
pFrame->Alert(_("Memory allocation error during capture"));
Disconnect();
return true;
}
}
setValue(CONTROL_EXPOSURE, exposureUS, false);
setValue(CONTROL_GAIN, GuideCameraGain, false);
int bufSize = xsize * ysize;
unsigned char* buffer = new unsigned char[bufSize];
bool gotFrame = getImageData(buffer, bufSize, duration * 2 + 1000);
if (!gotFrame)
return true;
unsigned char* src = buffer;
unsigned short* dest = img.ImageData;
for (int y = 0; y < ysize; y++)
{
for (int x = 0; x < xsize; x++, src++, dest++)
{
*dest = (unsigned short)*src;
}
}
delete[] buffer;
if (recon) SubtractDark(img);
return false;
}
GuideDirections GetDirection(int direction)
{
switch (direction)
{
default:
case NORTH:
return guideNorth;
case EAST:
return guideEast;
case WEST:
return guideWest;
case SOUTH:
return guideSouth;
}
}
bool Camera_ZWO::ST4PulseGuideScope(int direction, int duration)
{
pulseGuide(GetDirection(direction), duration);
return false;
}
void Camera_ZWO::ClearGuidePort()
{
pulseGuide(guideNorth, 0);
}
#endif // ZWO_ASI
<|endoftext|>
|
<commit_before>/*
*
* Copyright (c) 2020-2021 Project CHIP 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.
*/
/**
* @file
* This file implements unit tests for the SessionManager implementation.
*/
#define CHIP_ENABLE_TEST_ENCRYPTED_BUFFER_API // Up here in case some other header
// includes SessionManager.h indirectly
#include <credentials/PersistentStorageOpCertStore.h>
#include <crypto/PersistentStorageOperationalKeystore.h>
#include <lib/core/CHIPCore.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/TestPersistentStorageDelegate.h>
#include <lib/support/UnitTestContext.h>
#include <lib/support/UnitTestRegistration.h>
#include <protocols/secure_channel/MessageCounterManager.h>
#include <transport/SessionManager.h>
#include <transport/TransportMgr.h>
#include <transport/tests/LoopbackTransportManager.h>
#include <nlbyteorder.h>
#include <nlunit-test.h>
#include <errno.h>
#undef CHIP_ENABLE_TEST_ENCRYPTED_BUFFER_API
namespace {
using namespace chip;
using namespace chip::Inet;
using namespace chip::Transport;
using namespace chip::Test;
using TestContext = chip::Test::LoopbackTransportManager;
struct MessageTestEntry
{
const char * name;
const char * peerAddr;
const char * payload;
const char * plain;
const char * encrypted;
const char * privacy;
size_t payloadLength;
size_t plainLength;
size_t encryptedLength;
size_t privacyLength;
const char * encryptKey;
const char * privacyKey;
const char * epochKey;
const char * nonce;
const char * privacyNonce;
const char * compressedFabricId;
const char * mic;
uint16_t sessionId;
NodeId peerNodeId;
FabricIndex fabricIndex;
};
struct MessageTestEntry theMessageTestVector[] = {
{
.name = "secure pase message",
.peerAddr = "::1",
.payload = "",
.plain = "\x00\xb8\x0b\x00\x39\x30\x00\x00\x05\x64\xee\x0e\x20\x7d",
.encrypted = "\x00\xb8\x0b\x00\x39\x30\x00\x00\x5a\x98\x9a\xe4\x2e\x8d"
"\x84\x7f\x53\x5c\x30\x07\xe6\x15\x0c\xd6\x58\x67\xf2\xb8\x17\xdb", // Includes MIC
.privacy = "\x00\xb8\x0b\x00\x39\x30\x00\x00\x5a\x98\x9a\xe4\x2e\x8d"
"\x84\x7f\x53\x5c\x30\x07\xe6\x15\x0c\xd6\x58\x67\xf2\xb8\x17\xdb", // Includes MIC
.payloadLength = 0,
.plainLength = 14,
.encryptedLength = 30,
.privacyLength = 30,
.encryptKey = "\x5e\xde\xd2\x44\xe5\x53\x2b\x3c\xdc\x23\x40\x9d\xba\xd0\x52\xd2",
.nonce = "\x00\x39\x30\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
.sessionId = 0x0bb8, // 3000
.peerNodeId = 0x0000000000000000ULL,
.fabricIndex = 1,
},
};
const uint16_t theMessageTestVectorLength = sizeof(theMessageTestVector) / sizeof(theMessageTestVector[0]);
// Just enough init to replace a ton of boilerplate
class FabricTableHolder
{
public:
FabricTableHolder() {}
~FabricTableHolder()
{
mFabricTable.Shutdown();
mOpKeyStore.Finish();
mOpCertStore.Finish();
}
CHIP_ERROR Init()
{
ReturnErrorOnFailure(mOpKeyStore.Init(&mStorage));
ReturnErrorOnFailure(mOpCertStore.Init(&mStorage));
chip::FabricTable::InitParams initParams;
initParams.storage = &mStorage;
initParams.operationalKeystore = &mOpKeyStore;
initParams.opCertStore = &mOpCertStore;
return mFabricTable.Init(initParams);
}
FabricTable & GetFabricTable() { return mFabricTable; }
private:
chip::FabricTable mFabricTable;
chip::TestPersistentStorageDelegate mStorage;
chip::PersistentStorageOperationalKeystore mOpKeyStore;
chip::Credentials::PersistentStorageOpCertStore mOpCertStore;
};
class TestSessionManagerCallback : public SessionMessageDelegate
{
public:
void OnMessageReceived(const PacketHeader & header, const PayloadHeader & payloadHeader, const SessionHandle & session,
DuplicateMessage isDuplicate, System::PacketBufferHandle && msgBuf) override
{
mReceivedCount++;
MessageTestEntry & testEntry = theMessageTestVector[mTestVectorIndex];
ChipLogProgress(Test, "OnMessageReceived: sessionId=0x%04x", testEntry.sessionId);
NL_TEST_ASSERT(mSuite, header.GetSessionId() == testEntry.sessionId);
size_t dataLength = msgBuf->DataLength();
size_t expectLength = testEntry.payloadLength;
NL_TEST_ASSERT(mSuite, dataLength == expectLength);
NL_TEST_ASSERT(mSuite, memcmp(msgBuf->Start(), testEntry.payload, dataLength) == 0);
ChipLogProgress(Test, "TestSessionManagerDispatch[%d] PASS", mTestVectorIndex);
}
void ResetTest(unsigned testVectorIndex)
{
mTestVectorIndex = testVectorIndex;
mReceivedCount = 0;
}
unsigned NumMessagesReceived() { return mReceivedCount; }
nlTestSuite * mSuite = nullptr;
unsigned mTestVectorIndex = 0;
unsigned mReceivedCount = 0;
};
PeerAddress AddressFromString(const char * str)
{
Inet::IPAddress addr;
VerifyOrDie(Inet::IPAddress::FromString(str, addr));
return PeerAddress::UDP(addr);
}
void TestSessionManagerInit(nlTestSuite * inSuite, TestContext & ctx, SessionManager & sessionManager)
{
static FabricTableHolder fabricTableHolder;
static secure_channel::MessageCounterManager gMessageCounterManager;
static chip::TestPersistentStorageDelegate deviceStorage;
NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == fabricTableHolder.Init());
NL_TEST_ASSERT(inSuite,
CHIP_NO_ERROR ==
sessionManager.Init(&ctx.GetSystemLayer(), &ctx.GetTransportMgr(), &gMessageCounterManager, &deviceStorage,
&fabricTableHolder.GetFabricTable()));
}
void TestSessionManagerDispatch(nlTestSuite * inSuite, void * inContext)
{
CHIP_ERROR err = CHIP_NO_ERROR;
TestContext & ctx = *reinterpret_cast<TestContext *>(inContext);
SessionManager sessionManager;
TestSessionManagerCallback callback;
TestSessionManagerInit(inSuite, ctx, sessionManager);
sessionManager.SetMessageDelegate(&callback);
IPAddress addr;
IPAddress::FromString("::1", addr);
Transport::PeerAddress peer(Transport::PeerAddress::UDP(addr, CHIP_PORT));
SessionHolder aliceToBobSession;
callback.mSuite = inSuite;
for (unsigned i = 0; i < theMessageTestVectorLength; i++)
{
MessageTestEntry & testEntry = theMessageTestVector[i];
callback.ResetTest(i);
ChipLogProgress(Test, "===> TestSessionManagerDispatch[%d] '%s': sessionId=0x%04x", i, testEntry.name, testEntry.sessionId);
// Inject Sessions
err = sessionManager.InjectPaseSessionWithTestKey(aliceToBobSession, testEntry.sessionId, testEntry.peerNodeId,
testEntry.sessionId, testEntry.fabricIndex, peer,
CryptoContext::SessionRole::kResponder);
NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR);
const char * plain = testEntry.plain;
const ByteSpan expectedPlain(reinterpret_cast<const uint8_t *>(plain), testEntry.plainLength);
const char * privacy = testEntry.privacy;
chip::System::PacketBufferHandle msg =
chip::MessagePacketBuffer::NewWithData(reinterpret_cast<const uint8_t *>(privacy), testEntry.privacyLength);
// TODO: inject raw keys rather than always defaulting to test key
const PeerAddress peerAddress = AddressFromString(testEntry.peerAddr);
sessionManager.OnMessageReceived(peerAddress, std::move(msg));
NL_TEST_ASSERT(inSuite, callback.NumMessagesReceived() > 0);
}
sessionManager.Shutdown();
}
// ============================================================================
// Test Suite Instrumenation
// ============================================================================
/**
* Initialize the test suite.
*/
int Initialize(void * aContext)
{
CHIP_ERROR err = reinterpret_cast<TestContext *>(aContext)->Init();
return (err == CHIP_NO_ERROR) ? SUCCESS : FAILURE;
}
/**
* Finalize the test suite.
*/
int Finalize(void * aContext)
{
reinterpret_cast<TestContext *>(aContext)->Shutdown();
return SUCCESS;
}
/**
* Test Suite that lists all the test functions.
*/
// clang-format off
const nlTest sTests[] =
{
NL_TEST_DEF("Test Session Manager Dispatch", TestSessionManagerDispatch),
NL_TEST_SENTINEL()
};
nlTestSuite sSuite =
{
"TestSessionManagerDispatch",
&sTests[0],
Initialize,
Finalize
};
// clang-format on
} // namespace
/**
* Main
*/
int TestSessionManagerDispatchSuite()
{
return chip::ExecuteTestsWithContext<TestContext>(&sSuite);
}
CHIP_REGISTER_TEST_SUITE(TestSessionManagerDispatchSuite);
<commit_msg>[session][test] Extend TestSessionManagerDispatch with group test (#22769)<commit_after>/*
*
* Copyright (c) 2020-2021 Project CHIP 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.
*/
/**
* @file
* This file implements unit tests for the SessionManager implementation.
*/
#define CHIP_ENABLE_TEST_ENCRYPTED_BUFFER_API // Up here in case some other header
// includes SessionManager.h indirectly
#include <credentials/GroupDataProviderImpl.h>
#include <credentials/PersistentStorageOpCertStore.h>
#include <crypto/PersistentStorageOperationalKeystore.h>
#include <lib/core/CHIPCore.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/TestPersistentStorageDelegate.h>
#include <lib/support/UnitTestContext.h>
#include <lib/support/UnitTestRegistration.h>
#include <protocols/secure_channel/MessageCounterManager.h>
#include <transport/SessionManager.h>
#include <transport/TransportMgr.h>
#include <transport/tests/LoopbackTransportManager.h>
#include <nlbyteorder.h>
#include <nlunit-test.h>
#include <errno.h>
#undef CHIP_ENABLE_TEST_ENCRYPTED_BUFFER_API
namespace {
using namespace chip;
using namespace chip::Inet;
using namespace chip::Transport;
using namespace chip::Test;
using namespace chip::Credentials;
using GroupInfo = GroupDataProvider::GroupInfo;
using GroupKey = GroupDataProvider::GroupKey;
using KeySet = GroupDataProvider::KeySet;
using SecurityPolicy = GroupDataProvider::SecurityPolicy;
using TestContext = chip::Test::LoopbackTransportManager;
struct MessageTestEntry
{
const char * name;
const char * peerAddr;
const char * payload;
const char * plain;
const char * encrypted;
const char * privacy;
size_t payloadLength;
size_t plainLength;
size_t encryptedLength;
size_t privacyLength;
const char * encryptKey;
const char * privacyKey;
const char * epochKey;
const char * nonce;
const char * privacyNonce;
const char * compressedFabricId;
const char * mic;
uint16_t sessionId;
NodeId peerNodeId;
GroupId groupId;
NodeId sourceNodeId;
};
struct MessageTestEntry theMessageTestVector[] = {
{
.name = "secure pase message (no payload)",
.peerAddr = "::1",
.payload = "",
.plain = "\x00\xb8\x0b\x00\x39\x30\x00\x00\x05\x64\xee\x0e\x20\x7d",
.encrypted = "\x00\xb8\x0b\x00\x39\x30\x00\x00\x5a\x98\x9a\xe4\x2e\x8d"
"\x84\x7f\x53\x5c\x30\x07\xe6\x15\x0c\xd6\x58\x67\xf2\xb8\x17\xdb", // Includes MIC
.privacy = "\x00\xb8\x0b\x00\x39\x30\x00\x00\x5a\x98\x9a\xe4\x2e\x8d"
"\x84\x7f\x53\x5c\x30\x07\xe6\x15\x0c\xd6\x58\x67\xf2\xb8\x17\xdb", // Includes MIC
.payloadLength = 0,
.plainLength = 14,
.encryptedLength = 30,
.privacyLength = 30,
// TODO(#22830): unicast message tests must use test key currently
.encryptKey = "\x5e\xde\xd2\x44\xe5\x53\x2b\x3c\xdc\x23\x40\x9d\xba\xd0\x52\xd2",
.nonce = "\x00\x39\x30\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
.sessionId = 0x0bb8, // 3000
.peerNodeId = 0x0000000000000000ULL,
},
{
.name = "secure pase message (short payload)",
.peerAddr = "::1",
.payload = "\x11\x22\x33\x44\x55",
.plain = "\x00\xb8\x0b\x00\x39\x30\x00\x00\x05\x64\xee\x0e\x20\x7d\x11\x22\x33\x44\x55",
.encrypted = "\x00\xb8\x0b\x00\x39\x30\x00\x00\x5a\x98\x9a\xe4\x2e\x8d\x0f\x7f\x88\x5d\xfb"
"\x2f\xaa\x89\x49\xcf\x73\x0a\x57\x28\xe0\x35\x46\x10\xa0\xc4\xa7", // Includes MIC
.privacy = "\x00\xb8\x0b\x00\x39\x30\x00\x00\x5a\x98\x9a\xe4\x2e\x8d\x0f\x7f\x88\x5d\xfb"
"\x2f\xaa\x89\x49\xcf\x73\x0a\x57\x28\xe0\x35\x46\x10\xa0\xc4\xa7", // Includes MIC
.payloadLength = 5,
.plainLength = 19,
.encryptedLength = 35,
.privacyLength = 35,
// TODO(#22830): unicast message tests must use test key currently
.encryptKey = "\x5e\xde\xd2\x44\xe5\x53\x2b\x3c\xdc\x23\x40\x9d\xba\xd0\x52\xd2",
.nonce = "\x00\x39\x30\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
.sessionId = 0x0bb8, // 3000
.peerNodeId = 0x0000000000000000ULL,
},
{
.name = "secure group message (no privacy)",
.peerAddr = "::1",
.payload = "",
.plain = "\06\x7d\xdb\x01\x78\x56\x34\x12\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x01\x64\xee\x0e\x20\x7d",
.encrypted = "\x06\x7d\xdb\x01\x78\x56\x34\x12\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x65\xc7\x67\xbc\x6c\xda"
"\x01\x06\xc9\x80\x13\x23\x90\x0e\x9b\x3c\xe6\xd4\xbb\x03\x27\xd6", // Includes MIC
.privacy = "\x06\x7d\xdb\x01\x78\x56\x34\x12\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x65\xc7\x67\xbc\x6c\xda"
"\x01\x06\xc9\x80\x13\x23\x90\x0e\x9b\x3c\xe6\xd4\xbb\x03\x27\xd6", // Includes MIC
.payloadLength = 0,
.plainLength = 24,
.encryptedLength = 40,
.privacyLength = 40,
.encryptKey = "\xca\x92\xd7\xa0\x94\x2d\x1a\x51\x1a\x0e\x26\xad\x07\x4f\x4c\x2f",
.privacyKey = "\xbf\xe9\xda\x01\x6a\x76\x53\x65\xf2\xdd\x97\xa9\xf9\x39\xe4\x25",
.epochKey = "\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf",
.nonce = "\x01\x78\x56\x34\x12\x01\x00\x00\x00\x00\x00\x00\x00",
.privacyNonce = "\xdb\x7d\x23\x90\x0e\x9b\x3c\xe6\xd4\xbb\x03\x27\xd6",
.sessionId = 0xdb7d, // 56189
.peerNodeId = 0x0000000000000000ULL,
.groupId = 2,
.sourceNodeId = 0x0000000000000002ULL,
},
};
const uint16_t theMessageTestVectorLength = sizeof(theMessageTestVector) / sizeof(theMessageTestVector[0]);
// Just enough init to replace a ton of boilerplate
constexpr FabricIndex kFabricIndex = kMinValidFabricIndex;
constexpr size_t kGroupIndex = 0;
constexpr uint16_t kMaxGroupsPerFabric = 5;
constexpr uint16_t kMaxGroupKeysPerFabric = 8;
static chip::TestPersistentStorageDelegate sStorageDelegate;
static GroupDataProviderImpl sProvider(kMaxGroupsPerFabric, kMaxGroupKeysPerFabric);
class FabricTableHolder
{
public:
FabricTableHolder() {}
~FabricTableHolder()
{
mFabricTable.Shutdown();
mOpKeyStore.Finish();
mOpCertStore.Finish();
}
CHIP_ERROR Init()
{
ReturnErrorOnFailure(mOpKeyStore.Init(&mStorage));
ReturnErrorOnFailure(mOpCertStore.Init(&mStorage));
// Initialize Group Data Provider
sProvider.SetStorageDelegate(&sStorageDelegate);
// sProvider.SetListener(&chip::app::TestGroups::sListener);
ReturnErrorOnFailure(sProvider.Init());
Credentials::SetGroupDataProvider(&sProvider);
// Initialize Fabric Table
chip::FabricTable::InitParams initParams;
initParams.storage = &mStorage;
initParams.operationalKeystore = &mOpKeyStore;
initParams.opCertStore = &mOpCertStore;
return mFabricTable.Init(initParams);
}
FabricTable & GetFabricTable() { return mFabricTable; }
private:
chip::FabricTable mFabricTable;
chip::TestPersistentStorageDelegate mStorage;
chip::PersistentStorageOperationalKeystore mOpKeyStore;
chip::Credentials::PersistentStorageOpCertStore mOpCertStore;
};
class TestSessionManagerCallback : public SessionMessageDelegate
{
public:
void OnMessageReceived(const PacketHeader & header, const PayloadHeader & payloadHeader, const SessionHandle & session,
DuplicateMessage isDuplicate, System::PacketBufferHandle && msgBuf) override
{
mReceivedCount++;
MessageTestEntry & testEntry = theMessageTestVector[mTestVectorIndex];
ChipLogProgress(Test, "OnMessageReceived: sessionId=0x%04x", testEntry.sessionId);
NL_TEST_ASSERT(mSuite, header.GetSessionId() == testEntry.sessionId);
size_t dataLength = msgBuf->DataLength();
size_t expectLength = testEntry.payloadLength;
NL_TEST_ASSERT(mSuite, dataLength == expectLength);
NL_TEST_ASSERT(mSuite, memcmp(msgBuf->Start(), testEntry.payload, dataLength) == 0);
ChipLogProgress(Test, "::: TestSessionManagerDispatch[%d] PASS", mTestVectorIndex);
}
void ResetTest(unsigned testVectorIndex)
{
mTestVectorIndex = testVectorIndex;
mReceivedCount = 0;
}
unsigned NumMessagesReceived() { return mReceivedCount; }
nlTestSuite * mSuite = nullptr;
unsigned mTestVectorIndex = 0;
unsigned mReceivedCount = 0;
};
PeerAddress AddressFromString(const char * str)
{
Inet::IPAddress addr;
VerifyOrDie(Inet::IPAddress::FromString(str, addr));
return PeerAddress::UDP(addr);
}
void TestSessionManagerInit(nlTestSuite * inSuite, TestContext & ctx, SessionManager & sessionManager)
{
static FabricTableHolder fabricTableHolder;
static secure_channel::MessageCounterManager gMessageCounterManager;
static chip::TestPersistentStorageDelegate deviceStorage;
NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == fabricTableHolder.Init());
NL_TEST_ASSERT(inSuite,
CHIP_NO_ERROR ==
sessionManager.Init(&ctx.GetSystemLayer(), &ctx.GetTransportMgr(), &gMessageCounterManager, &deviceStorage,
&fabricTableHolder.GetFabricTable()));
}
// constexpr chip::FabricId kFabricId1 = 0x2906C908D115D362;
static const uint8_t kCompressedFabricIdBuffer1[] = { 0x87, 0xe1, 0xb0, 0x04, 0xe2, 0x35, 0xa1, 0x30 };
constexpr ByteSpan kCompressedFabricId1(kCompressedFabricIdBuffer1);
CHIP_ERROR InjectGroupSessionWithTestKey(SessionHolder & sessionHolder, MessageTestEntry & testEntry)
{
constexpr uint16_t kKeySetIndex = 0x0;
GroupId groupId = testEntry.groupId;
GroupDataProvider * provider = GetGroupDataProvider();
static KeySet sKeySet(kKeySetIndex, SecurityPolicy::kTrustFirst, 1);
static GroupKey sGroupKeySet(groupId, kKeySetIndex);
static GroupInfo sGroupInfo(groupId, "Name Matter Not");
static Transport::IncomingGroupSession sSessionBobToFriends(groupId, kFabricIndex, testEntry.sourceNodeId);
if (testEntry.epochKey)
{
memcpy(sKeySet.epoch_keys[0].key, testEntry.epochKey, 16);
sKeySet.epoch_keys[0].start_time = 0;
sGroupInfo.group_id = groupId;
sGroupKeySet.group_id = groupId;
ReturnErrorOnFailure(provider->SetKeySet(kFabricIndex, kCompressedFabricId1, sKeySet));
ReturnErrorOnFailure(provider->SetGroupKeyAt(kFabricIndex, kGroupIndex, sGroupKeySet));
ReturnErrorOnFailure(provider->SetGroupInfoAt(kFabricIndex, kGroupIndex, sGroupInfo));
}
sessionHolder = SessionHandle(sSessionBobToFriends);
return CHIP_NO_ERROR;
}
void TestSessionManagerDispatch(nlTestSuite * inSuite, void * inContext)
{
CHIP_ERROR err = CHIP_NO_ERROR;
TestContext & ctx = *reinterpret_cast<TestContext *>(inContext);
SessionManager sessionManager;
TestSessionManagerCallback callback;
TestSessionManagerInit(inSuite, ctx, sessionManager);
sessionManager.SetMessageDelegate(&callback);
IPAddress addr;
IPAddress::FromString("::1", addr);
Transport::PeerAddress peer(Transport::PeerAddress::UDP(addr, CHIP_PORT));
SessionHolder aliceToBobSession;
SessionHolder testGroupSession;
callback.mSuite = inSuite;
for (unsigned i = 0; i < theMessageTestVectorLength; i++)
{
MessageTestEntry & testEntry = theMessageTestVector[i];
callback.ResetTest(i);
ChipLogProgress(Test, "===> TestSessionManagerDispatch[%d] '%s': sessionId=0x%04x", i, testEntry.name, testEntry.sessionId);
// TODO(#22830): inject raw keys rather than always defaulting to test key
// TODO: switch on session type
// Inject Sessions
err = sessionManager.InjectPaseSessionWithTestKey(aliceToBobSession, testEntry.sessionId, testEntry.peerNodeId,
testEntry.sessionId, kFabricIndex, peer,
CryptoContext::SessionRole::kResponder);
NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR);
err = InjectGroupSessionWithTestKey(testGroupSession, testEntry);
NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == err);
const char * plain = testEntry.plain;
const ByteSpan expectedPlain(reinterpret_cast<const uint8_t *>(plain), testEntry.plainLength);
const char * privacy = testEntry.privacy;
chip::System::PacketBufferHandle msg =
chip::MessagePacketBuffer::NewWithData(reinterpret_cast<const uint8_t *>(privacy), testEntry.privacyLength);
const PeerAddress peerAddress = AddressFromString(testEntry.peerAddr);
sessionManager.OnMessageReceived(peerAddress, std::move(msg));
NL_TEST_ASSERT(inSuite, callback.NumMessagesReceived() > 0);
}
sessionManager.Shutdown();
}
// ============================================================================
// Test Suite Instrumenation
// ============================================================================
/**
* Initialize the test suite.
*/
int Initialize(void * aContext)
{
CHIP_ERROR err = reinterpret_cast<TestContext *>(aContext)->Init();
return (err == CHIP_NO_ERROR) ? SUCCESS : FAILURE;
}
/**
* Finalize the test suite.
*/
int Finalize(void * aContext)
{
reinterpret_cast<TestContext *>(aContext)->Shutdown();
return SUCCESS;
}
/**
* Test Suite that lists all the test functions.
*/
// clang-format off
const nlTest sTests[] =
{
NL_TEST_DEF("Test Session Manager Dispatch", TestSessionManagerDispatch),
NL_TEST_SENTINEL()
};
nlTestSuite sSuite =
{
"TestSessionManagerDispatch",
&sTests[0],
Initialize,
Finalize
};
// clang-format on
} // namespace
/**
* Main
*/
int TestSessionManagerDispatchSuite()
{
return chip::ExecuteTestsWithContext<TestContext>(&sSuite);
}
CHIP_REGISTER_TEST_SUITE(TestSessionManagerDispatchSuite);
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2002 The Apache Software Foundation. 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 2001, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
* $Log$
* Revision 1.8 2003/01/09 15:30:09 tng
* Performance: construct message loader only when required.
*
* Revision 1.7 2002/12/04 02:32:43 knoaman
* #include cleanup.
*
* Revision 1.6 2002/11/27 18:05:38 tng
* Schema Fix: cast the toEmit back to XMLErrs:Codes so that it can be caught by the Scanner properly.
*
* Revision 1.5 2002/11/15 21:58:04 peiyongz
* Leave thread safety issue to message loader
*
* Revision 1.4 2002/11/04 14:49:42 tng
* C++ Namespace Support.
*
* Revision 1.3 2002/09/24 20:12:48 tng
* Performance: use XMLString::equals instead of XMLString::compareString
*
* Revision 1.2 2002/05/22 20:54:14 knoaman
* Prepare for DOM L3 :
* - Make use of the XMLEntityHandler/XMLErrorReporter interfaces, instead of using
* EntityHandler/ErrorHandler directly.
* - Add 'AbstractDOMParser' class to provide common functionality for XercesDOMParser
* and DOMBuilder.
*
* Revision 1.1 2002/03/21 15:34:40 knoaman
* Add support for reporting line/column numbers of schema errors.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/framework/XMLErrorCodes.hpp>
#include <xercesc/framework/XMLValidityCodes.hpp>
#include <xercesc/framework/XMLErrorReporter.hpp>
#include <xercesc/util/XMLMsgLoader.hpp>
#include <xercesc/util/XMLRegisterCleanup.hpp>
#include <xercesc/validators/schema/XSDErrorReporter.hpp>
#include <xercesc/validators/schema/XSDLocator.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Local static data
// ---------------------------------------------------------------------------
static XMLMsgLoader* gErrMsgLoader = 0;
static XMLMsgLoader* gValidMsgLoader = 0;
// ---------------------------------------------------------------------------
// Local, static functions
// ---------------------------------------------------------------------------
static void reinitErrMsgLoader()
{
delete gErrMsgLoader;
gErrMsgLoader = 0;
}
static void reinitValidMsgLoader()
{
delete gValidMsgLoader;
gValidMsgLoader = 0;
}
static XMLMsgLoader* getErrMsgLoader()
{
static XMLRegisterCleanup cleanupErrMsgLoader;
if (gErrMsgLoader == 0)
{
XMLMsgLoader* t = XMLPlatformUtils::loadMsgSet(XMLUni::fgXMLErrDomain);
if (!t)
XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);
else {
if (XMLPlatformUtils::compareAndSwap((void **)&gErrMsgLoader, t, 0) != 0)
{
delete t;
}
else
{
cleanupErrMsgLoader.registerCleanup(reinitErrMsgLoader);
}
}
}
return gErrMsgLoader;
}
static XMLMsgLoader* getValidMsgLoader()
{
static XMLRegisterCleanup cleanupValidMsgLoader;
if (gValidMsgLoader == 0)
{
XMLMsgLoader* t = XMLPlatformUtils::loadMsgSet(XMLUni::fgXMLErrDomain);
if (!t)
XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);
else {
if (XMLPlatformUtils::compareAndSwap((void **)&gValidMsgLoader, t, 0) != 0)
{
delete t;
}
else
{
cleanupValidMsgLoader.registerCleanup(reinitValidMsgLoader);
}
}
}
return gValidMsgLoader;
}
// ---------------------------------------------------------------------------
// XSDErrorReporter: Constructors and Destructor
// ---------------------------------------------------------------------------
XSDErrorReporter::XSDErrorReporter(XMLErrorReporter* const errorReporter) :
fExitOnFirstFatal(false)
, fErrorReporter(errorReporter)
{
}
// ---------------------------------------------------------------------------
// XSDErrorReporter: Error reporting
// ---------------------------------------------------------------------------
void XSDErrorReporter::emitError(const unsigned int toEmit,
const XMLCh* const msgDomain,
const Locator* const aLocator)
{
// Bump the error count if it is not a warning
// if (XMLErrs::errorType(toEmit) != XMLErrorReporter::ErrType_Warning)
// incrementErrorCount();
//
// Load the message into alocal and replace any tokens found in
// the text.
//
const unsigned int msgSize = 1023;
XMLCh errText[msgSize + 1];
XMLMsgLoader* msgLoader = getErrMsgLoader();
XMLErrorReporter::ErrTypes errType = XMLErrs::errorType((XMLErrs::Codes) toEmit);
if (XMLString::equals(msgDomain, XMLUni::fgValidityDomain)) {
errType = XMLValid::errorType((XMLValid::Codes) toEmit);
msgLoader = getValidMsgLoader();
}
if (!msgLoader->loadMsg(toEmit, errText, msgSize))
{
// <TBD> Should probably load a default message here
}
if (fErrorReporter)
fErrorReporter->error(toEmit, msgDomain, errType, errText, aLocator->getSystemId(),
aLocator->getPublicId(), aLocator->getLineNumber(),
aLocator->getColumnNumber());
// Bail out if its fatal an we are to give up on the first fatal error
if (errType == XMLErrorReporter::ErrType_Fatal && fExitOnFirstFatal)
throw (XMLErrs::Codes) toEmit;
}
void XSDErrorReporter::emitError(const unsigned int toEmit,
const XMLCh* const msgDomain,
const Locator* const aLocator,
const XMLCh* const text1,
const XMLCh* const text2,
const XMLCh* const text3,
const XMLCh* const text4)
{
// Bump the error count if it is not a warning
// if (XMLErrs::errorType(toEmit) != XMLErrorReporter::ErrType_Warning)
// incrementErrorCount();
//
// Load the message into alocal and replace any tokens found in
// the text.
//
const unsigned int maxChars = 2047;
XMLCh errText[maxChars + 1];
XMLMsgLoader* msgLoader = getErrMsgLoader();
XMLErrorReporter::ErrTypes errType = XMLErrs::errorType((XMLErrs::Codes) toEmit);
if (XMLString::equals(msgDomain, XMLUni::fgValidityDomain)) {
errType = XMLValid::errorType((XMLValid::Codes) toEmit);
msgLoader = getValidMsgLoader();
}
if (!msgLoader->loadMsg(toEmit, errText, maxChars, text1, text2, text3, text4))
{
// <TBD> Should probably load a default message here
}
if (fErrorReporter)
fErrorReporter->error(toEmit, msgDomain, errType, errText, aLocator->getSystemId(),
aLocator->getPublicId(), aLocator->getLineNumber(),
aLocator->getColumnNumber());
// Bail out if its fatal an we are to give up on the first fatal error
if (errType == XMLErrorReporter::ErrType_Fatal && fExitOnFirstFatal)
throw (XMLErrs::Codes) toEmit;
}
XERCES_CPP_NAMESPACE_END
<commit_msg>We should load the validation message set.<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2002 The Apache Software Foundation. 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 2001, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
* $Log$
* Revision 1.9 2003/01/13 16:13:37 knoaman
* We should load the validation message set.
*
* Revision 1.8 2003/01/09 15:30:09 tng
* Performance: construct message loader only when required.
*
* Revision 1.7 2002/12/04 02:32:43 knoaman
* #include cleanup.
*
* Revision 1.6 2002/11/27 18:05:38 tng
* Schema Fix: cast the toEmit back to XMLErrs:Codes so that it can be caught by the Scanner properly.
*
* Revision 1.5 2002/11/15 21:58:04 peiyongz
* Leave thread safety issue to message loader
*
* Revision 1.4 2002/11/04 14:49:42 tng
* C++ Namespace Support.
*
* Revision 1.3 2002/09/24 20:12:48 tng
* Performance: use XMLString::equals instead of XMLString::compareString
*
* Revision 1.2 2002/05/22 20:54:14 knoaman
* Prepare for DOM L3 :
* - Make use of the XMLEntityHandler/XMLErrorReporter interfaces, instead of using
* EntityHandler/ErrorHandler directly.
* - Add 'AbstractDOMParser' class to provide common functionality for XercesDOMParser
* and DOMBuilder.
*
* Revision 1.1 2002/03/21 15:34:40 knoaman
* Add support for reporting line/column numbers of schema errors.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/framework/XMLErrorCodes.hpp>
#include <xercesc/framework/XMLValidityCodes.hpp>
#include <xercesc/framework/XMLErrorReporter.hpp>
#include <xercesc/util/XMLMsgLoader.hpp>
#include <xercesc/util/XMLRegisterCleanup.hpp>
#include <xercesc/validators/schema/XSDErrorReporter.hpp>
#include <xercesc/validators/schema/XSDLocator.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Local static data
// ---------------------------------------------------------------------------
static XMLMsgLoader* gErrMsgLoader = 0;
static XMLMsgLoader* gValidMsgLoader = 0;
// ---------------------------------------------------------------------------
// Local, static functions
// ---------------------------------------------------------------------------
static void reinitErrMsgLoader()
{
delete gErrMsgLoader;
gErrMsgLoader = 0;
}
static void reinitValidMsgLoader()
{
delete gValidMsgLoader;
gValidMsgLoader = 0;
}
static XMLMsgLoader* getErrMsgLoader()
{
static XMLRegisterCleanup cleanupErrMsgLoader;
if (gErrMsgLoader == 0)
{
XMLMsgLoader* t = XMLPlatformUtils::loadMsgSet(XMLUni::fgXMLErrDomain);
if (!t)
XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);
else {
if (XMLPlatformUtils::compareAndSwap((void **)&gErrMsgLoader, t, 0) != 0)
{
delete t;
}
else
{
cleanupErrMsgLoader.registerCleanup(reinitErrMsgLoader);
}
}
}
return gErrMsgLoader;
}
static XMLMsgLoader* getValidMsgLoader()
{
static XMLRegisterCleanup cleanupValidMsgLoader;
if (gValidMsgLoader == 0)
{
XMLMsgLoader* t = XMLPlatformUtils::loadMsgSet(XMLUni::fgValidityDomain);
if (!t)
XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);
else {
if (XMLPlatformUtils::compareAndSwap((void **)&gValidMsgLoader, t, 0) != 0)
{
delete t;
}
else
{
cleanupValidMsgLoader.registerCleanup(reinitValidMsgLoader);
}
}
}
return gValidMsgLoader;
}
// ---------------------------------------------------------------------------
// XSDErrorReporter: Constructors and Destructor
// ---------------------------------------------------------------------------
XSDErrorReporter::XSDErrorReporter(XMLErrorReporter* const errorReporter) :
fExitOnFirstFatal(false)
, fErrorReporter(errorReporter)
{
}
// ---------------------------------------------------------------------------
// XSDErrorReporter: Error reporting
// ---------------------------------------------------------------------------
void XSDErrorReporter::emitError(const unsigned int toEmit,
const XMLCh* const msgDomain,
const Locator* const aLocator)
{
// Bump the error count if it is not a warning
// if (XMLErrs::errorType(toEmit) != XMLErrorReporter::ErrType_Warning)
// incrementErrorCount();
//
// Load the message into alocal and replace any tokens found in
// the text.
//
const unsigned int msgSize = 1023;
XMLCh errText[msgSize + 1];
XMLMsgLoader* msgLoader = getErrMsgLoader();
XMLErrorReporter::ErrTypes errType = XMLErrs::errorType((XMLErrs::Codes) toEmit);
if (XMLString::equals(msgDomain, XMLUni::fgValidityDomain)) {
errType = XMLValid::errorType((XMLValid::Codes) toEmit);
msgLoader = getValidMsgLoader();
}
if (!msgLoader->loadMsg(toEmit, errText, msgSize))
{
// <TBD> Should probably load a default message here
}
if (fErrorReporter)
fErrorReporter->error(toEmit, msgDomain, errType, errText, aLocator->getSystemId(),
aLocator->getPublicId(), aLocator->getLineNumber(),
aLocator->getColumnNumber());
// Bail out if its fatal an we are to give up on the first fatal error
if (errType == XMLErrorReporter::ErrType_Fatal && fExitOnFirstFatal)
throw (XMLErrs::Codes) toEmit;
}
void XSDErrorReporter::emitError(const unsigned int toEmit,
const XMLCh* const msgDomain,
const Locator* const aLocator,
const XMLCh* const text1,
const XMLCh* const text2,
const XMLCh* const text3,
const XMLCh* const text4)
{
// Bump the error count if it is not a warning
// if (XMLErrs::errorType(toEmit) != XMLErrorReporter::ErrType_Warning)
// incrementErrorCount();
//
// Load the message into alocal and replace any tokens found in
// the text.
//
const unsigned int maxChars = 2047;
XMLCh errText[maxChars + 1];
XMLMsgLoader* msgLoader = getErrMsgLoader();
XMLErrorReporter::ErrTypes errType = XMLErrs::errorType((XMLErrs::Codes) toEmit);
if (XMLString::equals(msgDomain, XMLUni::fgValidityDomain)) {
errType = XMLValid::errorType((XMLValid::Codes) toEmit);
msgLoader = getValidMsgLoader();
}
if (!msgLoader->loadMsg(toEmit, errText, maxChars, text1, text2, text3, text4))
{
// <TBD> Should probably load a default message here
}
if (fErrorReporter)
fErrorReporter->error(toEmit, msgDomain, errType, errText, aLocator->getSystemId(),
aLocator->getPublicId(), aLocator->getLineNumber(),
aLocator->getColumnNumber());
// Bail out if its fatal an we are to give up on the first fatal error
if (errType == XMLErrorReporter::ErrType_Fatal && fExitOnFirstFatal)
throw (XMLErrs::Codes) toEmit;
}
XERCES_CPP_NAMESPACE_END
<|endoftext|>
|
<commit_before>/**
* 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.
*/
#ifndef __STOUT_OPTION_HPP__
#define __STOUT_OPTION_HPP__
#include <assert.h>
#include <algorithm>
#include <stout/none.hpp>
#include <stout/some.hpp>
template <typename T>
class Option
{
public:
static Option<T> none()
{
return Option<T>(NONE);
}
static Option<T> some(const T& t)
{
return Option<T>(SOME, new T(t));
}
Option() : state(NONE), t(NULL) {}
Option(const T& _t) : state(SOME), t(new T(_t)) {}
template <typename U>
Option(const U& u) : state(SOME), t(new T(u)) {}
Option(const None& none) : state(NONE), t(NULL) {}
template <typename U>
Option(const _Some<U>& some) : state(SOME), t(new T(some.t)) {}
Option(const Option<T>& that)
{
state = that.state;
if (that.t != NULL) {
t = new T(*that.t);
} else {
t = NULL;
}
}
~Option()
{
delete t;
}
Option<T>& operator = (const Option<T>& that)
{
if (this != &that) {
delete t;
state = that.state;
if (that.t != NULL) {
t = new T(*that.t);
} else {
t = NULL;
}
}
return *this;
}
bool operator == (const Option<T>& that) const
{
return (state == NONE && that.state == NONE) ||
(state == SOME && that.state == SOME && *t == *that.t);
}
bool operator != (const Option<T>& that) const
{
return !operator == (that);
}
bool operator == (const T& that) const
{
return state == SOME && *t == that;
}
bool operator != (const T& that) const
{
return !operator == (that);
}
bool isSome() const { return state == SOME; }
bool isNone() const { return state == NONE; }
T get() const { assert(state == SOME); return *t; }
T get(const T& _t) const { return state == NONE ? _t : *t; }
private:
enum State {
SOME,
NONE,
};
Option(State _state, T* _t = NULL)
: state(_state), t(_t) {}
State state;
T* t;
};
template <typename T>
Option<T> min(const Option<T>& left, const Option<T>& right)
{
if (left.isSome() && right.isSome()) {
return std::min(left.get(), right.get());
} else if (left.isSome()) {
return left.get();
} else if (right.isSome()) {
return right.get();
} else {
return Option<T>::none();
}
}
template <typename T>
Option<T> min(const Option<T>& left, const T& right)
{
return min(left, Option<T>(right));
}
template <typename T>
Option<T> min(const T& left, const Option<T>& right)
{
return min(Option<T>(left), right);
}
template <typename T>
Option<T> max(const Option<T>& left, const Option<T>& right)
{
if (left.isSome() && right.isSome()) {
return std::max(left.get(), right.get());
} else if (left.isSome()) {
return left.get();
} else if (right.isSome()) {
return right.get();
} else {
return Option<T>::none();
}
}
template <typename T>
Option<T> max(const Option<T>& left, const T& right)
{
return max(left, Option<T>(right));
}
template <typename T>
Option<T> max(const T& left, const Option<T>& right)
{
return max(Option<T>(left), right);
}
#endif // __STOUT_OPTION_HPP__
<commit_msg>Changed Option::get to return a const reference to reduce copying.<commit_after>/**
* 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.
*/
#ifndef __STOUT_OPTION_HPP__
#define __STOUT_OPTION_HPP__
#include <assert.h>
#include <algorithm>
#include <stout/none.hpp>
#include <stout/some.hpp>
template <typename T>
class Option
{
public:
static Option<T> none()
{
return Option<T>(NONE);
}
static Option<T> some(const T& t)
{
return Option<T>(SOME, new T(t));
}
Option() : state(NONE), t(NULL) {}
Option(const T& _t) : state(SOME), t(new T(_t)) {}
template <typename U>
Option(const U& u) : state(SOME), t(new T(u)) {}
Option(const None& none) : state(NONE), t(NULL) {}
template <typename U>
Option(const _Some<U>& some) : state(SOME), t(new T(some.t)) {}
Option(const Option<T>& that)
{
state = that.state;
if (that.t != NULL) {
t = new T(*that.t);
} else {
t = NULL;
}
}
~Option()
{
delete t;
}
Option<T>& operator = (const Option<T>& that)
{
if (this != &that) {
delete t;
state = that.state;
if (that.t != NULL) {
t = new T(*that.t);
} else {
t = NULL;
}
}
return *this;
}
bool operator == (const Option<T>& that) const
{
return (state == NONE && that.state == NONE) ||
(state == SOME && that.state == SOME && *t == *that.t);
}
bool operator != (const Option<T>& that) const
{
return !operator == (that);
}
bool operator == (const T& that) const
{
return state == SOME && *t == that;
}
bool operator != (const T& that) const
{
return !operator == (that);
}
bool isSome() const { return state == SOME; }
bool isNone() const { return state == NONE; }
const T& get() const { assert(state == SOME); return *t; }
// This must return a copy to avoid returning a reference to a temporary.
T get(const T& _t) const { return state == NONE ? _t : *t; }
private:
enum State {
SOME,
NONE,
};
Option(State _state, T* _t = NULL)
: state(_state), t(_t) {}
State state;
T* t;
};
template <typename T>
Option<T> min(const Option<T>& left, const Option<T>& right)
{
if (left.isSome() && right.isSome()) {
return std::min(left.get(), right.get());
} else if (left.isSome()) {
return left.get();
} else if (right.isSome()) {
return right.get();
} else {
return Option<T>::none();
}
}
template <typename T>
Option<T> min(const Option<T>& left, const T& right)
{
return min(left, Option<T>(right));
}
template <typename T>
Option<T> min(const T& left, const Option<T>& right)
{
return min(Option<T>(left), right);
}
template <typename T>
Option<T> max(const Option<T>& left, const Option<T>& right)
{
if (left.isSome() && right.isSome()) {
return std::max(left.get(), right.get());
} else if (left.isSome()) {
return left.get();
} else if (right.isSome()) {
return right.get();
} else {
return Option<T>::none();
}
}
template <typename T>
Option<T> max(const Option<T>& left, const T& right)
{
return max(left, Option<T>(right));
}
template <typename T>
Option<T> max(const T& left, const Option<T>& right)
{
return max(Option<T>(left), right);
}
#endif // __STOUT_OPTION_HPP__
<|endoftext|>
|
<commit_before>#include <age/math/Vector.h>
#include <gtest/gtest.h>
using namespace age::math;
TEST(Vector, Constructor)
{
{
Vector v{};
EXPECT_DOUBLE_EQ(v.X, 0.0);
EXPECT_DOUBLE_EQ(v.Y, 0.0);
}
{
Vector v{-1.0, 1.0};
EXPECT_DOUBLE_EQ(v.X, -1.0);
EXPECT_DOUBLE_EQ(v.Y, 1.0);
}
}
TEST(Vector, Copy)
{
Vector v{-1.0, 1.0};
Vector v1(v);
Vector v2 = v;
EXPECT_DOUBLE_EQ(v.X, v1.X);
EXPECT_DOUBLE_EQ(v.Y, v1.Y);
EXPECT_DOUBLE_EQ(v.X, v2.X);
EXPECT_DOUBLE_EQ(v.Y, v2.Y);
}
TEST(Vector, Reference)
{
Vector v;
v.X = -1.0;
v.Y = 1.0;
EXPECT_DOUBLE_EQ(v.X, -1.0);
EXPECT_DOUBLE_EQ(v.Y, 1.0);
}
TEST(Vector, Equals)
{
Vector v;
EXPECT_EQ(v, Vector());
v.X = 1;
v.Y = 1;
EXPECT_EQ(v, (Vector{1, 1}));
v.X = -1;
v.Y = -1;
EXPECT_EQ(v, (Vector{-1, -1}));
}
TEST(Vector, LessThan)
{
Vector v{};
EXPECT_LT(v, (Vector{1, 1}));
}
TEST(Vector, GreaterThan)
{
Vector v{};
EXPECT_GT(v, (Vector{-1, -1}));
}
TEST(Vector, OperatorPlus)
{
Vector v1{0.0, 0.0};
Vector v2{1.0, 0.0};
Vector v3{0.0, 1.0};
Vector v4{1.0, 1.0};
EXPECT_EQ(v1, v1 + v1);
EXPECT_EQ(v2, v2 + v1);
EXPECT_EQ(v3, v3 + v1);
EXPECT_EQ(v4, v4 + v1);
const auto v5 = v1 + v2 + v3 + v4;
EXPECT_EQ((Vector{2.0, 2.0}), v5);
}
TEST(Vector, OperatorMinus)
{
Vector v1{0.0, 0.0};
Vector v2{1.0, 0.0};
Vector v3{0.0, 1.0};
Vector v4{1.0, 1.0};
EXPECT_EQ(v1, v1 - v1);
EXPECT_EQ(v2, v2 - v1);
EXPECT_EQ(v3, v3 - v1);
EXPECT_EQ(v4, v4 - v1);
const auto v5 = v1 - v2 - v3 - v4;
EXPECT_EQ((Vector{-2.0, -2.0}), v5);
}
<commit_msg>Fix test failure caused by uninitialized vector.<commit_after>#include <age/math/Vector.h>
#include <gtest/gtest.h>
using namespace age::math;
TEST(Vector, Constructor)
{
{
Vector v{};
EXPECT_DOUBLE_EQ(v.X, 0.0);
EXPECT_DOUBLE_EQ(v.Y, 0.0);
}
{
Vector v{-1.0, 1.0};
EXPECT_DOUBLE_EQ(v.X, -1.0);
EXPECT_DOUBLE_EQ(v.Y, 1.0);
}
}
TEST(Vector, Copy)
{
Vector v{-1.0, 1.0};
Vector v1(v);
Vector v2 = v;
EXPECT_DOUBLE_EQ(v.X, v1.X);
EXPECT_DOUBLE_EQ(v.Y, v1.Y);
EXPECT_DOUBLE_EQ(v.X, v2.X);
EXPECT_DOUBLE_EQ(v.Y, v2.Y);
}
TEST(Vector, Reference)
{
Vector v;
v.X = -1.0;
v.Y = 1.0;
EXPECT_DOUBLE_EQ(v.X, -1.0);
EXPECT_DOUBLE_EQ(v.Y, 1.0);
}
TEST(Vector, Equals)
{
Vector v{};
EXPECT_EQ(v, Vector());
v.X = 1;
v.Y = 1;
EXPECT_EQ(v, (Vector{1, 1}));
v.X = -1;
v.Y = -1;
EXPECT_EQ(v, (Vector{-1, -1}));
}
TEST(Vector, LessThan)
{
Vector v{};
EXPECT_LT(v, (Vector{1, 1}));
}
TEST(Vector, GreaterThan)
{
Vector v{};
EXPECT_GT(v, (Vector{-1, -1}));
}
TEST(Vector, OperatorPlus)
{
Vector v1{0.0, 0.0};
Vector v2{1.0, 0.0};
Vector v3{0.0, 1.0};
Vector v4{1.0, 1.0};
EXPECT_EQ(v1, v1 + v1);
EXPECT_EQ(v2, v2 + v1);
EXPECT_EQ(v3, v3 + v1);
EXPECT_EQ(v4, v4 + v1);
const auto v5 = v1 + v2 + v3 + v4;
EXPECT_EQ((Vector{2.0, 2.0}), v5);
}
TEST(Vector, OperatorMinus)
{
Vector v1{0.0, 0.0};
Vector v2{1.0, 0.0};
Vector v3{0.0, 1.0};
Vector v4{1.0, 1.0};
EXPECT_EQ(v1, v1 - v1);
EXPECT_EQ(v2, v2 - v1);
EXPECT_EQ(v3, v3 - v1);
EXPECT_EQ(v4, v4 - v1);
const auto v5 = v1 - v2 - v3 - v4;
EXPECT_EQ((Vector{-2.0, -2.0}), v5);
}
<|endoftext|>
|
<commit_before>#pragma once
#include <gcl/concepts.hpp>
#include <gcl/mp/type_tag.hpp>
#include <tuple>
#include <type_traits>
// todo : T::operator()... -> trait<Ts...>
namespace gcl::mp
{
struct tags {
struct is_const {};
struct is_volatile {};
struct is_no_except {};
/*struct is_lvalue_reference {};
struct is_rvalue_reference {};
struct is_constexpr {};
struct is_lambda {};*/
};
template <gcl::concepts::function Function>
class function_traits {
#ifdef _MSC_VER
#pragma warning(disable : 4348)
// Clang, GCC does not consider such code as default template-parameter redefinition
#endif
template <typename, class function_attr = type_tag::container<>>
struct member_function_traits_impl;
template <typename ClassType, typename ReturnType, typename... Arguments, class function_attr>
struct member_function_traits_impl<ReturnType (ClassType::*)(Arguments...), function_attr> {
using result_type = ReturnType;
using class_type = ClassType;
using arguments = std::tuple<Arguments...>;
template <std::size_t N>
using argument = typename std::tuple_element_t<N, std::tuple<Arguments...>>;
constexpr static bool is_member_function_v = true;
constexpr static bool is_class_v = std::is_class_v<Function>;
constexpr static bool is_const_v = function_attr::template contains<tags::is_const>;
constexpr static bool is_volatile_v = function_attr::template contains<tags::is_volatile>;
constexpr static bool is_noexcept_v = function_attr::template contains<tags::is_no_except>;
};
template <typename ClassType, typename ReturnType, typename... Arguments>
struct member_function_traits_impl<ReturnType (ClassType::*)(Arguments...) noexcept>
: member_function_traits_impl<
ReturnType (ClassType::*)(Arguments...),
type_tag::container<tags::is_no_except>> {};
template <typename ClassType, typename ReturnType, typename... Arguments>
struct member_function_traits_impl<ReturnType (ClassType::*)(Arguments...) const>
: member_function_traits_impl<
ReturnType (ClassType::*)(Arguments...),
type_tag::container<tags::is_const>> {};
template <typename ClassType, typename ReturnType, typename... Arguments>
struct member_function_traits_impl<ReturnType (ClassType::*)(Arguments...) const noexcept>
: member_function_traits_impl<
ReturnType (ClassType::*)(Arguments...),
type_tag::container<tags::is_const, tags::is_no_except>> {};
template <typename ClassType, typename ReturnType, typename... Arguments>
struct member_function_traits_impl<ReturnType (ClassType::*)(Arguments...) volatile>
: member_function_traits_impl<
ReturnType (ClassType::*)(Arguments...),
type_tag::container<tags::is_volatile>> {};
template <typename ClassType, typename ReturnType, typename... Arguments>
struct member_function_traits_impl<ReturnType (ClassType::*)(Arguments...) const volatile>
: member_function_traits_impl<
ReturnType (ClassType::*)(Arguments...),
type_tag::container<tags::is_const, tags::is_volatile>> {};
template <typename ClassType, typename ReturnType, typename... Arguments>
struct member_function_traits_impl<ReturnType (ClassType::*)(Arguments...) volatile noexcept>
: member_function_traits_impl<
ReturnType (ClassType::*)(Arguments...),
type_tag::container<tags::is_volatile, tags::is_no_except>> {};
template <typename ClassType, typename ReturnType, typename... Arguments>
struct member_function_traits_impl<ReturnType (ClassType::*)(Arguments...) const volatile noexcept>
: member_function_traits_impl<
ReturnType (ClassType::*)(Arguments...),
type_tag::container<tags::is_const, tags::is_volatile, tags::is_no_except>> {};
template <typename, class function_attr = type_tag::container<>>
struct function_traits_impl;
template <typename ReturnType, typename... Arguments, class function_attr>
struct function_traits_impl<ReturnType (*)(Arguments...), function_attr> {
using result_type = ReturnType;
using arguments = std::tuple<Arguments...>;
template <std::size_t N>
using argument = typename std::tuple_element_t<N, std::tuple<Arguments...>>;
constexpr static bool is_member_function_v = false;
constexpr static bool is_class_v = std::is_class_v<Function>;
constexpr static bool is_const_v = function_attr::template contains<tags::is_const>;
constexpr static bool is_volatile_v = function_attr::template contains<tags::is_volatile>;
constexpr static bool is_noexcept_v = function_attr::template contains<tags::is_no_except>;
};
template <typename ReturnType, typename... Arguments>
struct function_traits_impl<ReturnType (*)(Arguments...) noexcept>
: function_traits_impl<
ReturnType (*)(Arguments...),
type_tag::container<tags::is_no_except>> {};
#ifdef _MSC_VER
#pragma warning(default : 4348)
#endif
public:
using type = std::conditional_t<
std::is_member_function_pointer_v<Function>,
member_function_traits_impl<Function>,
function_traits_impl<Function>>;
};
// is type -> functor object (including lambdas)
// -> [0..N] multiple parenthesis operators
// -> maybe overload pattern
// -> what about template operator() ?
template <typename Function>
using function_traits_t = typename function_traits<Function>::type;
// using function_traits = member_function_traits_impl<decltype(&Function::operator()...)>;
}
#include <array>
namespace gcl::mp::test
{
struct toto {
int not_const_member(char) { return 42; }
int noexcept_not_const_member(char) noexcept { return 42; }
int const_member(char) const { return 42; }
int noexcept_const_member(char) const noexcept { return 42; }
int volatile_member(char) volatile { return 42; }
int noexcept_volatile_member(char) volatile noexcept { return 42; }
};
static_assert(std::is_same_v<int, function_traits_t<decltype(&toto::not_const_member)>::result_type>);
static_assert(std::is_same_v<int, function_traits_t<decltype(&toto::noexcept_not_const_member)>::result_type>);
static_assert(std::is_same_v<int, function_traits_t<decltype(&toto::const_member)>::result_type>);
static_assert(std::is_same_v<int, function_traits_t<decltype(&toto::noexcept_const_member)>::result_type>);
static_assert(std::is_same_v<int, function_traits_t<decltype(&toto::volatile_member)>::result_type>);
static_assert(std::is_same_v<int, function_traits_t<decltype(&toto::noexcept_volatile_member)>::result_type>);
int some_function(char) { return 42; };
int noexcept_function(char) noexcept { return 42; };
static_assert(std::is_same_v<char, function_traits_t<decltype(&some_function)>::argument<0>>);
static_assert(std::is_same_v<char, function_traits_t<decltype(&noexcept_function)>::argument<0>>);
void check_function_attributes()
{
#if not __clang__
{
constexpr auto check_attr = []<typename T, std::array<bool, 3> attr_expectations>() consteval
{
static_assert(std::get<0>(attr_expectations) == function_traits_t<T>::is_const_v);
static_assert(std::get<1>(attr_expectations) == function_traits_t<T>::is_noexcept_v);
static_assert(std::get<2>(attr_expectations) == function_traits_t<T>::is_volatile_v);
return true; // symbol deduction
};
constexpr static auto _ = std::array{
// ensure consteval context
check_attr
.template operator()<decltype(&toto::const_member), std::array<bool, 3>{true, false, false}>(),
check_attr
.template operator()<decltype(&toto::not_const_member), std::array<bool, 3>{false, false, false}>(),
check_attr.template
operator()<decltype(&toto::noexcept_not_const_member), std::array<bool, 3>{false, true, false}>(),
check_attr.template
operator()<decltype(&toto::noexcept_const_member), std::array<bool, 3>{true, true, false}>(),
check_attr
.template operator()<decltype(&toto::volatile_member), std::array<bool, 3>{false, false, true}>(),
check_attr.template
operator()<decltype(&toto::noexcept_volatile_member), std::array<bool, 3>{false, true, true}>()};
}
}
#endif
}<commit_msg>[clang-support] : fix issue with undefined STL symbols : ill-formed namespace<commit_after>#pragma once
#include <gcl/concepts.hpp>
#include <gcl/mp/type_tag.hpp>
#include <tuple>
#include <type_traits>
// todo : T::operator()... -> trait<Ts...>
namespace gcl::mp
{
struct tags {
struct is_const {};
struct is_volatile {};
struct is_no_except {};
/*struct is_lvalue_reference {};
struct is_rvalue_reference {};
struct is_constexpr {};
struct is_lambda {};*/
};
template <gcl::concepts::function Function>
class function_traits {
#ifdef _MSC_VER
#pragma warning(disable : 4348)
// Clang, GCC does not consider such code as default template-parameter redefinition
#endif
template <typename, class function_attr = type_tag::container<>>
struct member_function_traits_impl;
template <typename ClassType, typename ReturnType, typename... Arguments, class function_attr>
struct member_function_traits_impl<ReturnType (ClassType::*)(Arguments...), function_attr> {
using result_type = ReturnType;
using class_type = ClassType;
using arguments = std::tuple<Arguments...>;
template <std::size_t N>
using argument = typename std::tuple_element_t<N, std::tuple<Arguments...>>;
constexpr static bool is_member_function_v = true;
constexpr static bool is_class_v = std::is_class_v<Function>;
constexpr static bool is_const_v = function_attr::template contains<tags::is_const>;
constexpr static bool is_volatile_v = function_attr::template contains<tags::is_volatile>;
constexpr static bool is_noexcept_v = function_attr::template contains<tags::is_no_except>;
};
template <typename ClassType, typename ReturnType, typename... Arguments>
struct member_function_traits_impl<ReturnType (ClassType::*)(Arguments...) noexcept>
: member_function_traits_impl<
ReturnType (ClassType::*)(Arguments...),
type_tag::container<tags::is_no_except>> {};
template <typename ClassType, typename ReturnType, typename... Arguments>
struct member_function_traits_impl<ReturnType (ClassType::*)(Arguments...) const>
: member_function_traits_impl<
ReturnType (ClassType::*)(Arguments...),
type_tag::container<tags::is_const>> {};
template <typename ClassType, typename ReturnType, typename... Arguments>
struct member_function_traits_impl<ReturnType (ClassType::*)(Arguments...) const noexcept>
: member_function_traits_impl<
ReturnType (ClassType::*)(Arguments...),
type_tag::container<tags::is_const, tags::is_no_except>> {};
template <typename ClassType, typename ReturnType, typename... Arguments>
struct member_function_traits_impl<ReturnType (ClassType::*)(Arguments...) volatile>
: member_function_traits_impl<
ReturnType (ClassType::*)(Arguments...),
type_tag::container<tags::is_volatile>> {};
template <typename ClassType, typename ReturnType, typename... Arguments>
struct member_function_traits_impl<ReturnType (ClassType::*)(Arguments...) const volatile>
: member_function_traits_impl<
ReturnType (ClassType::*)(Arguments...),
type_tag::container<tags::is_const, tags::is_volatile>> {};
template <typename ClassType, typename ReturnType, typename... Arguments>
struct member_function_traits_impl<ReturnType (ClassType::*)(Arguments...) volatile noexcept>
: member_function_traits_impl<
ReturnType (ClassType::*)(Arguments...),
type_tag::container<tags::is_volatile, tags::is_no_except>> {};
template <typename ClassType, typename ReturnType, typename... Arguments>
struct member_function_traits_impl<ReturnType (ClassType::*)(Arguments...) const volatile noexcept>
: member_function_traits_impl<
ReturnType (ClassType::*)(Arguments...),
type_tag::container<tags::is_const, tags::is_volatile, tags::is_no_except>> {};
template <typename, class function_attr = type_tag::container<>>
struct function_traits_impl;
template <typename ReturnType, typename... Arguments, class function_attr>
struct function_traits_impl<ReturnType (*)(Arguments...), function_attr> {
using result_type = ReturnType;
using arguments = std::tuple<Arguments...>;
template <std::size_t N>
using argument = typename std::tuple_element_t<N, std::tuple<Arguments...>>;
constexpr static bool is_member_function_v = false;
constexpr static bool is_class_v = std::is_class_v<Function>;
constexpr static bool is_const_v = function_attr::template contains<tags::is_const>;
constexpr static bool is_volatile_v = function_attr::template contains<tags::is_volatile>;
constexpr static bool is_noexcept_v = function_attr::template contains<tags::is_no_except>;
};
template <typename ReturnType, typename... Arguments>
struct function_traits_impl<ReturnType (*)(Arguments...) noexcept>
: function_traits_impl<ReturnType (*)(Arguments...), type_tag::container<tags::is_no_except>> {};
#ifdef _MSC_VER
#pragma warning(default : 4348)
#endif
public:
using type = std::conditional_t<
std::is_member_function_pointer_v<Function>,
member_function_traits_impl<Function>,
function_traits_impl<Function>>;
};
// is type -> functor object (including lambdas)
// -> [0..N] multiple parenthesis operators
// -> maybe overload pattern
// -> what about template operator() ?
template <typename Function>
using function_traits_t = typename function_traits<Function>::type;
// using function_traits = member_function_traits_impl<decltype(&Function::operator()...)>;
}
#include <array>
namespace gcl::mp::test
{
struct toto {
int not_const_member(char) { return 42; }
int noexcept_not_const_member(char) noexcept { return 42; }
int const_member(char) const { return 42; }
int noexcept_const_member(char) const noexcept { return 42; }
int volatile_member(char) volatile { return 42; }
int noexcept_volatile_member(char) volatile noexcept { return 42; }
};
static_assert(std::is_same_v<int, function_traits_t<decltype(&toto::not_const_member)>::result_type>);
static_assert(std::is_same_v<int, function_traits_t<decltype(&toto::noexcept_not_const_member)>::result_type>);
static_assert(std::is_same_v<int, function_traits_t<decltype(&toto::const_member)>::result_type>);
static_assert(std::is_same_v<int, function_traits_t<decltype(&toto::noexcept_const_member)>::result_type>);
static_assert(std::is_same_v<int, function_traits_t<decltype(&toto::volatile_member)>::result_type>);
static_assert(std::is_same_v<int, function_traits_t<decltype(&toto::noexcept_volatile_member)>::result_type>);
int some_function(char) { return 42; };
int noexcept_function(char) noexcept { return 42; };
static_assert(std::is_same_v<char, function_traits_t<decltype(&some_function)>::argument<0>>);
static_assert(std::is_same_v<char, function_traits_t<decltype(&noexcept_function)>::argument<0>>);
void check_function_attributes()
{
#if not __clang__
constexpr auto check_attr = []<typename T, std::array<bool, 3> attr_expectations>() consteval
{
static_assert(std::get<0>(attr_expectations) == function_traits_t<T>::is_const_v);
static_assert(std::get<1>(attr_expectations) == function_traits_t<T>::is_noexcept_v);
static_assert(std::get<2>(attr_expectations) == function_traits_t<T>::is_volatile_v);
return true; // symbol deduction
};
constexpr static auto _ = std::array{
// ensure consteval context
check_attr.template operator()<decltype(&toto::const_member), std::array<bool, 3>{true, false, false}>(),
check_attr
.template operator()<decltype(&toto::not_const_member), std::array<bool, 3>{false, false, false}>(),
check_attr.template
operator()<decltype(&toto::noexcept_not_const_member), std::array<bool, 3>{false, true, false}>(),
check_attr
.template operator()<decltype(&toto::noexcept_const_member), std::array<bool, 3>{true, true, false}>(),
check_attr.template operator()<decltype(&toto::volatile_member), std::array<bool, 3>{false, false, true}>(),
check_attr.template
operator()<decltype(&toto::noexcept_volatile_member), std::array<bool, 3>{false, true, true}>()};
#endif
}
}<|endoftext|>
|
<commit_before>#include <clpeak.h>
#define MSTRINGIFY(...) #__VA_ARGS__
static const char *stringifiedKernels =
#include "global_bandwidth_kernels.cl"
#include "compute_sp_kernels.cl"
#include "compute_hp_kernels.cl"
#include "compute_dp_kernels.cl"
#include "compute_integer_kernels.cl"
;
static const char *stringifiedKernelsNoInt =
#include "global_bandwidth_kernels.cl"
#include "compute_sp_kernels.cl"
#include "compute_hp_kernels.cl"
#include "compute_dp_kernels.cl"
;
#ifdef USE_STUB_OPENCL
// Prototype
extern "C" {
void stubOpenclReset();
}
#endif
clPeak::clPeak(): forcePlatform(false), forceDevice(false), useEventTimer(false),
isGlobalBW(true), isComputeSP(true), isComputeDP(true), isComputeInt(true),
isTransferBW(true), isKernelLatency(true),
specifiedPlatform(0), specifiedDevice(0)
{
}
clPeak::~clPeak()
{
if(log) delete log;
}
int clPeak::runAll()
{
try
{
#ifdef USE_STUB_OPENCL
stubOpenclReset();
#endif
vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
log->xmlOpenTag("clpeak");
log->xmlAppendAttribs("os", OS_NAME);
for(size_t p=0; p < platforms.size(); p++)
{
if(forcePlatform && (p != specifiedPlatform))
continue;
std::string platformName = platforms[p].getInfo<CL_PLATFORM_NAME>();
trimString(platformName);
log->print(NEWLINE "Platform: " + platformName + NEWLINE);
log->xmlOpenTag("platform");
log->xmlAppendAttribs("name", platformName);
// Disable intel integer kernel only on windows
bool isIntel = false;
#if defined(_WIN32)
isIntel = (platformName.find("Intel") != std::string::npos)? true: false;
#endif
bool isApple = (platformName.find("Apple") != std::string::npos)? true: false;
cl_context_properties cps[3] = {
CL_CONTEXT_PLATFORM,
(cl_context_properties)(platforms[p])(),
0
};
cl::Context ctx(CL_DEVICE_TYPE_ALL, cps);
vector<cl::Device> devices = ctx.getInfo<CL_CONTEXT_DEVICES>();
cl::Program prog;
// FIXME Disabling integer compute tests on intel platform
// Kernel build is taking much much longer time
// FIXME Disabling integer compute tests on apple platform
// Causes Segmentation fault: 11
if(isIntel || isApple)
{
cl::Program::Sources source(1, make_pair(stringifiedKernelsNoInt, (strlen(stringifiedKernelsNoInt)+1)));
isComputeInt = false;
prog = cl::Program(ctx, source);
}
else
{
cl::Program::Sources source(1, make_pair(stringifiedKernels, (strlen(stringifiedKernels)+1)));
prog = cl::Program(ctx, source);
}
for(size_t d=0; d < devices.size(); d++)
{
if(forceDevice && (d != specifiedDevice))
continue;
device_info_t devInfo = getDeviceInfo(devices[d]);
log->print(TAB "Device: " + devInfo.deviceName + NEWLINE);
log->print(TAB TAB "Driver version : ");
log->print(devInfo.driverVersion); log->print(" (" OS_NAME ")" NEWLINE);
log->print(TAB TAB "Compute units : ");
log->print(devInfo.numCUs); log->print(NEWLINE);
log->print(TAB TAB "Clock frequency : ");
log->print(devInfo.maxClockFreq); log->print(" MHz" NEWLINE);
log->xmlOpenTag("device");
log->xmlAppendAttribs("name", devInfo.deviceName);
log->xmlAppendAttribs("driver_version", devInfo.driverVersion);
log->xmlAppendAttribs("compute_units", devInfo.numCUs);
log->xmlAppendAttribs("clock_frequency", devInfo.maxClockFreq);
log->xmlAppendAttribs("clock_frequency_unit", "MHz");
try
{
vector<cl::Device> dev = {devices[d]};
prog.build(dev, BUILD_OPTIONS);
}
catch (cl::Error &error)
{
UNUSED(error);
log->print(TAB TAB "Build Log: " + prog.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[d])
+ NEWLINE NEWLINE);
continue;
}
cl::CommandQueue queue = cl::CommandQueue(ctx, devices[d], CL_QUEUE_PROFILING_ENABLE);
runGlobalBandwidthTest(queue, prog, devInfo);
runComputeSP(queue, prog, devInfo);
runComputeHP(queue, prog, devInfo);
runComputeDP(queue, prog, devInfo);
runComputeInteger(queue, prog, devInfo);
runTransferBandwidthTest(queue, prog, devInfo);
runKernelLatency(queue, prog, devInfo);
log->print(NEWLINE);
log->xmlCloseTag(); // device
}
log->xmlCloseTag(); // platform
}
log->xmlCloseTag(); // clpeak
}
catch(cl::Error &error)
{
stringstream ss;
ss << error.what() << " (" << error.err() << ")" NEWLINE;
log->print(ss.str());
return -1;
}
return 0;
}
float clPeak::run_kernel(cl::CommandQueue &queue, cl::Kernel &kernel, cl::NDRange &globalSize, cl::NDRange &localSize, uint iters)
{
float timed = 0;
// Dummy calls
queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
queue.finish();
if(useEventTimer)
{
for(uint i=0; i<iters; i++)
{
cl::Event timeEvent;
queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize, NULL, &timeEvent);
queue.finish();
timed += timeInUS(timeEvent);
}
} else // std timer
{
Timer timer;
timer.start();
for(uint i=0; i<iters; i++)
{
queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
queue.flush();
}
queue.finish();
timed = timer.stopAndTime();
}
return (timed / static_cast<float>(iters));
}
<commit_msg>Undo disabling of int kernels for intel<commit_after>#include <clpeak.h>
#define MSTRINGIFY(...) #__VA_ARGS__
static const char *stringifiedKernels =
#include "global_bandwidth_kernels.cl"
#include "compute_sp_kernels.cl"
#include "compute_hp_kernels.cl"
#include "compute_dp_kernels.cl"
#include "compute_integer_kernels.cl"
;
static const char *stringifiedKernelsNoInt =
#include "global_bandwidth_kernels.cl"
#include "compute_sp_kernels.cl"
#include "compute_hp_kernels.cl"
#include "compute_dp_kernels.cl"
;
#ifdef USE_STUB_OPENCL
// Prototype
extern "C" {
void stubOpenclReset();
}
#endif
clPeak::clPeak(): forcePlatform(false), forceDevice(false), useEventTimer(false),
isGlobalBW(true), isComputeSP(true), isComputeDP(true), isComputeInt(true),
isTransferBW(true), isKernelLatency(true),
specifiedPlatform(0), specifiedDevice(0)
{
}
clPeak::~clPeak()
{
if(log) delete log;
}
int clPeak::runAll()
{
try
{
#ifdef USE_STUB_OPENCL
stubOpenclReset();
#endif
vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
log->xmlOpenTag("clpeak");
log->xmlAppendAttribs("os", OS_NAME);
for(size_t p=0; p < platforms.size(); p++)
{
if(forcePlatform && (p != specifiedPlatform))
continue;
std::string platformName = platforms[p].getInfo<CL_PLATFORM_NAME>();
trimString(platformName);
log->print(NEWLINE "Platform: " + platformName + NEWLINE);
log->xmlOpenTag("platform");
log->xmlAppendAttribs("name", platformName);
bool isApple = (platformName.find("Apple") != std::string::npos)? true: false;
cl_context_properties cps[3] = {
CL_CONTEXT_PLATFORM,
(cl_context_properties)(platforms[p])(),
0
};
cl::Context ctx(CL_DEVICE_TYPE_ALL, cps);
vector<cl::Device> devices = ctx.getInfo<CL_CONTEXT_DEVICES>();
cl::Program prog;
// FIXME Disabling integer compute tests on apple platform
// Causes Segmentation fault: 11
if(isApple)
{
cl::Program::Sources source(1, make_pair(stringifiedKernelsNoInt, (strlen(stringifiedKernelsNoInt)+1)));
isComputeInt = false;
prog = cl::Program(ctx, source);
}
else
{
cl::Program::Sources source(1, make_pair(stringifiedKernels, (strlen(stringifiedKernels)+1)));
prog = cl::Program(ctx, source);
}
for(size_t d=0; d < devices.size(); d++)
{
if(forceDevice && (d != specifiedDevice))
continue;
device_info_t devInfo = getDeviceInfo(devices[d]);
log->print(TAB "Device: " + devInfo.deviceName + NEWLINE);
log->print(TAB TAB "Driver version : ");
log->print(devInfo.driverVersion); log->print(" (" OS_NAME ")" NEWLINE);
log->print(TAB TAB "Compute units : ");
log->print(devInfo.numCUs); log->print(NEWLINE);
log->print(TAB TAB "Clock frequency : ");
log->print(devInfo.maxClockFreq); log->print(" MHz" NEWLINE);
log->xmlOpenTag("device");
log->xmlAppendAttribs("name", devInfo.deviceName);
log->xmlAppendAttribs("driver_version", devInfo.driverVersion);
log->xmlAppendAttribs("compute_units", devInfo.numCUs);
log->xmlAppendAttribs("clock_frequency", devInfo.maxClockFreq);
log->xmlAppendAttribs("clock_frequency_unit", "MHz");
try
{
vector<cl::Device> dev = {devices[d]};
prog.build(dev, BUILD_OPTIONS);
}
catch (cl::Error &error)
{
UNUSED(error);
log->print(TAB TAB "Build Log: " + prog.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[d])
+ NEWLINE NEWLINE);
continue;
}
cl::CommandQueue queue = cl::CommandQueue(ctx, devices[d], CL_QUEUE_PROFILING_ENABLE);
runGlobalBandwidthTest(queue, prog, devInfo);
runComputeSP(queue, prog, devInfo);
runComputeHP(queue, prog, devInfo);
runComputeDP(queue, prog, devInfo);
runComputeInteger(queue, prog, devInfo);
runTransferBandwidthTest(queue, prog, devInfo);
runKernelLatency(queue, prog, devInfo);
log->print(NEWLINE);
log->xmlCloseTag(); // device
}
log->xmlCloseTag(); // platform
}
log->xmlCloseTag(); // clpeak
}
catch(cl::Error &error)
{
stringstream ss;
ss << error.what() << " (" << error.err() << ")" NEWLINE;
log->print(ss.str());
return -1;
}
return 0;
}
float clPeak::run_kernel(cl::CommandQueue &queue, cl::Kernel &kernel, cl::NDRange &globalSize, cl::NDRange &localSize, uint iters)
{
float timed = 0;
// Dummy calls
queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
queue.finish();
if(useEventTimer)
{
for(uint i=0; i<iters; i++)
{
cl::Event timeEvent;
queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize, NULL, &timeEvent);
queue.finish();
timed += timeInUS(timeEvent);
}
} else // std timer
{
Timer timer;
timer.start();
for(uint i=0; i<iters; i++)
{
queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
queue.flush();
}
queue.finish();
timed = timer.stopAndTime();
}
return (timed / static_cast<float>(iters));
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include "include/types.h"
#include "include/utime.h"
#include "objclass/objclass.h"
#include "rgw/rgw_cls_api.h"
#include "common/Clock.h"
#include "global/global_context.h"
CLS_VER(1,0)
CLS_NAME(rgw)
cls_handle_t h_class;
cls_method_handle_t h_rgw_bucket_init_index;
cls_method_handle_t h_rgw_bucket_list;
cls_method_handle_t h_rgw_bucket_prepare_op;
cls_method_handle_t h_rgw_bucket_complete_op;
#define ROUND_BLOCK_SIZE 4096
static uint64_t get_rounded_size(uint64_t size)
{
return (size + ROUND_BLOCK_SIZE - 1) & ~(ROUND_BLOCK_SIZE - 1);
}
static int read_bucket_dir(cls_method_context_t hctx, struct rgw_bucket_dir& dir)
{
bufferlist bl;
uint64_t size;
int rc = cls_cxx_stat(hctx, &size, NULL);
if (rc < 0)
return rc;
rc = cls_cxx_map_read_full(hctx, &bl);
if (rc < 0)
return rc;
try {
bufferlist::iterator iter = bl.begin();
bufferlist header_bl;
::decode(header_bl, iter);
bufferlist::iterator header_iter = header_bl.begin();
::decode(dir.header, header_iter);
__u32 nkeys = 0;
::decode(nkeys, iter);
while (nkeys) {
string key;
bufferlist value;
::decode(key, iter);
::decode(value, iter);
bufferlist::iterator val_iter = value.begin();
::decode(dir.m[key], val_iter);
--nkeys;
}
} catch (buffer::error& err) {
CLS_LOG("ERROR: read_bucket_dir(): failed to decode buffer\n");
return -EIO;
}
return 0;
}
static int write_bucket_dir(cls_method_context_t hctx, struct rgw_bucket_dir& dir)
{
bufferlist bl;
::encode(dir, bl);
int rc = cls_cxx_write_full(hctx, &bl);
return rc;
}
int rgw_bucket_list(cls_method_context_t hctx, bufferlist *in, bufferlist *out)
{
bufferlist bl;
struct rgw_bucket_dir dir;
int rc = read_bucket_dir(hctx, dir);
if (rc < 0)
return rc;
bufferlist::iterator iter = in->begin();
struct rgw_cls_list_op op;
try {
::decode(op, iter);
} catch (buffer::error& err) {
CLS_LOG("ERROR: rgw_bucket_list(): failed to decode request\n");
return -EINVAL;
}
struct rgw_cls_list_ret ret;
struct rgw_bucket_dir& new_dir = ret.dir;
new_dir.header = dir.header;
std::map<string, struct rgw_bucket_dir_entry>& m = new_dir.m;
std::map<string, struct rgw_bucket_dir_entry>::iterator miter = dir.m.upper_bound(op.start_obj);
uint32_t i;
for (i = 0; i != op.num_entries && miter != dir.m.end(); ++i, ++miter) {
m[miter->first] = miter->second;
}
ret.is_truncated = (miter != dir.m.end());
::encode(ret, *out);
return 0;
}
int rgw_bucket_init_index(cls_method_context_t hctx, bufferlist *in, bufferlist *out)
{
bufferlist bl;
bufferlist::iterator iter;
uint64_t size;
int rc = cls_cxx_stat(hctx, &size, NULL);
if (rc < 0)
return rc;
if (size != 0) {
CLS_LOG("ERROR: index already initialized\n");
return -EINVAL;
}
rgw_bucket_dir dir;
bufferlist map_bl;
bufferlist header_bl;
::encode(dir.header, header_bl);
::encode(header_bl, map_bl);
__u32 num_keys = 0;
::encode(num_keys, map_bl);
rc = cls_cxx_map_write_full(hctx, &map_bl);
return rc;
}
int rgw_bucket_prepare_op(cls_method_context_t hctx, bufferlist *in, bufferlist *out)
{
bufferlist bl;
struct rgw_bucket_dir dir;
int rc = read_bucket_dir(hctx, dir);
if (rc < 0)
return rc;
rgw_cls_obj_prepare_op op;
bufferlist::iterator iter = in->begin();
try {
::decode(op, iter);
} catch (buffer::error& err) {
CLS_LOG("ERROR: rgw_bucket_prepare_op(): failed to decode request\n");
return -EINVAL;
}
CLS_LOG("rgw_bucket_prepare_op(): request: op=%d name=%s tag=%s\n", op.op, op.name.c_str(), op.tag.c_str());
std::map<string, struct rgw_bucket_dir_entry>::iterator miter = dir.m.find(op.name);
struct rgw_bucket_dir_entry *entry = NULL;
if (miter != dir.m.end()) {
entry = &miter->second;
} else {
entry = &dir.m[op.name];
entry->name = op.name;
entry->epoch = 0;
entry->exists = false;
}
if (op.tag.empty()) {
CLS_LOG("ERROR: tag is empty\n");
return -EINVAL;
}
struct rgw_bucket_pending_info& info = entry->pending_map[op.tag];
info.timestamp = ceph_clock_now(g_ceph_context);
info.state = CLS_RGW_STATE_PENDING_MODIFY;
info.op = op.op;
entry->pending_map[op.tag] = info;
rc = write_bucket_dir(hctx, dir);
return rc;
}
int rgw_bucket_complete_op(cls_method_context_t hctx, bufferlist *in, bufferlist *out)
{
bufferlist bl;
struct rgw_bucket_dir dir;
int rc = read_bucket_dir(hctx, dir);
if (rc < 0)
return rc;
CLS_LOG("rgw_bucket_complete_op(): dir.m.size()=%lld", dir.m.size());
rgw_cls_obj_complete_op op;
bufferlist::iterator iter = in->begin();
try {
::decode(op, iter);
} catch (buffer::error& err) {
CLS_LOG("ERROR: rgw_bucket_complete_op(): failed to decode request\n");
return -EINVAL;
}
CLS_LOG("rgw_bucket_complete_op(): request: op=%d name=%s epoch=%lld tag=%s\n", op.op, op.name.c_str(), op.epoch, op.tag.c_str());
std::map<string, struct rgw_bucket_dir_entry>::iterator miter = dir.m.find(op.name);
struct rgw_bucket_dir_entry *entry = NULL;
CLS_LOG("rgw_bucket_modify(): dir.m.size()=%lld", dir.m.size());
if (miter != dir.m.end()) {
entry = &miter->second;
CLS_LOG("rgw_bucket_complete_op(): existing entry: epoch=%lld\n", entry->epoch);
if (op.epoch <= entry->epoch) {
CLS_LOG("rgw_bucket_complete_op(): skipping request, old epoch\n");
return 0;
}
if (entry->exists) {
struct rgw_bucket_category_stats& stats = dir.header.stats[entry->meta.category];
stats.num_entries--;
stats.total_size -= entry->meta.size;
stats.total_size_rounded -= get_rounded_size(entry->meta.size);
}
} else {
entry = &dir.m[op.name];
entry->name = op.name;
entry->epoch = op.epoch;
entry->meta = op.meta;
}
if (op.tag.size()) {
map<string, struct rgw_bucket_pending_info>::iterator pinter = entry->pending_map.find(op.tag);
if (pinter == entry->pending_map.end()) {
CLS_LOG("ERROR: couldn't find tag for pending operation\n");
return -EINVAL;
}
entry->pending_map.erase(pinter);
}
switch (op.op) {
case CLS_RGW_OP_DEL:
if (miter != dir.m.end()) {
if (!entry->pending_map.size())
dir.m.erase(miter);
else
entry->exists = false;
} else {
return -ENOENT;
}
break;
case CLS_RGW_OP_ADD:
{
struct rgw_bucket_dir_entry_meta& meta = op.meta;
struct rgw_bucket_category_stats& stats = dir.header.stats[meta.category];
entry->meta = meta;
entry->name = op.name;
entry->epoch = op.epoch;
entry->exists = true;
stats.num_entries++;
stats.total_size += meta.size;
stats.total_size_rounded += get_rounded_size(meta.size);
}
break;
}
rc = write_bucket_dir(hctx, dir);
return rc;
}
void __cls_init()
{
CLS_LOG("Loaded rgw class!");
cls_register("rgw", &h_class);
cls_register_cxx_method(h_class, "bucket_init_index", CLS_METHOD_RD | CLS_METHOD_WR | CLS_METHOD_PUBLIC, rgw_bucket_init_index, &h_rgw_bucket_init_index);
cls_register_cxx_method(h_class, "bucket_list", CLS_METHOD_RD | CLS_METHOD_PUBLIC, rgw_bucket_list, &h_rgw_bucket_list);
cls_register_cxx_method(h_class, "bucket_prepare_op", CLS_METHOD_RD | CLS_METHOD_WR | CLS_METHOD_PUBLIC, rgw_bucket_prepare_op, &h_rgw_bucket_prepare_op);
cls_register_cxx_method(h_class, "bucket_complete_op", CLS_METHOD_RD | CLS_METHOD_WR | CLS_METHOD_PUBLIC, rgw_bucket_complete_op, &h_rgw_bucket_complete_op);
return;
}
<commit_msg>cls_rgw: refactor rgw_bucket_prepare_op in terms of tmap<commit_after>#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include "include/types.h"
#include "include/utime.h"
#include "objclass/objclass.h"
#include "rgw/rgw_cls_api.h"
#include "common/Clock.h"
#include "global/global_context.h"
CLS_VER(1,0)
CLS_NAME(rgw)
cls_handle_t h_class;
cls_method_handle_t h_rgw_bucket_init_index;
cls_method_handle_t h_rgw_bucket_list;
cls_method_handle_t h_rgw_bucket_prepare_op;
cls_method_handle_t h_rgw_bucket_complete_op;
#define ROUND_BLOCK_SIZE 4096
static uint64_t get_rounded_size(uint64_t size)
{
return (size + ROUND_BLOCK_SIZE - 1) & ~(ROUND_BLOCK_SIZE - 1);
}
static int read_bucket_dir(cls_method_context_t hctx, struct rgw_bucket_dir& dir)
{
bufferlist bl;
uint64_t size;
int rc = cls_cxx_stat(hctx, &size, NULL);
if (rc < 0)
return rc;
rc = cls_cxx_map_read_full(hctx, &bl);
if (rc < 0)
return rc;
try {
bufferlist::iterator iter = bl.begin();
bufferlist header_bl;
::decode(header_bl, iter);
bufferlist::iterator header_iter = header_bl.begin();
::decode(dir.header, header_iter);
__u32 nkeys = 0;
::decode(nkeys, iter);
while (nkeys) {
string key;
bufferlist value;
::decode(key, iter);
::decode(value, iter);
bufferlist::iterator val_iter = value.begin();
::decode(dir.m[key], val_iter);
--nkeys;
}
} catch (buffer::error& err) {
CLS_LOG("ERROR: read_bucket_dir(): failed to decode buffer\n");
return -EIO;
}
return 0;
}
static int write_bucket_dir(cls_method_context_t hctx, struct rgw_bucket_dir& dir)
{
bufferlist bl;
::encode(dir, bl);
int rc = cls_cxx_write_full(hctx, &bl);
return rc;
}
int rgw_bucket_list(cls_method_context_t hctx, bufferlist *in, bufferlist *out)
{
bufferlist bl;
struct rgw_bucket_dir dir;
int rc = read_bucket_dir(hctx, dir);
if (rc < 0)
return rc;
bufferlist::iterator iter = in->begin();
struct rgw_cls_list_op op;
try {
::decode(op, iter);
} catch (buffer::error& err) {
CLS_LOG("ERROR: rgw_bucket_list(): failed to decode request\n");
return -EINVAL;
}
struct rgw_cls_list_ret ret;
struct rgw_bucket_dir& new_dir = ret.dir;
new_dir.header = dir.header;
std::map<string, struct rgw_bucket_dir_entry>& m = new_dir.m;
std::map<string, struct rgw_bucket_dir_entry>::iterator miter = dir.m.upper_bound(op.start_obj);
uint32_t i;
for (i = 0; i != op.num_entries && miter != dir.m.end(); ++i, ++miter) {
m[miter->first] = miter->second;
}
ret.is_truncated = (miter != dir.m.end());
::encode(ret, *out);
return 0;
}
int rgw_bucket_init_index(cls_method_context_t hctx, bufferlist *in, bufferlist *out)
{
bufferlist bl;
bufferlist::iterator iter;
uint64_t size;
int rc = cls_cxx_stat(hctx, &size, NULL);
if (rc < 0)
return rc;
if (size != 0) {
CLS_LOG("ERROR: index already initialized\n");
return -EINVAL;
}
rgw_bucket_dir dir;
bufferlist map_bl;
bufferlist header_bl;
::encode(dir.header, header_bl);
::encode(header_bl, map_bl);
__u32 num_keys = 0;
::encode(num_keys, map_bl);
rc = cls_cxx_map_write_full(hctx, &map_bl);
return rc;
}
int rgw_bucket_prepare_op(cls_method_context_t hctx, bufferlist *in, bufferlist *out)
{
// decode request
rgw_cls_obj_prepare_op op;
bufferlist::iterator iter = in->begin();
try {
::decode(op, iter);
} catch (buffer::error& err) {
CLS_LOG("ERROR: rgw_bucket_prepare_op(): failed to decode request\n");
return -EINVAL;
}
if (op.tag.empty()) {
CLS_LOG("ERROR: tag is empty\n");
return -EINVAL;
}
CLS_LOG("rgw_bucket_prepare_op(): request: op=%d name=%s tag=%s\n", op.op, op.name.c_str(), op.tag.c_str());
// get on-disk state
bufferlist cur_value;
int rc = cls_cxx_map_read_key(hctx, op.name, &cur_value);
if (rc < 0 && rc != -ENOENT)
return rc;
struct rgw_bucket_dir_entry entry;
if (rc != -ENOENT) {
bufferlist::iterator biter = cur_value.begin();
::decode(entry, biter);
} else { // no entry, initialize fields
entry.name = op.name;
entry.epoch = 0;
entry.exists = false;
}
// fill in proper state
struct rgw_bucket_pending_info& info = entry.pending_map[op.tag];
info.timestamp = ceph_clock_now(g_ceph_context);
info.state = CLS_RGW_STATE_PENDING_MODIFY;
info.op = op.op;
// write out new key to disk
bufferlist info_bl;
::encode(entry, info_bl);
cls_cxx_map_write_key(hctx, op.name, &info_bl);
return rc;
}
int rgw_bucket_complete_op(cls_method_context_t hctx, bufferlist *in, bufferlist *out)
{
bufferlist bl;
struct rgw_bucket_dir dir;
int rc = read_bucket_dir(hctx, dir);
if (rc < 0)
return rc;
CLS_LOG("rgw_bucket_complete_op(): dir.m.size()=%lld", dir.m.size());
rgw_cls_obj_complete_op op;
bufferlist::iterator iter = in->begin();
try {
::decode(op, iter);
} catch (buffer::error& err) {
CLS_LOG("ERROR: rgw_bucket_complete_op(): failed to decode request\n");
return -EINVAL;
}
CLS_LOG("rgw_bucket_complete_op(): request: op=%d name=%s epoch=%lld tag=%s\n", op.op, op.name.c_str(), op.epoch, op.tag.c_str());
std::map<string, struct rgw_bucket_dir_entry>::iterator miter = dir.m.find(op.name);
struct rgw_bucket_dir_entry *entry = NULL;
CLS_LOG("rgw_bucket_modify(): dir.m.size()=%lld", dir.m.size());
if (miter != dir.m.end()) {
entry = &miter->second;
CLS_LOG("rgw_bucket_complete_op(): existing entry: epoch=%lld\n", entry->epoch);
if (op.epoch <= entry->epoch) {
CLS_LOG("rgw_bucket_complete_op(): skipping request, old epoch\n");
return 0;
}
if (entry->exists) {
struct rgw_bucket_category_stats& stats = dir.header.stats[entry->meta.category];
stats.num_entries--;
stats.total_size -= entry->meta.size;
stats.total_size_rounded -= get_rounded_size(entry->meta.size);
}
} else {
entry = &dir.m[op.name];
entry->name = op.name;
entry->epoch = op.epoch;
entry->meta = op.meta;
}
if (op.tag.size()) {
map<string, struct rgw_bucket_pending_info>::iterator pinter = entry->pending_map.find(op.tag);
if (pinter == entry->pending_map.end()) {
CLS_LOG("ERROR: couldn't find tag for pending operation\n");
return -EINVAL;
}
entry->pending_map.erase(pinter);
}
switch (op.op) {
case CLS_RGW_OP_DEL:
if (miter != dir.m.end()) {
if (!entry->pending_map.size())
dir.m.erase(miter);
else
entry->exists = false;
} else {
return -ENOENT;
}
break;
case CLS_RGW_OP_ADD:
{
struct rgw_bucket_dir_entry_meta& meta = op.meta;
struct rgw_bucket_category_stats& stats = dir.header.stats[meta.category];
entry->meta = meta;
entry->name = op.name;
entry->epoch = op.epoch;
entry->exists = true;
stats.num_entries++;
stats.total_size += meta.size;
stats.total_size_rounded += get_rounded_size(meta.size);
}
break;
}
rc = write_bucket_dir(hctx, dir);
return rc;
}
void __cls_init()
{
CLS_LOG("Loaded rgw class!");
cls_register("rgw", &h_class);
cls_register_cxx_method(h_class, "bucket_init_index", CLS_METHOD_RD | CLS_METHOD_WR | CLS_METHOD_PUBLIC, rgw_bucket_init_index, &h_rgw_bucket_init_index);
cls_register_cxx_method(h_class, "bucket_list", CLS_METHOD_RD | CLS_METHOD_PUBLIC, rgw_bucket_list, &h_rgw_bucket_list);
cls_register_cxx_method(h_class, "bucket_prepare_op", CLS_METHOD_RD | CLS_METHOD_WR | CLS_METHOD_PUBLIC, rgw_bucket_prepare_op, &h_rgw_bucket_prepare_op);
cls_register_cxx_method(h_class, "bucket_complete_op", CLS_METHOD_RD | CLS_METHOD_WR | CLS_METHOD_PUBLIC, rgw_bucket_complete_op, &h_rgw_bucket_complete_op);
return;
}
<|endoftext|>
|
<commit_before>/**
* @file lltracesampler.cpp
*
* $LicenseInfo:firstyear=2001&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2012, Linden Research, Inc.
*
* 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;
* version 2.1 of the License only.
*
* 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
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "linden_common.h"
#include "lltracerecording.h"
#include "lltrace.h"
#include "llthread.h"
namespace LLTrace
{
///////////////////////////////////////////////////////////////////////
// Recording
///////////////////////////////////////////////////////////////////////
Recording::Recording()
: mElapsedSeconds(0),
mIsStarted(false),
mRates(new AccumulatorBuffer<RateAccumulator<F32> >()),
mMeasurements(new AccumulatorBuffer<MeasurementAccumulator<F32> >()),
mStackTimers(new AccumulatorBuffer<TimerAccumulator>())
{}
Recording::~Recording()
{}
void Recording::start()
{
reset();
resume();
}
void Recording::reset()
{
mRates.write()->reset();
mMeasurements.write()->reset();
mStackTimers.write()->reset();
mElapsedSeconds = 0.0;
mSamplingTimer.reset();
}
void Recording::update()
{
mElapsedSeconds = 0.0;
mSamplingTimer.reset();
}
void Recording::resume()
{
if (!mIsStarted)
{
mSamplingTimer.reset();
LLTrace::get_thread_recorder()->activate(this);
mIsStarted = true;
}
}
void Recording::stop()
{
if (mIsStarted)
{
mElapsedSeconds += mSamplingTimer.getElapsedTimeF64();
LLTrace::get_thread_recorder()->deactivate(this);
mIsStarted = false;
}
}
void Recording::makePrimary()
{
mRates.write()->makePrimary();
mMeasurements.write()->makePrimary();
mStackTimers.write()->makePrimary();
}
bool Recording::isPrimary()
{
return mRates->isPrimary();
}
void Recording::mergeSamples( const Recording& other )
{
mRates.write()->mergeSamples(*other.mRates);
mMeasurements.write()->mergeSamples(*other.mMeasurements);
mStackTimers.write()->mergeSamples(*other.mStackTimers);
}
void Recording::mergeDeltas(const Recording& baseline, const Recording& target)
{
mRates.write()->mergeDeltas(*baseline.mRates, *target.mRates);
mStackTimers.write()->mergeDeltas(*baseline.mStackTimers, *target.mStackTimers);
}
F32 Recording::getSum(const Rate<F32>& stat)
{
return stat.getAccumulator(mRates).getSum();
}
F32 Recording::getPerSec(const Rate<F32>& stat)
{
return stat.getAccumulator(mRates).getSum() / mElapsedSeconds;
}
F32 Recording::getSum(const Measurement<F32>& stat)
{
return stat.getAccumulator(mMeasurements).getSum();
}
F32 Recording::getMin(const Measurement<F32>& stat)
{
return stat.getAccumulator(mMeasurements).getMin();
}
F32 Recording::getMax(const Measurement<F32>& stat)
{
return stat.getAccumulator(mMeasurements).getMax();
}
F32 Recording::getMean(const Measurement<F32>& stat)
{
return stat.getAccumulator(mMeasurements).getMean();
}
F32 Recording::getStandardDeviation(const Measurement<F32>& stat)
{
return stat.getAccumulator(mMeasurements).getStandardDeviation();
}
F32 Recording::getSum(const Count<F32>& stat)
{
return getSum(stat.mTotal);
}
F32 Recording::getPerSec(const Count<F32>& stat)
{
return getPerSec(stat.mTotal);
}
F32 Recording::getIncrease(const Count<F32>& stat)
{
return getSum(stat.mIncrease);
}
F32 Recording::getIncreasePerSec(const Count<F32>& stat)
{
return getPerSec(stat.mIncrease);
}
F32 Recording::getDecrease(const Count<F32>& stat)
{
return getSum(stat.mDecrease);
}
F32 Recording::getDecreasePerSec(const Count<F32>& stat)
{
return getPerSec(stat.mDecrease);
}
F32 Recording::getChurn(const Count<F32>& stat)
{
return getIncrease(stat) + getDecrease(stat);
}
F32 Recording::getChurnPerSec(const Count<F32>& stat)
{
return getIncreasePerSec(stat) + getDecreasePerSec(stat);
}
}
<commit_msg>SH-3405 WIP convert existing stats to lltrace system added update() method to trace recorders to allow mid-collection snapshots<commit_after>/**
* @file lltracesampler.cpp
*
* $LicenseInfo:firstyear=2001&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2012, Linden Research, Inc.
*
* 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;
* version 2.1 of the License only.
*
* 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
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "linden_common.h"
#include "lltracerecording.h"
#include "lltrace.h"
#include "llthread.h"
namespace LLTrace
{
///////////////////////////////////////////////////////////////////////
// Recording
///////////////////////////////////////////////////////////////////////
Recording::Recording()
: mElapsedSeconds(0),
mIsStarted(false),
mRates(new AccumulatorBuffer<RateAccumulator<F32> >()),
mMeasurements(new AccumulatorBuffer<MeasurementAccumulator<F32> >()),
mStackTimers(new AccumulatorBuffer<TimerAccumulator>())
{}
Recording::~Recording()
{}
void Recording::start()
{
reset();
resume();
}
void Recording::reset()
{
mRates.write()->reset();
mMeasurements.write()->reset();
mStackTimers.write()->reset();
mElapsedSeconds = 0.0;
mSamplingTimer.reset();
}
void Recording::update()
{
if (mIsStarted)
{
LLTrace::get_thread_recorder()->update(this);
mElapsedSeconds = 0.0;
mSamplingTimer.reset();
}
}
void Recording::resume()
{
if (!mIsStarted)
{
mSamplingTimer.reset();
LLTrace::get_thread_recorder()->activate(this);
mIsStarted = true;
}
}
void Recording::stop()
{
if (mIsStarted)
{
mElapsedSeconds += mSamplingTimer.getElapsedTimeF64();
LLTrace::get_thread_recorder()->deactivate(this);
mIsStarted = false;
}
}
void Recording::makePrimary()
{
mRates.write()->makePrimary();
mMeasurements.write()->makePrimary();
mStackTimers.write()->makePrimary();
}
bool Recording::isPrimary()
{
return mRates->isPrimary();
}
void Recording::mergeSamples( const Recording& other )
{
mRates.write()->mergeSamples(*other.mRates);
mMeasurements.write()->mergeSamples(*other.mMeasurements);
mStackTimers.write()->mergeSamples(*other.mStackTimers);
}
void Recording::mergeDeltas(const Recording& baseline, const Recording& target)
{
mRates.write()->mergeDeltas(*baseline.mRates, *target.mRates);
mStackTimers.write()->mergeDeltas(*baseline.mStackTimers, *target.mStackTimers);
}
F32 Recording::getSum(const Rate<F32>& stat)
{
return stat.getAccumulator(mRates).getSum();
}
F32 Recording::getPerSec(const Rate<F32>& stat)
{
return stat.getAccumulator(mRates).getSum() / mElapsedSeconds;
}
F32 Recording::getSum(const Measurement<F32>& stat)
{
return stat.getAccumulator(mMeasurements).getSum();
}
F32 Recording::getMin(const Measurement<F32>& stat)
{
return stat.getAccumulator(mMeasurements).getMin();
}
F32 Recording::getMax(const Measurement<F32>& stat)
{
return stat.getAccumulator(mMeasurements).getMax();
}
F32 Recording::getMean(const Measurement<F32>& stat)
{
return stat.getAccumulator(mMeasurements).getMean();
}
F32 Recording::getStandardDeviation(const Measurement<F32>& stat)
{
return stat.getAccumulator(mMeasurements).getStandardDeviation();
}
F32 Recording::getSum(const Count<F32>& stat)
{
return getSum(stat.mTotal);
}
F32 Recording::getPerSec(const Count<F32>& stat)
{
return getPerSec(stat.mTotal);
}
F32 Recording::getIncrease(const Count<F32>& stat)
{
return getSum(stat.mIncrease);
}
F32 Recording::getIncreasePerSec(const Count<F32>& stat)
{
return getPerSec(stat.mIncrease);
}
F32 Recording::getDecrease(const Count<F32>& stat)
{
return getSum(stat.mDecrease);
}
F32 Recording::getDecreasePerSec(const Count<F32>& stat)
{
return getPerSec(stat.mDecrease);
}
F32 Recording::getChurn(const Count<F32>& stat)
{
return getIncrease(stat) + getDecrease(stat);
}
F32 Recording::getChurnPerSec(const Count<F32>& stat)
{
return getIncreasePerSec(stat) + getDecreasePerSec(stat);
}
}
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "projectfilewizardextension.h"
#include "projectexplorer.h"
#include "session.h"
#include "projectnodes.h"
#include "nodesvisitor.h"
#include "projectwizardpage.h"
#include <utils/qtcassert.h>
#include <utils/stringutils.h>
#include <coreplugin/basefilewizard.h>
#include <coreplugin/dialogs/iwizard.h>
#include <coreplugin/filemanager.h>
#include <coreplugin/icore.h>
#include <coreplugin/iversioncontrol.h>
#include <coreplugin/vcsmanager.h>
#include <extensionsystem/pluginmanager.h>
#include <QtCore/QVariant>
#include <QtCore/QtAlgorithms>
#include <QtCore/QDebug>
#include <QtCore/QFileInfo>
#include <QtCore/QMultiMap>
#include <QtCore/QDir>
enum { debugExtension = 0 };
namespace ProjectExplorer {
typedef QList<ProjectNode *> ProjectNodeList;
namespace Internal {
// AllProjectNodesVisitor: Retrieve all projects (*.pri/*.pro).
class AllProjectNodesVisitor : public NodesVisitor
{
public:
static ProjectNodeList allProjects();
virtual void visitProjectNode(ProjectNode *node);
private:
ProjectNodeList m_projectNodes;
};
ProjectNodeList AllProjectNodesVisitor::allProjects()
{
AllProjectNodesVisitor visitor;
ProjectExplorerPlugin::instance()->session()->sessionNode()->accept(&visitor);
return visitor.m_projectNodes;
}
void AllProjectNodesVisitor::visitProjectNode(ProjectNode *node)
{
if (node->supportedActions().contains(ProjectNode::AddFile))
m_projectNodes.push_back(node);
}
// ProjectEntry: Context entry for a *.pri/*.pro file. Stores name and path
// for quick sort and path search, provides operator<() for maps.
struct ProjectEntry {
enum Type { ProFile, PriFile }; // Sort order: 'pro' before 'pri'
ProjectEntry() : node(0), type(ProFile) {}
explicit ProjectEntry(ProjectNode *node);
int compare(const ProjectEntry &rhs) const;
ProjectNode *node;
QString nativeDirectory; // For matching against wizards' files, which are native.
QString fileName;
QString baseName;
Type type;
};
ProjectEntry::ProjectEntry(ProjectNode *n) :
node(n),
type(ProFile)
{
const QFileInfo fi(node->path());
fileName = fi.fileName();
baseName = fi.baseName();
if (fi.suffix() != QLatin1String("pro"))
type = PriFile;
nativeDirectory = QDir::toNativeSeparators(fi.absolutePath());
}
// Sort helper that sorts by base name and puts '*.pro' before '*.pri'
int ProjectEntry::compare(const ProjectEntry &rhs) const
{
if (const int drc = nativeDirectory.compare(rhs.nativeDirectory))
return drc;
if (const int brc = baseName.compare(rhs.baseName))
return brc;
if (type < rhs.type)
return -1;
if (type > rhs.type)
return 1;
return 0;
}
inline bool operator<(const ProjectEntry &pe1, const ProjectEntry &pe2)
{
return pe1.compare(pe2) < 0;
}
QDebug operator<<(QDebug d, const ProjectEntry &e)
{
d.nospace() << e.nativeDirectory << ' ' << e.fileName << ' ' << e.type;
return d;
}
// --------- ProjectWizardContext
struct ProjectWizardContext
{
ProjectWizardContext();
void clear();
QList<Core::IVersionControl*> versionControls;
QList<ProjectEntry> projects;
ProjectWizardPage *page;
bool repositoryExists; // Is VCS 'add' sufficient, or should a repository be created?
QString commonDirectory;
};
ProjectWizardContext::ProjectWizardContext() :
page(0),
repositoryExists(false)
{
}
void ProjectWizardContext::clear()
{
versionControls.clear();
projects.clear();
commonDirectory.clear();
page = 0;
repositoryExists = false;
}
// ---- ProjectFileWizardExtension
ProjectFileWizardExtension::ProjectFileWizardExtension()
: m_context(0)
{
}
ProjectFileWizardExtension::~ProjectFileWizardExtension()
{
delete m_context;
}
// Find the project the new files should be added to given their common
// path. Either a direct match on the directory or the directory with
// the longest matching path (list containing"/project/subproject1" matching
// common path "/project/subproject1/newuserpath").
// This relies on 'pro' occurring before 'pri' in the list.
static int findMatchingProject(const QList<ProjectEntry> &projects,
const QString &commonPath)
{
if (projects.isEmpty() || commonPath.isEmpty())
return -1;
int bestMatch = -1;
int bestMatchLength = 0;
const int count = projects.size();
for (int p = 0; p < count; p++) {
// Direct match or better match? (note that the wizards' files are native).
const QString &projectDirectory = projects.at(p).nativeDirectory;
if (projectDirectory == commonPath)
return p;
if (projectDirectory.size() > bestMatchLength
&& commonPath.startsWith(projectDirectory)) {
bestMatchLength = projectDirectory.size();
bestMatch = p;
}
}
return bestMatch;
}
void ProjectFileWizardExtension::firstExtensionPageShown(const QList<Core::GeneratedFile> &files)
{
if (debugExtension)
qDebug() << Q_FUNC_INFO << files.size();
// Parametrize wizard page: find best project to add to, set up files display and
// version control depending on path
QStringList fileNames;
foreach (const Core::GeneratedFile &f, files)
fileNames.push_back(f.path());
m_context->commonDirectory = Utils::commonPath(fileNames);
m_context->page->setFilesDisplay(m_context->commonDirectory, fileNames);
// Find best project (Entry at 0 is 'None').
const int bestProjectIndex = findMatchingProject(m_context->projects, m_context->commonDirectory);
if (bestProjectIndex == -1) {
m_context->page->setCurrentProjectIndex(0);
} else {
m_context->page->setCurrentProjectIndex(bestProjectIndex + 1);
}
initializeVersionControlChoices();
}
void ProjectFileWizardExtension::initializeVersionControlChoices()
{
// Figure out version control situation:
// 1) Directory is managed and VCS supports "Add" -> List it
// 2) Directory is managed and VCS does not support "Add" -> None available
// 3) Directory is not managed -> Offer all VCS that support "CreateRepository"
if (!m_context->commonDirectory.isEmpty()) {
Core::IVersionControl *managingControl = Core::ICore::instance()->vcsManager()->findVersionControlForDirectory(m_context->commonDirectory);
if (managingControl) {
// Under VCS
if (managingControl->supportsOperation(Core::IVersionControl::AddOperation)) {
m_context->versionControls.push_back(managingControl);
m_context->repositoryExists = true;
}
} else {
// Create
foreach (Core::IVersionControl *vc, ExtensionSystem::PluginManager::instance()->getObjects<Core::IVersionControl>())
if (vc->supportsOperation(Core::IVersionControl::CreateRepositoryOperation))
m_context->versionControls.push_back(vc);
m_context->repositoryExists = false;
}
} // has a common root.
// Compile names
//: No version control system selected
QStringList versionControlChoices = QStringList(tr("<None>"));
foreach(const Core::IVersionControl *c, m_context->versionControls)
versionControlChoices.push_back(c->displayName());
m_context->page->setVersionControls(versionControlChoices);
// Enable adding to version control by default.
if (m_context->repositoryExists && versionControlChoices.size() >= 2)
m_context->page->setVersionControlIndex(1);
}
QList<QWizardPage *> ProjectFileWizardExtension::extensionPages(const Core::IWizard *wizard)
{
if (!m_context) {
m_context = new ProjectWizardContext;
} else {
m_context->clear();
}
// Init context with page and projects
m_context->page = new ProjectWizardPage;
// Project list remains the same over duration of wizard execution
// Note that projects cannot be added to projects.
initProjectChoices(wizard->kind() != Core::IWizard::ProjectWizard);
return QList<QWizardPage *>() << m_context->page;
}
void ProjectFileWizardExtension::initProjectChoices(bool enabled)
{
// Set up project list which remains the same over duration of wizard execution
// As tooltip, set the directory for disambiguation (should someone have
// duplicate base names in differing directories).
//: No project selected
QStringList projectChoices(tr("<None>"));
QStringList projectToolTips( QString::null ); // Do not use QString() - gcc-bug.
if (enabled) {
typedef QMap<ProjectEntry, bool> ProjectEntryMap;
// Sort by base name and purge duplicated entries (resulting from dependencies)
// via Map.
ProjectEntryMap entryMap;
foreach(ProjectNode *n, AllProjectNodesVisitor::allProjects())
entryMap.insert(ProjectEntry(n), true);
// Collect names
const ProjectEntryMap::const_iterator cend = entryMap.constEnd();
for (ProjectEntryMap::const_iterator it = entryMap.constBegin(); it != cend; ++it) {
m_context->projects.push_back(it.key());
projectChoices.push_back(it.key().fileName);
projectToolTips.push_back(it.key().nativeDirectory);
}
}
m_context->page->setProjects(projectChoices);
m_context->page->setProjectToolTips(projectToolTips);
}
bool ProjectFileWizardExtension::process(const QList<Core::GeneratedFile> &files, QString *errorMessage)
{
return processProject(files, errorMessage) &&
processVersionControl(files, errorMessage);
}
// Add files to project && version control
bool ProjectFileWizardExtension::processProject(const QList<Core::GeneratedFile> &files, QString *errorMessage)
{
typedef QMultiMap<FileType, QString> TypeFileMap;
// Add files to project (Entry at 0 is 'None').
const int projectIndex = m_context->page->currentProjectIndex() - 1;
if (projectIndex < 0 || projectIndex >= m_context->projects.size())
return true;
ProjectNode *project = m_context->projects.at(projectIndex).node;
// Split into lists by file type and bulk-add them.
TypeFileMap typeFileMap;
const Core::MimeDatabase *mdb = Core::ICore::instance()->mimeDatabase();
foreach (const Core::GeneratedFile &generatedFile, files) {
const QString path = generatedFile.path();
typeFileMap.insert(typeForFileName(mdb, path), path);
}
foreach (FileType type, typeFileMap.uniqueKeys()) {
const QStringList files = typeFileMap.values(type);
if (!project->addFiles(type, files)) {
*errorMessage = tr("Failed to add one or more files to project\n'%1' (%2).").
arg(project->path(), files.join(QString(QLatin1Char(','))));
return false;
}
}
return true;
}
bool ProjectFileWizardExtension::processVersionControl(const QList<Core::GeneratedFile> &files, QString *errorMessage)
{
// Add files to version control (Entry at 0 is 'None').
const int vcsIndex = m_context->page->versionControlIndex() - 1;
if (vcsIndex < 0 || vcsIndex >= m_context->versionControls.size())
return true;
QTC_ASSERT(!m_context->commonDirectory.isEmpty(), return false);
Core::IVersionControl *versionControl = m_context->versionControls.at(vcsIndex);
// Create repository?
if (!m_context->repositoryExists) {
QTC_ASSERT(versionControl->supportsOperation(Core::IVersionControl::CreateRepositoryOperation), return false);
if (!versionControl->vcsCreateRepository(m_context->commonDirectory)) {
*errorMessage = tr("A version control system repository could not be created in '%1'.").arg(m_context->commonDirectory);
return false;
}
}
// Add files if supported.
if (versionControl->supportsOperation(Core::IVersionControl::AddOperation)) {
foreach (const Core::GeneratedFile &generatedFile, files) {
if (!versionControl->vcsAdd(generatedFile.path())) {
*errorMessage = tr("Failed to add '%1' to the version control system.").arg(generatedFile.path());
return false;
}
}
}
return true;
}
} // namespace Internal
} // namespace ProjectExplorer
<commit_msg>Wizards: Fix duplicate list of VCS in last page.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "projectfilewizardextension.h"
#include "projectexplorer.h"
#include "session.h"
#include "projectnodes.h"
#include "nodesvisitor.h"
#include "projectwizardpage.h"
#include <utils/qtcassert.h>
#include <utils/stringutils.h>
#include <coreplugin/basefilewizard.h>
#include <coreplugin/dialogs/iwizard.h>
#include <coreplugin/filemanager.h>
#include <coreplugin/icore.h>
#include <coreplugin/iversioncontrol.h>
#include <coreplugin/vcsmanager.h>
#include <extensionsystem/pluginmanager.h>
#include <QtCore/QVariant>
#include <QtCore/QtAlgorithms>
#include <QtCore/QDebug>
#include <QtCore/QFileInfo>
#include <QtCore/QMultiMap>
#include <QtCore/QDir>
enum { debugExtension = 0 };
namespace ProjectExplorer {
typedef QList<ProjectNode *> ProjectNodeList;
namespace Internal {
// AllProjectNodesVisitor: Retrieve all projects (*.pri/*.pro).
class AllProjectNodesVisitor : public NodesVisitor
{
public:
static ProjectNodeList allProjects();
virtual void visitProjectNode(ProjectNode *node);
private:
ProjectNodeList m_projectNodes;
};
ProjectNodeList AllProjectNodesVisitor::allProjects()
{
AllProjectNodesVisitor visitor;
ProjectExplorerPlugin::instance()->session()->sessionNode()->accept(&visitor);
return visitor.m_projectNodes;
}
void AllProjectNodesVisitor::visitProjectNode(ProjectNode *node)
{
if (node->supportedActions().contains(ProjectNode::AddFile))
m_projectNodes.push_back(node);
}
// ProjectEntry: Context entry for a *.pri/*.pro file. Stores name and path
// for quick sort and path search, provides operator<() for maps.
struct ProjectEntry {
enum Type { ProFile, PriFile }; // Sort order: 'pro' before 'pri'
ProjectEntry() : node(0), type(ProFile) {}
explicit ProjectEntry(ProjectNode *node);
int compare(const ProjectEntry &rhs) const;
ProjectNode *node;
QString nativeDirectory; // For matching against wizards' files, which are native.
QString fileName;
QString baseName;
Type type;
};
ProjectEntry::ProjectEntry(ProjectNode *n) :
node(n),
type(ProFile)
{
const QFileInfo fi(node->path());
fileName = fi.fileName();
baseName = fi.baseName();
if (fi.suffix() != QLatin1String("pro"))
type = PriFile;
nativeDirectory = QDir::toNativeSeparators(fi.absolutePath());
}
// Sort helper that sorts by base name and puts '*.pro' before '*.pri'
int ProjectEntry::compare(const ProjectEntry &rhs) const
{
if (const int drc = nativeDirectory.compare(rhs.nativeDirectory))
return drc;
if (const int brc = baseName.compare(rhs.baseName))
return brc;
if (type < rhs.type)
return -1;
if (type > rhs.type)
return 1;
return 0;
}
inline bool operator<(const ProjectEntry &pe1, const ProjectEntry &pe2)
{
return pe1.compare(pe2) < 0;
}
QDebug operator<<(QDebug d, const ProjectEntry &e)
{
d.nospace() << e.nativeDirectory << ' ' << e.fileName << ' ' << e.type;
return d;
}
// --------- ProjectWizardContext
struct ProjectWizardContext
{
ProjectWizardContext();
void clear();
QList<Core::IVersionControl*> versionControls;
QList<ProjectEntry> projects;
ProjectWizardPage *page;
bool repositoryExists; // Is VCS 'add' sufficient, or should a repository be created?
QString commonDirectory;
};
ProjectWizardContext::ProjectWizardContext() :
page(0),
repositoryExists(false)
{
}
void ProjectWizardContext::clear()
{
versionControls.clear();
projects.clear();
commonDirectory.clear();
page = 0;
repositoryExists = false;
}
// ---- ProjectFileWizardExtension
ProjectFileWizardExtension::ProjectFileWizardExtension()
: m_context(0)
{
}
ProjectFileWizardExtension::~ProjectFileWizardExtension()
{
delete m_context;
}
// Find the project the new files should be added to given their common
// path. Either a direct match on the directory or the directory with
// the longest matching path (list containing"/project/subproject1" matching
// common path "/project/subproject1/newuserpath").
// This relies on 'pro' occurring before 'pri' in the list.
static int findMatchingProject(const QList<ProjectEntry> &projects,
const QString &commonPath)
{
if (projects.isEmpty() || commonPath.isEmpty())
return -1;
int bestMatch = -1;
int bestMatchLength = 0;
const int count = projects.size();
for (int p = 0; p < count; p++) {
// Direct match or better match? (note that the wizards' files are native).
const QString &projectDirectory = projects.at(p).nativeDirectory;
if (projectDirectory == commonPath)
return p;
if (projectDirectory.size() > bestMatchLength
&& commonPath.startsWith(projectDirectory)) {
bestMatchLength = projectDirectory.size();
bestMatch = p;
}
}
return bestMatch;
}
void ProjectFileWizardExtension::firstExtensionPageShown(const QList<Core::GeneratedFile> &files)
{
if (debugExtension)
qDebug() << Q_FUNC_INFO << files.size();
// Parametrize wizard page: find best project to add to, set up files display and
// version control depending on path
QStringList fileNames;
foreach (const Core::GeneratedFile &f, files)
fileNames.push_back(f.path());
m_context->commonDirectory = Utils::commonPath(fileNames);
m_context->page->setFilesDisplay(m_context->commonDirectory, fileNames);
// Find best project (Entry at 0 is 'None').
const int bestProjectIndex = findMatchingProject(m_context->projects, m_context->commonDirectory);
if (bestProjectIndex == -1) {
m_context->page->setCurrentProjectIndex(0);
} else {
m_context->page->setCurrentProjectIndex(bestProjectIndex + 1);
}
initializeVersionControlChoices();
}
void ProjectFileWizardExtension::initializeVersionControlChoices()
{
// Figure out version control situation:
// 1) Directory is managed and VCS supports "Add" -> List it
// 2) Directory is managed and VCS does not support "Add" -> None available
// 3) Directory is not managed -> Offer all VCS that support "CreateRepository"
m_context->versionControls.clear();
if (!m_context->commonDirectory.isEmpty()) {
Core::IVersionControl *managingControl = Core::ICore::instance()->vcsManager()->findVersionControlForDirectory(m_context->commonDirectory);
if (managingControl) {
// Under VCS
if (managingControl->supportsOperation(Core::IVersionControl::AddOperation)) {
m_context->versionControls.push_back(managingControl);
m_context->repositoryExists = true;
}
} else {
// Create
foreach (Core::IVersionControl *vc, ExtensionSystem::PluginManager::instance()->getObjects<Core::IVersionControl>())
if (vc->supportsOperation(Core::IVersionControl::CreateRepositoryOperation))
m_context->versionControls.push_back(vc);
m_context->repositoryExists = false;
}
} // has a common root.
// Compile names
//: No version control system selected
QStringList versionControlChoices = QStringList(tr("<None>"));
foreach(const Core::IVersionControl *c, m_context->versionControls)
versionControlChoices.push_back(c->displayName());
m_context->page->setVersionControls(versionControlChoices);
// Enable adding to version control by default.
if (m_context->repositoryExists && versionControlChoices.size() >= 2)
m_context->page->setVersionControlIndex(1);
}
QList<QWizardPage *> ProjectFileWizardExtension::extensionPages(const Core::IWizard *wizard)
{
if (!m_context) {
m_context = new ProjectWizardContext;
} else {
m_context->clear();
}
// Init context with page and projects
m_context->page = new ProjectWizardPage;
// Project list remains the same over duration of wizard execution
// Note that projects cannot be added to projects.
initProjectChoices(wizard->kind() != Core::IWizard::ProjectWizard);
return QList<QWizardPage *>() << m_context->page;
}
void ProjectFileWizardExtension::initProjectChoices(bool enabled)
{
// Set up project list which remains the same over duration of wizard execution
// As tooltip, set the directory for disambiguation (should someone have
// duplicate base names in differing directories).
//: No project selected
QStringList projectChoices(tr("<None>"));
QStringList projectToolTips( QString::null ); // Do not use QString() - gcc-bug.
if (enabled) {
typedef QMap<ProjectEntry, bool> ProjectEntryMap;
// Sort by base name and purge duplicated entries (resulting from dependencies)
// via Map.
ProjectEntryMap entryMap;
foreach(ProjectNode *n, AllProjectNodesVisitor::allProjects())
entryMap.insert(ProjectEntry(n), true);
// Collect names
const ProjectEntryMap::const_iterator cend = entryMap.constEnd();
for (ProjectEntryMap::const_iterator it = entryMap.constBegin(); it != cend; ++it) {
m_context->projects.push_back(it.key());
projectChoices.push_back(it.key().fileName);
projectToolTips.push_back(it.key().nativeDirectory);
}
}
m_context->page->setProjects(projectChoices);
m_context->page->setProjectToolTips(projectToolTips);
}
bool ProjectFileWizardExtension::process(const QList<Core::GeneratedFile> &files, QString *errorMessage)
{
return processProject(files, errorMessage) &&
processVersionControl(files, errorMessage);
}
// Add files to project && version control
bool ProjectFileWizardExtension::processProject(const QList<Core::GeneratedFile> &files, QString *errorMessage)
{
typedef QMultiMap<FileType, QString> TypeFileMap;
// Add files to project (Entry at 0 is 'None').
const int projectIndex = m_context->page->currentProjectIndex() - 1;
if (projectIndex < 0 || projectIndex >= m_context->projects.size())
return true;
ProjectNode *project = m_context->projects.at(projectIndex).node;
// Split into lists by file type and bulk-add them.
TypeFileMap typeFileMap;
const Core::MimeDatabase *mdb = Core::ICore::instance()->mimeDatabase();
foreach (const Core::GeneratedFile &generatedFile, files) {
const QString path = generatedFile.path();
typeFileMap.insert(typeForFileName(mdb, path), path);
}
foreach (FileType type, typeFileMap.uniqueKeys()) {
const QStringList files = typeFileMap.values(type);
if (!project->addFiles(type, files)) {
*errorMessage = tr("Failed to add one or more files to project\n'%1' (%2).").
arg(project->path(), files.join(QString(QLatin1Char(','))));
return false;
}
}
return true;
}
bool ProjectFileWizardExtension::processVersionControl(const QList<Core::GeneratedFile> &files, QString *errorMessage)
{
// Add files to version control (Entry at 0 is 'None').
const int vcsIndex = m_context->page->versionControlIndex() - 1;
if (vcsIndex < 0 || vcsIndex >= m_context->versionControls.size())
return true;
QTC_ASSERT(!m_context->commonDirectory.isEmpty(), return false);
Core::IVersionControl *versionControl = m_context->versionControls.at(vcsIndex);
// Create repository?
if (!m_context->repositoryExists) {
QTC_ASSERT(versionControl->supportsOperation(Core::IVersionControl::CreateRepositoryOperation), return false);
if (!versionControl->vcsCreateRepository(m_context->commonDirectory)) {
*errorMessage = tr("A version control system repository could not be created in '%1'.").arg(m_context->commonDirectory);
return false;
}
}
// Add files if supported.
if (versionControl->supportsOperation(Core::IVersionControl::AddOperation)) {
foreach (const Core::GeneratedFile &generatedFile, files) {
if (!versionControl->vcsAdd(generatedFile.path())) {
*errorMessage = tr("Failed to add '%1' to the version control system.").arg(generatedFile.path());
return false;
}
}
}
return true;
}
} // namespace Internal
} // namespace ProjectExplorer
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#include "modelmerger.h"
#include "modelmerger.h"
#include "modelnode.h"
#include "abstractview.h"
#include "model.h"
#include "nodeproperty.h"
#include "nodelistproperty.h"
#include "bindingproperty.h"
#include "variantproperty.h"
#include "rewritertransaction.h"
#include <rewritingexception.h>
#include <QSet>
#include <QStringList>
#include <QtDebug>
namespace QmlDesigner {
static ModelNode createNodeFromNode(const ModelNode &modelNode,const QHash<QString, QString> &idRenamingHash, AbstractView *view);
static QString fixExpression(const QString &expression, const QHash<QString, QString> &idRenamingHash)
{
QString newExpression = expression;
foreach (const QString &id, idRenamingHash.keys()) {
if (newExpression.contains(id))
newExpression = newExpression.replace(id, idRenamingHash.value(id));
}
return newExpression;
}
static void syncVariantProperties(ModelNode &outputNode, const ModelNode &inputNode)
{
foreach (const VariantProperty &variantProperty, inputNode.variantProperties()) {
outputNode.variantProperty(variantProperty.name()) = variantProperty.value();
}
}
static void syncBindingProperties(ModelNode &outputNode, const ModelNode &inputNode, const QHash<QString, QString> &idRenamingHash)
{
foreach (const BindingProperty &bindingProperty, inputNode.bindingProperties()) {
outputNode.bindingProperty(bindingProperty.name()).setExpression(fixExpression(bindingProperty.expression(), idRenamingHash));
}
}
static void syncId(ModelNode &outputNode, const ModelNode &inputNode, const QHash<QString, QString> &idRenamingHash)
{
if (!inputNode.id().isEmpty()) {
outputNode.setId(idRenamingHash.value(inputNode.id()));
}
}
static void splitIdInBaseNameAndNumber(const QString &id, QString *baseId, int *number)
{
int counter = 0;
while(counter < id.count()) {
bool canConvertToInteger = false;
int newNumber = id.right(counter +1).toInt(&canConvertToInteger);
if (canConvertToInteger)
*number = newNumber;
else
break;
counter++;
}
*baseId = id.left(id.count() - counter);
}
static void setupIdRenamingHash(const ModelNode &modelNode, QHash<QString, QString> &idRenamingHash, AbstractView *view)
{
QList<ModelNode> allNodes(modelNode.allSubModelNodes());
allNodes.append(modelNode);
foreach (const ModelNode &node, allNodes) {
if (!node.id().isEmpty()) {
QString newId = node.id();
QString baseId;
int number = 1;
splitIdInBaseNameAndNumber(newId, &baseId, &number);
while (view->hasId(newId) || idRenamingHash.values().contains(newId)) {
newId = baseId + QString::number(number);
number++;
}
idRenamingHash.insert(node.id(), newId);
}
}
}
static void syncNodeProperties(ModelNode &outputNode, const ModelNode &inputNode, const QHash<QString, QString> &idRenamingHash, AbstractView *view)
{
foreach (const NodeProperty &nodeProperty, inputNode.nodeProperties()) {
ModelNode newNode = createNodeFromNode(nodeProperty.modelNode(), idRenamingHash, view);
outputNode.nodeProperty(nodeProperty.name()).reparentHere(newNode);
}
}
static void syncNodeListProperties(ModelNode &outputNode, const ModelNode &inputNode, const QHash<QString, QString> &idRenamingHash, AbstractView *view)
{
foreach (const NodeListProperty &nodeListProperty, inputNode.nodeListProperties()) {
foreach (const ModelNode &node, nodeListProperty.toModelNodeList()) {
ModelNode newNode = createNodeFromNode(node, idRenamingHash, view);
outputNode.nodeListProperty(nodeListProperty.name()).reparentHere(newNode);
}
}
}
static ModelNode createNodeFromNode(const ModelNode &modelNode,const QHash<QString, QString> &idRenamingHash, AbstractView *view)
{
QList<QPair<QString, QVariant> > propertyList;
foreach (const VariantProperty &variantProperty, modelNode.variantProperties()) {
propertyList.append(QPair<QString, QVariant>(variantProperty.name(), variantProperty.value()));
}
ModelNode newNode(view->createModelNode(modelNode.type(),modelNode.majorVersion(),modelNode.minorVersion(), propertyList));
syncBindingProperties(newNode, modelNode, idRenamingHash);
syncId(newNode, modelNode, idRenamingHash);
syncNodeProperties(newNode, modelNode, idRenamingHash, view);
syncNodeListProperties(newNode, modelNode, idRenamingHash, view);
return newNode;
}
ModelNode ModelMerger::insertModel(const ModelNode &modelNode)
{
RewriterTransaction transaction(view()->beginRewriterTransaction());
QList<Import> newImports;
foreach (const Import &import, modelNode.model()->imports()) {
if (!view()->model()->hasImport(import, true)) {
newImports.append(import);
}
}
view()->model()->changeImports(newImports, QList<Import>());
QHash<QString, QString> idRenamingHash;
setupIdRenamingHash(modelNode, idRenamingHash, view());
qDebug() << idRenamingHash;
ModelNode newNode(createNodeFromNode(modelNode, idRenamingHash, view()));
return newNode;
}
void ModelMerger::replaceModel(const ModelNode &modelNode)
{
view()->model()->changeImports(modelNode.model()->imports(), QList<Import>());
view()->model()->setFileUrl(modelNode.model()->fileUrl());
try {
RewriterTransaction transaction(view()->beginRewriterTransaction());
ModelNode rootNode(view()->rootModelNode());
foreach (const QString &propertyName, rootNode.propertyNames())
rootNode.removeProperty(propertyName);
QHash<QString, QString> idRenamingHash;
setupIdRenamingHash(modelNode, idRenamingHash, view());
syncVariantProperties(rootNode, modelNode);
syncBindingProperties(rootNode, modelNode, idRenamingHash);
syncId(rootNode, modelNode, idRenamingHash);
syncNodeProperties(rootNode, modelNode, idRenamingHash, view());
syncNodeListProperties(rootNode, modelNode, idRenamingHash, view());
m_view->changeRootNodeType(modelNode.type(), modelNode.majorVersion(), modelNode.minorVersion());
} catch (RewritingException &e) {
qWarning() << e.description(); //silent error
}
}
} //namespace QmlDesigner
<commit_msg>QmlDesigner.modelMerger: fix<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#include "modelmerger.h"
#include "modelmerger.h"
#include "modelnode.h"
#include "abstractview.h"
#include "model.h"
#include "nodeproperty.h"
#include "nodelistproperty.h"
#include "bindingproperty.h"
#include "variantproperty.h"
#include "rewritertransaction.h"
#include <rewritingexception.h>
#include <QSet>
#include <QStringList>
#include <QtDebug>
namespace QmlDesigner {
static ModelNode createNodeFromNode(const ModelNode &modelNode,const QHash<QString, QString> &idRenamingHash, AbstractView *view);
static QString fixExpression(const QString &expression, const QHash<QString, QString> &idRenamingHash)
{
QString newExpression = expression;
foreach (const QString &id, idRenamingHash.keys()) {
if (newExpression.contains(id))
newExpression = newExpression.replace(id, idRenamingHash.value(id));
}
return newExpression;
}
static void syncVariantProperties(ModelNode &outputNode, const ModelNode &inputNode)
{
foreach (const VariantProperty &variantProperty, inputNode.variantProperties()) {
outputNode.variantProperty(variantProperty.name()) = variantProperty.value();
}
}
static void syncBindingProperties(ModelNode &outputNode, const ModelNode &inputNode, const QHash<QString, QString> &idRenamingHash)
{
foreach (const BindingProperty &bindingProperty, inputNode.bindingProperties()) {
outputNode.bindingProperty(bindingProperty.name()).setExpression(fixExpression(bindingProperty.expression(), idRenamingHash));
}
}
static void syncId(ModelNode &outputNode, const ModelNode &inputNode, const QHash<QString, QString> &idRenamingHash)
{
if (!inputNode.id().isEmpty()) {
outputNode.setId(idRenamingHash.value(inputNode.id()));
}
}
static void splitIdInBaseNameAndNumber(const QString &id, QString *baseId, int *number)
{
int counter = 0;
while(counter < id.count()) {
bool canConvertToInteger = false;
int newNumber = id.right(counter +1).toInt(&canConvertToInteger);
if (canConvertToInteger)
*number = newNumber;
else
break;
counter++;
}
*baseId = id.left(id.count() - counter);
}
static void setupIdRenamingHash(const ModelNode &modelNode, QHash<QString, QString> &idRenamingHash, AbstractView *view)
{
QList<ModelNode> allNodes(modelNode.allSubModelNodes());
allNodes.append(modelNode);
foreach (const ModelNode &node, allNodes) {
if (!node.id().isEmpty()) {
QString newId = node.id();
QString baseId;
int number = 1;
splitIdInBaseNameAndNumber(newId, &baseId, &number);
while (view->hasId(newId) || idRenamingHash.values().contains(newId)) {
newId = baseId + QString::number(number);
number++;
}
idRenamingHash.insert(node.id(), newId);
}
}
}
static void syncNodeProperties(ModelNode &outputNode, const ModelNode &inputNode, const QHash<QString, QString> &idRenamingHash, AbstractView *view)
{
foreach (const NodeProperty &nodeProperty, inputNode.nodeProperties()) {
ModelNode newNode = createNodeFromNode(nodeProperty.modelNode(), idRenamingHash, view);
outputNode.nodeProperty(nodeProperty.name()).reparentHere(newNode);
}
}
static void syncNodeListProperties(ModelNode &outputNode, const ModelNode &inputNode, const QHash<QString, QString> &idRenamingHash, AbstractView *view)
{
foreach (const NodeListProperty &nodeListProperty, inputNode.nodeListProperties()) {
foreach (const ModelNode &node, nodeListProperty.toModelNodeList()) {
ModelNode newNode = createNodeFromNode(node, idRenamingHash, view);
outputNode.nodeListProperty(nodeListProperty.name()).reparentHere(newNode);
}
}
}
static ModelNode createNodeFromNode(const ModelNode &modelNode,const QHash<QString, QString> &idRenamingHash, AbstractView *view)
{
QList<QPair<QString, QVariant> > propertyList;
QList<QPair<QString, QVariant> > variantPropertyList;
foreach (const VariantProperty &variantProperty, modelNode.variantProperties()) {
propertyList.append(QPair<QString, QVariant>(variantProperty.name(), variantProperty.value()));
}
ModelNode newNode(view->createModelNode(modelNode.type(),modelNode.majorVersion(),modelNode.minorVersion(),
propertyList, variantPropertyList, modelNode.nodeSource(), modelNode.nodeSourceType()));
syncBindingProperties(newNode, modelNode, idRenamingHash);
syncId(newNode, modelNode, idRenamingHash);
syncNodeProperties(newNode, modelNode, idRenamingHash, view);
syncNodeListProperties(newNode, modelNode, idRenamingHash, view);
return newNode;
}
ModelNode ModelMerger::insertModel(const ModelNode &modelNode)
{
RewriterTransaction transaction(view()->beginRewriterTransaction());
QList<Import> newImports;
foreach (const Import &import, modelNode.model()->imports()) {
if (!view()->model()->hasImport(import, true)) {
newImports.append(import);
}
}
view()->model()->changeImports(newImports, QList<Import>());
QHash<QString, QString> idRenamingHash;
setupIdRenamingHash(modelNode, idRenamingHash, view());
qDebug() << idRenamingHash;
ModelNode newNode(createNodeFromNode(modelNode, idRenamingHash, view()));
return newNode;
}
void ModelMerger::replaceModel(const ModelNode &modelNode)
{
view()->model()->changeImports(modelNode.model()->imports(), QList<Import>());
view()->model()->setFileUrl(modelNode.model()->fileUrl());
try {
RewriterTransaction transaction(view()->beginRewriterTransaction());
ModelNode rootNode(view()->rootModelNode());
foreach (const QString &propertyName, rootNode.propertyNames())
rootNode.removeProperty(propertyName);
QHash<QString, QString> idRenamingHash;
setupIdRenamingHash(modelNode, idRenamingHash, view());
syncVariantProperties(rootNode, modelNode);
syncBindingProperties(rootNode, modelNode, idRenamingHash);
syncId(rootNode, modelNode, idRenamingHash);
syncNodeProperties(rootNode, modelNode, idRenamingHash, view());
syncNodeListProperties(rootNode, modelNode, idRenamingHash, view());
m_view->changeRootNodeType(modelNode.type(), modelNode.majorVersion(), modelNode.minorVersion());
} catch (RewritingException &e) {
qWarning() << e.description(); //silent error
}
}
} //namespace QmlDesigner
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2014 DataStax
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 "common.hpp"
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <functional>
namespace cass {
uv_buf_t alloc_buffer(size_t suggested_size) {
return uv_buf_init(new char[suggested_size], suggested_size);
}
uv_buf_t alloc_buffer(uv_handle_t* handle, size_t suggested_size) {
(void)handle;
return alloc_buffer(suggested_size);
}
void free_buffer(uv_buf_t buf) {
delete[] buf.base;
}
void clear_buffer_deque(std::deque<uv_buf_t>& buffers) {
for (std::deque<uv_buf_t>::iterator it = buffers.begin(); it != buffers.end();
++it) {
free_buffer(*it);
}
buffers.clear();
}
std::string opcode_to_string(int opcode) {
switch (opcode) {
case CQL_OPCODE_ERROR:
return "CQL_OPCODE_ERROR";
case CQL_OPCODE_STARTUP:
return "CQL_OPCODE_STARTUP";
case CQL_OPCODE_READY:
return "CQL_OPCODE_READY";
case CQL_OPCODE_AUTHENTICATE:
return "CQL_OPCODE_AUTHENTICATE";
case CQL_OPCODE_CREDENTIALS:
return "CQL_OPCODE_CREDENTIALS";
case CQL_OPCODE_OPTIONS:
return "CQL_OPCODE_OPTIONS";
case CQL_OPCODE_SUPPORTED:
return "CQL_OPCODE_SUPPORTED";
case CQL_OPCODE_QUERY:
return "CQL_OPCODE_QUERY";
case CQL_OPCODE_RESULT:
return "CQL_OPCODE_RESULT";
case CQL_OPCODE_PREPARE:
return "CQL_OPCODE_PREPARE";
case CQL_OPCODE_EXECUTE:
return "CQL_OPCODE_EXECUTE";
case CQL_OPCODE_REGISTER:
return "CQL_OPCODE_REGISTER";
case CQL_OPCODE_EVENT:
return "CQL_OPCODE_EVENT";
case CQL_OPCODE_BATCH:
return "CQL_OPCODE_BATCH";
};
assert(false);
return "";
}
std::string& trim(std::string& str) {
// Trim front
str.erase(str.begin(),
std::find_if(str.begin(), str.end(),
std::not1(std::ptr_fun<int, int>(std::isspace))));
// Trim back
str.erase(
std::find_if(str.rbegin(), str.rend(),
std::not1(std::ptr_fun<int, int>(std::isspace))).base(),
str.end());
return str;
}
} // namespace cass
<commit_msg>Added header for std::isspace<commit_after>/*
Copyright (c) 2014 DataStax
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 "common.hpp"
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <functional>
#include <locale>
namespace cass {
uv_buf_t alloc_buffer(size_t suggested_size) {
return uv_buf_init(new char[suggested_size], suggested_size);
}
uv_buf_t alloc_buffer(uv_handle_t* handle, size_t suggested_size) {
(void)handle;
return alloc_buffer(suggested_size);
}
void free_buffer(uv_buf_t buf) {
delete[] buf.base;
}
void clear_buffer_deque(std::deque<uv_buf_t>& buffers) {
for (std::deque<uv_buf_t>::iterator it = buffers.begin(); it != buffers.end();
++it) {
free_buffer(*it);
}
buffers.clear();
}
std::string opcode_to_string(int opcode) {
switch (opcode) {
case CQL_OPCODE_ERROR:
return "CQL_OPCODE_ERROR";
case CQL_OPCODE_STARTUP:
return "CQL_OPCODE_STARTUP";
case CQL_OPCODE_READY:
return "CQL_OPCODE_READY";
case CQL_OPCODE_AUTHENTICATE:
return "CQL_OPCODE_AUTHENTICATE";
case CQL_OPCODE_CREDENTIALS:
return "CQL_OPCODE_CREDENTIALS";
case CQL_OPCODE_OPTIONS:
return "CQL_OPCODE_OPTIONS";
case CQL_OPCODE_SUPPORTED:
return "CQL_OPCODE_SUPPORTED";
case CQL_OPCODE_QUERY:
return "CQL_OPCODE_QUERY";
case CQL_OPCODE_RESULT:
return "CQL_OPCODE_RESULT";
case CQL_OPCODE_PREPARE:
return "CQL_OPCODE_PREPARE";
case CQL_OPCODE_EXECUTE:
return "CQL_OPCODE_EXECUTE";
case CQL_OPCODE_REGISTER:
return "CQL_OPCODE_REGISTER";
case CQL_OPCODE_EVENT:
return "CQL_OPCODE_EVENT";
case CQL_OPCODE_BATCH:
return "CQL_OPCODE_BATCH";
};
assert(false);
return "";
}
std::string& trim(std::string& str) {
// Trim front
str.erase(str.begin(),
std::find_if(str.begin(), str.end(),
std::not1(std::ptr_fun<int, int>(std::isspace))));
// Trim back
str.erase(
std::find_if(str.rbegin(), str.rend(),
std::not1(std::ptr_fun<int, int>(std::isspace))).base(),
str.end());
return str;
}
} // namespace cass
<|endoftext|>
|
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
//MITK
#include <mitkInteractionTestHelper.h>
#include <mitkStandaloneDataStorage.h>
#include <mitkGlobalInteraction.h>
#include <mitkIOUtil.h>
#include <mitkInteractionEventConst.h>
//us
#include <usGetModuleContext.h>
#include <tinyxml.h>
mitk::InteractionTestHelper::InteractionTestHelper(const std::string &interactionXmlFilePath)
: m_InteractionFilePath(interactionXmlFilePath)
{
this->Initialize(interactionXmlFilePath);
}
void mitk::InteractionTestHelper::Initialize(const std::string &interactionXmlFilePath)
{
//TiXmlDocument document(interactionXmlPath.c_str());
TiXmlDocument document(interactionXmlFilePath);
bool loadOkay = document.LoadFile();
if (loadOkay)
{
// Global interaction must(!) be initialized
if(! mitk::GlobalInteraction::GetInstance()->IsInitialized())
mitk::GlobalInteraction::GetInstance()->Initialize("global");
//get RenderingManager instance
mitk::RenderingManager* rm = mitk::RenderingManager::GetInstance();
//create data storage
m_DataStorage = mitk::StandaloneDataStorage::New();
//for each renderer found create a render window and configure
for( TiXmlElement* element = document.FirstChildElement(mitk::InteractionEventConst::xmlTagInteractions())->FirstChildElement(mitk::InteractionEventConst::xmlTagConfigRoot())->FirstChildElement(mitk::InteractionEventConst::xmlTagRenderer());
element != NULL;
element = element->NextSiblingElement(mitk::InteractionEventConst::xmlTagRenderer()) )
{
//get name of renderer
const char* rendererName = element->Attribute(mitk::InteractionEventConst::xmlEventPropertyRendererName().c_str());
//get view direction
mitk::SliceNavigationController::ViewDirection viewDirection = mitk::SliceNavigationController::Axial;
if(element->Attribute(mitk::InteractionEventConst::xmlEventPropertyViewDirection()) != NULL)
{
int viewDirectionNum = std::atoi(element->Attribute(mitk::InteractionEventConst::xmlEventPropertyViewDirection())->c_str());
viewDirection = static_cast<mitk::SliceNavigationController::ViewDirection>(viewDirectionNum);
}
//get mapper slot id
mitk::BaseRenderer::MapperSlotId mapperID = mitk::BaseRenderer::Standard2D;
if(element->Attribute(mitk::InteractionEventConst::xmlEventPropertyMapperID()) != NULL)
{
int mapperIDNum = std::atoi(element->Attribute(mitk::InteractionEventConst::xmlEventPropertyMapperID())->c_str());
mapperID = static_cast<mitk::BaseRenderer::MapperSlotId>(mapperIDNum);
}
//create renderWindow, renderer and dispatcher
mitk::RenderWindow::Pointer rw = mitk::RenderWindow::New(NULL, rendererName, rm); //VtkRenderWindow is created within constructor if NULL
//set storage of renderer
rw->GetRenderer()->SetDataStorage(m_DataStorage);
//set view direction to axial
rw->GetSliceNavigationController()->SetDefaultViewDirection( viewDirection );
//set renderer to render 2D
rw->GetRenderer()->SetMapperID(mapperID);
//connect SliceNavigationControllers to timestep changed event of TimeNavigationController
rw->GetSliceNavigationController()->ConnectGeometryTimeEvent(rm->GetTimeNavigationController(), false);
rm->GetTimeNavigationController()->ConnectGeometryTimeEvent(rw->GetSliceNavigationController(), false);
//add to list of kown render windows
m_RenderWindowList.push_back(rw);
}
//########### register display interactor to handle scroll events ##################
//use MouseModeSwitcher to ensure that the statemachine of DisplayInteractor is loaded correctly
m_MouseModeSwitcher = mitk::MouseModeSwitcher::New();
}
else
{
mitkThrow() << "Can not load interaction xml file <" << m_InteractionFilePath << ">";
}
}
mitk::InteractionTestHelper::~InteractionTestHelper()
{
//unregister renderers
InteractionTestHelper::RenderWindowListType::iterator it = m_RenderWindowList.begin();
InteractionTestHelper::RenderWindowListType::iterator end = m_RenderWindowList.end();
for(; it != end; it++)
{
mitk::BaseRenderer::RemoveInstance((*it)->GetVtkRenderWindow());
}
}
mitk::DataStorage::Pointer mitk::InteractionTestHelper::GetDataStorage()
{
return m_DataStorage;
}
void mitk::InteractionTestHelper::AddNodeToStorage(mitk::DataNode::Pointer node)
{
this->m_DataStorage->Add(node);
mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(m_DataStorage);
}
void mitk::InteractionTestHelper::PlaybackInteraction()
{
//load events if not loaded yet
if(m_Events.empty())
this->LoadInteraction();
//playback all events in queue
for (unsigned long i=0; i < m_Events.size(); ++i)
{
//let dispatcher of sending renderer process the event
m_Events.at(i)->GetSender()->GetDispatcher()->ProcessEvent(m_Events.at(i));
}
}
void mitk::InteractionTestHelper::LoadInteraction()
{
//load interaction pattern from xml file
std::ifstream xmlStream(m_InteractionFilePath.c_str());
mitk::XML2EventParser parser(xmlStream);
m_Events = parser.GetInteractions();
xmlStream.close();
}
void mitk::InteractionTestHelper::SetTimeStep(int newTimeStep)
{
bool timeStepIsvalid = mitk::RenderingManager::GetInstance()->GetTimeNavigationController()->GetCreatedWorldGeometry()->IsValidTimeStep(newTimeStep);
if(timeStepIsvalid)
{
mitk::RenderingManager::GetInstance()->GetTimeNavigationController()->GetTime()->SetPos(newTimeStep);
}
}
mitk::RenderWindow* mitk::InteractionTestHelper::GetRenderWindowByName(const std::string &name)
{
InteractionTestHelper::RenderWindowListType::iterator it = m_RenderWindowList.begin();
InteractionTestHelper::RenderWindowListType::iterator end = m_RenderWindowList.end();
for(; it != end; it++)
{
if( name.compare( (*it)->GetRenderer()->GetName() ) == 0)
return (*it).GetPointer();
}
return NULL;
}
mitk::RenderWindow* mitk::InteractionTestHelper::GetRenderWindowByDefaultViewDirection(mitk::SliceNavigationController::ViewDirection viewDirection)
{
InteractionTestHelper::RenderWindowListType::iterator it = m_RenderWindowList.begin();
InteractionTestHelper::RenderWindowListType::iterator end = m_RenderWindowList.end();
for(; it != end; it++)
{
if( viewDirection == (*it)->GetSliceNavigationController()->GetDefaultViewDirection() )
return (*it).GetPointer();
}
return NULL;
}
mitk::RenderWindow* mitk::InteractionTestHelper::GetRenderWindow(unsigned int index)
{
if( index < m_RenderWindowList.size() )
{
return m_RenderWindowList.at(index).GetPointer();
}
else
{
return NULL;
}
}
<commit_msg>TODO check connection of 3D render-window with one of the 2D windows.<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
//MITK
#include <mitkInteractionTestHelper.h>
#include <mitkStandaloneDataStorage.h>
#include <mitkGlobalInteraction.h>
#include <mitkIOUtil.h>
#include <mitkInteractionEventConst.h>
//us
#include <usGetModuleContext.h>
#include <tinyxml.h>
mitk::InteractionTestHelper::InteractionTestHelper(const std::string &interactionXmlFilePath)
: m_InteractionFilePath(interactionXmlFilePath)
{
this->Initialize(interactionXmlFilePath);
}
void mitk::InteractionTestHelper::Initialize(const std::string &interactionXmlFilePath)
{
//TiXmlDocument document(interactionXmlPath.c_str());
TiXmlDocument document(interactionXmlFilePath);
bool loadOkay = document.LoadFile();
if (loadOkay)
{
// Global interaction must(!) be initialized
if(! mitk::GlobalInteraction::GetInstance()->IsInitialized())
mitk::GlobalInteraction::GetInstance()->Initialize("global");
//get RenderingManager instance
mitk::RenderingManager* rm = mitk::RenderingManager::GetInstance();
//create data storage
m_DataStorage = mitk::StandaloneDataStorage::New();
//for each renderer found create a render window and configure
for( TiXmlElement* element = document.FirstChildElement(mitk::InteractionEventConst::xmlTagInteractions())->FirstChildElement(mitk::InteractionEventConst::xmlTagConfigRoot())->FirstChildElement(mitk::InteractionEventConst::xmlTagRenderer());
element != NULL;
element = element->NextSiblingElement(mitk::InteractionEventConst::xmlTagRenderer()) )
{
//get name of renderer
const char* rendererName = element->Attribute(mitk::InteractionEventConst::xmlEventPropertyRendererName().c_str());
//get view direction
mitk::SliceNavigationController::ViewDirection viewDirection = mitk::SliceNavigationController::Axial;
if(element->Attribute(mitk::InteractionEventConst::xmlEventPropertyViewDirection()) != NULL)
{
int viewDirectionNum = std::atoi(element->Attribute(mitk::InteractionEventConst::xmlEventPropertyViewDirection())->c_str());
viewDirection = static_cast<mitk::SliceNavigationController::ViewDirection>(viewDirectionNum);
}
//get mapper slot id
mitk::BaseRenderer::MapperSlotId mapperID = mitk::BaseRenderer::Standard2D;
if(element->Attribute(mitk::InteractionEventConst::xmlEventPropertyMapperID()) != NULL)
{
int mapperIDNum = std::atoi(element->Attribute(mitk::InteractionEventConst::xmlEventPropertyMapperID())->c_str());
mapperID = static_cast<mitk::BaseRenderer::MapperSlotId>(mapperIDNum);
}
//create renderWindow, renderer and dispatcher
mitk::RenderWindow::Pointer rw = mitk::RenderWindow::New(NULL, rendererName, rm); //VtkRenderWindow is created within constructor if NULL
//set storage of renderer
rw->GetRenderer()->SetDataStorage(m_DataStorage);
//set view direction to axial
rw->GetSliceNavigationController()->SetDefaultViewDirection( viewDirection );
//set renderer to render 2D
rw->GetRenderer()->SetMapperID(mapperID);
//connect SliceNavigationControllers to timestep changed event of TimeNavigationController
rw->GetSliceNavigationController()->ConnectGeometryTimeEvent(rm->GetTimeNavigationController(), false);
rm->GetTimeNavigationController()->ConnectGeometryTimeEvent(rw->GetSliceNavigationController(), false);
//add to list of kown render windows
m_RenderWindowList.push_back(rw);
}
//TODO: check the following lines taken from QmitkStdMultiWidget and adapt them to be executed in our code here.
// mitkWidget1->GetSliceNavigationController()
// ->ConnectGeometrySendEvent(mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow()));
//########### register display interactor to handle scroll events ##################
//use MouseModeSwitcher to ensure that the statemachine of DisplayInteractor is loaded correctly
m_MouseModeSwitcher = mitk::MouseModeSwitcher::New();
}
else
{
mitkThrow() << "Can not load interaction xml file <" << m_InteractionFilePath << ">";
}
}
mitk::InteractionTestHelper::~InteractionTestHelper()
{
//unregister renderers
InteractionTestHelper::RenderWindowListType::iterator it = m_RenderWindowList.begin();
InteractionTestHelper::RenderWindowListType::iterator end = m_RenderWindowList.end();
for(; it != end; it++)
{
mitk::BaseRenderer::RemoveInstance((*it)->GetVtkRenderWindow());
}
}
mitk::DataStorage::Pointer mitk::InteractionTestHelper::GetDataStorage()
{
return m_DataStorage;
}
void mitk::InteractionTestHelper::AddNodeToStorage(mitk::DataNode::Pointer node)
{
this->m_DataStorage->Add(node);
mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(m_DataStorage);
}
void mitk::InteractionTestHelper::PlaybackInteraction()
{
//load events if not loaded yet
if(m_Events.empty())
this->LoadInteraction();
//playback all events in queue
for (unsigned long i=0; i < m_Events.size(); ++i)
{
//let dispatcher of sending renderer process the event
m_Events.at(i)->GetSender()->GetDispatcher()->ProcessEvent(m_Events.at(i));
}
}
void mitk::InteractionTestHelper::LoadInteraction()
{
//load interaction pattern from xml file
std::ifstream xmlStream(m_InteractionFilePath.c_str());
mitk::XML2EventParser parser(xmlStream);
m_Events = parser.GetInteractions();
xmlStream.close();
}
void mitk::InteractionTestHelper::SetTimeStep(int newTimeStep)
{
bool timeStepIsvalid = mitk::RenderingManager::GetInstance()->GetTimeNavigationController()->GetCreatedWorldGeometry()->IsValidTimeStep(newTimeStep);
if(timeStepIsvalid)
{
mitk::RenderingManager::GetInstance()->GetTimeNavigationController()->GetTime()->SetPos(newTimeStep);
}
}
mitk::RenderWindow* mitk::InteractionTestHelper::GetRenderWindowByName(const std::string &name)
{
InteractionTestHelper::RenderWindowListType::iterator it = m_RenderWindowList.begin();
InteractionTestHelper::RenderWindowListType::iterator end = m_RenderWindowList.end();
for(; it != end; it++)
{
if( name.compare( (*it)->GetRenderer()->GetName() ) == 0)
return (*it).GetPointer();
}
return NULL;
}
mitk::RenderWindow* mitk::InteractionTestHelper::GetRenderWindowByDefaultViewDirection(mitk::SliceNavigationController::ViewDirection viewDirection)
{
InteractionTestHelper::RenderWindowListType::iterator it = m_RenderWindowList.begin();
InteractionTestHelper::RenderWindowListType::iterator end = m_RenderWindowList.end();
for(; it != end; it++)
{
if( viewDirection == (*it)->GetSliceNavigationController()->GetDefaultViewDirection() )
return (*it).GetPointer();
}
return NULL;
}
mitk::RenderWindow* mitk::InteractionTestHelper::GetRenderWindow(unsigned int index)
{
if( index < m_RenderWindowList.size() )
{
return m_RenderWindowList.at(index).GetPointer();
}
else
{
return NULL;
}
}
<|endoftext|>
|
<commit_before>#ifndef CONFIG_HPP
#define CONFIG_HPP
#include <algorithm> // find
#include <deque>
#include "config_t.hpp"
#include "observer.hpp"
namespace generic {
class config : public config_t
, public observer<config_t>
{
public:
template<typename ... CS>
config(config_t * c, CS ... cs)
{
attach(c, cs ...);
}
~config(void)
{
for (auto & c : m_configs) {
c->detach(this);
}
}
template<typename ... CS>
void
attach(config_t * c, CS ... cs)
{
unfold_attach(c, cs ...);
}
template<typename ... CS>
void
detach(config_t * c, CS ... cs)
{
unfold_detach(c, cs ...);
}
const option &
operator[](const std::string & name)
{
for (auto & c : m_configs) {
try {
return (*c)[name];
} catch (...) {}
}
throw std::invalid_argument("No config value for \"" + name + "\"");
}
void
notify(config_t * c)
{
observable::notify();
}
private:
std::deque<config_t *> m_configs;
void
unfold_attach(config_t * c)
{
c->attach(this);
m_configs.push_back(c);
}
void
unfold_detach(config_t * c)
{
c->detach(this);
auto result = std::find(m_configs.begin(), m_configs.end(), c);
if (result != m_configs.end()) {
m_configs.erase(result);
}
}
}; // class config
}; // namespace generic
#endif // CONFIG_HPP
<commit_msg>Recursion needs to be actually unfold somewhere<commit_after>#ifndef CONFIG_HPP
#define CONFIG_HPP
#include <algorithm> // find
#include <deque>
#include "config_t.hpp"
#include "observer.hpp"
namespace generic {
class config : public config_t
, public observer<config_t>
{
public:
template<typename ... CS>
config(config_t * c, CS ... cs)
{
attach(c, cs ...);
}
~config(void)
{
for (auto & c : m_configs) {
c->detach(this);
}
}
template<typename ... CS>
void
attach(config_t * c, CS ... cs)
{
unfold_attach(c, cs ...);
}
template<typename ... CS>
void
detach(config_t * c, CS ... cs)
{
unfold_detach(c, cs ...);
}
const option &
operator[](const std::string & name)
{
for (auto & c : m_configs) {
try {
return (*c)[name];
} catch (...) {}
}
throw std::invalid_argument("No config value for \"" + name + "\"");
}
void
notify(config_t * c)
{
observable::notify();
}
private:
std::deque<config_t *> m_configs;
template<typename ... CS>
void
unfold_attach(config_t * c, CS ... cs)
{
unfold_attach(c);
unfold_attach(cs ...);
}
void
unfold_attach(config_t * c)
{
c->attach(this);
m_configs.push_back(c);
}
template<typename ... CS>
void
unfold_detach(config_t * c, CS ... cs)
{
unfold_detach(c);
unfold_detach(cs ...);
}
void
unfold_detach(config_t * c)
{
c->detach(this);
auto result = std::find(m_configs.begin(), m_configs.end(), c);
if (result != m_configs.end()) {
m_configs.erase(result);
}
}
}; // class config
}; // namespace generic
#endif // CONFIG_HPP
<|endoftext|>
|
<commit_before>/**************************************************************************
*
* Copyright 2007-2011 VMware, Inc.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**************************************************************************/
#include <assert.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "os.hpp"
#include "os_thread.hpp"
#include "os_string.hpp"
#include "os_version.hpp"
#include "trace_ostream.hpp"
#include "trace_writer_local.hpp"
#include "trace_format.hpp"
#include "os_backtrace.hpp"
namespace trace {
static const char *memcpy_args[3] = {"dest", "src", "n"};
const FunctionSig memcpy_sig = {0, "memcpy", 3, memcpy_args};
static const char *malloc_args[1] = {"size"};
const FunctionSig malloc_sig = {1, "malloc", 1, malloc_args};
static const char *free_args[1] = {"ptr"};
const FunctionSig free_sig = {2, "free", 1, free_args};
static const char *realloc_args[2] = {"ptr", "size"};
const FunctionSig realloc_sig = {3, "realloc", 2, realloc_args};
static void exceptionCallback(void)
{
localWriter.flush();
}
LocalWriter::LocalWriter() :
acquired(0)
{
os::String process = os::getProcessName();
os::log("apitrace: loaded into %s\n", process.str());
// Install the signal handlers as early as possible, to prevent
// interfering with the application's signal handling.
os::setExceptionCallback(exceptionCallback);
}
LocalWriter::~LocalWriter()
{
os::resetExceptionCallback();
checkProcessId();
os::String process = os::getProcessName();
os::log("apitrace: unloaded from %s\n", process.str());
}
void
LocalWriter::open(void) {
os::String szFileName;
const char *lpFileName;
lpFileName = getenv("TRACE_FILE");
if (!lpFileName) {
static unsigned dwCounter = 0;
os::String process = os::getProcessName();
#ifdef _WIN32
process.trimExtension();
#endif
process.trimDirectory();
#ifdef ANDROID
os::String prefix = "/data/data";
prefix.join(process);
#else
os::String prefix = os::getCurrentDir();
#ifdef _WIN32
// Avoid writing into Windows' system directory as quite often access
// will be denied.
if (IsWindows8OrGreater()) {
char szDirectory[MAX_PATH + 1];
GetSystemDirectoryA(szDirectory, sizeof szDirectory);
if (stricmp(prefix, szDirectory) == 0) {
GetTempPathA(sizeof szDirectory, szDirectory);
prefix = szDirectory;
}
}
#endif
#endif
prefix.join(process);
for (;;) {
FILE *file;
if (dwCounter)
szFileName = os::String::format("%s.%u.trace", prefix.str(), dwCounter);
else
szFileName = os::String::format("%s.trace", prefix.str());
lpFileName = szFileName;
file = fopen(lpFileName, "rb");
if (file == NULL)
break;
fclose(file);
++dwCounter;
}
}
os::log("apitrace: tracing to %s\n", lpFileName);
if (!Writer::open(lpFileName)) {
os::log("apitrace: error: failed to open %s\n", lpFileName);
os::abort();
}
pid = os::getCurrentProcessId();
#if 0
// For debugging the exception handler
*((int *)0) = 0;
#endif
}
static uintptr_t next_thread_num = 1;
static OS_THREAD_SPECIFIC(uintptr_t)
thread_num;
void LocalWriter::checkProcessId(void) {
if (m_file &&
os::getCurrentProcessId() != pid) {
// We are a forked child process that inherited the trace file, so
// create a new file. We can't call any method of the current
// file, as it may cause it to flush and corrupt the parent's
// trace, so we effectively leak the old file object.
close();
// Don't want to open the same file again
os::unsetEnvironment("TRACE_FILE");
open();
}
}
unsigned LocalWriter::beginEnter(const FunctionSig *sig, bool fake) {
mutex.lock();
++acquired;
checkProcessId();
if (!m_file) {
open();
}
uintptr_t this_thread_num = thread_num;
if (!this_thread_num) {
this_thread_num = next_thread_num++;
thread_num = this_thread_num;
}
assert(this_thread_num);
unsigned thread_id = this_thread_num - 1;
unsigned call_no = Writer::beginEnter(sig, thread_id);
if (!fake && os::backtrace_is_needed(sig->name)) {
std::vector<RawStackFrame> backtrace = os::get_backtrace();
beginBacktrace(backtrace.size());
for (auto & frame : backtrace) {
writeStackFrame(&frame);
}
endBacktrace();
}
return call_no;
}
void LocalWriter::endEnter(void) {
Writer::endEnter();
--acquired;
mutex.unlock();
}
void LocalWriter::beginLeave(unsigned call) {
mutex.lock();
++acquired;
Writer::beginLeave(call);
}
void LocalWriter::endLeave(void) {
Writer::endLeave();
--acquired;
mutex.unlock();
}
void LocalWriter::flush(void) {
/*
* Do nothing if the mutex is already acquired (e.g., if a segfault happen
* while writing the file) as state could be inconsistent, therefore yield
* inconsistent trace files and/or repeated segfaults till infinity.
*/
mutex.lock();
if (acquired) {
os::log("apitrace: ignoring exception while tracing\n");
} else {
++acquired;
if (m_file) {
if (os::getCurrentProcessId() != pid) {
os::log("apitrace: ignoring exception in child process\n");
} else {
os::log("apitrace: flushing trace due to an exception\n");
m_file->flush();
}
}
--acquired;
}
mutex.unlock();
}
LocalWriter localWriter;
void fakeMemcpy(const void *ptr, size_t size) {
assert(ptr);
if (!size) {
return;
}
unsigned _call = localWriter.beginEnter(&memcpy_sig, true);
#if defined(_WIN32) && !defined(NDEBUG)
size_t maxSize = 0;
MEMORY_BASIC_INFORMATION mi;
while (VirtualQuery((const uint8_t *)ptr + maxSize, &mi, sizeof mi) == sizeof mi &&
mi.Protect & (PAGE_READONLY|PAGE_READWRITE)) {
maxSize = (const uint8_t *)mi.BaseAddress + mi.RegionSize - (const uint8_t *)ptr;
}
if (maxSize < size) {
os::log("apitrace: warning: %u: clamping size from %Iu to %Iu\n", _call, size, maxSize);
size = maxSize;
}
#endif
localWriter.beginArg(0);
localWriter.writePointer((uintptr_t)ptr);
localWriter.endArg();
localWriter.beginArg(1);
localWriter.writeBlob(ptr, size);
localWriter.endArg();
localWriter.beginArg(2);
localWriter.writeUInt(size);
localWriter.endArg();
localWriter.endEnter();
localWriter.beginLeave(_call);
localWriter.endLeave();
}
} /* namespace trace */
<commit_msg>trace: Rewrite flush log messages.<commit_after>/**************************************************************************
*
* Copyright 2007-2011 VMware, Inc.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**************************************************************************/
#include <assert.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "os.hpp"
#include "os_thread.hpp"
#include "os_string.hpp"
#include "os_version.hpp"
#include "trace_ostream.hpp"
#include "trace_writer_local.hpp"
#include "trace_format.hpp"
#include "os_backtrace.hpp"
namespace trace {
static const char *memcpy_args[3] = {"dest", "src", "n"};
const FunctionSig memcpy_sig = {0, "memcpy", 3, memcpy_args};
static const char *malloc_args[1] = {"size"};
const FunctionSig malloc_sig = {1, "malloc", 1, malloc_args};
static const char *free_args[1] = {"ptr"};
const FunctionSig free_sig = {2, "free", 1, free_args};
static const char *realloc_args[2] = {"ptr", "size"};
const FunctionSig realloc_sig = {3, "realloc", 2, realloc_args};
static void exceptionCallback(void)
{
localWriter.flush();
}
LocalWriter::LocalWriter() :
acquired(0)
{
os::String process = os::getProcessName();
os::log("apitrace: loaded into %s\n", process.str());
// Install the signal handlers as early as possible, to prevent
// interfering with the application's signal handling.
os::setExceptionCallback(exceptionCallback);
}
LocalWriter::~LocalWriter()
{
os::resetExceptionCallback();
checkProcessId();
os::String process = os::getProcessName();
os::log("apitrace: unloaded from %s\n", process.str());
}
void
LocalWriter::open(void) {
os::String szFileName;
const char *lpFileName;
lpFileName = getenv("TRACE_FILE");
if (!lpFileName) {
static unsigned dwCounter = 0;
os::String process = os::getProcessName();
#ifdef _WIN32
process.trimExtension();
#endif
process.trimDirectory();
#ifdef ANDROID
os::String prefix = "/data/data";
prefix.join(process);
#else
os::String prefix = os::getCurrentDir();
#ifdef _WIN32
// Avoid writing into Windows' system directory as quite often access
// will be denied.
if (IsWindows8OrGreater()) {
char szDirectory[MAX_PATH + 1];
GetSystemDirectoryA(szDirectory, sizeof szDirectory);
if (stricmp(prefix, szDirectory) == 0) {
GetTempPathA(sizeof szDirectory, szDirectory);
prefix = szDirectory;
}
}
#endif
#endif
prefix.join(process);
for (;;) {
FILE *file;
if (dwCounter)
szFileName = os::String::format("%s.%u.trace", prefix.str(), dwCounter);
else
szFileName = os::String::format("%s.trace", prefix.str());
lpFileName = szFileName;
file = fopen(lpFileName, "rb");
if (file == NULL)
break;
fclose(file);
++dwCounter;
}
}
os::log("apitrace: tracing to %s\n", lpFileName);
if (!Writer::open(lpFileName)) {
os::log("apitrace: error: failed to open %s\n", lpFileName);
os::abort();
}
pid = os::getCurrentProcessId();
#if 0
// For debugging the exception handler
*((int *)0) = 0;
#endif
}
static uintptr_t next_thread_num = 1;
static OS_THREAD_SPECIFIC(uintptr_t)
thread_num;
void LocalWriter::checkProcessId(void) {
if (m_file &&
os::getCurrentProcessId() != pid) {
// We are a forked child process that inherited the trace file, so
// create a new file. We can't call any method of the current
// file, as it may cause it to flush and corrupt the parent's
// trace, so we effectively leak the old file object.
close();
// Don't want to open the same file again
os::unsetEnvironment("TRACE_FILE");
open();
}
}
unsigned LocalWriter::beginEnter(const FunctionSig *sig, bool fake) {
mutex.lock();
++acquired;
checkProcessId();
if (!m_file) {
open();
}
uintptr_t this_thread_num = thread_num;
if (!this_thread_num) {
this_thread_num = next_thread_num++;
thread_num = this_thread_num;
}
assert(this_thread_num);
unsigned thread_id = this_thread_num - 1;
unsigned call_no = Writer::beginEnter(sig, thread_id);
if (!fake && os::backtrace_is_needed(sig->name)) {
std::vector<RawStackFrame> backtrace = os::get_backtrace();
beginBacktrace(backtrace.size());
for (auto & frame : backtrace) {
writeStackFrame(&frame);
}
endBacktrace();
}
return call_no;
}
void LocalWriter::endEnter(void) {
Writer::endEnter();
--acquired;
mutex.unlock();
}
void LocalWriter::beginLeave(unsigned call) {
mutex.lock();
++acquired;
Writer::beginLeave(call);
}
void LocalWriter::endLeave(void) {
Writer::endLeave();
--acquired;
mutex.unlock();
}
void LocalWriter::flush(void) {
/*
* Do nothing if the mutex is already acquired (e.g., if a segfault happen
* while writing the file) as state could be inconsistent, therefore yield
* inconsistent trace files and/or repeated segfaults till infinity.
*/
mutex.lock();
if (acquired) {
os::log("apitrace: ignoring recurrent flush\n");
} else {
++acquired;
if (m_file) {
if (os::getCurrentProcessId() != pid) {
os::log("apitrace: ignoring flush in child process\n");
} else {
os::log("apitrace: flushing trace\n");
m_file->flush();
}
}
--acquired;
}
mutex.unlock();
}
LocalWriter localWriter;
void fakeMemcpy(const void *ptr, size_t size) {
assert(ptr);
if (!size) {
return;
}
unsigned _call = localWriter.beginEnter(&memcpy_sig, true);
#if defined(_WIN32) && !defined(NDEBUG)
size_t maxSize = 0;
MEMORY_BASIC_INFORMATION mi;
while (VirtualQuery((const uint8_t *)ptr + maxSize, &mi, sizeof mi) == sizeof mi &&
mi.Protect & (PAGE_READONLY|PAGE_READWRITE)) {
maxSize = (const uint8_t *)mi.BaseAddress + mi.RegionSize - (const uint8_t *)ptr;
}
if (maxSize < size) {
os::log("apitrace: warning: %u: clamping size from %Iu to %Iu\n", _call, size, maxSize);
size = maxSize;
}
#endif
localWriter.beginArg(0);
localWriter.writePointer((uintptr_t)ptr);
localWriter.endArg();
localWriter.beginArg(1);
localWriter.writeBlob(ptr, size);
localWriter.endArg();
localWriter.beginArg(2);
localWriter.writeUInt(size);
localWriter.endArg();
localWriter.endEnter();
localWriter.beginLeave(_call);
localWriter.endLeave();
}
} /* namespace trace */
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2009 RobotCub Consortium
* Author: Alessandro Scalzo alessandro.scalzo@iit.it
* CopyPolicy: Released under the terms of the GNU GPL v2.0.
*
*/
/**
*
**/
#include "qticubskinguiplugin.h"
#include <QDebug>
using namespace yarp::os;
static yarp::os::Semaphore gMutex(1);
QtiDynTreeSoleGuiPlugin::QtiDynTreeSoleGuiPlugin(QQuickItem *parent):
QQuickPaintedItem(parent)
{
// By default, QQuickItem does not draw anything. If you subclass
// QQuickItem to create a visual item, you will need to uncomment the
// following line and re-implement updatePaintNode()
setFlag(ItemHasContents, true);
gXpos = 32;
gYpos = 32;
gWidth = 300;
gHeight = 300;
gRowStride = 0;
gImageArea = 0;
gImageSize = 0;
gMapSize = 0;
gpActivationMap = NULL;
observerThread = NULL;
window_title = "SoleGui";
timer.setInterval(50);
timer.setSingleShot(false);
connect(&timer, SIGNAL(timeout()), this, SLOT(onTimeout()));
}
QtiDynTreeSoleGuiPlugin::~QtiDynTreeSoleGuiPlugin()
{
timer.stop();
mutex.lock();
if (observerThread){
observerThread->stop();
delete observerThread;
}
mutex.unlock();
}
void QtiDynTreeSoleGuiPlugin::paint(QPainter *painter)
{
if (!timer.isActive()){
return;
}
int width=painter->device()->width();
int height=painter->device()->height();
bDrawing=false;
if (bDrawing){
return;
}
bDrawing=true;
mutex.lock();
if (width!=gWidth || height!=gHeight){
gWidth=width;
gHeight=height;
gRowStride=3*gWidth;
gImageSize=gRowStride*gHeight;
gImageArea=gWidth*gHeight;
gMapSize=gWidth*gHeight*sizeof(double);
if (gpActivationMap){
delete [] gpActivationMap;
}
gpActivationMap = new double[gImageArea];
if (observerThread && gWidth>=180 && gHeight>=180){
//gpSkinMeshThreadPort->resize(gWidth,gHeight);
}
}
if (observerThread) {
painter->beginNativePainting();
observerThread->draw(painter, gWidth, gHeight);
painter->endNativePainting();
}
mutex.unlock();
bDrawing=false;
}
/*! \brief parse the parameters received from the main container in QstringList form
\param params the parameter list
*/
bool QtiDynTreeSoleGuiPlugin::parseParameters(QStringList params)
{
Network yarp;
rf.setVerbose();
rf.setDefaultContext("soleGui/soleGui");
rf.setDefaultConfigFile("soleGui.ini");
// Transform Qt Params array in standard argc & argv
int c = params.count();
char **v;
v = (char**)malloc(sizeof(char*) * c);
for (int i=0; i<params.count(); i++){
v[i] = (char*)malloc(sizeof(char) * params.at(i).length()+1);
strcpy(v[i],params.at(i).toLatin1().data());
}
if (!rf.configure(c, v)){
free(v);
return false;
}
gWidth =rf.find("width" ).asInt();
gHeight=rf.find("height").asInt();
if (rf.check("xpos")){
gXpos=rf.find("xpos").asInt();
}
if (rf.check("ypos")){
gYpos=rf.find("ypos").asInt();
}
window_title=QString("SoleGui");
windowTitleChanged();
posXChanged();
posYChanged();
widthChanged();
heightChanged();
yDebug("RF: %s", rf.toString().data());
gRowStride=3*gWidth;
gImageSize=gRowStride*gHeight;
gMapSize=gWidth*gHeight*sizeof(double);
gImageArea=gWidth*gHeight;
gpActivationMap=new double[gImageArea];
/***********/
// TODO
/***********/
timer.start();
connect(this, SIGNAL(init()), this, SLOT(onInit()), Qt::QueuedConnection);
init();
return true;
}
void QtiDynTreeSoleGuiPlugin::onTimeout()
{
update();
}
void QtiDynTreeSoleGuiPlugin::onInit()
{
int period = rf.check("period")?rf.find("period").asInt():50;
observerThread=new ObserverThread(rf, period);
observerThread->start();
done();
}
/*! \brief Returns the title.*/
QString QtiDynTreeSoleGuiPlugin::windowTitle()
{
return window_title;
}
/*! \brief Returns the x position.*/
int QtiDynTreeSoleGuiPlugin::posX()
{
return gXpos;
}
/*! \brief Returns the y position.*/
int QtiDynTreeSoleGuiPlugin::posY()
{
return gYpos;
}
/*! \brief Returns the width.*/
int QtiDynTreeSoleGuiPlugin::windowWidth()
{
return gWidth;
}
/*! \brief Returns the height.*/
int QtiDynTreeSoleGuiPlugin::windowHeight()
{
return gHeight;
}
<commit_msg>More style fixes<commit_after>/*
* Copyright (C) 2009 RobotCub Consortium
* Author: Alessandro Scalzo alessandro.scalzo@iit.it
* CopyPolicy: Released under the terms of the GNU GPL v2.0.
*
*/
/**
*
**/
#include "qticubskinguiplugin.h"
#include <QDebug>
using namespace yarp::os;
static yarp::os::Semaphore gMutex(1);
QtiDynTreeSoleGuiPlugin::QtiDynTreeSoleGuiPlugin(QQuickItem *parent):
QQuickPaintedItem(parent)
{
// By default, QQuickItem does not draw anything. If you subclass
// QQuickItem to create a visual item, you will need to uncomment the
// following line and re-implement updatePaintNode()
setFlag(ItemHasContents, true);
gXpos = 32;
gYpos = 32;
gWidth = 300;
gHeight = 300;
gRowStride = 0;
gImageArea = 0;
gImageSize = 0;
gMapSize = 0;
gpActivationMap = NULL;
observerThread = NULL;
window_title = "SoleGui";
timer.setInterval(50);
timer.setSingleShot(false);
connect(&timer, SIGNAL(timeout()), this, SLOT(onTimeout()));
}
QtiDynTreeSoleGuiPlugin::~QtiDynTreeSoleGuiPlugin()
{
timer.stop();
mutex.lock();
if (observerThread){
observerThread->stop();
delete observerThread;
}
mutex.unlock();
}
void QtiDynTreeSoleGuiPlugin::paint(QPainter *painter)
{
if (!timer.isActive()){
return;
}
int width=painter->device()->width();
int height=painter->device()->height();
bDrawing=false;
if (bDrawing){
return;
}
bDrawing=true;
mutex.lock();
if (width!=gWidth || height!=gHeight){
gWidth=width;
gHeight=height;
gRowStride=3*gWidth;
gImageSize=gRowStride*gHeight;
gImageArea=gWidth*gHeight;
gMapSize=gWidth*gHeight*sizeof(double);
if (gpActivationMap){
delete [] gpActivationMap;
}
gpActivationMap = new double[gImageArea];
if (observerThread && gWidth>=180 && gHeight>=180){
//gpSkinMeshThreadPort->resize(gWidth,gHeight);
}
}
if (observerThread) {
painter->beginNativePainting();
observerThread->draw(painter, gWidth, gHeight);
painter->endNativePainting();
}
mutex.unlock();
bDrawing=false;
}
/*! \brief parse the parameters received from the main container in QstringList form
\param params the parameter list
*/
bool QtiDynTreeSoleGuiPlugin::parseParameters(QStringList params)
{
Network yarp;
rf.setVerbose();
rf.setDefaultContext("soleGui/soleGui");
rf.setDefaultConfigFile("soleGui.ini");
// Transform Qt Params array in standard argc & argv
int c = params.count();
char **v;
v = (char**)malloc(sizeof(char*) * c);
for (int i=0; i<params.count(); i++){
v[i] = (char*)malloc(sizeof(char) * params.at(i).length()+1);
strcpy(v[i], params.at(i).toLatin1().data());
}
if (!rf.configure(c, v)){
free(v);
return false;
}
gWidth =rf.find("width" ).asInt();
gHeight=rf.find("height").asInt();
if (rf.check("xpos")){
gXpos=rf.find("xpos").asInt();
}
if (rf.check("ypos")){
gYpos=rf.find("ypos").asInt();
}
window_title=QString("SoleGui");
windowTitleChanged();
posXChanged();
posYChanged();
widthChanged();
heightChanged();
yDebug("RF: %s", rf.toString().data());
gRowStride=3*gWidth;
gImageSize=gRowStride*gHeight;
gMapSize=gWidth*gHeight*sizeof(double);
gImageArea=gWidth*gHeight;
gpActivationMap=new double[gImageArea];
/***********/
// TODO
/***********/
timer.start();
connect(this, SIGNAL(init()), this, SLOT(onInit()), Qt::QueuedConnection);
init();
return true;
}
void QtiDynTreeSoleGuiPlugin::onTimeout()
{
update();
}
void QtiDynTreeSoleGuiPlugin::onInit()
{
int period = rf.check("period")?rf.find("period").asInt():50;
observerThread=new ObserverThread(rf, period);
observerThread->start();
done();
}
/*! \brief Returns the title.*/
QString QtiDynTreeSoleGuiPlugin::windowTitle()
{
return window_title;
}
/*! \brief Returns the x position.*/
int QtiDynTreeSoleGuiPlugin::posX()
{
return gXpos;
}
/*! \brief Returns the y position.*/
int QtiDynTreeSoleGuiPlugin::posY()
{
return gYpos;
}
/*! \brief Returns the width.*/
int QtiDynTreeSoleGuiPlugin::windowWidth()
{
return gWidth;
}
/*! \brief Returns the height.*/
int QtiDynTreeSoleGuiPlugin::windowHeight()
{
return gHeight;
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2017 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include "caf/actor_config.hpp"
#include "caf/abstract_actor.hpp"
namespace caf {
actor_config::actor_config(execution_unit* ptr)
: host(ptr),
flags(abstract_channel::is_abstract_actor_flag),
groups(nullptr) {
// nop
}
std::string to_string(const actor_config& x) {
std::string result = "actor_config(";
if (x.groups == nullptr)
result += "[]";
else
result += deep_to_string(*x.groups);
auto add = [&](int flag, const char* name) {
if ((x.flags & flag) != 0) {
result += ", ";
result += name;
}
};
add(abstract_channel::is_actor_bind_decorator_flag, "bind_decorator_flag");
add(abstract_channel::is_actor_dot_decorator_flag, "dot_decorator_flag");
add(abstract_actor::is_detached_flag, "detached_flag");
add(abstract_actor::is_blocking_flag, "blocking_flag");
add(abstract_actor::is_priority_aware_flag, "priority_aware_flag");
add(abstract_actor::is_hidden_flag, "hidden_flag");
result += ")";
return result;
}
} // namespace caf
<commit_msg>Fix bug in actor_config's to_string<commit_after>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2017 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include "caf/actor_config.hpp"
#include "caf/abstract_actor.hpp"
namespace caf {
actor_config::actor_config(execution_unit* ptr)
: host(ptr),
flags(abstract_channel::is_abstract_actor_flag),
groups(nullptr) {
// nop
}
std::string to_string(const actor_config& x) {
// Note: x.groups is an input range. Traversing it is emptying it, hence we
// cannot look inside the range here.
std::string result = "actor_config(";
auto add = [&](int flag, const char* name) {
if ((x.flags & flag) != 0) {
result += ", ";
result += name;
}
};
add(abstract_channel::is_actor_bind_decorator_flag, "bind_decorator_flag");
add(abstract_channel::is_actor_dot_decorator_flag, "dot_decorator_flag");
add(abstract_actor::is_detached_flag, "detached_flag");
add(abstract_actor::is_blocking_flag, "blocking_flag");
add(abstract_actor::is_priority_aware_flag, "priority_aware_flag");
add(abstract_actor::is_hidden_flag, "hidden_flag");
result += ")";
return result;
}
} // namespace caf
<|endoftext|>
|
<commit_before>//===-- StringRef.cpp - Lightweight String References ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/SmallVector.h"
using namespace llvm;
// MSVC emits references to this into the translation units which reference it.
#ifndef _MSC_VER
const size_t StringRef::npos;
#endif
static char ascii_tolower(char x) {
if (x >= 'A' && x <= 'Z')
return x - 'A' + 'a';
return x;
}
/// compare_lower - Compare strings, ignoring case.
int StringRef::compare_lower(StringRef RHS) const {
for (size_t I = 0, E = min(Length, RHS.Length); I != E; ++I) {
char LHC = ascii_tolower(Data[I]);
char RHC = ascii_tolower(RHS.Data[I]);
if (LHC != RHC)
return LHC < RHC ? -1 : 1;
}
if (Length == RHS.Length)
return 0;
return Length < RHS.Length ? -1 : 1;
}
// Compute the edit distance between the two given strings.
unsigned StringRef::edit_distance(llvm::StringRef Other,
bool AllowReplacements) {
// The algorithm implemented below is the "classic"
// dynamic-programming algorithm for computing the Levenshtein
// distance, which is described here:
//
// http://en.wikipedia.org/wiki/Levenshtein_distance
//
// Although the algorithm is typically described using an m x n
// array, only two rows are used at a time, so this implemenation
// just keeps two separate vectors for those two rows.
size_type m = size();
size_type n = Other.size();
SmallVector<unsigned, 32> previous(n+1, 0);
for (SmallVector<unsigned, 32>::size_type i = 0; i <= n; ++i)
previous[i] = i;
SmallVector<unsigned, 32> current(n+1, 0);
for (size_type y = 1; y <= m; ++y) {
current.assign(n+1, 0);
current[0] = y;
for (size_type x = 1; x <= n; ++x) {
if (AllowReplacements) {
current[x] = min(previous[x-1] + ((*this)[y-1] == Other[x-1]? 0u:1u),
min(current[x-1], previous[x])+1);
}
else {
if ((*this)[y-1] == Other[x-1]) current[x] = previous[x-1];
else current[x] = min(current[x-1], previous[x]) + 1;
}
}
current.swap(previous);
}
return previous[n];
}
//===----------------------------------------------------------------------===//
// String Searching
//===----------------------------------------------------------------------===//
/// find - Search for the first string \arg Str in the string.
///
/// \return - The index of the first occurence of \arg Str, or npos if not
/// found.
size_t StringRef::find(StringRef Str, size_t From) const {
size_t N = Str.size();
if (N > Length)
return npos;
for (size_t e = Length - N + 1, i = min(From, e); i != e; ++i)
if (substr(i, N).equals(Str))
return i;
return npos;
}
/// rfind - Search for the last string \arg Str in the string.
///
/// \return - The index of the last occurence of \arg Str, or npos if not
/// found.
size_t StringRef::rfind(StringRef Str) const {
size_t N = Str.size();
if (N > Length)
return npos;
for (size_t i = Length - N + 1, e = 0; i != e;) {
--i;
if (substr(i, N).equals(Str))
return i;
}
return npos;
}
/// find_first_of - Find the first character in the string that is in \arg
/// Chars, or npos if not found.
///
/// Note: O(size() * Chars.size())
StringRef::size_type StringRef::find_first_of(StringRef Chars,
size_t From) const {
for (size_type i = min(From, Length), e = Length; i != e; ++i)
if (Chars.find(Data[i]) != npos)
return i;
return npos;
}
/// find_first_not_of - Find the first character in the string that is not
/// \arg C or npos if not found.
StringRef::size_type StringRef::find_first_not_of(char C, size_t From) const {
for (size_type i = min(From, Length), e = Length; i != e; ++i)
if (Data[i] != C)
return i;
return npos;
}
/// find_first_not_of - Find the first character in the string that is not
/// in the string \arg Chars, or npos if not found.
///
/// Note: O(size() * Chars.size())
StringRef::size_type StringRef::find_first_not_of(StringRef Chars,
size_t From) const {
for (size_type i = min(From, Length), e = Length; i != e; ++i)
if (Chars.find(Data[i]) == npos)
return i;
return npos;
}
//===----------------------------------------------------------------------===//
// Helpful Algorithms
//===----------------------------------------------------------------------===//
/// count - Return the number of non-overlapped occurrences of \arg Str in
/// the string.
size_t StringRef::count(StringRef Str) const {
size_t Count = 0;
size_t N = Str.size();
if (N > Length)
return 0;
for (size_t i = 0, e = Length - N + 1; i != e; ++i)
if (substr(i, N).equals(Str))
++Count;
return Count;
}
/// GetAsUnsignedInteger - Workhorse method that converts a integer character
/// sequence of radix up to 36 to an unsigned long long value.
static bool GetAsUnsignedInteger(StringRef Str, unsigned Radix,
unsigned long long &Result) {
// Autosense radix if not specified.
if (Radix == 0) {
if (Str.startswith("0x")) {
Str = Str.substr(2);
Radix = 16;
} else if (Str.startswith("0b")) {
Str = Str.substr(2);
Radix = 2;
} else if (Str.startswith("0"))
Radix = 8;
else
Radix = 10;
}
// Empty strings (after the radix autosense) are invalid.
if (Str.empty()) return true;
// Parse all the bytes of the string given this radix. Watch for overflow.
Result = 0;
while (!Str.empty()) {
unsigned CharVal;
if (Str[0] >= '0' && Str[0] <= '9')
CharVal = Str[0]-'0';
else if (Str[0] >= 'a' && Str[0] <= 'z')
CharVal = Str[0]-'a'+10;
else if (Str[0] >= 'A' && Str[0] <= 'Z')
CharVal = Str[0]-'A'+10;
else
return true;
// If the parsed value is larger than the integer radix, the string is
// invalid.
if (CharVal >= Radix)
return true;
// Add in this character.
unsigned long long PrevResult = Result;
Result = Result*Radix+CharVal;
// Check for overflow.
if (Result < PrevResult)
return true;
Str = Str.substr(1);
}
return false;
}
bool StringRef::getAsInteger(unsigned Radix, unsigned long long &Result) const {
return GetAsUnsignedInteger(*this, Radix, Result);
}
bool StringRef::getAsInteger(unsigned Radix, long long &Result) const {
unsigned long long ULLVal;
// Handle positive strings first.
if (empty() || front() != '-') {
if (GetAsUnsignedInteger(*this, Radix, ULLVal) ||
// Check for value so large it overflows a signed value.
(long long)ULLVal < 0)
return true;
Result = ULLVal;
return false;
}
// Get the positive part of the value.
if (GetAsUnsignedInteger(substr(1), Radix, ULLVal) ||
// Reject values so large they'd overflow as negative signed, but allow
// "-0". This negates the unsigned so that the negative isn't undefined
// on signed overflow.
(long long)-ULLVal > 0)
return true;
Result = -ULLVal;
return false;
}
bool StringRef::getAsInteger(unsigned Radix, int &Result) const {
long long Val;
if (getAsInteger(Radix, Val) ||
(int)Val != Val)
return true;
Result = Val;
return false;
}
bool StringRef::getAsInteger(unsigned Radix, unsigned &Result) const {
unsigned long long Val;
if (getAsInteger(Radix, Val) ||
(unsigned)Val != Val)
return true;
Result = Val;
return false;
}
<commit_msg>Switch StringRef::edit_distance over to using raw pointers, since both std::vector and llvm::SmallVector have annoying performance tradeoffs. No, I don't expect this to matter, and now it won't.<commit_after>//===-- StringRef.cpp - Lightweight String References ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/StringRef.h"
#include <cstring>
using namespace llvm;
// MSVC emits references to this into the translation units which reference it.
#ifndef _MSC_VER
const size_t StringRef::npos;
#endif
static char ascii_tolower(char x) {
if (x >= 'A' && x <= 'Z')
return x - 'A' + 'a';
return x;
}
/// compare_lower - Compare strings, ignoring case.
int StringRef::compare_lower(StringRef RHS) const {
for (size_t I = 0, E = min(Length, RHS.Length); I != E; ++I) {
char LHC = ascii_tolower(Data[I]);
char RHC = ascii_tolower(RHS.Data[I]);
if (LHC != RHC)
return LHC < RHC ? -1 : 1;
}
if (Length == RHS.Length)
return 0;
return Length < RHS.Length ? -1 : 1;
}
// Compute the edit distance between the two given strings.
unsigned StringRef::edit_distance(llvm::StringRef Other,
bool AllowReplacements) {
// The algorithm implemented below is the "classic"
// dynamic-programming algorithm for computing the Levenshtein
// distance, which is described here:
//
// http://en.wikipedia.org/wiki/Levenshtein_distance
//
// Although the algorithm is typically described using an m x n
// array, only two rows are used at a time, so this implemenation
// just keeps two separate vectors for those two rows.
size_type m = size();
size_type n = Other.size();
unsigned SmallPrevious[32];
unsigned SmallCurrent[32];
unsigned *previous = SmallPrevious;
unsigned *current = SmallCurrent;
if (n + 1 > 32) {
previous = new unsigned [n+1];
current = new unsigned [n+1];
}
for (unsigned i = 0; i <= n; ++i)
previous[i] = i;
for (size_type y = 1; y <= m; ++y) {
std::memset(current, 0, (n + 1) * sizeof(unsigned));
current[0] = y;
for (size_type x = 1; x <= n; ++x) {
if (AllowReplacements) {
current[x] = min(previous[x-1] + ((*this)[y-1] == Other[x-1]? 0u:1u),
min(current[x-1], previous[x])+1);
}
else {
if ((*this)[y-1] == Other[x-1]) current[x] = previous[x-1];
else current[x] = min(current[x-1], previous[x]) + 1;
}
}
unsigned *tmp = current;
current = previous;
previous = tmp;
}
unsigned Result = previous[n];
if (n + 1 > 32) {
delete [] previous;
delete [] current;
}
return Result;
}
//===----------------------------------------------------------------------===//
// String Searching
//===----------------------------------------------------------------------===//
/// find - Search for the first string \arg Str in the string.
///
/// \return - The index of the first occurence of \arg Str, or npos if not
/// found.
size_t StringRef::find(StringRef Str, size_t From) const {
size_t N = Str.size();
if (N > Length)
return npos;
for (size_t e = Length - N + 1, i = min(From, e); i != e; ++i)
if (substr(i, N).equals(Str))
return i;
return npos;
}
/// rfind - Search for the last string \arg Str in the string.
///
/// \return - The index of the last occurence of \arg Str, or npos if not
/// found.
size_t StringRef::rfind(StringRef Str) const {
size_t N = Str.size();
if (N > Length)
return npos;
for (size_t i = Length - N + 1, e = 0; i != e;) {
--i;
if (substr(i, N).equals(Str))
return i;
}
return npos;
}
/// find_first_of - Find the first character in the string that is in \arg
/// Chars, or npos if not found.
///
/// Note: O(size() * Chars.size())
StringRef::size_type StringRef::find_first_of(StringRef Chars,
size_t From) const {
for (size_type i = min(From, Length), e = Length; i != e; ++i)
if (Chars.find(Data[i]) != npos)
return i;
return npos;
}
/// find_first_not_of - Find the first character in the string that is not
/// \arg C or npos if not found.
StringRef::size_type StringRef::find_first_not_of(char C, size_t From) const {
for (size_type i = min(From, Length), e = Length; i != e; ++i)
if (Data[i] != C)
return i;
return npos;
}
/// find_first_not_of - Find the first character in the string that is not
/// in the string \arg Chars, or npos if not found.
///
/// Note: O(size() * Chars.size())
StringRef::size_type StringRef::find_first_not_of(StringRef Chars,
size_t From) const {
for (size_type i = min(From, Length), e = Length; i != e; ++i)
if (Chars.find(Data[i]) == npos)
return i;
return npos;
}
//===----------------------------------------------------------------------===//
// Helpful Algorithms
//===----------------------------------------------------------------------===//
/// count - Return the number of non-overlapped occurrences of \arg Str in
/// the string.
size_t StringRef::count(StringRef Str) const {
size_t Count = 0;
size_t N = Str.size();
if (N > Length)
return 0;
for (size_t i = 0, e = Length - N + 1; i != e; ++i)
if (substr(i, N).equals(Str))
++Count;
return Count;
}
/// GetAsUnsignedInteger - Workhorse method that converts a integer character
/// sequence of radix up to 36 to an unsigned long long value.
static bool GetAsUnsignedInteger(StringRef Str, unsigned Radix,
unsigned long long &Result) {
// Autosense radix if not specified.
if (Radix == 0) {
if (Str.startswith("0x")) {
Str = Str.substr(2);
Radix = 16;
} else if (Str.startswith("0b")) {
Str = Str.substr(2);
Radix = 2;
} else if (Str.startswith("0"))
Radix = 8;
else
Radix = 10;
}
// Empty strings (after the radix autosense) are invalid.
if (Str.empty()) return true;
// Parse all the bytes of the string given this radix. Watch for overflow.
Result = 0;
while (!Str.empty()) {
unsigned CharVal;
if (Str[0] >= '0' && Str[0] <= '9')
CharVal = Str[0]-'0';
else if (Str[0] >= 'a' && Str[0] <= 'z')
CharVal = Str[0]-'a'+10;
else if (Str[0] >= 'A' && Str[0] <= 'Z')
CharVal = Str[0]-'A'+10;
else
return true;
// If the parsed value is larger than the integer radix, the string is
// invalid.
if (CharVal >= Radix)
return true;
// Add in this character.
unsigned long long PrevResult = Result;
Result = Result*Radix+CharVal;
// Check for overflow.
if (Result < PrevResult)
return true;
Str = Str.substr(1);
}
return false;
}
bool StringRef::getAsInteger(unsigned Radix, unsigned long long &Result) const {
return GetAsUnsignedInteger(*this, Radix, Result);
}
bool StringRef::getAsInteger(unsigned Radix, long long &Result) const {
unsigned long long ULLVal;
// Handle positive strings first.
if (empty() || front() != '-') {
if (GetAsUnsignedInteger(*this, Radix, ULLVal) ||
// Check for value so large it overflows a signed value.
(long long)ULLVal < 0)
return true;
Result = ULLVal;
return false;
}
// Get the positive part of the value.
if (GetAsUnsignedInteger(substr(1), Radix, ULLVal) ||
// Reject values so large they'd overflow as negative signed, but allow
// "-0". This negates the unsigned so that the negative isn't undefined
// on signed overflow.
(long long)-ULLVal > 0)
return true;
Result = -ULLVal;
return false;
}
bool StringRef::getAsInteger(unsigned Radix, int &Result) const {
long long Val;
if (getAsInteger(Radix, Val) ||
(int)Val != Val)
return true;
Result = Val;
return false;
}
bool StringRef::getAsInteger(unsigned Radix, unsigned &Result) const {
unsigned long long Val;
if (getAsInteger(Radix, Val) ||
(unsigned)Val != Val)
return true;
Result = Val;
return false;
}
<|endoftext|>
|
<commit_before>//===- Dominators.cpp - Dominator Calculation -----------------------------===//
//
// This file implements simple dominator construction algorithms for finding
// forward dominators. Postdominators are available in libanalysis, but are not
// included in libvmcore, because it's not needed. Forward dominators are
// needed to support the Verifier pass.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/Dominators.h"
#include "llvm/Support/CFG.h"
#include "llvm/Assembly/Writer.h"
#include "Support/DepthFirstIterator.h"
#include "Support/SetOperations.h"
using std::set;
//===----------------------------------------------------------------------===//
// DominatorSet Implementation
//===----------------------------------------------------------------------===//
static RegisterAnalysis<DominatorSet>
A("domset", "Dominator Set Construction", true);
// dominates - Return true if A dominates B. This performs the special checks
// neccesary if A and B are in the same basic block.
//
bool DominatorSetBase::dominates(Instruction *A, Instruction *B) const {
BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
if (BBA != BBB) return dominates(BBA, BBB);
// Loop through the basic block until we find A or B.
BasicBlock::iterator I = BBA->begin();
for (; &*I != A && &*I != B; ++I) /*empty*/;
// A dominates B if it is found first in the basic block...
return &*I == A;
}
void DominatorSet::calculateDominatorsFromBlock(BasicBlock *RootBB) {
bool Changed;
Doms[RootBB].insert(RootBB); // Root always dominates itself...
do {
Changed = false;
DomSetType WorkingSet;
df_iterator<BasicBlock*> It = df_begin(RootBB), End = df_end(RootBB);
for ( ; It != End; ++It) {
BasicBlock *BB = *It;
pred_iterator PI = pred_begin(BB), PEnd = pred_end(BB);
if (PI != PEnd) { // Is there SOME predecessor?
// Loop until we get to a predecessor that has had it's dom set filled
// in at least once. We are guaranteed to have this because we are
// traversing the graph in DFO and have handled start nodes specially.
//
while (Doms[*PI].empty()) ++PI;
WorkingSet = Doms[*PI];
for (++PI; PI != PEnd; ++PI) { // Intersect all of the predecessor sets
DomSetType &PredSet = Doms[*PI];
if (PredSet.size())
set_intersect(WorkingSet, PredSet);
}
}
WorkingSet.insert(BB); // A block always dominates itself
DomSetType &BBSet = Doms[BB];
if (BBSet != WorkingSet) {
BBSet.swap(WorkingSet); // Constant time operation!
Changed = true; // The sets changed.
}
WorkingSet.clear(); // Clear out the set for next iteration
}
} while (Changed);
}
// runOnFunction - This method calculates the forward dominator sets for the
// specified function.
//
bool DominatorSet::runOnFunction(Function &F) {
Doms.clear(); // Reset from the last time we were run...
Root = &F.getEntryNode();
assert(pred_begin(Root) == pred_end(Root) &&
"Root node has predecessors in function!");
// Calculate dominator sets for the reachable basic blocks...
calculateDominatorsFromBlock(Root);
// Every basic block in the function should at least dominate themselves, and
// thus every basic block should have an entry in Doms. The one case where we
// miss this is when a basic block is unreachable. To get these we now do an
// extra pass over the function, calculating dominator information for
// unreachable blocks.
//
for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
if (Doms[I].empty()) {
calculateDominatorsFromBlock(I);
}
return false;
}
static std::ostream &operator<<(std::ostream &o, const set<BasicBlock*> &BBs) {
for (set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
I != E; ++I) {
o << " ";
WriteAsOperand(o, *I, false);
o << "\n";
}
return o;
}
void DominatorSetBase::print(std::ostream &o) const {
for (const_iterator I = begin(), E = end(); I != E; ++I)
o << "=============================--------------------------------\n"
<< "\nDominator Set For Basic Block\n" << I->first
<< "-------------------------------\n" << I->second << "\n";
}
//===----------------------------------------------------------------------===//
// ImmediateDominators Implementation
//===----------------------------------------------------------------------===//
static RegisterAnalysis<ImmediateDominators>
C("idom", "Immediate Dominators Construction", true);
// calcIDoms - Calculate the immediate dominator mapping, given a set of
// dominators for every basic block.
void ImmediateDominatorsBase::calcIDoms(const DominatorSetBase &DS) {
// Loop over all of the nodes that have dominators... figuring out the IDOM
// for each node...
//
for (DominatorSet::const_iterator DI = DS.begin(), DEnd = DS.end();
DI != DEnd; ++DI) {
BasicBlock *BB = DI->first;
const DominatorSet::DomSetType &Dominators = DI->second;
unsigned DomSetSize = Dominators.size();
if (DomSetSize == 1) continue; // Root node... IDom = null
// Loop over all dominators of this node. This corresponds to looping over
// nodes in the dominator chain, looking for a node whose dominator set is
// equal to the current nodes, except that the current node does not exist
// in it. This means that it is one level higher in the dom chain than the
// current node, and it is our idom!
//
DominatorSet::DomSetType::const_iterator I = Dominators.begin();
DominatorSet::DomSetType::const_iterator End = Dominators.end();
for (; I != End; ++I) { // Iterate over dominators...
// All of our dominators should form a chain, where the number of elements
// in the dominator set indicates what level the node is at in the chain.
// We want the node immediately above us, so it will have an identical
// dominator set, except that BB will not dominate it... therefore it's
// dominator set size will be one less than BB's...
//
if (DS.getDominators(*I).size() == DomSetSize - 1) {
IDoms[BB] = *I;
break;
}
}
}
}
void ImmediateDominatorsBase::print(std::ostream &o) const {
for (const_iterator I = begin(), E = end(); I != E; ++I)
o << "=============================--------------------------------\n"
<< "\nImmediate Dominator For Basic Block\n" << *I->first
<< "is: \n" << *I->second << "\n";
}
//===----------------------------------------------------------------------===//
// DominatorTree Implementation
//===----------------------------------------------------------------------===//
static RegisterAnalysis<DominatorTree>
E("domtree", "Dominator Tree Construction", true);
// DominatorTreeBase::reset - Free all of the tree node memory.
//
void DominatorTreeBase::reset() {
for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
delete I->second;
Nodes.clear();
}
void DominatorTreeBase::Node2::setIDom(Node2 *NewIDom) {
assert(IDom && "No immediate dominator?");
if (IDom != NewIDom) {
std::vector<Node*>::iterator I =
std::find(IDom->Children.begin(), IDom->Children.end(), this);
assert(I != IDom->Children.end() &&
"Not in immediate dominator children set!");
// I am no longer your child...
IDom->Children.erase(I);
// Switch to new dominator
IDom = NewIDom;
IDom->Children.push_back(this);
}
}
void DominatorTree::calculate(const DominatorSet &DS) {
Nodes[Root] = new Node(Root, 0); // Add a node for the root...
// Iterate over all nodes in depth first order...
for (df_iterator<BasicBlock*> I = df_begin(Root), E = df_end(Root);
I != E; ++I) {
BasicBlock *BB = *I;
const DominatorSet::DomSetType &Dominators = DS.getDominators(BB);
unsigned DomSetSize = Dominators.size();
if (DomSetSize == 1) continue; // Root node... IDom = null
// Loop over all dominators of this node. This corresponds to looping over
// nodes in the dominator chain, looking for a node whose dominator set is
// equal to the current nodes, except that the current node does not exist
// in it. This means that it is one level higher in the dom chain than the
// current node, and it is our idom! We know that we have already added
// a DominatorTree node for our idom, because the idom must be a
// predecessor in the depth first order that we are iterating through the
// function.
//
DominatorSet::DomSetType::const_iterator I = Dominators.begin();
DominatorSet::DomSetType::const_iterator End = Dominators.end();
for (; I != End; ++I) { // Iterate over dominators...
// All of our dominators should form a chain, where the number of
// elements in the dominator set indicates what level the node is at in
// the chain. We want the node immediately above us, so it will have
// an identical dominator set, except that BB will not dominate it...
// therefore it's dominator set size will be one less than BB's...
//
if (DS.getDominators(*I).size() == DomSetSize - 1) {
// We know that the immediate dominator should already have a node,
// because we are traversing the CFG in depth first order!
//
Node *IDomNode = Nodes[*I];
assert(IDomNode && "No node for IDOM?");
// Add a new tree node for this BasicBlock, and link it as a child of
// IDomNode
Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
break;
}
}
}
}
static std::ostream &operator<<(std::ostream &o,
const DominatorTreeBase::Node *Node) {
return o << Node->getNode()
<< "\n------------------------------------------\n";
}
static void PrintDomTree(const DominatorTreeBase::Node *N, std::ostream &o,
unsigned Lev) {
o << "Level #" << Lev << ": " << N;
for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end();
I != E; ++I) {
PrintDomTree(*I, o, Lev+1);
}
}
void DominatorTreeBase::print(std::ostream &o) const {
o << "=============================--------------------------------\n"
<< "Inorder Dominator Tree:\n";
PrintDomTree(Nodes.find(getRoot())->second, o, 1);
}
//===----------------------------------------------------------------------===//
// DominanceFrontier Implementation
//===----------------------------------------------------------------------===//
static RegisterAnalysis<DominanceFrontier>
G("domfrontier", "Dominance Frontier Construction", true);
const DominanceFrontier::DomSetType &
DominanceFrontier::calculate(const DominatorTree &DT,
const DominatorTree::Node *Node) {
// Loop over CFG successors to calculate DFlocal[Node]
BasicBlock *BB = Node->getNode();
DomSetType &S = Frontiers[BB]; // The new set to fill in...
for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
SI != SE; ++SI) {
// Does Node immediately dominate this successor?
if (DT[*SI]->getIDom() != Node)
S.insert(*SI);
}
// At this point, S is DFlocal. Now we union in DFup's of our children...
// Loop through and visit the nodes that Node immediately dominates (Node's
// children in the IDomTree)
//
for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
NI != NE; ++NI) {
DominatorTree::Node *IDominee = *NI;
const DomSetType &ChildDF = calculate(DT, IDominee);
DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
for (; CDFI != CDFE; ++CDFI) {
if (!Node->dominates(DT[*CDFI]))
S.insert(*CDFI);
}
}
return S;
}
void DominanceFrontierBase::print(std::ostream &o) const {
for (const_iterator I = begin(), E = end(); I != E; ++I) {
o << "=============================--------------------------------\n"
<< "\nDominance Frontier For Basic Block\n";
WriteAsOperand(o, I->first, false);
o << " is: \n" << I->second << "\n";
}
}
<commit_msg>Improve printing of dominator sets<commit_after>//===- Dominators.cpp - Dominator Calculation -----------------------------===//
//
// This file implements simple dominator construction algorithms for finding
// forward dominators. Postdominators are available in libanalysis, but are not
// included in libvmcore, because it's not needed. Forward dominators are
// needed to support the Verifier pass.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/Dominators.h"
#include "llvm/Support/CFG.h"
#include "llvm/Assembly/Writer.h"
#include "Support/DepthFirstIterator.h"
#include "Support/SetOperations.h"
using std::set;
//===----------------------------------------------------------------------===//
// DominatorSet Implementation
//===----------------------------------------------------------------------===//
static RegisterAnalysis<DominatorSet>
A("domset", "Dominator Set Construction", true);
// dominates - Return true if A dominates B. This performs the special checks
// neccesary if A and B are in the same basic block.
//
bool DominatorSetBase::dominates(Instruction *A, Instruction *B) const {
BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
if (BBA != BBB) return dominates(BBA, BBB);
// Loop through the basic block until we find A or B.
BasicBlock::iterator I = BBA->begin();
for (; &*I != A && &*I != B; ++I) /*empty*/;
// A dominates B if it is found first in the basic block...
return &*I == A;
}
void DominatorSet::calculateDominatorsFromBlock(BasicBlock *RootBB) {
bool Changed;
Doms[RootBB].insert(RootBB); // Root always dominates itself...
do {
Changed = false;
DomSetType WorkingSet;
df_iterator<BasicBlock*> It = df_begin(RootBB), End = df_end(RootBB);
for ( ; It != End; ++It) {
BasicBlock *BB = *It;
pred_iterator PI = pred_begin(BB), PEnd = pred_end(BB);
if (PI != PEnd) { // Is there SOME predecessor?
// Loop until we get to a predecessor that has had it's dom set filled
// in at least once. We are guaranteed to have this because we are
// traversing the graph in DFO and have handled start nodes specially.
//
while (Doms[*PI].empty()) ++PI;
WorkingSet = Doms[*PI];
for (++PI; PI != PEnd; ++PI) { // Intersect all of the predecessor sets
DomSetType &PredSet = Doms[*PI];
if (PredSet.size())
set_intersect(WorkingSet, PredSet);
}
}
WorkingSet.insert(BB); // A block always dominates itself
DomSetType &BBSet = Doms[BB];
if (BBSet != WorkingSet) {
BBSet.swap(WorkingSet); // Constant time operation!
Changed = true; // The sets changed.
}
WorkingSet.clear(); // Clear out the set for next iteration
}
} while (Changed);
}
// runOnFunction - This method calculates the forward dominator sets for the
// specified function.
//
bool DominatorSet::runOnFunction(Function &F) {
Doms.clear(); // Reset from the last time we were run...
Root = &F.getEntryNode();
assert(pred_begin(Root) == pred_end(Root) &&
"Root node has predecessors in function!");
// Calculate dominator sets for the reachable basic blocks...
calculateDominatorsFromBlock(Root);
// Every basic block in the function should at least dominate themselves, and
// thus every basic block should have an entry in Doms. The one case where we
// miss this is when a basic block is unreachable. To get these we now do an
// extra pass over the function, calculating dominator information for
// unreachable blocks.
//
for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
if (Doms[I].empty()) {
calculateDominatorsFromBlock(I);
}
return false;
}
static std::ostream &operator<<(std::ostream &o, const set<BasicBlock*> &BBs) {
for (set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
I != E; ++I) {
o << " ";
WriteAsOperand(o, *I, false);
o << "\n";
}
return o;
}
void DominatorSetBase::print(std::ostream &o) const {
for (const_iterator I = begin(), E = end(); I != E; ++I) {
o << "=============================--------------------------------\n"
<< "\nDominator Set For Basic Block: ";
WriteAsOperand(o, I->first, false);
o << "\n-------------------------------\n" << I->second << "\n";
}
}
//===----------------------------------------------------------------------===//
// ImmediateDominators Implementation
//===----------------------------------------------------------------------===//
static RegisterAnalysis<ImmediateDominators>
C("idom", "Immediate Dominators Construction", true);
// calcIDoms - Calculate the immediate dominator mapping, given a set of
// dominators for every basic block.
void ImmediateDominatorsBase::calcIDoms(const DominatorSetBase &DS) {
// Loop over all of the nodes that have dominators... figuring out the IDOM
// for each node...
//
for (DominatorSet::const_iterator DI = DS.begin(), DEnd = DS.end();
DI != DEnd; ++DI) {
BasicBlock *BB = DI->first;
const DominatorSet::DomSetType &Dominators = DI->second;
unsigned DomSetSize = Dominators.size();
if (DomSetSize == 1) continue; // Root node... IDom = null
// Loop over all dominators of this node. This corresponds to looping over
// nodes in the dominator chain, looking for a node whose dominator set is
// equal to the current nodes, except that the current node does not exist
// in it. This means that it is one level higher in the dom chain than the
// current node, and it is our idom!
//
DominatorSet::DomSetType::const_iterator I = Dominators.begin();
DominatorSet::DomSetType::const_iterator End = Dominators.end();
for (; I != End; ++I) { // Iterate over dominators...
// All of our dominators should form a chain, where the number of elements
// in the dominator set indicates what level the node is at in the chain.
// We want the node immediately above us, so it will have an identical
// dominator set, except that BB will not dominate it... therefore it's
// dominator set size will be one less than BB's...
//
if (DS.getDominators(*I).size() == DomSetSize - 1) {
IDoms[BB] = *I;
break;
}
}
}
}
void ImmediateDominatorsBase::print(std::ostream &o) const {
for (const_iterator I = begin(), E = end(); I != E; ++I)
o << "=============================--------------------------------\n"
<< "\nImmediate Dominator For Basic Block\n" << *I->first
<< "is: \n" << *I->second << "\n";
}
//===----------------------------------------------------------------------===//
// DominatorTree Implementation
//===----------------------------------------------------------------------===//
static RegisterAnalysis<DominatorTree>
E("domtree", "Dominator Tree Construction", true);
// DominatorTreeBase::reset - Free all of the tree node memory.
//
void DominatorTreeBase::reset() {
for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
delete I->second;
Nodes.clear();
}
void DominatorTreeBase::Node2::setIDom(Node2 *NewIDom) {
assert(IDom && "No immediate dominator?");
if (IDom != NewIDom) {
std::vector<Node*>::iterator I =
std::find(IDom->Children.begin(), IDom->Children.end(), this);
assert(I != IDom->Children.end() &&
"Not in immediate dominator children set!");
// I am no longer your child...
IDom->Children.erase(I);
// Switch to new dominator
IDom = NewIDom;
IDom->Children.push_back(this);
}
}
void DominatorTree::calculate(const DominatorSet &DS) {
Nodes[Root] = new Node(Root, 0); // Add a node for the root...
// Iterate over all nodes in depth first order...
for (df_iterator<BasicBlock*> I = df_begin(Root), E = df_end(Root);
I != E; ++I) {
BasicBlock *BB = *I;
const DominatorSet::DomSetType &Dominators = DS.getDominators(BB);
unsigned DomSetSize = Dominators.size();
if (DomSetSize == 1) continue; // Root node... IDom = null
// Loop over all dominators of this node. This corresponds to looping over
// nodes in the dominator chain, looking for a node whose dominator set is
// equal to the current nodes, except that the current node does not exist
// in it. This means that it is one level higher in the dom chain than the
// current node, and it is our idom! We know that we have already added
// a DominatorTree node for our idom, because the idom must be a
// predecessor in the depth first order that we are iterating through the
// function.
//
DominatorSet::DomSetType::const_iterator I = Dominators.begin();
DominatorSet::DomSetType::const_iterator End = Dominators.end();
for (; I != End; ++I) { // Iterate over dominators...
// All of our dominators should form a chain, where the number of
// elements in the dominator set indicates what level the node is at in
// the chain. We want the node immediately above us, so it will have
// an identical dominator set, except that BB will not dominate it...
// therefore it's dominator set size will be one less than BB's...
//
if (DS.getDominators(*I).size() == DomSetSize - 1) {
// We know that the immediate dominator should already have a node,
// because we are traversing the CFG in depth first order!
//
Node *IDomNode = Nodes[*I];
assert(IDomNode && "No node for IDOM?");
// Add a new tree node for this BasicBlock, and link it as a child of
// IDomNode
Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
break;
}
}
}
}
static std::ostream &operator<<(std::ostream &o,
const DominatorTreeBase::Node *Node) {
return o << Node->getNode()
<< "\n------------------------------------------\n";
}
static void PrintDomTree(const DominatorTreeBase::Node *N, std::ostream &o,
unsigned Lev) {
o << "Level #" << Lev << ": " << N;
for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end();
I != E; ++I) {
PrintDomTree(*I, o, Lev+1);
}
}
void DominatorTreeBase::print(std::ostream &o) const {
o << "=============================--------------------------------\n"
<< "Inorder Dominator Tree:\n";
PrintDomTree(Nodes.find(getRoot())->second, o, 1);
}
//===----------------------------------------------------------------------===//
// DominanceFrontier Implementation
//===----------------------------------------------------------------------===//
static RegisterAnalysis<DominanceFrontier>
G("domfrontier", "Dominance Frontier Construction", true);
const DominanceFrontier::DomSetType &
DominanceFrontier::calculate(const DominatorTree &DT,
const DominatorTree::Node *Node) {
// Loop over CFG successors to calculate DFlocal[Node]
BasicBlock *BB = Node->getNode();
DomSetType &S = Frontiers[BB]; // The new set to fill in...
for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
SI != SE; ++SI) {
// Does Node immediately dominate this successor?
if (DT[*SI]->getIDom() != Node)
S.insert(*SI);
}
// At this point, S is DFlocal. Now we union in DFup's of our children...
// Loop through and visit the nodes that Node immediately dominates (Node's
// children in the IDomTree)
//
for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
NI != NE; ++NI) {
DominatorTree::Node *IDominee = *NI;
const DomSetType &ChildDF = calculate(DT, IDominee);
DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
for (; CDFI != CDFE; ++CDFI) {
if (!Node->dominates(DT[*CDFI]))
S.insert(*CDFI);
}
}
return S;
}
void DominanceFrontierBase::print(std::ostream &o) const {
for (const_iterator I = begin(), E = end(); I != E; ++I) {
o << "=============================--------------------------------\n"
<< "\nDominance Frontier For Basic Block\n";
WriteAsOperand(o, I->first, false);
o << " is: \n" << I->second << "\n";
}
}
<|endoftext|>
|
<commit_before>// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
/**
* core.cpp
*
* Copyright (C) 2003 Zack Rusin <zack@kde.org>
*
* 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 "core.h"
#include "pluginmanager.h"
#include "editor.h"
#include "plugin.h"
#include <ksettings/dialog.h>
#include <kplugininfo.h>
#include <kapplication.h>
#include <kconfig.h>
#include <ktrader.h>
#include <klibloader.h>
#include <kstdaction.h>
#include <klistbox.h>
#include <kiconloader.h>
#include <kstandarddirs.h>
#include <kshortcut.h>
#include <klocale.h>
#include <kstatusbar.h>
#include <kguiitem.h>
#include <kmenu.h>
#include <kshortcut.h>
#include <kcmultidialog.h>
#include <kaction.h>
#include <kstdaccel.h>
#include <kdebug.h>
#include <qwidgetstack.h>
#include <qhbox.h>
#include <qwidget.h>
using namespace Komposer;
Core::Core( QWidget *parent, const char *name )
: KomposerIface( "KomposerIface" ),
KMainWindow( parent, name ), m_currentEditor( 0 )
{
initWidgets();
initCore();
initConnections();
setInstance( new KInstance( "komposer" ) );
createActions();
setXMLFile( "komposerui.rc" );
createGUI( 0 );
resize( 600, 400 ); // initial size
setAutoSaveSettings();
loadSettings();
}
Core::~Core()
{
saveSettings();
//Prefs::self()->writeConfig();
}
void
Core::addEditor( Komposer::Editor *editor )
{
if ( editor->widget() ) {
m_stack->addWidget( editor->widget() );
m_stack->raiseWidget( editor->widget() );
editor->widget()->show();
m_currentEditor = editor;
}
// merge the editors GUI into the main window
//insertChildClient( editor );
guiFactory()->addClient( editor );
}
void
Core::addPlugin( Komposer::Plugin *plugin )
{
//insertChildClient( plugin );
guiFactory()->addClient( plugin );
}
void
Core::slotPluginLoaded( Plugin *plugin )
{
kdDebug() << "Plugin loaded "<<endl;
Editor *editor = dynamic_cast<Editor*>( plugin );
if ( editor ) {
addEditor( editor );
} else {
addPlugin( plugin );
}
}
void
Core::slotAllPluginsLoaded()
{
QValueList<KPluginInfo*> plugins = m_pluginManager->availablePlugins();
kdDebug()<<"Number of available plugins is "<< plugins.count() <<endl;
for ( QValueList<KPluginInfo*>::iterator it = plugins.begin(); it != plugins.end(); ++it ) {
KPluginInfo *i = ( *it );
kdDebug()<<"\tAvailable plugin "<< i->pluginName()
<<", comment = "<< i->comment() <<endl;
}
if ( !m_stack->visibleWidget() ) {
m_pluginManager->loadPlugin( "komposer_defaulteditor", PluginManager::LoadAsync );
}
}
#if 0
void
Core::slotActivePartChanged( KParts::Part *part )
{
if ( !part ) {
createGUI( 0 );
return;
}
kdDebug() << "Part activated: " << part << " with stack id. "
<< m_stack->id( part->widget() )<< endl;
createGUI( part );
}
void
Core::selectEditor( Komposer::Editor *editor )
{
if ( !editor )
return;
KParts::Part *part = editor->part();
editor->select();
QPtrList<KParts::Part> *partList = const_cast<QPtrList<KParts::Part>*>(
m_partManager->parts() );
if ( partList->find( part ) == -1 )
addPart( part );
m_partManager->setActivePart( part );
QWidget *view = part->widget();
Q_ASSERT( view );
kdDebug()<<"Raising view "<<view<<endl;
if ( view )
{
m_stack->raiseWidget( view );
view->show();
view->setFocus();
m_currentEditor = editor;
}
}
void
Core::selectEditor( const QString &editorName )
{
}
#endif
void
Core::loadSettings()
{
//kdDebug()<<"Trying to select "<< Prefs::self()->m_activeEditor <<endl;
//selectEditor( Prefs::self()->m_activeEditor );
//m_activeEditors = Prefs::self()->m_activeEditors;
}
void
Core::saveSettings()
{
//if ( m_currentEditor )
//Prefs::self()->m_activeEditor = m_currentEditor->identifier();
}
void
Core::slotQuit()
{
kdDebug()<<"exit"<<endl;
m_pluginManager->shutdown();
}
void
Core::slotPreferences()
{
if ( m_dlg == 0 )
m_dlg = new KSettings::Dialog( this );
m_dlg->show();
}
void
Core::initWidgets()
{
statusBar()->show();
QHBox *topWidget = new QHBox( this );
setCentralWidget( topWidget );
m_stack = new QWidgetStack( topWidget );
}
void
Core::initCore()
{
m_pluginManager = new PluginManager( this );
connect( m_pluginManager, SIGNAL(pluginLoaded(Plugin*)),
SLOT(slotPluginLoaded(Plugin*)) );
connect( m_pluginManager, SIGNAL(allPluginsLoaded()),
SLOT(slotAllPluginsLoaded()) );
m_pluginManager->loadAllPlugins();
kdDebug()<<"Loading"<<endl;
}
void
Core::initConnections()
{
connect( kapp, SIGNAL(shutDown()),
SLOT(slotQuit()) );
}
void
Core::createActions()
{
KStdAction::close( this, SLOT(slotClose()), actionCollection() );
(void) new KAction( i18n( "&Send" ), "mail_send", CTRL+Key_Return,
this, SLOT(slotSendNow()), actionCollection(),
"send_default" );
(void) new KAction( i18n( "&Queue" ), "queue", 0,
this, SLOT(slotSendLater()),
actionCollection(), "send_alternative" );
(void) new KAction( i18n( "Save in &Drafts Folder" ), "filesave", 0,
this, SLOT(slotSaveDraft()),
actionCollection(), "save_in_drafts" );
(void) new KAction( i18n( "&Insert File..." ), "fileopen", 0,
this, SLOT(slotInsertFile()),
actionCollection(), "insert_file" );
(void) new KAction( i18n( "&Address Book" ), "contents",0,
this, SLOT(slotAddrBook()),
actionCollection(), "addressbook" );
(void) new KAction( i18n( "&New Composer" ), "mail_new",
KStdAccel::shortcut( KStdAccel::New ),
this, SLOT(slotNewComposer()),
actionCollection(), "new_composer" );
(void) new KAction( i18n( "&Attach File..." ), "attach",
0, this, SLOT(slotAttachFile()),
actionCollection(), "attach_file" );
}
void
Core::slotClose()
{
close( false );
}
void
Core::slotSendNow()
{
}
void
Core::slotSendLater()
{
}
void
Core::slotSaveDraft()
{
}
void
Core::slotInsertFile()
{
}
void
Core::slotAddrBook()
{
}
void
Core::slotNewComposer()
{
}
void
Core::slotAttachFile()
{
}
void
Core::send( int how )
{
}
void
Core::addAttachment( const KURL &url, const QString &comment )
{
}
void
Core::setBody( const QString &body )
{
m_currentEditor->setText( body );
}
void
Core::addAttachment( const QString &name,
const QCString &cte,
const QByteArray &data,
const QCString &type,
const QCString &subType,
const QCString ¶mAttr,
const QString ¶mValue,
const QCString &contDisp )
{
}
#include "core.moc"
<commit_msg>KApplication::shutDown() -> QCoreApplication::aboutToQuit()<commit_after>// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
/**
* core.cpp
*
* Copyright (C) 2003 Zack Rusin <zack@kde.org>
*
* 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 "core.h"
#include "pluginmanager.h"
#include "editor.h"
#include "plugin.h"
#include <ksettings/dialog.h>
#include <kplugininfo.h>
#include <kapplication.h>
#include <kconfig.h>
#include <ktrader.h>
#include <klibloader.h>
#include <kstdaction.h>
#include <klistbox.h>
#include <kiconloader.h>
#include <kstandarddirs.h>
#include <kshortcut.h>
#include <klocale.h>
#include <kstatusbar.h>
#include <kguiitem.h>
#include <kmenu.h>
#include <kshortcut.h>
#include <kcmultidialog.h>
#include <kaction.h>
#include <kstdaccel.h>
#include <kdebug.h>
#include <qwidgetstack.h>
#include <qhbox.h>
#include <qwidget.h>
using namespace Komposer;
Core::Core( QWidget *parent, const char *name )
: KomposerIface( "KomposerIface" ),
KMainWindow( parent, name ), m_currentEditor( 0 )
{
initWidgets();
initCore();
initConnections();
setInstance( new KInstance( "komposer" ) );
createActions();
setXMLFile( "komposerui.rc" );
createGUI( 0 );
resize( 600, 400 ); // initial size
setAutoSaveSettings();
loadSettings();
}
Core::~Core()
{
saveSettings();
//Prefs::self()->writeConfig();
}
void
Core::addEditor( Komposer::Editor *editor )
{
if ( editor->widget() ) {
m_stack->addWidget( editor->widget() );
m_stack->raiseWidget( editor->widget() );
editor->widget()->show();
m_currentEditor = editor;
}
// merge the editors GUI into the main window
//insertChildClient( editor );
guiFactory()->addClient( editor );
}
void
Core::addPlugin( Komposer::Plugin *plugin )
{
//insertChildClient( plugin );
guiFactory()->addClient( plugin );
}
void
Core::slotPluginLoaded( Plugin *plugin )
{
kdDebug() << "Plugin loaded "<<endl;
Editor *editor = dynamic_cast<Editor*>( plugin );
if ( editor ) {
addEditor( editor );
} else {
addPlugin( plugin );
}
}
void
Core::slotAllPluginsLoaded()
{
QValueList<KPluginInfo*> plugins = m_pluginManager->availablePlugins();
kdDebug()<<"Number of available plugins is "<< plugins.count() <<endl;
for ( QValueList<KPluginInfo*>::iterator it = plugins.begin(); it != plugins.end(); ++it ) {
KPluginInfo *i = ( *it );
kdDebug()<<"\tAvailable plugin "<< i->pluginName()
<<", comment = "<< i->comment() <<endl;
}
if ( !m_stack->visibleWidget() ) {
m_pluginManager->loadPlugin( "komposer_defaulteditor", PluginManager::LoadAsync );
}
}
#if 0
void
Core::slotActivePartChanged( KParts::Part *part )
{
if ( !part ) {
createGUI( 0 );
return;
}
kdDebug() << "Part activated: " << part << " with stack id. "
<< m_stack->id( part->widget() )<< endl;
createGUI( part );
}
void
Core::selectEditor( Komposer::Editor *editor )
{
if ( !editor )
return;
KParts::Part *part = editor->part();
editor->select();
QPtrList<KParts::Part> *partList = const_cast<QPtrList<KParts::Part>*>(
m_partManager->parts() );
if ( partList->find( part ) == -1 )
addPart( part );
m_partManager->setActivePart( part );
QWidget *view = part->widget();
Q_ASSERT( view );
kdDebug()<<"Raising view "<<view<<endl;
if ( view )
{
m_stack->raiseWidget( view );
view->show();
view->setFocus();
m_currentEditor = editor;
}
}
void
Core::selectEditor( const QString &editorName )
{
}
#endif
void
Core::loadSettings()
{
//kdDebug()<<"Trying to select "<< Prefs::self()->m_activeEditor <<endl;
//selectEditor( Prefs::self()->m_activeEditor );
//m_activeEditors = Prefs::self()->m_activeEditors;
}
void
Core::saveSettings()
{
//if ( m_currentEditor )
//Prefs::self()->m_activeEditor = m_currentEditor->identifier();
}
void
Core::slotQuit()
{
kdDebug()<<"exit"<<endl;
m_pluginManager->shutdown();
}
void
Core::slotPreferences()
{
if ( m_dlg == 0 )
m_dlg = new KSettings::Dialog( this );
m_dlg->show();
}
void
Core::initWidgets()
{
statusBar()->show();
QHBox *topWidget = new QHBox( this );
setCentralWidget( topWidget );
m_stack = new QWidgetStack( topWidget );
}
void
Core::initCore()
{
m_pluginManager = new PluginManager( this );
connect( m_pluginManager, SIGNAL(pluginLoaded(Plugin*)),
SLOT(slotPluginLoaded(Plugin*)) );
connect( m_pluginManager, SIGNAL(allPluginsLoaded()),
SLOT(slotAllPluginsLoaded()) );
m_pluginManager->loadAllPlugins();
kdDebug()<<"Loading"<<endl;
}
void
Core::initConnections()
{
connect( kapp, SIGNAL(aboutToQuit()),
SLOT(slotQuit()) );
}
void
Core::createActions()
{
KStdAction::close( this, SLOT(slotClose()), actionCollection() );
(void) new KAction( i18n( "&Send" ), "mail_send", CTRL+Key_Return,
this, SLOT(slotSendNow()), actionCollection(),
"send_default" );
(void) new KAction( i18n( "&Queue" ), "queue", 0,
this, SLOT(slotSendLater()),
actionCollection(), "send_alternative" );
(void) new KAction( i18n( "Save in &Drafts Folder" ), "filesave", 0,
this, SLOT(slotSaveDraft()),
actionCollection(), "save_in_drafts" );
(void) new KAction( i18n( "&Insert File..." ), "fileopen", 0,
this, SLOT(slotInsertFile()),
actionCollection(), "insert_file" );
(void) new KAction( i18n( "&Address Book" ), "contents",0,
this, SLOT(slotAddrBook()),
actionCollection(), "addressbook" );
(void) new KAction( i18n( "&New Composer" ), "mail_new",
KStdAccel::shortcut( KStdAccel::New ),
this, SLOT(slotNewComposer()),
actionCollection(), "new_composer" );
(void) new KAction( i18n( "&Attach File..." ), "attach",
0, this, SLOT(slotAttachFile()),
actionCollection(), "attach_file" );
}
void
Core::slotClose()
{
close( false );
}
void
Core::slotSendNow()
{
}
void
Core::slotSendLater()
{
}
void
Core::slotSaveDraft()
{
}
void
Core::slotInsertFile()
{
}
void
Core::slotAddrBook()
{
}
void
Core::slotNewComposer()
{
}
void
Core::slotAttachFile()
{
}
void
Core::send( int how )
{
}
void
Core::addAttachment( const KURL &url, const QString &comment )
{
}
void
Core::setBody( const QString &body )
{
m_currentEditor->setText( body );
}
void
Core::addAttachment( const QString &name,
const QCString &cte,
const QByteArray &data,
const QCString &type,
const QCString &subType,
const QCString ¶mAttr,
const QString ¶mValue,
const QCString &contDisp )
{
}
#include "core.moc"
<|endoftext|>
|
<commit_before>#include "Solver.h"
#include "defines.h"
namespace sqaod {
/* name string for float/double */
template<class real> const char *typeString();
template<> const char *typeString<float>() { return "float"; }
template<> const char *typeString<double>() { return "double"; }
}
using namespace sqaod;
template<class real>
void Solver<real>::setPreferences(const Preferences &prefs) {
for (Preferences::const_iterator it = prefs.begin();
it != prefs.end(); ++it) {
setPreference(*it);
}
}
/* solver state */
template<class real>
void Solver<real>::setState(SolverState state) {
solverState_ |= state;
}
template<class real>
void Solver<real>::clearState(SolverState state) {
solverState_ &= ~state;
}
template<class real>
bool Solver<real>::isRandSeedGiven() const {
return bool(solverState_ & solRandSeedGiven);
}
template<class real>
bool Solver<real>::isProblemSet() const {
return bool(solverState_ & solProblemSet);
}
template<class real>
bool Solver<real>::isInitialized() const {
return bool(solverState_ & solInitialized);
}
template<class real>
bool Solver<real>::isQSet() const {
return bool(solverState_ & solQSet);
}
template<class real>
void Solver<real>::throwErrorIfProblemNotSet() const {
throwErrorIf(!isProblemSet(), "Problem is not set.");
}
template<class real>
void Solver<real>::throwErrorIfNotInitialized() const {
throwErrorIfProblemNotSet();
throwErrorIf(!isInitialized(),
"not initialized, call initAnneal() or initSearch() in advance.");
}
template<class real>
void Solver<real>::throwErrorIfQNotSet() const {
throwErrorIf(!isQSet(),
"Bits(x or q) not initialized. Plase set or randomize in advance.");
}
template<class real>
void Solver<real>::throwErrorIfSolutionNotAvailable() const {
throwErrorIf(!(solverState_ & solSolutionAvailable),
"Bits(x or q) not initialized. Plase set or randomize in advance.");
}
template<class real>
Algorithm BFSearcher<real>::selectAlgorithm(Algorithm algo) {
return algoBruteForceSearch;
}
template<class real>
Algorithm BFSearcher<real>::getAlgorithm() const {
return algoBruteForceSearch;
}
template<class real>
Preferences Annealer<real>::getPreferences() const {
Preferences prefs;
prefs.pushBack(Preference(pnAlgorithm, this->getAlgorithm()));
prefs.pushBack(Preference(pnNumTrotters, m_));
prefs.pushBack(Preference(pnPrecision, typeString<real>()));
return prefs;
}
template<class real>
void Annealer<real>::setPreference(const Preference &pref) {
if (pref.name == pnNumTrotters) {
throwErrorIf(pref.nTrotters <= 0, "# trotters must be a positive integer.");
if (this->m_ != pref.nTrotters)
Solver<real>::clearState(Solver<real>::solInitialized);
this->m_ = pref.nTrotters;
}
}
template<class real>
void DenseGraphSolver<real>::getProblemSize(SizeType *N) const {
*N = N_;
}
template<class real>
void BipartiteGraphSolver<real>::getProblemSize(SizeType *N0, SizeType *N1) const {
*N0 = N0_;
*N1 = N1_;
}
template<class real>
Preferences DenseGraphBFSearcher<real>::getPreferences() const {
Preferences prefs;
prefs.pushBack(Preference(pnAlgorithm, this->getAlgorithm()));
prefs.pushBack(Preference(pnTileSize, tileSize_));
prefs.pushBack(Preference(pnPrecision, typeString<real>()));
return prefs;
}
template<class real>
void DenseGraphBFSearcher<real>::setPreference(const Preference &pref) {
if (pref.name == pnTileSize) {
throwErrorIf(pref.tileSize <= 0, "tileSize must be a positive integer.");
tileSize_ = pref.tileSize;
}
}
template<class real>
void DenseGraphBFSearcher<real>::search() {
this->initSearch();
PackedBits xStep = std::min(PackedBits(tileSize_), xMax_);
for (PackedBits xTile = 0; xTile < xMax_; xTile += xStep)
searchRange(xTile, xTile + xStep);
this->finSearch();
}
template<class real>
Preferences BipartiteGraphBFSearcher<real>::getPreferences() const {
Preferences prefs;
prefs.pushBack(Preference(pnAlgorithm, algoBruteForceSearch));
prefs.pushBack(Preference(pnTileSize0, tileSize0_));
prefs.pushBack(Preference(pnTileSize1, tileSize1_));
return prefs;
}
template<class real>
void BipartiteGraphBFSearcher<real>::setPreference(const Preference &pref) {
if (pref.name == pnTileSize0) {
throwErrorIf(pref.tileSize <= 0, "tileSize0 must be a positive integer.");
tileSize0_ = pref.tileSize;
}
if (pref.name == pnTileSize1) {
throwErrorIf(pref.tileSize <= 0, "tileSize1 must be a positive integer.");
tileSize1_ = pref.tileSize;
}
}
template<class real>
void BipartiteGraphBFSearcher<real>::search() {
this->initSearch();
PackedBits xStep0 = std::min((PackedBits)tileSize0_, x0max_);
PackedBits xStep1 = std::min((PackedBits)tileSize1_, x1max_);
for (PackedBits xTile1 = 0; xTile1 < x1max_; xTile1 += xStep1) {
for (PackedBits xTile0 = 0; xTile0 < x0max_; xTile0 += xStep0) {
searchRange(xTile0, xTile0 + xStep0, xTile1, xTile1 + xStep1);
}
}
this->finSearch();
}
/* explicit instantiation */
template struct sqaod::Solver<double>;
template struct sqaod::Solver<float>;
template struct sqaod::BFSearcher<double>;
template struct sqaod::BFSearcher<float>;
template struct sqaod::Annealer<double>;
template struct sqaod::Annealer<float>;
template struct sqaod::DenseGraphSolver<double>;
template struct sqaod::DenseGraphSolver<float>;
template struct sqaod::BipartiteGraphSolver<double>;
template struct sqaod::BipartiteGraphSolver<float>;
template struct sqaod::DenseGraphBFSearcher<double>;
template struct sqaod::DenseGraphBFSearcher<float>;
template struct sqaod::DenseGraphAnnealer<double>;
template struct sqaod::DenseGraphAnnealer<float>;
template struct sqaod::BipartiteGraphBFSearcher<double>;
template struct sqaod::BipartiteGraphBFSearcher<float>;
template struct sqaod::BipartiteGraphAnnealer<double>;
template struct sqaod::BipartiteGraphAnnealer<float>;
<commit_msg>Removing redundant 'this->'.<commit_after>#include "Solver.h"
#include "defines.h"
namespace sqaod {
/* name string for float/double */
template<class real> const char *typeString();
template<> const char *typeString<float>() { return "float"; }
template<> const char *typeString<double>() { return "double"; }
}
using namespace sqaod;
template<class real>
void Solver<real>::setPreferences(const Preferences &prefs) {
for (Preferences::const_iterator it = prefs.begin();
it != prefs.end(); ++it) {
setPreference(*it);
}
}
/* solver state */
template<class real>
void Solver<real>::setState(SolverState state) {
solverState_ |= state;
}
template<class real>
void Solver<real>::clearState(SolverState state) {
solverState_ &= ~state;
}
template<class real>
bool Solver<real>::isRandSeedGiven() const {
return bool(solverState_ & solRandSeedGiven);
}
template<class real>
bool Solver<real>::isProblemSet() const {
return bool(solverState_ & solProblemSet);
}
template<class real>
bool Solver<real>::isInitialized() const {
return bool(solverState_ & solInitialized);
}
template<class real>
bool Solver<real>::isQSet() const {
return bool(solverState_ & solQSet);
}
template<class real>
void Solver<real>::throwErrorIfProblemNotSet() const {
throwErrorIf(!isProblemSet(), "Problem is not set.");
}
template<class real>
void Solver<real>::throwErrorIfNotInitialized() const {
throwErrorIfProblemNotSet();
throwErrorIf(!isInitialized(),
"not initialized, call initAnneal() or initSearch() in advance.");
}
template<class real>
void Solver<real>::throwErrorIfQNotSet() const {
throwErrorIf(!isQSet(),
"Bits(x or q) not initialized. Plase set or randomize in advance.");
}
template<class real>
void Solver<real>::throwErrorIfSolutionNotAvailable() const {
throwErrorIf(!(solverState_ & solSolutionAvailable),
"Bits(x or q) not initialized. Plase set or randomize in advance.");
}
template<class real>
Algorithm BFSearcher<real>::selectAlgorithm(Algorithm algo) {
return algoBruteForceSearch;
}
template<class real>
Algorithm BFSearcher<real>::getAlgorithm() const {
return algoBruteForceSearch;
}
template<class real>
Preferences Annealer<real>::getPreferences() const {
Preferences prefs;
prefs.pushBack(Preference(pnAlgorithm, this->getAlgorithm()));
prefs.pushBack(Preference(pnNumTrotters, m_));
prefs.pushBack(Preference(pnPrecision, typeString<real>()));
return prefs;
}
template<class real>
void Annealer<real>::setPreference(const Preference &pref) {
if (pref.name == pnNumTrotters) {
throwErrorIf(pref.nTrotters <= 0, "# trotters must be a positive integer.");
if (m_ != pref.nTrotters)
Solver<real>::clearState(Solver<real>::solInitialized);
m_ = pref.nTrotters;
}
}
template<class real>
void DenseGraphSolver<real>::getProblemSize(SizeType *N) const {
*N = N_;
}
template<class real>
void BipartiteGraphSolver<real>::getProblemSize(SizeType *N0, SizeType *N1) const {
*N0 = N0_;
*N1 = N1_;
}
template<class real>
Preferences DenseGraphBFSearcher<real>::getPreferences() const {
Preferences prefs;
prefs.pushBack(Preference(pnAlgorithm, this->getAlgorithm()));
prefs.pushBack(Preference(pnTileSize, tileSize_));
prefs.pushBack(Preference(pnPrecision, typeString<real>()));
return prefs;
}
template<class real>
void DenseGraphBFSearcher<real>::setPreference(const Preference &pref) {
if (pref.name == pnTileSize) {
throwErrorIf(pref.tileSize <= 0, "tileSize must be a positive integer.");
tileSize_ = pref.tileSize;
}
}
template<class real>
void DenseGraphBFSearcher<real>::search() {
this->initSearch();
PackedBits xStep = std::min(PackedBits(tileSize_), xMax_);
for (PackedBits xTile = 0; xTile < xMax_; xTile += xStep)
searchRange(xTile, xTile + xStep);
this->finSearch();
}
template<class real>
Preferences BipartiteGraphBFSearcher<real>::getPreferences() const {
Preferences prefs;
prefs.pushBack(Preference(pnAlgorithm, algoBruteForceSearch));
prefs.pushBack(Preference(pnTileSize0, tileSize0_));
prefs.pushBack(Preference(pnTileSize1, tileSize1_));
return prefs;
}
template<class real>
void BipartiteGraphBFSearcher<real>::setPreference(const Preference &pref) {
if (pref.name == pnTileSize0) {
throwErrorIf(pref.tileSize <= 0, "tileSize0 must be a positive integer.");
tileSize0_ = pref.tileSize;
}
if (pref.name == pnTileSize1) {
throwErrorIf(pref.tileSize <= 0, "tileSize1 must be a positive integer.");
tileSize1_ = pref.tileSize;
}
}
template<class real>
void BipartiteGraphBFSearcher<real>::search() {
this->initSearch();
PackedBits xStep0 = std::min((PackedBits)tileSize0_, x0max_);
PackedBits xStep1 = std::min((PackedBits)tileSize1_, x1max_);
for (PackedBits xTile1 = 0; xTile1 < x1max_; xTile1 += xStep1) {
for (PackedBits xTile0 = 0; xTile0 < x0max_; xTile0 += xStep0) {
searchRange(xTile0, xTile0 + xStep0, xTile1, xTile1 + xStep1);
}
}
this->finSearch();
}
/* explicit instantiation */
template struct sqaod::Solver<double>;
template struct sqaod::Solver<float>;
template struct sqaod::BFSearcher<double>;
template struct sqaod::BFSearcher<float>;
template struct sqaod::Annealer<double>;
template struct sqaod::Annealer<float>;
template struct sqaod::DenseGraphSolver<double>;
template struct sqaod::DenseGraphSolver<float>;
template struct sqaod::BipartiteGraphSolver<double>;
template struct sqaod::BipartiteGraphSolver<float>;
template struct sqaod::DenseGraphBFSearcher<double>;
template struct sqaod::DenseGraphBFSearcher<float>;
template struct sqaod::DenseGraphAnnealer<double>;
template struct sqaod::DenseGraphAnnealer<float>;
template struct sqaod::BipartiteGraphBFSearcher<double>;
template struct sqaod::BipartiteGraphBFSearcher<float>;
template struct sqaod::BipartiteGraphAnnealer<double>;
template struct sqaod::BipartiteGraphAnnealer<float>;
<|endoftext|>
|
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "DebugOperatorNew.h"
#include "Application.h"
#include "Framework.h"
#include "LoggingFunctions.h"
#include <QDir>
#ifdef _WIN32
#include <WinSock2.h>
#include <Windows.h>
#endif
#ifdef WINDOWS_APP
#include <io.h>
#include <iostream>
#include <fcntl.h>
#include <conio.h>
#endif
#if defined(_MSC_VER) && defined(MEMORY_LEAK_CHECK)
// for reporting memory leaks upon debug exit
#include <crtdbg.h>
#endif
#if defined(_MSC_VER) && defined(_DMEMDUMP)
// For generating minidump
#include <dbghelp.h>
#include <shellapi.h>
#include <shlobj.h>
#pragma warning(push)
#pragma warning(disable : 4996)
#include <strsafe.h>
#pragma warning(pop)
#endif
#include "MemoryLeakCheck.h"
int run(int argc, char **argv);
#if defined(_MSC_VER) && defined(_DMEMDUMP)
int generate_dump(EXCEPTION_POINTERS* pExceptionPointers);
#endif
int main(int argc, char **argv)
{
int return_value = EXIT_SUCCESS;
// set up a debug flag for memory leaks. Output the results to file when the app exits.
// Note that this file is written to the same directory where the executable resides,
// so you can only use this in a development version where you have write access to
// that directory.
#if defined(_MSC_VER) && defined(MEMORY_LEAK_CHECK) && defined(_DEBUG)
int tmpDbgFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF;
_CrtSetDbgFlag(tmpDbgFlag);
HANDLE hLogFile = CreateFileW(L"fullmemoryleaklog.txt", GENERIC_WRITE,
FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
#endif
#if defined(_MSC_VER) && defined(_DMEMDUMP)
__try
{
#endif
return_value = run(argc, argv);
#if defined(_MSC_VER) && defined(_DMEMDUMP)
}
__except(generate_dump(GetExceptionInformation()))
{
}
#endif
#if defined(_MSC_VER) && defined(MEMORY_LEAK_CHECK) && defined(_DEBUG)
if (hLogFile != INVALID_HANDLE_VALUE)
{
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, hLogFile);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ERROR, hLogFile);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ASSERT, hLogFile);
}
#endif
// Note: We cannot close the file handle manually here. Have to let the OS close it
// after it has printed out the list of leaks to the file.
//CloseHandle(hLogFile);
return return_value;
}
int run(int argc, char **argv)
{
int return_value = EXIT_SUCCESS;
// Initilizing prints
LogInfo("Starting up Tundra");
LogInfo("* Working directory: " + QDir::currentPath());
// Parse and print command arguments
QStringList arguments;
for(int i = 1; i < argc; ++i)
arguments << argv[i];
QString fullArguments = arguments.join(" ");
if (fullArguments.contains("--"))
{
LogInfo("* Command arguments:");
int iStart = fullArguments.indexOf("--");
while (iStart != -1)
{
int iStop = fullArguments.indexOf("--", iStart+1);
QString subStr = fullArguments.mid(iStart, iStop-iStart);
if (!subStr.isEmpty() && !subStr.isNull())
{
LogInfo(" " + subStr);
iStart = fullArguments.indexOf("--", iStart+1);
}
else
iStart = -1;
}
}
LogInfo(""); // endl
// Create application object
#if !defined(_DEBUG) || !defined (_MSC_VER)
try
#endif
{
Framework* fw = new Framework(argc, argv);
fw->Go();
delete fw;
}
#if !defined(_DEBUG) || !defined (_MSC_VER)
catch(std::exception& e)
{
Application::Message("An exception has occurred!", e.what());
#if defined(_DEBUG)
throw;
#else
return_value = EXIT_FAILURE;
#endif
}
#endif
return return_value;
}
#if defined(_MSC_VER) && defined(WINDOWS_APP)
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
// Parse Windows command line
std::vector<std::string> arguments;
std::string cmdLine(lpCmdLine);
unsigned i;
unsigned cmdStart = 0;
unsigned cmdEnd = 0;
bool cmd = false;
bool quote = false;
if (cmdLine.find("--headless") != std::string::npos)
{
// Code below apapted from http://www.programmingforums.org/post163691-12.html
BOOL ret = AllocConsole();
if (!ret)
return EXIT_FAILURE;
// Prepare input
long hIn =(long)GetStdHandle(STD_INPUT_HANDLE);
int hCrt = _open_osfhandle(hIn, _O_TEXT);
FILE *hf = _fdopen(hCrt, "r+");
setvbuf(hf,0,_IONBF,0);
*stdin = *hf;
// Prepare output
long hOut =(long)GetStdHandle(STD_OUTPUT_HANDLE);
hCrt = _open_osfhandle(hOut, _O_TEXT);
hf = _fdopen(hCrt, "w+");
setvbuf(hf, 0, _IONBF, 0);
*stdout = *hf;
printf("Trying to start Tundra as Windows GUI application in headless mode: console window created.\n");
}
for(i = 0; i < cmdLine.length(); ++i)
{
if (cmdLine[i] == '\"')
quote = !quote;
if ((cmdLine[i] == ' ') && (!quote))
{
if (cmd)
{
cmd = false;
cmdEnd = i;
arguments.push_back(cmdLine.substr(cmdStart, cmdEnd-cmdStart));
}
}
else
{
if (!cmd)
{
cmd = true;
cmdStart = i;
}
}
}
if (cmd)
arguments.push_back(cmdLine.substr(cmdStart, i-cmdStart));
std::vector<const char*> argv;
for(size_t i = 0; i < arguments.size(); ++i)
argv.push_back(arguments[i].c_str());
if (argv.size())
return main(argv.size(), (char**)&argv[0]);
else
return main(0, 0);
}
#endif
#if defined(_MSC_VER) && defined(_DMEMDUMP)
int generate_dump(EXCEPTION_POINTERS* pExceptionPointers)
{
// Add a hardcoded check to guarantee we only write a dump file of the first crash exception that is received.
// Sometimes a crash is so bad that writing the dump below causes another exception to occur, in which case
// this function would be recursively called, spawning tons of error dialogs to the user.
static bool dumpGenerated = false;
if (dumpGenerated)
{
printf("WARNING: Not generating another dump, one has been generated already!\n");
return 0;
}
dumpGenerated = true;
BOOL bMiniDumpSuccessful;
WCHAR szPath[MAX_PATH];
WCHAR szFileName[MAX_PATH];
// Can't use Application for application name and version,
// since it might have not been initialized yet, or it might have caused
// the exception in the first place
WCHAR* szAppName = L"realXtend";
WCHAR* szVersion = L"Tundra_v2.0";
DWORD dwBufferSize = MAX_PATH;
HANDLE hDumpFile;
SYSTEMTIME stLocalTime;
MINIDUMP_EXCEPTION_INFORMATION ExpParam;
GetLocalTime( &stLocalTime );
GetTempPathW( dwBufferSize, szPath );
StringCchPrintf( szFileName, MAX_PATH, L"%s%s", szPath, szAppName );
CreateDirectoryW( szFileName, 0 );
StringCchPrintf( szFileName, MAX_PATH, L"%s%s\\%s-%04d%02d%02d-%02d%02d%02d-%ld-%ld.dmp",
szPath, szAppName, szVersion,
stLocalTime.wYear, stLocalTime.wMonth, stLocalTime.wDay,
stLocalTime.wHour, stLocalTime.wMinute, stLocalTime.wSecond,
GetCurrentProcessId(), GetCurrentThreadId());
hDumpFile = CreateFileW(szFileName, GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_WRITE|FILE_SHARE_READ, 0, CREATE_ALWAYS, 0, 0);
ExpParam.ThreadId = GetCurrentThreadId();
ExpParam.ExceptionPointers = pExceptionPointers;
ExpParam.ClientPointers = TRUE;
bMiniDumpSuccessful = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(),
hDumpFile, MiniDumpWithDataSegs, &ExpParam, 0, 0);
std::wstring message(L"Program ");
message += szAppName;
message += L" encountered an unexpected error.\n\nCrashdump was saved to location:\n";
message += szFileName;
if (bMiniDumpSuccessful)
Application::Message(L"Minidump generated!", message);
else
Application::Message(szAppName, L"Unexpected error was encountered while generating minidump!");
return EXCEPTION_EXECUTE_HANDLER;
}
#endif
<commit_msg>Small adjustments to the the console creation when running Windows GUI app in headless mode.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "DebugOperatorNew.h"
#include "Application.h"
#include "Framework.h"
#include "LoggingFunctions.h"
#include <QDir>
#ifdef _WIN32
#include <WinSock2.h>
#include <Windows.h>
#endif
#ifdef WINDOWS_APP
#include <io.h>
#include <iostream>
#include <fcntl.h>
#include <conio.h>
#endif
#if defined(_MSC_VER) && defined(MEMORY_LEAK_CHECK)
// for reporting memory leaks upon debug exit
#include <crtdbg.h>
#endif
#if defined(_MSC_VER) && defined(_DMEMDUMP)
// For generating minidump
#include <dbghelp.h>
#include <shellapi.h>
#include <shlobj.h>
#pragma warning(push)
#pragma warning(disable : 4996)
#include <strsafe.h>
#pragma warning(pop)
#endif
#include "MemoryLeakCheck.h"
int run(int argc, char **argv);
#if defined(_MSC_VER) && defined(_DMEMDUMP)
int generate_dump(EXCEPTION_POINTERS* pExceptionPointers);
#endif
int main(int argc, char **argv)
{
int return_value = EXIT_SUCCESS;
// set up a debug flag for memory leaks. Output the results to file when the app exits.
// Note that this file is written to the same directory where the executable resides,
// so you can only use this in a development version where you have write access to
// that directory.
#if defined(_MSC_VER) && defined(MEMORY_LEAK_CHECK) && defined(_DEBUG)
int tmpDbgFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF;
_CrtSetDbgFlag(tmpDbgFlag);
HANDLE hLogFile = CreateFileW(L"fullmemoryleaklog.txt", GENERIC_WRITE,
FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
#endif
#if defined(_MSC_VER) && defined(_DMEMDUMP)
__try
{
#endif
return_value = run(argc, argv);
#if defined(_MSC_VER) && defined(_DMEMDUMP)
}
__except(generate_dump(GetExceptionInformation()))
{
}
#endif
#if defined(_MSC_VER) && defined(MEMORY_LEAK_CHECK) && defined(_DEBUG)
if (hLogFile != INVALID_HANDLE_VALUE)
{
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, hLogFile);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ERROR, hLogFile);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ASSERT, hLogFile);
}
#endif
// Note: We cannot close the file handle manually here. Have to let the OS close it
// after it has printed out the list of leaks to the file.
//CloseHandle(hLogFile);
return return_value;
}
int run(int argc, char **argv)
{
int return_value = EXIT_SUCCESS;
// Initilizing prints
LogInfo("Starting up Tundra");
LogInfo("* Working directory: " + QDir::currentPath());
// Parse and print command arguments
QStringList arguments;
for(int i = 1; i < argc; ++i)
arguments << argv[i];
QString fullArguments = arguments.join(" ");
if (fullArguments.contains("--"))
{
LogInfo("* Command arguments:");
int iStart = fullArguments.indexOf("--");
while (iStart != -1)
{
int iStop = fullArguments.indexOf("--", iStart+1);
QString subStr = fullArguments.mid(iStart, iStop-iStart);
if (!subStr.isEmpty() && !subStr.isNull())
{
LogInfo(" " + subStr);
iStart = fullArguments.indexOf("--", iStart+1);
}
else
iStart = -1;
}
}
LogInfo(""); // endl
// Create application object
#if !defined(_DEBUG) || !defined (_MSC_VER)
try
#endif
{
Framework* fw = new Framework(argc, argv);
fw->Go();
delete fw;
}
#if !defined(_DEBUG) || !defined (_MSC_VER)
catch(std::exception& e)
{
Application::Message("An exception has occurred!", e.what());
#if defined(_DEBUG)
throw;
#else
return_value = EXIT_FAILURE;
#endif
}
#endif
return return_value;
}
#if defined(_MSC_VER) && defined(WINDOWS_APP)
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
std::string cmdLine(lpCmdLine);
// If trying to run Windows GUI application in headless mode, we must set up the console in order to be able to proceed.
if (cmdLine.find("--headless") != std::string::npos)
{
// Code below adapted from http://dslweb.nwnexus.com/~ast/dload/guicon.htm
BOOL ret = AllocConsole();
if (!ret)
return EXIT_FAILURE;
// Prepare stdin, stdout and stderr.
long hStd =(long)GetStdHandle(STD_INPUT_HANDLE);
int hCrt = _open_osfhandle(hStd, _O_TEXT);
FILE *hf = _fdopen(hCrt, "r+");
setvbuf(hf,0,_IONBF,0);
*stdin = *hf;
hStd =(long)GetStdHandle(STD_OUTPUT_HANDLE);
hCrt = _open_osfhandle(hStd, _O_TEXT);
hf = _fdopen(hCrt, "w+");
setvbuf(hf, 0, _IONBF, 0);
*stdout = *hf;
hStd =(long)GetStdHandle(STD_ERROR_HANDLE);
hCrt = _open_osfhandle(hStd, _O_TEXT);
hf = _fdopen(hCrt, "w+");
setvbuf(hf, 0, _IONBF, 0);
*stderr = *hf;
// Make C++ IO streams cout, wcout, cin, wcin, wcerr, cerr, wclog and clog point to console as well.
std::ios::sync_with_stdio();
printf("Tried to start Tundra as a Windows GUI application in headless mode: console window created.\n");
}
// Parse the Windows command line.
std::vector<std::string> arguments;
unsigned i;
unsigned cmdStart = 0;
unsigned cmdEnd = 0;
bool cmd = false;
bool quote = false;
for(i = 0; i < cmdLine.length(); ++i)
{
if (cmdLine[i] == '\"')
quote = !quote;
if ((cmdLine[i] == ' ') && (!quote))
{
if (cmd)
{
cmd = false;
cmdEnd = i;
arguments.push_back(cmdLine.substr(cmdStart, cmdEnd-cmdStart));
}
}
else
{
if (!cmd)
{
cmd = true;
cmdStart = i;
}
}
}
if (cmd)
arguments.push_back(cmdLine.substr(cmdStart, i-cmdStart));
std::vector<const char*> argv;
for(size_t i = 0; i < arguments.size(); ++i)
argv.push_back(arguments[i].c_str());
if (argv.size())
return main(argv.size(), (char**)&argv[0]);
else
return main(0, 0);
}
#endif
#if defined(_MSC_VER) && defined(_DMEMDUMP)
int generate_dump(EXCEPTION_POINTERS* pExceptionPointers)
{
// Add a hardcoded check to guarantee we only write a dump file of the first crash exception that is received.
// Sometimes a crash is so bad that writing the dump below causes another exception to occur, in which case
// this function would be recursively called, spawning tons of error dialogs to the user.
static bool dumpGenerated = false;
if (dumpGenerated)
{
printf("WARNING: Not generating another dump, one has been generated already!\n");
return 0;
}
dumpGenerated = true;
BOOL bMiniDumpSuccessful;
WCHAR szPath[MAX_PATH];
WCHAR szFileName[MAX_PATH];
// Can't use Application for application name and version,
// since it might have not been initialized yet, or it might have caused
// the exception in the first place
WCHAR* szAppName = L"realXtend";
WCHAR* szVersion = L"Tundra_v2.0";
DWORD dwBufferSize = MAX_PATH;
HANDLE hDumpFile;
SYSTEMTIME stLocalTime;
MINIDUMP_EXCEPTION_INFORMATION ExpParam;
GetLocalTime( &stLocalTime );
GetTempPathW( dwBufferSize, szPath );
StringCchPrintf( szFileName, MAX_PATH, L"%s%s", szPath, szAppName );
CreateDirectoryW( szFileName, 0 );
StringCchPrintf( szFileName, MAX_PATH, L"%s%s\\%s-%04d%02d%02d-%02d%02d%02d-%ld-%ld.dmp",
szPath, szAppName, szVersion,
stLocalTime.wYear, stLocalTime.wMonth, stLocalTime.wDay,
stLocalTime.wHour, stLocalTime.wMinute, stLocalTime.wSecond,
GetCurrentProcessId(), GetCurrentThreadId());
hDumpFile = CreateFileW(szFileName, GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_WRITE|FILE_SHARE_READ, 0, CREATE_ALWAYS, 0, 0);
ExpParam.ThreadId = GetCurrentThreadId();
ExpParam.ExceptionPointers = pExceptionPointers;
ExpParam.ClientPointers = TRUE;
bMiniDumpSuccessful = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(),
hDumpFile, MiniDumpWithDataSegs, &ExpParam, 0, 0);
std::wstring message(L"Program ");
message += szAppName;
message += L" encountered an unexpected error.\n\nCrashdump was saved to location:\n";
message += szFileName;
if (bMiniDumpSuccessful)
Application::Message(L"Minidump generated!", message);
else
Application::Message(szAppName, L"Unexpected error was encountered while generating minidump!");
return EXCEPTION_EXECUTE_HANDLER;
}
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (c) MZ3 Project Team All rights reserved.
* Code licensed under the BSD License:
* http://www.mz3.jp/license.txt
*/
#include "stdafx.h"
#include "MZ3.h"
#include "Mz3GroupData.h"
#include "util_base.h"
#include "util_mz3.h"
#include "inifile.h"
/**
* gbvy[Wp̏
*
* O[vXgƂ̔z̃Xg̐B
*/
bool Mz3GroupData::initForTopPage(AccessTypeInfo& accessTypeInfo, const InitializeType initType)
{
this->groups.clear();
this->services = initType.strSelectedServices;
// T[rX̏ꍇ͑SIƂ݂ȂST[rXlj
if (this->services.empty()) {
for (size_t idx=0; idx<theApp.m_luaServices.size(); idx++) {
this->services += " ";
this->services += theApp.m_luaServices[idx].name;
}
}
// CxgnȟĂяo
util::CallMZ3ScriptHookFunctions("", "creating_default_group", this);
return true;
}
/**
* group ɃJeSljB
*
* category_url NULL ܂͋̏ꍇ́AJeSʂɉftHgURLw肷B
* JeSʂɉJ^Cvw肷B
*/
bool Mz3GroupData::appendCategoryByIniData(
AccessTypeInfo& accessTypeInfo,
CGroupItem& group, const std::string& category_name, ACCESS_TYPE category_type, const char* category_url, bool bCruise )
{
// ftHgURLicategory_url w̏ꍇɗpURLj
LPCTSTR default_category_url = accessTypeInfo.getDefaultCategoryURL(category_type);
AccessTypeInfo::BODY_INDICATE_TYPE colType1 = accessTypeInfo.getBodyHeaderCol1Type(category_type);
AccessTypeInfo::BODY_INDICATE_TYPE colType2 = accessTypeInfo.getBodyHeaderCol2Type(category_type);
AccessTypeInfo::BODY_INDICATE_TYPE colType3 = accessTypeInfo.getBodyHeaderCol3Type(category_type);
if (colType1==AccessTypeInfo::BODY_INDICATE_TYPE_NONE ||
colType2==AccessTypeInfo::BODY_INDICATE_TYPE_NONE)
{
// T|[gÔߒljI
// MZ3LOGGER_ERROR(L"T|[gÔߒlj܂B");
return false;
}
// ANZXʕɔڍs
switch( category_type ) {
case ACCESS_LIST_FAVORITE_USER:
// Cɓ胆[U
if (category_url != NULL && strstr(category_url, "kind=community")!=NULL) {
// uCɓR~vƂď
category_type = ACCESS_LIST_FAVORITE_COMMUNITY;
}
break;
}
// URL w肳Ă URL pB
CString url = default_category_url;
if( category_url!=NULL && strlen(category_url) > 0 ) {
// `init@C̈ڍs
if (category_type == ACCESS_LIST_FOOTSTEP &&
strcmp(category_url, "show_log.pl")==0)
{
// URLAPIpURLɒu
} else if (category_type == ACCESS_LIST_FRIEND &&
strcmp(category_url, "list_friend.pl")==0)
{
// }C~NꗗURLAPIpURLɒu
} else {
url = util::my_mbstowcs(category_url).c_str();
}
}
static CCategoryItem item;
item.init(
util::my_mbstowcs(category_name).c_str(),
url,
category_type,
group.categories.size(),
colType1, colType2, colType3 );
item.m_bCruise = bCruise;
group.categories.push_back( item );
return true;
}
/**
* L̃}bvB
*
* JeSʕ JeS
*/
void Mz3GroupDataInifileHelper::InitMap(AccessTypeInfo& accessTypeInfo) {
category_string2type.RemoveAll();
category_string2type.InitHashTable( 20 );
// AccessTypeInfo ̃VACYL[enbVe[u\z
AccessTypeInfo::ACCESS_TYPE_TO_DATA_MAP::iterator it;
for (it=accessTypeInfo.m_map.begin(); it!=accessTypeInfo.m_map.end(); it++) {
ACCESS_TYPE accessType = it->first;
AccessTypeInfo::Data& data = it->second;
switch (data.infoType) {
case AccessTypeInfo::INFO_TYPE_CATEGORY:
// category_string2type ̍\z
if (!data.serializeKey.empty()) {
category_string2type[ util::my_mbstowcs(data.serializeKey.c_str()).c_str() ] = accessType;
}
break;
default:
// nothing to do.
break;
}
}
}
/**
* ini t@CiO[v`t@Cj Mz3GroupData B
*/
bool Mz3GroupDataReader::load( AccessTypeInfo& accessTypeInfo, Mz3GroupData& target, const CString& inifilename )
{
target.groups.clear();
inifile::IniFile inifile;
Mz3GroupDataInifileHelper helper(accessTypeInfo);
// O[v`t@C̃[h
if(! inifile.Load( inifilename ) ) {
return false;
}
// \[gς݃ZNVXg擾
std::vector<std::string> group_section_names;
{
// ZNVꗗ擾B
group_section_names = inifile.GetSectionNames();
// ZNVꗗ̂uGroupvŎn܂̂𒊏oB
for( size_t i=0; i<group_section_names.size(); ) {
if( strncmp( group_section_names[i].c_str(), "Group", 5 ) != 0 ) {
// uGroupvŎn܂Ȃ̂ŏB
group_section_names.erase( group_section_names.begin()+i );
}else{
i++;
}
}
// \[g
sort( group_section_names.begin(), group_section_names.end() );
}
// eZNVɑĒljs
for( size_t i=0; i<group_section_names.size(); i++ ) {
const char* section_name = group_section_names[i].c_str();
// "Name" ̒l擾AO[vƂB
std::string group_name = inifile.GetValue( "Name", section_name );
if( group_name.empty() ) {
continue;
}
// "Type" ̒l擾AO[vʂƂB
// O[v̎ʂ͔p~BS GROUP_GENERAL ƂB
ACCESS_TYPE group_type = ACCESS_GROUP_GENERAL;
// "Url" ̒l擾AURLƂB
std::string url = inifile.GetValue( "Url", section_name );
// O[v쐬
CGroupItem group;
group.init( util::my_mbstowcs(group_name).c_str(), util::my_mbstowcs(url).c_str(), group_type );
// "CategoryXX" ̒l擾ABXX [01,30] ƂB
for( int j=0; j<30; j++ ) {
CStringA key;
key.Format( "Category%02d", j+1 );
// "CategoryXX" ̒l݂ȂΏIB
if(! inifile.RecordExists( (const char*)key, section_name ) ) {
break;
}
// "CategoryXX" ̒l擾B
std::string value = inifile.GetValue( (const char*)key, section_name );
// J}ŕXgB
std::vector<std::string> values;
util::split_by_comma( values, value );
if( values.size() < 2 ) {
continue;
}
// Xg̑1vfJeSƂB
std::string& category_name = values[0];
// Xg̑2vfJeSʂƂB
// JeSʖJeSʕϊsB
ACCESS_TYPE category_type = helper.CategoryString2Type( util::my_mbstowcs(values[1]).c_str() );
if( category_type == ACCESS_INVALID ) {
continue;
}
// Xg̑3vfURLƂB
// ݂Ȃꍇ̓JeSʂ̃ftHglpB
const char* category_url = NULL;
if( values.size() >= 3 ) {
category_url = values[2].c_str();
}
// Xg̑4vftOƂB
// ݂Ȃꍇ͏ȂƂB
bool bCruise = false;
if( values.size() >= 4 ) {
bCruise = atoi(values[3].c_str()) != 0 ? true : false;
}
// JeSljB
target.appendCategoryByIniData( accessTypeInfo, group, category_name, category_type, category_url, bCruise );
}
// JeSPȏȂAgroups ɒljB
if( group.categories.size() >= 1 ) {
target.groups.push_back( group );
}
}
// O[vvf[ȂIB
if( target.groups.empty() ) {
return false;
}
return true;
}
/**
* Mz3GroupData IuWFNg ini t@CiO[v`t@CjB
*/
bool Mz3GroupDataWriter::save( AccessTypeInfo& accessTypeInfo, const Mz3GroupData& target, const CString& inifilename )
{
inifile::IniFile inifile;
const int n = target.groups.size();
for( int i=0; i<n; i++ ) {
const CGroupItem& group = target.groups[i];
if (!group.bSaveToGroupFile) {
continue;
}
// ZNV
CStringA strSectionName;
strSectionName.Format( "Group%02d", i+1 );
// Name o
inifile.SetValue( L"Name", group.name, strSectionName );
// Type o( GROUP_GENERAL Ƃ)
inifile.SetValue( "Type", accessTypeInfo.getSerializeKey(ACCESS_GROUP_GENERAL), (LPCSTR)strSectionName );
// Url o
inifile.SetValue( L"Url", group.mixi.GetURL(), strSectionName );
// CategoryXX o
int nc = group.categories.size();
int categoryNumber = 1;
for( int j=0; j<nc; j++ ) {
// L[
CString key;
key.Format( L"Category%02d", categoryNumber );
// EӒl
// EӒl͏ɁAuJeŚvAuJeSʕvAuURLv
const CCategoryItem& item = group.categories[j];
CString categoryString = util::my_mbstowcs(accessTypeInfo.getSerializeKey(item.m_mixi.GetAccessType())).c_str();
if (categoryString.IsEmpty() || item.bSaveToGroupFile==false)
continue;
CString value;
value.Format( L"%s,%s,%s,%d",
item.m_name,
categoryString,
item.m_mixi.GetURL(),
item.m_bCruise ? 1 : 0
);
// o
inifile.SetValue( key, value, strSectionName );
categoryNumber ++;
}
}
// ۑ
return inifile.Save( inifilename, false );
}
<commit_msg>- Twitter のタイムラインを公式RTが表示できるAPIに変更(カテゴリのURL移行処理を含む)<commit_after>/*
* Copyright (c) MZ3 Project Team All rights reserved.
* Code licensed under the BSD License:
* http://www.mz3.jp/license.txt
*/
#include "stdafx.h"
#include "MZ3.h"
#include "Mz3GroupData.h"
#include "util_base.h"
#include "util_mz3.h"
#include "inifile.h"
/**
* gbvy[Wp̏
*
* O[vXgƂ̔z̃Xg̐B
*/
bool Mz3GroupData::initForTopPage(AccessTypeInfo& accessTypeInfo, const InitializeType initType)
{
this->groups.clear();
this->services = initType.strSelectedServices;
// T[rX̏ꍇ͑SIƂ݂ȂST[rXlj
if (this->services.empty()) {
for (size_t idx=0; idx<theApp.m_luaServices.size(); idx++) {
this->services += " ";
this->services += theApp.m_luaServices[idx].name;
}
}
// CxgnȟĂяo
util::CallMZ3ScriptHookFunctions("", "creating_default_group", this);
return true;
}
/**
* group ɃJeSljB
*
* category_url NULL ܂͋̏ꍇ́AJeSʂɉftHgURLw肷B
* JeSʂɉJ^Cvw肷B
*/
bool Mz3GroupData::appendCategoryByIniData(
AccessTypeInfo& accessTypeInfo,
CGroupItem& group, const std::string& category_name, ACCESS_TYPE category_type, const char* category_url, bool bCruise )
{
// ftHgURLicategory_url w̏ꍇɗpURLj
LPCTSTR default_category_url = accessTypeInfo.getDefaultCategoryURL(category_type);
AccessTypeInfo::BODY_INDICATE_TYPE colType1 = accessTypeInfo.getBodyHeaderCol1Type(category_type);
AccessTypeInfo::BODY_INDICATE_TYPE colType2 = accessTypeInfo.getBodyHeaderCol2Type(category_type);
AccessTypeInfo::BODY_INDICATE_TYPE colType3 = accessTypeInfo.getBodyHeaderCol3Type(category_type);
if (colType1==AccessTypeInfo::BODY_INDICATE_TYPE_NONE ||
colType2==AccessTypeInfo::BODY_INDICATE_TYPE_NONE)
{
// T|[gÔߒljI
// MZ3LOGGER_ERROR(L"T|[gÔߒlj܂B");
return false;
}
// ANZXʕɔڍs
switch( category_type ) {
case ACCESS_LIST_FAVORITE_USER:
// Cɓ胆[U
if (category_url != NULL && strstr(category_url, "kind=community")!=NULL) {
// uCɓR~vƂď
category_type = ACCESS_LIST_FAVORITE_COMMUNITY;
}
break;
}
// URL w肳Ă URL pB
CString url = default_category_url;
if( category_url!=NULL && strlen(category_url) > 0 ) {
// `init@C̈ڍs
if (category_type == ACCESS_LIST_FOOTSTEP && strcmp(category_url, "show_log.pl")==0) {
// URLAPIpURLɒu(ftHgURL̗p)
} else if (category_type == ACCESS_LIST_FRIEND && strcmp(category_url, "list_friend.pl")==0) {
// }C~NꗗURLAPIpURLɒu(ftHgURL̗p)
} else if (category_type == ACCESS_TWITTER_FRIENDS_TIMELINE &&
strstr(category_url, "http://twitter.com/statuses/friends_timeline.xml")!=NULL)
{
// friends_timeline.xml home_timeline.xml ɏ
CString strCategoryUrl(category_url);
strCategoryUrl.Replace(L"http://twitter.com/statuses/friends_timeline.xml",
L"http://twitter.com/statuses/home_timeline.xml");
url = strCategoryUrl;
} else {
// JeSURL̗p
url = util::my_mbstowcs(category_url).c_str();
}
}
static CCategoryItem item;
item.init(
util::my_mbstowcs(category_name).c_str(),
url,
category_type,
group.categories.size(),
colType1, colType2, colType3 );
item.m_bCruise = bCruise;
group.categories.push_back( item );
return true;
}
/**
* L̃}bvB
*
* JeSʕ JeS
*/
void Mz3GroupDataInifileHelper::InitMap(AccessTypeInfo& accessTypeInfo) {
category_string2type.RemoveAll();
category_string2type.InitHashTable( 20 );
// AccessTypeInfo ̃VACYL[enbVe[u\z
AccessTypeInfo::ACCESS_TYPE_TO_DATA_MAP::iterator it;
for (it=accessTypeInfo.m_map.begin(); it!=accessTypeInfo.m_map.end(); it++) {
ACCESS_TYPE accessType = it->first;
AccessTypeInfo::Data& data = it->second;
switch (data.infoType) {
case AccessTypeInfo::INFO_TYPE_CATEGORY:
// category_string2type ̍\z
if (!data.serializeKey.empty()) {
category_string2type[ util::my_mbstowcs(data.serializeKey.c_str()).c_str() ] = accessType;
}
break;
default:
// nothing to do.
break;
}
}
}
/**
* ini t@CiO[v`t@Cj Mz3GroupData B
*/
bool Mz3GroupDataReader::load( AccessTypeInfo& accessTypeInfo, Mz3GroupData& target, const CString& inifilename )
{
target.groups.clear();
inifile::IniFile inifile;
Mz3GroupDataInifileHelper helper(accessTypeInfo);
// O[v`t@C̃[h
if(! inifile.Load( inifilename ) ) {
return false;
}
// \[gς݃ZNVXg擾
std::vector<std::string> group_section_names;
{
// ZNVꗗ擾B
group_section_names = inifile.GetSectionNames();
// ZNVꗗ̂uGroupvŎn܂̂𒊏oB
for( size_t i=0; i<group_section_names.size(); ) {
if( strncmp( group_section_names[i].c_str(), "Group", 5 ) != 0 ) {
// uGroupvŎn܂Ȃ̂ŏB
group_section_names.erase( group_section_names.begin()+i );
}else{
i++;
}
}
// \[g
sort( group_section_names.begin(), group_section_names.end() );
}
// eZNVɑĒljs
for( size_t i=0; i<group_section_names.size(); i++ ) {
const char* section_name = group_section_names[i].c_str();
// "Name" ̒l擾AO[vƂB
std::string group_name = inifile.GetValue( "Name", section_name );
if( group_name.empty() ) {
continue;
}
// "Type" ̒l擾AO[vʂƂB
// O[v̎ʂ͔p~BS GROUP_GENERAL ƂB
ACCESS_TYPE group_type = ACCESS_GROUP_GENERAL;
// "Url" ̒l擾AURLƂB
std::string url = inifile.GetValue( "Url", section_name );
// O[v쐬
CGroupItem group;
group.init( util::my_mbstowcs(group_name).c_str(), util::my_mbstowcs(url).c_str(), group_type );
// "CategoryXX" ̒l擾ABXX [01,30] ƂB
for( int j=0; j<30; j++ ) {
CStringA key;
key.Format( "Category%02d", j+1 );
// "CategoryXX" ̒l݂ȂΏIB
if(! inifile.RecordExists( (const char*)key, section_name ) ) {
break;
}
// "CategoryXX" ̒l擾B
std::string value = inifile.GetValue( (const char*)key, section_name );
// J}ŕXgB
std::vector<std::string> values;
util::split_by_comma( values, value );
if( values.size() < 2 ) {
continue;
}
// Xg̑1vfJeSƂB
std::string& category_name = values[0];
// Xg̑2vfJeSʂƂB
// JeSʖJeSʕϊsB
ACCESS_TYPE category_type = helper.CategoryString2Type( util::my_mbstowcs(values[1]).c_str() );
if( category_type == ACCESS_INVALID ) {
continue;
}
// Xg̑3vfURLƂB
// ݂Ȃꍇ̓JeSʂ̃ftHglpB
const char* category_url = NULL;
if( values.size() >= 3 ) {
category_url = values[2].c_str();
}
// Xg̑4vftOƂB
// ݂Ȃꍇ͏ȂƂB
bool bCruise = false;
if( values.size() >= 4 ) {
bCruise = atoi(values[3].c_str()) != 0 ? true : false;
}
// JeSljB
target.appendCategoryByIniData( accessTypeInfo, group, category_name, category_type, category_url, bCruise );
}
// JeSPȏȂAgroups ɒljB
if( group.categories.size() >= 1 ) {
target.groups.push_back( group );
}
}
// O[vvf[ȂIB
if( target.groups.empty() ) {
return false;
}
return true;
}
/**
* Mz3GroupData IuWFNg ini t@CiO[v`t@CjB
*/
bool Mz3GroupDataWriter::save( AccessTypeInfo& accessTypeInfo, const Mz3GroupData& target, const CString& inifilename )
{
inifile::IniFile inifile;
const int n = target.groups.size();
for( int i=0; i<n; i++ ) {
const CGroupItem& group = target.groups[i];
if (!group.bSaveToGroupFile) {
continue;
}
// ZNV
CStringA strSectionName;
strSectionName.Format( "Group%02d", i+1 );
// Name o
inifile.SetValue( L"Name", group.name, strSectionName );
// Type o( GROUP_GENERAL Ƃ)
inifile.SetValue( "Type", accessTypeInfo.getSerializeKey(ACCESS_GROUP_GENERAL), (LPCSTR)strSectionName );
// Url o
inifile.SetValue( L"Url", group.mixi.GetURL(), strSectionName );
// CategoryXX o
int nc = group.categories.size();
int categoryNumber = 1;
for( int j=0; j<nc; j++ ) {
// L[
CString key;
key.Format( L"Category%02d", categoryNumber );
// EӒl
// EӒl͏ɁAuJeŚvAuJeSʕvAuURLv
const CCategoryItem& item = group.categories[j];
CString categoryString = util::my_mbstowcs(accessTypeInfo.getSerializeKey(item.m_mixi.GetAccessType())).c_str();
if (categoryString.IsEmpty() || item.bSaveToGroupFile==false)
continue;
CString value;
value.Format( L"%s,%s,%s,%d",
item.m_name,
categoryString,
item.m_mixi.GetURL(),
item.m_bCruise ? 1 : 0
);
// o
inifile.SetValue( key, value, strSectionName );
categoryNumber ++;
}
}
// ۑ
return inifile.Save( inifilename, false );
}
<|endoftext|>
|
<commit_before>//Copyright (c) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "utils/linearAlg2D.h" //Distance from point to line.
#include "MergeInfillLines.h"
namespace cura
{
MergeInfillLines::MergeInfillLines(ExtruderPlan& plan) : extruder_plan(plan)
{
//Just copy the parameters to their fields.
}
/*
* first_is_already_merged == false
*
* o o
* / /
* / /
* / + / ---> -(t)-o-----o
* / /
* / /
* o o
*
* travel (t) to first location is done through first_path_start_changed and new_first_path_start.
* this gets rid of the tiny "blips". Depending on the merged line distance a small gap may appear, but this is
* accounted for in the volume.
*
* first_is_already_merged == true
*
* o
* /
* /
* o-----o + / ---> o-----------o or with slight o-----o-----o
* / / / bend /
* / / / /
* o o o o
*
*/
void MergeInfillLines::mergeLinesSideBySide(const bool first_is_already_merged, GCodePath& first_path, const Point first_path_start, GCodePath& second_path, const Point second_path_start, Point& new_first_path_start) const
{
coord_t first_path_length_flow = 0;
Point average_first_path;
Point previous_point = first_path_start;
for (const Point point : first_path.points)
{
first_path_length_flow += vSize(point - previous_point);
previous_point = point;
}
first_path_length_flow *= first_path.flow; //To get the volume we don't need to include the line width since it's the same for both lines.
if (first_is_already_merged)
{
// take second point of path, first_path.points[0]
average_first_path = first_path.points[0];
}
else
{
average_first_path += first_path_start;
for (const Point point : first_path.points)
{
average_first_path += point;
}
average_first_path /= (first_path.points.size() + 1);
}
coord_t second_path_length_flow = 0;
Point previous_point_second = second_path_start;
Point average_second_path = second_path_start;
for (const Point point : second_path.points)
{
second_path_length_flow += vSize(point - previous_point_second);
average_second_path += point;
previous_point_second = point;
}
second_path_length_flow *= second_path.flow;
average_second_path /= (second_path.points.size() + 1);
coord_t new_path_length = 0;
if (first_is_already_merged)
{
// check if the new point is a good extension of last part of existing polyline
// because of potential accumulation of errors introduced each time a line is merged, we do not allow any error.
if (first_path.points.size() > 1 && LinearAlg2D::getDist2FromLine(average_second_path, first_path.points[first_path.points.size()-2], first_path.points[first_path.points.size()-1]) == 0) {
first_path.points[first_path.points.size()-1] = average_second_path;
} else {
first_path.points.push_back(average_second_path);
}
}
else
{
first_path.points.clear();
new_first_path_start = average_first_path;
//first_path.points.push_back(average_first_path);
first_path.points.push_back(average_second_path);
}
previous_point = first_path_start;
for (const Point point : first_path.points)
{
new_path_length += vSize(point - previous_point);
previous_point = point;
}
first_path.flow = static_cast<double>(first_path_length_flow + second_path_length_flow) / new_path_length;
}
bool MergeInfillLines::tryMerge(const bool first_is_already_merged, GCodePath& first_path, const Point first_path_start, GCodePath& second_path, const Point second_path_start, Point& new_first_path_start) const
{
const Point first_path_end = first_path.points.back();
const Point second_path_end = second_path.points.back();
const coord_t line_width = first_path.config->getLineWidth();
//Lines may be adjacent side-by-side then.
Point first_path_leave_point;
coord_t merged_size2;
if (first_is_already_merged) {
first_path_leave_point = first_path.points.back(); // this is the point that's going to merge
} else {
first_path_leave_point = (first_path_start + first_path_end) / 2;
}
const Point second_path_destination_point = (second_path_start + second_path_end) / 2;
const Point merged_direction = second_path_destination_point - first_path_leave_point;
if (first_is_already_merged)
{
merged_size2 = vSize2(second_path_destination_point - first_path.points.back()); // check distance with last point in merged line that is to be replaced
}
else
{
merged_size2 = vSize2(merged_direction);
}
if (merged_size2 > 25 * line_width * line_width)
{
return false; //Lines are too far away from each other.
}
if (merged_direction.X == 0 && merged_direction.Y == 0)
{
return true; // we can just disregard the second point as it's exactly at the leave point of the first path.
}
// Max 1 line width to the side of the merged_direction
if (LinearAlg2D::getDist2FromLine(first_path_start, second_path_destination_point, second_path_destination_point + merged_direction) > line_width * line_width
|| LinearAlg2D::getDist2FromLine(first_path_end, second_path_destination_point, second_path_destination_point + merged_direction) > line_width * line_width
|| LinearAlg2D::getDist2FromLine(second_path_start, first_path_leave_point, first_path_leave_point + merged_direction) > line_width * line_width
|| LinearAlg2D::getDist2FromLine(second_path_end, first_path_leave_point, first_path_leave_point + merged_direction) > line_width * line_width
|| dot(normal(merged_direction, 1000), normal(second_path_end - second_path_start, 1000)) > 866000) // angle of old second_path with new merged direction should not be too small (30 degrees), as it will introduce holes
{
return false; //One of the lines is too far from the merged line. Lines would be too wide or too far off.
}
if (first_is_already_merged && first_path.points.size() > 1 && first_path.points[first_path.points.size() - 2] == second_path_destination_point) // yes this can actually happen
{
return false;
}
mergeLinesSideBySide(first_is_already_merged, first_path, first_path_start, second_path, second_path_start, new_first_path_start);
return true;
}
bool MergeInfillLines::mergeInfillLines(std::vector<GCodePath>& paths, const Point& starting_position) const
{
/* Algorithm overview:
1. Loop over all lines to see if they can be merged.
1a. Check if two adjacent lines can be merged (skipping travel moves in
between).
1b. If they can, merge both lines into the first line.
1c. If they are merged, check next that the first line can be merged
with the line after the second line.
2. Do a second iteration over all paths to remove the tombstones. */
std::vector<size_t> remove_path_indices;
std::set<size_t> is_merged;
std::set<size_t> removed; // keep track of what we already removed, so don't remove it again
//For each two adjacent lines, see if they can be merged.
size_t first_path_index = 0;
Point first_path_start = Point(starting_position.X, starting_position.Y); // this one is not going to be overwritten
size_t second_path_index = 1;
for (; second_path_index < paths.size(); second_path_index++)
{
GCodePath& first_path = paths[first_path_index];
GCodePath& second_path = paths[second_path_index];
Point second_path_start = paths[second_path_index - 1].points.back();
const coord_t line_width = first_path.config->getLineWidth();
if (second_path.config->isTravelPath())
{
continue; //Skip travel paths, we're looking for the first non-travel path.
}
bool allow_try_merge = true;
// see if we meet criteria to merge. should be: travel - path1 not travel - (...) - travel - path2 not travel - travel
// we're checking the travels here
if (first_path_index <= 1 || !paths[first_path_index - 1].isTravelPath()) // "<= 1" because we don't want the first travel being changed. That may introduce a hole somewhere
{
allow_try_merge = false;
}
if (second_path_index + 1 >= paths.size() || !paths[second_path_index + 1].isTravelPath())
{
allow_try_merge = false;
}
if (first_path.config->isTravelPath()) //Don't merge travel moves.
{
allow_try_merge = false;
}
if (first_path.config != second_path.config) //Only merge lines that have the same type.
{
allow_try_merge = false;
}
if (first_path.config->type != PrintFeatureType::Infill && first_path.config->type != PrintFeatureType::Skin) //Only merge skin and infill lines.
{
allow_try_merge = false;
}
const bool first_is_already_merged = is_merged.find(first_path_index) != is_merged.end();
if ((!first_is_already_merged && first_path.points.size() > 1) || second_path.points.size() > 1)
{
// For now we only merge simple lines, not polylines, to keep it simple.
// If the first line is already a merged line, then allow it.
allow_try_merge = false;
}
Point new_first_path_start;
if (allow_try_merge && tryMerge(first_is_already_merged, first_path, first_path_start, second_path, second_path_start, new_first_path_start))
{
if (!first_is_already_merged)
{
paths[first_path_index - 1].points.back().X = new_first_path_start.X;
paths[first_path_index - 1].points.back().Y = new_first_path_start.Y;
}
/* If we combine two lines, the next path may also be merged into the fist line, so we do NOT update
first_path_index. */
for (size_t to_delete_index = first_path_index + 1; to_delete_index <= second_path_index; to_delete_index++)
{
if (removed.find(to_delete_index) == removed.end()) // if there are line(s) between first and second, then those lines are already marked as to be deleted, only add the new line(s)
{
remove_path_indices.push_back(to_delete_index);
removed.insert(to_delete_index);
}
}
is_merged.insert(first_path_index);
}
else
{
/* If we do not combine, the next iteration we must simply merge the
second path with the line after it. */
first_path_index = second_path_index;
first_path_start = second_path_start;
}
}
//Delete all removed lines in one pass so that we need to move lines less often.
if (!remove_path_indices.empty())
{
size_t path_index = remove_path_indices[0];
for (size_t removed_position = 1; removed_position < remove_path_indices.size(); removed_position++)
{
for (; path_index < remove_path_indices[removed_position] - removed_position; path_index++)
{
paths[path_index] = paths[path_index + removed_position]; //Shift all paths.
}
}
for (; path_index < paths.size() - remove_path_indices.size(); path_index++) //Remaining shifts at the end.
{
paths[path_index] = paths[path_index + remove_path_indices.size()];
}
paths.erase(paths.begin() + path_index, paths.end());
return true;
}
else
{
return false;
}
}
}//namespace cura
<commit_msg>Remove redundant check for merging lines. Now has very nice result. CURA-5535<commit_after>//Copyright (c) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "utils/linearAlg2D.h" //Distance from point to line.
#include "MergeInfillLines.h"
namespace cura
{
MergeInfillLines::MergeInfillLines(ExtruderPlan& plan) : extruder_plan(plan)
{
//Just copy the parameters to their fields.
}
/*
* first_is_already_merged == false
*
* o o
* / /
* / /
* / + / ---> -(t)-o-----o
* / /
* / /
* o o
*
* travel (t) to first location is done through first_path_start_changed and new_first_path_start.
* this gets rid of the tiny "blips". Depending on the merged line distance a small gap may appear, but this is
* accounted for in the volume.
*
* first_is_already_merged == true
*
* o
* /
* /
* o-----o + / ---> o-----------o or with slight o-----o-----o
* / / / bend /
* / / / /
* o o o o
*
*/
void MergeInfillLines::mergeLinesSideBySide(const bool first_is_already_merged, GCodePath& first_path, const Point first_path_start, GCodePath& second_path, const Point second_path_start, Point& new_first_path_start) const
{
coord_t first_path_length_flow = 0;
Point average_first_path;
Point previous_point = first_path_start;
for (const Point point : first_path.points)
{
first_path_length_flow += vSize(point - previous_point);
previous_point = point;
}
first_path_length_flow *= first_path.flow; //To get the volume we don't need to include the line width since it's the same for both lines.
if (first_is_already_merged)
{
// take second point of path, first_path.points[0]
average_first_path = first_path.points[0];
}
else
{
average_first_path += first_path_start;
for (const Point point : first_path.points)
{
average_first_path += point;
}
average_first_path /= (first_path.points.size() + 1);
}
coord_t second_path_length_flow = 0;
Point previous_point_second = second_path_start;
Point average_second_path = second_path_start;
for (const Point point : second_path.points)
{
second_path_length_flow += vSize(point - previous_point_second);
average_second_path += point;
previous_point_second = point;
}
second_path_length_flow *= second_path.flow;
average_second_path /= (second_path.points.size() + 1);
coord_t new_path_length = 0;
if (first_is_already_merged)
{
// check if the new point is a good extension of last part of existing polyline
// because of potential accumulation of errors introduced each time a line is merged, we do not allow any error.
if (first_path.points.size() > 1 && LinearAlg2D::getDist2FromLine(average_second_path, first_path.points[first_path.points.size()-2], first_path.points[first_path.points.size()-1]) == 0) {
first_path.points[first_path.points.size()-1] = average_second_path;
} else {
first_path.points.push_back(average_second_path);
}
}
else
{
first_path.points.clear();
new_first_path_start = average_first_path;
//first_path.points.push_back(average_first_path);
first_path.points.push_back(average_second_path);
}
previous_point = first_path_start;
for (const Point point : first_path.points)
{
new_path_length += vSize(point - previous_point);
previous_point = point;
}
first_path.flow = static_cast<double>(first_path_length_flow + second_path_length_flow) / new_path_length;
}
bool MergeInfillLines::tryMerge(const bool first_is_already_merged, GCodePath& first_path, const Point first_path_start, GCodePath& second_path, const Point second_path_start, Point& new_first_path_start) const
{
const Point first_path_end = first_path.points.back();
const Point second_path_end = second_path.points.back();
const coord_t line_width = first_path.config->getLineWidth();
//Lines may be adjacent side-by-side then.
Point first_path_leave_point;
coord_t merged_size2;
if (first_is_already_merged)
{
first_path_leave_point = first_path.points.back(); // this is the point that's going to merge
} else {
first_path_leave_point = (first_path_start + first_path_end) / 2;
}
const Point second_path_destination_point = (second_path_start + second_path_end) / 2;
const Point merged_direction = second_path_destination_point - first_path_leave_point;
if (first_is_already_merged)
{
merged_size2 = vSize2(second_path_destination_point - first_path.points.back()); // check distance with last point in merged line that is to be replaced
}
else
{
merged_size2 = vSize2(merged_direction);
}
if (merged_size2 > 25 * line_width * line_width)
{
return false; //Lines are too far away from each other.
}
if (merged_direction.X == 0 && merged_direction.Y == 0)
{
return true; // we can just disregard the second point as it's exactly at the leave point of the first path.
}
// Max 1 line width to the side of the merged_direction
if (LinearAlg2D::getDist2FromLine(first_path_end, second_path_destination_point, second_path_destination_point + merged_direction) > line_width * line_width
|| LinearAlg2D::getDist2FromLine(second_path_start, first_path_leave_point, first_path_leave_point + merged_direction) > line_width * line_width
|| LinearAlg2D::getDist2FromLine(second_path_end, first_path_leave_point, first_path_leave_point + merged_direction) > line_width * line_width
|| abs(dot(normal(merged_direction, 1000), normal(second_path_end - second_path_start, 1000))) > 866000) // angle of old second_path with new merged direction should not be too small (30 degrees), as it will introduce holes
{
return false; //One of the lines is too far from the merged line. Lines would be too wide or too far off.
}
if (first_is_already_merged && first_path.points.size() > 1 && first_path.points[first_path.points.size() - 2] == second_path_destination_point) // yes this can actually happen
{
return false;
}
mergeLinesSideBySide(first_is_already_merged, first_path, first_path_start, second_path, second_path_start, new_first_path_start);
return true;
}
bool MergeInfillLines::mergeInfillLines(std::vector<GCodePath>& paths, const Point& starting_position) const
{
/* Algorithm overview:
1. Loop over all lines to see if they can be merged.
1a. Check if two adjacent lines can be merged (skipping travel moves in
between).
1b. If they can, merge both lines into the first line.
1c. If they are merged, check next that the first line can be merged
with the line after the second line.
2. Do a second iteration over all paths to remove the tombstones. */
std::vector<size_t> remove_path_indices;
std::set<size_t> is_merged;
std::set<size_t> removed; // keep track of what we already removed, so don't remove it again
//For each two adjacent lines, see if they can be merged.
size_t first_path_index = 0;
Point first_path_start = Point(starting_position.X, starting_position.Y); // this one is not going to be overwritten
size_t second_path_index = 1;
for (; second_path_index < paths.size(); second_path_index++)
{
GCodePath& first_path = paths[first_path_index];
GCodePath& second_path = paths[second_path_index];
Point second_path_start = paths[second_path_index - 1].points.back();
const coord_t line_width = first_path.config->getLineWidth();
if (second_path.config->isTravelPath())
{
continue; //Skip travel paths, we're looking for the first non-travel path.
}
bool allow_try_merge = true;
// see if we meet criteria to merge. should be: travel - path1 not travel - (...) - travel - path2 not travel - travel
// we're checking the travels here
if (first_path_index <= 1 || !paths[first_path_index - 1].isTravelPath()) // "<= 1" because we don't want the first travel being changed. That may introduce a hole somewhere
{
allow_try_merge = false;
}
if (second_path_index + 1 >= paths.size() || !paths[second_path_index + 1].isTravelPath())
{
allow_try_merge = false;
}
if (first_path.config->isTravelPath()) //Don't merge travel moves.
{
allow_try_merge = false;
}
if (first_path.config != second_path.config) //Only merge lines that have the same type.
{
allow_try_merge = false;
}
if (first_path.config->type != PrintFeatureType::Infill && first_path.config->type != PrintFeatureType::Skin) //Only merge skin and infill lines.
{
allow_try_merge = false;
}
const bool first_is_already_merged = is_merged.find(first_path_index) != is_merged.end();
if ((!first_is_already_merged && first_path.points.size() > 1) || second_path.points.size() > 1)
{
// For now we only merge simple lines, not polylines, to keep it simple.
// If the first line is already a merged line, then allow it.
allow_try_merge = false;
}
Point new_first_path_start;
if (allow_try_merge && tryMerge(first_is_already_merged, first_path, first_path_start, second_path, second_path_start, new_first_path_start))
{
if (!first_is_already_merged)
{
paths[first_path_index - 1].points.back().X = new_first_path_start.X;
paths[first_path_index - 1].points.back().Y = new_first_path_start.Y;
}
/* If we combine two lines, the next path may also be merged into the fist line, so we do NOT update
first_path_index. */
for (size_t to_delete_index = first_path_index + 1; to_delete_index <= second_path_index; to_delete_index++)
{
if (removed.find(to_delete_index) == removed.end()) // if there are line(s) between first and second, then those lines are already marked as to be deleted, only add the new line(s)
{
remove_path_indices.push_back(to_delete_index);
removed.insert(to_delete_index);
}
}
is_merged.insert(first_path_index);
}
else
{
/* If we do not combine, the next iteration we must simply merge the
second path with the line after it. */
first_path_index = second_path_index;
first_path_start = second_path_start;
}
}
//Delete all removed lines in one pass so that we need to move lines less often.
if (!remove_path_indices.empty())
{
size_t path_index = remove_path_indices[0];
for (size_t removed_position = 1; removed_position < remove_path_indices.size(); removed_position++)
{
for (; path_index < remove_path_indices[removed_position] - removed_position; path_index++)
{
paths[path_index] = paths[path_index + removed_position]; //Shift all paths.
}
}
for (; path_index < paths.size() - remove_path_indices.size(); path_index++) //Remaining shifts at the end.
{
paths[path_index] = paths[path_index + remove_path_indices.size()];
}
paths.erase(paths.begin() + path_index, paths.end());
return true;
}
else
{
return false;
}
}
}//namespace cura
<|endoftext|>
|
<commit_before>#include <filterfalse.hpp>
#include "helpers.hpp"
#include <vector>
#include <string>
#include <iterator>
#include "catch.hpp"
using iter::filterfalse;
using Vec = const std::vector<int>;
namespace {
bool less_than_five(int i) {
return i < 5;
}
class LessThanValue {
private:
int compare_val;
public:
LessThanValue(int v) : compare_val(v) {}
bool operator()(int i) {
return i < this->compare_val;
}
};
}
TEST_CASE("filterfalse: handles different functor types", "[filterfalse]") {
Vec ns = {1, 2, 5, 6, 3, 1, 7, -1, 5};
Vec vc = {5, 6, 7, 5};
SECTION("with function pointer") {
auto f = filterfalse(less_than_five, ns);
Vec v(std::begin(f), std::end(f));
REQUIRE(v == vc);
}
SECTION("with callable object") {
std::vector<int> v;
SECTION("Normal call") {
auto f = filterfalse(LessThanValue{5}, ns);
v.assign(std::begin(f), std::end(f));
}
SECTION("Pipe") {
auto f = ns | filterfalse(LessThanValue{5});
v.assign(std::begin(f), std::end(f));
}
REQUIRE(v == vc);
}
SECTION("with lambda") {
auto ltf = [](int i) { return i < 5; };
auto f = filterfalse(ltf, ns);
Vec v(std::begin(f), std::end(f));
REQUIRE(v == vc);
}
}
TEST_CASE("filterfalse: using identity", "[filterfalse]") {
Vec ns{0, 1, 2, 0, 3, 0, 0, 0, 4, 5, 0};
std::vector<int> v;
SECTION("Normal call") {
auto f = filterfalse(ns);
v.assign(std::begin(f), std::end(f));
}
SECTION("Pipe") {
auto f = ns | filterfalse;
v.assign(std::begin(f), std::end(f));
}
Vec vc = {0, 0, 0, 0, 0, 0};
REQUIRE(v == vc);
}
TEST_CASE("filterfalse: binds to lvalues, moves rvales", "[filterfalse]") {
itertest::BasicIterable<int> bi{1, 2, 3, 4};
SECTION("one-arg binds to lvalues") {
filterfalse(bi);
REQUIRE_FALSE(bi.was_moved_from());
}
SECTION("two-arg binds to lvalues") {
filterfalse(less_than_five, bi);
REQUIRE_FALSE(bi.was_moved_from());
}
SECTION("one-arg moves rvalues") {
filterfalse(std::move(bi));
REQUIRE(bi.was_moved_from());
}
SECTION("two-arg moves rvalues") {
filterfalse(less_than_five, std::move(bi));
REQUIRE(bi.was_moved_from());
}
}
TEST_CASE("filterfalse: all elements pass predicate", "[filterfalse]") {
Vec ns{0, 1, 2, 3, 4};
auto f = filterfalse(less_than_five, ns);
REQUIRE(std::begin(f) == std::end(f));
}
TEST_CASE("filterfalse: iterator meets requirements", "[filterfalse]") {
std::string s{};
auto c = filterfalse([] { return true; }, s);
REQUIRE(itertest::IsIterator<decltype(std::begin(c))>::value);
}
template <typename T, typename U>
using ImpT = decltype(filterfalse(std::declval<T>(), std::declval<U>()));
TEST_CASE("filterfalse: has correct ctor and assign ops", "[filterfalse]") {
using T1 = ImpT<bool (*)(char c), std::string&>;
auto lam = [](char) { return false; };
using T2 = ImpT<decltype(lam), std::string>;
REQUIRE(itertest::IsMoveConstructibleOnly<T1>::value);
REQUIRE(itertest::IsMoveConstructibleOnly<T2>::value);
}
<commit_msg>Tests filterfalse with different begin and end<commit_after>#include <filterfalse.hpp>
#include "helpers.hpp"
#include <vector>
#include <string>
#include <iterator>
#include "catch.hpp"
using iter::filterfalse;
using Vec = const std::vector<int>;
namespace {
bool less_than_five(int i) {
return i < 5;
}
class LessThanValue {
private:
int compare_val;
public:
LessThanValue(int v) : compare_val(v) {}
bool operator()(int i) {
return i < this->compare_val;
}
};
}
TEST_CASE("filterfalse: handles different functor types", "[filterfalse]") {
Vec ns = {1, 2, 5, 6, 3, 1, 7, -1, 5};
Vec vc = {5, 6, 7, 5};
SECTION("with function pointer") {
auto f = filterfalse(less_than_five, ns);
Vec v(std::begin(f), std::end(f));
REQUIRE(v == vc);
}
SECTION("with callable object") {
std::vector<int> v;
SECTION("Normal call") {
auto f = filterfalse(LessThanValue{5}, ns);
v.assign(std::begin(f), std::end(f));
}
SECTION("Pipe") {
auto f = ns | filterfalse(LessThanValue{5});
v.assign(std::begin(f), std::end(f));
}
REQUIRE(v == vc);
}
SECTION("with lambda") {
auto ltf = [](int i) { return i < 5; };
auto f = filterfalse(ltf, ns);
Vec v(std::begin(f), std::end(f));
REQUIRE(v == vc);
}
}
TEST_CASE("filterfalse: Works with different begin and end types",
"[filterfalse]") {
CharRange cr{'d'};
auto f = filterfalse([](char c){return c == 'b';}, cr);
Vec v(f.begin(), f.end());
Vec vc{'a', 'c'};
REQUIRE(v == vc);
}
TEST_CASE("filterfalse: using identity", "[filterfalse]") {
Vec ns{0, 1, 2, 0, 3, 0, 0, 0, 4, 5, 0};
std::vector<int> v;
SECTION("Normal call") {
auto f = filterfalse(ns);
v.assign(std::begin(f), std::end(f));
}
SECTION("Pipe") {
auto f = ns | filterfalse;
v.assign(std::begin(f), std::end(f));
}
Vec vc = {0, 0, 0, 0, 0, 0};
REQUIRE(v == vc);
}
TEST_CASE("filterfalse: binds to lvalues, moves rvales", "[filterfalse]") {
itertest::BasicIterable<int> bi{1, 2, 3, 4};
SECTION("one-arg binds to lvalues") {
filterfalse(bi);
REQUIRE_FALSE(bi.was_moved_from());
}
SECTION("two-arg binds to lvalues") {
filterfalse(less_than_five, bi);
REQUIRE_FALSE(bi.was_moved_from());
}
SECTION("one-arg moves rvalues") {
filterfalse(std::move(bi));
REQUIRE(bi.was_moved_from());
}
SECTION("two-arg moves rvalues") {
filterfalse(less_than_five, std::move(bi));
REQUIRE(bi.was_moved_from());
}
}
TEST_CASE("filterfalse: all elements pass predicate", "[filterfalse]") {
Vec ns{0, 1, 2, 3, 4};
auto f = filterfalse(less_than_five, ns);
REQUIRE(std::begin(f) == std::end(f));
}
TEST_CASE("filterfalse: iterator meets requirements", "[filterfalse]") {
std::string s{};
auto c = filterfalse([] { return true; }, s);
REQUIRE(itertest::IsIterator<decltype(std::begin(c))>::value);
}
template <typename T, typename U>
using ImpT = decltype(filterfalse(std::declval<T>(), std::declval<U>()));
TEST_CASE("filterfalse: has correct ctor and assign ops", "[filterfalse]") {
using T1 = ImpT<bool (*)(char c), std::string&>;
auto lam = [](char) { return false; };
using T2 = ImpT<decltype(lam), std::string>;
REQUIRE(itertest::IsMoveConstructibleOnly<T1>::value);
REQUIRE(itertest::IsMoveConstructibleOnly<T2>::value);
}
<|endoftext|>
|
<commit_before>#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "overlap.hpp"
#include "result.hpp"
#include "comparator.hpp"
using namespace std;
using namespace OLC;
TEST_CASE("result class", "[result]")
{
vector<Nucleotide> vec1;
vec1.push_back(Nucleotide(NucleotideLetter(0x02)));
vec1.push_back(Nucleotide(NucleotideLetter(0x03)));
vec1.push_back(Nucleotide(NucleotideLetter(0x01)));
vec1.push_back(Nucleotide(NucleotideLetter(0x00)));
vec1.push_back(Nucleotide(NucleotideLetter(0x03)));
vec1.push_back(Nucleotide(NucleotideLetter(0x02)));
vector<Nucleotide> vec2;
vec2.push_back(Nucleotide(NucleotideLetter(0x01)));
vec2.push_back(Nucleotide(NucleotideLetter(0x03)));
vec2.push_back(Nucleotide(NucleotideLetter(0x03)));
vec2.push_back(Nucleotide(NucleotideLetter(0x01)));
vec2.push_back(Nucleotide(NucleotideLetter(0x00)));
vec2.push_back(Nucleotide(NucleotideLetter(0x02)));
vec2.push_back(Nucleotide(NucleotideLetter(0x01)));
const Overlap overlap = compare(vec1, vec2);
const uint32_t overlapFirstEnd = overlap.getEndFirst();
const uint32_t overlapSecondEnd = overlap.getEndSecond();
const uint32_t overlapFirstStart = overlap.getStartFirst();
const uint32_t overlapSecondStart = overlap.getStartSecond();
const uint32_t overlapLength = overlapFirstEnd - overlapFirstStart + 1;
int32_t ahang = overlapFirstStart;
int32_t bhang = vec2.size() - overlapSecondEnd - 1;
if (overlapSecondStart < overlapFirstStart)
ahang *= -1;
if (vec1.size() > overlapSecondEnd)
bhang *= -1;
Result result(1, 2, overlapLength, ahang, bhang);
SECTION("check length")
{
REQUIRE(result.getLength() == 3);
}
SECTION("check ahang and bhang")
{
REQUIRE(result.getAhng() == 1);
REQUIRE(result.getBhng() == -2);
}
const Overlap overlapReverse = compare(vec2, vec1);
int32_t ahangReverse = overlapReverse.getStartFirst();
int32_t bhangReverse = vec1.size() - overlapReverse.getEndSecond() - 1;
if (overlapReverse.getStartSecond() < overlapReverse.getStartFirst()) {
ahangReverse *= -1;
}
if (vec2.size() > overlapReverse.getEndSecond()) {
bhangReverse *= -1;
}
SECTION("check ahang and bhang in reverse case")
{
REQUIRE(ahangReverse == -2);
REQUIRE(bhangReverse == -2);
}
vector<Nucleotide> vec3;
vec3.push_back(Nucleotide(NucleotideLetter(0x02)));
vec3.push_back(Nucleotide(NucleotideLetter(0x03)));
vec3.push_back(Nucleotide(NucleotideLetter(0x01)));
vec3.push_back(Nucleotide(NucleotideLetter(0x02)));
vector<Nucleotide> vec4;
vec4.push_back(Nucleotide(NucleotideLetter(0x03)));
vec4.push_back(Nucleotide(NucleotideLetter(0x01)));
vec4.push_back(Nucleotide(NucleotideLetter(0x02)));
vec4.push_back(Nucleotide(NucleotideLetter(0x03)));
vec4.push_back(Nucleotide(NucleotideLetter(0x01)));
const Overlap overlapEnd = compare(vec4, vec3);
int32_t ahangEnd = overlapEnd.getStartFirst();
int32_t bhangEnd = vec4.size() - overlapEnd.getEndSecond() -1;
if (overlapEnd.getStartSecond() < overlapEnd.getStartFirst()) {
ahangEnd *= -1;
}
if (vec4.size() > overlapEnd.getEndSecond()) {
bhangEnd *= -1;
}
SECTION("check possible negative ahang/bhang in a trivial case")
{
REQUIRE(ahangEnd == 1);
REQUIRE(bhangEnd == -1);
}
}<commit_msg>result_test: fix spaces<commit_after>#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "overlap.hpp"
#include "result.hpp"
#include "comparator.hpp"
using namespace std;
using namespace OLC;
TEST_CASE("result class", "[result]")
{
vector<Nucleotide> vec1;
vec1.push_back(Nucleotide(NucleotideLetter(0x02)));
vec1.push_back(Nucleotide(NucleotideLetter(0x03)));
vec1.push_back(Nucleotide(NucleotideLetter(0x01)));
vec1.push_back(Nucleotide(NucleotideLetter(0x00)));
vec1.push_back(Nucleotide(NucleotideLetter(0x03)));
vec1.push_back(Nucleotide(NucleotideLetter(0x02)));
vector<Nucleotide> vec2;
vec2.push_back(Nucleotide(NucleotideLetter(0x01)));
vec2.push_back(Nucleotide(NucleotideLetter(0x03)));
vec2.push_back(Nucleotide(NucleotideLetter(0x03)));
vec2.push_back(Nucleotide(NucleotideLetter(0x01)));
vec2.push_back(Nucleotide(NucleotideLetter(0x00)));
vec2.push_back(Nucleotide(NucleotideLetter(0x02)));
vec2.push_back(Nucleotide(NucleotideLetter(0x01)));
const Overlap overlap = compare(vec1, vec2);
const uint32_t overlapFirstEnd = overlap.getEndFirst();
const uint32_t overlapSecondEnd = overlap.getEndSecond();
const uint32_t overlapFirstStart = overlap.getStartFirst();
const uint32_t overlapSecondStart = overlap.getStartSecond();
const uint32_t overlapLength = overlapFirstEnd - overlapFirstStart + 1;
int32_t ahang = overlapFirstStart;
int32_t bhang = vec2.size() - overlapSecondEnd - 1;
if (overlapSecondStart < overlapFirstStart)
ahang *= -1;
if (vec1.size() > overlapSecondEnd)
bhang *= -1;
Result result(1, 2, overlapLength, ahang, bhang);
SECTION("check length")
{
REQUIRE(result.getLength() == 3);
}
SECTION("check ahang and bhang")
{
REQUIRE(result.getAhng() == 1);
REQUIRE(result.getBhng() == -2);
}
const Overlap overlapReverse = compare(vec2, vec1);
int32_t ahangReverse = overlapReverse.getStartFirst();
int32_t bhangReverse = vec1.size() - overlapReverse.getEndSecond() - 1;
if (overlapReverse.getStartSecond() < overlapReverse.getStartFirst()) {
ahangReverse *= -1;
}
if (vec2.size() > overlapReverse.getEndSecond()) {
bhangReverse *= -1;
}
SECTION("check ahang and bhang in reverse case")
{
REQUIRE(ahangReverse == -2);
REQUIRE(bhangReverse == -2);
}
vector<Nucleotide> vec3;
vec3.push_back(Nucleotide(NucleotideLetter(0x02)));
vec3.push_back(Nucleotide(NucleotideLetter(0x03)));
vec3.push_back(Nucleotide(NucleotideLetter(0x01)));
vec3.push_back(Nucleotide(NucleotideLetter(0x02)));
vector<Nucleotide> vec4;
vec4.push_back(Nucleotide(NucleotideLetter(0x03)));
vec4.push_back(Nucleotide(NucleotideLetter(0x01)));
vec4.push_back(Nucleotide(NucleotideLetter(0x02)));
vec4.push_back(Nucleotide(NucleotideLetter(0x03)));
vec4.push_back(Nucleotide(NucleotideLetter(0x01)));
const Overlap overlapEnd = compare(vec4, vec3);
int32_t ahangEnd = overlapEnd.getStartFirst();
int32_t bhangEnd = vec4.size() - overlapEnd.getEndSecond() -1;
if (overlapEnd.getStartSecond() < overlapEnd.getStartFirst()) {
ahangEnd *= -1;
}
if (vec4.size() > overlapEnd.getEndSecond()) {
bhangEnd *= -1;
}
SECTION("check possible negative ahang/bhang in a trivial case")
{
REQUIRE(ahangEnd == 1);
REQUIRE(bhangEnd == -1);
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: epgm.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hjs $ $Date: 2004-06-25 12:32:04 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <vcl/svapp.hxx>
#include <vcl/graph.hxx>
#include <vcl/bmpacc.hxx>
#include <vcl/msgbox.hxx>
#include <svtools/solar.hrc>
#include <svtools/fltcall.hxx>
#include <svtools/FilterConfigItem.hxx>
#include "strings.hrc"
#include "dlgepgm.hrc"
#include "dlgepgm.hxx"
//============================ PGMWriter ==================================
class PGMWriter {
private:
PFilterCallback mpCallback;
void * mpCallerData;
SvStream* mpOStm; // Die auszugebende PGM-Datei
USHORT mpOStmOldModus;
BOOL mbStatus;
UINT32 mnMode;
BitmapReadAccess* mpAcc;
ULONG mnWidth, mnHeight; // Bildausmass in Pixeln
BOOL ImplCallback( USHORT nPercent );
BOOL ImplWriteHeader();
void ImplWriteBody();
void ImplWriteNumber( sal_Int32 );
public:
PGMWriter();
~PGMWriter();
BOOL WritePGM( const Graphic& rGraphic, SvStream& rPGM,
PFilterCallback pCallback, void* pCallerdata,
FilterConfigItem* pConfigItem );
};
//=================== Methoden von PGMWriter ==============================
PGMWriter::PGMWriter() :
mpAcc ( NULL ),
mbStatus ( TRUE )
{
}
// ------------------------------------------------------------------------
PGMWriter::~PGMWriter()
{
}
// ------------------------------------------------------------------------
BOOL PGMWriter::ImplCallback( USHORT nPercent )
{
if ( mpCallback != NULL )
{
if ( ( (*mpCallback)( mpCallerData, nPercent ) ) == TRUE )
{
mpOStm->SetError( SVSTREAM_FILEFORMAT_ERROR );
return TRUE;
}
}
return FALSE;
}
// ------------------------------------------------------------------------
BOOL PGMWriter::WritePGM( const Graphic& rGraphic, SvStream& rPGM,
PFilterCallback pCallback, void* pCallerdata,
FilterConfigItem* pConfigItem )
{
mpOStm = &rPGM;
mpCallback = pCallback;
mpCallerData = pCallerdata;
if ( pConfigItem )
mnMode = pConfigItem->ReadInt32( String( RTL_CONSTASCII_USTRINGPARAM( "FileFormat" ) ), 0 );
BitmapEx aBmpEx( rGraphic.GetBitmapEx() );
Bitmap aBmp = aBmpEx.GetBitmap();
aBmp.Convert( BMP_CONVERSION_8BIT_GREYS );
mpOStmOldModus = mpOStm->GetNumberFormatInt();
mpOStm->SetNumberFormatInt( NUMBERFORMAT_INT_BIGENDIAN );
mpAcc = aBmp.AcquireReadAccess();
if( mpAcc )
{
if ( ImplWriteHeader() )
{
ImplWriteBody();
}
aBmp.ReleaseAccess( mpAcc );
}
else
mbStatus = FALSE;
mpOStm->SetNumberFormatInt( mpOStmOldModus );
return mbStatus;
}
// ------------------------------------------------------------------------
BOOL PGMWriter::ImplWriteHeader()
{
mnWidth = mpAcc->Width();
mnHeight = mpAcc->Height();
if ( mnWidth && mnHeight )
{
if ( mnMode == 0 )
*mpOStm << "P5\x0a";
else
*mpOStm << "P2\x0a";
ImplWriteNumber( mnWidth );
*mpOStm << (BYTE)32;
ImplWriteNumber( mnHeight );
*mpOStm << (BYTE)32;
ImplWriteNumber( 255 ); // max. gray value
*mpOStm << (BYTE)10;
}
else
mbStatus = FALSE;
return mbStatus;
}
// ------------------------------------------------------------------------
void PGMWriter::ImplWriteBody()
{
if ( mnMode == 0 )
{
for ( ULONG y = 0; y < mnHeight; y++ )
{
for ( ULONG x = 0; x < mnWidth; x++ )
{
*mpOStm << (BYTE)( mpAcc->GetPixel( y, x ) );
}
}
}
else
{
for ( ULONG y = 0; y < mnHeight; y++ )
{
int nCount = 70;
for ( ULONG x = 0; x < mnWidth; x++ )
{
BYTE nDat, nNumb;
if ( nCount < 0 )
{
nCount = 69;
*mpOStm << (BYTE)10;
}
nDat = (BYTE)mpAcc->GetPixel( y, x );
if ( ( nNumb = nDat / 100 ) )
{
*mpOStm << (BYTE)( nNumb + '0' );
nDat -= ( nNumb * 100 );
nNumb = nDat / 10;
*mpOStm << (BYTE)( nNumb + '0' );
nDat -= ( nNumb * 10 );
*mpOStm << (BYTE)( nDat + '0' );
nCount -= 4;
}
else if ( ( nNumb = nDat / 10 ) )
{
*mpOStm << (BYTE)( nNumb + '0' );
nDat -= ( nNumb * 10 );
*mpOStm << (BYTE)( nDat + '0' );
nCount -= 3;
}
else
{
*mpOStm << (BYTE)( nDat + '0' );
nCount -= 2;
}
*mpOStm << (BYTE)' ';
}
*mpOStm << (BYTE)10;
}
}
}
// ------------------------------------------------------------------------
// eine Dezimalzahl im ASCII format wird in den Stream geschrieben
void PGMWriter::ImplWriteNumber( sal_Int32 nNumber )
{
const ByteString aNum( ByteString::CreateFromInt32( nNumber ) );
for( sal_Int16 n = 0UL, nLen = aNum.Len(); n < nLen; n++ )
*mpOStm << aNum.GetChar( n );
}
// ------------------------------------------------------------------------
// ---------------------
// - exported function -
// ---------------------
extern "C" BOOL __LOADONCALLAPI GraphicExport( SvStream& rStream, Graphic& rGraphic,
PFilterCallback pCallback, void* pCallerData,
FilterConfigItem* pConfigItem, BOOL )
{
PGMWriter aPGMWriter;
return aPGMWriter.WritePGM( rGraphic, rStream, pCallback, pCallerData, pConfigItem );
}
// ------------------------------------------------------------------------
extern "C" BOOL __LOADONCALLAPI DoExportDialog( FltCallDialogParameter& rPara )
{
BOOL bRet = FALSE;
if ( rPara.pWindow )
{
ByteString aResMgrName( "epg" );
ResMgr* pResMgr;
aResMgrName.Append( ByteString::CreateFromInt32( SOLARUPD ) );
pResMgr = ResMgr::CreateResMgr( aResMgrName.GetBuffer(), Application::GetSettings().GetUILocale() );
if( pResMgr )
{
rPara.pResMgr = pResMgr;
bRet = ( DlgExportEPGM( rPara ).Execute() == RET_OK );
delete pResMgr;
}
else
bRet = TRUE;
}
return bRet;
}
// ------------------------------------------------------------------------
#pragma hdrstop
// ---------------
// - Win16 trash -
// ---------------
#ifdef WIN
static HINSTANCE hDLLInst = 0;
extern "C" int CALLBACK LibMain( HINSTANCE hDLL, WORD, WORD nHeap, LPSTR )
{
if ( nHeap )
UnlockData( 0 );
hDLLInst = hDLL;
return TRUE;
}
// ------------------------------------------------------------------------
extern "C" int CALLBACK WEP( int )
{
return 1;
}
#endif
<commit_msg>INTEGRATION: CWS ooo20040815 (1.4.18); FILE MERGED 2004/08/04 13:03:27 waratah 1.4.18.1: #i32569# add default clause to case with comment remove a pramga for gcc builds<commit_after>/*************************************************************************
*
* $RCSfile: epgm.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2004-09-09 11:28:07 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <vcl/svapp.hxx>
#include <vcl/graph.hxx>
#include <vcl/bmpacc.hxx>
#include <vcl/msgbox.hxx>
#include <svtools/solar.hrc>
#include <svtools/fltcall.hxx>
#include <svtools/FilterConfigItem.hxx>
#include "strings.hrc"
#include "dlgepgm.hrc"
#include "dlgepgm.hxx"
//============================ PGMWriter ==================================
class PGMWriter {
private:
PFilterCallback mpCallback;
void * mpCallerData;
SvStream* mpOStm; // Die auszugebende PGM-Datei
USHORT mpOStmOldModus;
BOOL mbStatus;
UINT32 mnMode;
BitmapReadAccess* mpAcc;
ULONG mnWidth, mnHeight; // Bildausmass in Pixeln
BOOL ImplCallback( USHORT nPercent );
BOOL ImplWriteHeader();
void ImplWriteBody();
void ImplWriteNumber( sal_Int32 );
public:
PGMWriter();
~PGMWriter();
BOOL WritePGM( const Graphic& rGraphic, SvStream& rPGM,
PFilterCallback pCallback, void* pCallerdata,
FilterConfigItem* pConfigItem );
};
//=================== Methoden von PGMWriter ==============================
PGMWriter::PGMWriter() :
mbStatus ( TRUE ),
mpAcc ( NULL )
{
}
// ------------------------------------------------------------------------
PGMWriter::~PGMWriter()
{
}
// ------------------------------------------------------------------------
BOOL PGMWriter::ImplCallback( USHORT nPercent )
{
if ( mpCallback != NULL )
{
if ( ( (*mpCallback)( mpCallerData, nPercent ) ) == TRUE )
{
mpOStm->SetError( SVSTREAM_FILEFORMAT_ERROR );
return TRUE;
}
}
return FALSE;
}
// ------------------------------------------------------------------------
BOOL PGMWriter::WritePGM( const Graphic& rGraphic, SvStream& rPGM,
PFilterCallback pCallback, void* pCallerdata,
FilterConfigItem* pConfigItem )
{
mpOStm = &rPGM;
mpCallback = pCallback;
mpCallerData = pCallerdata;
if ( pConfigItem )
mnMode = pConfigItem->ReadInt32( String( RTL_CONSTASCII_USTRINGPARAM( "FileFormat" ) ), 0 );
BitmapEx aBmpEx( rGraphic.GetBitmapEx() );
Bitmap aBmp = aBmpEx.GetBitmap();
aBmp.Convert( BMP_CONVERSION_8BIT_GREYS );
mpOStmOldModus = mpOStm->GetNumberFormatInt();
mpOStm->SetNumberFormatInt( NUMBERFORMAT_INT_BIGENDIAN );
mpAcc = aBmp.AcquireReadAccess();
if( mpAcc )
{
if ( ImplWriteHeader() )
{
ImplWriteBody();
}
aBmp.ReleaseAccess( mpAcc );
}
else
mbStatus = FALSE;
mpOStm->SetNumberFormatInt( mpOStmOldModus );
return mbStatus;
}
// ------------------------------------------------------------------------
BOOL PGMWriter::ImplWriteHeader()
{
mnWidth = mpAcc->Width();
mnHeight = mpAcc->Height();
if ( mnWidth && mnHeight )
{
if ( mnMode == 0 )
*mpOStm << "P5\x0a";
else
*mpOStm << "P2\x0a";
ImplWriteNumber( mnWidth );
*mpOStm << (BYTE)32;
ImplWriteNumber( mnHeight );
*mpOStm << (BYTE)32;
ImplWriteNumber( 255 ); // max. gray value
*mpOStm << (BYTE)10;
}
else
mbStatus = FALSE;
return mbStatus;
}
// ------------------------------------------------------------------------
void PGMWriter::ImplWriteBody()
{
if ( mnMode == 0 )
{
for ( ULONG y = 0; y < mnHeight; y++ )
{
for ( ULONG x = 0; x < mnWidth; x++ )
{
*mpOStm << (BYTE)( mpAcc->GetPixel( y, x ) );
}
}
}
else
{
for ( ULONG y = 0; y < mnHeight; y++ )
{
int nCount = 70;
for ( ULONG x = 0; x < mnWidth; x++ )
{
BYTE nDat, nNumb;
if ( nCount < 0 )
{
nCount = 69;
*mpOStm << (BYTE)10;
}
nDat = (BYTE)mpAcc->GetPixel( y, x );
if ( ( nNumb = nDat / 100 ) )
{
*mpOStm << (BYTE)( nNumb + '0' );
nDat -= ( nNumb * 100 );
nNumb = nDat / 10;
*mpOStm << (BYTE)( nNumb + '0' );
nDat -= ( nNumb * 10 );
*mpOStm << (BYTE)( nDat + '0' );
nCount -= 4;
}
else if ( ( nNumb = nDat / 10 ) )
{
*mpOStm << (BYTE)( nNumb + '0' );
nDat -= ( nNumb * 10 );
*mpOStm << (BYTE)( nDat + '0' );
nCount -= 3;
}
else
{
*mpOStm << (BYTE)( nDat + '0' );
nCount -= 2;
}
*mpOStm << (BYTE)' ';
}
*mpOStm << (BYTE)10;
}
}
}
// ------------------------------------------------------------------------
// eine Dezimalzahl im ASCII format wird in den Stream geschrieben
void PGMWriter::ImplWriteNumber( sal_Int32 nNumber )
{
const ByteString aNum( ByteString::CreateFromInt32( nNumber ) );
for( sal_Int16 n = 0UL, nLen = aNum.Len(); n < nLen; n++ )
*mpOStm << aNum.GetChar( n );
}
// ------------------------------------------------------------------------
// ---------------------
// - exported function -
// ---------------------
extern "C" BOOL __LOADONCALLAPI GraphicExport( SvStream& rStream, Graphic& rGraphic,
PFilterCallback pCallback, void* pCallerData,
FilterConfigItem* pConfigItem, BOOL )
{
PGMWriter aPGMWriter;
return aPGMWriter.WritePGM( rGraphic, rStream, pCallback, pCallerData, pConfigItem );
}
// ------------------------------------------------------------------------
extern "C" BOOL __LOADONCALLAPI DoExportDialog( FltCallDialogParameter& rPara )
{
BOOL bRet = FALSE;
if ( rPara.pWindow )
{
ByteString aResMgrName( "epg" );
ResMgr* pResMgr;
aResMgrName.Append( ByteString::CreateFromInt32( SOLARUPD ) );
pResMgr = ResMgr::CreateResMgr( aResMgrName.GetBuffer(), Application::GetSettings().GetUILocale() );
if( pResMgr )
{
rPara.pResMgr = pResMgr;
bRet = ( DlgExportEPGM( rPara ).Execute() == RET_OK );
delete pResMgr;
}
else
bRet = TRUE;
}
return bRet;
}
// ------------------------------------------------------------------------
#ifndef GCC
#pragma hdrstop
#endif
// ---------------
// - Win16 trash -
// ---------------
#ifdef WIN
static HINSTANCE hDLLInst = 0;
extern "C" int CALLBACK LibMain( HINSTANCE hDLL, WORD, WORD nHeap, LPSTR )
{
if ( nHeap )
UnlockData( 0 );
hDLLInst = hDLL;
return TRUE;
}
// ------------------------------------------------------------------------
extern "C" int CALLBACK WEP( int )
{
return 1;
}
#endif
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (c) 2016, Johan Mabille and Sylvain Corlay *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XSIMD_TEST_UTILS_HPP
#define XSIMD_TEST_UTILS_HPP
#include <limits>
#include <algorithm>
#include <cmath>
#include <vector>
#include <iostream>
#include <ostream>
#include <iomanip>
#include <string>
#include <typeinfo>
namespace xsimd
{
template <class T>
inline std::string value_type_name()
{
return typeid(T).name();
}
namespace detail
{
template <class T>
bool check_is_small(const T& value, const T& tolerance)
{
using std::abs;
return abs(value) < abs(tolerance);
}
template <class T>
T safe_division(const T& lhs, const T& rhs)
{
if(rhs < static_cast<T>(1) && lhs > rhs * (std::numeric_limits<T>::max)())
{
return (std::numeric_limits<T>::max)();
}
if(lhs == static_cast<T>(0) ||
rhs > static_cast<T>(1) &&
lhs < rhs * (std::numeric_limits<T>::min)())
{
return static_cast<T>(0);
}
return lhs / rhs;
}
template <class T>
bool check_is_close(const T& lhs, const T& rhs, const T& relative_precision)
{
using std::abs;
T diff = abs(lhs - rhs);
T d1 = safe_division(diff, abs(rhs));
T d2 = safe_division(diff, abs(lhs));
return d1 <= relative_precision && d2 <= relative_precision;
}
}
template <class T>
bool scalar_comparison(const T& lhs, const T& rhs)
{
using std::max;
using std::abs;
T relative_precision = 2048 * std::numeric_limits<T>::epsilon();
T absolute_zero_prox = 2048 * std::numeric_limits<T>::epsilon();
if(max(abs(lhs), abs(rhs)) < T(1e-3))
{
return detail::check_is_small(lhs - rhs, absolute_zero_prox);
}
else
{
return detail::check_is_close(lhs, rhs, relative_precision);
}
}
template <class T, class A>
int vector_comparison(const std::vector<T, A>& lhs, const std::vector<T, A>& rhs)
{
if(lhs.size() != rhs.size())
{
return -1;
}
int nb_diff = 0;
for(auto lhs_iter = lhs.begin(), rhs_iter = rhs.begin(); lhs_iter != lhs.end(); ++lhs_iter, ++rhs_iter)
{
if(!scalar_comparison(*lhs_iter, *rhs_iter))
{
++nb_diff;
}
}
return nb_diff;
}
template <class T, class A>
inline std::ostream& operator<<(std::ostream& os, const std::vector<T, A>& v)
{
os << '[';
for(size_t i = 0; i < v.size() - 1; ++i)
{
os << v[i] << ',';
}
os << v.back() << ']' << std::endl;
return os;
}
template <class T>
inline bool check_almost_equal(const std::string& topic, const T& res, const T& ref, std::ostream& out)
{
out << topic;
out << std::setprecision(20);
if(scalar_comparison(res, ref))
{
out << "OK" << std::endl;
return true;
}
else
{
out << "BAD" << std::endl;
out << "Expected : " << std::endl << ref << std::endl;
out << "Got : " << std::endl << res << std::endl;
return false;
}
}
#define PRINT_COUT
template <class T, class A>
inline bool check_almost_equal(const std::string& topic, const std::vector<T, A>& res, const std::vector<T, A>& ref, std::ostream& out)
{
out << topic;
out << std::setprecision(20);
int comp = vector_comparison(res, ref);
if(comp == 0)
{
out << "OK" << std::endl;
return true;
}
else if (comp == -1)
{
out << "BAD" << std::endl;
out << "Expected size : " << ref.size() << std::endl;
out << "Actual size : " << res.size() << std::endl;
#ifdef PRINT_COUT
std::cout << topic << "BAD" << std::endl;
std::cout << "Expected size : " << ref.size() << std::endl;
std::cout << "Actual size : " << res.size() << std::endl;
#endif
return false;
}
else
{
out << "BAD" << std::endl;
out << "Expected : " << std::endl << ref << std::endl;;
out << "Got : " << std::endl << res << std::endl;
out << "Nb diff : " << comp << std::endl;
#ifdef PRINT_COUT
std::cout << topic << "BAD" << std::endl;
std::cout << "Nb diff : " << comp << std::endl;
#endif
return false;
}
}
}
#endif
<commit_msg>added percentage of errors<commit_after>/***************************************************************************
* Copyright (c) 2016, Johan Mabille and Sylvain Corlay *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XSIMD_TEST_UTILS_HPP
#define XSIMD_TEST_UTILS_HPP
#include <limits>
#include <algorithm>
#include <cmath>
#include <vector>
#include <iostream>
#include <ostream>
#include <iomanip>
#include <string>
#include <typeinfo>
namespace xsimd
{
template <class T>
inline std::string value_type_name()
{
return typeid(T).name();
}
namespace detail
{
template <class T>
bool check_is_small(const T& value, const T& tolerance)
{
using std::abs;
return abs(value) < abs(tolerance);
}
template <class T>
T safe_division(const T& lhs, const T& rhs)
{
if(rhs < static_cast<T>(1) && lhs > rhs * (std::numeric_limits<T>::max)())
{
return (std::numeric_limits<T>::max)();
}
if(lhs == static_cast<T>(0) ||
rhs > static_cast<T>(1) &&
lhs < rhs * (std::numeric_limits<T>::min)())
{
return static_cast<T>(0);
}
return lhs / rhs;
}
template <class T>
bool check_is_close(const T& lhs, const T& rhs, const T& relative_precision)
{
using std::abs;
T diff = abs(lhs - rhs);
T d1 = safe_division(diff, abs(rhs));
T d2 = safe_division(diff, abs(lhs));
return d1 <= relative_precision && d2 <= relative_precision;
}
}
template <class T>
bool scalar_comparison(const T& lhs, const T& rhs)
{
using std::max;
using std::abs;
T relative_precision = 2048 * std::numeric_limits<T>::epsilon();
T absolute_zero_prox = 2048 * std::numeric_limits<T>::epsilon();
if(max(abs(lhs), abs(rhs)) < T(1e-3))
{
return detail::check_is_small(lhs - rhs, absolute_zero_prox);
}
else
{
return detail::check_is_close(lhs, rhs, relative_precision);
}
}
template <class T, class A>
int vector_comparison(const std::vector<T, A>& lhs, const std::vector<T, A>& rhs)
{
if(lhs.size() != rhs.size())
{
return -1;
}
int nb_diff = 0;
for(auto lhs_iter = lhs.begin(), rhs_iter = rhs.begin(); lhs_iter != lhs.end(); ++lhs_iter, ++rhs_iter)
{
if(!scalar_comparison(*lhs_iter, *rhs_iter))
{
++nb_diff;
}
}
return nb_diff;
}
template <class T, class A>
inline std::ostream& operator<<(std::ostream& os, const std::vector<T, A>& v)
{
os << '[';
for(size_t i = 0; i < v.size() - 1; ++i)
{
os << v[i] << ',';
}
os << v.back() << ']' << std::endl;
return os;
}
template <class T>
inline bool check_almost_equal(const std::string& topic, const T& res, const T& ref, std::ostream& out)
{
out << topic;
out << std::setprecision(20);
if(scalar_comparison(res, ref))
{
out << "OK" << std::endl;
return true;
}
else
{
out << "BAD" << std::endl;
out << "Expected : " << std::endl << ref << std::endl;
out << "Got : " << std::endl << res << std::endl;
return false;
}
}
#define PRINT_COUT
template <class T, class A>
inline bool check_almost_equal(const std::string& topic, const std::vector<T, A>& res, const std::vector<T, A>& ref, std::ostream& out)
{
out << topic;
out << std::setprecision(20);
int comp = vector_comparison(res, ref);
if(comp == 0)
{
out << "OK" << std::endl;
return true;
}
else if (comp == -1)
{
out << "BAD" << std::endl;
out << "Expected size : " << ref.size() << std::endl;
out << "Actual size : " << res.size() << std::endl;
#ifdef PRINT_COUT
std::cout << topic << "BAD" << std::endl;
std::cout << "Expected size : " << ref.size() << std::endl;
std::cout << "Actual size : " << res.size() << std::endl;
#endif
return false;
}
else
{
double pct = double(comp) / (double(res.size()));
out << "BAD" << std::endl;
out << "Expected : " << std::endl << ref << std::endl;;
out << "Got : " << std::endl << res << std::endl;
out << "Nb diff : " << comp << '(' << pct << "%)" << std::endl;
#ifdef PRINT_COUT
std::cout << topic << "BAD" << std::endl;
std::cout << "Nb diff : " << comp << '(' << pct << "%)" << std::endl;
#endif
return false;
}
}
}
#endif
<|endoftext|>
|
<commit_before>// csafmt_whitespace.cpp -*-C++-*-
// ----------------------------------------------------------------------------
#include <csabase_analyser.h>
#include <csabase_location.h>
#include <csabase_ppobserver.h>
#include <csabase_registercheck.h>
#include <csabase_util.h>
#include <llvm/Support/Regex.h>
#include <string>
#ident "$Id$"
// ----------------------------------------------------------------------------
static std::string const check_name("whitespace");
// ----------------------------------------------------------------------------
using clang::SourceLocation;
using clang::SourceManager;
using clang::SourceRange;
using bde_verify::csabase::Analyser;
using bde_verify::csabase::Location;
using bde_verify::csabase::PPObserver;
using bde_verify::csabase::Range;
using bde_verify::csabase::Visitor;
namespace
{
struct files
// Callback object for inspecting files.
{
Analyser& d_analyser; // Analyser object.
files(Analyser& analyser);
// Create a 'files' object, accessing the specified 'analyser'.
void operator()(SourceLocation loc,
std::string const &,
std::string const &);
// The file specified by 'loc' is examined for tab characters and
// trailing spaces.
};
files::files(Analyser& analyser)
: d_analyser(analyser)
{
}
llvm::Regex bad_ws("\t+| +\n", llvm::Regex::NoFlags);
void files::operator()(SourceLocation loc,
std::string const &,
std::string const &)
{
const SourceManager &m = d_analyser.manager();
llvm::StringRef buf = m.getBufferData(m.getFileID(loc));
if (buf.find('\t') != buf.find(" \n")) {
loc = m.getLocForStartOfFile(m.getFileID(loc));
size_t offset = 0;
llvm::StringRef s;
llvm::SmallVector<llvm::StringRef, 7> matches;
while (bad_ws.match(s = buf.drop_front(offset), &matches)) {
llvm::StringRef text = matches[0];
std::pair<size_t, size_t> m = bde_verify::csabase::mid_match(s, text);
size_t matchpos = offset + m.first;
offset = matchpos + text.size();
if (text[0] == '\t') {
d_analyser.report(loc.getLocWithOffset(matchpos),
check_name, "TAB01",
"Tab character%s0 in source")
<< static_cast<long>(text.size());
}
else {
d_analyser.report(loc.getLocWithOffset(matchpos),
check_name, "ESP01",
"Space%s0 at end of line")
<< static_cast<long>(text.size() - 1);
}
}
}
}
void subscribe(Analyser& analyser, Visitor&, PPObserver& observer)
// Hook up the callback functions.
{
observer.onOpenFile += files(analyser);
}
} // close anonymous namespace
// ----------------------------------------------------------------------------
static bde_verify::csabase::RegisterCheck c1(check_name, &subscribe);
<commit_msg>Rewrite whitespace errors (tabs are just replacedd with spaces, though).<commit_after>// csafmt_whitespace.cpp -*-C++-*-
// ----------------------------------------------------------------------------
#include <csabase_analyser.h>
#include <csabase_location.h>
#include <csabase_ppobserver.h>
#include <csabase_registercheck.h>
#include <csabase_util.h>
#include <llvm/Support/Regex.h>
#include <clang/Rewrite/Core/Rewriter.h>
#include <string>
#ident "$Id$"
// ----------------------------------------------------------------------------
static std::string const check_name("whitespace");
// ----------------------------------------------------------------------------
using clang::SourceLocation;
using clang::SourceManager;
using clang::SourceRange;
using bde_verify::csabase::Analyser;
using bde_verify::csabase::Location;
using bde_verify::csabase::PPObserver;
using bde_verify::csabase::Range;
using bde_verify::csabase::Visitor;
namespace
{
struct files
// Callback object for inspecting files.
{
Analyser& d_analyser; // Analyser object.
files(Analyser& analyser);
// Create a 'files' object, accessing the specified 'analyser'.
void operator()(SourceLocation loc,
std::string const &,
std::string const &);
// The file specified by 'loc' is examined for tab characters and
// trailing spaces.
};
files::files(Analyser& analyser)
: d_analyser(analyser)
{
}
llvm::Regex bad_ws("\t+| +\n", llvm::Regex::NoFlags);
void files::operator()(SourceLocation loc,
std::string const &,
std::string const &)
{
const SourceManager &m = d_analyser.manager();
llvm::StringRef buf = m.getBufferData(m.getFileID(loc));
if (buf.find('\t') != buf.find(" \n")) {
loc = m.getLocForStartOfFile(m.getFileID(loc));
size_t offset = 0;
llvm::StringRef s;
llvm::SmallVector<llvm::StringRef, 7> matches;
while (bad_ws.match(s = buf.drop_front(offset), &matches)) {
llvm::StringRef text = matches[0];
std::pair<size_t, size_t> m =
bde_verify::csabase::mid_match(s, text);
size_t matchpos = offset + m.first;
offset = matchpos + text.size();
SourceLocation sloc = loc.getLocWithOffset(matchpos);
if (text[0] == '\t') {
d_analyser.report(sloc, check_name, "TAB01",
"Tab character%s0 in source")
<< static_cast<long>(text.size());
d_analyser.rewriter().ReplaceText(
sloc, text.size(), std::string(text.size(), ' '));
}
else {
d_analyser.report(loc.getLocWithOffset(matchpos),
check_name, "ESP01",
"Space%s0 at end of line")
<< static_cast<long>(text.size() - 1);
d_analyser.rewriter().RemoveText(sloc, text.size() - 1);
}
}
}
}
void subscribe(Analyser& analyser, Visitor&, PPObserver& observer)
// Hook up the callback functions.
{
observer.onOpenFile += files(analyser);
}
} // close anonymous namespace
// ----------------------------------------------------------------------------
static bde_verify::csabase::RegisterCheck c1(check_name, &subscribe);
<|endoftext|>
|
<commit_before>/* cbr
* RandomMotionPath.cpp
*
* Copyright (c) 2009, Ewen Cheslack-Postava
* 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 cbr 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 "RandomMotionPath.hpp"
#include <algorithm>
#include <cmath>
#include "Random.hpp"
#ifndef PI
#define PI 3.14159f
#endif
namespace CBR {
static Vector3f UniformSampleSphere(float u1, float u2) {
float32 z = 1.f - 2.f * u1;
float32 r = sqrtf(std::max(0.f, 1.f - z*z));
float32 phi = 2.f * PI * u2;
float32 x = r * cosf(phi);
float32 y = r * sinf(phi);
return Vector3f(x, y, z);
}
RandomMotionPath::RandomMotionPath(const Time& start, const Time& end, const Vector3f& startpos, float32 speed, const Duration& update_period) {
MotionVector3f last_motion(start, startpos, Vector3f(0,0,0));
for(Time curtime = start; curtime < end; curtime += update_period) {
Vector3f curpos = last_motion.position(curtime);
Vector3f dir = UniformSampleSphere( randFloat(), randFloat() );
mUpdates.push_back(MotionVector3f(curtime, curpos, dir));
}
}
const MotionVector3f RandomMotionPath::initial() const {
assert( !mUpdates.empty() );
return mUpdates[0];
}
const MotionVector3f* RandomMotionPath::nextUpdate(const Time& curtime) const {
for(uint32 i = 0; i < mUpdates.size(); i++)
if (mUpdates[i].updateTime() > curtime) return &mUpdates[i];
return NULL;
}
} // namespace CBR
<commit_msg>Make RandomMotionPath offset its first update uniformly over the first update period so we get more even updates instead of everything updating at once. Also, update last_motion each time through the loop, which was not happening before.<commit_after>/* cbr
* RandomMotionPath.cpp
*
* Copyright (c) 2009, Ewen Cheslack-Postava
* 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 cbr 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 "RandomMotionPath.hpp"
#include <algorithm>
#include <cmath>
#include "Random.hpp"
#ifndef PI
#define PI 3.14159f
#endif
namespace CBR {
static Vector3f UniformSampleSphere(float u1, float u2) {
float32 z = 1.f - 2.f * u1;
float32 r = sqrtf(std::max(0.f, 1.f - z*z));
float32 phi = 2.f * PI * u2;
float32 x = r * cosf(phi);
float32 y = r * sinf(phi);
return Vector3f(x, y, z);
}
RandomMotionPath::RandomMotionPath(const Time& start, const Time& end, const Vector3f& startpos, float32 speed, const Duration& update_period) {
MotionVector3f last_motion(start, startpos, Vector3f(0,0,0));
mUpdates.push_back(last_motion);
Time offset_start = start + update_period * randFloat();
for(Time curtime = offset_start; curtime < end; curtime += update_period) {
Vector3f curpos = last_motion.position(curtime);
Vector3f dir = UniformSampleSphere( randFloat(), randFloat() );
last_motion = MotionVector3f(curtime, curpos, dir);
mUpdates.push_back(last_motion);
}
}
const MotionVector3f RandomMotionPath::initial() const {
assert( !mUpdates.empty() );
return mUpdates[0];
}
const MotionVector3f* RandomMotionPath::nextUpdate(const Time& curtime) const {
for(uint32 i = 0; i < mUpdates.size(); i++)
if (mUpdates[i].updateTime() > curtime) return &mUpdates[i];
return NULL;
}
} // namespace CBR
<|endoftext|>
|
<commit_before>/**
* \file
* \brief ThreadRoundRobinSchedulingTestCase class implementation
*
* \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* 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/.
*
* \date 2014-10-27
*/
#include "ThreadRoundRobinSchedulingTestCase.hpp"
#include "SequenceAsserter.hpp"
#include "distortos/StaticThread.hpp"
#include "distortos/ThisThread.hpp"
#include "distortos/architecture/InterruptMaskingLock.hpp"
namespace distortos
{
namespace test
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/
/// size of stack for test thread, bytes
constexpr size_t testThreadStackSize {192};
/// priority of test thread
constexpr uint8_t testThreadPriority {1};
/// number of test threads
constexpr size_t totalThreads {10};
/// number of loops in test thread
constexpr size_t loops {5};
/*---------------------------------------------------------------------------------------------------------------------+
| local functions' declarations
+---------------------------------------------------------------------------------------------------------------------*/
void thread(SequenceAsserter& sequenceAsserter, unsigned int sequencePoint, unsigned int sequenceStep);
/*---------------------------------------------------------------------------------------------------------------------+
| local types
+---------------------------------------------------------------------------------------------------------------------*/
/// type of test thread
using TestThread = decltype(makeStaticThread<testThreadStackSize>({}, thread,
std::ref(std::declval<SequenceAsserter&>()), std::declval<unsigned int>(), std::declval<unsigned int>()));
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Test thread.
*
* Marks the sequence point in SequenceAsserter and waits for context switch. This is repeated several times.
*
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] sequencePoint is the sequence point of this instance
* \param [in] sequenceStep is the step added to sequence point in each iteration of the loop
*/
void thread(SequenceAsserter& sequenceAsserter, const unsigned int sequencePoint, const unsigned int sequenceStep)
{
for (size_t i = 0; i < loops; ++i)
{
sequenceAsserter.sequencePoint(sequencePoint + i * sequenceStep);
// this loop waits for a context switch, which is detected by checking the time between subsequent reads of
// TickClock - if the thread is not preempted, max difference is 1 tick
auto previous = TickClock::now();
decltype(previous) now;
while ((now = TickClock::now()) - previous <= TickClock::duration{1})
previous = now;
}
}
/**
* \brief Builder of TestThread objects.
*
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] sequencePoint is the sequence point of this instance
* \param [in] sequenceStep is the step added to sequence point in each iteration of the loop
*
* \return constructed TestThread object
*/
TestThread makeTestThread(SequenceAsserter& sequenceAsserter, const unsigned int sequencePoint,
const unsigned int sequenceStep)
{
return makeStaticThread<testThreadStackSize>(testThreadPriority, thread, std::ref(sequenceAsserter),
static_cast<unsigned int>(sequencePoint), static_cast<unsigned int>(sequenceStep));
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
bool ThreadRoundRobinSchedulingTestCase::run_() const
{
SequenceAsserter sequenceAsserter;
std::array<TestThread, totalThreads> threads
{{
makeTestThread(sequenceAsserter, 0, totalThreads),
makeTestThread(sequenceAsserter, 1, totalThreads),
makeTestThread(sequenceAsserter, 2, totalThreads),
makeTestThread(sequenceAsserter, 3, totalThreads),
makeTestThread(sequenceAsserter, 4, totalThreads),
makeTestThread(sequenceAsserter, 5, totalThreads),
makeTestThread(sequenceAsserter, 6, totalThreads),
makeTestThread(sequenceAsserter, 7, totalThreads),
makeTestThread(sequenceAsserter, 8, totalThreads),
makeTestThread(sequenceAsserter, 9, totalThreads),
}};
volatile bool dummyThreadTerminate {};
// this thread is needed, because test threads need at least one other thread (which would preempt them) to
// exit their wait loop, so there is a problem with ending the very last iteration of the very last thread...
auto dummyThread = makeStaticThread<testThreadStackSize>(testThreadPriority,
[&dummyThreadTerminate]()
{
while (dummyThreadTerminate != true);
});
decltype(TickClock::now()) testStart;
{
architecture::InterruptMaskingLock interruptMaskingLock;
// wait for beginning of next tick - test threads should be started in the same tick
ThisThread::sleepFor({});
for (auto& thread : threads)
thread.start();
dummyThread.start();
testStart = TickClock::now();
}
for (auto& thread : threads)
thread.join();
const auto testDuration = TickClock::now() - testStart;
dummyThreadTerminate = true;
dummyThread.join();
if (sequenceAsserter.assertSequence(totalThreads * loops) == false)
return false;
// calculations need to take dummyThread into account - this is the "+ 1"
if (testDuration != scheduler::RoundRobinQuantum::getInitial() * (totalThreads + 1) * loops)
return false;
return true;
}
} // namespace test
} // namespace distortos
<commit_msg>test: reimplement test thread in ThreadRoundRobinSchedulingTestCase using statistics::getContextSwitchCount()<commit_after>/**
* \file
* \brief ThreadRoundRobinSchedulingTestCase class implementation
*
* \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* 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/.
*
* \date 2014-11-04
*/
#include "ThreadRoundRobinSchedulingTestCase.hpp"
#include "SequenceAsserter.hpp"
#include "distortos/StaticThread.hpp"
#include "distortos/ThisThread.hpp"
#include "distortos/statistics.hpp"
#include "distortos/architecture/InterruptMaskingLock.hpp"
namespace distortos
{
namespace test
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/
/// size of stack for test thread, bytes
constexpr size_t testThreadStackSize {192};
/// priority of test thread
constexpr uint8_t testThreadPriority {1};
/// number of test threads
constexpr size_t totalThreads {10};
/// number of loops in test thread
constexpr size_t loops {5};
/*---------------------------------------------------------------------------------------------------------------------+
| local functions' declarations
+---------------------------------------------------------------------------------------------------------------------*/
void thread(SequenceAsserter& sequenceAsserter, unsigned int sequencePoint, unsigned int sequenceStep);
/*---------------------------------------------------------------------------------------------------------------------+
| local types
+---------------------------------------------------------------------------------------------------------------------*/
/// type of test thread
using TestThread = decltype(makeStaticThread<testThreadStackSize>({}, thread,
std::ref(std::declval<SequenceAsserter&>()), std::declval<unsigned int>(), std::declval<unsigned int>()));
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Test thread.
*
* Marks the sequence point in SequenceAsserter and waits for context switch. This is repeated several times.
*
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] sequencePoint is the sequence point of this instance
* \param [in] sequenceStep is the step added to sequence point in each iteration of the loop
*/
void thread(SequenceAsserter& sequenceAsserter, const unsigned int sequencePoint, const unsigned int sequenceStep)
{
for (size_t i = 0; i < loops; ++i)
{
sequenceAsserter.sequencePoint(sequencePoint + i * sequenceStep);
const auto contextSwitchCount = statistics::getContextSwitchCount();
while (contextSwitchCount == statistics::getContextSwitchCount());
}
}
/**
* \brief Builder of TestThread objects.
*
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] sequencePoint is the sequence point of this instance
* \param [in] sequenceStep is the step added to sequence point in each iteration of the loop
*
* \return constructed TestThread object
*/
TestThread makeTestThread(SequenceAsserter& sequenceAsserter, const unsigned int sequencePoint,
const unsigned int sequenceStep)
{
return makeStaticThread<testThreadStackSize>(testThreadPriority, thread, std::ref(sequenceAsserter),
static_cast<unsigned int>(sequencePoint), static_cast<unsigned int>(sequenceStep));
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
bool ThreadRoundRobinSchedulingTestCase::run_() const
{
SequenceAsserter sequenceAsserter;
std::array<TestThread, totalThreads> threads
{{
makeTestThread(sequenceAsserter, 0, totalThreads),
makeTestThread(sequenceAsserter, 1, totalThreads),
makeTestThread(sequenceAsserter, 2, totalThreads),
makeTestThread(sequenceAsserter, 3, totalThreads),
makeTestThread(sequenceAsserter, 4, totalThreads),
makeTestThread(sequenceAsserter, 5, totalThreads),
makeTestThread(sequenceAsserter, 6, totalThreads),
makeTestThread(sequenceAsserter, 7, totalThreads),
makeTestThread(sequenceAsserter, 8, totalThreads),
makeTestThread(sequenceAsserter, 9, totalThreads),
}};
volatile bool dummyThreadTerminate {};
// this thread is needed, because test threads need at least one other thread (which would preempt them) to
// exit their wait loop, so there is a problem with ending the very last iteration of the very last thread...
auto dummyThread = makeStaticThread<testThreadStackSize>(testThreadPriority,
[&dummyThreadTerminate]()
{
while (dummyThreadTerminate != true);
});
decltype(TickClock::now()) testStart;
{
architecture::InterruptMaskingLock interruptMaskingLock;
// wait for beginning of next tick - test threads should be started in the same tick
ThisThread::sleepFor({});
for (auto& thread : threads)
thread.start();
dummyThread.start();
testStart = TickClock::now();
}
for (auto& thread : threads)
thread.join();
const auto testDuration = TickClock::now() - testStart;
dummyThreadTerminate = true;
dummyThread.join();
if (sequenceAsserter.assertSequence(totalThreads * loops) == false)
return false;
// calculations need to take dummyThread into account - this is the "+ 1"
if (testDuration != scheduler::RoundRobinQuantum::getInitial() * (totalThreads + 1) * loops)
return false;
return true;
}
} // namespace test
} // namespace distortos
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////
//
// The MIT License (MIT)
//
// STP - SFML TMX Parser
// Copyright (c) 2013-2014 Manuel Sabogal
//
// 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 "STP/Core/TileSet.hpp"
#include <stdexcept>
#include <cmath>
#include <string>
namespace tmx {
TileSet::TileSet() {}
TileSet::TileSet(unsigned int firstgid, const std::string& name, unsigned int tilewidth,
unsigned int tileheight, tmx::Image image, unsigned int spacing,
unsigned int margin, sf::Vector2i tileoffset) :
firstgid_(firstgid),
name_(name),
tilewidth_(tilewidth),
tileheight_(tileheight),
spacing_(spacing),
margin_(margin),
width_no_spacing_(0),
height_no_spacing_(0),
image_(image),
tileoffset_(tileoffset) {
unsigned int width_no_margin = image_.GetWidth() - (margin_ * 2);
unsigned int height_no_margin = image_.GetHeight() - (margin_ * 2);
if (spacing != 0) {
for (unsigned int i = 0; i <= width_no_margin; ++i) {
i += tilewidth + spacing_;
width_no_spacing_ += tilewidth;
}
for (unsigned int i = 0; i <= height_no_margin; ++i) {
i += tileheight + spacing_;
height_no_spacing_ += tileheight;
}
} else {
width_no_spacing_ = width_no_margin;
height_no_spacing_ = height_no_margin;
}
lastgid_ = firstgid + (width_no_spacing_ / tilewidth) * (height_no_spacing_ / tileheight) - 1;
// Add each tile to the TileSet
unsigned int tile_amount = lastgid_ - firstgid_ + 1;
sf::Vector2u cont;
sf::Vector2u tile_pos;
tiles_.reserve(tile_amount);
for (unsigned int i = 0; i < tile_amount; ++i) {
tile_pos.x = (cont.x * tilewidth_) + (spacing_ * i) + margin_;
tile_pos.y = (cont.y * tileheight_) + (spacing_ * i) + margin_;
sf::IntRect texture_rect(tile_pos.x, tile_pos.y, tilewidth_, tileheight_);
tiles_.push_back(tmx::TileSet::Tile(i, texture_rect, this));
cont.x = (cont.x + 1) % (width_no_spacing_ / tilewidth_);
if (cont.x == 0) cont.y += 1;
}
}
tmx::TileSet::Tile& TileSet::GetTile(unsigned int id) {
if (id >= tiles_.size()) {
char error[100];
sprintf(error, "Error: tile local id %u out of range.\n", id);
throw std::out_of_range(error);
}
return tiles_[id];
}
sf::IntRect TileSet::GetTextureRect(unsigned int id) const {
if (id >= tiles_.size()) {
char error[100];
sprintf(error, "Error: tile local id %u out of range.\n", id);
throw std::out_of_range(error);
}
return tiles_[id].GetTextureRect();
}
const sf::Texture* TileSet::GetTexture() const {
return image_.GetTexture();
}
const std::string& TileSet::GetName() const {
return name_;
}
const sf::Vector2i TileSet::GetTileOffSet() const {
return tileoffset_;
}
unsigned int TileSet::GetTileWidth() const {
return tilewidth_;
}
unsigned int TileSet::GetTileHeight() const {
return tileheight_;
}
unsigned int TileSet::GetFirstGID() const {
return firstgid_;
}
unsigned int TileSet::GetLastGID() const {
return lastgid_;
}
////////////////////////////////////////////////////////////
// TileSet::Tile implementation
////////////////////////////////////////////////////////////
TileSet::Tile::Tile(unsigned int id, sf::IntRect texture_rect, const tmx::TileSet* parent) :
id_(id),
texture_rect_(texture_rect) {
}
const sf::Texture* TileSet::Tile::GetTexture() const {
return parent_->GetTexture();
}
sf::IntRect TileSet::Tile::GetTextureRect() const {
return texture_rect_;
}
} // namespace tmx
<commit_msg>Properly parse tilesets with spacing<commit_after>////////////////////////////////////////////////////////////
//
// The MIT License (MIT)
//
// STP - SFML TMX Parser
// Copyright (c) 2013-2014 Manuel Sabogal
//
// 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 "STP/Core/TileSet.hpp"
#include <stdexcept>
#include <cmath>
#include <string>
namespace tmx {
TileSet::TileSet() {}
TileSet::TileSet(unsigned int firstgid, const std::string& name, unsigned int tilewidth,
unsigned int tileheight, tmx::Image image, unsigned int spacing,
unsigned int margin, sf::Vector2i tileoffset) :
firstgid_(firstgid),
name_(name),
tilewidth_(tilewidth),
tileheight_(tileheight),
spacing_(spacing),
margin_(margin),
width_no_spacing_(0),
height_no_spacing_(0),
image_(image),
tileoffset_(tileoffset) {
unsigned int width_no_margin = image_.GetWidth() - (margin_ * 2);
unsigned int height_no_margin = image_.GetHeight() - (margin_ * 2);
if (spacing != 0) {
for (unsigned int i = 0; i <= width_no_margin;) {
i += tilewidth + spacing_;
width_no_spacing_ += tilewidth;
}
for (unsigned int i = 0; i <= height_no_margin;) {
i += tileheight + spacing_;
height_no_spacing_ += tileheight;
}
} else {
width_no_spacing_ = width_no_margin;
height_no_spacing_ = height_no_margin;
}
lastgid_ = firstgid + (width_no_spacing_ / tilewidth) * (height_no_spacing_ / tileheight) - 1;
// Add each tile to the TileSet
unsigned int tile_amount = lastgid_ - firstgid_ + 1;
sf::Vector2u cont;
sf::Vector2u tile_pos;
tiles_.reserve(tile_amount);
for (unsigned int i = 0; i < tile_amount; ++i) {
tile_pos.x = (cont.x * tilewidth_) + (spacing_ * cont.x) + margin_;
tile_pos.y = (cont.y * tileheight_) + (spacing_ * cont.y) + margin_;
sf::IntRect texture_rect(tile_pos.x, tile_pos.y, tilewidth_, tileheight_);
tiles_.push_back(tmx::TileSet::Tile(i, texture_rect, this));
cont.x = (cont.x + 1) % (width_no_spacing_ / tilewidth_);
if (cont.x == 0) cont.y += 1;
}
}
tmx::TileSet::Tile& TileSet::GetTile(unsigned int id) {
if (id >= tiles_.size()) {
char error[100];
sprintf(error, "Error: tile local id %u out of range.\n", id);
throw std::out_of_range(error);
}
return tiles_[id];
}
sf::IntRect TileSet::GetTextureRect(unsigned int id) const {
if (id >= tiles_.size()) {
char error[100];
sprintf(error, "Error: tile local id %u out of range.\n", id);
throw std::out_of_range(error);
}
return tiles_[id].GetTextureRect();
}
const sf::Texture* TileSet::GetTexture() const {
return image_.GetTexture();
}
const std::string& TileSet::GetName() const {
return name_;
}
const sf::Vector2i TileSet::GetTileOffSet() const {
return tileoffset_;
}
unsigned int TileSet::GetTileWidth() const {
return tilewidth_;
}
unsigned int TileSet::GetTileHeight() const {
return tileheight_;
}
unsigned int TileSet::GetFirstGID() const {
return firstgid_;
}
unsigned int TileSet::GetLastGID() const {
return lastgid_;
}
////////////////////////////////////////////////////////////
// TileSet::Tile implementation
////////////////////////////////////////////////////////////
TileSet::Tile::Tile(unsigned int id, sf::IntRect texture_rect, const tmx::TileSet* parent) :
id_(id),
texture_rect_(texture_rect) {
}
const sf::Texture* TileSet::Tile::GetTexture() const {
return parent_->GetTexture();
}
sf::IntRect TileSet::Tile::GetTextureRect() const {
return texture_rect_;
}
} // namespace tmx
<|endoftext|>
|
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.
#ifndef SERVER_CONNECTION_HPP
#define SERVER_CONNECTION_HPP
#include <net/tcp/connection.hpp>
#include <rtc>
#include "request.hpp"
#include "response.hpp"
namespace server {
class Server;
class Connection;
using Connection_ptr = std::shared_ptr<Connection>;
class Connection {
private:
const static size_t BUFSIZE = 1460;
using Connection_ptr = net::tcp::Connection_ptr;
using buffer_t = net::tcp::buffer_t;
using OnData = net::tcp::Connection::ReadCallback;
using Disconnect = net::tcp::Connection::Disconnect;
using OnDisconnect = net::tcp::Connection::DisconnectCallback;
using OnClose = net::tcp::Connection::CloseCallback;
using OnError = net::tcp::Connection::ErrorCallback;
using TCPException = net::tcp::TCPException;
using OnPacketDropped = net::tcp::Connection::PacketDroppedCallback;
using Packet_ptr = net::tcp::Packet_ptr;
using OnConnection = std::function<void()>;
public:
Connection(Server&, Connection_ptr, size_t idx);
Request_ptr get_request() noexcept
{ return request_; }
Response_ptr get_response() noexcept
{ return response_; }
void close();
std::string to_string() const
{ return "Connection:[" + conn_->remote().to_string() + "]"; }
static void on_connection(OnConnection cb)
{ on_connection_ = cb; }
RTC::timestamp_t idle_since() const
{ return idle_since_; }
void close_tcp()
{
if(conn_->is_closing() == false)
conn_->close();
}
void timeout();
~Connection();
private:
Server& server_;
Connection_ptr conn_;
Request_ptr request_;
Response_ptr response_;
size_t idx_;
RTC::timestamp_t idle_since_;
static size_t PAYLOAD_LIMIT;
static OnConnection on_connection_;
void on_data(buffer_t, size_t);
void on_disconnect(Connection_ptr, Disconnect);
void on_error(TCPException);
void on_packet_dropped(Packet_ptr, std::string);
void update_idle()
{ idle_since_ = RTC::now(); }
}; // < server::Connection
}; // < server
#endif
<commit_msg>connection: Changed Connection::idle_since signature<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.
#ifndef SERVER_CONNECTION_HPP
#define SERVER_CONNECTION_HPP
#include <net/tcp/connection.hpp>
#include <rtc>
#include "request.hpp"
#include "response.hpp"
namespace server {
class Server;
class Connection;
using Connection_ptr = std::shared_ptr<Connection>;
class Connection {
private:
const static size_t BUFSIZE = 1460;
using Connection_ptr = net::tcp::Connection_ptr;
using buffer_t = net::tcp::buffer_t;
using OnData = net::tcp::Connection::ReadCallback;
using Disconnect = net::tcp::Connection::Disconnect;
using OnDisconnect = net::tcp::Connection::DisconnectCallback;
using OnClose = net::tcp::Connection::CloseCallback;
using OnError = net::tcp::Connection::ErrorCallback;
using TCPException = net::tcp::TCPException;
using OnPacketDropped = net::tcp::Connection::PacketDroppedCallback;
using Packet_ptr = net::tcp::Packet_ptr;
using OnConnection = std::function<void()>;
public:
Connection(Server&, Connection_ptr, size_t idx);
Request_ptr get_request() noexcept
{ return request_; }
Response_ptr get_response() noexcept
{ return response_; }
void close();
std::string to_string() const
{ return "Connection:[" + conn_->remote().to_string() + "]"; }
static void on_connection(OnConnection cb)
{ on_connection_ = cb; }
RTC::timestamp_t idle_since() const noexcept
{ return idle_since_; }
void close_tcp()
{
if(conn_->is_closing() == false)
conn_->close();
}
void timeout();
~Connection();
private:
Server& server_;
Connection_ptr conn_;
Request_ptr request_;
Response_ptr response_;
size_t idx_;
RTC::timestamp_t idle_since_;
static size_t PAYLOAD_LIMIT;
static OnConnection on_connection_;
void on_data(buffer_t, size_t);
void on_disconnect(Connection_ptr, Disconnect);
void on_error(TCPException);
void on_packet_dropped(Packet_ptr, std::string);
void update_idle()
{ idle_since_ = RTC::now(); }
}; // < server::Connection
}; // < server
#endif
<|endoftext|>
|
<commit_before>// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "osfhandle.h"
#include <io.h>
#define U_I18N_IMPLEMENTATION
#include "third_party/icu/source/common/unicode/ubidi.h"
#include "third_party/icu/source/common/unicode/uchar.h"
#include "third_party/icu/source/common/unicode/uidna.h"
#include "third_party/icu/source/common/unicode/unistr.h"
#include "third_party/icu/source/common/unicode/unorm.h"
#include "third_party/icu/source/common/unicode/urename.h"
#include "third_party/icu/source/common/unicode/ustring.h"
#include "third_party/icu/source/i18n/unicode/measfmt.h"
#include "third_party/icu/source/i18n/unicode/translit.h"
#include "third_party/icu/source/i18n/unicode/ucsdet.h"
#include "third_party/icu/source/i18n/unicode/ulocdata.h"
#include "third_party/icu/source/i18n/unicode/uregex.h"
#include "third_party/icu/source/i18n/unicode/uspoof.h"
#include "third_party/icu/source/i18n/unicode/usearch.h"
#include "v8-profiler.h"
#include "v8-inspector.h"
namespace node {
int open_osfhandle(intptr_t osfhandle, int flags) {
return _open_osfhandle(osfhandle, flags);
}
int close(int fd) {
return _close(fd);
}
void ReferenceSymbols() {
// Following symbols are used by electron.exe but got stripped by compiler,
// by using the symbols we can force compiler to keep the objects in node.dll,
// thus electron.exe can link with the exported symbols.
// v8_profiler symbols:
v8::TracingCpuProfiler::Create(nullptr);
// v8_inspector symbols:
reinterpret_cast<v8_inspector::V8InspectorSession*>(nullptr)->
canDispatchMethod(v8_inspector::StringView());
reinterpret_cast<v8_inspector::V8InspectorClient*>(nullptr)->unmuteMetrics(0);
// icu symbols:
u_errorName(U_ZERO_ERROR);
ubidi_setPara(nullptr, nullptr, 0, 0, nullptr, nullptr);
ucsdet_getName(nullptr, nullptr);
uidna_openUTS46(UIDNA_CHECK_BIDI, nullptr);
ulocdata_close(nullptr);
unorm_normalize(nullptr, 0, UNORM_NFC, 0, nullptr, 0, nullptr);
uregex_matches(nullptr, 0, nullptr);
uspoof_open(nullptr);
usearch_setPattern(nullptr, nullptr, 0, nullptr);
usearch_setPattern(nullptr, nullptr, 0, nullptr);
UMeasureFormatWidth width = UMEASFMT_WIDTH_WIDE;
UErrorCode status = U_ZERO_ERROR;
icu::MeasureFormat format(icu::Locale::getRoot(), width, status);
reinterpret_cast<icu::Transliterator*>(nullptr)->clone();
}
} // namespace node
<commit_msg>Fix linking error with icu symbols<commit_after>// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "osfhandle.h"
#include <io.h>
#define U_I18N_IMPLEMENTATION
#include "third_party/icu/source/common/unicode/ubidi.h"
#include "third_party/icu/source/common/unicode/uchar.h"
#include "third_party/icu/source/common/unicode/uidna.h"
#include "third_party/icu/source/common/unicode/unistr.h"
#include "third_party/icu/source/common/unicode/unorm.h"
#include "third_party/icu/source/common/unicode/urename.h"
#include "third_party/icu/source/common/unicode/ustring.h"
#include "third_party/icu/source/i18n/unicode/dtitvfmt.h"
#include "third_party/icu/source/i18n/unicode/measfmt.h"
#include "third_party/icu/source/i18n/unicode/translit.h"
#include "third_party/icu/source/i18n/unicode/ucsdet.h"
#include "third_party/icu/source/i18n/unicode/ulocdata.h"
#include "third_party/icu/source/i18n/unicode/uregex.h"
#include "third_party/icu/source/i18n/unicode/uspoof.h"
#include "third_party/icu/source/i18n/unicode/usearch.h"
#include "v8-profiler.h"
#include "v8-inspector.h"
namespace node {
int open_osfhandle(intptr_t osfhandle, int flags) {
return _open_osfhandle(osfhandle, flags);
}
int close(int fd) {
return _close(fd);
}
void ReferenceSymbols() {
// Following symbols are used by electron.exe but got stripped by compiler,
// by using the symbols we can force compiler to keep the objects in node.dll,
// thus electron.exe can link with the exported symbols.
// v8_profiler symbols:
v8::TracingCpuProfiler::Create(nullptr);
// v8_inspector symbols:
reinterpret_cast<v8_inspector::V8InspectorSession*>(nullptr)->
canDispatchMethod(v8_inspector::StringView());
reinterpret_cast<v8_inspector::V8InspectorClient*>(nullptr)->unmuteMetrics(0);
// icu symbols:
u_errorName(U_ZERO_ERROR);
ubidi_setPara(nullptr, nullptr, 0, 0, nullptr, nullptr);
ucsdet_getName(nullptr, nullptr);
uidna_openUTS46(UIDNA_CHECK_BIDI, nullptr);
ulocdata_close(nullptr);
unorm_normalize(nullptr, 0, UNORM_NFC, 0, nullptr, 0, nullptr);
uregex_matches(nullptr, 0, nullptr);
uspoof_open(nullptr);
usearch_setPattern(nullptr, nullptr, 0, nullptr);
usearch_setPattern(nullptr, nullptr, 0, nullptr);
UMeasureFormatWidth width = UMEASFMT_WIDTH_WIDE;
UErrorCode status = U_ZERO_ERROR;
icu::MeasureFormat format(icu::Locale::getRoot(), width, status);
icu::DateIntervalFormat::createInstance(UnicodeString(),
icu::Locale::getRoot(), status);
reinterpret_cast<icu::Transliterator*>(nullptr)->clone();
}
} // namespace node
<|endoftext|>
|
<commit_before>/*
* Appcelerator Kroll - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.
*/
#include "binding.h"
namespace kroll
{
StaticBoundObject::StaticBoundObject()
{
}
StaticBoundObject::~StaticBoundObject()
{
ScopedLock lock(&mutex);
std::map<std::string, Value*>::iterator iter = properties.begin();
while (iter != properties.end())
{
KR_DECREF(iter->second);
iter++;
}
}
Value* StaticBoundObject::Get(const char *name)
{
ScopedLock lock(&mutex);
std::map<std::string, Value*>::iterator iter;
iter = properties.find(name);
if (iter != properties.end()) {
KR_ADDREF(iter->second);
return iter->second;
}
return Value::Undefined();
}
void StaticBoundObject::Set(const char *name, Value* value)
{
ScopedLock lock(&mutex);
KR_ADDREF(value);
this->UnSet(name);
this->properties[name] = value;
}
void StaticBoundObject::UnSet(const char *name)
{
ScopedLock lock(&mutex);
std::map<std::string, Value*>::iterator iter = this->properties.find(name);
if (this->properties.end() != iter)
{
KR_DECREF(iter->second);
this->properties.erase(iter);
}
}
void StaticBoundObject::GetPropertyNames(std::vector<const char *> *property_names)
{
ScopedLock lock(&mutex);
std::map<std::string, Value*>::iterator iter = properties.begin();
while (iter != properties.end())
{
property_names->push_back(strdup(iter->first.c_str()));
iter++;
}
}
void StaticBoundObject::SetObject(const char *name, BoundObject* object)
{
Value* obj_val = new Value(object);
this->Set(name, obj_val);
KR_DECREF(obj_val);
}
}
KROLL_API kroll::RefCounted* CreateEmptyBoundObject()
{
return new kroll::StaticBoundObject();
}
<commit_msg>Add necessary include<commit_after>/*
* Appcelerator Kroll - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.
*/
#include "binding.h"
#include <cstring>
namespace kroll
{
StaticBoundObject::StaticBoundObject()
{
}
StaticBoundObject::~StaticBoundObject()
{
ScopedLock lock(&mutex);
std::map<std::string, Value*>::iterator iter = properties.begin();
while (iter != properties.end())
{
KR_DECREF(iter->second);
iter++;
}
}
Value* StaticBoundObject::Get(const char *name)
{
ScopedLock lock(&mutex);
std::map<std::string, Value*>::iterator iter;
iter = properties.find(name);
if (iter != properties.end()) {
KR_ADDREF(iter->second);
return iter->second;
}
return Value::Undefined();
}
void StaticBoundObject::Set(const char *name, Value* value)
{
ScopedLock lock(&mutex);
KR_ADDREF(value);
this->UnSet(name);
this->properties[name] = value;
}
void StaticBoundObject::UnSet(const char *name)
{
ScopedLock lock(&mutex);
std::map<std::string, Value*>::iterator iter = this->properties.find(name);
if (this->properties.end() != iter)
{
KR_DECREF(iter->second);
this->properties.erase(iter);
}
}
void StaticBoundObject::GetPropertyNames(std::vector<const char *> *property_names)
{
ScopedLock lock(&mutex);
std::map<std::string, Value*>::iterator iter = properties.begin();
while (iter != properties.end())
{
property_names->push_back(strdup(iter->first.c_str()));
iter++;
}
}
void StaticBoundObject::SetObject(const char *name, BoundObject* object)
{
Value* obj_val = new Value(object);
this->Set(name, obj_val);
KR_DECREF(obj_val);
}
}
KROLL_API kroll::RefCounted* CreateEmptyBoundObject()
{
return new kroll::StaticBoundObject();
}
<|endoftext|>
|
<commit_before>/**
* Clever programming language
* Copyright (c) Clever Team
*
* This file is distributed under the MIT license. See LICENSE for details.
*/
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include "core/clever.h"
#include "core/cstring.h"
#include "core/value.h"
namespace clever {
jmp_buf fatal_error;
/**
* Errors and stuff.
*/
#ifdef CLEVER_DEBUG
void clever_assert_(const char* file, const char* function, long line, const char* expr,
int hypothesis, const char* format, ...) {
va_list vl;
std::ostringstream out;
if (!hypothesis) {
va_start(vl, format);
::printf("clever: Assertion '%s' failed. File: %s Line: %ld Function: %s.\n\t", expr, file, line, function);
vsprintf(out, format, vl);
va_end(vl);
std::cerr << out.str() << std::endl;
std::abort();
}
}
#endif
/**
* Throws an error message and abort the VM execution
*/
void clever_error(const char* format, ...) {
va_list vl;
va_start(vl, format);
vprintfln(format, vl);
va_end(vl);
}
/**
* Throws a fatal error message and abort the VM execution
*/
void clever_fatal(const char* format, ...) {
va_list vl;
va_start(vl, format);
vprintfln(format, vl);
va_end(vl);
CLEVER_EXIT_FATAL();
}
/**
* Formatter
*/
void vsprintf(std::ostringstream& outstr, const char* format, va_list ap) {
char* chr = const_cast<char*>(format);
if (!chr) {
return;
}
while (*chr) {
/* Check for escape %% */
if (*chr != '%' || *++chr == '%') {
outstr << *chr++;
continue;
}
switch (*chr) {
/* int */
case 'i':
outstr << va_arg(ap, int);
break;
/* double */
case 'd':
outstr << va_arg(ap, double);
break;
/* size_t */
case 'N':
outstr << va_arg(ap, size_t);
break;
/* int64_t */
case 'l':
outstr << va_arg(ap, int64_t);
break;
/* const CString* */
case 'S':
outstr << *va_arg(ap, const CString*);
break;
/* const char* */
case 's':
outstr << va_arg(ap, const char*);
break;
/* Value* */
/*
case 'v':
outstr << va_arg(ap, Value*)->toString();
break;*/
}
++chr;
}
}
void vprintfln(const char* format, va_list args) {
std::ostringstream out;
vsprintf(out, format, args);
std::cout << out.str() << std::endl;
}
void printfln(const char* format, ...) {
va_list args;
va_start(args, format);
vprintfln(format, args);
va_end(args);
}
void sprintf(std::ostringstream& outstr, const char* format, ...) {
va_list args;
va_start(args, format);
vsprintf(outstr, format, args);
va_end(args);
}
void printf(const char* format, ...) {
std::ostringstream out;
va_list args;
va_start(args, format);
vsprintf(out, format, args);
std::cout << out.str();
va_end(args);
}
// Verify a vector of Values conform to a specific set of types (and implicit length)
// Typespec:
// f - a function
// s - a string
// i - a integral number
// d - a double precision number
// a - array
// b - boolean
// n - numeric
// c - current object
// * - any type
// Example:
// clever_check_args("sii") - check that the first arg is string and the next two are integral
// clever_check_args("sdi") - check that the first arg is a string, the second a double and the third an integer
// clever_check_args("*si") - ignore the first arg, verify the second and third
// NOTE:
// We could pass in another parameter to cause a fatality/throw exception on error here, for now fail gracefully
bool check_args(const ::std::vector<Value*>& args, const char* typespec, const Type* type) {
size_t argslen = args.size();
// Void arguments checking
if (typespec == NULL) {
return argslen > 0;
}
clever_assert_not_null(typespec);
size_t speclen = ::strlen(typespec);
if (speclen != argslen) {
return false;
}
for (size_t arg = 0; arg < speclen; ++arg) {
if (!(arg < speclen && argslen > arg)) {
return false;
}
const Type* const arg_type = args[arg]->getType();
switch (typespec[arg]) {
// Function
case 'f':
if (arg_type != CLEVER_FUNC_TYPE) {
return false;
}
break;
// String
case 's':
if (arg_type != CLEVER_STR_TYPE) {
return false;
}
break;
// Integer
case 'i':
if (arg_type != CLEVER_INT_TYPE) {
return false;
}
break;
// Double
case 'd':
if (arg_type != CLEVER_DOUBLE_TYPE) {
return false;
}
break;
// Array
case 'a':
if (arg_type != CLEVER_ARRAY_TYPE) {
return false;
}
break;
// Boolean
case 'b':
if (arg_type != CLEVER_BOOL_TYPE) {
return false;
}
break;
// Number
case 'n':
if ((arg_type != CLEVER_DOUBLE_TYPE)
&& (arg_type != CLEVER_INT_TYPE)) {
return false;
}
break;
// Current type
case 'c':
if (arg_type != type) {
return false;
}
break;
// Any type
case '*':
break;
default:
/** Value::verify encountered an unexpected type specification @ arg **/
break;
}
}
return true;
}
} // clever
<commit_msg>+map type in check_args<commit_after>/**
* Clever programming language
* Copyright (c) Clever Team
*
* This file is distributed under the MIT license. See LICENSE for details.
*/
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include "core/clever.h"
#include "core/cstring.h"
#include "core/value.h"
namespace clever {
jmp_buf fatal_error;
/**
* Errors and stuff.
*/
#ifdef CLEVER_DEBUG
void clever_assert_(const char* file, const char* function, long line, const char* expr,
int hypothesis, const char* format, ...) {
va_list vl;
std::ostringstream out;
if (!hypothesis) {
va_start(vl, format);
::printf("clever: Assertion '%s' failed. File: %s Line: %ld Function: %s.\n\t", expr, file, line, function);
vsprintf(out, format, vl);
va_end(vl);
std::cerr << out.str() << std::endl;
std::abort();
}
}
#endif
/**
* Throws an error message and abort the VM execution
*/
void clever_error(const char* format, ...) {
va_list vl;
va_start(vl, format);
vprintfln(format, vl);
va_end(vl);
}
/**
* Throws a fatal error message and abort the VM execution
*/
void clever_fatal(const char* format, ...) {
va_list vl;
va_start(vl, format);
vprintfln(format, vl);
va_end(vl);
CLEVER_EXIT_FATAL();
}
/**
* Formatter
*/
void vsprintf(std::ostringstream& outstr, const char* format, va_list ap) {
char* chr = const_cast<char*>(format);
if (!chr) {
return;
}
while (*chr) {
/* Check for escape %% */
if (*chr != '%' || *++chr == '%') {
outstr << *chr++;
continue;
}
switch (*chr) {
/* int */
case 'i':
outstr << va_arg(ap, int);
break;
/* double */
case 'd':
outstr << va_arg(ap, double);
break;
/* size_t */
case 'N':
outstr << va_arg(ap, size_t);
break;
/* int64_t */
case 'l':
outstr << va_arg(ap, int64_t);
break;
/* const CString* */
case 'S':
outstr << *va_arg(ap, const CString*);
break;
/* const char* */
case 's':
outstr << va_arg(ap, const char*);
break;
/* Value* */
/*
case 'v':
outstr << va_arg(ap, Value*)->toString();
break;*/
}
++chr;
}
}
void vprintfln(const char* format, va_list args) {
std::ostringstream out;
vsprintf(out, format, args);
std::cout << out.str() << std::endl;
}
void printfln(const char* format, ...) {
va_list args;
va_start(args, format);
vprintfln(format, args);
va_end(args);
}
void sprintf(std::ostringstream& outstr, const char* format, ...) {
va_list args;
va_start(args, format);
vsprintf(outstr, format, args);
va_end(args);
}
void printf(const char* format, ...) {
std::ostringstream out;
va_list args;
va_start(args, format);
vsprintf(out, format, args);
std::cout << out.str();
va_end(args);
}
// Verify a vector of Values conform to a specific set of types (and implicit length)
// Typespec:
// f - a function
// s - a string
// i - a integral number
// d - a double precision number
// a - array
// m - map
// b - boolean
// n - numeric
// c - current object
// * - any type
// Example:
// clever_check_args("sii") - check that the first arg is string and the next two are integral
// clever_check_args("sdi") - check that the first arg is a string, the second a double and the third an integer
// clever_check_args("*si") - ignore the first arg, verify the second and third
// NOTE:
// We could pass in another parameter to cause a fatality/throw exception on error here, for now fail gracefully
bool check_args(const ::std::vector<Value*>& args, const char* typespec, const Type* type) {
size_t argslen = args.size();
// Void arguments checking
if (typespec == NULL) {
return argslen > 0;
}
clever_assert_not_null(typespec);
size_t speclen = ::strlen(typespec);
if (speclen != argslen) {
return false;
}
for (size_t arg = 0; arg < speclen; ++arg) {
if (!(arg < speclen && argslen > arg)) {
return false;
}
const Type* const arg_type = args[arg]->getType();
switch (typespec[arg]) {
// Function
case 'f':
if (arg_type != CLEVER_FUNC_TYPE) {
return false;
}
break;
// String
case 's':
if (arg_type != CLEVER_STR_TYPE) {
return false;
}
break;
// Integer
case 'i':
if (arg_type != CLEVER_INT_TYPE) {
return false;
}
break;
// Double
case 'd':
if (arg_type != CLEVER_DOUBLE_TYPE) {
return false;
}
break;
// Array
case 'a':
if (arg_type != CLEVER_ARRAY_TYPE) {
return false;
}
break;
// Map
case 'm':
if (arg_type != CLEVER_MAP_TYPE) {
return false;
}
break;
// Boolean
case 'b':
if (arg_type != CLEVER_BOOL_TYPE) {
return false;
}
break;
// Number
case 'n':
if ((arg_type != CLEVER_DOUBLE_TYPE)
&& (arg_type != CLEVER_INT_TYPE)) {
return false;
}
break;
// Current type
case 'c':
if (arg_type != type) {
return false;
}
break;
// Any type
case '*':
break;
default:
/** Value::verify encountered an unexpected type specification @ arg **/
break;
}
}
return true;
}
} // clever
<|endoftext|>
|
<commit_before>/* Copyright (C) 2012-2017 IBM Corp.
* This program is 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 accompanying LICENSE file.
*/
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <NTL/BasicThreadPool.h>
NTL_CLIENT
#include "EncryptedArray.h"
#include "FHE.h"
#include "intraSlot.h"
#include "binaryArith.h"
#ifdef DEBUG_PRINTOUT
#include "debugging.h"
#endif
// define flags FLAG_PRINT_ZZX, FLAG_PRINT_POLY, FLAG_PRINT_VEC, functions
// decryptAndPrint(ostream, ctxt, sk, ea, flags)
// decryptAndCompare(ctxt, sk, ea, pa);
static std::vector<zzX> unpackSlotEncoding; // a global variable
static bool verbose=false;
static long mValues[][15] = {
// { p, phi(m), m, d, m1, m2, m3, g1, g2, g3, ord1,ord2,ord3, B,c}
{ 2, 48, 105, 12, 3, 35, 0, 71, 76, 0, 2, 2, 0, 25, 2},
{ 2 , 600, 1023, 10, 11, 93, 0, 838, 584, 0, 10, 6, 0, 25, 2},
{ 2, 2304, 4641, 24, 7, 3,221, 3979, 3095, 3760, 6, 2, -8, 25, 3},
{ 2, 15004, 15709, 22, 23,683, 0, 4099, 13663, 0, 22, 31, 0, 25, 3},
{ 2, 27000, 32767, 15, 31, 7, 151, 11628, 28087,25824, 30, 6, -10, 28, 4}
};
void test15for4(FHESecKey& secKey);
void testProduct(FHESecKey& secKey, long bitSize, long outSize,
bool bootstrap = false);
int main(int argc, char *argv[])
{
ArgMapping amap;
long prm=1;
amap.arg("prm", prm, "parameter size (0-tiny,...,4-huge)");
long bitSize = 5;
amap.arg("bitSize", bitSize, "bitSize of input integers (<=32)");
long outSize = 0;
amap.arg("outSize", outSize, "bitSize of output integers", "as many as needed");
long nTests = 3;
amap.arg("nTests", nTests, "number of tests to run");
bool bootstrap = false;
amap.arg("bootstrap", bootstrap, "test multiplication with bootstrapping");
long seed=0;
amap.arg("seed", seed, "PRG seed");
long nthreads=1;
amap.arg("nthreads", nthreads, "number of threads");
amap.arg("verbose", verbose, "print more information");
amap.parse(argc, argv);
assert(prm >= 0 && prm < 5);
if (seed) NTL::SetSeed(ZZ(seed));
if (nthreads>1) NTL::SetNumThreads(nthreads);
if (bitSize<=0) bitSize=5;
else if (bitSize>32) bitSize=32;
long* vals = mValues[prm];
long p = vals[0];
// long phim = vals[1];
long m = vals[2];
NTL::Vec<long> mvec;
append(mvec, vals[4]);
if (vals[5]>1) append(mvec, vals[5]);
if (vals[6]>1) append(mvec, vals[6]);
std::vector<long> gens;
gens.push_back(vals[7]);
if (vals[8]>1) gens.push_back(vals[8]);
if (vals[9]>1) gens.push_back(vals[9]);
std::vector<long> ords;
ords.push_back(vals[10]);
if (abs(vals[11])>1) ords.push_back(vals[11]);
if (abs(vals[12])>1) ords.push_back(vals[12]);
long B = vals[13];
long c = vals[14];
// Compute the number of levels
long L;
if (bootstrap) L=30; // that should be enough
else {
double nBits =
(outSize>0 && outSize<2*bitSize)? outSize : (2*bitSize);
double three4twoLvls = log(nBits/2) / log(1.5);
double add2NumsLvls = log(nBits) / log(2.0);
L = 3 + ceil(three4twoLvls + add2NumsLvls);
}
if (verbose) {
cout <<"input bitSize="<<bitSize<<", output size bound="<<outSize
<<", running "<<nTests<<" tests for each function\n";
if (nthreads>1) cout << " using "<<NTL::AvailableThreads()<<" threads\n";
cout << "computing key-independent tables..." << std::flush;
}
FHEcontext context(m, p, /*r=*/1, gens, ords);
context.bitsPerLevel = B;
buildModChain(context, L, c,/*extraBits=*/8);
if (bootstrap) {
context.makeBootstrappable(mvec, /*t=*/0,
/*flag=*/false, /*cacheType=DCRT*/2);
}
buildUnpackSlotEncoding(unpackSlotEncoding, *context.ea);
if (verbose) {
cout << " done.\n";
context.zMStar.printout();
cout << " L="<<L<<", B="<<B<<endl;
cout << "\ncomputing key-dependent tables..." << std::flush;
}
FHESecKey secKey(context);
secKey.GenSecKey(/*Hweight=*/128);
addSome1DMatrices(secKey); // compute key-switching matrices
addFrbMatrices(secKey);
if (bootstrap) secKey.genRecryptData();
if (verbose) cout << " done\n";
activeContext = &context; // make things a little easier sometimes
#ifdef DEBUG_PRINTOUT
dbgEa = (EncryptedArray*) context.ea;
dbgKey = &secKey;
#endif
for (long i=0; i<nTests; i++)
test15for4(secKey);
cout << " *** test15for4 PASS ***\n";
for (long i=0; i<nTests; i++)
testProduct(secKey, bitSize, outSize, bootstrap);
cout << " *** testProduct PASS ***\n";
if (verbose) printAllTimers(cout);
return 0;
}
void test15for4(FHESecKey& secKey)
{
std::vector<Ctxt> inBuf(15, Ctxt(secKey));
std::vector<Ctxt*> inPtrs(15, nullptr);
std::vector<Ctxt> outBuf(5, Ctxt(secKey));
long sum=0;
std::string inputBits = "(";
for (int i=0; i<15; i++) {
if (NTL::RandomBnd(10)>0) { // leave empty with small probability
inPtrs[i] = &(inBuf[i]);
long bit = NTL::RandomBnd(2); // a random bit
secKey.Encrypt(inBuf[i], ZZX(bit));
inputBits += std::to_string(bit) + ",";
sum += bit;
}
else inputBits += "-,";
}
inputBits += ")";
// Add these bits
long numOutputs
= fifteenOrLess4Four(CtPtrs_vectorCt(outBuf), CtPtrs_vectorPt(inPtrs));
// Check the result
long sum2=0;
for (int i=0; i<numOutputs; i++) {
ZZX poly;
secKey.Decrypt(poly, outBuf[i]);
sum2 += to_long(ConstTerm(poly)) << i;
}
if (sum != sum2) {
cout << "15to4 error: inputs="<<inputBits<<", sum="<<sum;
cout << " but sum2="<<sum2<<endl;
exit(0);
}
else if (verbose)
cout << "15to4 succeeded, sum"<<inputBits<<"="<<sum2<<endl;
}
void testProduct(FHESecKey& secKey, long bitSize, long outSize,
bool bootstrap)
{
const EncryptedArray& ea = *(secKey.getContext().ea);
long mask = (outSize? ((1L<<outSize)-1) : -1);
// Choose two random n-bit integers
long pa = RandomBits_long(bitSize);
long pb = RandomBits_long(bitSize);
// Encrypt the individual bits
NTL::Vec<Ctxt> eProduct, enca, encb;
resize(enca, bitSize, Ctxt(secKey));
resize(encb, bitSize, Ctxt(secKey));
for (long i=0; i<bitSize; i++) {
secKey.Encrypt(enca[i], ZZX((pa>>i)&1));
secKey.Encrypt(encb[i], ZZX((pb>>i)&1));
if (bootstrap) { // put them at a lower level
enca[i].modDownToLevel(5);
encb[i].modDownToLevel(5);
}
}
// Test positive multiplication
vector<long> slots;
{CtPtrs_VecCt eep(eProduct); // A wrappers around the output vector
multTwoNumbers(eep,CtPtrs_VecCt(enca),CtPtrs_VecCt(encb),/*negative=*/false,
outSize, &unpackSlotEncoding);
decryptBinaryNums(slots, eep, secKey, ea);
} // get rid of the wrapper
long pProd = pa*pb;
if (slots[0] != ((pa*pb)&mask)) {
cout << "Positive product error: pa="<<pa<<", pb="<<pb
<< ", but product="<<slots[0]
<< " (should be "<<pProd<<'&'<<mask<<'='<<(pProd&mask)<<")\n";
exit(0);
}
else if (verbose) {
cout << "positive product succeeded: ";
if (outSize) cout << "bottom "<<outSize<<" bits of ";
cout << pa<<"*"<<pb<<"="<<slots[0]<<endl;
}
// Test negative multiplication
secKey.Encrypt(encb[bitSize-1], ZZX(1));
decryptBinaryNums(slots, CtPtrs_VecCt(encb), secKey, ea, /*negative=*/true);
pb = slots[0];
eProduct.kill();
{CtPtrs_VecCt eep(eProduct); // A wrappers around the output vector
multTwoNumbers(eep,CtPtrs_VecCt(enca),CtPtrs_VecCt(encb),/*negative=*/true,
outSize, &unpackSlotEncoding);
decryptBinaryNums(slots, eep, secKey, ea, /*negative=*/true);
} // get rid of the wrapper
pProd = pa*pb;
if ((slots[0]&mask) != (pProd&mask)) {
cout << "Negative product error: pa="<<pa<<", pb="<<pb
<< ", but product="<<slots[0]
<< " (should be "<<pProd<<'&'<<mask<<'='<<(pProd&mask)<<")\n";
exit(0);
}
else if (verbose) {
cout << "negative product succeeded: ";
if (outSize) cout << "bottom "<<outSize<<" bits of ";
cout << pa<<"*"<<pb<<"="<<slots[0]<<endl;
}
#ifdef DEBUG_PRINTOUT
const Ctxt* minCtxt = nullptr;
long minLvl=1000;
for (const Ctxt& c: eProduct) {
long lvl = c.findBaseLevel();
if (lvl < minLvl) {
minCtxt = &c;
minLvl = lvl;
}
}
decryptAndPrint((cout<<" after multiplication: "), *minCtxt, secKey, ea,0);
cout << endl;
#endif
}
<commit_msg>moretesting options for binaryArith<commit_after>/* Copyright (C) 2012-2017 IBM Corp.
* This program is 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 accompanying LICENSE file.
*/
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <NTL/BasicThreadPool.h>
NTL_CLIENT
#include "EncryptedArray.h"
#include "FHE.h"
#include "intraSlot.h"
#include "binaryArith.h"
#ifdef DEBUG_PRINTOUT
#include "debugging.h"
#endif
// define flags FLAG_PRINT_ZZX, FLAG_PRINT_POLY, FLAG_PRINT_VEC, functions
// decryptAndPrint(ostream, ctxt, sk, ea, flags)
// decryptAndCompare(ctxt, sk, ea, pa);
static std::vector<zzX> unpackSlotEncoding; // a global variable
static bool verbose=false;
static long mValues[][15] = {
// { p, phi(m), m, d, m1, m2, m3, g1, g2, g3, ord1,ord2,ord3, B,c}
{ 2, 48, 105, 12, 3, 35, 0, 71, 76, 0, 2, 2, 0, 25, 2},
{ 2 , 600, 1023, 10, 11, 93, 0, 838, 584, 0, 10, 6, 0, 25, 2},
{ 2, 2304, 4641, 24, 7, 3,221, 3979, 3095, 3760, 6, 2, -8, 25, 3},
{ 2, 5460, 8193, 26,8193, 0, 0, 46, 0, 0, 210, 0, 0, 25, 3},
{ 2, 8190, 8191, 13,8191, 0, 0, 39, 0, 0, 630, 0, 0, 25, 3},
{ 2, 10752, 11441, 48, 17,673, 0, 4712, 2024, 0, 16,-14, 0, 25, 3},
{ 2, 15004, 15709, 22, 23,683, 0, 4099, 13663, 0, 22, 31, 0, 25, 3},
{ 2, 27000, 32767, 15, 31, 7,151, 11628, 28087,25824, 30, 6, -10, 28, 4}
};
void test15for4(FHESecKey& secKey);
void testProduct(FHESecKey& secKey, long bitSize1, long bitSize2,
long outSize, bool bootstrap = false);
void testAdd(FHESecKey& secKey, long bitSize1, long bitSize2,
long outSize, bool bootstrap = false);
int main(int argc, char *argv[])
{
ArgMapping amap;
long prm=1;
amap.arg("prm", prm, "parameter size (0-tiny,...,7-huge)");
long bitSize = 5;
amap.arg("bitSize", bitSize, "bitSize of input integers (<=32)");
long bitSize2 = 0;
amap.arg("bitSize2", bitSize2, "bitSize of 2nd input integer (<=32)",
"same as bitSize");
long outSize = 0;
amap.arg("outSize", outSize, "bitSize of output integers", "as many as needed");
long nTests = 2;
amap.arg("nTests", nTests, "number of tests to run");
bool bootstrap = false;
amap.arg("bootstrap", bootstrap, "test multiplication with bootstrapping");
long seed=0;
amap.arg("seed", seed, "PRG seed");
long nthreads=1;
amap.arg("nthreads", nthreads, "number of threads");
amap.arg("verbose", verbose, "print more information");
long tests2avoid = 1;
amap.arg("tests2avoid", tests2avoid, "bitmap of tests to disable (1-15for4, 2-add, 4-multiply");
amap.parse(argc, argv);
assert(prm >= 0 && prm < 5);
if (seed) NTL::SetSeed(ZZ(seed));
if (nthreads>1) NTL::SetNumThreads(nthreads);
if (bitSize<=0) bitSize=5;
else if (bitSize>32) bitSize=32;
if (bitSize2<=0) bitSize2=bitSize;
else if (bitSize2>32) bitSize2=32;
long* vals = mValues[prm];
long p = vals[0];
// long phim = vals[1];
long m = vals[2];
NTL::Vec<long> mvec;
append(mvec, vals[4]);
if (vals[5]>1) append(mvec, vals[5]);
if (vals[6]>1) append(mvec, vals[6]);
std::vector<long> gens;
gens.push_back(vals[7]);
if (vals[8]>1) gens.push_back(vals[8]);
if (vals[9]>1) gens.push_back(vals[9]);
std::vector<long> ords;
ords.push_back(vals[10]);
if (abs(vals[11])>1) ords.push_back(vals[11]);
if (abs(vals[12])>1) ords.push_back(vals[12]);
long B = vals[13];
long c = vals[14];
// Compute the number of levels
long L;
if (bootstrap) L=30; // that should be enough
else {
double nBits =
(outSize>0 && outSize<2*bitSize)? outSize : (2*bitSize);
double three4twoLvls = log(nBits/2) / log(1.5);
double add2NumsLvls = log(nBits) / log(2.0);
L = 3 + ceil(three4twoLvls + add2NumsLvls);
}
if (verbose) {
cout <<"input bitSizes="<<bitSize<<','<<bitSize2
<<", output size bound="<<outSize
<<", running "<<nTests<<" tests for each function\n";
if (nthreads>1) cout << " using "<<NTL::AvailableThreads()<<" threads\n";
cout << "computing key-independent tables..." << std::flush;
}
FHEcontext context(m, p, /*r=*/1, gens, ords);
context.bitsPerLevel = B;
buildModChain(context, L, c,/*extraBits=*/8);
if (bootstrap) {
context.makeBootstrappable(mvec, /*t=*/0,
/*flag=*/false, /*cacheType=DCRT*/2);
}
buildUnpackSlotEncoding(unpackSlotEncoding, *context.ea);
if (verbose) {
cout << " done.\n";
context.zMStar.printout();
cout << " L="<<L<<", B="<<B<<endl;
cout << "\ncomputing key-dependent tables..." << std::flush;
}
FHESecKey secKey(context);
secKey.GenSecKey(/*Hweight=*/128);
addSome1DMatrices(secKey); // compute key-switching matrices
addFrbMatrices(secKey);
if (bootstrap) secKey.genRecryptData();
if (verbose) cout << " done\n";
activeContext = &context; // make things a little easier sometimes
#ifdef DEBUG_PRINTOUT
dbgEa = (EncryptedArray*) context.ea;
dbgKey = &secKey;
#endif
if (!(tests2avoid & 1)) {
for (long i=0; i<nTests; i++)
test15for4(secKey);
cout << " *** test15for4 PASS ***\n";
}
if (!(tests2avoid & 2)) {
for (long i=0; i<nTests; i++)
testAdd(secKey, bitSize, bitSize2, outSize, bootstrap);
cout << " *** testAdd PASS ***\n";
}
if (!(tests2avoid & 4)) {
for (long i=0; i<nTests; i++)
testProduct(secKey, bitSize, bitSize2, outSize, bootstrap);
cout << " *** testProduct PASS ***\n";
}
if (verbose) printAllTimers(cout);
return 0;
}
void test15for4(FHESecKey& secKey)
{
std::vector<Ctxt> inBuf(15, Ctxt(secKey));
std::vector<Ctxt*> inPtrs(15, nullptr);
std::vector<Ctxt> outBuf(5, Ctxt(secKey));
long sum=0;
std::string inputBits = "(";
for (int i=0; i<15; i++) {
if (NTL::RandomBnd(10)>0) { // leave empty with small probability
inPtrs[i] = &(inBuf[i]);
long bit = NTL::RandomBnd(2); // a random bit
secKey.Encrypt(inBuf[i], ZZX(bit));
inputBits += std::to_string(bit) + ",";
sum += bit;
}
else inputBits += "-,";
}
inputBits += ")";
// Add these bits
if (verbose) {
cout << endl;
CheckCtxt(inBuf[lsize(inBuf)-1], "b4 15for4");
}
long numOutputs
= fifteenOrLess4Four(CtPtrs_vectorCt(outBuf), CtPtrs_vectorPt(inPtrs));
if (verbose)
CheckCtxt(outBuf[lsize(outBuf)-1], "after 15for4");
// Check the result
long sum2=0;
for (int i=0; i<numOutputs; i++) {
ZZX poly;
secKey.Decrypt(poly, outBuf[i]);
sum2 += to_long(ConstTerm(poly)) << i;
}
if (sum != sum2) {
cout << "15to4 error: inputs="<<inputBits<<", sum="<<sum;
cout << " but sum2="<<sum2<<endl;
exit(0);
}
else if (verbose)
cout << "15to4 succeeded, sum"<<inputBits<<"="<<sum2<<endl;
}
void testProduct(FHESecKey& secKey, long bitSize, long bitSize2,
long outSize, bool bootstrap)
{
const EncryptedArray& ea = *(secKey.getContext().ea);
long mask = (outSize? ((1L<<outSize)-1) : -1);
// Choose two random n-bit integers
long pa = RandomBits_long(bitSize);
long pb = RandomBits_long(bitSize2);
// Encrypt the individual bits
NTL::Vec<Ctxt> eProduct, enca, encb;
resize(enca, bitSize, Ctxt(secKey));
for (long i=0; i<bitSize; i++) {
secKey.Encrypt(enca[i], ZZX((pa>>i)&1));
if (bootstrap) { // put them at a lower level
enca[i].modDownToLevel(5);
}
}
resize(encb, bitSize2, Ctxt(secKey));
for (long i=0; i<bitSize2; i++) {
secKey.Encrypt(encb[i], ZZX((pb>>i)&1));
if (bootstrap) { // put them at a lower level
encb[i].modDownToLevel(5);
}
}
if (verbose) {
cout << "\n bits-size "<<bitSize<<'+'<<bitSize2;
if (outSize>0) cout << "->"<<outSize;
CheckCtxt(encb[0], "b4 multiplication");
}
// Test positive multiplication
vector<long> slots;
{CtPtrs_VecCt eep(eProduct); // A wrappers around the output vector
multTwoNumbers(eep,CtPtrs_VecCt(enca),CtPtrs_VecCt(encb),/*negative=*/false,
outSize, &unpackSlotEncoding);
decryptBinaryNums(slots, eep, secKey, ea);
} // get rid of the wrapper
if (verbose)
CheckCtxt(eProduct[lsize(eProduct)-1], "after multiplication");
long pProd = pa*pb;
if (slots[0] != ((pa*pb)&mask)) {
cout << "Positive product error: pa="<<pa<<", pb="<<pb
<< ", but product="<<slots[0]
<< " (should be "<<pProd<<'&'<<mask<<'='<<(pProd&mask)<<")\n";
exit(0);
}
else if (verbose) {
cout << "positive product succeeded: ";
if (outSize) cout << "bottom "<<outSize<<" bits of ";
cout << pa<<"*"<<pb<<"="<<slots[0]<<endl;
}
// Test negative multiplication
secKey.Encrypt(encb[bitSize2-1], ZZX(1));
decryptBinaryNums(slots, CtPtrs_VecCt(encb), secKey, ea, /*negative=*/true);
pb = slots[0];
eProduct.kill();
{CtPtrs_VecCt eep(eProduct); // A wrappers around the output vector
multTwoNumbers(eep,CtPtrs_VecCt(enca),CtPtrs_VecCt(encb),/*negative=*/true,
outSize, &unpackSlotEncoding);
decryptBinaryNums(slots, eep, secKey, ea, /*negative=*/true);
} // get rid of the wrapper
if (verbose)
CheckCtxt(eProduct[lsize(eProduct)-1], "after multiplication");
pProd = pa*pb;
if ((slots[0]&mask) != (pProd&mask)) {
cout << "Negative product error: pa="<<pa<<", pb="<<pb
<< ", but product="<<slots[0]
<< " (should be "<<pProd<<'&'<<mask<<'='<<(pProd&mask)<<")\n";
exit(0);
}
else if (verbose) {
cout << "negative product succeeded: ";
if (outSize) cout << "bottom "<<outSize<<" bits of ";
cout << pa<<"*"<<pb<<"="<<slots[0]<<endl;
}
#ifdef DEBUG_PRINTOUT
const Ctxt* minCtxt = nullptr;
long minLvl=1000;
for (const Ctxt& c: eProduct) {
long lvl = c.findBaseLevel();
if (lvl < minLvl) {
minCtxt = &c;
minLvl = lvl;
}
}
decryptAndPrint((cout<<" after multiplication: "), *minCtxt, secKey, ea,0);
cout << endl;
#endif
}
void testAdd(FHESecKey& secKey, long bitSize1, long bitSize2,
long outSize, bool bootstrap)
{
const EncryptedArray& ea = *(secKey.getContext().ea);
long mask = (outSize? ((1L<<outSize)-1) : -1);
// Choose two random n-bit integers
long pa = RandomBits_long(bitSize1);
long pb = RandomBits_long(bitSize2);
// Encrypt the individual bits
NTL::Vec<Ctxt> eSum, enca, encb;
resize(enca, bitSize1, Ctxt(secKey));
for (long i=0; i<bitSize1; i++) {
secKey.Encrypt(enca[i], ZZX((pa>>i)&1));
if (bootstrap) { // put them at a lower level
enca[i].modDownToLevel(5);
}
}
resize(encb, bitSize2, Ctxt(secKey));
for (long i=0; i<bitSize2; i++) {
secKey.Encrypt(encb[i], ZZX((pb>>i)&1));
if (bootstrap) { // put them at a lower level
encb[i].modDownToLevel(5);
}
}
if (verbose) {
cout << "\n bits-size "<<bitSize1<<'+'<<bitSize2;
if (outSize>0) cout << "->"<<outSize;
cout <<endl;
CheckCtxt(encb[0], "b4 addition");
}
// Test addition
vector<long> slots;
{CtPtrs_VecCt eep(eSum); // A wrapper around the output vector
addTwoNumbers(eep, CtPtrs_VecCt(enca), CtPtrs_VecCt(encb),
outSize, &unpackSlotEncoding);
decryptBinaryNums(slots, eep, secKey, ea);
} // get rid of the wrapper
if (verbose) CheckCtxt(eSum[lsize(eSum)-1], "after addition");
long pSum = pa+pb;
if (slots[0] != ((pa+pb)&mask)) {
cout << "addTwoNums error: pa="<<pa<<", pb="<<pb
<< ", but pSum="<<slots[0]
<< " (should be ="<<(pSum&mask)<<")\n";
exit(0);
}
else if (verbose) {
cout << "addTwoNums succeeded: ";
if (outSize) cout << "bottom "<<outSize<<" bits of ";
cout << pa<<"+"<<pb<<"="<<slots[0]<<endl;
}
#ifdef DEBUG_PRINTOUT
const Ctxt* minCtxt = nullptr;
long minLvl=1000;
for (const Ctxt& c: eSum) {
long lvl = c.findBaseLevel();
if (lvl < minLvl) {
minCtxt = &c;
minLvl = lvl;
}
}
decryptAndPrint((cout<<" after addition: "), *minCtxt, secKey, ea,0);
cout << endl;
#endif
}
<|endoftext|>
|
<commit_before>// Copyright © 2016 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.
#include <Arduino.h>
#include <TheThingsNetwork.h>
void TheThingsNetwork::init(Stream& modemStream, Stream& debugStream) {
this->modemStream = &modemStream;
this->debugStream = &debugStream;
}
String TheThingsNetwork::readLine(int waitTime) {
unsigned long start = millis();
while (millis() < start + waitTime) {
String line = modemStream->readStringUntil('\n');
if (line.length() > 0) {
return line.substring(0, line.length() - 1);
}
}
return "";
}
bool TheThingsNetwork::waitForOK(int waitTime, String okMessage) {
String line = readLine(waitTime);
if (line == "") {
debugPrintLn("Wait for OK time-out expired");
return false;
}
if (line != okMessage) {
debugPrintLn("Response is not OK: " + line);
return false;
}
return true;
}
String TheThingsNetwork::readValue(String cmd) {
modemStream->println(cmd);
return readLine();
}
bool TheThingsNetwork::sendCommand(String cmd, int waitTime) {
debugPrintLn("Sending: " + cmd);
modemStream->println(cmd);
return waitForOK(waitTime);
}
bool TheThingsNetwork::sendCommand(String cmd, String value, int waitTime) {
int l = value.length();
byte buf[l];
value.getBytes(buf, l);
return sendCommand(cmd, buf, l, waitTime);
}
char btohexa_high(unsigned char b) {
b >>= 4;
return (b > 0x9u) ? b + 'A' - 10 : b + '0';
}
char btohexa_low(unsigned char b) {
b &= 0x0F;
return (b > 0x9u) ? b + 'A' - 10 : b + '0';
}
bool TheThingsNetwork::sendCommand(String cmd, const byte *buf, int length, int waitTime) {
debugPrintLn("Sending: " + cmd + " with " + String(length) + " bytes");
modemStream->print(cmd + " ");
for (int i = 0; i < length; i++) {
modemStream->print(btohexa_high(buf[i]));
modemStream->print(btohexa_low(buf[i]));
}
modemStream->println();
return waitForOK(waitTime);
}
void TheThingsNetwork::reset(bool adr, int sf, int fsb) {
#if !ADR_SUPPORTED
adr = false;
#endif
modemStream->println("sys reset");
String version = readLine(3000);
if (version == "") {
debugPrintLn("Invalid version");
return;
}
model = version.substring(0, version.indexOf(' '));
debugPrintLn("Version is " + version + ", model is " + model);
sendCommand("mac set adr " + String(adr ? "on" : "off"));
int dr = -1;
if (model == "RN2483") {
sendCommand("mac set pwridx " + String(PWRIDX_868));
switch (sf) {
case 7:
dr = 5;
break;
case 8:
dr = 4;
break;
case 9:
dr = 3;
break;
case 10:
dr = 2;
break;
case 11:
dr = 1;
break;
case 12:
dr = 0;
break;
default:
debugPrintLn("Invalid SF")
break;
}
}
else if (model == "RN2903") {
sendCommand("mac set pwridx " + String(PWRIDX_915));
enableFsbChannels(fsb);
switch (sf) {
case 7:
dr = 3;
break;
case 8:
dr = 2;
break;
case 9:
dr = 1;
break;
case 10:
dr = 0;
break;
default:
debugPrintLn("Invalid SF")
break;
}
}
if (dr > -1)
sendCommand("mac set dr " + String(dr));
}
bool TheThingsNetwork::enableFsbChannels(int fsb) {
int chLow = fsb > 0 ? (fsb - 1) * 8 : 0;
int chHigh = fsb > 0 ? chLow + 7 : 71;
int ch500 = fsb + 63;
for (int i = 0; i < 72; i++)
if (i == ch500 || chLow <= i && i <= chHigh)
sendCommand("mac set ch status " + String(i) + " on");
else
sendCommand("mac set ch status " + String(i) + " off");
return true;
}
bool TheThingsNetwork::personalize(const byte devAddr[4], const byte nwkSKey[16], const byte appSKey[16]) {
sendCommand("mac set devaddr", devAddr, 4);
sendCommand("mac set nwkskey", nwkSKey, 16);
sendCommand("mac set appskey", appSKey, 16);
sendCommand("mac join abp");
String response = readLine();
if (response != "accepted") {
debugPrintLn("Personalize not accepted: " + response);
return false;
}
debugPrintLn("Personalize accepted. Status: " + readValue("mac get status"));
return true;
}
bool TheThingsNetwork::join(const byte appEui[8], const byte appKey[16]) {
String devEui = readValue("sys get hweui");
sendCommand("mac set appeui", appEui, 8);
sendCommand("mac set deveui " + devEui);
sendCommand("mac set appkey", appKey, 16);
if (!sendCommand("mac join otaa")) {
debugPrintLn("Send join command failed");
return false;
}
String response = readLine(10000);
if (response != "accepted") {
debugPrintLn("Join not accepted: " + response);
return false;
}
debugPrintLn("Join accepted. Status: " + readValue("mac get status"));
return true;
}
int TheThingsNetwork::sendBytes(const byte* buffer, int length, int port, bool confirm) {
if (!sendCommand("mac tx " + String(confirm ? "cnf" : "uncnf") + " " + String(port), buffer, length)) {
debugPrintLn("Send command failed");
return 0;
}
String response = readLine(10000);
if (response == "") {
debugPrintLn("Time-out");
return 0;
}
if (response == "mac_tx_ok") {
debugPrintLn("Successful transmission");
return 0;
}
if (response.startsWith("mac_rx")) {
int portEnds = response.indexOf(" ", 7);
this->downlinkPort = response.substring(7, portEnds).toInt();
String data = response.substring(portEnds + 1);
int downlinkLength = data.length() / 2;
for (int i = 0, d = 0; i < downlinkLength; i++, d += 2)
this->downlink[i] = HEX_PAIR_TO_BYTE(data[d], data[d+1]);
debugPrintLn("Successful transmission. Received " + String(downlinkLength) + " bytes");
return downlinkLength;
}
debugPrintLn("Unexpected response: " + response);
}
int TheThingsNetwork::sendString(String message, int port, bool confirm) {
int l = message.length();
byte buf[l + 1];
message.getBytes(buf, l + 1);
return sendBytes(buf, l, port, confirm);
}
void TheThingsNetwork::showStatus() {
debugPrintLn("EUI: " + readValue("sys get hweui"));
debugPrintLn("Battery: " + readValue("sys get vdd"));
debugPrintLn("AppEUI: " + readValue("mac get appeui"));
debugPrintLn("DevEUI: " + readValue("mac get deveui"));
debugPrintLn("DevAddr: " + readValue("mac get devaddr"));
if (this->model == "RN2483") {
debugPrintLn("Band: " + readValue("mac get band"));
}
debugPrintLn("Data Rate: " + readValue("mac get dr"));
debugPrintLn("RX Delay 1: " + readValue("mac get rxdelay1"));
debugPrintLn("RX Delay 2: " + readValue("mac get rxdelay2"));
}
<commit_msg>rebased to include downlink<commit_after>// Copyright © 2016 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.
#include <Arduino.h>
#include <TheThingsNetwork.h>
void TheThingsNetwork::init(Stream& modemStream, Stream& debugStream) {
this->modemStream = &modemStream;
this->debugStream = &debugStream;
}
String TheThingsNetwork::readLine(int waitTime) {
unsigned long start = millis();
while (millis() < start + waitTime) {
String line = modemStream->readStringUntil('\n');
if (line.length() > 0) {
return line.substring(0, line.length() - 1);
}
}
return "";
}
bool TheThingsNetwork::waitForOK(int waitTime, String okMessage) {
String line = readLine(waitTime);
if (line == "") {
debugPrintLn(F("Wait for OK time-out expired"));
return false;
}
if (line != okMessage) {
debugPrint(F("Response is not OK: "));
debugPrintLn(line);
return false;
}
return true;
}
String TheThingsNetwork::readValue(String cmd) {
modemStream->println(cmd);
return readLine();
}
bool TheThingsNetwork::sendCommand(String cmd, int waitTime) {
debugPrint(F("Sending: "));
debugPrintLn(cmd);
modemStream->println(cmd);
return waitForOK(waitTime);
}
bool TheThingsNetwork::sendCommand(String cmd, String value, int waitTime) {
int l = value.length();
byte buf[l];
value.getBytes(buf, l);
return sendCommand(cmd, buf, l, waitTime);
}
char btohexa_high(unsigned char b) {
b >>= 4;
return (b > 0x9u) ? b + 'A' - 10 : b + '0';
}
char btohexa_low(unsigned char b) {
b &= 0x0F;
return (b > 0x9u) ? b + 'A' - 10 : b + '0';
}
bool TheThingsNetwork::sendCommand(String cmd, const byte *buf, int length, int waitTime) {
String str = "";
debugPrint(F("Sending: "));
debugPrint(cmd);
debugPrint(F(" with "));
debugPrint(length);
debugPrintLn(F(" bytes"));
modemStream->print(cmd + " ");
for (int i = 0; i < length; i++) {
modemStream->print(btohexa_high(buf[i]));
modemStream->print(btohexa_low(buf[i]));
}
modemStream->println();
return waitForOK(waitTime);
}
void TheThingsNetwork::reset(bool adr, int sf, int fsb) {
#if !ADR_SUPPORTED
adr = false;
#endif
modemStream->println(F("sys reset"));
String version = readLine(3000);
if (version == "") {
debugPrintLn(F("Invalid version"));
return;
}
model = version.substring(0, version.indexOf(' '));
debugPrint(F("Version is "));
debugPrint(version);
debugPrint(F(", model is "));
debugPrintLn(model);
String str = "";
str.concat(F("mac set adr "));
if(adr){
str.concat(F("on"));
} else {
str.concat(F("off"));
}
sendCommand(str);
int dr = -1;
if (model == F("RN2483")) {
str = "";
str.concat(F("mac set pwridx "));
str.concat(PWRIDX_868);
sendCommand(str);
switch (sf) {
case 7:
dr = 5;
break;
case 8:
dr = 4;
break;
case 9:
dr = 3;
break;
case 10:
dr = 2;
break;
case 11:
dr = 1;
break;
case 12:
dr = 0;
break;
default:
debugPrintLn(F("Invalid SF"))
break;
}
}
else if (model == F("RN2903")) {
str = "";
str.concat(F("mac set pwridx "));
str.concat(PWRIDX_915);
sendCommand(str);
enableFsbChannels(fsb);
switch (sf) {
case 7:
dr = 3;
break;
case 8:
dr = 2;
break;
case 9:
dr = 1;
break;
case 10:
dr = 0;
break;
default:
debugPrintLn(F("Invalid SF"))
break;
}
}
if (dr > -1){
str = "";
str.concat(F("mac set dr "));
str.concat(dr);
sendCommand(str);
}
}
bool TheThingsNetwork::enableFsbChannels(int fsb) {
int chLow = fsb > 0 ? (fsb - 1) * 8 : 0;
int chHigh = fsb > 0 ? chLow + 7 : 71;
int ch500 = fsb + 63;
for (int i = 0; i < 72; i++){
String str = "";
str.concat(F("mac set ch status "));
str.concat(i);
if (i == ch500 || chLow <= i && i <= chHigh){
str.concat(F(" on"));
}
else{
str.concat(F(" off"));
}
sendCommand(str);
}
return true;
}
bool TheThingsNetwork::personalize(const byte devAddr[4], const byte nwkSKey[16], const byte appSKey[16]) {
sendCommand(F("mac set devaddr"), devAddr, 4);
sendCommand(F("mac set nwkskey"), nwkSKey, 16);
sendCommand(F("mac set appskey"), appSKey, 16);
sendCommand(F("mac join abp"));
String response = readLine();
if (response != F("accepted")) {
debugPrint(F("Personalize not accepted: "));
debugPrintLn(response);
return false;
}
debugPrint(F("Personalize accepted. Status: "));
debugPrintLn(readValue(F("mac get status")));
return true;
}
bool TheThingsNetwork::join(const byte appEui[8], const byte appKey[16]) {
String devEui = readValue(F("sys get hweui"));
sendCommand(F("mac set appeui"), appEui, 8);
String str = "";
str.concat(F("mac set deveui "));
str.concat(devEui);
sendCommand(str);
sendCommand(F("mac set appkey"), appKey, 16);
if (!sendCommand(F("mac join otaa"))) {
debugPrintLn(F("Send join command failed"));
return false;
}
String response = readLine(10000);
if (response != F("accepted")) {
debugPrint(F("Join not accepted: "));
debugPrintLn(response);
return false;
}
debugPrint(F("Join accepted. Status: "));
debugPrintLn(readValue(F("mac get status")));
return true;
}
int TheThingsNetwork::sendBytes(const byte* buffer, int length, int port, bool confirm) {
String str = "";
str.concat(F("mac tx "));
str.concat(confirm ? F("cnf ") : F("uncnf "));
str.concat(port);
if (!sendCommand(str, buffer, length)) {
debugPrintLn(F("Send command failed"));
return 0;
}
String response = readLine(10000);
if (response == "") {
debugPrintLn(F("Time-out"));
return 0;
}
if (response == F("mac_tx_ok")) {
debugPrintLn(F("Successful transmission"));
return 0;
}
if (response.startsWith(F("mac_rx"))) {
int portEnds = response.indexOf(" ", 7);
this->downlinkPort = response.substring(7, portEnds).toInt();
String data = response.substring(portEnds + 1);
int downlinkLength = data.length() / 2;
for (int i = 0, d = 0; i < downlinkLength; i++, d += 2)
this->downlink[i] = HEX_PAIR_TO_BYTE(data[d], data[d+1]);
debugPrint(F("Successful transmission. Received "));
debugPrint(downlinkLength);
debugPrintLn(F(" bytes"));
return downlinkLength;
}
debugPrint(F("Unexpected response: "));
debugPrintLn(response);
}
int TheThingsNetwork::sendString(String message, int port, bool confirm) {
int l = message.length();
byte buf[l + 1];
message.getBytes(buf, l + 1);
return sendBytes(buf, l, port, confirm);
}
void TheThingsNetwork::showStatus() {
debugPrint(F("EUI: "));
debugPrintLn(readValue(F("sys get hweui")));
debugPrint(F("Battery: "));
debugPrint(readValue(F("sys get vdd")));
debugPrint(F("AppEUI: "));
debugPrintLn(readValue(F("mac get appeui")));
debugPrint(F("DevEUI: "));
debugPrintLn(readValue(F("mac get deveui")));
debugPrint(F("DevAddr: "));
debugPrintLn(readValue(F("mac get devaddr")));
if (this->model == F("RN2483")) {
debugPrint(F("Band: "));
debugPrintLn(readValue(F("mac get band")));
}
debugPrint(F("Data Rate: "));
debugPrintLn(readValue(F("mac get dr")));
debugPrint(F("RX Delay 1: "));
debugPrintLn(readValue(F("mac get rxdelay1")));
debugPrint(F("RX Delay 2: "));
debugPrintLn(readValue(F("mac get rxdelay2")));
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <fstream>
using namespace std;
template <class T>
struct Node
{
T element;
Node<T> *left, *right, *pparent;
};
template <class T>
class BST {
private:
Node<T> *root;
int count;
public:
BST();
~BST();
void deleteTree(Node<T> *Tree);
void show(ostream&cout, const Node<T> *Tree) const;
void add(const T&);
bool search(const T&, Node<T> *Tree) const;
void input(const string& file);
void output(const string& file) const;
Node<T>* MinElement(Node<T>* min);
Node<T>* getroot() const;
int getcount() const;
Node<T>* del(Node<T>* parent, Node<T>* current, const T& val);
bool delVal(const T& val);
};
template <typename T> BST<T>::BST() {
root = NULL;
count = 0;
}
template <typename T> BST<T>::~BST() {
deleteTree(root);
}
template <typename T>void BST<T>::deleteTree(Node<T> *Tree) {
if (!Tree)
return;
if (Tree->left) {
deleteTree(Tree->left);
Tree->left = nullptr;
}
if (Tree->right) {
deleteTree(Tree->right);
Tree->right = nullptr;
}
delete Tree;
}
template <typename T> void BST<T>::show(ostream&cout, const Node<T> *Tree) const{
if (Tree != NULL) {
cout << Tree->element << endl;;
show(cout, Tree->left);
show(cout, Tree->right);
}
}
template <typename T> void BST<T>::add(const T &x) {
Node<T>* daughter = new Node<T>;
daughter->element = x;
daughter->left = daughter->right = nullptr;
Node<T>* parent = root;
Node<T>* temp = root;
while (temp)
{
parent = temp;
if (x < temp->element)
temp = temp->left;
else temp = temp->right;
}
if (!parent)
root = daughter;
else {
if (x < parent->element)
parent->left = daughter;
else
parent->right = daughter;
}
count++;
}
template <typename T> Node<T>* BST<T>::getroot() const {
return root;
}
template <typename T> int BST<T>::getcount() const {
return count;
}
template <typename T> void BST<T>::input(const string& file) {
ifstream fin(file);
try
{
int temp;
while (!fin.eof()) throw 1;
{
fin >> temp;
add(temp);
}
fin.close();
}
catch (int i)
{
cout << "This file don't find" << endl;
}
}
template <typename T> void BST<T>::output(const string& file) const {
ofstream fout(file);
show(fout, root);
fout.close();
}
template <typename T> bool BST<T>::search(const T&x, Node<T>* Tree) const {
if (Tree == nullptr)
return false;
if (x == Tree->element) {
return true;
}
else if (x < Tree->element) {
search(x, Tree->left);
}
else search(x, Tree->right);
}
template <typename T> Node<T>* BST<T>::MinElement(Node<T>* min) {
if (min->left == nullptr)
return min;
else
return MinElement(min->left);
}
template <typename T>
Node<T>* BST<T>::del(Node<T>* parent, Node<T>* current, const T& val)
{
if (!current) return false;
if (current->element == val)
{
if (current->left == NULL || current->right == NULL)
{
Node<T>* temp = current->left;
if (current->right) temp = current->right;
if (parent)
{
if (parent->left == current)
{
parent->left = temp;
}
else
{
parent->right = temp;
}
}
else
{
this->root = temp;
}
}
else
{
Node<T>* validSubs = current->right;
while (validSubs->left)
{
validSubs = validSubs->left;
}
T temp = current->element;
current->element = validSubs->element;
validSubs->element = temp;
return del(current, current->right, temp);
}
delete current;
count--;
return true;
}
if (current->element > val)
return del(current, current->left, val);
else
return del(current, current->right, val);
}
template <typename T>
bool BST<T>::delVal(const T& val) {
return this->del(NULL, root, val);
}
<commit_msg>Create BST.hpp<commit_after>#include <iostream>
#include <fstream>
using namespace std;
template <class T>
struct Node
{
T element;
Node<T> *left, *right, *pparent;
};
template <class T>
class BST {
private:
Node<T> *root;
int count;
public:
BST();
~BST();
void deleteTree(Node<T> *Tree);
void show(ostream&cout, const Node<T> *Tree) const;
void add(const T&);
bool search(const T&, Node<T> *Tree) const;
void input(const string& file);
void output(const string& file) const;
Node<T>* MinElement(Node<T>* min);
Node<T>* getroot() const;
int getcount() const;
Node<T>* del(Node<T>* parent, Node<T>* current, const T& val);
bool delVal(const T& val);
};
template <typename T> BST<T>::BST() {
root = NULL;
count = 0;
}
template <typename T> BST<T>::~BST() {
deleteTree(root);
}
template <typename T>void BST<T>::deleteTree(Node<T> *Tree) {
if (!Tree)
return;
if (Tree->left) {
deleteTree(Tree->left);
Tree->left = nullptr;
}
if (Tree->right) {
deleteTree(Tree->right);
Tree->right = nullptr;
}
delete Tree;
}
template <typename T> void BST<T>::show(ostream&cout, const Node<T> *Tree) const{
if (Tree != NULL) {
cout << Tree->element << endl;;
show(cout, Tree->left);
show(cout, Tree->right);
}
}
template <typename T> void BST<T>::add(const T &x) {
Node<T>* daughter = new Node<T>;
daughter->element = x;
daughter->left = daughter->right = nullptr;
Node<T>* parent = root;
Node<T>* temp = root;
while (temp)
{
parent = temp;
if (x < temp->element)
temp = temp->left;
else temp = temp->right;
}
if (!parent)
root = daughter;
else {
if (x < parent->element)
parent->left = daughter;
else
parent->right = daughter;
}
count++;
}
template <typename T> Node<T>* BST<T>::getroot() const {
return root;
}
template <typename T> int BST<T>::getcount() const {
return count;
}
template <typename T> void BST<T>::input(const string& file) {
ifstream fin(file);
try
{
int temp;
while (!fin.eof()) throw 1;
{
fin >> temp;
add(temp);
count++;
}
fin.close();
}
catch (int i)
{
cout << "This file don't find" << endl;
}
}
template <typename T> void BST<T>::output(const string& file) const {
ofstream fout(file);
show(fout, root);
fout.close();
}
template <typename T> bool BST<T>::search(const T&x, Node<T>* Tree) const {
if (Tree == nullptr)
return false;
if (x == Tree->element) {
return true;
}
else if (x < Tree->element) {
search(x, Tree->left);
}
else search(x, Tree->right);
}
template <typename T> Node<T>* BST<T>::MinElement(Node<T>* min) {
if (min->left == nullptr)
return min;
else
return MinElement(min->left);
}
template <typename T>
Node<T>* BST<T>::del(Node<T>* parent, Node<T>* current, const T& val)
{
if (!current) return false;
if (current->element == val)
{
if (current->left == NULL || current->right == NULL)
{
Node<T>* temp = current->left;
if (current->right) temp = current->right;
if (parent)
{
if (parent->left == current)
{
parent->left = temp;
}
else
{
parent->right = temp;
}
}
else
{
this->root = temp;
}
}
else
{
Node<T>* validSubs = current->right;
while (validSubs->left)
{
validSubs = validSubs->left;
}
T temp = current->element;
current->element = validSubs->element;
validSubs->element = temp;
return del(current, current->right, temp);
}
delete current;
count--;
return true;
}
if (current->element > val)
return del(current, current->left, val);
else
return del(current, current->right, val);
}
template <typename T>
bool BST<T>::delVal(const T& val) {
return this->del(NULL, root, val);
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2013 Matthew Harvey
*
* 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.
*/
#ifndef GUARD_log_hpp_778298908902
#define GUARD_log_hpp_778298908902
/** @file log.hpp
*
* @brief Logging facilities
*/
#include <boost/lexical_cast.hpp>
#include <exception>
#include <new>
#include <string>
namespace jewel
{
/**
* Class to facilitate logging.
*
* To fire logging events using the Log class, client code should use the
* following macros.
*
* <b>JEWEL_ENABLE_LOGGING must be defined in the client code, otherwise the
* logging macros will have no effect at all and will compile away to
* nothing.</b>
*
* \b JEWEL_LOG_TRACE() will fire a logging event that simply displays the name
* of the function, file and line number where it appeared, with a severity
* level of \e trace.
*
* \b JEWEL_LOG_MESSAGE(severity, message) will fire a logging event with
* severity of \e severity and with a message \e message, which should be
* a C-style string. The log will also show
* the function, file and line number in the source code where it appears.
*
* \b JEWEL_LOG_VALUE(severity, expression) will fire a logging event which
* describes the value of \e expression, which should be C++ expression
* that may be written to a std::ostream, e.g. "1 + 2" or "x" (assuming x
* is defined). Do not include quotes around the expression when passing
* it to the macro. The log will also show the function, file and line number
* in the source code where is appears.
*
* \b JEWEL_HARD_LOGGING_THRESHOLD is by default defined as 0, which means that
* there is no
* <em>compile-time</em> restriction on what is logged. If you want to
* restrict which statements are logged at <em>compile-time</em>, so that
* statements below a certain severity level are not logged regardless of
* the runtime threshold passed to Log::set_threshold, you can
* do so by setting \b JEWEL_HARD_LOGGING_THRESHOLD to a higher
* severity level, e.g. jewel::Log::error. On most compilers,
* with optimization on,
* should mean that logging statements below this "hard" threshold are
* compiled away to nothing.
*
* These logging facilities are guaranteed never to throw an exception, with
* the following provisos...
*
* (a) Log::set_filepath may throw std::bad_alloc.
*
* (b) The \b JEWEL_LOG_VALUE macro makes use of
* boost::lexical_cast, the implementation of which inserts the passed
* expression onto a std::ostream during the casting process. If this process
* of calling boost::lexical_cast results in either boost::bad_lexical_cast or
* std::bad_alloc being thrown, then that exception will be swallowed rather
* than propagated. But if any other exception is thrown during the insertion
* of the passed expression onto the std::ostream, then that exception will
* not be caught.
*
* Note it is impossible to set the Log to point to a particular stream. We
* can only pass a filepath for the Log to write to
* a given file. This is a deliberate restriction that enables the Log class to
* provide the no-throw guarantee for all its member functions and associated
* macros (except as detailed above). If we enable a stream to be passed to
* Log, then it might be that exceptions are enabled on that stream, and it then
* becomes difficult/complicated if we still want to offer the no-throw
* guarantee. The main price paid for this policy is that logging cannot
* (at least, not easily) be directed to standard output / standard error - we
* can only easily direct it to a file.
*
* <b>NOTE These logging facilities are not thread-safe!</b>
*
* @todo MEDIUM PRIORITY Provide a way to direct logging to standard output
* streams without sacrificing exception safety and without complicating the
* API too much.
*
* @todo MEDIUM PRIORITY Write unit tests for this.
*/
class Log
{
public:
/**
* @enum Level
*
* Represents a series of increasing severity levels for
* logging events.
*/
enum Level
{
// Note if we add levels, we also need to update the
// severity_string function.
trace = 0, /**< to signify "trace purposes only" */
info, /**< to signify "information purposes only" */
warning, /**< to signify something that might be an error */
error /**< to signify something that is definitely an error */
};
/**
* Tell the logging engine the file you want log messages written to.
* This must be called or logging will not occur at all.
*
* @throws std::bad_alloc in the unlikely event of memory allocation
* failure while creating the underlying logging stream.
*/
static void set_filepath(std::string const& p_filepath);
/**
* Sets the logging threshold so that logging events will be written
* to the file if and only if their severity is greater than or
* equal to \e p_level. By default, the threshold is Log::info.
*/
static void set_threshold(Level p_level);
/**
* Passes a logging event to the logging mechanism. Note this should
* not normally be called by client code, which should instead use
* the convenience macros provided (see class documentation for Log).
*/
static void log
( Level p_severity,
char const* p_message,
char const* p_function,
char const* p_file,
int p_line,
char const* p_compilation_date = 0,
char const* p_compilation_time = 0,
char const* p_exception_type = 0,
char const* p_expression = 0,
char const* p_value = 0
);
private:
Log(); // private and unimplemented - we don't want instances.
static char const* severity_string(Level p_level);
// Pass a stream pointer to set the static stream pointer that lives
// inside the function. Pass nothing to simply retrieve that pointer.
static std::ostream* stream_aux(std::ostream* p_stream = 0);
static Level& threshold_aux();
};
} // namespace jewel
// MACROS
#ifdef JEWEL_ENABLE_LOGGING
# ifndef JEWEL_HARD_LOGGING_THRESHOLD
# define JEWEL_HARD_LOGGING_THRESHOLD 0
# endif
# define JEWEL_LOG_TRACE() \
if (jewel::Log::trace < JEWEL_HARD_LOGGING_THRESHOLD) ; \
else \
jewel::Log::log \
( jewel::Log::trace, \
0, \
__func__, \
__FILE__, \
__LINE__, \
__DATE__, \
__TIME__ \
)
# define JEWEL_LOG_MESSAGE(severity, message) \
if (severity < JEWEL_HARD_LOGGING_THRESHOLD) ; \
else \
jewel::Log::log \
( severity, \
message, \
__func__, \
__FILE__, \
__LINE__, \
__DATE__, \
__TIME__ \
)
# define JEWEL_LOG_VALUE(severity, expression) \
if (severity < JEWEL_HARD_LOGGING_THRESHOLD) ; \
else \
try \
{ \
jewel::Log::log \
( severity, \
0, \
__func__, \
__FILE__, \
__LINE__, \
__DATE__, \
__TIME__, \
0, \
#expression, \
boost::lexical_cast<std::string>(expression).c_str() \
); \
} \
catch (boost::bad_lexical_cast) \
{ \
JEWEL_LOG_MESSAGE \
( \
severity, \
"Could not log value of expression (" #expression "): " \
"caught boost::bad_lexical_cast." \
); \
} \
catch (std::bad_alloc) \
{ \
JEWEL_LOG_MESSAGE \
( \
severity, \
"Could not log value of expression (" #expression "): " \
"caught std::bad_alloc." \
); \
}
#else
# define JEWEL_LOG_TRACE() do {} while (0)
# define JEWEL_LOG_MESSAGE(severity, message) \
if (false) { (void)(severity); (void)(message); } // Silence compiler warnings re. unused variables, and prevent them from being evaluated.
# define JEWEL_LOG_VALUE(severity, expression) \
if (false) { (void)(severity); (void)(expression); } // Silence compiler warnings re. unused variables, and prevent them from being evaluated.
#endif // JEWEL_ENABLE_LOGGING
// INLINE FUNCTION DEFINITIONS
namespace jewel
{
inline
Log::Level&
Log::threshold_aux()
{
static Level ret = info;
return ret;
}
} // namespace jewel
#endif // GUARD_log_hpp_778298908902
<commit_msg>Improved documentation for jewel::Log. Described format of resulting log file and referred to tools/jewel_log_to_csv.py re. converting to CSV.<commit_after>/*
* Copyright 2013 Matthew Harvey
*
* 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.
*/
#ifndef GUARD_log_hpp_778298908902
#define GUARD_log_hpp_778298908902
/** @file log.hpp
*
* @brief Logging facilities
*/
#include <boost/lexical_cast.hpp>
#include <exception>
#include <new>
#include <string>
namespace jewel
{
/**
* Class to facilitate logging.
*
* To fire logging events using the Log class, client code should use the
* following macros.
*
* <b>JEWEL_ENABLE_LOGGING must be defined in the client code, otherwise the
* logging macros will have no effect at all and will compile away to
* nothing.</b>
*
* \b JEWEL_LOG_TRACE() will fire a logging event that simply displays the name
* of the function, file and line number where it appeared, with a severity
* level of \e trace.
*
* \b JEWEL_LOG_MESSAGE(severity, message) will fire a logging event with
* severity of \e severity and with a message \e message, which should be
* a C-style string. The log will also show
* the function, file and line number in the source code where it appears.
*
* \b JEWEL_LOG_VALUE(severity, expression) will fire a logging event which
* describes the value of \e expression, which should be C++ expression
* that may be written to a std::ostream, e.g. "1 + 2" or "x" (assuming x
* is defined). Do not include quotes around the expression when passing
* it to the macro. The log will also show the function, file and line number
* in the source code where is appears.
*
* \b JEWEL_HARD_LOGGING_THRESHOLD is by default defined as 0, which means that
* there is no
* <em>compile-time</em> restriction on what is logged. If you want to
* restrict which statements are logged at <em>compile-time</em>, so that
* statements below a certain severity level are not logged regardless of
* the runtime threshold passed to Log::set_threshold, you can
* do so by setting \b JEWEL_HARD_LOGGING_THRESHOLD to a higher
* severity level, e.g. jewel::Log::error. On most compilers,
* with optimization on,
* should mean that logging statements below this "hard" threshold are
* compiled away to nothing.
*
* These logging facilities are guaranteed never to throw an exception, with
* the following provisos...
*
* (a) Log::set_filepath may throw std::bad_alloc.
*
* (b) The \b JEWEL_LOG_VALUE macro makes use of
* boost::lexical_cast, the implementation of which inserts the passed
* expression onto a std::ostream during the casting process. If this process
* of calling boost::lexical_cast results in either boost::bad_lexical_cast or
* std::bad_alloc being thrown, then that exception will be swallowed rather
* than propagated. But if any other exception is thrown during the insertion
* of the passed expression onto the std::ostream, then that exception will
* not be caught.
*
* Note it is impossible to set the Log to point to a particular stream. We
* can only pass a filepath for the Log to write to
* a given file. This is a deliberate restriction that enables the Log class to
* provide the no-throw guarantee for all its member functions and associated
* macros (except as detailed above). If we enable a stream to be passed to
* Log, then it might be that exceptions are enabled on that stream, and it then
* becomes difficult/complicated if we still want to offer the no-throw
* guarantee. The main price paid for this policy is that logging cannot
* (at least, not easily) be directed to standard output / standard error - we
* can only easily direct it to a file.
*
* The format of the resulting log file is designed to be both readable for
* a human and easy to parse. In particular, if desired, it can be converted
* into CSV format using the Python utility script provided with this
* library (under "tools"). The CSV file can then be sorted, filtered and
* otherwise analysed using a spreadsheet program. Here is an example of a
* single logging entry:
*
* <em>
* {R}\n
* {F}[id]198\n
* {F}[severity]warning\n
* {F}[message]Division by zero.\n
* {F}[function]operator/=\n
* {F}[file]/home/matthew/Workbench/versioned/git/jewel/src/decimal.cpp\n
* {F}[line]503\n
* {F}[compilation_date]Nov 29 2013\n
* {F}[compilation_time]09:41:57\n
* {F}[exception_type]DecimalDivisionByZeroException\n
* </em>
*
* The "{R}" marks the start of each logging entry (i.e. record), and the
* "{F}" marks the begging of each field in a given entry. For reasons of
* efficiency and simplicity of implementation (including ease of providing
* the no-throw guarantee), there is no sophisticated formatting / escaping
* performed when the original logging entry is created. This means that if
* e.g. the "message" field contains the string
* "{R}", the formatting will be irregular and conversion to CSV via the
* Python script is likely to break (although the human-readability of the raw
* log file is unlikely to be compromised). This should be a
* rare enough occurrence, however, and it should be pretty obvious when it
* does occur. Assuming no such irregularity occurs, then
* conversion to CSV via the Python script is itself quite robust, with
* proper escaping etc. performed.
*
* <b>NOTE These logging facilities are not thread-safe!</b>
*
* @todo MEDIUM PRIORITY Provide a way to direct logging to standard output
* streams without sacrificing exception safety and without complicating the
* API too much.
*
* @todo MEDIUM PRIORITY Write unit tests for this.
*/
class Log
{
public:
/**
* @enum Level
*
* Represents a series of increasing severity levels for
* logging events.
*/
enum Level
{
// Note if we add levels, we also need to update the
// severity_string function.
trace = 0, /**< to signify "trace purposes only" */
info, /**< to signify "information purposes only" */
warning, /**< to signify something that might be an error */
error /**< to signify something that is definitely an error */
};
/**
* Tell the logging engine the file you want log messages written to.
* This must be called or logging will not occur at all.
*
* @throws std::bad_alloc in the unlikely event of memory allocation
* failure while creating the underlying logging stream.
*/
static void set_filepath(std::string const& p_filepath);
/**
* Sets the logging threshold so that logging events will be written
* to the file if and only if their severity is greater than or
* equal to \e p_level. By default, the threshold is Log::info.
*/
static void set_threshold(Level p_level);
/**
* Passes a logging event to the logging mechanism. Note this should
* not normally be called by client code, which should instead use
* the convenience macros provided (see class documentation for Log).
*/
static void log
( Level p_severity,
char const* p_message,
char const* p_function,
char const* p_file,
int p_line,
char const* p_compilation_date = 0,
char const* p_compilation_time = 0,
char const* p_exception_type = 0,
char const* p_expression = 0,
char const* p_value = 0
);
private:
Log(); // private and unimplemented - we don't want instances.
static char const* severity_string(Level p_level);
// Pass a stream pointer to set the static stream pointer that lives
// inside the function. Pass nothing to simply retrieve that pointer.
static std::ostream* stream_aux(std::ostream* p_stream = 0);
static Level& threshold_aux();
};
} // namespace jewel
// MACROS
#ifdef JEWEL_ENABLE_LOGGING
# ifndef JEWEL_HARD_LOGGING_THRESHOLD
# define JEWEL_HARD_LOGGING_THRESHOLD 0
# endif
# define JEWEL_LOG_TRACE() \
if (jewel::Log::trace < JEWEL_HARD_LOGGING_THRESHOLD) ; \
else \
jewel::Log::log \
( jewel::Log::trace, \
0, \
__func__, \
__FILE__, \
__LINE__, \
__DATE__, \
__TIME__ \
)
# define JEWEL_LOG_MESSAGE(severity, message) \
if (severity < JEWEL_HARD_LOGGING_THRESHOLD) ; \
else \
jewel::Log::log \
( severity, \
message, \
__func__, \
__FILE__, \
__LINE__, \
__DATE__, \
__TIME__ \
)
# define JEWEL_LOG_VALUE(severity, expression) \
if (severity < JEWEL_HARD_LOGGING_THRESHOLD) ; \
else \
try \
{ \
jewel::Log::log \
( severity, \
0, \
__func__, \
__FILE__, \
__LINE__, \
__DATE__, \
__TIME__, \
0, \
#expression, \
boost::lexical_cast<std::string>(expression).c_str() \
); \
} \
catch (boost::bad_lexical_cast) \
{ \
JEWEL_LOG_MESSAGE \
( \
severity, \
"Could not log value of expression (" #expression "): " \
"caught boost::bad_lexical_cast." \
); \
} \
catch (std::bad_alloc) \
{ \
JEWEL_LOG_MESSAGE \
( \
severity, \
"Could not log value of expression (" #expression "): " \
"caught std::bad_alloc." \
); \
}
#else
# define JEWEL_LOG_TRACE() do {} while (0)
# define JEWEL_LOG_MESSAGE(severity, message) \
if (false) { (void)(severity); (void)(message); } // Silence compiler warnings re. unused variables, and prevent them from being evaluated.
# define JEWEL_LOG_VALUE(severity, expression) \
if (false) { (void)(severity); (void)(expression); } // Silence compiler warnings re. unused variables, and prevent them from being evaluated.
#endif // JEWEL_ENABLE_LOGGING
// INLINE FUNCTION DEFINITIONS
namespace jewel
{
inline
Log::Level&
Log::threshold_aux()
{
static Level ret = info;
return ret;
}
} // namespace jewel
#endif // GUARD_log_hpp_778298908902
<|endoftext|>
|
<commit_before>
// Copyright (c) 2012 Nokia, Inc.
// 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 <errno.h>
#include <fcntl.h>
#include <linux/ioctl.h>
#include <linux/types.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "portal.h"
#include <sys/cdefs.h>
#include <android/log.h>
#define ALOGD(fmt, ...) __android_log_print(ANDROID_LOG_DEBUG, "PORTAL", fmt, __VA_ARGS__)
#define ALOGE(fmt, ...) __android_log_print(ANDROID_LOG_ERROR, "PORTAL", fmt, __VA_ARGS__)
#define PORTAL_ALLOC _IOWR('B', 10, PortalAlloc)
#define PORTAL_PUTGET _IOWR('B', 17, PortalMessage)
#define PORTAL_PUT _IOWR('B', 18, PortalMessage)
#define PORTAL_GET _IOWR('B', 19, PortalMessage)
#define PORTAL_REGS _IOWR('B', 20, PortalMessage)
#define PORTAL_SET_FCLK_RATE _IOWR('B', 40, PortalClockRequest)
PortalInterface portal;
void PortalInstance::close()
{
if (fd > 0) {
::close(fd);
fd = -1;
}
}
PortalInstance::PortalInstance(const char *instanceName, PortalIndications *indications)
: indications(indications), fd(-1), instanceName(strdup(instanceName))
{
}
PortalInstance::~PortalInstance()
{
close();
if (instanceName)
free(instanceName);
}
int PortalInstance::open()
{
if (this->fd >= 0)
return 0;
FILE *pgfile = fopen("/sys/devices/amba.0/f8007000.devcfg/prog_done", "r");
if (pgfile == 0) {
ALOGE("failed to open /sys/devices/amba.0/f8007000.devcfg/prog_done %d\n", errno);
return -1;
}
char line[128];
fgets(line, sizeof(line), pgfile);
if (line[0] != '1') {
ALOGE("FPGA not programmed: %s\n", line);
return -ENODEV;
}
fclose(pgfile);
char path[128];
snprintf(path, sizeof(path), "/dev/%s", instanceName);
this->fd = ::open(path, O_RDWR);
if (this->fd < 0) {
ALOGE("Failed to open %s fd=%d errno=%d\n", path, this->fd, path);
return -errno;
}
hwregs = (volatile unsigned int*)mmap(NULL, 2<<PAGE_SHIFT, PROT_READ|PROT_WRITE, MAP_SHARED, this->fd, 0);
if (hwregs == MAP_FAILED) {
ALOGE("Failed to mmap PortalHWRegs from fd=%d errno=%d\n", this->fd, errno);
return -errno;
}
portal.registerInstance(this);
return 0;
}
PortalInstance *portalOpen(const char *instanceName)
{
PortalInstance *instance = new PortalInstance(instanceName);
instance->open();
return instance;
}
int PortalInstance::sendMessage(PortalMessage *msg)
{
int rc = open();
if (rc != 0) {
ALOGD("PortalInstance::sendMessage fd=%d rc=%d\n", fd, rc);
return rc;
}
rc = ioctl(fd, PORTAL_PUT, msg);
//ALOGD("sendmessage portal fd=%d rc=%d\n", fd, rc);
if (rc)
ALOGE("PortalInstance::sendMessage fd=%d rc=%d errno=%d:%s PUTGET=%x PUT=%x GET=%x\n", fd, rc, errno, strerror(errno),
PORTAL_PUTGET, PORTAL_PUT, PORTAL_GET);
return rc;
}
int PortalInstance::receiveMessage(PortalMessage *msg)
{
int rc = open();
if (rc != 0) {
ALOGD("PortalInstance::receiveMessage fd=%d rc=%d\n", fd, rc);
return 0;
}
int status = ioctl(fd, PORTAL_GET, msg);
if (status) {
if (errno != EAGAIN)
fprintf(stderr, "receiveMessage rc=%d errno=%d:%s\n", status, errno, strerror(errno));
return 0;
}
return 1;
}
PortalInterface::PortalInterface()
: fds(0), numFds(0)
{
}
PortalInterface::~PortalInterface()
{
if (fds) {
::free(fds);
fds = 0;
}
}
int PortalInterface::registerInstance(PortalInstance *instance)
{
numFds++;
instances = (PortalInstance **)realloc(instances, numFds*sizeof(PortalInstance *));
instances[numFds-1] = instance;
fds = (struct pollfd *)realloc(fds, numFds*sizeof(struct pollfd));
struct pollfd *pollfd = &fds[numFds-1];
memset(pollfd, 0, sizeof(struct pollfd));
pollfd->fd = instance->fd;
pollfd->events = POLLIN;
return 0;
}
int PortalInterface::alloc(size_t size, int *fd, PortalAlloc *portalAlloc)
{
if (!portal.numFds) {
ALOGE("%s No fds open\n", __FUNCTION__);
return -ENODEV;
}
PortalAlloc alloc;
memset(&alloc, 0, sizeof(alloc));
void *ptr = 0;
alloc.size = size;
int rc = ioctl(portal.fds[0].fd, PORTAL_ALLOC, &alloc);
if (rc)
return rc;
ptr = mmap(0, alloc.size, PROT_READ|PROT_WRITE, MAP_SHARED, alloc.fd, 0);
fprintf(stderr, "alloc size=%d rc=%d alloc.fd=%d ptr=%p\n", size, rc, alloc.fd, ptr);
if (fd)
*fd = alloc.fd;
if (portalAlloc)
*portalAlloc = alloc;
return 0;
}
int PortalInterface::free(int fd)
{
return 0;
}
int PortalInterface::setClockFrequency(int clkNum, long requestedFrequency, long *actualFrequency)
{
if (!portal.numFds) {
ALOGE("%s No fds open\n", __FUNCTION__);
return -ENODEV;
}
PortalClockRequest request;
request.clknum = clkNum;
request.requested_rate = requestedFrequency;
int status = ioctl(portal.fds[0].fd, PORTAL_SET_FCLK_RATE, (long)&request);
if (status == 0 && actualFrequency)
*actualFrequency = request.actual_rate;
if (status < 0)
status = errno;
return status;
}
int PortalInterface::dumpRegs()
{
if (!portal.numFds) {
ALOGE("%s No fds open\n", __FUNCTION__);
return -ENODEV;
}
int foo = 0;
int rc = ioctl(portal.fds[0].fd, PORTAL_REGS, &foo);
return rc;
}
int PortalInterface::exec(idleFunc func)
{
unsigned int *buf = new unsigned int[1024];
PortalMessage *msg = (PortalMessage *)(buf);
if (!portal.numFds) {
ALOGE("PortalInterface::exec No fds open numFds=%d\n", portal.numFds);
return -ENODEV;
}
int rc;
while ((rc = poll(portal.fds, portal.numFds, -1)) >= 0) {
for (int i = 0; i < portal.numFds; i++) {
if (portal.fds[i].revents == 0)
continue;
if (!portal.instances) {
fprintf(stderr, "No instances but rc=%d revents=%d\n", rc, portal.fds[i].revents);
}
PortalInstance *instance = portal.instances[i];
memset(buf, 0, 1024);
// sanity check, to see the status of interrupt source and enable
volatile unsigned int int_src = *(instance->hwregs+0x0);
volatile unsigned int int_en = *(instance->hwregs+0x1);
fprintf(stderr, "portal.instance[%d]: int_src=%08x int_en=%08x\n", i, int_src,int_en);
// handle all messasges from this portal instance
int messageReceived = instance->receiveMessage(msg);
while (messageReceived) {
fprintf(stderr, "messageReceived: msg->size=%d msg->channel=%d\n", msg->size, msg->channel);
if (msg->size && instance->indications)
instance->indications->handleMessage(msg);
messageReceived = instance->receiveMessage(msg);
}
// re-enable interupt which was disabled by portal_isr
*(instance->hwregs+0x1) = 1;
}
// rc of 0 indicates timeout
if (rc == 0) {
if (0)
ALOGD("poll timeout rc=%d errno=%d:%s func=%p\n", rc, errno, strerror(errno), func);
if (func)
func();
}
}
// return only in error case
fprintf(stderr, "poll returned rc=%d errno=%d:%s\n", rc, errno, strerror(errno));
return rc;
}
<commit_msg>removed noisy debug<commit_after>
// Copyright (c) 2012 Nokia, Inc.
// 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 <errno.h>
#include <fcntl.h>
#include <linux/ioctl.h>
#include <linux/types.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "portal.h"
#include <sys/cdefs.h>
#include <android/log.h>
#define ALOGD(fmt, ...) __android_log_print(ANDROID_LOG_DEBUG, "PORTAL", fmt, __VA_ARGS__)
#define ALOGE(fmt, ...) __android_log_print(ANDROID_LOG_ERROR, "PORTAL", fmt, __VA_ARGS__)
#define PORTAL_ALLOC _IOWR('B', 10, PortalAlloc)
#define PORTAL_PUTGET _IOWR('B', 17, PortalMessage)
#define PORTAL_PUT _IOWR('B', 18, PortalMessage)
#define PORTAL_GET _IOWR('B', 19, PortalMessage)
#define PORTAL_REGS _IOWR('B', 20, PortalMessage)
#define PORTAL_SET_FCLK_RATE _IOWR('B', 40, PortalClockRequest)
PortalInterface portal;
void PortalInstance::close()
{
if (fd > 0) {
::close(fd);
fd = -1;
}
}
PortalInstance::PortalInstance(const char *instanceName, PortalIndications *indications)
: indications(indications), fd(-1), instanceName(strdup(instanceName))
{
}
PortalInstance::~PortalInstance()
{
close();
if (instanceName)
free(instanceName);
}
int PortalInstance::open()
{
if (this->fd >= 0)
return 0;
FILE *pgfile = fopen("/sys/devices/amba.0/f8007000.devcfg/prog_done", "r");
if (pgfile == 0) {
ALOGE("failed to open /sys/devices/amba.0/f8007000.devcfg/prog_done %d\n", errno);
return -1;
}
char line[128];
fgets(line, sizeof(line), pgfile);
if (line[0] != '1') {
ALOGE("FPGA not programmed: %s\n", line);
return -ENODEV;
}
fclose(pgfile);
char path[128];
snprintf(path, sizeof(path), "/dev/%s", instanceName);
this->fd = ::open(path, O_RDWR);
if (this->fd < 0) {
ALOGE("Failed to open %s fd=%d errno=%d\n", path, this->fd, path);
return -errno;
}
hwregs = (volatile unsigned int*)mmap(NULL, 2<<PAGE_SHIFT, PROT_READ|PROT_WRITE, MAP_SHARED, this->fd, 0);
if (hwregs == MAP_FAILED) {
ALOGE("Failed to mmap PortalHWRegs from fd=%d errno=%d\n", this->fd, errno);
return -errno;
}
portal.registerInstance(this);
return 0;
}
PortalInstance *portalOpen(const char *instanceName)
{
PortalInstance *instance = new PortalInstance(instanceName);
instance->open();
return instance;
}
int PortalInstance::sendMessage(PortalMessage *msg)
{
int rc = open();
if (rc != 0) {
ALOGD("PortalInstance::sendMessage fd=%d rc=%d\n", fd, rc);
return rc;
}
rc = ioctl(fd, PORTAL_PUT, msg);
//ALOGD("sendmessage portal fd=%d rc=%d\n", fd, rc);
if (rc)
ALOGE("PortalInstance::sendMessage fd=%d rc=%d errno=%d:%s PUTGET=%x PUT=%x GET=%x\n", fd, rc, errno, strerror(errno),
PORTAL_PUTGET, PORTAL_PUT, PORTAL_GET);
return rc;
}
int PortalInstance::receiveMessage(PortalMessage *msg)
{
int rc = open();
if (rc != 0) {
ALOGD("PortalInstance::receiveMessage fd=%d rc=%d\n", fd, rc);
return 0;
}
int status = ioctl(fd, PORTAL_GET, msg);
if (status) {
if (errno != EAGAIN)
fprintf(stderr, "receiveMessage rc=%d errno=%d:%s\n", status, errno, strerror(errno));
return 0;
}
return 1;
}
PortalInterface::PortalInterface()
: fds(0), numFds(0)
{
}
PortalInterface::~PortalInterface()
{
if (fds) {
::free(fds);
fds = 0;
}
}
int PortalInterface::registerInstance(PortalInstance *instance)
{
numFds++;
instances = (PortalInstance **)realloc(instances, numFds*sizeof(PortalInstance *));
instances[numFds-1] = instance;
fds = (struct pollfd *)realloc(fds, numFds*sizeof(struct pollfd));
struct pollfd *pollfd = &fds[numFds-1];
memset(pollfd, 0, sizeof(struct pollfd));
pollfd->fd = instance->fd;
pollfd->events = POLLIN;
return 0;
}
int PortalInterface::alloc(size_t size, int *fd, PortalAlloc *portalAlloc)
{
if (!portal.numFds) {
ALOGE("%s No fds open\n", __FUNCTION__);
return -ENODEV;
}
PortalAlloc alloc;
memset(&alloc, 0, sizeof(alloc));
void *ptr = 0;
alloc.size = size;
int rc = ioctl(portal.fds[0].fd, PORTAL_ALLOC, &alloc);
if (rc)
return rc;
ptr = mmap(0, alloc.size, PROT_READ|PROT_WRITE, MAP_SHARED, alloc.fd, 0);
fprintf(stderr, "alloc size=%d rc=%d alloc.fd=%d ptr=%p\n", size, rc, alloc.fd, ptr);
if (fd)
*fd = alloc.fd;
if (portalAlloc)
*portalAlloc = alloc;
return 0;
}
int PortalInterface::free(int fd)
{
return 0;
}
int PortalInterface::setClockFrequency(int clkNum, long requestedFrequency, long *actualFrequency)
{
if (!portal.numFds) {
ALOGE("%s No fds open\n", __FUNCTION__);
return -ENODEV;
}
PortalClockRequest request;
request.clknum = clkNum;
request.requested_rate = requestedFrequency;
int status = ioctl(portal.fds[0].fd, PORTAL_SET_FCLK_RATE, (long)&request);
if (status == 0 && actualFrequency)
*actualFrequency = request.actual_rate;
if (status < 0)
status = errno;
return status;
}
int PortalInterface::dumpRegs()
{
if (!portal.numFds) {
ALOGE("%s No fds open\n", __FUNCTION__);
return -ENODEV;
}
int foo = 0;
int rc = ioctl(portal.fds[0].fd, PORTAL_REGS, &foo);
return rc;
}
int PortalInterface::exec(idleFunc func)
{
unsigned int *buf = new unsigned int[1024];
PortalMessage *msg = (PortalMessage *)(buf);
if (!portal.numFds) {
ALOGE("PortalInterface::exec No fds open numFds=%d\n", portal.numFds);
return -ENODEV;
}
int rc;
while ((rc = poll(portal.fds, portal.numFds, -1)) >= 0) {
for (int i = 0; i < portal.numFds; i++) {
if (portal.fds[i].revents == 0)
continue;
if (!portal.instances) {
fprintf(stderr, "No instances but rc=%d revents=%d\n", rc, portal.fds[i].revents);
}
PortalInstance *instance = portal.instances[i];
memset(buf, 0, 1024);
// sanity check, to see the status of interrupt source and enable
volatile unsigned int int_src = *(instance->hwregs+0x0);
volatile unsigned int int_en = *(instance->hwregs+0x1);
//fprintf(stderr, "portal.instance[%d]: int_src=%08x int_en=%08x\n", i, int_src,int_en);
// handle all messasges from this portal instance
int messageReceived = instance->receiveMessage(msg);
while (messageReceived) {
//fprintf(stderr, "messageReceived: msg->size=%d msg->channel=%d\n", msg->size, msg->channel);
if (msg->size && instance->indications)
instance->indications->handleMessage(msg);
messageReceived = instance->receiveMessage(msg);
}
// re-enable interupt which was disabled by portal_isr
*(instance->hwregs+0x1) = 1;
}
// rc of 0 indicates timeout
if (rc == 0) {
if (0)
ALOGD("poll timeout rc=%d errno=%d:%s func=%p\n", rc, errno, strerror(errno), func);
if (func)
func();
}
}
// return only in error case
fprintf(stderr, "poll returned rc=%d errno=%d:%s\n", rc, errno, strerror(errno));
return rc;
}
<|endoftext|>
|
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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 "paddle/framework/backward.h"
#include <list>
#include <memory>
#include "paddle/framework/op_registry.h"
#include "paddle/operators/net_op.h"
#include "paddle/operators/recurrent_op.h"
namespace paddle {
namespace framework {
template <typename Map, typename T>
static void ForEachVarName(const Map& names, T callback) {
for (auto& name : names) {
for (auto& n : name.second) {
if (callback(n)) return;
}
}
}
// return whether all the names + suffixes in the set
static bool AllInSet(
const std::map<std::string, std::vector<std::string>>& names,
const std::string& suffix, const std::unordered_set<std::string>& set) {
bool all_in_set = true;
ForEachVarName(names, [&all_in_set, &set, &suffix](const std::string& n) {
all_in_set = set.find(n + suffix) != set.end();
return !all_in_set;
});
return all_in_set;
}
static std::unique_ptr<OperatorBase> NOP() {
auto net_op = new operators::NetOp();
net_op->SetType("@NOP@");
net_op->CompleteAddOp();
return std::unique_ptr<OperatorBase>(net_op);
}
// Get backward operator from a forward operator, a recursive implementation.
//
// no_grad_names the gradient variable names without gradient calculating.
//
// uniq_id is a unique index used inside recursively calling
// BackwardRecursive. use `uid = uniq_id++;` to get the unique index, and
// pass `uniq_id` through recursive calling.
//
// returns The backward operator. In a simple situation, it may be a simple
// operator, in a complex situation, it maybe a NetOp.
//
// See Backward.h for details
static std::unique_ptr<OperatorBase> BackwardRecursive(
const OperatorBase& forwardOp,
std::unordered_set<std::string>& no_grad_names, size_t& uniq_id) {
// If all input gradients of forwarding operator do not need to calculate,
// just return an NOP. Not return null ptr because NOP does not take
// too much time for calculation, but it is useful for simplifying logic.
if (AllInSet(forwardOp.Inputs() /*names*/, kGradVarSuffix /*suffix*/,
no_grad_names /*set*/)) {
return NOP();
}
// All output gradients of forwarding operator do not need to calculate.
// Then all input gradients cannot be computed at all, and we put them into
// `no_grad_names` set. Return an NOP.
if (AllInSet(forwardOp.Outputs() /*names*/, kGradVarSuffix /*suffix*/,
no_grad_names /*set*/)) {
ForEachVarName(forwardOp.Inputs(),
[&no_grad_names](const std::string& name) -> bool {
no_grad_names.insert(GradVarName(name));
return false;
});
return NOP();
}
// Returned gradient network
auto net = std::unique_ptr<operators::NetOp>(new operators::NetOp());
if (forwardOp.IsNetOp()) {
// Because forwardOp is a net op, it can static_cast.
auto& forwardNet = static_cast<const operators::NetOp&>(forwardOp);
// Map from output gradient variable name to operator's indices in
// backward net's ops_. That operator generates that variable.
std::unordered_map<std::string, std::vector<size_t>> dup_output_ops;
size_t local_op_id = 0;
// reversely travel forwardNet and collect all duplicate outputs.
for (auto it = forwardNet.ops_.rbegin(); it != forwardNet.ops_.rend();
++it, ++local_op_id) {
auto& fwd = *it;
auto bwd = BackwardRecursive(*fwd, no_grad_names, uniq_id);
ForEachVarName(bwd->Outputs(),
[&dup_output_ops, local_op_id](const std::string& out) {
dup_output_ops[out].emplace_back(local_op_id);
return false;
});
net->AppendOp(std::move(bwd));
}
// Get unique ID for this method.
auto uid = uniq_id++;
// TODO(dzh): more comment
// multiple operators which have the same output (y for example) may
// overwrite the same y variable when backward, special operations are token
// to handle this case. For each duplicate output, rename it to an alias
// (original name with a offset), append an `add` op for its operator,
// and finally sum all the alias variable to the final output variable y.
using Pos = std::pair<size_t, std::unique_ptr<OperatorBase>>;
std::list<Pos> insert_position;
for (auto& dup_output_op : dup_output_ops) {
const std::string& name = dup_output_op.first;
// duplicate @Empty@ don't need to be added
if (name == kEmptyVarName) continue;
auto& dup_op = dup_output_op.second;
// no duplicate output
if (dup_op.size() == 1) continue;
// process the duplicate outputs
std::vector<std::string> dup_outputs;
for (size_t i = 0; i < dup_op.size(); ++i) {
// rename each duplicate output to an alias
auto op_offset = dup_op[i];
dup_outputs.push_back(name + "@RENAME@" + std::to_string(uid) + "@" +
std::to_string(i));
net->ops_[op_offset]->Rename(name, dup_outputs.back());
}
// collect all the offset to append `add` op for each alias
insert_position.push_back(
{dup_op.back(), OpRegistry::CreateOp("add", {{"X", {dup_outputs}}},
{{"Out", {name}}}, {})});
}
// make sure the inserted `add` ops follow the BFS order.
insert_position.sort(
[](const Pos& l, const Pos& r) { return l.first > r.first; });
for (auto& pos : insert_position) {
net->InsertOp(pos.first + 1, std::move(pos.second));
}
} else {
std::unique_ptr<OperatorBase> grad_op(OpRegistry::CreateGradOp(forwardOp));
ForEachVarName(grad_op->Inputs(), [&no_grad_names, &net, &grad_op](
const std::string& grad_input) {
if (no_grad_names.count(grad_input)) {
// +1 for \0
std::string prefix = grad_input.substr(
0, grad_input.size() - sizeof(kGradVarSuffix) / sizeof(char) + 1);
grad_op->Rename(grad_input, prefix + kZeroVarSuffix);
// If part of input gradient of that operator is not calculated, fill
// zero variables to that input gradient.
net->AppendOp(OpRegistry::CreateOp("fill_zeros_like", {{"X", {prefix}}},
{{"Y", {grad_input}}}, {}));
}
return false;
});
ForEachVarName(grad_op->Outputs(),
[&no_grad_names, &grad_op](const std::string& grad_output) {
if (no_grad_names.count(grad_output)) {
grad_op->Rename(grad_output, kEmptyVarName);
}
return false;
});
// process recurrent gradient op as a special operator.
if (forwardOp.Type() == "recurrent") {
// NOTE clean up cycle call somewhere (RNN's stepnet constains itself), or
// this will result in infinite loop.
const auto& rnnop =
*static_cast<const operators::RecurrentOp*>(&forwardOp);
auto rnn_grad_op =
static_cast<operators::RecurrentGradientOp*>(grad_op.get());
const auto& stepnet_op =
*static_cast<const OperatorBase*>(&rnnop.stepnet());
// create stepnet's gradient op
rnn_grad_op->set_stepnet(
BackwardRecursive(stepnet_op, no_grad_names, uniq_id));
}
if (net->ops_.empty()) { // Current no aux op is added to network
return grad_op;
}
net->AppendOp(std::move(grad_op));
}
net->SetType("@GENERATED_BACKWARD@");
net->CompleteAddOp();
return std::unique_ptr<OperatorBase>(
static_cast<OperatorBase*>(net.release()));
}
// See header for comments
std::unique_ptr<OperatorBase> Backward(
const OperatorBase& forwardOp,
const std::unordered_set<std::string>& no_grad_vars) {
std::unordered_set<std::string> no_grad_names;
no_grad_names.reserve(no_grad_vars.size() + 1);
no_grad_names.insert(std::string(kEmptyVarName) + kGradVarSuffix);
for (auto& name : no_grad_vars) {
no_grad_names.insert(name + kGradVarSuffix);
}
size_t uid = 0;
return BackwardRecursive(forwardOp, no_grad_names, uid);
}
} // namespace framework
} // namespace paddle
<commit_msg>add generic add operator<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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 "paddle/framework/backward.h"
#include <list>
#include <memory>
#include "paddle/framework/op_registry.h"
#include "paddle/operators/net_op.h"
#include "paddle/operators/recurrent_op.h"
namespace paddle {
namespace framework {
template <typename Map, typename T>
static void ForEachVarName(const Map& names, T callback) {
for (auto& name : names) {
for (auto& n : name.second) {
if (callback(n)) return;
}
}
}
// return whether all the names + suffixes in the set
static bool AllInSet(
const std::map<std::string, std::vector<std::string>>& names,
const std::string& suffix, const std::unordered_set<std::string>& set) {
bool all_in_set = true;
ForEachVarName(names, [&all_in_set, &set, &suffix](const std::string& n) {
all_in_set = set.find(n + suffix) != set.end();
return !all_in_set;
});
return all_in_set;
}
static std::unique_ptr<OperatorBase> NOP() {
auto net_op = new operators::NetOp();
net_op->SetType("@NOP@");
net_op->CompleteAddOp();
return std::unique_ptr<OperatorBase>(net_op);
}
// Get backward operator from a forward operator, a recursive implementation.
//
// no_grad_names the gradient variable names without gradient calculating.
//
// uniq_id is a unique index used inside recursively calling
// BackwardRecursive. use `uid = uniq_id++;` to get the unique index, and
// pass `uniq_id` through recursive calling.
//
// returns The backward operator. In a simple situation, it may be a simple
// operator, in a complex situation, it maybe a NetOp.
//
// See Backward.h for details
static std::unique_ptr<OperatorBase> BackwardRecursive(
const OperatorBase& forwardOp,
std::unordered_set<std::string>& no_grad_names, size_t& uniq_id) {
// If all input gradients of forwarding operator do not need to calculate,
// just return an NOP. Not return null ptr because NOP does not take
// too much time for calculation, but it is useful for simplifying logic.
if (AllInSet(forwardOp.Inputs() /*names*/, kGradVarSuffix /*suffix*/,
no_grad_names /*set*/)) {
return NOP();
}
// All output gradients of forwarding operator do not need to calculate.
// Then all input gradients cannot be computed at all, and we put them into
// `no_grad_names` set. Return an NOP.
if (AllInSet(forwardOp.Outputs() /*names*/, kGradVarSuffix /*suffix*/,
no_grad_names /*set*/)) {
ForEachVarName(forwardOp.Inputs(),
[&no_grad_names](const std::string& name) -> bool {
no_grad_names.insert(GradVarName(name));
return false;
});
return NOP();
}
// Returned gradient network
auto net = std::unique_ptr<operators::NetOp>(new operators::NetOp());
if (forwardOp.IsNetOp()) {
// Because forwardOp is a net op, it can static_cast.
auto& forwardNet = static_cast<const operators::NetOp&>(forwardOp);
// Map from output gradient variable name to operator's indices in
// backward net's ops_. That operator generates that variable.
std::unordered_map<std::string, std::vector<size_t>> dup_output_ops;
size_t local_op_id = 0;
// reversely travel forwardNet and collect all duplicate outputs.
for (auto it = forwardNet.ops_.rbegin(); it != forwardNet.ops_.rend();
++it, ++local_op_id) {
auto& fwd = *it;
auto bwd = BackwardRecursive(*fwd, no_grad_names, uniq_id);
ForEachVarName(bwd->Outputs(),
[&dup_output_ops, local_op_id](const std::string& out) {
dup_output_ops[out].emplace_back(local_op_id);
return false;
});
net->AppendOp(std::move(bwd));
}
// Get unique ID for this method.
auto uid = uniq_id++;
// TODO(dzh): more comment
// multiple operators which have the same output (y for example) may
// overwrite the same y variable when backward, special operations are token
// to handle this case. For each duplicate output, rename it to an alias
// (original name with a offset), append an `add` op for its operator,
// and finally sum all the alias variable to the final output variable y.
using Pos = std::pair<size_t, std::unique_ptr<OperatorBase>>;
std::list<Pos> insert_position;
for (auto& dup_output_op : dup_output_ops) {
const std::string& name = dup_output_op.first;
// duplicate @Empty@ don't need to be added
if (name == kEmptyVarName) continue;
auto& dup_op = dup_output_op.second;
// no duplicate output
if (dup_op.size() == 1) continue;
// process the duplicate outputs
std::vector<std::string> dup_outputs;
for (size_t i = 0; i < dup_op.size(); ++i) {
// rename each duplicate output to an alias
auto op_offset = dup_op[i];
dup_outputs.push_back(name + "@RENAME@" + std::to_string(uid) + "@" +
std::to_string(i));
net->ops_[op_offset]->Rename(name, dup_outputs.back());
}
// collect all the offset to append `add` op for each alias
//
// one variable is shared between multiple operators.
// insert add operator one by one, then add it to output
if (dup_outputs.size() == 2) {
insert_position.push_back(
{dup_op.back(),
OpRegistry::CreateOp(
"add", {{"X", {dup_outputs[0]}}, {"Y", {dup_outputs[1]}}},
{{"Out", {name}}}, {})});
} else {
for (size_t output_idx = 0; output_idx < dup_outputs.size() - 1;
++output_idx) {
auto insert_add_x = dup_outputs[output_idx];
auto insert_add_y = dup_outputs[output_idx];
auto insert_add_out = name + "@SHARED@" + std::to_string(output_idx);
// first add op inserted
if (output_idx == dup_outputs.size() - 1) {
insert_add_out = name;
}
if (output_idx != 0) {
insert_add_y = name + "@SHARED@" + std::to_string(output_idx);
}
insert_position.push_back(
{dup_op.back(),
OpRegistry::CreateOp(
"add", {{"X", {insert_add_x}}, {"Y", {insert_add_y}}},
{{"Out", {insert_add_out}}}, {})});
}
}
}
// make sure the inserted `add` ops follow the BFS order.
insert_position.sort(
[](const Pos& l, const Pos& r) { return l.first > r.first; });
for (auto& pos : insert_position) {
net->InsertOp(pos.first + 1, std::move(pos.second));
}
} else {
std::unique_ptr<OperatorBase> grad_op(OpRegistry::CreateGradOp(forwardOp));
ForEachVarName(grad_op->Inputs(), [&no_grad_names, &net, &grad_op](
const std::string& grad_input) {
if (no_grad_names.count(grad_input)) {
// +1 for \0
std::string prefix = grad_input.substr(
0, grad_input.size() - sizeof(kGradVarSuffix) / sizeof(char) + 1);
grad_op->Rename(grad_input, prefix + kZeroVarSuffix);
// If part of input gradient of that operator is not calculated, fill
// zero variables to that input gradient.
net->AppendOp(OpRegistry::CreateOp("fill_zeros_like", {{"X", {prefix}}},
{{"Y", {grad_input}}}, {}));
}
return false;
});
ForEachVarName(grad_op->Outputs(),
[&no_grad_names, &grad_op](const std::string& grad_output) {
if (no_grad_names.count(grad_output)) {
grad_op->Rename(grad_output, kEmptyVarName);
}
return false;
});
// process recurrent gradient op as a special operator.
if (forwardOp.Type() == "recurrent") {
// NOTE clean up cycle call somewhere (RNN's stepnet constains itself), or
// this will result in infinite loop.
const auto& rnnop =
*static_cast<const operators::RecurrentOp*>(&forwardOp);
auto rnn_grad_op =
static_cast<operators::RecurrentGradientOp*>(grad_op.get());
const auto& stepnet_op =
*static_cast<const OperatorBase*>(&rnnop.stepnet());
// create stepnet's gradient op
rnn_grad_op->set_stepnet(
BackwardRecursive(stepnet_op, no_grad_names, uniq_id));
}
if (net->ops_.empty()) { // Current no aux op is added to network
return grad_op;
}
net->AppendOp(std::move(grad_op));
}
net->SetType("@GENERATED_BACKWARD@");
net->CompleteAddOp();
return std::unique_ptr<OperatorBase>(
static_cast<OperatorBase*>(net.release()));
}
// See header for comments
std::unique_ptr<OperatorBase> Backward(
const OperatorBase& forwardOp,
const std::unordered_set<std::string>& no_grad_vars) {
std::unordered_set<std::string> no_grad_names;
no_grad_names.reserve(no_grad_vars.size() + 1);
no_grad_names.insert(std::string(kEmptyVarName) + kGradVarSuffix);
for (auto& name : no_grad_vars) {
no_grad_names.insert(name + kGradVarSuffix);
}
size_t uid = 0;
return BackwardRecursive(forwardOp, no_grad_names, uid);
}
} // namespace framework
} // namespace paddle
<|endoftext|>
|
<commit_before>#ifndef __PROCESS_COLLECT_HPP__
#define __PROCESS_COLLECT_HPP__
#include <assert.h>
#include <set>
#include <process/defer.hpp>
#include <process/future.hpp>
#include <process/process.hpp>
namespace process {
// Waits on each future in the specified set and returns the set of
// resulting values. If any future is discarded then the result will
// be a failure. Likewise, if any future fails than the result future
// will be a failure.
template <typename T>
Future<std::set<T> > collect(std::set<Future<T> >& futures);
namespace internal {
template <typename T>
class CollectProcess : public Process<CollectProcess<T> >
{
public:
CollectProcess(
const std::set<Future<T> >& _futures,
Promise<std::set<T> >* _promise)
: futures(_futures), promise(_promise) {}
virtual ~CollectProcess()
{
delete promise;
}
virtual void initialize()
{
// Stop this nonsense if nobody cares.
promise->future().onDiscarded(defer(this, &CollectProcess::discarded));
typename std::set<Future<T> >::iterator iterator;
for (iterator = futures.begin(); iterator != futures.end(); ++iterator) {
const Future<T>& future = *iterator;
future.onAny(defer(this, &CollectProcess::waited, future));
}
}
private:
void discarded()
{
terminate(this);
}
void waited(const Future<T>& future)
{
if (future.isFailed()) {
promise->fail("Collect failed: " + future.failure());
} else if (future.isDiscarded()) {
promise->fail("Collect failed: future discarded");
} else {
assert(future.isReady());
values.insert(future.get());
if (futures.size() == values.size()) {
promise->set(values);
terminate(this);
}
}
}
std::set<Future<T> > futures;
Promise<std::set<T> >* promise;
std::set<T> values;
};
} // namespace internal {
template <typename T>
inline Future<std::set<T> > collect(std::set<Future<T> >& futures)
{
Promise<std::set<T> >* promise = new Promise<std::set<T> >();
spawn(new internal::CollectProcess<T>(futures, promise), true);
return promise->future();
}
} // namespace process {
#endif // __PROCESS_COLLECT_HPP__
<commit_msg>making collect more stl general<commit_after>#ifndef __PROCESS_COLLECT_HPP__
#define __PROCESS_COLLECT_HPP__
#include <assert.h>
#include <set>
#include <process/defer.hpp>
#include <process/future.hpp>
#include <process/process.hpp>
namespace process {
// Waits on each future in the specified set and returns the set of
// resulting values. If any future is discarded then the result will
// be a failure. Likewise, if any future fails than the result future
// will be a failure.
template <typename T>
Future<std::list<T> > collect(std::list<Future<T> >& futures);
namespace internal {
template <typename T>
class CollectProcess : public Process<CollectProcess<T> >
{
public:
CollectProcess(
const std::list<Future<T> >& _futures,
Promise<std::list<T> >* _promise)
: futures(_futures), promise(_promise) {}
virtual ~CollectProcess()
{
delete promise;
}
virtual void initialize()
{
// Stop this nonsense if nobody cares.
promise->future().onDiscarded(defer(this, &CollectProcess::discarded));
typename std::list<Future<T> >::iterator iterator;
for (iterator = futures.begin(); iterator != futures.end(); ++iterator) {
const Future<T>& future = *iterator;
future.onAny(defer(this, &CollectProcess::waited, future));
}
}
private:
void discarded()
{
terminate(this);
}
void waited(const Future<T>& future)
{
if (future.isFailed()) {
promise->fail("Collect failed: " + future.failure());
} else if (future.isDiscarded()) {
promise->fail("Collect failed: future discarded");
} else {
assert(future.isReady());
values.push_back(future.get());
if (futures.size() == values.size()) {
promise->set(values);
terminate(this);
}
}
}
std::list<Future<T> > futures;
Promise<std::list<T> >* promise;
std::list<T> values;
};
} // namespace internal {
template <typename T>
inline Future<std::list<T> > collect(std::list<Future<T> >& futures)
{
Promise<std::list<T> >* promise = new Promise<std::list<T> >();
spawn(new internal::CollectProcess<T>(futures, promise), true);
return promise->future();
}
} // namespace process {
#endif // __PROCESS_COLLECT_HPP__
<|endoftext|>
|
<commit_before>// Copyright (c) 2018 PaddlePaddle 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 "paddle/fluid/imperative/layer.h"
#include <deque>
#include <limits>
#include <map>
#include <random>
#include <utility>
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/string/printf.h"
namespace paddle {
namespace imperative {
using framework::Variable;
void AddTo(Variable* src, Variable* dst) {
framework::LoDTensor* dst_tensor = dst->GetMutable<framework::LoDTensor>();
framework::LoDTensor* src_tensor = src->GetMutable<framework::LoDTensor>();
PADDLE_ENFORCE(dst_tensor->numel() == src_tensor->numel(), "%lld vs %lld",
dst_tensor->numel(), src_tensor->numel());
float* dst_data = dst_tensor->mutable_data<float>(platform::CPUPlace());
const float* src_data = src_tensor->data<float>();
for (size_t i = 0; i < src_tensor->numel(); ++i) {
dst_data[i] += src_data[i];
}
}
class Autograd {
public:
explicit Autograd(framework::Scope* scope) : scope_(scope) {}
void RunBackward(VarBase* var) {
PADDLE_ENFORCE(var->pre_op_->op_desc_);
// TODO(panyx0718): Only create for vars that "require_grad"
(*var->pre_op_->output_vars_)[var->pre_op_out_idx_]->grads_ = var->grads_;
std::deque<OpBase*> ready;
ready.push_back(var->pre_op_);
std::map<OpBase*, int> dep_counts = ComputeDepCounts(var->pre_op_);
while (!ready.empty()) {
OpBase* ready_op = ready.front();
ready.pop_front();
std::vector<Variable*> input_grads = ready_op->ApplyGrad(scope_);
for (size_t i = 0; i < input_grads.size(); ++i) {
if (!input_grads[i]) continue;
OpBase* pre_op = ready_op->pre_ops_->at(i);
if (!pre_op) continue;
dep_counts[pre_op] -= 1;
PADDLE_ENFORCE(dep_counts[pre_op] >= 0);
bool pre_op_ready = dep_counts[pre_op] == 0;
if (pre_op_ready) {
ready.push_back(pre_op);
}
}
}
}
private:
std::map<OpBase*, int> ComputeDepCounts(OpBase* op) {
std::map<OpBase*, int> ret;
std::deque<OpBase*> queue;
queue.push_back(op);
std::unordered_set<OpBase*> visited;
visited.insert(op);
while (!queue.empty()) {
OpBase* candidate = queue.front();
queue.pop_front();
for (OpBase* pre_op : *(candidate->pre_ops_)) {
if (!pre_op) continue;
if (visited.find(pre_op) == visited.end()) {
visited.insert(pre_op);
queue.push_back(pre_op);
}
ret[pre_op] += 1;
}
}
return ret;
}
framework::Scope* scope_;
};
framework::Variable* CreateVariable(const std::string& name,
const framework::DDim& dim, float val,
framework::Scope* scope,
bool random_name = true) {
std::string varname = name;
if (random_name) {
std::mt19937 rng;
rng.seed(std::random_device()());
std::uniform_int_distribution<std::mt19937::result_type> dist6(
1, std::numeric_limits<int>::max());
int id = dist6(rng);
varname = string::Sprintf("%s@%d", varname, id);
}
VLOG(3) << "creating var " << varname;
framework::Variable* var = scope->Var(varname);
framework::LoDTensor* tensor = var->GetMutable<framework::LoDTensor>();
float* data = tensor->mutable_data<float>(dim, platform::CPUPlace());
std::fill(data, data + tensor->numel(), val);
return var;
}
framework::LoDTensor& VarBase::Grad() {
VLOG(3) << "get var grad " << var_desc_->Name();
return *grads_->GetMutable<framework::LoDTensor>();
}
void VarBase::ApplyGrad(framework::Scope* scope, Variable* grad) {
PADDLE_ENFORCE(grad->IsInitialized(), "grad %s must be initialized",
var_desc_->Name());
PADDLE_ENFORCE(grad->Get<framework::LoDTensor>().IsInitialized(),
"variable %s has NO gradient, please set stop_gradient to it",
var_desc_->Name());
VLOG(3) << "apply var grad " << var_desc_->Name() << " "
<< grad->Get<framework::LoDTensor>().data<float>()[0];
if (!grads_) {
grads_ =
CreateVariable(string::Sprintf("%s@IGrad", var_desc_->Name()),
var_->Get<framework::LoDTensor>().dims(), 0.0, scope);
}
AddTo(grad, grads_);
VLOG(3) << "grad_ after apply var grad " << var_desc_->Name() << " "
<< grads_->Get<framework::LoDTensor>().data<float>()[0];
}
std::vector<Variable*> OpBase::ApplyGrad(framework::Scope* scope) {
VLOG(3) << "op grad " << grad_op_desc_->Type();
if (!grad_to_var_) {
return {};
}
for (const std::string& grad_invar : grad_op_desc_->InputArgumentNames()) {
if (grad_to_var_->find(grad_invar) == grad_to_var_->end()) {
// grad op inputs can be forward inputs, so not in grad_to_var.
continue;
}
VLOG(3) << "op grad input var " << grad_invar;
framework::VarDesc& grad_invar_desc =
block_->FindRecursiveOrCreateVar(grad_invar);
framework::Variable* var = scope->Var(grad_invar);
const std::string& invar = grad_to_var_->at(grad_invar);
for (VarBase* varbase : *output_vars_) {
// Use the accumulated grads_ by sharing the input with grads_.
if (varbase->var_desc_->Name() == invar) {
var->GetMutable<framework::LoDTensor>()->ShareDataWith(
varbase->grads_->Get<framework::LoDTensor>());
break;
}
}
grad_invar_desc.SetShape(
framework::vectorize(var->Get<framework::LoDTensor>().dims()));
VLOG(3)
<< "set op grad var desc's shape size "
<< framework::vectorize(var->Get<framework::LoDTensor>().dims()).size();
}
for (const std::string& outvar : grad_op_desc_->OutputArgumentNames()) {
VLOG(3) << "op grad output var " << outvar;
block_->FindRecursiveOrCreateVar(outvar);
framework::Variable* var = scope->Var(outvar);
if (!var->IsInitialized()) {
VLOG(3) << "init op grad output var " << outvar;
framework::VarDesc* var_desc = block_->FindVar(outvar);
if (var_desc->GetType() == framework::proto::VarType::LOD_TENSOR) {
var->GetMutable<framework::LoDTensor>();
} else {
LOG(ERROR) << "tracer doesn't support yet";
}
}
VLOG(3) << "op grad output var " << outvar << " is inited";
}
grad_op_desc_->InferShape(*block_);
grad_op_desc_->InferVarType(block_);
std::unique_ptr<framework::OperatorBase> opbase =
framework::OpRegistry::CreateOp(*grad_op_desc_);
opbase->Run(*scope, platform::CPUPlace());
// `ret` matches exactly with `input_vars_` of forward op.
std::vector<Variable*> ret;
for (size_t i = 0; i < input_vars_->size(); ++i) {
bool found = false;
VarBase* origin_var = (*input_vars_)[i];
for (const std::string& outvar : grad_op_desc_->OutputArgumentNames()) {
Variable* var = scope->FindVar(outvar);
std::string orig_var_name = grad_to_var_->at(outvar);
if (origin_var->var_desc_->Name() != orig_var_name ||
origin_var->stop_gradient_) {
continue;
}
VLOG(3) << "apply grad " << outvar << " with origin " << orig_var_name;
origin_var->ApplyGrad(scope, var);
found = true;
ret.push_back(var);
// TODO(panyx0718): There might be another outvar with the same name.
// In that case, it doesn't matter the first one or the second one is
// used.
break;
}
if (!found) {
ret.push_back(nullptr);
}
}
return ret;
}
void VarBase::RunBackward(framework::Scope* scope) {
grads_ = CreateVariable(framework::GradVarName(var_desc_->Name()),
var_->Get<framework::LoDTensor>().dims(), 1.0, scope,
false);
if (!pre_op_) return;
Autograd(scope).RunBackward(this);
}
} // namespace imperative
} // namespace paddle
<commit_msg>Polish code<commit_after>// Copyright (c) 2018 PaddlePaddle 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 "paddle/fluid/imperative/layer.h"
#include <deque>
#include <limits>
#include <map>
#include <random>
#include <utility>
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/string/printf.h"
namespace paddle {
namespace imperative {
using framework::Variable;
void AddTo(Variable* src, Variable* dst) {
framework::LoDTensor* dst_tensor = dst->GetMutable<framework::LoDTensor>();
framework::LoDTensor* src_tensor = src->GetMutable<framework::LoDTensor>();
PADDLE_ENFORCE(dst_tensor->numel() == src_tensor->numel(), "%lld vs %lld",
dst_tensor->numel(), src_tensor->numel());
float* dst_data = dst_tensor->mutable_data<float>(platform::CPUPlace());
const float* src_data = src_tensor->data<float>();
for (size_t i = 0; i < src_tensor->numel(); ++i) {
dst_data[i] += src_data[i];
}
}
class Autograd {
public:
explicit Autograd(framework::Scope* scope) : scope_(scope) {}
void RunBackward(VarBase* var) {
PADDLE_ENFORCE(var->pre_op_->op_desc_);
// TODO(panyx0718): Only create for vars that "require_grad"
(*var->pre_op_->output_vars_)[var->pre_op_out_idx_]->grads_ = var->grads_;
std::deque<OpBase*> ready;
ready.push_back(var->pre_op_);
std::map<OpBase*, int> dep_counts = ComputeDepCounts(var->pre_op_);
while (!ready.empty()) {
OpBase* ready_op = ready.front();
ready.pop_front();
std::vector<Variable*> input_grads = ready_op->ApplyGrad(scope_);
for (size_t i = 0; i < input_grads.size(); ++i) {
if (!input_grads[i]) continue;
OpBase* pre_op = ready_op->pre_ops_->at(i);
if (!pre_op) continue;
dep_counts[pre_op] -= 1;
PADDLE_ENFORCE(dep_counts[pre_op] >= 0);
bool pre_op_ready = dep_counts[pre_op] == 0;
if (pre_op_ready) {
ready.push_back(pre_op);
}
}
}
}
private:
std::map<OpBase*, int> ComputeDepCounts(OpBase* op) {
std::map<OpBase*, int> ret;
std::deque<OpBase*> queue;
queue.push_back(op);
std::unordered_set<OpBase*> visited;
visited.insert(op);
while (!queue.empty()) {
OpBase* candidate = queue.front();
queue.pop_front();
for (OpBase* pre_op : *(candidate->pre_ops_)) {
if (!pre_op) continue;
if (visited.find(pre_op) == visited.end()) {
visited.insert(pre_op);
queue.push_back(pre_op);
}
ret[pre_op] += 1;
}
}
return ret;
}
framework::Scope* scope_;
};
framework::Variable* CreateVariable(const std::string& name,
const framework::DDim& dim, float val,
framework::Scope* scope,
bool random_name = true) {
std::string varname = name;
if (random_name) {
std::mt19937 rng;
rng.seed(std::random_device()());
std::uniform_int_distribution<std::mt19937::result_type> dist6(
1, std::numeric_limits<int>::max());
int id = dist6(rng);
varname = string::Sprintf("%s@%d", varname, id);
}
VLOG(3) << "creating var " << varname;
framework::Variable* var = scope->Var(varname);
framework::LoDTensor* tensor = var->GetMutable<framework::LoDTensor>();
float* data = tensor->mutable_data<float>(dim, platform::CPUPlace());
std::fill(data, data + tensor->numel(), val);
return var;
}
framework::LoDTensor& VarBase::Grad() {
VLOG(3) << "get var grad " << var_desc_->Name();
return *grads_->GetMutable<framework::LoDTensor>();
}
void VarBase::ApplyGrad(framework::Scope* scope, Variable* grad) {
PADDLE_ENFORCE(grad->IsInitialized(), "grad %s must be initialized",
var_desc_->Name());
PADDLE_ENFORCE(grad->Get<framework::LoDTensor>().IsInitialized(),
"variable %s has NO gradient, please set stop_gradient to it",
var_desc_->Name());
VLOG(3) << "apply var grad " << var_desc_->Name() << " "
<< grad->Get<framework::LoDTensor>().data<float>()[0];
if (!grads_) {
grads_ =
CreateVariable(string::Sprintf("%s@IGrad", var_desc_->Name()),
var_->Get<framework::LoDTensor>().dims(), 0.0, scope);
}
AddTo(grad, grads_);
VLOG(3) << "grad_ after apply var grad " << var_desc_->Name() << " "
<< grads_->Get<framework::LoDTensor>().data<float>()[0];
}
std::vector<Variable*> OpBase::ApplyGrad(framework::Scope* scope) {
VLOG(3) << "op grad " << grad_op_desc_->Type();
for (const std::string& grad_invar : grad_op_desc_->InputArgumentNames()) {
if (grad_to_var_->find(grad_invar) == grad_to_var_->end()) {
// grad op inputs can be forward inputs, so not in grad_to_var.
continue;
}
VLOG(3) << "op grad input var " << grad_invar;
framework::VarDesc& grad_invar_desc =
block_->FindRecursiveOrCreateVar(grad_invar);
framework::Variable* var = scope->Var(grad_invar);
const std::string& invar = grad_to_var_->at(grad_invar);
for (VarBase* varbase : *output_vars_) {
// Use the accumulated grads_ by sharing the input with grads_.
if (varbase->var_desc_->Name() == invar) {
var->GetMutable<framework::LoDTensor>()->ShareDataWith(
varbase->grads_->Get<framework::LoDTensor>());
break;
}
}
grad_invar_desc.SetShape(
framework::vectorize(var->Get<framework::LoDTensor>().dims()));
VLOG(3)
<< "set op grad var desc's shape size "
<< framework::vectorize(var->Get<framework::LoDTensor>().dims()).size();
}
for (const std::string& outvar : grad_op_desc_->OutputArgumentNames()) {
VLOG(3) << "op grad output var " << outvar;
block_->FindRecursiveOrCreateVar(outvar);
framework::Variable* var = scope->Var(outvar);
if (!var->IsInitialized()) {
VLOG(3) << "init op grad output var " << outvar;
framework::VarDesc* var_desc = block_->FindVar(outvar);
if (var_desc->GetType() == framework::proto::VarType::LOD_TENSOR) {
var->GetMutable<framework::LoDTensor>();
} else {
LOG(ERROR) << "tracer doesn't support yet";
}
}
VLOG(3) << "op grad output var " << outvar << " is inited";
}
grad_op_desc_->InferShape(*block_);
grad_op_desc_->InferVarType(block_);
std::unique_ptr<framework::OperatorBase> opbase =
framework::OpRegistry::CreateOp(*grad_op_desc_);
opbase->Run(*scope, platform::CPUPlace());
// `ret` matches exactly with `input_vars_` of forward op.
std::vector<Variable*> ret;
for (size_t i = 0; i < input_vars_->size(); ++i) {
bool found = false;
VarBase* origin_var = (*input_vars_)[i];
for (const std::string& outvar : grad_op_desc_->OutputArgumentNames()) {
Variable* var = scope->FindVar(outvar);
std::string orig_var_name = grad_to_var_->at(outvar);
if (origin_var->var_desc_->Name() != orig_var_name ||
origin_var->stop_gradient_) {
continue;
}
VLOG(3) << "apply grad " << outvar << " with origin " << orig_var_name;
origin_var->ApplyGrad(scope, var);
found = true;
ret.push_back(var);
// TODO(panyx0718): There might be another outvar with the same name.
// In that case, it doesn't matter the first one or the second one is
// used.
break;
}
if (!found) {
ret.push_back(nullptr);
}
}
return ret;
}
void VarBase::RunBackward(framework::Scope* scope) {
grads_ = CreateVariable(framework::GradVarName(var_desc_->Name()),
var_->Get<framework::LoDTensor>().dims(), 1.0, scope,
false);
if (!pre_op_) return;
Autograd(scope).RunBackward(this);
}
} // namespace imperative
} // namespace paddle
<|endoftext|>
|
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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 "paddle/framework/channel.h"
#include <chrono>
#include <thread>
#include "gtest/gtest.h"
using paddle::framework::Channel;
using paddle::framework::MakeChannel;
using paddle::framework::CloseChannel;
TEST(Channel, MakeAndClose) {
using paddle::framework::details::Buffered;
using paddle::framework::details::UnBuffered;
{
// MakeChannel should return a buffered channel is buffer_size > 0.
auto ch = MakeChannel<int>(10);
EXPECT_NE(dynamic_cast<Buffered<int> *>(ch), nullptr);
EXPECT_EQ(dynamic_cast<UnBuffered<int> *>(ch), nullptr);
CloseChannel(ch);
delete ch;
}
{
// MakeChannel should return an un-buffered channel is buffer_size = 0.
auto ch = MakeChannel<int>(0);
EXPECT_EQ(dynamic_cast<Buffered<int> *>(ch), nullptr);
EXPECT_NE(dynamic_cast<UnBuffered<int> *>(ch), nullptr);
CloseChannel(ch);
delete ch;
}
}
TEST(Channel, SufficientBufferSizeDoesntBlock) {
const size_t buffer_size = 10;
auto ch = MakeChannel<size_t>(buffer_size);
for (size_t i = 0; i < buffer_size; ++i) {
ch->Send(&i); // should not block
}
size_t out;
for (size_t i = 0; i < buffer_size; ++i) {
ch->Receive(&out); // should not block
EXPECT_EQ(out, i);
}
CloseChannel(ch);
delete ch;
}
TEST(Channel, ConcurrentSendNonConcurrentReceiveWithSufficientBufferSize) {
const size_t buffer_size = 10;
auto ch = MakeChannel<size_t>(buffer_size);
size_t sum = 0;
std::thread t([&]() {
// Try to write more than buffer size.
for (size_t i = 0; i < 2 * buffer_size; ++i) {
ch->Send(&i); // should not block
sum += i;
}
});
std::this_thread::sleep_for(std::chrono::milliseconds(100)); // wait 0.5 sec
EXPECT_EQ(sum, 45U);
CloseChannel(ch);
t.join();
delete ch;
}
TEST(Channel, SimpleUnbufferedChannelTest) {
auto ch = MakeChannel<int>(0);
unsigned sum_send = 0;
std::thread t([&]() {
for (int i = 0; i < 5; i++) {
ch->Send(&i);
sum_send += i;
}
});
for (int i = 0; i < 5; i++) {
int recv;
ch->Receive(&recv);
EXPECT_EQ(recv, i);
}
CloseChannel(ch);
t.join();
EXPECT_EQ(sum_send, 10U);
delete ch;
}
// This tests that closing an unbuffered channel also unblocks
// unblocks any receivers waiting for senders
TEST(Channel, UnbufferedChannelCloseUnblocksReceiversTest) {
auto ch = MakeChannel<int>(0);
size_t num_threads = 5;
std::thread t[num_threads];
bool thread_ended[num_threads];
// Launches threads that try to read and are blocked becausew of no writers
for (size_t i = 0; i < num_threads; i++) {
thread_ended[i] = false;
t[i] = std::thread(
[&](bool *p) {
int data;
ch->Receive(&data);
*p = true;
},
&thread_ended[i]);
}
std::this_thread::sleep_for(std::chrono::milliseconds(500)); // wait 0.5 sec
// Verify that all the threads are blocked
for (size_t i = 0; i < num_threads; i++) {
EXPECT_EQ(thread_ended[i], false);
}
// Explicitly close the thread
// This should unblock all receivers
CloseChannel(ch);
std::this_thread::sleep_for(std::chrono::milliseconds(500)); // wait 0.5 sec
// Verify that all threads got unblocked
for (size_t i = 0; i < num_threads; i++) {
EXPECT_EQ(thread_ended[i], true);
}
for (size_t i = 0; i < num_threads; i++) t[i].join();
delete ch;
}
// This tests that closing an unbuffered channel also unblocks
// unblocks any senders waiting for senders
TEST(Channel, UnbufferedChannelCloseUnblocksSendersTest) {
auto ch = MakeChannel<int>(0);
size_t num_threads = 5;
std::thread t[num_threads];
bool thread_ended[num_threads];
// Launches threads that try to read and are blocked becausew of no writers
for (size_t i = 0; i < num_threads; i++) {
thread_ended[i] = false;
t[i] = std::thread(
[&](bool *p) {
int data = 10;
ch->Send(&data);
*p = true;
},
&thread_ended[i]);
}
std::this_thread::sleep_for(std::chrono::milliseconds(500)); // wait 0.5 sec
// Verify that all the threads are blocked
for (size_t i = 0; i < num_threads; i++) {
EXPECT_EQ(thread_ended[i], false);
}
// Explicitly close the thread
// This should unblock all receivers
CloseChannel(ch);
std::this_thread::sleep_for(std::chrono::milliseconds(500)); // wait 0.5 sec
// Verify that all threads got unblocked
for (size_t i = 0; i < num_threads; i++) {
EXPECT_EQ(thread_ended[i], true);
}
for (size_t i = 0; i < num_threads; i++) t[i].join();
delete ch;
}
TEST(Channel, UnbufferedLessReceiveMoreSendTest) {
auto ch = MakeChannel<int>(0);
unsigned sum_send = 0;
// Send should block after three iterations
// since we only have three receivers.
std::thread t([&]() {
// Try to send more number of times
// than receivers
for (int i = 0; i < 4; i++) {
ch->Send(&i);
sum_send += i;
}
});
for (int i = 0; i < 3; i++) {
int recv;
ch->Receive(&recv);
EXPECT_EQ(recv, i);
}
std::this_thread::sleep_for(std::chrono::milliseconds(100)); // wait 0.5 sec
EXPECT_EQ(sum_send, 3U);
CloseChannel(ch);
t.join();
delete ch;
}
<commit_msg>Added more receivers less senders. Receivers should block. (#8061)<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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 "paddle/framework/channel.h"
#include <chrono>
#include <thread>
#include "gtest/gtest.h"
using paddle::framework::Channel;
using paddle::framework::MakeChannel;
using paddle::framework::CloseChannel;
TEST(Channel, MakeAndClose) {
using paddle::framework::details::Buffered;
using paddle::framework::details::UnBuffered;
{
// MakeChannel should return a buffered channel is buffer_size > 0.
auto ch = MakeChannel<int>(10);
EXPECT_NE(dynamic_cast<Buffered<int> *>(ch), nullptr);
EXPECT_EQ(dynamic_cast<UnBuffered<int> *>(ch), nullptr);
CloseChannel(ch);
delete ch;
}
{
// MakeChannel should return an un-buffered channel is buffer_size = 0.
auto ch = MakeChannel<int>(0);
EXPECT_EQ(dynamic_cast<Buffered<int> *>(ch), nullptr);
EXPECT_NE(dynamic_cast<UnBuffered<int> *>(ch), nullptr);
CloseChannel(ch);
delete ch;
}
}
TEST(Channel, SufficientBufferSizeDoesntBlock) {
const size_t buffer_size = 10;
auto ch = MakeChannel<size_t>(buffer_size);
for (size_t i = 0; i < buffer_size; ++i) {
ch->Send(&i); // should not block
}
size_t out;
for (size_t i = 0; i < buffer_size; ++i) {
ch->Receive(&out); // should not block
EXPECT_EQ(out, i);
}
CloseChannel(ch);
delete ch;
}
TEST(Channel, ConcurrentSendNonConcurrentReceiveWithSufficientBufferSize) {
const size_t buffer_size = 10;
auto ch = MakeChannel<size_t>(buffer_size);
size_t sum = 0;
std::thread t([&]() {
// Try to write more than buffer size.
for (size_t i = 0; i < 2 * buffer_size; ++i) {
ch->Send(&i); // should block after 10 iterations
sum += i;
}
});
std::this_thread::sleep_for(std::chrono::milliseconds(100)); // wait 0.5 sec
EXPECT_EQ(sum, 45U);
CloseChannel(ch);
t.join();
delete ch;
}
TEST(Channel, SimpleUnbufferedChannelTest) {
auto ch = MakeChannel<int>(0);
unsigned sum_send = 0;
std::thread t([&]() {
for (int i = 0; i < 5; i++) {
ch->Send(&i);
sum_send += i;
}
});
for (int i = 0; i < 5; i++) {
int recv;
ch->Receive(&recv);
EXPECT_EQ(recv, i);
}
CloseChannel(ch);
t.join();
EXPECT_EQ(sum_send, 10U);
delete ch;
}
// This tests that closing an unbuffered channel also unblocks
// unblocks any receivers waiting for senders
TEST(Channel, UnbufferedChannelCloseUnblocksReceiversTest) {
auto ch = MakeChannel<int>(0);
size_t num_threads = 5;
std::thread t[num_threads];
bool thread_ended[num_threads];
// Launches threads that try to read and are blocked becausew of no writers
for (size_t i = 0; i < num_threads; i++) {
thread_ended[i] = false;
t[i] = std::thread(
[&](bool *p) {
int data;
ch->Receive(&data);
*p = true;
},
&thread_ended[i]);
}
std::this_thread::sleep_for(std::chrono::milliseconds(500)); // wait 0.5 sec
// Verify that all the threads are blocked
for (size_t i = 0; i < num_threads; i++) {
EXPECT_EQ(thread_ended[i], false);
}
// Explicitly close the thread
// This should unblock all receivers
CloseChannel(ch);
std::this_thread::sleep_for(std::chrono::milliseconds(500)); // wait 0.5 sec
// Verify that all threads got unblocked
for (size_t i = 0; i < num_threads; i++) {
EXPECT_EQ(thread_ended[i], true);
}
for (size_t i = 0; i < num_threads; i++) t[i].join();
delete ch;
}
// This tests that closing an unbuffered channel also unblocks
// unblocks any senders waiting for senders
TEST(Channel, UnbufferedChannelCloseUnblocksSendersTest) {
auto ch = MakeChannel<int>(0);
size_t num_threads = 5;
std::thread t[num_threads];
bool thread_ended[num_threads];
// Launches threads that try to read and are blocked becausew of no writers
for (size_t i = 0; i < num_threads; i++) {
thread_ended[i] = false;
t[i] = std::thread(
[&](bool *p) {
int data = 10;
ch->Send(&data);
*p = true;
},
&thread_ended[i]);
}
std::this_thread::sleep_for(std::chrono::milliseconds(500)); // wait 0.5 sec
// Verify that all the threads are blocked
for (size_t i = 0; i < num_threads; i++) {
EXPECT_EQ(thread_ended[i], false);
}
// Explicitly close the thread
// This should unblock all receivers
CloseChannel(ch);
std::this_thread::sleep_for(std::chrono::milliseconds(500)); // wait 0.5 sec
// Verify that all threads got unblocked
for (size_t i = 0; i < num_threads; i++) {
EXPECT_EQ(thread_ended[i], true);
}
for (size_t i = 0; i < num_threads; i++) t[i].join();
delete ch;
}
TEST(Channel, UnbufferedLessReceiveMoreSendTest) {
auto ch = MakeChannel<int>(0);
unsigned sum_send = 0;
// Send should block after three iterations
// since we only have three receivers.
std::thread t([&]() {
// Try to send more number of times
// than receivers
for (int i = 0; i < 4; i++) {
ch->Send(&i);
sum_send += i;
}
});
for (int i = 0; i < 3; i++) {
int recv;
ch->Receive(&recv);
EXPECT_EQ(recv, i);
}
std::this_thread::sleep_for(std::chrono::milliseconds(100)); // wait 0.5 sec
EXPECT_EQ(sum_send, 3U);
CloseChannel(ch);
t.join();
delete ch;
}
TEST(Channel, UnbufferedMoreReceiveLessSendTest) {
auto ch = MakeChannel<int>(0);
unsigned sum_send = 0;
unsigned sum_receive = 0;
// The receiver should block after 5
// iterations, since there are only 5 senders.
std::thread t([&]() {
for (int i = 0; i < 8; i++) {
int recv;
ch->Receive(&recv); // should block after the fifth iteration.
EXPECT_EQ(recv, i);
sum_receive += i;
}
});
for (int i = 0; i < 5; i++) {
ch->Send(&i);
sum_send += i;
}
std::this_thread::sleep_for(std::chrono::milliseconds(500)); // wait 0.5 sec
EXPECT_EQ(sum_send, 10U);
EXPECT_EQ(sum_receive, 10U);
// send three more elements
for (int i = 5; i < 8; i++) {
ch->Send(&i);
sum_send += i;
}
CloseChannel(ch);
t.join();
EXPECT_EQ(sum_send, 28U);
EXPECT_EQ(sum_receive, 28U);
delete ch;
}
<|endoftext|>
|
<commit_before>/*
* Copyright Regents of the University of Minnesota, 2015. This software is released under the following license: http://opensource.org/licenses/GPL-2.0
* Source code originally developed at the University of Minnesota Interactive Visualization Lab (http://ivlab.cs.umn.edu).
*
* Code author(s):
* Ben Knorlein
*/
#include <GL/freeglut.h>
#include "VRFreeGLUTWindowToolkit.h"
#include <main/VRMainInterface.h>
#include <iostream>
namespace MinVR {
static void error_callback(const char *fmt, va_list ap)
{
std::cerr << "FREEGLUT - ERROR : " << fmt << " - " << ap << std::endl;
}
static void warning_callback(const char *fmt, va_list ap)
{
std::cerr << "FREEGLUT - WARNING : " << fmt << " - " << ap << std::endl;
}
VRFreeGLUTWindowToolkit::VRFreeGLUTWindowToolkit(VRMainInterface *vrMain) : _vrMain(vrMain), _inputDev(NULL) {
char *myargv [1];
int myargc=1;
myargv [0]=strdup ("");
glutInitErrorFunc(error_callback);
glutInitWarningFunc(warning_callback);
glutInit(&myargc, myargv);
_inputDev = new VRFreeGLUTInputDevice();
}
VRFreeGLUTWindowToolkit::~VRFreeGLUTWindowToolkit() {
if (_inputDev != NULL) {
delete _inputDev;
}
for (std::vector<int>::iterator it = _windows.begin(); it != _windows.end(); ++it){
glutDestroyWindow(*it);
}
}
int
VRFreeGLUTWindowToolkit::createWindow(VRWindowSettings settings) {
unsigned int mode = GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA | GLUT_STENCIL;
if (settings.quadBuffered) {
mode = mode | GLUT_STEREO;
}
glutInitDisplayMode(mode);
glutInitWindowPosition(settings.xpos,settings.ypos);
glutInitWindowSize(settings.width,settings.height);
int windowID = glutCreateWindow(settings.caption.c_str());
if(settings.border == 0) glutFullScreen();
_inputDev->addWindow(windowID);
if (_windows.size() == 0) {
// if this is the first window created, then register the virtual input device
// with VRMain so that VRMain will start polling GLFW for input events
_vrMain->addInputDevice(_inputDev);
}
_windows.push_back(windowID);
return _windows.size()-1;
}
void
VRFreeGLUTWindowToolkit::destroyWindow(int windowID) {
glutDestroyWindow(_windows[windowID]);
}
void
VRFreeGLUTWindowToolkit::makeWindowCurrent(int windowID) {
glutSetWindow(_windows[windowID]);
}
void
VRFreeGLUTWindowToolkit::swapBuffers(int windowID) {
glutSetWindow(_windows[windowID]);
glutSwapBuffers();
}
VRFreeGLUTWindowToolkit*
VRFreeGLUTWindowToolkit::create(VRMainInterface *vrMain, VRDataIndex *config, const std::string &nameSpace) {
return new VRFreeGLUTWindowToolkit(vrMain);
}
} /* namespace MinVR */
<commit_msg>fixes #131 : Removed the deletion of the inputdevice as it is already deleted in VRMain<commit_after>/*
* Copyright Regents of the University of Minnesota, 2015. This software is released under the following license: http://opensource.org/licenses/GPL-2.0
* Source code originally developed at the University of Minnesota Interactive Visualization Lab (http://ivlab.cs.umn.edu).
*
* Code author(s):
* Ben Knorlein
*/
#include <GL/freeglut.h>
#include "VRFreeGLUTWindowToolkit.h"
#include <main/VRMainInterface.h>
#include <iostream>
namespace MinVR {
static void error_callback(const char *fmt, va_list ap)
{
std::cerr << "FREEGLUT - ERROR : " << fmt << " - " << ap << std::endl;
}
static void warning_callback(const char *fmt, va_list ap)
{
std::cerr << "FREEGLUT - WARNING : " << fmt << " - " << ap << std::endl;
}
VRFreeGLUTWindowToolkit::VRFreeGLUTWindowToolkit(VRMainInterface *vrMain) : _vrMain(vrMain), _inputDev(NULL) {
char *myargv [1];
int myargc=1;
myargv [0]=strdup ("");
glutInitErrorFunc(error_callback);
glutInitWarningFunc(warning_callback);
glutInit(&myargc, myargv);
_inputDev = new VRFreeGLUTInputDevice();
}
VRFreeGLUTWindowToolkit::~VRFreeGLUTWindowToolkit() {
for (std::vector<int>::iterator it = _windows.begin(); it != _windows.end(); ++it){
glutDestroyWindow(*it);
}
}
int
VRFreeGLUTWindowToolkit::createWindow(VRWindowSettings settings) {
unsigned int mode = GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA | GLUT_STENCIL;
if (settings.quadBuffered) {
mode = mode | GLUT_STEREO;
}
glutInitDisplayMode(mode);
glutInitWindowPosition(settings.xpos,settings.ypos);
glutInitWindowSize(settings.width,settings.height);
int windowID = glutCreateWindow(settings.caption.c_str());
if(settings.border == 0) glutFullScreen();
_inputDev->addWindow(windowID);
if (_windows.size() == 0) {
// if this is the first window created, then register the virtual input device
// with VRMain so that VRMain will start polling GLFW for input events
_vrMain->addInputDevice(_inputDev);
}
_windows.push_back(windowID);
return _windows.size()-1;
}
void
VRFreeGLUTWindowToolkit::destroyWindow(int windowID) {
glutDestroyWindow(_windows[windowID]);
}
void
VRFreeGLUTWindowToolkit::makeWindowCurrent(int windowID) {
glutSetWindow(_windows[windowID]);
}
void
VRFreeGLUTWindowToolkit::swapBuffers(int windowID) {
glutSetWindow(_windows[windowID]);
glutSwapBuffers();
}
VRFreeGLUTWindowToolkit*
VRFreeGLUTWindowToolkit::create(VRMainInterface *vrMain, VRDataIndex *config, const std::string &nameSpace) {
return new VRFreeGLUTWindowToolkit(vrMain);
}
} /* namespace MinVR */
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2012 Andreas Heider, Julius Adorf, Markus Grimm
*
* MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include "tpofinder/detect.h"
#include "tpofinder/visualize.h"
using namespace cv;
using namespace tpofinder;
using namespace std;
namespace po = boost::program_options;
const string NAME = "tpofind";
bool verbose = false;
bool webcam = false;
vector<string> files;
VideoCapture *capture = NULL;
Mat image;
int frame = 0;
void processCommandLine(int argc, char* argv[]) {
po::options_description named_opts;
named_opts.add_options()
("webcam,w", "Read images from webcam.")
("verbose,v", "Display verbose messages.")
("help,h", "Print help message.");
po::options_description hidden_opts;
hidden_opts.add_options()
("file,f", po::value<vector<string> >(&files));
po::options_description all_opts;
all_opts.add(named_opts);
all_opts.add(hidden_opts);
po::positional_options_description popts;
popts.add("file", -1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv)
.options(all_opts)
.positional(popts)
.run(), vm);
po::notify(vm);
webcam = vm.count("webcam") > 0;
verbose = vm.count("verbose") > 0;
if (vm.count("help")) {
cout << "Usage: tpofind [OPTIONS] image ..." << endl;
cout << named_opts << endl;
exit(0);
}
}
void openCamera() {
capture = new VideoCapture(0); // open the default camera
if (!capture->isOpened()) { // check if we succeeded
cerr << "Could not open default camera." << endl;
exit(-1);
}
}
void loadModel(Modelbase& modelbase, const string& path) {
if (verbose) {
cout << boost::format("Loading object %-20s ... ") % path;
}
modelbase.add(path);
if (verbose) {
cout << "[DONE]" << endl;
}
}
void nextImage() {
if (webcam) {
*capture >> image;
} else if (files.size() > 0) {
image = imread(files[frame]);
} else {
string s;
getline(cin, s);
image = imread(s);
}
frame++;
}
bool hasNextImage() {
return frame < files.size();
}
void processImage(Detector& detector) {
if (!image.empty()) {
Scene scene = detector.describe(image);
vector<Detection> detections = detector.detect(scene);
BOOST_FOREACH(Detection d, detections) {
drawDetection(image, d);
}
}
}
bool readFromCommandLine() {
return files.size() > 0;
}
int main(int argc, char* argv[]) {
processCommandLine(argc, argv);
namedWindow(NAME, 1);
// TODO: adapt to OpenCV 2.4.
// TODO: remove duplication
Ptr<FeatureDetector> fd = new OrbFeatureDetector(1000, 1.2, 8);
Ptr<FeatureDetector> trainFd = new OrbFeatureDetector(250, 1.2, 8);
Ptr<DescriptorExtractor> de = new OrbDescriptorExtractor(1000, 1.2, 8);
Ptr<flann::IndexParams> indexParams = new flann::LshIndexParams(15, 12, 2);
Ptr<DescriptorMatcher> dm = new FlannBasedMatcher(indexParams);
Feature trainFeature(trainFd, de, dm);
Modelbase modelbase(trainFeature);
loadModel(modelbase, "data/adapter");
loadModel(modelbase, "data/blokus");
loadModel(modelbase, "data/stockholm");
loadModel(modelbase, "data/taco");
loadModel(modelbase, "data/tea");
Feature feature(fd, de, dm);
Ptr<DetectionFilter> filter = new AndFilter(
Ptr<DetectionFilter > (new EigenvalueFilter(-1, 4.0)),
Ptr<DetectionFilter > (new InliersRatioFilter(0.30)));
Detector detector(modelbase, feature, filter);
if (webcam) {
openCamera();
}
int i = 0;
while (hasNextImage()) {
nextImage();
processImage(detector);
imshow(NAME, image);
if (waitKey(1) >= 0) break;
}
if (readFromCommandLine()) {
waitKey(-1);
}
delete capture;
return 0;
}
<commit_msg>Improve standard input.<commit_after>/**
* Copyright (c) 2012 Andreas Heider, Julius Adorf, Markus Grimm
*
* MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include "tpofinder/detect.h"
#include "tpofinder/visualize.h"
using namespace cv;
using namespace tpofinder;
using namespace std;
namespace po = boost::program_options;
const string NAME = "tpofind";
bool verbose = false;
bool webcam = false;
vector<string> files;
VideoCapture *capture = NULL;
Mat image;
int frame = 0;
bool readEmpty = false;
void processCommandLine(int argc, char* argv[]) {
po::options_description named_opts;
named_opts.add_options()
("webcam,w", "Read images from webcam.")
("verbose,v", "Display verbose messages.")
("help,h", "Print help message.");
po::options_description hidden_opts;
hidden_opts.add_options()
("file,f", po::value<vector<string> >(&files));
po::options_description all_opts;
all_opts.add(named_opts);
all_opts.add(hidden_opts);
po::positional_options_description popts;
popts.add("file", -1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv)
.options(all_opts)
.positional(popts)
.run(), vm);
po::notify(vm);
webcam = vm.count("webcam") > 0;
verbose = vm.count("verbose") > 0;
if (vm.count("help")) {
cout << "Usage: tpofind [OPTIONS] image ..." << endl;
cout << named_opts << endl;
exit(0);
}
}
bool readFromCommandLine() {
return files.size() > 0;
}
void openCamera() {
capture = new VideoCapture(0);
if (!capture->isOpened()) {
cerr << "Could not open default camera." << endl;
exit(-1);
}
}
void loadModel(Modelbase& modelbase, const string& path) {
if (verbose) {
cout << boost::format("Loading object %-20s ... ") % path;
}
modelbase.add(path);
if (verbose) {
cout << "[DONE]" << endl;
}
}
void nextImage() {
if (webcam) {
if (verbose) {
cout << "Reading from webcam ... ";
}
*capture >> image;
if (verbose) {
cout << "[DONE]" << endl;
}
} else if (files.size() > 0) {
if (verbose) {
cout << "Reading from command-line ... ";
}
image = imread(files[frame]);
if (verbose) {
cout << "[DONE]" << endl;
}
} else {
string s;
cout << "$ ";
getline(cin, s);
if (verbose) {
cout << "Reading from standard input ... ";
}
if (s.empty()) {
readEmpty = true;
} else {
image = imread(s);
}
if (verbose) {
if (s.empty() || !image.empty()) {
cout << "[DONE]" << endl;
} else {
cout << "[FAIL]" << endl;
}
}
}
frame++;
}
bool hasNextImage() {
return (webcam || (!readFromCommandLine() || frame < files.size())) && !readEmpty;
}
void processImage(Detector& detector) {
if (!image.empty()) {
cout << "Detecting objects on image ... ";
Scene scene = detector.describe(image);
vector<Detection> detections = detector.detect(scene);
cout << "[DONE]" << endl;
BOOST_FOREACH(Detection d, detections) {
drawDetection(image, d);
}
}
}
int main(int argc, char* argv[]) {
processCommandLine(argc, argv);
cvStartWindowThread();
namedWindow(NAME, 1);
// TODO: adapt to OpenCV 2.4.
// TODO: remove duplication
// TODO: support SIFT
Ptr<FeatureDetector> fd = new OrbFeatureDetector(1000, 1.2, 8);
Ptr<FeatureDetector> trainFd = new OrbFeatureDetector(250, 1.2, 8);
Ptr<DescriptorExtractor> de = new OrbDescriptorExtractor(1000, 1.2, 8);
Ptr<flann::IndexParams> indexParams = new flann::LshIndexParams(15, 12, 2);
Ptr<DescriptorMatcher> dm = new FlannBasedMatcher(indexParams);
Feature trainFeature(trainFd, de, dm);
Modelbase modelbase(trainFeature);
loadModel(modelbase, "data/adapter");
loadModel(modelbase, "data/blokus");
loadModel(modelbase, "data/stockholm");
loadModel(modelbase, "data/taco");
loadModel(modelbase, "data/tea");
Feature feature(fd, de, dm);
Ptr<DetectionFilter> filter = new AndFilter(
Ptr<DetectionFilter > (new EigenvalueFilter(-1, 4.0)),
Ptr<DetectionFilter > (new InliersRatioFilter(0.30)));
Detector detector(modelbase, feature, filter);
if (webcam) {
openCamera();
}
int i = 0;
while (hasNextImage()) {
nextImage();
processImage(detector);
if (!image.empty()) {
imshow(NAME, image);
if (waitKey(1) >= 0) break;
}
}
if (verbose) {
cout << "No more images to process ... [DONE]" << endl;
}
while (waitKey(10) == 0) {
imshow(NAME, image);
}
delete capture;
if (verbose) {
cout << "Quitting ... [DONE]" << endl;
}
return 0;
}
<|endoftext|>
|
<commit_before><commit_msg>Windows: Put ScopedHGlobal in the right scope so it unlocks a STGMEDIUM's handle before we call ReleaseStgMedium.<commit_after><|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// File: ProcessJac.cpp
//
// For more information, please see: http://www.nektar.info/
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description: Calculate Jacobians of elements.
//
////////////////////////////////////////////////////////////////////////////////
#include "MeshElements.h"
#include "ProcessJac.h"
#include <SpatialDomains/MeshGraph.h>
#include <LibUtilities/Foundations/ManagerAccess.h> // for PointsManager, etc
#include <vector>
using namespace std;
namespace Nektar
{
namespace Utilities
{
ModuleKey ProcessJac::className =
GetModuleFactory().RegisterCreatorFunction(
ModuleKey(eProcessModule, "jac"), ProcessJac::create,
"Process elements based on values of Jacobian.");
ProcessJac::ProcessJac(MeshSharedPtr m) : ProcessModule(m)
{
m_config["extract"] = ConfigOption(
true, "0", "Extract non-valid elements from mesh.");
m_config["list"] = ConfigOption(
true, "0", "Print list of elements having negative Jacobian.");
}
ProcessJac::~ProcessJac()
{
}
void ProcessJac::Process()
{
if (m_mesh->m_verbose)
{
cout << "ProcessJac: Calculating Jacobians... " << endl;
}
bool extract = m_config["extract"].as<bool>();
bool printList = m_config["list"].as<bool>();
vector<ElementSharedPtr> el = m_mesh->m_element[m_mesh->m_expDim];
if (extract)
{
m_mesh->m_element[m_mesh->m_expDim].clear();
}
if (printList)
{
cout << "Elements with negative Jacobian:" << endl;
}
int nNeg = 0;
// Iterate over list of elements of expansion dimension.
for (int i = 0; i < el.size(); ++i)
{
// Create elemental geometry.
SpatialDomains::GeometrySharedPtr geom =
el[i]->GetGeom(m_mesh->m_spaceDim);
// Generate geometric factors.
SpatialDomains::GeomFactorsSharedPtr gfac =
geom->GetGeomFactors();
// Get the Jacobian and, if it is negative, print a warning
// message.
if (!gfac->IsValid())
{
nNeg++;
if (printList)
{
cout << " - " << el[i]->GetId() << " ("
<< StdRegions::ElementTypeMap[el[i]->GetConf().m_e]
<< ")" << endl;
}
if (extract)
{
m_mesh->m_element[m_mesh->m_expDim].push_back(el[i]);
}
}
}
if (extract)
{
m_mesh->m_element[m_mesh->m_expDim-1].clear();
ProcessVertices();
ProcessEdges();
ProcessFaces();
ProcessElements();
ProcessComposites();
}
if (printList || m_mesh->m_verbose)
{
cout << "Total negative Jacobians: " << nNeg << endl;
}
else if (nNeg > 0)
{
cout << "WARNING: Detected " << nNeg << " element"
<< (nNeg == 1 ? "" : "s") << " with negative Jacobian."
<< endl;
}
}
}
}
<commit_msg>Added options to curve inside face of a prism and also to remove curve if jacobian was identified as singular. The first option does not seem very general and is being archived with this commit. I will then remove it in the next commit<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// File: ProcessJac.cpp
//
// For more information, please see: http://www.nektar.info/
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description: Calculate Jacobians of elements.
//
////////////////////////////////////////////////////////////////////////////////
#include "MeshElements.h"
#include "ProcessJac.h"
#include <SpatialDomains/MeshGraph.h>
#include <LibUtilities/Foundations/ManagerAccess.h> // for PointsManager, etc
#include <vector>
using namespace std;
namespace Nektar
{
namespace Utilities
{
ModuleKey ProcessJac::className =
GetModuleFactory().RegisterCreatorFunction(
ModuleKey(eProcessModule, "jac"), ProcessJac::create,
"Process elements based on values of Jacobian.");
ProcessJac::ProcessJac(MeshSharedPtr m) : ProcessModule(m)
{
m_config["extract"] = ConfigOption(
true, "0", "Extract non-valid elements from mesh.");
m_config["deformprismifsingular"] = ConfigOption(
true, "0", "deform internal prism face if singular.");
m_config["removecurveifsingular"] = ConfigOption(
true, "0", "remove curve nodes if element is singular.");
m_config["list"] = ConfigOption(
true, "0", "Print list of elements having negative Jacobian.");
}
ProcessJac::~ProcessJac()
{
}
void ProcessJac::Process()
{
if (m_mesh->m_verbose)
{
cout << "ProcessJac: Calculating Jacobians... " << endl;
}
bool extract = m_config["extract"].as<bool>();
bool printList = m_config["list"].as<bool>();
bool DeformPrismIfSingular = m_config["deformprismifsingular"].as<bool>();
bool RemoveCurveIfSingular = m_config["removecurveifsingular"].as<bool>();
vector<ElementSharedPtr> el = m_mesh->m_element[m_mesh->m_expDim];
if (extract)
{
m_mesh->m_element[m_mesh->m_expDim].clear();
}
if (printList)
{
cout << "Elements with negative Jacobian:" << endl;
}
int nNeg = 0;
// Iterate over list of elements of expansion dimension.
for (int i = 0; i < el.size(); ++i)
{
// Create elemental geometry.
SpatialDomains::GeometrySharedPtr geom =
el[i]->GetGeom(m_mesh->m_spaceDim);
// Generate geometric factors.
SpatialDomains::GeomFactorsSharedPtr gfac =
geom->GetGeomFactors();
// Get the Jacobian and, if it is negative, print a warning
// message.
if (!gfac->IsValid())
{
nNeg++;
if (printList)
{
cout << " - " << el[i]->GetId() << " ("
<< StdRegions::ElementTypeMap[el[i]->GetConf().m_e]
<< ")" << endl;
}
if(DeformPrismIfSingular)
{
int nSurf = el[i]->GetFaceCount();
if(nSurf == 5) // prism mesh
{
int triedges[3][2] = {{0,2},{5,6},{4,7}};
// find edges ndoes and blend to far side.
for(int e = 0; e < 3; ++e)
{
EdgeSharedPtr e1 = el[i]->GetEdge(triedges[e][0]);
EdgeSharedPtr e2 = el[i]->GetEdge(triedges[e][1]);
EdgeSharedPtr efrom,eto;
if(e1->m_edgeNodes.size() == 0)
{
efrom = e2;
eto = e1;
}
else if(e2->m_edgeNodes.size() == 0)
{
efrom = e1;
eto = e2;
}
else
{
continue;
}
// determine vector fron node 1 to 2
NodeSharedPtr nfrom1 = efrom->m_n1;
NodeSharedPtr nfrom2 = efrom->m_n2;
// determine vector fron node 1 to 2 of
NodeSharedPtr nto1 = eto->m_n1;
NodeSharedPtr nto2 = eto->m_n2;
Node n1to2 = *nto2 - *nto1;
Node n1from2 = *nfrom2 - *nfrom1;
int ne = efrom->m_edgeNodes.size();
vector<int> mapnode(ne);
//edges are reversed.
if(n1to2.dot(n1from2) < 0)
{
for(int j = 0; j < ne; ++j)
{
mapnode[j] = ne-j-1;
}
nto1 = eto->m_n2;
nto2 = eto->m_n1;
}
else
{
for(int j = 0; j < ne; ++j)
{
mapnode[j] = j;
}
}
SpatialDomains::GeometrySharedPtr edgeom = efrom->GetGeom(m_mesh->m_spaceDim);
StdRegions::StdExpansionSharedPtr xmap = edgeom->GetXmap();
Array<OneD, Array<OneD, NekDouble> > xc(m_mesh->m_spaceDim);
int nq = xmap->GetTotPoints();
for(int j = 0; j < m_mesh->m_spaceDim; ++j)
{
xc[j] = Array<OneD, NekDouble>(nq);
}
Array<OneD, NekDouble> coeffs(xmap->GetNcoeffs());
edgeom->FillGeom();
// extract coefficients from modal
// space replace the node values and
// backward transform.
// X coord
Vmath::Vcopy(xmap->GetNcoeffs(),
edgeom->GetCoeffs(0),1,
coeffs,1);
// replace vertices with to values;
coeffs[0] = nto1->m_x;
coeffs[1] = nto2->m_x;
// bwdtrans
xmap->BwdTrans(coeffs,xc[0]);
// Y coord
Vmath::Vcopy(xmap->GetNcoeffs(),
edgeom->GetCoeffs(1),1,
coeffs,1);
// replace vertices with to values;
coeffs[0] = nto1->m_y;
coeffs[1] = nto2->m_y;
// bwdtrans
xmap->BwdTrans(coeffs,xc[1]);
// Z coord
Vmath::Vcopy(xmap->GetNcoeffs(),
edgeom->GetCoeffs(2),1,
coeffs,1);
// replace vertices with to values;
coeffs[0] = nto1->m_z;
coeffs[1] = nto2->m_z;
// bwdtrans
xmap->BwdTrans(coeffs,xc[2]);
for(int j = 0; j < ne; ++j)
{
NodeSharedPtr n = boost::shared_ptr<Node>(new Node());
(*n).m_x = xc[0][mapnode[j]+1];
(*n).m_y = xc[1][mapnode[j]+1];
(*n).m_z = xc[2][mapnode[j]+1];
eto->m_edgeNodes.push_back(n);
}
}
}
}
if(RemoveCurveIfSingular)
{
int nSurf = el[i]->GetFaceCount();
if(nSurf == 5) // prism mesh
{
// find edges ndoes and blend to far side.
for(int e = 0; e < el[i]->GetEdgeCount(); ++e)
{
EdgeSharedPtr ed = el[i]->GetEdge(e);
EdgeSet::iterator it;
// find edge in m_edgeSet;
if((it = m_mesh->m_edgeSet.find(ed)) != m_mesh->m_edgeSet.end())
{
if((*it)->m_edgeNodes.size())
{
vector<NodeSharedPtr> zeroNodes;
(*it)->m_edgeNodes = zeroNodes;
}
}
}
}
}
if (extract)
{
m_mesh->m_element[m_mesh->m_expDim].push_back(el[i]);
}
}
}
if (extract)
{
m_mesh->m_element[m_mesh->m_expDim-1].clear();
ProcessVertices();
ProcessEdges();
ProcessFaces();
ProcessElements();
ProcessComposites();
}
if(DeformPrismIfSingular)
{
ProcessEdges();
}
if (printList || m_mesh->m_verbose)
{
cout << "Total negative Jacobians: " << nNeg << endl;
}
else if (nNeg > 0)
{
cout << "WARNING: Detected " << nNeg << " element"
<< (nNeg == 1 ? "" : "s") << " with negative Jacobian."
<< endl;
}
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "audio_frame_operations.h"
#include "module_common_types.h"
namespace webrtc {
namespace voe {
WebRtc_Word32
AudioFrameOperations::MonoToStereo(AudioFrame& audioFrame)
{
if (audioFrame._audioChannel != 1)
{
return -1;
}
if ((audioFrame._payloadDataLengthInSamples << 1) >=
AudioFrame::kMaxAudioFrameSizeSamples)
{
// not enough memory to expand from mono to stereo
return -1;
}
int16_t payloadCopy[AudioFrame::kMaxAudioFrameSizeSamples];
memcpy(payloadCopy, audioFrame._payloadData,
sizeof(int16_t) * audioFrame._payloadDataLengthInSamples);
for (int i = 0; i < audioFrame._payloadDataLengthInSamples; i++)
{
audioFrame._payloadData[2*i] = payloadCopy[i];
audioFrame._payloadData[2*i+1] = payloadCopy[i];
}
audioFrame._audioChannel = 2;
return 0;
}
WebRtc_Word32
AudioFrameOperations::StereoToMono(AudioFrame& audioFrame)
{
if (audioFrame._audioChannel != 2)
{
return -1;
}
for (int i = 0; i < audioFrame._payloadDataLengthInSamples; i++)
{
audioFrame._payloadData[i] = (audioFrame._payloadData[2*i] >> 1) +
(audioFrame._payloadData[2*i+1] >> 1);
}
audioFrame._audioChannel = 1;
return 0;
}
void AudioFrameOperations::SwapStereoChannels(AudioFrame* frame) {
for (int i = 0; i < frame->_payloadDataLengthInSamples * 2; i += 2) {
int16_t temp_data = frame->_payloadData[i];
frame->_payloadData[i] = frame->_payloadData[i + 1];
frame->_payloadData[i + 1] = temp_data;
}
}
WebRtc_Word32
AudioFrameOperations::Mute(AudioFrame& audioFrame)
{
const int sizeInBytes = sizeof(WebRtc_Word16) *
audioFrame._payloadDataLengthInSamples * audioFrame._audioChannel;
memset(audioFrame._payloadData, 0, sizeInBytes);
audioFrame._energy = 0;
return 0;
}
WebRtc_Word32
AudioFrameOperations::Scale(const float left,
const float right,
AudioFrame& audioFrame)
{
if (audioFrame._audioChannel == 1)
{
assert(false);
return -1;
}
for (int i = 0; i < audioFrame._payloadDataLengthInSamples; i++)
{
audioFrame._payloadData[2*i] =
(WebRtc_Word16)(left*audioFrame._payloadData[2*i]);
audioFrame._payloadData[2*i+1] =
(WebRtc_Word16)(right*audioFrame._payloadData[2*i+1]);
}
return 0;
}
WebRtc_Word32
AudioFrameOperations::ScaleWithSat(const float scale, AudioFrame& audioFrame)
{
WebRtc_Word32 tmp(0);
// Ensure that the output result is saturated [-32768, +32768].
for (int i = 0;
i < audioFrame._payloadDataLengthInSamples * audioFrame._audioChannel;
i++)
{
tmp = static_cast<WebRtc_Word32> (scale * audioFrame._payloadData[i]);
if (tmp < -32768)
{
audioFrame._payloadData[i] = -32768;
}
else if (tmp > 32767)
{
audioFrame._payloadData[i] = 32767;
}
else
{
audioFrame._payloadData[i] = static_cast<WebRtc_Word16> (tmp);
}
}
return 0;
}
} // namespace voe
} // namespace webrtc
<commit_msg>Fail silently when swapping mono.<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "audio_frame_operations.h"
#include "module_common_types.h"
namespace webrtc {
namespace voe {
WebRtc_Word32
AudioFrameOperations::MonoToStereo(AudioFrame& audioFrame)
{
if (audioFrame._audioChannel != 1)
{
return -1;
}
if ((audioFrame._payloadDataLengthInSamples << 1) >=
AudioFrame::kMaxAudioFrameSizeSamples)
{
// not enough memory to expand from mono to stereo
return -1;
}
int16_t payloadCopy[AudioFrame::kMaxAudioFrameSizeSamples];
memcpy(payloadCopy, audioFrame._payloadData,
sizeof(int16_t) * audioFrame._payloadDataLengthInSamples);
for (int i = 0; i < audioFrame._payloadDataLengthInSamples; i++)
{
audioFrame._payloadData[2*i] = payloadCopy[i];
audioFrame._payloadData[2*i+1] = payloadCopy[i];
}
audioFrame._audioChannel = 2;
return 0;
}
WebRtc_Word32
AudioFrameOperations::StereoToMono(AudioFrame& audioFrame)
{
if (audioFrame._audioChannel != 2)
{
return -1;
}
for (int i = 0; i < audioFrame._payloadDataLengthInSamples; i++)
{
audioFrame._payloadData[i] = (audioFrame._payloadData[2*i] >> 1) +
(audioFrame._payloadData[2*i+1] >> 1);
}
audioFrame._audioChannel = 1;
return 0;
}
void AudioFrameOperations::SwapStereoChannels(AudioFrame* frame) {
if (frame->_audioChannel != 2) return;
for (int i = 0; i < frame->_payloadDataLengthInSamples * 2; i += 2) {
int16_t temp_data = frame->_payloadData[i];
frame->_payloadData[i] = frame->_payloadData[i + 1];
frame->_payloadData[i + 1] = temp_data;
}
}
WebRtc_Word32
AudioFrameOperations::Mute(AudioFrame& audioFrame)
{
const int sizeInBytes = sizeof(WebRtc_Word16) *
audioFrame._payloadDataLengthInSamples * audioFrame._audioChannel;
memset(audioFrame._payloadData, 0, sizeInBytes);
audioFrame._energy = 0;
return 0;
}
WebRtc_Word32
AudioFrameOperations::Scale(const float left,
const float right,
AudioFrame& audioFrame)
{
if (audioFrame._audioChannel == 1)
{
assert(false);
return -1;
}
for (int i = 0; i < audioFrame._payloadDataLengthInSamples; i++)
{
audioFrame._payloadData[2*i] =
(WebRtc_Word16)(left*audioFrame._payloadData[2*i]);
audioFrame._payloadData[2*i+1] =
(WebRtc_Word16)(right*audioFrame._payloadData[2*i+1]);
}
return 0;
}
WebRtc_Word32
AudioFrameOperations::ScaleWithSat(const float scale, AudioFrame& audioFrame)
{
WebRtc_Word32 tmp(0);
// Ensure that the output result is saturated [-32768, +32768].
for (int i = 0;
i < audioFrame._payloadDataLengthInSamples * audioFrame._audioChannel;
i++)
{
tmp = static_cast<WebRtc_Word32> (scale * audioFrame._payloadData[i]);
if (tmp < -32768)
{
audioFrame._payloadData[i] = -32768;
}
else if (tmp > 32767)
{
audioFrame._payloadData[i] = 32767;
}
else
{
audioFrame._payloadData[i] = static_cast<WebRtc_Word16> (tmp);
}
}
return 0;
}
} // namespace voe
} // namespace webrtc
<|endoftext|>
|
<commit_before>#include "file_system.h"
#include "memory.h"
#include "pen_string.h"
#include <Shlobj.h>
#include <Shlwapi.h>
#include <stdio.h>
namespace pen
{
#define WINDOWS_TICK 10000000
#define SEC_TO_UNIX_EPOCH 11644473600LL
c8* swap_slashes(const c8* filename);
static bool s_show_hidden = false;
void filesystem_toggle_hidden_files()
{
s_show_hidden = !s_show_hidden;
}
u32 win32_time_to_unix_seconds(long long ticks)
{
return (u32)(ticks / WINDOWS_TICK - SEC_TO_UNIX_EPOCH);
}
pen_error filesystem_getmtime(const c8* filename, u32& mtime_out)
{
c8* corrected_name = swap_slashes(filename);
OFSTRUCT of_struct;
HFILE f = OpenFile(corrected_name, &of_struct, OF_READ);
pen::memory_free(corrected_name);
if (f != HFILE_ERROR)
{
FILETIME c, m, a;
BOOL res = GetFileTime((HANDLE)(size_t)f, &c, &a, &m);
long long* wt = (long long*)&m;
u32 unix_ts = win32_time_to_unix_seconds(*wt);
mtime_out = unix_ts;
CloseHandle((HANDLE)(size_t)f);
return PEN_ERR_OK;
}
return PEN_ERR_FILE_NOT_FOUND;
}
c8* swap_slashes(const c8* filename)
{
// swap "/" for "\\"
const char* p_src_char = filename;
u32 str_len = pen::string_length(filename);
char* windir_filename = (char*)pen::memory_alloc(str_len + 1);
char* p_dest_char = windir_filename;
while (p_src_char < filename + str_len)
{
if (*p_src_char == '/')
*p_dest_char = '\\';
else if (*p_src_char == '@')
*p_dest_char = ':';
else
*p_dest_char = *p_src_char;
p_dest_char++;
p_src_char++;
}
*p_dest_char = '\0';
return windir_filename;
}
pen_error filesystem_read_file_to_buffer(const c8* filename, void** p_buffer, u32& buffer_size)
{
c8* windir_filename = swap_slashes(filename);
*p_buffer = NULL;
FILE* p_file = nullptr;
fopen_s(&p_file, windir_filename, "rb");
pen::memory_free(windir_filename);
if (p_file)
{
fseek(p_file, 0L, SEEK_END);
LONG size = ftell(p_file);
fseek(p_file, 0L, SEEK_SET);
buffer_size = (u32)size;
*p_buffer = pen::memory_alloc(buffer_size + 1);
fread(*p_buffer, 1, buffer_size, p_file);
((c8*)*p_buffer)[size] = '\0';
fclose(p_file);
return PEN_ERR_OK;
}
return PEN_ERR_FILE_NOT_FOUND;
}
pen_error filesystem_enum_volumes(fs_tree_node& tree)
{
DWORD drive_bit_mask = GetLogicalDrives();
if (drive_bit_mask == 0)
{
return PEN_ERR_FAILED;
}
const c8* volumes_str = "Volumes";
u32 volume_strlen = pen::string_length(volumes_str);
tree.name = (c8*)pen::memory_alloc(volume_strlen + 1);
memcpy(tree.name, volumes_str, volume_strlen);
tree.name[volume_strlen] = '\0';
const c8* drive_letters = {"ABCDEFGHIJKLMNOPQRSTUVWXYZ"};
u32 num_drives = pen::string_length(drive_letters);
u32 num_used_drives = 0;
u32 bit = 1;
for (u32 i = 0; i < num_drives; ++i)
{
if (drive_bit_mask & bit)
{
++num_used_drives;
}
bit <<= 1;
}
tree.num_children = num_used_drives;
tree.children = (fs_tree_node*)pen::memory_alloc(sizeof(fs_tree_node) * num_used_drives);
bit = 1;
u32 child = 0;
for (u32 i = 0; i < num_drives; ++i)
{
if (drive_bit_mask & bit)
{
tree.children[child].name = (c8*)pen::memory_alloc(3);
tree.children[child].name[0] = drive_letters[i];
tree.children[child].name[1] = ':';
tree.children[child].name[2] = '\0';
tree.children[child].num_children = 0;
tree.children[child].children = nullptr;
++child;
}
bit <<= 1;
}
return PEN_ERR_OK;
}
bool match_file(const WIN32_FIND_DATAA ffd, s32 num_wildcards, va_list wildcards)
{
if (num_wildcards <= 0)
{
return true;
}
va_list wildcards_consume;
va_copy(wildcards_consume, wildcards);
if (!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
for (s32 i = 0; i < num_wildcards; ++i)
{
const char* ft = va_arg(wildcards_consume, const char*);
if (PathMatchSpecExA(ffd.cFileName, ft, PMSF_NORMAL) == S_OK)
{
return true;
}
}
}
else
{
return true;
}
return false;
}
pen_error filesystem_enum_directory(const c8* directory, fs_tree_node& results, s32 num_wildcards, ...)
{
va_list filetypes;
va_start(filetypes, num_wildcards);
pen_error result = filesystem_enum_directory(directory, results, num_wildcards, filetypes);
va_end(filetypes);
return result;
}
pen_error filesystem_enum_directory(const c8* directory, fs_tree_node& tree, s32 num_wildcards, va_list args)
{
WIN32_FIND_DATAA ffd;
HANDLE hFind = INVALID_HANDLE_VALUE;
// need to make add a wildcard to the dirctory
u32 dir_len = pen::string_length(directory);
static c8 wildcard_dir[1024];
memcpy(wildcard_dir, directory, dir_len);
wildcard_dir[dir_len] = '\\';
wildcard_dir[dir_len + 1] = '*';
wildcard_dir[dir_len + 2] = '\0';
c8* windir_filename = swap_slashes(wildcard_dir);
u32 total_num = 0;
hFind = FindFirstFileA(windir_filename, &ffd);
do
{
if (hFind != INVALID_HANDLE_VALUE)
{
if(!s_show_hidden)
{
if((data.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0)
continue;
}
if (match_file(ffd, num_wildcards, args))
{
++total_num;
}
}
} while (FindNextFileA(hFind, &ffd) != 0);
// allocate children into the fs tree structure
tree.num_children = total_num;
if (tree.num_children == 0)
{
tree.children = nullptr;
return PEN_ERR_FILE_NOT_FOUND;
}
tree.children = (fs_tree_node*)pen::memory_alloc(sizeof(fs_tree_node) * total_num);
// reiterate and get the file names
u32 child = 0;
hFind = FindFirstFileA(windir_filename, &ffd);
do
{
if (hFind != INVALID_HANDLE_VALUE)
{
if (match_file(ffd, num_wildcards, args))
{
u32 file_name_len = pen::string_length(ffd.cFileName);
tree.children[child].name = (c8*)pen::memory_alloc(file_name_len + 1);
memcpy(tree.children[child].name, ffd.cFileName, file_name_len);
tree.children[child].name[file_name_len] = '\0';
tree.children[child].num_children = 0;
tree.children[child].children = nullptr;
++child;
}
}
} while (FindNextFileA(hFind, &ffd) != 0);
pen::memory_free(windir_filename);
return PEN_ERR_OK;
}
pen_error filesystem_enum_free_mem(fs_tree_node& tree)
{
for (u32 i = 0; i < tree.num_children; ++i)
{
filesystem_enum_free_mem(tree.children[i]);
}
pen::memory_free(tree.children);
pen::memory_free(tree.name);
return PEN_ERR_OK;
}
const c8* filesystem_get_user_directory()
{
static c8 path[MAX_PATH];
if (SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_PROFILE, NULL, 0, path)))
return &path[0];
return nullptr;
}
const c8** filesystem_get_user_directory(s32& directory_depth)
{
const u32 max_depth = 4;
static c8 dirs[max_depth][MAX_PATH];
static c8* dir_list[max_depth];
c8 path[MAX_PATH];
if (SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_PROFILE, NULL, 0, path)))
{
u32 len = pen::string_length(path);
u32 cur_pos = 0;
u32 cur_depth = 0;
for (u32 i = 0; i < len; ++i)
{
bool last_char = i == len - 1;
if (path[i] == '\\' || last_char)
{
u32 sub_dir_len = i - cur_pos;
if (last_char)
sub_dir_len++;
memcpy(dirs[cur_depth], &path[cur_pos], sub_dir_len);
dirs[cur_depth][sub_dir_len] = '\0';
cur_depth++;
cur_pos = i + 1;
}
}
directory_depth = cur_depth;
for (s32 i = 0; i < directory_depth; ++i)
{
dir_list[i] = &dirs[i][0];
}
return (const c8**)&dir_list[0];
}
return nullptr;
}
s32 filesystem_exclude_slash_depth()
{
// all windows directories when listed can exclude slashes
return -1;
}
} // namespace pen
<commit_msg>fix win32<commit_after>#include "file_system.h"
#include "memory.h"
#include "pen_string.h"
#include <Shlobj.h>
#include <Shlwapi.h>
#include <stdio.h>
namespace pen
{
#define WINDOWS_TICK 10000000
#define SEC_TO_UNIX_EPOCH 11644473600LL
c8* swap_slashes(const c8* filename);
static bool s_show_hidden = false;
void filesystem_toggle_hidden_files()
{
s_show_hidden = !s_show_hidden;
}
u32 win32_time_to_unix_seconds(long long ticks)
{
return (u32)(ticks / WINDOWS_TICK - SEC_TO_UNIX_EPOCH);
}
pen_error filesystem_getmtime(const c8* filename, u32& mtime_out)
{
c8* corrected_name = swap_slashes(filename);
OFSTRUCT of_struct;
HFILE f = OpenFile(corrected_name, &of_struct, OF_READ);
pen::memory_free(corrected_name);
if (f != HFILE_ERROR)
{
FILETIME c, m, a;
BOOL res = GetFileTime((HANDLE)(size_t)f, &c, &a, &m);
long long* wt = (long long*)&m;
u32 unix_ts = win32_time_to_unix_seconds(*wt);
mtime_out = unix_ts;
CloseHandle((HANDLE)(size_t)f);
return PEN_ERR_OK;
}
return PEN_ERR_FILE_NOT_FOUND;
}
c8* swap_slashes(const c8* filename)
{
// swap "/" for "\\"
const char* p_src_char = filename;
u32 str_len = pen::string_length(filename);
char* windir_filename = (char*)pen::memory_alloc(str_len + 1);
char* p_dest_char = windir_filename;
while (p_src_char < filename + str_len)
{
if (*p_src_char == '/')
*p_dest_char = '\\';
else if (*p_src_char == '@')
*p_dest_char = ':';
else
*p_dest_char = *p_src_char;
p_dest_char++;
p_src_char++;
}
*p_dest_char = '\0';
return windir_filename;
}
pen_error filesystem_read_file_to_buffer(const c8* filename, void** p_buffer, u32& buffer_size)
{
c8* windir_filename = swap_slashes(filename);
*p_buffer = NULL;
FILE* p_file = nullptr;
fopen_s(&p_file, windir_filename, "rb");
pen::memory_free(windir_filename);
if (p_file)
{
fseek(p_file, 0L, SEEK_END);
LONG size = ftell(p_file);
fseek(p_file, 0L, SEEK_SET);
buffer_size = (u32)size;
*p_buffer = pen::memory_alloc(buffer_size + 1);
fread(*p_buffer, 1, buffer_size, p_file);
((c8*)*p_buffer)[size] = '\0';
fclose(p_file);
return PEN_ERR_OK;
}
return PEN_ERR_FILE_NOT_FOUND;
}
pen_error filesystem_enum_volumes(fs_tree_node& tree)
{
DWORD drive_bit_mask = GetLogicalDrives();
if (drive_bit_mask == 0)
{
return PEN_ERR_FAILED;
}
const c8* volumes_str = "Volumes";
u32 volume_strlen = pen::string_length(volumes_str);
tree.name = (c8*)pen::memory_alloc(volume_strlen + 1);
memcpy(tree.name, volumes_str, volume_strlen);
tree.name[volume_strlen] = '\0';
const c8* drive_letters = {"ABCDEFGHIJKLMNOPQRSTUVWXYZ"};
u32 num_drives = pen::string_length(drive_letters);
u32 num_used_drives = 0;
u32 bit = 1;
for (u32 i = 0; i < num_drives; ++i)
{
if (drive_bit_mask & bit)
{
++num_used_drives;
}
bit <<= 1;
}
tree.num_children = num_used_drives;
tree.children = (fs_tree_node*)pen::memory_alloc(sizeof(fs_tree_node) * num_used_drives);
bit = 1;
u32 child = 0;
for (u32 i = 0; i < num_drives; ++i)
{
if (drive_bit_mask & bit)
{
tree.children[child].name = (c8*)pen::memory_alloc(3);
tree.children[child].name[0] = drive_letters[i];
tree.children[child].name[1] = ':';
tree.children[child].name[2] = '\0';
tree.children[child].num_children = 0;
tree.children[child].children = nullptr;
++child;
}
bit <<= 1;
}
return PEN_ERR_OK;
}
bool match_file(const WIN32_FIND_DATAA ffd, s32 num_wildcards, va_list wildcards)
{
if (num_wildcards <= 0)
{
return true;
}
va_list wildcards_consume;
va_copy(wildcards_consume, wildcards);
if (!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
for (s32 i = 0; i < num_wildcards; ++i)
{
const char* ft = va_arg(wildcards_consume, const char*);
if (PathMatchSpecExA(ffd.cFileName, ft, PMSF_NORMAL) == S_OK)
{
return true;
}
}
}
else
{
return true;
}
return false;
}
pen_error filesystem_enum_directory(const c8* directory, fs_tree_node& results, s32 num_wildcards, ...)
{
va_list filetypes;
va_start(filetypes, num_wildcards);
pen_error result = filesystem_enum_directory(directory, results, num_wildcards, filetypes);
va_end(filetypes);
return result;
}
pen_error filesystem_enum_directory(const c8* directory, fs_tree_node& tree, s32 num_wildcards, va_list args)
{
WIN32_FIND_DATAA ffd;
HANDLE hFind = INVALID_HANDLE_VALUE;
// need to make add a wildcard to the dirctory
u32 dir_len = pen::string_length(directory);
static c8 wildcard_dir[1024];
memcpy(wildcard_dir, directory, dir_len);
wildcard_dir[dir_len] = '\\';
wildcard_dir[dir_len + 1] = '*';
wildcard_dir[dir_len + 2] = '\0';
c8* windir_filename = swap_slashes(wildcard_dir);
u32 total_num = 0;
hFind = FindFirstFileA(windir_filename, &ffd);
do
{
if (hFind != INVALID_HANDLE_VALUE)
{
if(!s_show_hidden)
{
if((ffd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0)
continue;
}
if (match_file(ffd, num_wildcards, args))
{
++total_num;
}
}
} while (FindNextFileA(hFind, &ffd) != 0);
// allocate children into the fs tree structure
tree.num_children = total_num;
if (tree.num_children == 0)
{
tree.children = nullptr;
return PEN_ERR_FILE_NOT_FOUND;
}
tree.children = (fs_tree_node*)pen::memory_alloc(sizeof(fs_tree_node) * total_num);
// reiterate and get the file names
u32 child = 0;
hFind = FindFirstFileA(windir_filename, &ffd);
do
{
if (hFind != INVALID_HANDLE_VALUE)
{
if (match_file(ffd, num_wildcards, args))
{
u32 file_name_len = pen::string_length(ffd.cFileName);
tree.children[child].name = (c8*)pen::memory_alloc(file_name_len + 1);
memcpy(tree.children[child].name, ffd.cFileName, file_name_len);
tree.children[child].name[file_name_len] = '\0';
tree.children[child].num_children = 0;
tree.children[child].children = nullptr;
++child;
}
}
} while (FindNextFileA(hFind, &ffd) != 0);
pen::memory_free(windir_filename);
return PEN_ERR_OK;
}
pen_error filesystem_enum_free_mem(fs_tree_node& tree)
{
for (u32 i = 0; i < tree.num_children; ++i)
{
filesystem_enum_free_mem(tree.children[i]);
}
pen::memory_free(tree.children);
pen::memory_free(tree.name);
return PEN_ERR_OK;
}
const c8* filesystem_get_user_directory()
{
static c8 path[MAX_PATH];
if (SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_PROFILE, NULL, 0, path)))
return &path[0];
return nullptr;
}
const c8** filesystem_get_user_directory(s32& directory_depth)
{
const u32 max_depth = 4;
static c8 dirs[max_depth][MAX_PATH];
static c8* dir_list[max_depth];
c8 path[MAX_PATH];
if (SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_PROFILE, NULL, 0, path)))
{
u32 len = pen::string_length(path);
u32 cur_pos = 0;
u32 cur_depth = 0;
for (u32 i = 0; i < len; ++i)
{
bool last_char = i == len - 1;
if (path[i] == '\\' || last_char)
{
u32 sub_dir_len = i - cur_pos;
if (last_char)
sub_dir_len++;
memcpy(dirs[cur_depth], &path[cur_pos], sub_dir_len);
dirs[cur_depth][sub_dir_len] = '\0';
cur_depth++;
cur_pos = i + 1;
}
}
directory_depth = cur_depth;
for (s32 i = 0; i < directory_depth; ++i)
{
dir_list[i] = &dirs[i][0];
}
return (const c8**)&dir_list[0];
}
return nullptr;
}
s32 filesystem_exclude_slash_depth()
{
// all windows directories when listed can exclude slashes
return -1;
}
} // namespace pen
<|endoftext|>
|
<commit_before>/*
* LoadHandler.cpp
*
* Created on: 29.05.2017
* Author: Alexander
*/
#include "persistence/base/LoadHandler.hpp"
#include <sstream> // used for getLevel()
#include "abstractDataTypes/Bag.hpp"
#include "boost/algorithm/string.hpp" // used for string splitting
#include "ecore/EClassifier.hpp"
#include "ecore/EObject.hpp"
#include "ecore/EPackage.hpp"
#include "ecore/EStructuralFeature.hpp"
#include "persistence/base/HandlerHelper.hpp"
#include "pluginFramework/MDE4CPPPlugin.hpp"
#include "pluginFramework/PluginFramework.hpp"
using namespace persistence::base;
LoadHandler::LoadHandler()
{
m_rootObject = nullptr;
m_level = -1;
m_isXSIMode = true;
}
LoadHandler::~LoadHandler()
{
}
std::shared_ptr<ecore::EObject> LoadHandler::getObjectByRef(std::string ref)
{
std::shared_ptr<ecore::EObject> tmp;
if (!ref.empty())
{
if (m_refToObject_map.find(ref) != m_refToObject_map.end())
{
// found
tmp = m_refToObject_map.at(ref);
//return std::dynamic_pointer_cast<ecore::EObject>( tmp );
}
else
{
size_t double_dot = ref.find("#//", 0);
std::string _ref_prefix = "";
std::string _ref_name = "";
if (double_dot != std::string::npos)
{
std::string _ref_prefix = ref.substr(0, double_dot); // TODO '_ref_prefix' is not used in this case
std::string _ref_name = ref.substr(double_dot);
}
if (m_refToObject_map.find(_ref_name) != m_refToObject_map.end())
{
// found
tmp = m_refToObject_map.at(_ref_name);
//return std::dynamic_pointer_cast<ecore::EObject>( tmp );
}
else
{
MSG_WARNING("Given Reference-Name '" << ref << "' or '" << _ref_name << "' are not in stored map.");
return nullptr;
}
}
}
return tmp;
}
void LoadHandler::addToMap(std::shared_ptr<ecore::EObject> object)
{
addToMap(object, true);
}
void LoadHandler::addToMap(std::shared_ptr<ecore::EObject> object, bool useCurrentObjects)
{
std::shared_ptr<ecore::ENamedElement> namedElement = std::dynamic_pointer_cast<ecore::ENamedElement>(object);
if (namedElement == nullptr)
{
return;
}
std::string ref = getCurrentXMIID();
if (!ref.empty())
{
// do nothing here
}
else if (useCurrentObjects)
{
ref = persistence::base::HandlerHelper::extractReference(namedElement, m_rootObject, m_rootPrefix, m_currentObjects);
}
else
{
ref = persistence::base::HandlerHelper::extractReference(namedElement, m_rootObject, m_rootPrefix);
}
if (!ref.empty())
{
if (m_refToObject_map.find(ref) == m_refToObject_map.end())
{
// ref not found in map, so insert
m_refToObject_map.insert(std::pair<std::string, std::shared_ptr<ecore::EObject>>(ref, object));
MSG_DEBUG("Add to map: '" << ref << "'");
}
unsigned int index = ref.find(" ");
if (index != std::string::npos)
{
std::string ref2 = ref.substr(index+1, ref.size());
if (m_refToObject_map.find(ref2) == m_refToObject_map.end())
{
// ref not found in map, so insert
m_refToObject_map.insert(std::pair<std::string, std::shared_ptr<ecore::EObject>>(ref2, object));
MSG_DEBUG("Add to map: '" << ref2 << "'");
}
}
}
}
/**/
std::string LoadHandler::getPrefix()
{
return m_rootPrefix;
}
std::string LoadHandler::getRootName()
{
return m_rootName;
}
std::string LoadHandler::getLevel()
{
std::stringstream ss;
for (int ii = 0; ii < m_level; ii++)
{
ss << " ";
}
return ss.str();
}
void LoadHandler::handleRoot(std::shared_ptr<ecore::EObject> object)
{
if (object == nullptr)
{
return;
}
m_level++;
m_currentObjects.push_back(object);
m_rootObject = object;
getNextNodeName();
object->load(m_thisPtr);
}
void LoadHandler::handleChild(std::shared_ptr<ecore::EObject> object)
{
if (object == nullptr)
{
return;
}
m_level++;
m_currentObjects.push_back(object);
object->load(m_thisPtr); // call recursively 'object.load().
addToMap(object); // add 'object' to loadHandler's internal Map, that is used for resolving references.
release(); // report loadHandler to set 'this' as new current Object.
}
std::shared_ptr<ecore::EObject> LoadHandler::getCurrentObject()
{
std::shared_ptr<ecore::EObject> tmp_obj = m_currentObjects.back();
assert(tmp_obj);
return tmp_obj;
}
/*
* This API is adapted to API in Project emf4cpp.
*
* LINK to source: https://github.com/catedrasaes-umu/emf4cpp/tree/master/emf4cpp/ecorecpp/serializer/serializer-xerces.cpp
* ::ecorecpp::mapping::type_traits::string_t serializer::get_type(EObject_ptr obj) const
*
*/
std::string LoadHandler::extractType(std::shared_ptr<ecore::EObject> obj) const
{
return persistence::base::HandlerHelper::extractType(obj, m_rootPrefix);
}
void LoadHandler::release()
{
std::shared_ptr<ecore::EObject> tmp_obj = m_currentObjects.back();
if (tmp_obj == nullptr)
{
MSG_ERROR("You can't call " << __PRETTY_FUNCTION__ << " while current Object is nullptr.");
}
else
{
// set current (container) object as new current object (decrease depth)
m_currentObjects.pop_back();
m_level--;
}
}
void LoadHandler::addUnresolvedReference(const std::string &name, std::shared_ptr<ecore::EObject> object, std::shared_ptr<ecore::EStructuralFeature> esf)
{
if (object != nullptr)
{
if (esf != nullptr)
{
m_unresolvedReferences.push_back(persistence::base::UnresolvedReference(name, object, esf));
}
else
{
MSG_ERROR(MSG_FLF << " esf is a nullptr");
}
}
else
{
MSG_ERROR(MSG_FLF << " object is a nullptr");
}
}
void LoadHandler::resolveReferences()
{
while (!m_unresolvedReferences.empty())
{
persistence::base::UnresolvedReference uref = m_unresolvedReferences.back();
m_unresolvedReferences.pop_back();
std::string name = uref.refName;
std::shared_ptr<ecore::EObject> object = uref.eObject;
std::shared_ptr<ecore::EStructuralFeature> esf = uref.eStructuralFeature;
std::list<std::shared_ptr<ecore::EObject>> references;
try
{
if (esf->getUpperBound() == 1)
{
// EStructuralFeature is a single object
solve(name, references, object, esf);
}
else
{
// EStructuralFeature is a list of objects
std::list<std::string> _strs;
std::string _tmpStr;
boost::split(_strs, name, boost::is_any_of(" "));
while (_strs.size() > 0)
{
_tmpStr = _strs.front();
if (std::string::npos != _tmpStr.find("#//"))
{
solve(_tmpStr, references, object, esf);
}
_strs.pop_front();
}
// Call resolveReferences() of corresponding 'object'
object->resolveReferences(esf->getFeatureID(), references);
}
}
catch (std::exception& e)
{
MSG_ERROR(MSG_FLF << " Exception: " << e.what());
}
}
}
void LoadHandler::setThisPtr(std::shared_ptr<LoadHandler> thisPtr)
{
m_thisPtr = thisPtr;
}
void LoadHandler::solve(const std::string& name, std::list<std::shared_ptr<ecore::EObject>> references, std::shared_ptr<ecore::EObject> object, std::shared_ptr<ecore::EStructuralFeature> esf)
{
bool found = false;
bool libraryLoaded = false;
while (!found)
{
std::shared_ptr<ecore::EObject> resolved_object = this->getObjectByRef(name);
if (resolved_object)
{
references.push_back(resolved_object);
// Call resolveReferences() of corresponding 'object'
object->resolveReferences(esf->getFeatureID(), references);
found = true;
}
else
{
if (libraryLoaded)
{
return;
}
loadTypes(name);
libraryLoaded = true;
}
}
}
void LoadHandler::loadTypes(const std::string& name)
{
unsigned int indexStartUri = name.find(" ");
unsigned int indexEndUri = name.find("#");
if (indexStartUri != std::string::npos)
{
std::string nsURI = name.substr(indexStartUri+1, indexEndUri-indexStartUri-1);
std::shared_ptr<PluginFramework> pluginFramework = PluginFramework::eInstance();
std::shared_ptr<MDE4CPPPlugin> plugin = pluginFramework->findPluginByUri(nsURI);
if (plugin)
{
loadTypes(plugin->getEPackage());
}
}
}
void LoadHandler::loadTypes(std::shared_ptr<ecore::EPackage> package)
{
std::shared_ptr<Bag<ecore::EClassifier>> eClassifiers = package->getEClassifiers();
for (std::shared_ptr<ecore::EClassifier> eClassifier : *eClassifiers)
{
// Filter only EDataType objects and add to handler's internal map
std::shared_ptr<ecore::EClass> _metaClass = eClassifier->eClass();
addToMap(eClassifier, false); // TODO add default parameter force=true to addToMap()
}
}
std::map<std::string, std::shared_ptr<ecore::EObject>> LoadHandler::getTypesMap()
{
return m_refToObject_map;
}
<commit_msg>[persistence] do not use xmi:id for external types<commit_after>/*
* LoadHandler.cpp
*
* Created on: 29.05.2017
* Author: Alexander
*/
#include "persistence/base/LoadHandler.hpp"
#include <sstream> // used for getLevel()
#include "abstractDataTypes/Bag.hpp"
#include "boost/algorithm/string.hpp" // used for string splitting
#include "ecore/EClass.hpp"
#include "ecore/EClassifier.hpp"
#include "ecore/EObject.hpp"
#include "ecore/EPackage.hpp"
#include "ecore/EStructuralFeature.hpp"
#include "persistence/base/HandlerHelper.hpp"
#include "pluginFramework/MDE4CPPPlugin.hpp"
#include "pluginFramework/PluginFramework.hpp"
using namespace persistence::base;
LoadHandler::LoadHandler()
{
m_rootObject = nullptr;
m_level = -1;
m_isXSIMode = true;
}
LoadHandler::~LoadHandler()
{
}
std::shared_ptr<ecore::EObject> LoadHandler::getObjectByRef(std::string ref)
{
std::shared_ptr<ecore::EObject> tmp;
if (!ref.empty())
{
if (m_refToObject_map.find(ref) != m_refToObject_map.end())
{
// found
tmp = m_refToObject_map.at(ref);
//return std::dynamic_pointer_cast<ecore::EObject>( tmp );
}
else
{
size_t double_dot = ref.find("#//", 0);
std::string _ref_prefix = "";
std::string _ref_name = "";
if (double_dot != std::string::npos)
{
std::string _ref_prefix = ref.substr(0, double_dot); // TODO '_ref_prefix' is not used in this case
std::string _ref_name = ref.substr(double_dot);
}
if (m_refToObject_map.find(_ref_name) != m_refToObject_map.end())
{
// found
tmp = m_refToObject_map.at(_ref_name);
//return std::dynamic_pointer_cast<ecore::EObject>( tmp );
}
else
{
MSG_WARNING("Given Reference-Name '" << ref << "' or '" << _ref_name << "' are not in stored map.");
return nullptr;
}
}
}
return tmp;
}
void LoadHandler::addToMap(std::shared_ptr<ecore::EObject> object)
{
addToMap(object, true);
}
void LoadHandler::addToMap(std::shared_ptr<ecore::EObject> object, bool useCurrentObjects)
{
std::string ref = "";
if (useCurrentObjects)
{
ref = getCurrentXMIID();
if (ref.empty())
{
ref = persistence::base::HandlerHelper::extractReference(object, m_rootObject, m_rootPrefix, m_currentObjects);
}
}
else
{
ref = persistence::base::HandlerHelper::extractReference(object, m_rootObject, m_rootPrefix);
}
if (!ref.empty())
{
if (m_refToObject_map.find(ref) == m_refToObject_map.end())
{
// ref not found in map, so insert
m_refToObject_map.insert(std::pair<std::string, std::shared_ptr<ecore::EObject>>(ref, object));
MSG_DEBUG("Add to map: '" << ref << "' eClass: '" << object->eClass()->getName() << "'");
}
}
}
/**/
std::string LoadHandler::getPrefix()
{
return m_rootPrefix;
}
std::string LoadHandler::getRootName()
{
return m_rootName;
}
std::string LoadHandler::getLevel()
{
std::stringstream ss;
for (int ii = 0; ii < m_level; ii++)
{
ss << " ";
}
return ss.str();
}
void LoadHandler::handleRoot(std::shared_ptr<ecore::EObject> object)
{
if (object == nullptr)
{
return;
}
m_level++;
m_currentObjects.push_back(object);
m_rootObject = object;
getNextNodeName();
object->load(m_thisPtr);
}
void LoadHandler::handleChild(std::shared_ptr<ecore::EObject> object)
{
if (object == nullptr)
{
return;
}
m_level++;
m_currentObjects.push_back(object);
object->load(m_thisPtr); // call recursively 'object.load().
addToMap(object); // add 'object' to loadHandler's internal Map, that is used for resolving references.
release(); // report loadHandler to set 'this' as new current Object.
}
std::shared_ptr<ecore::EObject> LoadHandler::getCurrentObject()
{
std::shared_ptr<ecore::EObject> tmp_obj = m_currentObjects.back();
assert(tmp_obj);
return tmp_obj;
}
/*
* This API is adapted to API in Project emf4cpp.
*
* LINK to source: https://github.com/catedrasaes-umu/emf4cpp/tree/master/emf4cpp/ecorecpp/serializer/serializer-xerces.cpp
* ::ecorecpp::mapping::type_traits::string_t serializer::get_type(EObject_ptr obj) const
*
*/
std::string LoadHandler::extractType(std::shared_ptr<ecore::EObject> obj) const
{
return persistence::base::HandlerHelper::extractType(obj, m_rootPrefix);
}
void LoadHandler::release()
{
std::shared_ptr<ecore::EObject> tmp_obj = m_currentObjects.back();
if (tmp_obj == nullptr)
{
MSG_ERROR("You can't call " << __PRETTY_FUNCTION__ << " while current Object is nullptr.");
}
else
{
// set current (container) object as new current object (decrease depth)
m_currentObjects.pop_back();
m_level--;
}
}
void LoadHandler::addUnresolvedReference(const std::string &name, std::shared_ptr<ecore::EObject> object, std::shared_ptr<ecore::EStructuralFeature> esf)
{
if (object != nullptr)
{
if (esf != nullptr)
{
m_unresolvedReferences.push_back(persistence::base::UnresolvedReference(name, object, esf));
}
else
{
MSG_ERROR(MSG_FLF << " esf is a nullptr");
}
}
else
{
MSG_ERROR(MSG_FLF << " object is a nullptr");
}
}
void LoadHandler::resolveReferences()
{
while (!m_unresolvedReferences.empty())
{
persistence::base::UnresolvedReference uref = m_unresolvedReferences.back();
m_unresolvedReferences.pop_back();
std::string name = uref.refName;
std::shared_ptr<ecore::EObject> object = uref.eObject;
std::shared_ptr<ecore::EStructuralFeature> esf = uref.eStructuralFeature;
std::list<std::shared_ptr<ecore::EObject>> references;
try
{
if (esf->getUpperBound() == 1)
{
// EStructuralFeature is a single object
solve(name, references, object, esf);
}
else
{
// EStructuralFeature is a list of objects
std::list<std::string> _strs;
std::string _tmpStr;
boost::split(_strs, name, boost::is_any_of(" "));
while (_strs.size() > 0)
{
_tmpStr = _strs.front();
if (std::string::npos != _tmpStr.find("#//"))
{
solve(_tmpStr, references, object, esf);
}
_strs.pop_front();
}
// Call resolveReferences() of corresponding 'object'
object->resolveReferences(esf->getFeatureID(), references);
}
}
catch (std::exception& e)
{
MSG_ERROR(MSG_FLF << " Exception: " << e.what());
}
}
}
void LoadHandler::setThisPtr(std::shared_ptr<LoadHandler> thisPtr)
{
m_thisPtr = thisPtr;
}
void LoadHandler::solve(const std::string& name, std::list<std::shared_ptr<ecore::EObject>> references, std::shared_ptr<ecore::EObject> object, std::shared_ptr<ecore::EStructuralFeature> esf)
{
bool found = false;
bool libraryLoaded = false;
while (!found)
{
std::shared_ptr<ecore::EObject> resolved_object = this->getObjectByRef(name);
if (resolved_object)
{
references.push_back(resolved_object);
// Call resolveReferences() of corresponding 'object'
object->resolveReferences(esf->getFeatureID(), references);
found = true;
}
else
{
if (libraryLoaded)
{
return;
}
loadTypes(name);
libraryLoaded = true;
}
}
}
void LoadHandler::loadTypes(const std::string& name)
{
unsigned int indexStartUri = name.find(" ");
unsigned int indexEndUri = name.find("#");
if (indexStartUri != std::string::npos)
{
std::string nsURI = name.substr(indexStartUri+1, indexEndUri-indexStartUri-1);
std::shared_ptr<PluginFramework> pluginFramework = PluginFramework::eInstance();
std::shared_ptr<MDE4CPPPlugin> plugin = pluginFramework->findPluginByUri(nsURI);
if (plugin)
{
loadTypes(plugin->getEPackage());
}
}
}
void LoadHandler::loadTypes(std::shared_ptr<ecore::EPackage> package)
{
std::shared_ptr<Bag<ecore::EClassifier>> eClassifiers = package->getEClassifiers();
for (std::shared_ptr<ecore::EClassifier> eClassifier : *eClassifiers)
{
// Filter only EDataType objects and add to handler's internal map
std::shared_ptr<ecore::EClass> _metaClass = eClassifier->eClass();
addToMap(eClassifier, false); // TODO add default parameter force=true to addToMap()
}
}
std::map<std::string, std::shared_ptr<ecore::EObject>> LoadHandler::getTypesMap()
{
return m_refToObject_map;
}
<|endoftext|>
|
<commit_before>#include <gtest/gtest.h>
#include "photoeffects.hpp"
using namespace cv;
TEST(photoeffects, SepiaFakeTest) {
Mat src(10, 10, CV_8UC1), dst;
EXPECT_EQ(0, sepia(src, dst));
}
TEST(photoeffects, SepiaFailTest) {
Mat src(10, 10, CV_8UC3), dst;
EXPECT_EQ(1, sepia(src, dst));
}
TEST(photoeffects, SepiaTest) {
Mat src(10, 10, CV_8UC1), dst, hsvDst;
vector<Mat> channels(3);
EXPECT_EQ(0, sepia(src, dst));
cvtColor(dst, hsvDst, CV_BGR2HSV);
split(hsvDst, channels);
EXPECT_EQ(78, channels[1].at<uchar>(0, 0));
EXPECT_EQ(src.at<uchar>(0, 0) + 20, channels[2].at<uchar>(0, 0));
}
<commit_msg>Test was modified.<commit_after>#include <gtest/gtest.h>
#include "photoeffects.hpp"
using namespace cv;
TEST(photoeffects, SepiaFakeTest) {
Mat src(10, 10, CV_8UC1), dst;
EXPECT_EQ(0, sepia(src, dst));
}
TEST(photoeffects, SepiaFailTest) {
Mat src(10, 10, CV_8UC3), dst;
EXPECT_EQ(1, sepia(src, dst));
}
TEST(photoeffects, SepiaTest) {
Mat src(10, 10, CV_8UC1), dst, hsvDst;
vector<Mat> channels(3);
EXPECT_EQ(0, sepia(src, dst));
cvtColor(dst, hsvDst, CV_BGR2HSV);
split(hsvDst, channels);
EXPECT_EQ(src.at<uchar>(0, 0) + 20, channels[2].at<uchar>(0, 0));
}
<|endoftext|>
|
<commit_before>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <cstdio>
#include "symbol_table.h"
#include "ast.h"
#include "glsl_types.h"
#include "ir.h"
ir_instruction *
ast_function_expression::hir(exec_list *instructions,
struct _mesa_glsl_parse_state *state)
{
/* There are three sorts of function calls.
*
* 1. contstructors - The first subexpression is an ast_type_specifier.
* 2. methods - Only the .length() method of array types.
* 3. functions - Calls to regular old functions.
*
* There are two kinds of constructor call. Constructors for built-in
* language types, such as mat4 and vec2, are free form. The only
* requirement is that the parameters must provide enough values of the
* correct scalar type. Constructors for arrays and structures must have
* the exact number of parameters with matching types in the correct order.
* These constructors follow essentially the same type matching rules as
* functions.
*
* Method calls are actually detected when the ast_field_selection
* expression is handled.
*/
if (is_constructor()) {
return ir_call::get_error_instruction();
} else {
const ast_expression *id = subexpressions[0];
ir_function *f = (ir_function *)
_mesa_symbol_table_find_symbol(state->symbols, 0,
id->primary_expression.identifier);
if (f == NULL) {
YYLTYPE loc = id->get_location();
_mesa_glsl_error(& loc, state, "function `%s' undeclared",
id->primary_expression.identifier);
return ir_call::get_error_instruction();
}
/* Once we've determined that the function being called might exist,
* process the parameters.
*/
exec_list actual_parameters;
simple_node *const first = subexpressions[1];
if (first != NULL) {
simple_node *ptr = first;
do {
ir_instruction *const result =
((ast_node *) ptr)->hir(instructions, state);
ptr = ptr->next;
actual_parameters.push_tail(result);
} while (ptr != first);
}
/* After processing the function's actual parameters, try to find an
* overload of the function that matches.
*/
const ir_function_signature *sig =
f->matching_signature(& actual_parameters);
if (sig != NULL) {
/* FINISHME: The list of actual parameters needs to be modified to
* FINISHME: include any necessary conversions.
*/
return new ir_call(sig, & actual_parameters);
} else {
YYLTYPE loc = id->get_location();
/* FINISHME: Log a better error message here. G++ will show the types
* FINISHME: of the actual parameters and the set of candidate
* FINISHME: functions. A different error should also be logged when
* FINISHME: multiple functions match.
*/
_mesa_glsl_error(& loc, state, "no matching function for call to `%s'",
id->primary_expression.identifier);
return ir_call::get_error_instruction();
}
}
return ir_call::get_error_instruction();
}
<commit_msg>Factor guts of function matching code out to match_function_by_name<commit_after>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <cstdio>
#include "symbol_table.h"
#include "ast.h"
#include "glsl_types.h"
#include "ir.h"
static ir_instruction *
match_function_by_name(exec_list *instructions, const char *name,
YYLTYPE *loc, simple_node *parameters,
struct _mesa_glsl_parse_state *state)
{
ir_function *f = (ir_function *)
_mesa_symbol_table_find_symbol(state->symbols, 0, name);
if (f == NULL) {
_mesa_glsl_error(loc, state, "function `%s' undeclared", name);
return ir_call::get_error_instruction();
}
/* Once we've determined that the function being called might exist,
* process the parameters.
*/
exec_list actual_parameters;
simple_node *const first = parameters;
if (first != NULL) {
simple_node *ptr = first;
do {
ir_instruction *const result =
((ast_node *) ptr)->hir(instructions, state);
ptr = ptr->next;
actual_parameters.push_tail(result);
} while (ptr != first);
}
/* After processing the function's actual parameters, try to find an
* overload of the function that matches.
*/
const ir_function_signature *sig =
f->matching_signature(& actual_parameters);
if (sig != NULL) {
/* FINISHME: The list of actual parameters needs to be modified to
* FINISHME: include any necessary conversions.
*/
return new ir_call(sig, & actual_parameters);
} else {
/* FINISHME: Log a better error message here. G++ will show the types
* FINISHME: of the actual parameters and the set of candidate
* FINISHME: functions. A different error should also be logged when
* FINISHME: multiple functions match.
*/
_mesa_glsl_error(loc, state, "no matching function for call to `%s'",
name);
return ir_call::get_error_instruction();
}
}
ir_instruction *
ast_function_expression::hir(exec_list *instructions,
struct _mesa_glsl_parse_state *state)
{
/* There are three sorts of function calls.
*
* 1. contstructors - The first subexpression is an ast_type_specifier.
* 2. methods - Only the .length() method of array types.
* 3. functions - Calls to regular old functions.
*
* There are two kinds of constructor call. Constructors for built-in
* language types, such as mat4 and vec2, are free form. The only
* requirement is that the parameters must provide enough values of the
* correct scalar type. Constructors for arrays and structures must have
* the exact number of parameters with matching types in the correct order.
* These constructors follow essentially the same type matching rules as
* functions.
*
* Method calls are actually detected when the ast_field_selection
* expression is handled.
*/
if (is_constructor()) {
return ir_call::get_error_instruction();
} else {
const ast_expression *id = subexpressions[0];
YYLTYPE loc = id->get_location();
return match_function_by_name(instructions,
id->primary_expression.identifier, & loc,
subexpressions[1], state);
}
return ir_call::get_error_instruction();
}
<|endoftext|>
|
<commit_before>// Filename: guiManager.cxx
// Created by: cary (25Oct00)
//
////////////////////////////////////////////////////////////////////
#include "guiManager.h"
#include "config_gui.h"
#include <dataRelation.h>
#include <renderRelation.h>
#include <depthTestTransition.h>
#include <depthWriteTransition.h>
#include <materialTransition.h>
#include <cullFaceTransition.h>
#include <lightTransition.h>
#include <frustum.h>
#include <orthoProjection.h>
GuiManager::GuiMap* GuiManager::_map = (GuiManager::GuiMap*)0L;
GuiManager* GuiManager::get_ptr(GraphicsWindow* w, MouseAndKeyboard* mak) {
GuiManager* ret;
if (_map == (GuiMap*)0L) {
if (gui_cat->is_debug())
gui_cat->debug() << "allocating a manager map" << endl;
_map = new GuiMap;
}
GuiMap::const_iterator gi;
gi = _map->find(w);
if (gi != _map->end()) {
ret = (*gi).second;
if (gui_cat->is_debug())
gui_cat->debug() << "a manager for this window already exists (0x"
<< (void*)ret << ")" << endl;
} else {
// going to allocate a new GuiManager for this window
if (gui_cat->is_debug())
gui_cat->debug() << "allocating a new manager for this window" << endl;
// first see if there is a mouseWatcher already under the MouseAndKeyboard
bool has_watcher = false;
TypeHandle dgt = DataRelation::get_class_type();
MouseWatcher* watcher;
for (int i=0; i<mak->get_num_children(dgt); ++i)
if (mak->get_child(dgt, i)->get_child()->get_type() ==
MouseWatcher::get_class_type()) {
has_watcher = true;
watcher = DCAST(MouseWatcher, mak->get_child(dgt, i)->get_child());
}
if (!has_watcher) {
// there isn't already a mousewatcher in the data graph, so we'll make
// one and re-parent everything to it.
if (gui_cat->is_debug())
gui_cat->debug() << "no MouseWatcher found, making one" << endl;
watcher = new MouseWatcher("GUI watcher");
DataRelation* tmp = new DataRelation(mak, watcher);
for (int j=0; j<mak->get_num_children(dgt); ++j) {
NodeRelation* rel = mak->get_child(dgt, j);
if (rel != tmp)
// it's not the node we just created, so reparent it to ours
rel->change_parent(watcher);
}
} else if (gui_cat->is_debug())
gui_cat->debug() << "found a MouseWatcher, don't have to make one"
<< endl;
// now setup event triggers for the watcher
if (has_watcher)
gui_cat->warning() << "overwriting existing button down pattern '"
<< watcher->get_button_down_pattern()
<< "' with 'gui-%r-%b'" << endl;
watcher->set_button_down_pattern("gui-%r-%b");
if (has_watcher)
gui_cat->warning() << "overwriting existing button up pattern '"
<< watcher->get_button_up_pattern()
<< "' with 'gui-%r-%b-up'" << endl;
watcher->set_button_up_pattern("gui-%r-%b");
if (has_watcher)
gui_cat->warning() << "overwriting existing enter pattern '"
<< watcher->get_enter_pattern()
<< "' with 'gui-in-%r'" << endl;
watcher->set_enter_pattern("gui-in-%r");
if (has_watcher)
gui_cat->warning() << "overwriting existing exit pattern '"
<< watcher->get_leave_pattern()
<< "' with 'gui-out-%r'" << endl;
watcher->set_leave_pattern("gui-out-%r");
// next, create a 2d layer for the GUI stuff to live in.
Node* root2d_top = new NamedNode("GUI_top");
Node* root2d = new NamedNode("GUI");
NodeRelation* root2d_arc = new RenderRelation(root2d_top, root2d);
root2d_arc->set_transition(new DepthTestTransition(DepthTestProperty::M_none), 1);
root2d_arc->set_transition(new DepthWriteTransition(DepthWriteTransition::off()), 1);
root2d_arc->set_transition(new LightTransition(LightTransition::all_off()), 1);
root2d_arc->set_transition(new MaterialTransition(MaterialTransition::off()), 1);
root2d_arc->set_transition(new CullFaceTransition(CullFaceProperty::M_cull_none), 1);
PT(Camera) cam = new Camera("GUI_cam");
new RenderRelation(root2d, cam);
cam->set_scene(root2d_top);
Frustumf frust2d;
frust2d.make_ortho_2D();
cam->set_projection(OrthoProjection(frust2d));
GraphicsChannel *chan = w->get_channel(0); // root/full-window channel
nassertv(chan != (GraphicsChannel*)0L);
GraphicsLayer *layer = chan->make_layer();
nassertv(layer != (GraphicsLayer*)0L);
DisplayRegion *dr = layer->make_display_region();
nassertv(dr != (DisplayRegion*)0L);
dr->set_camera(cam);
if (gui_cat->is_debug())
gui_cat->debug() << "2D layer created" << endl;
// now make the manager for this window
ret = new GuiManager(watcher, root2d);
if (gui_cat->is_debug())
gui_cat->debug() << "new manager allocated (0x" << (void*)ret << ")"
<< endl;
(*_map)[w] = ret;
}
return ret;
}
void GuiManager::add_region(GuiRegion* region) {
RegionSet::const_iterator ri;
ri = _regions.find(region);
if (ri == _regions.end()) {
_watcher->add_region(region->get_region());
_regions.insert(region);
} else
gui_cat->warning() << "tried adding region ('" << *region
<< "') more then once" << endl;
}
void GuiManager::add_label(GuiLabel* label) {
LabelSet::const_iterator li;
li = _labels.find(label);
if (li == _labels.end()) {
// add it to the scenegraph
label->set_arc(new RenderRelation(_root, label->get_geometry()));
_labels.insert(label);
} else
gui_cat->warning() << "tried adding label (0x" << (void*)label
<< ") more then once" << endl;
}
void GuiManager::remove_region(GuiRegion* region) {
RegionSet::iterator ri;
ri = _regions.find(region);
if (ri == _regions.end())
gui_cat->warning() << "tried removing region ('" << *region
<< "') that isn't there" << endl;
else {
_watcher->remove_region(region->get_region());
_regions.erase(ri);
}
}
void GuiManager::remove_label(GuiLabel* label) {
LabelSet::iterator li;
li = _labels.find(label);
if (li == _labels.end())
gui_cat->warning() << "label (0x" << (void*)label
<< ") is not there to be removed" << endl;
else {
// remove it to the scenegraph
remove_arc(label->get_arc());
label->set_arc((RenderRelation*)0L);
_labels.erase(li);
}
}
<commit_msg>*** empty log message ***<commit_after>// Filename: guiManager.cxx
// Created by: cary (25Oct00)
//
////////////////////////////////////////////////////////////////////
#include "guiManager.h"
#include "config_gui.h"
#include <dataRelation.h>
#include <renderRelation.h>
#include <depthTestTransition.h>
#include <depthWriteTransition.h>
#include <materialTransition.h>
#include <cullFaceTransition.h>
#include <lightTransition.h>
#include <frustum.h>
#include <orthoProjection.h>
GuiManager::GuiMap* GuiManager::_map = (GuiManager::GuiMap*)0L;
GuiManager* GuiManager::get_ptr(GraphicsWindow* w, MouseAndKeyboard* mak) {
GuiManager* ret;
if (_map == (GuiMap*)0L) {
if (gui_cat->is_debug())
gui_cat->debug() << "allocating a manager map" << endl;
_map = new GuiMap;
}
GuiMap::const_iterator gi;
gi = _map->find(w);
if (gi != _map->end()) {
ret = (*gi).second;
if (gui_cat->is_debug())
gui_cat->debug() << "a manager for this window already exists (0x"
<< (void*)ret << ")" << endl;
} else {
// going to allocate a new GuiManager for this window
if (gui_cat->is_debug())
gui_cat->debug() << "allocating a new manager for this window" << endl;
// first see if there is a mouseWatcher already under the MouseAndKeyboard
bool has_watcher = false;
TypeHandle dgt = DataRelation::get_class_type();
MouseWatcher* watcher;
for (int i=0; i<mak->get_num_children(dgt); ++i)
if (mak->get_child(dgt, i)->get_child()->get_type() ==
MouseWatcher::get_class_type()) {
has_watcher = true;
watcher = DCAST(MouseWatcher, mak->get_child(dgt, i)->get_child());
}
if (!has_watcher) {
// there isn't already a mousewatcher in the data graph, so we'll make
// one and re-parent everything to it.
if (gui_cat->is_debug())
gui_cat->debug() << "no MouseWatcher found, making one" << endl;
watcher = new MouseWatcher("GUI watcher");
DataRelation* tmp = new DataRelation(mak, watcher);
for (int j=0; j<mak->get_num_children(dgt); ++j) {
NodeRelation* rel = mak->get_child(dgt, j);
if (rel != tmp)
// it's not the node we just created, so reparent it to ours
rel->change_parent(watcher);
}
} else if (gui_cat->is_debug())
gui_cat->debug() << "found a MouseWatcher, don't have to make one"
<< endl;
// now setup event triggers for the watcher
if (has_watcher)
gui_cat->warning() << "overwriting existing button down pattern '"
<< watcher->get_button_down_pattern()
<< "' with 'gui-%r-%b'" << endl;
watcher->set_button_down_pattern("gui-%r-%b");
if (has_watcher)
gui_cat->warning() << "overwriting existing button up pattern '"
<< watcher->get_button_up_pattern()
<< "' with 'gui-%r-%b-up'" << endl;
watcher->set_button_up_pattern("gui-%r-%b");
if (has_watcher)
gui_cat->warning() << "overwriting existing enter pattern '"
<< watcher->get_enter_pattern()
<< "' with 'gui-in-%r'" << endl;
watcher->set_enter_pattern("gui-in-%r");
if (has_watcher)
gui_cat->warning() << "overwriting existing exit pattern '"
<< watcher->get_leave_pattern()
<< "' with 'gui-out-%r'" << endl;
watcher->set_leave_pattern("gui-out-%r");
// next, create a 2d layer for the GUI stuff to live in.
Node* root2d_top = new NamedNode("GUI_top");
Node* root2d = new NamedNode("GUI");
NodeRelation* root2d_arc = new RenderRelation(root2d_top, root2d);
root2d_arc->set_transition(new DepthTestTransition(DepthTestProperty::M_none), 1);
root2d_arc->set_transition(new DepthWriteTransition(DepthWriteTransition::off()), 1);
root2d_arc->set_transition(new LightTransition(LightTransition::all_off()), 1);
root2d_arc->set_transition(new MaterialTransition(MaterialTransition::off()), 1);
root2d_arc->set_transition(new CullFaceTransition(CullFaceProperty::M_cull_none), 1);
PT(Camera) cam = new Camera("GUI_cam");
new RenderRelation(root2d, cam);
cam->set_scene(root2d_top);
Frustumf frust2d;
frust2d.make_ortho_2D();
cam->set_projection(OrthoProjection(frust2d));
GraphicsChannel *chan = w->get_channel(0); // root/full-window channel
nassertr(chan != (GraphicsChannel*)0L, NULL);
GraphicsLayer *layer = chan->make_layer();
nassertr(layer != (GraphicsLayer*)0L, NULL);
DisplayRegion *dr = layer->make_display_region();
nassertr(dr != (DisplayRegion*)0L, NULL);
dr->set_camera(cam);
if (gui_cat->is_debug())
gui_cat->debug() << "2D layer created" << endl;
// now make the manager for this window
ret = new GuiManager(watcher, root2d);
if (gui_cat->is_debug())
gui_cat->debug() << "new manager allocated (0x" << (void*)ret << ")"
<< endl;
(*_map)[w] = ret;
}
return ret;
}
void GuiManager::add_region(GuiRegion* region) {
RegionSet::const_iterator ri;
ri = _regions.find(region);
if (ri == _regions.end()) {
_watcher->add_region(region->get_region());
_regions.insert(region);
} else
gui_cat->warning() << "tried adding region ('" << *region
<< "') more then once" << endl;
}
void GuiManager::add_label(GuiLabel* label) {
LabelSet::const_iterator li;
li = _labels.find(label);
if (li == _labels.end()) {
// add it to the scenegraph
label->set_arc(new RenderRelation(_root, label->get_geometry()));
_labels.insert(label);
} else
gui_cat->warning() << "tried adding label (0x" << (void*)label
<< ") more then once" << endl;
}
void GuiManager::remove_region(GuiRegion* region) {
RegionSet::iterator ri;
ri = _regions.find(region);
if (ri == _regions.end())
gui_cat->warning() << "tried removing region ('" << *region
<< "') that isn't there" << endl;
else {
_watcher->remove_region(region->get_region());
_regions.erase(ri);
}
}
void GuiManager::remove_label(GuiLabel* label) {
LabelSet::iterator li;
li = _labels.find(label);
if (li == _labels.end())
gui_cat->warning() << "label (0x" << (void*)label
<< ") is not there to be removed" << endl;
else {
// remove it to the scenegraph
remove_arc(label->get_arc());
label->set_arc((RenderRelation*)0L);
_labels.erase(li);
}
}
<|endoftext|>
|
<commit_before>//
//! @file paramter_impl.cpp
//! @brief paramater impliment file.
// coipyright (C) NTTComware corporation. 2008 - 2009
// mail: n.nakai at sdy.co.jp
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <vector>
#include <fstream>
#include "parameter_impl.h"
#include "logger.h"
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include <boost/function.hpp>
#include <boost/format.hpp>
#ifndef PARAMETER_FILE
#define PARAMETER_FILE "/etc/l7vs/l7vs.cf"
#endif //PARAMETER_FILE
#if !defined(LOGGER_PROCESS_VSD) && !defined(LOGGER_PROCESS_ADM) && !defined(LOGGER_PROCESS_SNM)
#define LOGGER_PROCESS_VSD
#endif
#ifdef LOGGER_PROCESS_SNM
l7vs::LOG_CATEGORY_TAG logcat = l7vs::LOG_CAT_SSLPROXY_PARAMETER;
#elif LOGGER_PROCESS_SNM
l7vs::LOG_CATEGORY_TAG logcat = l7vs::LOG_CAT_SNMPAGENT_PARAMETER;
#elif LOGGER_PROCESS_ADM
l7vs::LOG_CATEGORY_TAG logcat = l7vs::LOG_CAT_L7VSADM_PARAMETER;
#else
l7vs::LOG_CATEGORY_TAG logcat = l7vs::LOG_CAT_L7VSD_PARAMETER;
#endif
static bool create_map_flag = false;
//
//! Initialize ParameterImpl class
//! @return true success
//! @return false failer
bool l7vs::ParameterImpl::init(){
boost::mutex::scoped_lock lock( create_mutex );
if( create_map_flag ) return true;
tag_section_table_map.clear();
stringMap.clear();
intMap.clear();
tag_section_table_map[PARAM_COMP_L7VSD] = "l7vsd";
tag_section_table_map[PARAM_COMP_COMMAND] = "command";
tag_section_table_map[PARAM_COMP_SESSION] = "session";
tag_section_table_map[PARAM_COMP_VIRTUALSERVICE]= "virtualservice";
tag_section_table_map[PARAM_COMP_MODULE] = "module";
tag_section_table_map[PARAM_COMP_REPLICATION] = "replication";
tag_section_table_map[PARAM_COMP_LOGGER] = "logger";
tag_section_table_map[PARAM_COMP_L7VSADM] = "l7vsadm";
tag_section_table_map[PARAM_COMP_SNMPAGENT] = "snmpagent";
tag_section_table_map[PARAM_COMP_SSLPROXY] = "sslproxy";
create_map_flag = read_file( PARAM_COMP_ALL );
return create_map_flag;
}
//! read config file
//! @param[in] COMPONENT TAG
//! @return true read success
//! @return false read false
bool l7vs::ParameterImpl::read_file( const l7vs::PARAMETER_COMPONENT_TAG comp ){
typedef std::vector< std::string > split_vector_type;
typedef std::pair< std::string, int > int_pair_type;
typedef std::pair< std::string, std::string > string_pair_type;
boost::mutex::scoped_lock lock( param_mutex );
std::string line;
std::ifstream ifs( PARAMETER_FILE );
string_map_type string_map;
int_map_type int_map;
if( !ifs ) return false; // don't open config files.
std::string section_string;
while( std::getline( ifs, line ) ){
boost::algorithm::trim( line ); // triming
if( line.size() == 0 ) continue; // zero line skip
if( line[0] == '#' ) continue; // comment line skip
std::string::size_type pos = line.find( '#' ); // comment is clear
if( pos != std::string::npos ) line = line.substr( 0, pos );
split_vector_type split_vec;
boost::algorithm::split( split_vec, line, boost::algorithm::is_any_of( "=" ) );
if( split_vec.size() == 1 ){ // section
if( split_vec[0].at(0) == '[' && split_vec[0].at( split_vec[0].size()-1 ) == ']' )
section_string = split_vec[0].substr( 1, split_vec[0].size() - 2 );
else{
boost::format formatter( "section tag false : %1%" );
formatter % split_vec[0];
Logger::putLogFatal( logcat, 0, formatter.str(), __FILE__, __LINE__ );
return false;
}
}
else if( split_vec.size() == 2 ){ // split_vec[0] = key, split_vec[1]=value
if( section_string.size() == 0 ){
boost::format formatter("don't match first section. key = %1%, value = %2%" );
formatter % split_vec[0] % split_vec[1];
Logger::putLogFatal( logcat, 0, formatter.str(), __FILE__, __LINE__ );
return false;
}
boost::algorithm::trim( split_vec[0] ); //trim keys
boost::algorithm::trim( split_vec[1] ); //trim values
std::string key = section_string;//create section.key
key += ".";
key += split_vec[0];
if( split_vec[1].at(0) == '\"' && split_vec[1].at( split_vec[1].size()-1 ) == '\"' ){ //string value
std::string strvalue = split_vec[1].substr( 1, split_vec[1].size()-2 ); //erase double cautation
std::pair< string_map_type::iterator, bool > ret =
string_map.insert( string_pair_type( key, strvalue ) ); //tmp map insert
if( !ret.second ){ //insert error
boost::format formatter( "section.key is duplicate. section.key = %1%, value = %2%" );
formatter % key % strvalue;
Logger::putLogError( logcat, 0, formatter.str(), __FILE__, __LINE__ );
}
}
else{ // int value
try{
int intvalue = boost::lexical_cast<int>( split_vec[1] );
std::pair< int_map_type::iterator, bool > ret =
int_map.insert( int_pair_type( key, intvalue ) ); // tmp map insert
if( !ret.second ){
boost::format formatter( "section.key is duplicate. section.key = %1%, value = %2%" );
formatter % key % intvalue;
Logger::putLogError( logcat, 0, formatter.str(), __FILE__, __LINE__ );
}
}
catch( boost::bad_lexical_cast& cast ){
boost::format formatter( "value is not numeric : %1%" );
formatter % split_vec[1];
Logger::putLogFatal( logcat, 0, formatter.str() , __FILE__, __LINE__ );
}
}
}
else{
boost::format formatter( "line is not support line = %1%" );
formatter % line;
Logger::putLogError( logcat, 0, formatter.str(), __FILE__, __LINE__ );
}
}
//convert temporaly map to global map.
if( comp == PARAM_COMP_ALL ){
intMap.clear();
BOOST_FOREACH( int_pair_type p, int_map ){ // all temp int map copy
intMap.insert( p );
}
stringMap.clear();
BOOST_FOREACH( string_pair_type p, string_map ){ //all temp string map copy
stringMap.insert( p );
}
}
else if( comp == PARAM_COMP_NOCAT ){ // comp error!
Logger::putLogError( logcat, 0, "parameter_component_none is not suport", __FILE__, __LINE__ );
}
else{
std::map< PARAMETER_COMPONENT_TAG, std::string >::iterator section_itr = tag_section_table_map.find( comp );
std::string section = section_itr->second;
for( int_map_type::iterator itr = intMap.begin();
itr != intMap.end();
++itr ){
split_vector_type split_vec;
boost::algorithm::split( split_vec, itr->first, boost::algorithm::is_any_of( "." ) );
if( split_vec[0] == section ){
intMap.erase( itr );
itr = intMap.begin();
}
}
BOOST_FOREACH( int_pair_type p, int_map ){
split_vector_type split_vec;
boost::algorithm::split( split_vec, p.first, boost::algorithm::is_any_of( "." ) );
if( split_vec[0] == section ){
std::pair< int_map_type::iterator, bool > ret = intMap.insert( p );
if( !ret.second ){
boost::format formatter( "not insert key = %1%, value = %2% " );
formatter % p.first % p.second;
Logger::putLogError( logcat, 0, formatter.str(), __FILE__, __LINE__ );
}
}
}
for( string_map_type::iterator itr = stringMap.begin();
itr != stringMap.end();
++itr ){
split_vector_type split_vec;
boost::algorithm::split( split_vec, itr->first, boost::algorithm::is_any_of( "." ) );
if( split_vec[0] == section ){
stringMap.erase( itr );
itr = stringMap.begin();
}
}
BOOST_FOREACH( string_pair_type p, string_map ){
split_vector_type split_vec;
boost::algorithm::split( split_vec, p.first, boost::algorithm::is_any_of( "." ) );
if( split_vec[0] == section ){
std::pair< string_map_type::iterator, bool > ret = stringMap.insert( p );
if( !ret.second ){
boost::format formatter( "not insert key = %1%, value = %2% " );
formatter % p.first % p.second;
Logger::putLogError( logcat, 0, formatter.str(), __FILE__, __LINE__ );
}
}
}
}
return true;
}
//! get a integer parameter
//! @param[in] PARAMETER_COMPONENT_TAG
//! @param[in] const std::string
//! @param[out] error code
//! @return integer value
int l7vs::ParameterImpl::get_int( const l7vs::PARAMETER_COMPONENT_TAG comp,
const std::string& key,
l7vs::error_code& err ){
boost::mutex::scoped_lock lock( param_mutex );
std::map< PARAMETER_COMPONENT_TAG, std::string >::iterator section_table_iterator = tag_section_table_map.find( comp );
int_map_type::iterator intmap_iterator = intMap.find( section_table_iterator->second + "." + key );
if( intmap_iterator != intMap.end() )
return intmap_iterator->second;
else
err.setter( true, "don't find key" );
return 0;
}
//! get a string parameter
//! @param[in] PARAMETER_COMPONENT_TAG
//! @param[in] const std::string
//! @param[out] error code
//! @return string value
std::string l7vs::ParameterImpl::get_string( const l7vs::PARAMETER_COMPONENT_TAG comp,
const std::string& key,
l7vs::error_code& err ){
boost::mutex::scoped_lock lock( param_mutex );
std::map< PARAMETER_COMPONENT_TAG, std::string >::iterator section_table_iterator = tag_section_table_map.find( comp );
string_map_type::iterator strmap_iterator = stringMap.find( section_table_iterator->second + "." + key );
if( strmap_iterator != stringMap.end() )
return strmap_iterator->second;
else
err.setter( true, "don't find key" );
return std::string("");
}
<commit_msg>parameterでconfigファイルがなかった場合にエラーログを出すように修正<commit_after>//
//! @file paramter_impl.cpp
//! @brief paramater impliment file.
// coipyright (C) NTTComware corporation. 2008 - 2009
// mail: n.nakai at sdy.co.jp
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <vector>
#include <fstream>
#include "parameter_impl.h"
#include "logger.h"
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include <boost/function.hpp>
#include <boost/format.hpp>
#ifndef PARAMETER_FILE
#define PARAMETER_FILE "/etc/l7vs/l7vs.cf"
#endif //PARAMETER_FILE
#if !defined(LOGGER_PROCESS_VSD) && !defined(LOGGER_PROCESS_ADM) && !defined(LOGGER_PROCESS_SNM)
#define LOGGER_PROCESS_VSD
#endif
#ifdef LOGGER_PROCESS_SNM
l7vs::LOG_CATEGORY_TAG logcat = l7vs::LOG_CAT_SSLPROXY_PARAMETER;
#elif LOGGER_PROCESS_SNM
l7vs::LOG_CATEGORY_TAG logcat = l7vs::LOG_CAT_SNMPAGENT_PARAMETER;
#elif LOGGER_PROCESS_ADM
l7vs::LOG_CATEGORY_TAG logcat = l7vs::LOG_CAT_L7VSADM_PARAMETER;
#else
l7vs::LOG_CATEGORY_TAG logcat = l7vs::LOG_CAT_L7VSD_PARAMETER;
#endif
static bool create_map_flag = false;
//
//! Initialize ParameterImpl class
//! @return true success
//! @return false failer
bool l7vs::ParameterImpl::init(){
boost::mutex::scoped_lock lock( create_mutex );
if( create_map_flag ) return true;
tag_section_table_map.clear();
stringMap.clear();
intMap.clear();
tag_section_table_map[PARAM_COMP_L7VSD] = "l7vsd";
tag_section_table_map[PARAM_COMP_COMMAND] = "command";
tag_section_table_map[PARAM_COMP_SESSION] = "session";
tag_section_table_map[PARAM_COMP_VIRTUALSERVICE]= "virtualservice";
tag_section_table_map[PARAM_COMP_MODULE] = "module";
tag_section_table_map[PARAM_COMP_REPLICATION] = "replication";
tag_section_table_map[PARAM_COMP_LOGGER] = "logger";
tag_section_table_map[PARAM_COMP_L7VSADM] = "l7vsadm";
tag_section_table_map[PARAM_COMP_SNMPAGENT] = "snmpagent";
tag_section_table_map[PARAM_COMP_SSLPROXY] = "sslproxy";
create_map_flag = read_file( PARAM_COMP_ALL );
return create_map_flag;
}
//! read config file
//! @param[in] COMPONENT TAG
//! @return true read success
//! @return false read false
bool l7vs::ParameterImpl::read_file( const l7vs::PARAMETER_COMPONENT_TAG comp ){
typedef std::vector< std::string > split_vector_type;
typedef std::pair< std::string, int > int_pair_type;
typedef std::pair< std::string, std::string > string_pair_type;
boost::mutex::scoped_lock lock( param_mutex );
std::string line;
std::ifstream ifs( PARAMETER_FILE );
string_map_type string_map;
int_map_type int_map;
if( !ifs ){
Logger::putLogFatal( logcat, 0, "CONFIG FILE NOT OPEN : " PARAMETER_FILE , __FILE__, __LINE__ );
return false; // don't open config files.
}
std::string section_string;
while( std::getline( ifs, line ) ){
boost::algorithm::trim( line ); // triming
if( line.size() == 0 ) continue; // zero line skip
if( line[0] == '#' ) continue; // comment line skip
std::string::size_type pos = line.find( '#' ); // comment is clear
if( pos != std::string::npos ) line = line.substr( 0, pos );
split_vector_type split_vec;
boost::algorithm::split( split_vec, line, boost::algorithm::is_any_of( "=" ) );
if( split_vec.size() == 1 ){ // section
if( split_vec[0].at(0) == '[' && split_vec[0].at( split_vec[0].size()-1 ) == ']' )
section_string = split_vec[0].substr( 1, split_vec[0].size() - 2 );
else{
boost::format formatter( "section tag false : %1%" );
formatter % split_vec[0];
Logger::putLogFatal( logcat, 0, formatter.str(), __FILE__, __LINE__ );
return false;
}
}
else if( split_vec.size() == 2 ){ // split_vec[0] = key, split_vec[1]=value
if( section_string.size() == 0 ){
boost::format formatter("don't match first section. key = %1%, value = %2%" );
formatter % split_vec[0] % split_vec[1];
Logger::putLogFatal( logcat, 0, formatter.str(), __FILE__, __LINE__ );
return false;
}
boost::algorithm::trim( split_vec[0] ); //trim keys
boost::algorithm::trim( split_vec[1] ); //trim values
std::string key = section_string;//create section.key
key += ".";
key += split_vec[0];
if( split_vec[1].at(0) == '\"' && split_vec[1].at( split_vec[1].size()-1 ) == '\"' ){ //string value
std::string strvalue = split_vec[1].substr( 1, split_vec[1].size()-2 ); //erase double cautation
std::pair< string_map_type::iterator, bool > ret =
string_map.insert( string_pair_type( key, strvalue ) ); //tmp map insert
if( !ret.second ){ //insert error
boost::format formatter( "section.key is duplicate. section.key = %1%, value = %2%" );
formatter % key % strvalue;
Logger::putLogError( logcat, 0, formatter.str(), __FILE__, __LINE__ );
}
}
else{ // int value
try{
int intvalue = boost::lexical_cast<int>( split_vec[1] );
std::pair< int_map_type::iterator, bool > ret =
int_map.insert( int_pair_type( key, intvalue ) ); // tmp map insert
if( !ret.second ){
boost::format formatter( "section.key is duplicate. section.key = %1%, value = %2%" );
formatter % key % intvalue;
Logger::putLogError( logcat, 0, formatter.str(), __FILE__, __LINE__ );
}
}
catch( boost::bad_lexical_cast& cast ){
boost::format formatter( "value is not numeric : %1%" );
formatter % split_vec[1];
Logger::putLogFatal( logcat, 0, formatter.str() , __FILE__, __LINE__ );
}
}
}
else{
boost::format formatter( "line is not support line = %1%" );
formatter % line;
Logger::putLogError( logcat, 0, formatter.str(), __FILE__, __LINE__ );
}
}
//convert temporaly map to global map.
if( comp == PARAM_COMP_ALL ){
intMap.clear();
BOOST_FOREACH( int_pair_type p, int_map ){ // all temp int map copy
intMap.insert( p );
}
stringMap.clear();
BOOST_FOREACH( string_pair_type p, string_map ){ //all temp string map copy
stringMap.insert( p );
}
}
else if( comp == PARAM_COMP_NOCAT ){ // comp error!
Logger::putLogError( logcat, 0, "parameter_component_none is not suport", __FILE__, __LINE__ );
}
else{
std::map< PARAMETER_COMPONENT_TAG, std::string >::iterator section_itr = tag_section_table_map.find( comp );
std::string section = section_itr->second;
for( int_map_type::iterator itr = intMap.begin();
itr != intMap.end();
++itr ){
split_vector_type split_vec;
boost::algorithm::split( split_vec, itr->first, boost::algorithm::is_any_of( "." ) );
if( split_vec[0] == section ){
intMap.erase( itr );
itr = intMap.begin();
}
}
BOOST_FOREACH( int_pair_type p, int_map ){
split_vector_type split_vec;
boost::algorithm::split( split_vec, p.first, boost::algorithm::is_any_of( "." ) );
if( split_vec[0] == section ){
std::pair< int_map_type::iterator, bool > ret = intMap.insert( p );
if( !ret.second ){
boost::format formatter( "not insert key = %1%, value = %2% " );
formatter % p.first % p.second;
Logger::putLogError( logcat, 0, formatter.str(), __FILE__, __LINE__ );
}
}
}
for( string_map_type::iterator itr = stringMap.begin();
itr != stringMap.end();
++itr ){
split_vector_type split_vec;
boost::algorithm::split( split_vec, itr->first, boost::algorithm::is_any_of( "." ) );
if( split_vec[0] == section ){
stringMap.erase( itr );
itr = stringMap.begin();
}
}
BOOST_FOREACH( string_pair_type p, string_map ){
split_vector_type split_vec;
boost::algorithm::split( split_vec, p.first, boost::algorithm::is_any_of( "." ) );
if( split_vec[0] == section ){
std::pair< string_map_type::iterator, bool > ret = stringMap.insert( p );
if( !ret.second ){
boost::format formatter( "not insert key = %1%, value = %2% " );
formatter % p.first % p.second;
Logger::putLogError( logcat, 0, formatter.str(), __FILE__, __LINE__ );
}
}
}
}
return true;
}
//! get a integer parameter
//! @param[in] PARAMETER_COMPONENT_TAG
//! @param[in] const std::string
//! @param[out] error code
//! @return integer value
int l7vs::ParameterImpl::get_int( const l7vs::PARAMETER_COMPONENT_TAG comp,
const std::string& key,
l7vs::error_code& err ){
boost::mutex::scoped_lock lock( param_mutex );
std::map< PARAMETER_COMPONENT_TAG, std::string >::iterator section_table_iterator = tag_section_table_map.find( comp );
int_map_type::iterator intmap_iterator = intMap.find( section_table_iterator->second + "." + key );
if( intmap_iterator != intMap.end() )
return intmap_iterator->second;
else
err.setter( true, "don't find key" );
return 0;
}
//! get a string parameter
//! @param[in] PARAMETER_COMPONENT_TAG
//! @param[in] const std::string
//! @param[out] error code
//! @return string value
std::string l7vs::ParameterImpl::get_string( const l7vs::PARAMETER_COMPONENT_TAG comp,
const std::string& key,
l7vs::error_code& err ){
boost::mutex::scoped_lock lock( param_mutex );
std::map< PARAMETER_COMPONENT_TAG, std::string >::iterator section_table_iterator = tag_section_table_map.find( comp );
string_map_type::iterator strmap_iterator = stringMap.find( section_table_iterator->second + "." + key );
if( strmap_iterator != stringMap.end() )
return strmap_iterator->second;
else
err.setter( true, "don't find key" );
return std::string("");
}
<|endoftext|>
|
<commit_before>#ifndef ALEPH_PERSISTENCE_DIAGRAMS_NORMS_HH__
#define ALEPH_PERSISTENCE_DIAGRAMS_NORMS_HH__
#include "persistenceDiagrams/PersistenceDiagram.hh"
#include <algorithm>
#include <vector>
#include <stdexcept>
#include <cmath>
namespace aleph
{
template <class DataType> double totalPersistence( const PersistenceDiagram<DataType>& D,
double k = 2.0,
bool weighted = false )
{
double result = 0.0;
if( !weighted )
{
for( auto&& point : D )
result = result + std::pow( static_cast<double>( point.persistence() ), k );
}
else
{
using Point = typename PersistenceDiagram<DataType>::Point;
std::vector<Point> points;
points.reserve( D.size() );
for( auto&& point : D )
points.push_back( point );
std::sort( points.begin(), points.end(), [] ( const Point& p, const Point& q )
{
if( p.x() == q.x() )
return p.y() < q.y();
else
return p.x() < q.x();
} );
std::vector<Point> uniquePoints;
std::unique_copy( points.begin(), points.end(),
std::back_inserter( uniquePoints ) );
std::vector<unsigned> counts;
counts.reserve( uniquePoints.size() );
for( auto&& point : uniquePoints )
{
auto count = static_cast<unsigned>( std::count( points.begin(), points.end(), point ) );
counts.push_back( count );
}
auto itPoint = uniquePoints.begin();
auto itCount = counts.begin();
for( ; itPoint != uniquePoints.end() && itCount != counts.end(); ++itPoint, ++itCount )
{
double weight = *itCount / static_cast<double>( points.size() );
result += weight * std::pow( static_cast<double>( itPoint->persistence() ), k );
}
}
return result;
}
template <class DataType> double pNorm( const PersistenceDiagram<DataType>& D,
double p = 2.0 )
{
if( p == 0.0 )
throw std::runtime_error( "Power must be non-zero" );
return std::pow( totalPersistence( D, p ), 1.0 / p );
}
template <class DataType> DataType infinityNorm( const PersistenceDiagram<DataType>& D )
{
if( D.empty() )
return DataType( 0 );
std::vector<DataType> persistenceValues;
for( auto&& point : D )
persistenceValues.push_back( point.persistence() );
return *std::max_element( persistenceValues.begin(), persistenceValues.end() );
}
} // namespace aleph
#endif
<commit_msg>Supporting weight-based $p$-norm calculation<commit_after>#ifndef ALEPH_PERSISTENCE_DIAGRAMS_NORMS_HH__
#define ALEPH_PERSISTENCE_DIAGRAMS_NORMS_HH__
#include "persistenceDiagrams/PersistenceDiagram.hh"
#include <algorithm>
#include <vector>
#include <stdexcept>
#include <cmath>
namespace aleph
{
template <class DataType> double totalPersistence( const PersistenceDiagram<DataType>& D,
double k = 2.0,
bool weighted = false )
{
double result = 0.0;
if( !weighted )
{
for( auto&& point : D )
result = result + std::pow( static_cast<double>( point.persistence() ), k );
}
else
{
using Point = typename PersistenceDiagram<DataType>::Point;
std::vector<Point> points;
points.reserve( D.size() );
for( auto&& point : D )
points.push_back( point );
std::sort( points.begin(), points.end(), [] ( const Point& p, const Point& q )
{
if( p.x() == q.x() )
return p.y() < q.y();
else
return p.x() < q.x();
} );
std::vector<Point> uniquePoints;
std::unique_copy( points.begin(), points.end(),
std::back_inserter( uniquePoints ) );
std::vector<unsigned> counts;
counts.reserve( uniquePoints.size() );
for( auto&& point : uniquePoints )
{
auto count = static_cast<unsigned>( std::count( points.begin(), points.end(), point ) );
counts.push_back( count );
}
auto itPoint = uniquePoints.begin();
auto itCount = counts.begin();
for( ; itPoint != uniquePoints.end() && itCount != counts.end(); ++itPoint, ++itCount )
{
double weight = *itCount / static_cast<double>( points.size() );
result += weight * std::pow( static_cast<double>( itPoint->persistence() ), k );
}
}
return result;
}
template <class DataType> double pNorm( const PersistenceDiagram<DataType>& D,
double p = 2.0,
bool weighted = false )
{
if( p == 0.0 )
throw std::runtime_error( "Power must be non-zero" );
return std::pow( totalPersistence( D, p, weighted ), 1.0 / p );
}
template <class DataType> DataType infinityNorm( const PersistenceDiagram<DataType>& D )
{
if( D.empty() )
return DataType( 0 );
std::vector<DataType> persistenceValues;
for( auto&& point : D )
persistenceValues.push_back( point.persistence() );
return *std::max_element( persistenceValues.begin(), persistenceValues.end() );
}
} // namespace aleph
#endif
<|endoftext|>
|
<commit_before>/// @file
/// @author Boris Mikic
/// @version 3.1
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php
#if defined(_WINRT) && !defined(_OPENKODE)
#include <gtypes/Vector2.h>
#include <hltypes/hlog.h>
#include <hltypes/hltypesUtil.h>
#include <hltypes/hmap.h>
#include <hltypes/hplatform.h>
#include <hltypes/hstring.h>
#include "april.h"
#include "Platform.h"
#include "RenderSystem.h"
#include "Window.h"
#include "WinRT.h"
using namespace Windows::Foundation::Collections;
using namespace Windows::Graphics::Display;
using namespace Windows::UI::Popups;
namespace april
{
SystemInfo getSystemInfo()
{
static SystemInfo info;
if (info.locale == "")
{
// number of CPU cores
SYSTEM_INFO w32info;
GetNativeSystemInfo(&w32info);
info.cpuCores = w32info.dwNumberOfProcessors;
// TODO - though, WinRT does not seem to be able to retrieve this information
// RAM size
info.ram = 1024;
// display resolution
#ifdef _WINRT_WINDOW
int width = (int)CoreWindow::GetForCurrentThread()->Bounds.Width;
int height = (int)CoreWindow::GetForCurrentThread()->Bounds.Height;
info.displayResolution.set((float)hmax(width, height), (float)hmin(width, height));
#endif
// display DPI
info.displayDpi = (int)DisplayProperties::LogicalDpi;
// other
info.locale = "";
#ifndef _WINP8
IIterator<Platform::String^>^ it = Windows::Globalization::ApplicationLanguages::Languages->First();
if (it->HasCurrent)
{
info.locale = _HL_PSTR_TO_HSTR(it->Current).lower();
}
#else
unsigned long count = 0;
unsigned long length = LOCALE_NAME_MAX_LENGTH;
wchar_t locale[LOCALE_NAME_MAX_LENGTH] = {0};
if (GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, &count, locale, &length) && count > 0 && length > 0)
{
info.locale = hstr::from_unicode(locale).lower();
}
#endif
if (info.locale == "")
{
info.locale = "en"; // default is "en"
}
else if (info.locale == "pt_pt" || info.locale == "pt-pt")
{
info.locale = "pt-PT";
}
else if (info.locale.utf8_size() > 2 && info.locale != "pt-PT")
{
info.locale = info.locale.utf8_substr(0, 2);
}
}
if (info.maxTextureSize == 0 && april::rendersys != NULL)
{
info.maxTextureSize = april::rendersys->getMaxTextureSize();
}
return info;
}
DeviceType getDeviceType()
{
#ifndef _WINP8
return DEVICE_WINDOWS_8;
#else
return DEVICE_WINDOWS_PHONE_8;
#endif
}
hstr getPackageName()
{
return _HL_PSTR_TO_HSTR(Windows::ApplicationModel::Package::Current->Id->FamilyName);
}
hstr getUserDataPath()
{
hlog::warn(april::logTag, "Cannot use getUserDataPath() on this platform.");
return ".";
}
static void(*currentCallback)(MessageBoxButton) = NULL;
void _messageBoxResult(int button)
{
switch (button)
{
case IDOK:
if (currentCallback != NULL)
{
(*currentCallback)(AMSGBTN_OK);
}
break;
case IDYES:
if (currentCallback != NULL)
{
(*currentCallback)(AMSGBTN_YES);
}
break;
case IDNO:
if (currentCallback != NULL)
{
(*currentCallback)(AMSGBTN_NO);
}
break;
case IDCANCEL:
if (currentCallback != NULL)
{
(*currentCallback)(AMSGBTN_CANCEL);
}
break;
}
}
void messageBox_platform(chstr title, chstr text, MessageBoxButton buttonMask, MessageBoxStyle style,
hmap<MessageBoxButton, hstr> customButtonTitles, void(*callback)(MessageBoxButton))
{
#ifndef _WINP8
currentCallback = callback;
_HL_HSTR_TO_PSTR_DEF(text);
_HL_HSTR_TO_PSTR_DEF(title);
MessageDialog^ dialog = ref new MessageDialog(ptext, ptitle);
UICommandInvokedHandler^ commandHandler = ref new UICommandInvokedHandler(
[](IUICommand^ command)
{
_messageBoxResult((int)command->Id);
});
hstr ok;
hstr yes;
hstr no;
hstr cancel;
_makeButtonLabels(&ok, &yes, &no, &cancel, buttonMask, customButtonTitles);
_HL_HSTR_TO_PSTR_DEF(ok);
_HL_HSTR_TO_PSTR_DEF(yes);
_HL_HSTR_TO_PSTR_DEF(no);
_HL_HSTR_TO_PSTR_DEF(cancel);
if ((buttonMask & AMSGBTN_OK) && (buttonMask & AMSGBTN_CANCEL))
{
dialog->Commands->Append(ref new UICommand(pok, commandHandler, IDOK));
dialog->Commands->Append(ref new UICommand(pcancel, commandHandler, IDCANCEL));
dialog->DefaultCommandIndex = 0;
dialog->CancelCommandIndex = 1;
}
else if ((buttonMask & AMSGBTN_YES) && (buttonMask & AMSGBTN_NO) && (buttonMask & AMSGBTN_CANCEL))
{
dialog->Commands->Append(ref new UICommand(pyes, commandHandler, IDYES));
dialog->Commands->Append(ref new UICommand(pno, commandHandler, IDNO));
dialog->Commands->Append(ref new UICommand(pcancel, commandHandler, IDCANCEL));
dialog->DefaultCommandIndex = 0;
dialog->CancelCommandIndex = 2;
}
else if (buttonMask & AMSGBTN_OK)
{
dialog->Commands->Append(ref new UICommand(pok, commandHandler, IDOK));
dialog->DefaultCommandIndex = 0;
dialog->CancelCommandIndex = 0;
}
else if ((buttonMask & AMSGBTN_YES) && (buttonMask & AMSGBTN_NO))
{
dialog->Commands->Append(ref new UICommand(pyes, commandHandler, IDYES));
dialog->Commands->Append(ref new UICommand(pno, commandHandler, IDNO));
dialog->DefaultCommandIndex = 0;
dialog->CancelCommandIndex = 1;
}
dialog->ShowAsync();
#else
// TODOp8 - if Microsoft ever decides to allow usage of basic features on Windows Phone 8, this has to be implemented
hlog::error(april::logTag, "Windows Phone 8 does not support messageBox()!)");
#endif
}
}
#endif
<commit_msg>- reduced default RAM indicator on WinP8<commit_after>/// @file
/// @author Boris Mikic
/// @version 3.1
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php
#if defined(_WINRT) && !defined(_OPENKODE)
#include <gtypes/Vector2.h>
#include <hltypes/hlog.h>
#include <hltypes/hltypesUtil.h>
#include <hltypes/hmap.h>
#include <hltypes/hplatform.h>
#include <hltypes/hstring.h>
#include "april.h"
#include "Platform.h"
#include "RenderSystem.h"
#include "Window.h"
#include "WinRT.h"
using namespace Windows::Foundation::Collections;
using namespace Windows::Graphics::Display;
using namespace Windows::UI::Popups;
namespace april
{
SystemInfo getSystemInfo()
{
static SystemInfo info;
if (info.locale == "")
{
// number of CPU cores
SYSTEM_INFO w32info;
GetNativeSystemInfo(&w32info);
info.cpuCores = w32info.dwNumberOfProcessors;
// TODO - though, WinRT does not seem to be able to retrieve this information
// RAM size
#ifndef _WINP8
info.ram = 1024;
#else
info.ram = 512;
#endif
// display resolution
#ifdef _WINRT_WINDOW
int width = (int)CoreWindow::GetForCurrentThread()->Bounds.Width;
int height = (int)CoreWindow::GetForCurrentThread()->Bounds.Height;
info.displayResolution.set((float)hmax(width, height), (float)hmin(width, height));
#endif
// display DPI
info.displayDpi = (int)DisplayProperties::LogicalDpi;
// other
info.locale = "";
#ifndef _WINP8
IIterator<Platform::String^>^ it = Windows::Globalization::ApplicationLanguages::Languages->First();
if (it->HasCurrent)
{
info.locale = _HL_PSTR_TO_HSTR(it->Current).lower();
}
#else
unsigned long count = 0;
unsigned long length = LOCALE_NAME_MAX_LENGTH;
wchar_t locale[LOCALE_NAME_MAX_LENGTH] = {0};
if (GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, &count, locale, &length) && count > 0 && length > 0)
{
info.locale = hstr::from_unicode(locale).lower();
}
#endif
if (info.locale == "")
{
info.locale = "en"; // default is "en"
}
else if (info.locale == "pt_pt" || info.locale == "pt-pt")
{
info.locale = "pt-PT";
}
else if (info.locale.utf8_size() > 2 && info.locale != "pt-PT")
{
info.locale = info.locale.utf8_substr(0, 2);
}
}
if (info.maxTextureSize == 0 && april::rendersys != NULL)
{
info.maxTextureSize = april::rendersys->getMaxTextureSize();
}
return info;
}
DeviceType getDeviceType()
{
#ifndef _WINP8
return DEVICE_WINDOWS_8;
#else
return DEVICE_WINDOWS_PHONE_8;
#endif
}
hstr getPackageName()
{
return _HL_PSTR_TO_HSTR(Windows::ApplicationModel::Package::Current->Id->FamilyName);
}
hstr getUserDataPath()
{
hlog::warn(april::logTag, "Cannot use getUserDataPath() on this platform.");
return ".";
}
static void(*currentCallback)(MessageBoxButton) = NULL;
void _messageBoxResult(int button)
{
switch (button)
{
case IDOK:
if (currentCallback != NULL)
{
(*currentCallback)(AMSGBTN_OK);
}
break;
case IDYES:
if (currentCallback != NULL)
{
(*currentCallback)(AMSGBTN_YES);
}
break;
case IDNO:
if (currentCallback != NULL)
{
(*currentCallback)(AMSGBTN_NO);
}
break;
case IDCANCEL:
if (currentCallback != NULL)
{
(*currentCallback)(AMSGBTN_CANCEL);
}
break;
}
}
void messageBox_platform(chstr title, chstr text, MessageBoxButton buttonMask, MessageBoxStyle style,
hmap<MessageBoxButton, hstr> customButtonTitles, void(*callback)(MessageBoxButton))
{
#ifndef _WINP8
currentCallback = callback;
_HL_HSTR_TO_PSTR_DEF(text);
_HL_HSTR_TO_PSTR_DEF(title);
MessageDialog^ dialog = ref new MessageDialog(ptext, ptitle);
UICommandInvokedHandler^ commandHandler = ref new UICommandInvokedHandler(
[](IUICommand^ command)
{
_messageBoxResult((int)command->Id);
});
hstr ok;
hstr yes;
hstr no;
hstr cancel;
_makeButtonLabels(&ok, &yes, &no, &cancel, buttonMask, customButtonTitles);
_HL_HSTR_TO_PSTR_DEF(ok);
_HL_HSTR_TO_PSTR_DEF(yes);
_HL_HSTR_TO_PSTR_DEF(no);
_HL_HSTR_TO_PSTR_DEF(cancel);
if ((buttonMask & AMSGBTN_OK) && (buttonMask & AMSGBTN_CANCEL))
{
dialog->Commands->Append(ref new UICommand(pok, commandHandler, IDOK));
dialog->Commands->Append(ref new UICommand(pcancel, commandHandler, IDCANCEL));
dialog->DefaultCommandIndex = 0;
dialog->CancelCommandIndex = 1;
}
else if ((buttonMask & AMSGBTN_YES) && (buttonMask & AMSGBTN_NO) && (buttonMask & AMSGBTN_CANCEL))
{
dialog->Commands->Append(ref new UICommand(pyes, commandHandler, IDYES));
dialog->Commands->Append(ref new UICommand(pno, commandHandler, IDNO));
dialog->Commands->Append(ref new UICommand(pcancel, commandHandler, IDCANCEL));
dialog->DefaultCommandIndex = 0;
dialog->CancelCommandIndex = 2;
}
else if (buttonMask & AMSGBTN_OK)
{
dialog->Commands->Append(ref new UICommand(pok, commandHandler, IDOK));
dialog->DefaultCommandIndex = 0;
dialog->CancelCommandIndex = 0;
}
else if ((buttonMask & AMSGBTN_YES) && (buttonMask & AMSGBTN_NO))
{
dialog->Commands->Append(ref new UICommand(pyes, commandHandler, IDYES));
dialog->Commands->Append(ref new UICommand(pno, commandHandler, IDNO));
dialog->DefaultCommandIndex = 0;
dialog->CancelCommandIndex = 1;
}
dialog->ShowAsync();
#else
// TODOp8 - if Microsoft ever decides to allow usage of basic features on Windows Phone 8, this has to be implemented
hlog::error(april::logTag, "Windows Phone 8 does not support messageBox()!)");
#endif
}
}
#endif
<|endoftext|>
|
<commit_before><commit_msg>more clean ups to C API and Ruby binding<commit_after><|endoftext|>
|
<commit_before><commit_msg>Temporarily exclude NonblockingSignalTests - no time to maintain them.<commit_after><|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Declarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsggravity_p.h"
#include <cmath>
QT_BEGIN_NAMESPACE
const qreal CONV = 0.017453292520444443;
/*!
\qmlclass Gravity QSGGravityAffector
\inqmlmodule QtQuick.Particles 2
\inherits Affector
\brief The Gravity element allows you to set a constant accleration in an angle
This element will set the acceleration of all affected particles to a vector of
the specified magnitude in the specified angle.
This element models the gravity of a massive object whose center of
gravity is far away (and thus the gravitational pull is effectively constant
across the scene). To model the gravity of an object near or inside the scene,
use PointAttractor.
*/
/*!
\qmlproperty real QtQuick.Particles2::Gravity::acceleration
Pixels per second that objects will be accelerated by.
*/
/*!
\qmlproperty real QtQuick.Particles2::Gravity::angle
Angle of acceleration.
*/
QSGGravityAffector::QSGGravityAffector(QSGItem *parent) :
QSGParticleAffector(parent), m_acceleration(-10), m_angle(90), m_xAcc(0), m_yAcc(0)
{
connect(this, SIGNAL(accelerationChanged(qreal)),
this, SLOT(recalc()));
connect(this, SIGNAL(angleChanged(qreal)),
this, SLOT(recalc()));
recalc();
}
void QSGGravityAffector::recalc()
{
qreal theta = m_angle * CONV;
m_xAcc = m_acceleration * cos(theta);
m_yAcc = m_acceleration * sin(theta);
}
bool QSGGravityAffector::affectParticle(QSGParticleData *d, qreal dt)
{
Q_UNUSED(dt);
bool changed = false;
if (d->ax != m_xAcc){
d->setInstantaneousAX(m_xAcc);
changed = true;
}
if (d->ay != m_yAcc){
d->setInstantaneousAY(m_yAcc);
changed = true;
}
return changed;
}
QT_END_NAMESPACE
<commit_msg>Documentation Augmentation<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Declarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsggravity_p.h"
#include <cmath>
QT_BEGIN_NAMESPACE
const qreal CONV = 0.017453292520444443;
/*!
\qmlclass Gravity QSGGravityAffector
\inqmlmodule QtQuick.Particles 2
\inherits Affector
\brief The Gravity element allows you to set a constant accleration in an angle
This element will set the acceleration of all affected particles to a vector of
the specified magnitude in the specified angle. If the angle or acceleration is
not varying, it is more efficient to set the specified acceleration on the Emitter.
This element models the gravity of a massive object whose center of
gravity is far away (and thus the gravitational pull is effectively constant
across the scene). To model the gravity of an object near or inside the scene,
use PointAttractor.
*/
/*!
\qmlproperty real QtQuick.Particles2::Gravity::acceleration
Pixels per second that objects will be accelerated by.
*/
/*!
\qmlproperty real QtQuick.Particles2::Gravity::angle
Angle of acceleration.
*/
QSGGravityAffector::QSGGravityAffector(QSGItem *parent) :
QSGParticleAffector(parent), m_acceleration(-10), m_angle(90), m_xAcc(0), m_yAcc(0)
{
connect(this, SIGNAL(accelerationChanged(qreal)),
this, SLOT(recalc()));
connect(this, SIGNAL(angleChanged(qreal)),
this, SLOT(recalc()));
recalc();
}
void QSGGravityAffector::recalc()
{
qreal theta = m_angle * CONV;
m_xAcc = m_acceleration * cos(theta);
m_yAcc = m_acceleration * sin(theta);
}
bool QSGGravityAffector::affectParticle(QSGParticleData *d, qreal dt)
{
Q_UNUSED(dt);
bool changed = false;
if (d->ax != m_xAcc){
d->setInstantaneousAX(m_xAcc);
changed = true;
}
if (d->ay != m_yAcc){
d->setInstantaneousAY(m_yAcc);
changed = true;
}
return changed;
}
QT_END_NAMESPACE
<|endoftext|>
|
<commit_before>// RUN: %clangxx -O0 -g %s -o %t && %run %t 2>&1 | FileCheck %s
// UNSUPPORTED: linux, solaris
#include <sys/cdefs.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
struct stat st;
char name[100];
mode_t type;
if (stat("/dev/null", &st))
exit(1);
type = S_ISCHR(st.st_mode) ? S_IFCHR : S_IFBLK;
if (!devname_r(st.st_rdev, type, name, sizeof(name)))
exit(1);
printf("%s\n", name);
// CHECK: null
return 0;
}
<commit_msg>Fix Posix/devname_r for NetBSD<commit_after>// RUN: %clangxx -O0 -g %s -o %t && %run %t 2>&1 | FileCheck %s
// UNSUPPORTED: linux, solaris
#include <sys/cdefs.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
struct stat st;
char name[100];
mode_t type;
if (stat("/dev/null", &st))
exit(1);
type = S_ISCHR(st.st_mode) ? S_IFCHR : S_IFBLK;
#if defined(__NetBSD__)
if (devname_r(st.st_rdev, type, name, sizeof(name)))
exit(1);
#else
if (!devname_r(st.st_rdev, type, name, sizeof(name)))
exit(1);
#endif
printf("%s\n", name);
// CHECK: null
return 0;
}
<|endoftext|>
|
<commit_before>#include <smartref.h>
#include <type_traits>
#include <vector>
#include <list>
namespace tests {
using smartref::using_;
//! These tests check for absence of the value_type member-type,
//! for using_<int>, which obviously doesn't have this member-type.
namespace test_absence {
template<typename T, typename = typename T::value_type>
constexpr auto has_value_type(int) {return true;}
template<typename T>
constexpr auto has_value_type(...) {return false;}
//! 1. Accessing the value_type member-type should be invalid
//! 2. Instantiating the class *template* should work,
//! and should not result in an ill-formed class.
//! (which is the case if value_type refers to an invalid type)
static_assert(!has_value_type<using_<int>>(0),
"TEST FAILED: value_type should not be defined for using_<int>!");
} // namespace test_absence
namespace test_basics {
//! A basic check to test support for std::vector<int>::value_type
static_assert(
std::is_same<
using_<std::vector<int>>::value_type,
std::vector<int> ::value_type
>::value);
//! Check whether we are not hard-coding support for std::vector
static_assert(
std::is_same<
using_<std::list<int>>::value_type,
std::list<int> ::value_type
>::value);
//! Check whether we are not hard-coding support for std::vector<int>
static_assert(
std::is_same<
using_<std::list<float>>::value_type,
std::list<float> ::value_type
>::value);
} // namespace test_basics
namespace test_proof_of_concept {
//! Test support for value_type
static_assert(
std::is_same<
using_<std::vector<int>>::value_type,
std::vector<int> ::value_type
>::value);
//! Test support for difference_type
static_assert(
std::is_same<
using_<std::vector<int>>::difference_type,
std::vector<int> ::difference_type
>::value);
//! Test support for iterator
static_assert(
std::is_same<
using_<std::vector<int>>::iterator,
std::vector<int> ::iterator
>::value);
} // namespace test_proof_of_concept
namespace test_user_defined_types {
struct UserDefined
{
using type = int;
};
} // namespace test_user_defined_types
} // namespace tests
namespace smartref {
// TODO: This currently needs to be declared in the smartref namespace.
// Figure out a way that it can be declared within an arbitrary namespace.
DECLARE_USING_MEMBER_TYPE(type);
template<typename Derived>
struct ::smartref::MemberFunctions<tests::test_user_defined_types::UserDefined, Derived>
: USING_MEMBER_TYPE(tests::test_user_defined_types::UserDefined, type)
{
};
} // namespace smartref
namespace tests {
namespace test_user_defined_types {
static_assert(
std::is_same<
using_<UserDefined>::type,
UserDefined ::type
>::value);
} // namespace test_user_defined_types
} // namespace tests
<commit_msg>Added a unit-test for a non-intrusive REFLECT on a member-type.<commit_after>#include <smartref.h>
#include <type_traits>
#include <vector>
#include <list>
namespace tests {
using smartref::using_;
//! These tests check for absence of the value_type member-type,
//! for using_<int>, which obviously doesn't have this member-type.
namespace test_absence {
template<typename T, typename = typename T::value_type>
constexpr auto has_value_type(int) {return true;}
template<typename T>
constexpr auto has_value_type(...) {return false;}
//! 1. Accessing the value_type member-type should be invalid
//! 2. Instantiating the class *template* should work,
//! and should not result in an ill-formed class.
//! (which is the case if value_type refers to an invalid type)
static_assert(!has_value_type<using_<int>>(0),
"TEST FAILED: value_type should not be defined for using_<int>!");
} // namespace test_absence
namespace test_basics {
//! A basic check to test support for std::vector<int>::value_type
static_assert(
std::is_same<
using_<std::vector<int>>::value_type,
std::vector<int> ::value_type
>::value);
//! Check whether we are not hard-coding support for std::vector
static_assert(
std::is_same<
using_<std::list<int>>::value_type,
std::list<int> ::value_type
>::value);
//! Check whether we are not hard-coding support for std::vector<int>
static_assert(
std::is_same<
using_<std::list<float>>::value_type,
std::list<float> ::value_type
>::value);
} // namespace test_basics
namespace test_proof_of_concept {
//! Test support for value_type
static_assert(
std::is_same<
using_<std::vector<int>>::value_type,
std::vector<int> ::value_type
>::value);
//! Test support for difference_type
static_assert(
std::is_same<
using_<std::vector<int>>::difference_type,
std::vector<int> ::difference_type
>::value);
//! Test support for iterator
static_assert(
std::is_same<
using_<std::vector<int>>::iterator,
std::vector<int> ::iterator
>::value);
} // namespace test_proof_of_concept
namespace test_user_defined_types {
struct UserDefined
{
using type = int;
};
} // namespace test_user_defined_types
} // namespace tests
namespace smartref {
// TODO: This currently needs to be declared in the smartref namespace.
// Figure out a way that it can be declared within an arbitrary namespace.
DECLARE_USING_MEMBER_TYPE(type);
template<typename Derived>
struct ::smartref::MemberFunctions<tests::test_user_defined_types::UserDefined, Derived>
: USING_MEMBER_TYPE(tests::test_user_defined_types::UserDefined, type)
{
};
} // namespace smartref
namespace tests {
namespace test_user_defined_types {
static_assert(
std::is_same<
using_<UserDefined>::type,
UserDefined ::type
>::value);
} // namespace test_user_defined_types
namespace test_nonintrusive_reflect {
struct UserDefined
{
using type = int;
};
REFLECT(UserDefined, type);
static_assert(
std::is_same<
using_<UserDefined>::type,
UserDefined ::type
>::value);
} // namespace test_nonintrusive_reflect
} // namespace tests
<|endoftext|>
|
<commit_before>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 "platform/platform.h"
#include "lighting/shadowMap/shadowMapManager.h"
#include "lighting/shadowMap/shadowMapPass.h"
#include "lighting/shadowMap/lightShadowMap.h"
#include "materials/materialManager.h"
#include "lighting/lightManager.h"
#include "core/util/safeDelete.h"
#include "scene/sceneRenderState.h"
#include "gfx/gfxTextureManager.h"
#include "core/module.h"
#include "console/consoleTypes.h"
GFX_ImplementTextureProfile(ShadowMapTexProfile,
GFXTextureProfile::DiffuseMap,
GFXTextureProfile::PreserveSize | GFXTextureProfile::Dynamic ,
GFXTextureProfile::NONE);
MODULE_BEGIN( ShadowMapManager )
MODULE_INIT
{
ManagedSingleton< ShadowMapManager >::createSingleton();
}
MODULE_SHUTDOWN
{
ManagedSingleton< ShadowMapManager >::deleteSingleton();
}
MODULE_END;
AFTER_MODULE_INIT( Sim )
{
Con::addVariable( "$pref::Shadows::textureScalar",
TypeF32, &LightShadowMap::smShadowTexScalar,
"@brief Used to scale the shadow texture sizes.\n"
"This can reduce the shadow quality and texture memory overhead or increase them.\n"
"@ingroup AdvancedLighting\n" );
Con::NotifyDelegate callabck( &LightShadowMap::releaseAllTextures );
Con::addVariableNotify( "$pref::Shadows::textureScalar", callabck );
Con::addVariable( "$pref::Shadows::disable",
TypeBool, &ShadowMapPass::smDisableShadowsPref,
"Used to disable all shadow rendering.\n"
"@ingroup AdvancedLighting\n" );
Con::addVariable( "$Shadows::disable",
TypeBool, &ShadowMapPass::smDisableShadowsEditor,
"Used by the editor to disable all shadow rendering.\n"
"@ingroup AdvancedLighting\n" );
Con::NotifyDelegate shadowCallback( &ShadowMapManager::updateShadowDisable );
Con::addVariableNotify( "$pref::Shadows::disable", shadowCallback );
Con::addVariableNotify( "$Shadows::disable", shadowCallback );
Con::addVariable("$pref::Shadows::teleportDist",
TypeF32, &ShadowMapPass::smShadowsTeleportDist,
"Minimum distance moved per frame to determine that we are teleporting.\n");
Con::addVariableNotify("$pref::Shadows::teleportDist", shadowCallback);
Con::addVariable("$pref::Shadows::turnRate",
TypeF32, &ShadowMapPass::smShadowsTurnRate,
"Minimum angle moved per frame to determine that we are turning quickly.\n");
Con::addVariableNotify("$pref::Shadows::turnRate", shadowCallback);
}
Signal<void(void)> ShadowMapManager::smShadowDeactivateSignal;
ShadowMapManager::ShadowMapManager()
: mShadowMapPass(NULL),
mCurrentShadowMap(NULL),
mCurrentDynamicShadowMap(NULL),
mIsActive(false)
{
}
ShadowMapManager::~ShadowMapManager()
{
}
void ShadowMapManager::setLightShadowMapForLight( LightInfo *light )
{
ShadowMapParams *params = light->getExtended<ShadowMapParams>();
if ( params )
{
mCurrentShadowMap = params->getShadowMap();
mCurrentDynamicShadowMap = params->getShadowMap(true);
}
else
{
mCurrentShadowMap = NULL;
mCurrentDynamicShadowMap = NULL;
}
}
void ShadowMapManager::activate()
{
ShadowManager::activate();
if (!getSceneManager())
{
Con::errorf("This world has no scene manager! Shadow manager not activating!");
return;
}
mShadowMapPass = new ShadowMapPass(LIGHTMGR, this);
getSceneManager()->getPreRenderSignal().notify( this, &ShadowMapManager::_onPreRender, 0.01f );
GFXTextureManager::addEventDelegate( this, &ShadowMapManager::_onTextureEvent );
mIsActive = true;
}
void ShadowMapManager::deactivate()
{
GFXTextureManager::removeEventDelegate( this, &ShadowMapManager::_onTextureEvent );
getSceneManager()->getPreRenderSignal().remove( this, &ShadowMapManager::_onPreRender );
SAFE_DELETE(mShadowMapPass);
mTapRotationTex = NULL;
// Clean up our shadow texture memory.
LightShadowMap::releaseAllTextures();
TEXMGR->cleanupPool();
mIsActive = false;
ShadowManager::deactivate();
}
void ShadowMapManager::_onPreRender( SceneManager *sg, const SceneRenderState *state )
{
if ( mShadowMapPass && state->isDiffusePass() )
mShadowMapPass->render( sg, state, (U32)-1 );
}
void ShadowMapManager::_onTextureEvent( GFXTexCallbackCode code )
{
if ( code == GFXZombify )
mTapRotationTex = NULL;
}
GFXTextureObject* ShadowMapManager::getTapRotationTex()
{
if ( mTapRotationTex.isValid() )
return mTapRotationTex;
mTapRotationTex.set( 64, 64, GFXFormatR8G8B8A8, &ShadowMapTexProfile,
"ShadowMapManager::getTapRotationTex" );
GFXLockedRect *rect = mTapRotationTex.lock();
U8 *f = rect->bits;
F32 angle;
for( U32 i = 0; i < 64*64; i++, f += 4 )
{
// We only pack the rotations into the red
// and green channels... the rest are empty.
angle = M_2PI_F * gRandGen.randF();
f[0] = U8_MAX * ( ( 1.0f + mSin( angle ) ) * 0.5f );
f[1] = U8_MAX * ( ( 1.0f + mCos( angle ) ) * 0.5f );
f[2] = 0;
f[3] = 0;
}
mTapRotationTex.unlock();
return mTapRotationTex;
}
void ShadowMapManager::updateShadowDisable()
{
bool disable = false;
if ( ShadowMapPass::smDisableShadowsEditor || ShadowMapPass::smDisableShadowsPref )
disable = true;
if ( disable != ShadowMapPass::smDisableShadows)
{
ShadowMapPass::smDisableShadows = disable;
smShadowDeactivateSignal.trigger();
}
}
<commit_msg>Fix assert on exit when Basic Lighting is removed<commit_after>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 "platform/platform.h"
#include "lighting/shadowMap/shadowMapManager.h"
#include "lighting/shadowMap/shadowMapPass.h"
#include "lighting/shadowMap/lightShadowMap.h"
#include "materials/materialManager.h"
#include "lighting/lightManager.h"
#include "core/util/safeDelete.h"
#include "scene/sceneRenderState.h"
#include "gfx/gfxTextureManager.h"
#include "core/module.h"
#include "console/consoleTypes.h"
GFX_ImplementTextureProfile(ShadowMapTexProfile,
GFXTextureProfile::DiffuseMap,
GFXTextureProfile::PreserveSize | GFXTextureProfile::Dynamic ,
GFXTextureProfile::NONE);
MODULE_BEGIN( ShadowMapManager )
#ifndef TORQUE_BASIC_LIGHTING
MODULE_SHUTDOWN_AFTER(Scene)
#endif
MODULE_INIT
{
ManagedSingleton< ShadowMapManager >::createSingleton();
}
MODULE_SHUTDOWN
{
ManagedSingleton< ShadowMapManager >::deleteSingleton();
}
MODULE_END;
AFTER_MODULE_INIT( Sim )
{
Con::addVariable( "$pref::Shadows::textureScalar",
TypeF32, &LightShadowMap::smShadowTexScalar,
"@brief Used to scale the shadow texture sizes.\n"
"This can reduce the shadow quality and texture memory overhead or increase them.\n"
"@ingroup AdvancedLighting\n" );
Con::NotifyDelegate callabck( &LightShadowMap::releaseAllTextures );
Con::addVariableNotify( "$pref::Shadows::textureScalar", callabck );
Con::addVariable( "$pref::Shadows::disable",
TypeBool, &ShadowMapPass::smDisableShadowsPref,
"Used to disable all shadow rendering.\n"
"@ingroup AdvancedLighting\n" );
Con::addVariable( "$Shadows::disable",
TypeBool, &ShadowMapPass::smDisableShadowsEditor,
"Used by the editor to disable all shadow rendering.\n"
"@ingroup AdvancedLighting\n" );
Con::NotifyDelegate shadowCallback( &ShadowMapManager::updateShadowDisable );
Con::addVariableNotify( "$pref::Shadows::disable", shadowCallback );
Con::addVariableNotify( "$Shadows::disable", shadowCallback );
Con::addVariable("$pref::Shadows::teleportDist",
TypeF32, &ShadowMapPass::smShadowsTeleportDist,
"Minimum distance moved per frame to determine that we are teleporting.\n");
Con::addVariableNotify("$pref::Shadows::teleportDist", shadowCallback);
Con::addVariable("$pref::Shadows::turnRate",
TypeF32, &ShadowMapPass::smShadowsTurnRate,
"Minimum angle moved per frame to determine that we are turning quickly.\n");
Con::addVariableNotify("$pref::Shadows::turnRate", shadowCallback);
}
Signal<void(void)> ShadowMapManager::smShadowDeactivateSignal;
ShadowMapManager::ShadowMapManager()
: mShadowMapPass(NULL),
mCurrentShadowMap(NULL),
mCurrentDynamicShadowMap(NULL),
mIsActive(false)
{
}
ShadowMapManager::~ShadowMapManager()
{
}
void ShadowMapManager::setLightShadowMapForLight( LightInfo *light )
{
ShadowMapParams *params = light->getExtended<ShadowMapParams>();
if ( params )
{
mCurrentShadowMap = params->getShadowMap();
mCurrentDynamicShadowMap = params->getShadowMap(true);
}
else
{
mCurrentShadowMap = NULL;
mCurrentDynamicShadowMap = NULL;
}
}
void ShadowMapManager::activate()
{
ShadowManager::activate();
if (!getSceneManager())
{
Con::errorf("This world has no scene manager! Shadow manager not activating!");
return;
}
mShadowMapPass = new ShadowMapPass(LIGHTMGR, this);
getSceneManager()->getPreRenderSignal().notify( this, &ShadowMapManager::_onPreRender, 0.01f );
GFXTextureManager::addEventDelegate( this, &ShadowMapManager::_onTextureEvent );
mIsActive = true;
}
void ShadowMapManager::deactivate()
{
GFXTextureManager::removeEventDelegate( this, &ShadowMapManager::_onTextureEvent );
getSceneManager()->getPreRenderSignal().remove( this, &ShadowMapManager::_onPreRender );
SAFE_DELETE(mShadowMapPass);
mTapRotationTex = NULL;
// Clean up our shadow texture memory.
LightShadowMap::releaseAllTextures();
TEXMGR->cleanupPool();
mIsActive = false;
ShadowManager::deactivate();
}
void ShadowMapManager::_onPreRender( SceneManager *sg, const SceneRenderState *state )
{
if ( mShadowMapPass && state->isDiffusePass() )
mShadowMapPass->render( sg, state, (U32)-1 );
}
void ShadowMapManager::_onTextureEvent( GFXTexCallbackCode code )
{
if ( code == GFXZombify )
mTapRotationTex = NULL;
}
GFXTextureObject* ShadowMapManager::getTapRotationTex()
{
if ( mTapRotationTex.isValid() )
return mTapRotationTex;
mTapRotationTex.set( 64, 64, GFXFormatR8G8B8A8, &ShadowMapTexProfile,
"ShadowMapManager::getTapRotationTex" );
GFXLockedRect *rect = mTapRotationTex.lock();
U8 *f = rect->bits;
F32 angle;
for( U32 i = 0; i < 64*64; i++, f += 4 )
{
// We only pack the rotations into the red
// and green channels... the rest are empty.
angle = M_2PI_F * gRandGen.randF();
f[0] = U8_MAX * ( ( 1.0f + mSin( angle ) ) * 0.5f );
f[1] = U8_MAX * ( ( 1.0f + mCos( angle ) ) * 0.5f );
f[2] = 0;
f[3] = 0;
}
mTapRotationTex.unlock();
return mTapRotationTex;
}
void ShadowMapManager::updateShadowDisable()
{
bool disable = false;
if ( ShadowMapPass::smDisableShadowsEditor || ShadowMapPass::smDisableShadowsPref )
disable = true;
if ( disable != ShadowMapPass::smDisableShadows)
{
ShadowMapPass::smDisableShadows = disable;
smShadowDeactivateSignal.trigger();
}
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.