text
stringlengths 54
60.6k
|
---|
<commit_before>#include <cstdio>
#include <cstdlib>
#include <locale>
#include <string>
#include <vector>
#include <algorithm>
#include <iostream> // NOLINT
#include <algorithm>
#include <tr1/array>
#include "config/config.h"
#include "stringpiece.h"
#include "ustringpiece.h"
#include "cmdline.h"
#include "ast.h"
#include "ast-serializer.h"
#include "parser.h"
#include "factory.h"
#include "interpreter.h"
#include "context.h"
#include "jsast.h"
#include "jsval.h"
#include "jsstring.h"
#include "jsscript.h"
#include "print.h"
#include "interactive.h"
#include "icu/ustream.h"
#include "icu/source.h"
#include "fpu.h"
int main(int argc, char **argv) {
using iv::lv5::JSVal;
iv::lv5::FixFPU();
std::locale::global(std::locale(""));
iv::cmdline::Parser cmd("lv5");
cmd.Add("help",
"help",
'h', "print this message");
cmd.Add("version",
"version",
'v', "print the version");
cmd.Add("warning",
"",
'W', "set warning level 0 - 2", false, 0, iv::cmdline::range(0, 2));
cmd.Add("ast",
"ast",
0, "print ast");
cmd.Add("copyright",
"copyright",
0, "print the copyright");
cmd.set_footer("[program_file] [arguments]");
bool cmd_parse_success = cmd.Parse(argc, argv);
if (!cmd_parse_success) {
std::cerr << cmd.error() << std::endl << cmd.usage();
return EXIT_FAILURE;
}
if (cmd.Exist("help")) {
std::cout << cmd.usage();
return EXIT_SUCCESS;
}
if (cmd.Exist("version")) {
printf("lv5 %s (compiled %s %s)\n", IV_VERSION, __DATE__, __TIME__);
return EXIT_SUCCESS;
}
if (cmd.Exist("copyright")) {
printf("lv5 - Copyright (C) 2010 %s\n", IV_DEVELOPER);
return EXIT_SUCCESS;
}
const std::vector<std::string>& rest = cmd.rest();
const std::string& filename = rest.front();
if (!rest.empty()) {
std::string str;
if (std::FILE* fp = std::fopen(filename.c_str(), "r")) {
std::tr1::array<char, 1024> buf;
while (std::size_t len = std::fread(buf.data(),
1,
buf.size(), fp)) {
str.append(buf.data(), len);
}
std::fclose(fp);
} else {
std::string err("lv5 can't open \"");
err.append(filename);
err.append("\"");
std::perror(err.c_str());
return EXIT_FAILURE;
}
iv::icu::Source src(str, filename);
iv::lv5::Context ctx;
iv::lv5::AstFactory factory(&ctx);
iv::core::Parser<iv::lv5::AstFactory, iv::icu::Source>
parser(&factory, &src);
const iv::lv5::FunctionLiteral* const global = parser.ParseProgram();
if (!global) {
std::cerr << parser.error() << std::endl;
return EXIT_FAILURE;
}
if (cmd.Exist("ast")) {
iv::core::ast::AstSerializer<iv::lv5::AstFactory> ser;
global->Accept(&ser);
std::cout << ser.out() << std::endl;
} else {
ctx.DefineFunction(&iv::lv5::Print, "print", 1);
iv::lv5::JSScript* const script = iv::lv5::JSGlobalScript::New(
&ctx, global, &factory, &src);
if (ctx.Run(script)) {
const JSVal e = ctx.ErrorVal();
ctx.error()->Clear();
const iv::lv5::JSString* const str = e.ToString(&ctx, ctx.error());
if (!*ctx.error()) {
std::cerr << *str << std::endl;
return EXIT_FAILURE;
}
}
}
} else {
// Interactive Shell Mode
iv::lv5::Interactive shell;
return shell.Run();
}
return 0;
}
<commit_msg>forget fix main.cc<commit_after>#include <cstdio>
#include <cstdlib>
#include <locale>
#include <string>
#include <vector>
#include <algorithm>
#include <iostream> // NOLINT
#include <algorithm>
#include <tr1/array>
#include "config/config.h"
#include "stringpiece.h"
#include "ustringpiece.h"
#include "cmdline.h"
#include "ast.h"
#include "ast_serializer.h"
#include "parser.h"
#include "factory.h"
#include "interpreter.h"
#include "context.h"
#include "jsast.h"
#include "jsval.h"
#include "jsstring.h"
#include "jsscript.h"
#include "print.h"
#include "interactive.h"
#include "icu/ustream.h"
#include "icu/source.h"
#include "fpu.h"
int main(int argc, char **argv) {
using iv::lv5::JSVal;
iv::lv5::FixFPU();
std::locale::global(std::locale(""));
iv::cmdline::Parser cmd("lv5");
cmd.Add("help",
"help",
'h', "print this message");
cmd.Add("version",
"version",
'v', "print the version");
cmd.Add("warning",
"",
'W', "set warning level 0 - 2", false, 0, iv::cmdline::range(0, 2));
cmd.Add("ast",
"ast",
0, "print ast");
cmd.Add("copyright",
"copyright",
0, "print the copyright");
cmd.set_footer("[program_file] [arguments]");
bool cmd_parse_success = cmd.Parse(argc, argv);
if (!cmd_parse_success) {
std::cerr << cmd.error() << std::endl << cmd.usage();
return EXIT_FAILURE;
}
if (cmd.Exist("help")) {
std::cout << cmd.usage();
return EXIT_SUCCESS;
}
if (cmd.Exist("version")) {
printf("lv5 %s (compiled %s %s)\n", IV_VERSION, __DATE__, __TIME__);
return EXIT_SUCCESS;
}
if (cmd.Exist("copyright")) {
printf("lv5 - Copyright (C) 2010 %s\n", IV_DEVELOPER);
return EXIT_SUCCESS;
}
const std::vector<std::string>& rest = cmd.rest();
const std::string& filename = rest.front();
if (!rest.empty()) {
std::string str;
if (std::FILE* fp = std::fopen(filename.c_str(), "r")) {
std::tr1::array<char, 1024> buf;
while (std::size_t len = std::fread(buf.data(),
1,
buf.size(), fp)) {
str.append(buf.data(), len);
}
std::fclose(fp);
} else {
std::string err("lv5 can't open \"");
err.append(filename);
err.append("\"");
std::perror(err.c_str());
return EXIT_FAILURE;
}
iv::icu::Source src(str, filename);
iv::lv5::Context ctx;
iv::lv5::AstFactory factory(&ctx);
iv::core::Parser<iv::lv5::AstFactory, iv::icu::Source>
parser(&factory, &src);
const iv::lv5::FunctionLiteral* const global = parser.ParseProgram();
if (!global) {
std::cerr << parser.error() << std::endl;
return EXIT_FAILURE;
}
if (cmd.Exist("ast")) {
iv::core::ast::AstSerializer<iv::lv5::AstFactory> ser;
global->Accept(&ser);
std::cout << ser.out() << std::endl;
} else {
ctx.DefineFunction(&iv::lv5::Print, "print", 1);
iv::lv5::JSScript* const script = iv::lv5::JSGlobalScript::New(
&ctx, global, &factory, &src);
if (ctx.Run(script)) {
const JSVal e = ctx.ErrorVal();
ctx.error()->Clear();
const iv::lv5::JSString* const str = e.ToString(&ctx, ctx.error());
if (!*ctx.error()) {
std::cerr << *str << std::endl;
return EXIT_FAILURE;
}
}
}
} else {
// Interactive Shell Mode
iv::lv5::Interactive shell;
return shell.Run();
}
return 0;
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/common/include/p9_xbus_scom_addresses_fixes.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file xbus_scom_addresses_fixes.H
/// @brief The *scom_addresses.H files are generated form figtree, but
/// the figree can be wrong. This file is included at the end
/// of scom_addresses.H and allows incorrect constants to be
/// fixed manually.
///
// *HWP HWP Owner: Ben Gass <[email protected]>
// *HWP FW Owner: ? <?>
// *HWP Team: SAO
// *HWP Level: 1
// *HWP Consumed by: FSP:HB:HS:OCC:SBE:CME:SGPE:PGPE:FPPE:IPPE
#ifndef __P9_XBUS_SCOM_ADDRESSES_FIXES_H
#define __P9_XBUS_SCOM_ADDRESSES_FIXES_H
//Example,
//Copy the whole line from the *scom_addresses.H file. Then add
//FIX in front of REG, and add another paramter that is the new
//corrected value.
//FIXREG64( PU_ALTD_ADDR_REG,
// RULL(0x05022800), SH_UNT, SH_ACS_SCOM,
// RULL(0x00090000)
// );
#endif
<commit_msg>update HWP level metadata for nest, common files<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/common/include/p9_xbus_scom_addresses_fixes.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file xbus_scom_addresses_fixes.H
/// @brief The *scom_addresses.H files are generated form figtree, but
/// the figree can be wrong. This file is included at the end
/// of scom_addresses.H and allows incorrect constants to be
/// fixed manually.
///
// *HWP HWP Owner: Ben Gass <[email protected]>
// *HWP FW Owner: ? <?>
// *HWP Team: SAO
// *HWP Level: 3
// *HWP Consumed by: FSP:HB:HS:OCC:SBE:CME:SGPE:PGPE:FPPE:IPPE
#ifndef __P9_XBUS_SCOM_ADDRESSES_FIXES_H
#define __P9_XBUS_SCOM_ADDRESSES_FIXES_H
//Example,
//Copy the whole line from the *scom_addresses.H file. Then add
//FIX in front of REG, and add another paramter that is the new
//corrected value.
//FIXREG64( PU_ALTD_ADDR_REG,
// RULL(0x05022800), SH_UNT, SH_ACS_SCOM,
// RULL(0x00090000)
// );
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SwXTextDefaults.cxx,v $
*
* $Revision: 1.21 $
*
* last change: $Author: rt $ $Date: 2008-03-12 12:26:28 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _SW_XTEXT_DEFAULTS_HXX
#include <SwXTextDefaults.hxx>
#endif
#ifndef _SWSTYLENAMEMAPPER_HXX
#include <SwStyleNameMapper.hxx>
#endif
#ifndef _FCHRFMT_HXX
#include <fchrfmt.hxx>
#endif
#ifndef _CHARFMT_HXX
#include <charfmt.hxx>
#endif
#ifndef _DOCSTYLE_HXX
#include <docstyle.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _SWDOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _UNOMAP_HXX
#include <unomap.hxx>
#endif
#ifndef SW_UNOMID_HXX
#include <unomid.h>
#endif
#ifndef _PARATR_HXX
#include <paratr.hxx>
#endif
#ifndef _UNOPRNMS_HXX
#include <unoprnms.hxx>
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#include <unomid.h>
using rtl::OUString;
using namespace rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
// declarations
void lcl_setPageDesc(SwDoc*, const uno::Any&, SfxItemSet& ); // from unoobj.cxx
SwXTextDefaults::SwXTextDefaults ( SwDoc * pNewDoc ) :
aPropSet( aSwMapProvider.GetPropertyMap ( PROPERTY_MAP_TEXT_DEFAULT ) ),
pDoc ( pNewDoc )
{
}
SwXTextDefaults::~SwXTextDefaults ()
{
}
uno::Reference< XPropertySetInfo > SAL_CALL SwXTextDefaults::getPropertySetInfo( )
throw(RuntimeException)
{
static uno::Reference < XPropertySetInfo > xRef = aPropSet.getPropertySetInfo();
return xRef;
}
void SAL_CALL SwXTextDefaults::setPropertyValue( const OUString& rPropertyName, const Any& aValue )
throw(UnknownPropertyException, PropertyVetoException, IllegalArgumentException, WrappedTargetException, RuntimeException)
{
vos::OGuard aGuard( Application::GetSolarMutex());
if (!pDoc)
throw RuntimeException();
const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName);
if (!pMap)
throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
if ( pMap->nFlags & PropertyAttribute::READONLY)
throw PropertyVetoException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Property is read-only: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
const SfxPoolItem& rItem = pDoc->GetDefault(pMap->nWID);
if (RES_PAGEDESC == pMap->nWID && MID_PAGEDESC_PAGEDESCNAME == pMap->nMemberId)
{
SfxItemSet aSet( pDoc->GetAttrPool(), RES_PAGEDESC, RES_PAGEDESC );
aSet.Put(rItem);
lcl_setPageDesc( pDoc, aValue, aSet );
pDoc->SetDefault(aSet.Get(RES_PAGEDESC));
}
else if ((RES_PARATR_DROP == pMap->nWID && MID_DROPCAP_CHAR_STYLE_NAME == pMap->nMemberId) ||
(RES_TXTATR_CHARFMT == pMap->nWID))
{
OUString uStyle;
if(aValue >>= uStyle)
{
String sStyle;
SwStyleNameMapper::FillUIName(uStyle, sStyle, nsSwGetPoolIdFromName::GET_POOLID_CHRFMT, sal_True );
SwDocStyleSheet* pStyle =
(SwDocStyleSheet*)pDoc->GetDocShell()->GetStyleSheetPool()->Find(sStyle, SFX_STYLE_FAMILY_CHAR);
SwFmtDrop* pDrop = 0;
SwFmtCharFmt *pCharFmt = 0;
if(pStyle)
{
rtl::Reference< SwDocStyleSheet > xStyle( new SwDocStyleSheet( *(SwDocStyleSheet*)pStyle ) );
if (RES_PARATR_DROP == pMap->nWID)
{
pDrop = (SwFmtDrop*)rItem.Clone(); // because rItem ist const...
pDrop->SetCharFmt(xStyle->GetCharFmt());
pDoc->SetDefault(*pDrop);
}
else // RES_TXTATR_CHARFMT == pMap->nWID
{
pCharFmt = (SwFmtCharFmt*)rItem.Clone(); // because rItem ist const...
pCharFmt->SetCharFmt(xStyle->GetCharFmt());
pDoc->SetDefault(*pCharFmt);
}
}
else
throw lang::IllegalArgumentException();
delete pDrop;
delete pCharFmt;
}
else
throw lang::IllegalArgumentException();
}
else
{
SfxPoolItem * pNewItem = rItem.Clone();
pNewItem->PutValue( aValue, pMap->nMemberId);
pDoc->SetDefault(*pNewItem);
delete pNewItem;
}
}
Any SAL_CALL SwXTextDefaults::getPropertyValue( const OUString& rPropertyName )
throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
vos::OGuard aGuard( Application::GetSolarMutex());
if (!pDoc)
throw RuntimeException();
const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName);
if (!pMap)
throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
Any aRet;
const SfxPoolItem& rItem = pDoc->GetDefault(pMap->nWID);
rItem.QueryValue( aRet, pMap->nMemberId );
return aRet;
}
void SAL_CALL SwXTextDefaults::addPropertyChangeListener( const OUString& /*rPropertyName*/, const uno::Reference< XPropertyChangeListener >& /*xListener*/ )
throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
DBG_WARNING ( "not implemented" );
}
void SAL_CALL SwXTextDefaults::removePropertyChangeListener( const OUString& /*rPropertyName*/, const uno::Reference< XPropertyChangeListener >& /*xListener*/ )
throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
DBG_WARNING ( "not implemented" );
}
void SAL_CALL SwXTextDefaults::addVetoableChangeListener( const OUString& /*rPropertyName*/, const uno::Reference< XVetoableChangeListener >& /*xListener*/ )
throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
DBG_WARNING ( "not implemented" );
}
void SAL_CALL SwXTextDefaults::removeVetoableChangeListener( const OUString& /*rPropertyName*/, const uno::Reference< XVetoableChangeListener >& /*xListener*/ )
throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
DBG_WARNING ( "not implemented" );
}
// XPropertyState
PropertyState SAL_CALL SwXTextDefaults::getPropertyState( const OUString& rPropertyName )
throw(UnknownPropertyException, RuntimeException)
{
vos::OGuard aGuard( Application::GetSolarMutex());
PropertyState eRet = PropertyState_DIRECT_VALUE;
if (!pDoc)
throw RuntimeException();
const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName);
if (!pMap)
throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
const SfxPoolItem& rItem = pDoc->GetDefault(pMap->nWID);
if (IsStaticDefaultItem ( &rItem ) )
eRet = PropertyState_DEFAULT_VALUE;
return eRet;
}
Sequence< PropertyState > SAL_CALL SwXTextDefaults::getPropertyStates( const Sequence< OUString >& rPropertyNames )
throw(UnknownPropertyException, RuntimeException)
{
const sal_Int32 nCount = rPropertyNames.getLength();
const OUString * pNames = rPropertyNames.getConstArray();
Sequence < PropertyState > aRet ( nCount );
PropertyState *pState = aRet.getArray();
for ( sal_Int32 nIndex = 0; nIndex < nCount; nIndex++)
pState[nIndex] = getPropertyState( pNames[nIndex] );
return aRet;
}
void SAL_CALL SwXTextDefaults::setPropertyToDefault( const OUString& rPropertyName )
throw(UnknownPropertyException, RuntimeException)
{
if (!pDoc)
throw RuntimeException();
const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName);
if (!pMap)
throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
if ( pMap->nFlags & PropertyAttribute::READONLY)
throw RuntimeException( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "setPropertyToDefault: property is read-only: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
SfxItemPool rSet (pDoc->GetAttrPool());
rSet.ResetPoolDefaultItem ( pMap->nWID );
}
Any SAL_CALL SwXTextDefaults::getPropertyDefault( const OUString& rPropertyName )
throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
if (!pDoc)
throw RuntimeException();
const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName);
if (!pMap)
throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
Any aRet;
SfxItemPool rSet (pDoc->GetAttrPool());
const SfxPoolItem *pItem = rSet.GetPoolDefaultItem ( pMap->nWID );
pItem->QueryValue( aRet, pMap->nMemberId );
return aRet;
}
rtl::OUString SAL_CALL SwXTextDefaults::getImplementationName( )
throw (RuntimeException)
{
return C2U("SwXTextDefaults");
}
sal_Bool SAL_CALL SwXTextDefaults::supportsService( const ::rtl::OUString& rServiceName )
throw (RuntimeException)
{
return rServiceName == C2U("com.sun.star.text.Defaults") ||
rServiceName == C2U("com.sun.star.style.CharacterProperties") ||
rServiceName == C2U("com.sun.star.style.CharacterPropertiesAsian") ||
rServiceName == C2U("com.sun.star.style.CharacterPropertiesComplex") ||
rServiceName == C2U("com.sun.star.style.ParagraphProperties") ||
rServiceName == C2U("com.sun.star.style.ParagraphPropertiesAsian") ||
rServiceName == C2U("com.sun.star.style.ParagraphPropertiesComplex");
}
uno::Sequence< ::rtl::OUString > SAL_CALL SwXTextDefaults::getSupportedServiceNames( )
throw (RuntimeException)
{
uno::Sequence< OUString > aRet(7);
OUString* pArr = aRet.getArray();
*pArr++ = C2U("com.sun.star.text.Defaults");
*pArr++ = C2U("com.sun.star.style.CharacterProperties");
*pArr++ = C2U("com.sun.star.style.CharacterPropertiesAsian");
*pArr++ = C2U("com.sun.star.style.CharacterPropertiesComplex");
*pArr++ = C2U("com.sun.star.style.ParagraphProperties");
*pArr++ = C2U("com.sun.star.style.ParagraphPropertiesAsian");
*pArr++ = C2U("com.sun.star.style.ParagraphPropertiesComplex");
return aRet;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.21.34); FILE MERGED 2008/04/01 15:57:34 thb 1.21.34.3: #i85898# Stripping all external header guards 2008/04/01 12:54:31 thb 1.21.34.2: #i85898# Stripping all external header guards 2008/03/31 16:55:13 rt 1.21.34.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SwXTextDefaults.cxx,v $
* $Revision: 1.22 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#include <vos/mutex.hxx>
#include <vcl/svapp.hxx>
#include <com/sun/star/beans/PropertyAttribute.hpp>
#include <SwXTextDefaults.hxx>
#include <SwStyleNameMapper.hxx>
#include <fchrfmt.hxx>
#include <charfmt.hxx>
#include <docstyle.hxx>
#include <doc.hxx>
#include <docsh.hxx>
#include <unomap.hxx>
#include <unomid.h>
#include <paratr.hxx>
#include <unoprnms.hxx>
#include <hintids.hxx>
#include <unomid.h>
using rtl::OUString;
using namespace rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
// declarations
void lcl_setPageDesc(SwDoc*, const uno::Any&, SfxItemSet& ); // from unoobj.cxx
SwXTextDefaults::SwXTextDefaults ( SwDoc * pNewDoc ) :
aPropSet( aSwMapProvider.GetPropertyMap ( PROPERTY_MAP_TEXT_DEFAULT ) ),
pDoc ( pNewDoc )
{
}
SwXTextDefaults::~SwXTextDefaults ()
{
}
uno::Reference< XPropertySetInfo > SAL_CALL SwXTextDefaults::getPropertySetInfo( )
throw(RuntimeException)
{
static uno::Reference < XPropertySetInfo > xRef = aPropSet.getPropertySetInfo();
return xRef;
}
void SAL_CALL SwXTextDefaults::setPropertyValue( const OUString& rPropertyName, const Any& aValue )
throw(UnknownPropertyException, PropertyVetoException, IllegalArgumentException, WrappedTargetException, RuntimeException)
{
vos::OGuard aGuard( Application::GetSolarMutex());
if (!pDoc)
throw RuntimeException();
const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName);
if (!pMap)
throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
if ( pMap->nFlags & PropertyAttribute::READONLY)
throw PropertyVetoException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Property is read-only: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
const SfxPoolItem& rItem = pDoc->GetDefault(pMap->nWID);
if (RES_PAGEDESC == pMap->nWID && MID_PAGEDESC_PAGEDESCNAME == pMap->nMemberId)
{
SfxItemSet aSet( pDoc->GetAttrPool(), RES_PAGEDESC, RES_PAGEDESC );
aSet.Put(rItem);
lcl_setPageDesc( pDoc, aValue, aSet );
pDoc->SetDefault(aSet.Get(RES_PAGEDESC));
}
else if ((RES_PARATR_DROP == pMap->nWID && MID_DROPCAP_CHAR_STYLE_NAME == pMap->nMemberId) ||
(RES_TXTATR_CHARFMT == pMap->nWID))
{
OUString uStyle;
if(aValue >>= uStyle)
{
String sStyle;
SwStyleNameMapper::FillUIName(uStyle, sStyle, nsSwGetPoolIdFromName::GET_POOLID_CHRFMT, sal_True );
SwDocStyleSheet* pStyle =
(SwDocStyleSheet*)pDoc->GetDocShell()->GetStyleSheetPool()->Find(sStyle, SFX_STYLE_FAMILY_CHAR);
SwFmtDrop* pDrop = 0;
SwFmtCharFmt *pCharFmt = 0;
if(pStyle)
{
rtl::Reference< SwDocStyleSheet > xStyle( new SwDocStyleSheet( *(SwDocStyleSheet*)pStyle ) );
if (RES_PARATR_DROP == pMap->nWID)
{
pDrop = (SwFmtDrop*)rItem.Clone(); // because rItem ist const...
pDrop->SetCharFmt(xStyle->GetCharFmt());
pDoc->SetDefault(*pDrop);
}
else // RES_TXTATR_CHARFMT == pMap->nWID
{
pCharFmt = (SwFmtCharFmt*)rItem.Clone(); // because rItem ist const...
pCharFmt->SetCharFmt(xStyle->GetCharFmt());
pDoc->SetDefault(*pCharFmt);
}
}
else
throw lang::IllegalArgumentException();
delete pDrop;
delete pCharFmt;
}
else
throw lang::IllegalArgumentException();
}
else
{
SfxPoolItem * pNewItem = rItem.Clone();
pNewItem->PutValue( aValue, pMap->nMemberId);
pDoc->SetDefault(*pNewItem);
delete pNewItem;
}
}
Any SAL_CALL SwXTextDefaults::getPropertyValue( const OUString& rPropertyName )
throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
vos::OGuard aGuard( Application::GetSolarMutex());
if (!pDoc)
throw RuntimeException();
const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName);
if (!pMap)
throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
Any aRet;
const SfxPoolItem& rItem = pDoc->GetDefault(pMap->nWID);
rItem.QueryValue( aRet, pMap->nMemberId );
return aRet;
}
void SAL_CALL SwXTextDefaults::addPropertyChangeListener( const OUString& /*rPropertyName*/, const uno::Reference< XPropertyChangeListener >& /*xListener*/ )
throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
DBG_WARNING ( "not implemented" );
}
void SAL_CALL SwXTextDefaults::removePropertyChangeListener( const OUString& /*rPropertyName*/, const uno::Reference< XPropertyChangeListener >& /*xListener*/ )
throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
DBG_WARNING ( "not implemented" );
}
void SAL_CALL SwXTextDefaults::addVetoableChangeListener( const OUString& /*rPropertyName*/, const uno::Reference< XVetoableChangeListener >& /*xListener*/ )
throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
DBG_WARNING ( "not implemented" );
}
void SAL_CALL SwXTextDefaults::removeVetoableChangeListener( const OUString& /*rPropertyName*/, const uno::Reference< XVetoableChangeListener >& /*xListener*/ )
throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
DBG_WARNING ( "not implemented" );
}
// XPropertyState
PropertyState SAL_CALL SwXTextDefaults::getPropertyState( const OUString& rPropertyName )
throw(UnknownPropertyException, RuntimeException)
{
vos::OGuard aGuard( Application::GetSolarMutex());
PropertyState eRet = PropertyState_DIRECT_VALUE;
if (!pDoc)
throw RuntimeException();
const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName);
if (!pMap)
throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
const SfxPoolItem& rItem = pDoc->GetDefault(pMap->nWID);
if (IsStaticDefaultItem ( &rItem ) )
eRet = PropertyState_DEFAULT_VALUE;
return eRet;
}
Sequence< PropertyState > SAL_CALL SwXTextDefaults::getPropertyStates( const Sequence< OUString >& rPropertyNames )
throw(UnknownPropertyException, RuntimeException)
{
const sal_Int32 nCount = rPropertyNames.getLength();
const OUString * pNames = rPropertyNames.getConstArray();
Sequence < PropertyState > aRet ( nCount );
PropertyState *pState = aRet.getArray();
for ( sal_Int32 nIndex = 0; nIndex < nCount; nIndex++)
pState[nIndex] = getPropertyState( pNames[nIndex] );
return aRet;
}
void SAL_CALL SwXTextDefaults::setPropertyToDefault( const OUString& rPropertyName )
throw(UnknownPropertyException, RuntimeException)
{
if (!pDoc)
throw RuntimeException();
const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName);
if (!pMap)
throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
if ( pMap->nFlags & PropertyAttribute::READONLY)
throw RuntimeException( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "setPropertyToDefault: property is read-only: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
SfxItemPool rSet (pDoc->GetAttrPool());
rSet.ResetPoolDefaultItem ( pMap->nWID );
}
Any SAL_CALL SwXTextDefaults::getPropertyDefault( const OUString& rPropertyName )
throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
if (!pDoc)
throw RuntimeException();
const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName);
if (!pMap)
throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
Any aRet;
SfxItemPool rSet (pDoc->GetAttrPool());
const SfxPoolItem *pItem = rSet.GetPoolDefaultItem ( pMap->nWID );
pItem->QueryValue( aRet, pMap->nMemberId );
return aRet;
}
rtl::OUString SAL_CALL SwXTextDefaults::getImplementationName( )
throw (RuntimeException)
{
return C2U("SwXTextDefaults");
}
sal_Bool SAL_CALL SwXTextDefaults::supportsService( const ::rtl::OUString& rServiceName )
throw (RuntimeException)
{
return rServiceName == C2U("com.sun.star.text.Defaults") ||
rServiceName == C2U("com.sun.star.style.CharacterProperties") ||
rServiceName == C2U("com.sun.star.style.CharacterPropertiesAsian") ||
rServiceName == C2U("com.sun.star.style.CharacterPropertiesComplex") ||
rServiceName == C2U("com.sun.star.style.ParagraphProperties") ||
rServiceName == C2U("com.sun.star.style.ParagraphPropertiesAsian") ||
rServiceName == C2U("com.sun.star.style.ParagraphPropertiesComplex");
}
uno::Sequence< ::rtl::OUString > SAL_CALL SwXTextDefaults::getSupportedServiceNames( )
throw (RuntimeException)
{
uno::Sequence< OUString > aRet(7);
OUString* pArr = aRet.getArray();
*pArr++ = C2U("com.sun.star.text.Defaults");
*pArr++ = C2U("com.sun.star.style.CharacterProperties");
*pArr++ = C2U("com.sun.star.style.CharacterPropertiesAsian");
*pArr++ = C2U("com.sun.star.style.CharacterPropertiesComplex");
*pArr++ = C2U("com.sun.star.style.ParagraphProperties");
*pArr++ = C2U("com.sun.star.style.ParagraphPropertiesAsian");
*pArr++ = C2U("com.sun.star.style.ParagraphPropertiesComplex");
return aRet;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <mapport.h>
#include <clientversion.h>
#include <logging.h>
#include <net.h>
#include <netaddress.h>
#include <netbase.h>
#include <threadinterrupt.h>
#include <util/system.h>
#include <util/thread.h>
#ifdef USE_NATPMP
#include <compat.h>
#include <natpmp.h>
#endif // USE_NATPMP
#ifdef USE_UPNP
#include <miniupnpc/miniupnpc.h>
#include <miniupnpc/upnpcommands.h>
#include <miniupnpc/upnperrors.h>
// The minimum supported miniUPnPc API version is set to 10. This keeps
// compatibility with Ubuntu 16.04 LTS and Debian 8 libminiupnpc-dev packages.
static_assert(MINIUPNPC_API_VERSION >= 10,
"miniUPnPc API version >= 10 assumed");
#endif // USE_UPNP
#include <atomic>
#include <cassert>
#include <chrono>
#include <functional>
#include <string>
#include <thread>
#if defined(USE_NATPMP) || defined(USE_UPNP)
static CThreadInterrupt g_mapport_interrupt;
static std::thread g_mapport_thread;
static std::atomic_uint g_mapport_target_proto{MapPortProtoFlag::NONE};
using namespace std::chrono_literals;
static constexpr auto PORT_MAPPING_REANNOUNCE_PERIOD{20min};
static constexpr auto PORT_MAPPING_RETRY_PERIOD{5min};
#ifdef USE_NATPMP
static uint16_t g_mapport_external_port = 0;
static bool NatpmpInit(natpmp_t *natpmp) {
const int r_init = initnatpmp(natpmp, /* detect gateway automatically */ 0,
/* forced gateway - NOT APPLIED*/ 0);
if (r_init == 0) {
return true;
}
LogPrintf("natpmp: initnatpmp() failed with %d error.\n", r_init);
return false;
}
static bool NatpmpDiscover(natpmp_t *natpmp,
struct in_addr &external_ipv4_addr) {
const int r_send = sendpublicaddressrequest(natpmp);
if (r_send == 2 /* OK */) {
int r_read;
natpmpresp_t response;
do {
r_read = readnatpmpresponseorretry(natpmp, &response);
} while (r_read == NATPMP_TRYAGAIN);
if (r_read == 0) {
external_ipv4_addr = response.pnu.publicaddress.addr;
return true;
} else if (r_read == NATPMP_ERR_NOGATEWAYSUPPORT) {
LogPrintf("natpmp: The gateway does not support NAT-PMP.\n");
} else {
LogPrintf("natpmp: readnatpmpresponseorretry() for public address "
"failed with %d error.\n",
r_read);
}
} else {
LogPrintf("natpmp: sendpublicaddressrequest() failed with %d error.\n",
r_send);
}
return false;
}
static bool NatpmpMapping(natpmp_t *natpmp,
const struct in_addr &external_ipv4_addr,
uint16_t private_port, bool &external_ip_discovered) {
const uint16_t suggested_external_port =
g_mapport_external_port ? g_mapport_external_port : private_port;
const int r_send =
sendnewportmappingrequest(natpmp, NATPMP_PROTOCOL_TCP, private_port,
suggested_external_port, 3600 /*seconds*/);
if (r_send == 12 /* OK */) {
int r_read;
natpmpresp_t response;
do {
r_read = readnatpmpresponseorretry(natpmp, &response);
} while (r_read == NATPMP_TRYAGAIN);
if (r_read == 0) {
auto pm = response.pnu.newportmapping;
if (private_port == pm.privateport && pm.lifetime > 0) {
g_mapport_external_port = pm.mappedpublicport;
const CService external{external_ipv4_addr,
pm.mappedpublicport};
if (!external_ip_discovered && fDiscover) {
AddLocal(external, LOCAL_MAPPED);
external_ip_discovered = true;
}
LogPrintf(
"natpmp: Port mapping successful. External address = %s\n",
external.ToString());
return true;
} else {
LogPrintf("natpmp: Port mapping failed.\n");
}
} else if (r_read == NATPMP_ERR_NOGATEWAYSUPPORT) {
LogPrintf("natpmp: The gateway does not support NAT-PMP.\n");
} else {
LogPrintf("natpmp: readnatpmpresponseorretry() for port mapping "
"failed with %d error.\n",
r_read);
}
} else {
LogPrintf("natpmp: sendnewportmappingrequest() failed with %d error.\n",
r_send);
}
return false;
}
[[maybe_unused]] static bool ProcessNatpmp() {
bool ret = false;
natpmp_t natpmp;
struct in_addr external_ipv4_addr;
if (NatpmpInit(&natpmp) && NatpmpDiscover(&natpmp, external_ipv4_addr)) {
bool external_ip_discovered = false;
const uint16_t private_port = GetListenPort();
do {
ret = NatpmpMapping(&natpmp, external_ipv4_addr, private_port,
external_ip_discovered);
} while (ret &&
g_mapport_interrupt.sleep_for(PORT_MAPPING_REANNOUNCE_PERIOD));
g_mapport_interrupt.reset();
const int r_send = sendnewportmappingrequest(
&natpmp, NATPMP_PROTOCOL_TCP, private_port, g_mapport_external_port,
/* remove a port mapping */ 0);
g_mapport_external_port = 0;
if (r_send == 12 /* OK */) {
LogPrintf("natpmp: Port mapping removed successfully.\n");
} else {
LogPrintf(
"natpmp: sendnewportmappingrequest(0) failed with %d error.\n",
r_send);
}
}
closenatpmp(&natpmp);
return ret;
}
#endif // USE_NATPMP
#ifdef USE_UPNP
static bool ProcessUpnp() {
bool ret = false;
std::string port = strprintf("%u", GetListenPort());
const char *multicastif = nullptr;
const char *minissdpdpath = nullptr;
struct UPNPDev *devlist = nullptr;
char lanaddr[64];
int error = 0;
#if MINIUPNPC_API_VERSION < 14
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
#else
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, 2, &error);
#endif
struct UPNPUrls urls;
struct IGDdatas data;
int r;
r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
if (r == 1) {
if (fDiscover) {
char externalIPAddress[40];
r = UPNP_GetExternalIPAddress(
urls.controlURL, data.first.servicetype, externalIPAddress);
if (r != UPNPCOMMAND_SUCCESS) {
LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r);
} else {
if (externalIPAddress[0]) {
CNetAddr resolved;
if (LookupHost(externalIPAddress, resolved, false)) {
LogPrintf("UPnP: ExternalIPAddress = %s\n",
resolved.ToString());
AddLocal(resolved, LOCAL_MAPPED);
}
} else {
LogPrintf("UPnP: GetExternalIPAddress failed.\n");
}
}
}
std::string strDesc = PACKAGE_NAME " " + FormatFullVersion();
do {
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr,
strDesc.c_str(), "TCP", 0, "0");
if (r != UPNPCOMMAND_SUCCESS) {
ret = false;
LogPrintf(
"AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
port, port, lanaddr, r, strupnperror(r));
break;
} else {
ret = true;
LogPrintf("UPnP Port Mapping successful.\n");
}
} while (g_mapport_interrupt.sleep_for(PORT_MAPPING_REANNOUNCE_PERIOD));
g_mapport_interrupt.reset();
r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), "TCP", 0);
LogPrintf("UPNP_DeletePortMapping() returned: %d\n", r);
freeUPNPDevlist(devlist);
devlist = nullptr;
FreeUPNPUrls(&urls);
} else {
LogPrintf("No valid UPnP IGDs found\n");
freeUPNPDevlist(devlist);
devlist = nullptr;
if (r != 0) {
FreeUPNPUrls(&urls);
}
}
return ret;
}
#endif // USE_UPNP
static void ThreadMapPort() {
do {
if (ProcessUpnp()) {
return;
}
} while (g_mapport_interrupt.sleep_for(PORT_MAPPING_RETRY_PERIOD));
}
void StartThreadMapPort() {
if (!g_mapport_thread.joinable()) {
assert(!g_mapport_interrupt);
g_mapport_thread =
std::thread(&util::TraceThread, "mapport", &ThreadMapPort);
}
}
static void DispatchMapPort() {
if (g_mapport_target_proto == MapPortProtoFlag::UPNP) {
StartThreadMapPort();
} else {
InterruptMapPort();
StopMapPort();
}
}
static void MapPortProtoSetEnabled(MapPortProtoFlag proto, bool enabled) {
if (enabled) {
g_mapport_target_proto |= proto;
} else {
g_mapport_target_proto &= ~proto;
}
}
void StartMapPort(bool use_upnp) {
MapPortProtoSetEnabled(MapPortProtoFlag::UPNP, use_upnp);
DispatchMapPort();
}
void InterruptMapPort() {
if (g_mapport_thread.joinable()) {
g_mapport_interrupt();
}
}
void StopMapPort() {
if (g_mapport_thread.joinable()) {
g_mapport_thread.join();
g_mapport_interrupt.reset();
}
}
#else // #if defined(USE_NATPMP) || defined(USE_UPNP)
void StartMapPort(bool use_upnp) {
// Intentionally left blank.
}
void InterruptMapPort() {
// Intentionally left blank.
}
void StopMapPort() {
// Intentionally left blank.
}
#endif // #if defined(USE_NATPMP) || defined(USE_UPNP)
<commit_msg>net: Add NAT-PMP to port mapping loop<commit_after>// Copyright (c) 2011-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <mapport.h>
#include <clientversion.h>
#include <logging.h>
#include <net.h>
#include <netaddress.h>
#include <netbase.h>
#include <threadinterrupt.h>
#include <util/system.h>
#include <util/thread.h>
#ifdef USE_NATPMP
#include <compat.h>
#include <natpmp.h>
#endif // USE_NATPMP
#ifdef USE_UPNP
#include <miniupnpc/miniupnpc.h>
#include <miniupnpc/upnpcommands.h>
#include <miniupnpc/upnperrors.h>
// The minimum supported miniUPnPc API version is set to 10. This keeps
// compatibility with Ubuntu 16.04 LTS and Debian 8 libminiupnpc-dev packages.
static_assert(MINIUPNPC_API_VERSION >= 10,
"miniUPnPc API version >= 10 assumed");
#endif // USE_UPNP
#include <atomic>
#include <cassert>
#include <chrono>
#include <functional>
#include <string>
#include <thread>
#if defined(USE_NATPMP) || defined(USE_UPNP)
static CThreadInterrupt g_mapport_interrupt;
static std::thread g_mapport_thread;
static std::atomic_uint g_mapport_enabled_protos{MapPortProtoFlag::NONE};
static std::atomic<MapPortProtoFlag> g_mapport_current_proto{
MapPortProtoFlag::NONE};
using namespace std::chrono_literals;
static constexpr auto PORT_MAPPING_REANNOUNCE_PERIOD{20min};
static constexpr auto PORT_MAPPING_RETRY_PERIOD{5min};
#ifdef USE_NATPMP
static uint16_t g_mapport_external_port = 0;
static bool NatpmpInit(natpmp_t *natpmp) {
const int r_init = initnatpmp(natpmp, /* detect gateway automatically */ 0,
/* forced gateway - NOT APPLIED*/ 0);
if (r_init == 0) {
return true;
}
LogPrintf("natpmp: initnatpmp() failed with %d error.\n", r_init);
return false;
}
static bool NatpmpDiscover(natpmp_t *natpmp,
struct in_addr &external_ipv4_addr) {
const int r_send = sendpublicaddressrequest(natpmp);
if (r_send == 2 /* OK */) {
int r_read;
natpmpresp_t response;
do {
r_read = readnatpmpresponseorretry(natpmp, &response);
} while (r_read == NATPMP_TRYAGAIN);
if (r_read == 0) {
external_ipv4_addr = response.pnu.publicaddress.addr;
return true;
} else if (r_read == NATPMP_ERR_NOGATEWAYSUPPORT) {
LogPrintf("natpmp: The gateway does not support NAT-PMP.\n");
} else {
LogPrintf("natpmp: readnatpmpresponseorretry() for public address "
"failed with %d error.\n",
r_read);
}
} else {
LogPrintf("natpmp: sendpublicaddressrequest() failed with %d error.\n",
r_send);
}
return false;
}
static bool NatpmpMapping(natpmp_t *natpmp,
const struct in_addr &external_ipv4_addr,
uint16_t private_port, bool &external_ip_discovered) {
const uint16_t suggested_external_port =
g_mapport_external_port ? g_mapport_external_port : private_port;
const int r_send =
sendnewportmappingrequest(natpmp, NATPMP_PROTOCOL_TCP, private_port,
suggested_external_port, 3600 /*seconds*/);
if (r_send == 12 /* OK */) {
int r_read;
natpmpresp_t response;
do {
r_read = readnatpmpresponseorretry(natpmp, &response);
} while (r_read == NATPMP_TRYAGAIN);
if (r_read == 0) {
auto pm = response.pnu.newportmapping;
if (private_port == pm.privateport && pm.lifetime > 0) {
g_mapport_external_port = pm.mappedpublicport;
const CService external{external_ipv4_addr,
pm.mappedpublicport};
if (!external_ip_discovered && fDiscover) {
AddLocal(external, LOCAL_MAPPED);
external_ip_discovered = true;
}
LogPrintf(
"natpmp: Port mapping successful. External address = %s\n",
external.ToString());
return true;
} else {
LogPrintf("natpmp: Port mapping failed.\n");
}
} else if (r_read == NATPMP_ERR_NOGATEWAYSUPPORT) {
LogPrintf("natpmp: The gateway does not support NAT-PMP.\n");
} else {
LogPrintf("natpmp: readnatpmpresponseorretry() for port mapping "
"failed with %d error.\n",
r_read);
}
} else {
LogPrintf("natpmp: sendnewportmappingrequest() failed with %d error.\n",
r_send);
}
return false;
}
[[maybe_unused]] static bool ProcessNatpmp() {
bool ret = false;
natpmp_t natpmp;
struct in_addr external_ipv4_addr;
if (NatpmpInit(&natpmp) && NatpmpDiscover(&natpmp, external_ipv4_addr)) {
bool external_ip_discovered = false;
const uint16_t private_port = GetListenPort();
do {
ret = NatpmpMapping(&natpmp, external_ipv4_addr, private_port,
external_ip_discovered);
} while (ret &&
g_mapport_interrupt.sleep_for(PORT_MAPPING_REANNOUNCE_PERIOD));
g_mapport_interrupt.reset();
const int r_send = sendnewportmappingrequest(
&natpmp, NATPMP_PROTOCOL_TCP, private_port, g_mapport_external_port,
/* remove a port mapping */ 0);
g_mapport_external_port = 0;
if (r_send == 12 /* OK */) {
LogPrintf("natpmp: Port mapping removed successfully.\n");
} else {
LogPrintf(
"natpmp: sendnewportmappingrequest(0) failed with %d error.\n",
r_send);
}
}
closenatpmp(&natpmp);
return ret;
}
#endif // USE_NATPMP
#ifdef USE_UPNP
static bool ProcessUpnp() {
bool ret = false;
std::string port = strprintf("%u", GetListenPort());
const char *multicastif = nullptr;
const char *minissdpdpath = nullptr;
struct UPNPDev *devlist = nullptr;
char lanaddr[64];
int error = 0;
#if MINIUPNPC_API_VERSION < 14
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
#else
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, 2, &error);
#endif
struct UPNPUrls urls;
struct IGDdatas data;
int r;
r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
if (r == 1) {
if (fDiscover) {
char externalIPAddress[40];
r = UPNP_GetExternalIPAddress(
urls.controlURL, data.first.servicetype, externalIPAddress);
if (r != UPNPCOMMAND_SUCCESS) {
LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r);
} else {
if (externalIPAddress[0]) {
CNetAddr resolved;
if (LookupHost(externalIPAddress, resolved, false)) {
LogPrintf("UPnP: ExternalIPAddress = %s\n",
resolved.ToString());
AddLocal(resolved, LOCAL_MAPPED);
}
} else {
LogPrintf("UPnP: GetExternalIPAddress failed.\n");
}
}
}
std::string strDesc = PACKAGE_NAME " " + FormatFullVersion();
do {
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr,
strDesc.c_str(), "TCP", 0, "0");
if (r != UPNPCOMMAND_SUCCESS) {
ret = false;
LogPrintf(
"AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
port, port, lanaddr, r, strupnperror(r));
break;
} else {
ret = true;
LogPrintf("UPnP Port Mapping successful.\n");
}
} while (g_mapport_interrupt.sleep_for(PORT_MAPPING_REANNOUNCE_PERIOD));
g_mapport_interrupt.reset();
r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), "TCP", 0);
LogPrintf("UPNP_DeletePortMapping() returned: %d\n", r);
freeUPNPDevlist(devlist);
devlist = nullptr;
FreeUPNPUrls(&urls);
} else {
LogPrintf("No valid UPnP IGDs found\n");
freeUPNPDevlist(devlist);
devlist = nullptr;
if (r != 0) {
FreeUPNPUrls(&urls);
}
}
return ret;
}
#endif // USE_UPNP
static void ThreadMapPort() {
bool ok;
do {
ok = false;
#ifdef USE_UPNP
// High priority protocol.
if (g_mapport_enabled_protos & MapPortProtoFlag::UPNP) {
g_mapport_current_proto = MapPortProtoFlag::UPNP;
ok = ProcessUpnp();
if (ok) {
continue;
}
}
#endif // USE_UPNP
#ifdef USE_NATPMP
// Low priority protocol.
if (g_mapport_enabled_protos & MapPortProtoFlag::NAT_PMP) {
g_mapport_current_proto = MapPortProtoFlag::NAT_PMP;
ok = ProcessNatpmp();
if (ok) {
continue;
}
}
#endif // USE_NATPMP
g_mapport_current_proto = MapPortProtoFlag::NONE;
if (g_mapport_enabled_protos == MapPortProtoFlag::NONE) {
return;
}
} while (ok || g_mapport_interrupt.sleep_for(PORT_MAPPING_RETRY_PERIOD));
}
void StartThreadMapPort() {
if (!g_mapport_thread.joinable()) {
assert(!g_mapport_interrupt);
g_mapport_thread =
std::thread(&util::TraceThread, "mapport", &ThreadMapPort);
}
}
static void DispatchMapPort() {
if (g_mapport_current_proto == MapPortProtoFlag::NONE &&
g_mapport_enabled_protos == MapPortProtoFlag::NONE) {
return;
}
if (g_mapport_current_proto == MapPortProtoFlag::NONE &&
g_mapport_enabled_protos != MapPortProtoFlag::NONE) {
StartThreadMapPort();
return;
}
if (g_mapport_current_proto != MapPortProtoFlag::NONE &&
g_mapport_enabled_protos == MapPortProtoFlag::NONE) {
InterruptMapPort();
StopMapPort();
return;
}
if (g_mapport_enabled_protos & g_mapport_current_proto) {
// Enabling another protocol does not cause switching from the currently
// used one.
return;
}
assert(g_mapport_thread.joinable());
assert(!g_mapport_interrupt);
// Interrupt a protocol-specific loop in the ThreadUpnp() or in the
// ThreadNatpmp() to force trying the next protocol in the ThreadMapPort()
// loop.
g_mapport_interrupt();
}
static void MapPortProtoSetEnabled(MapPortProtoFlag proto, bool enabled) {
if (enabled) {
g_mapport_enabled_protos |= proto;
} else {
g_mapport_enabled_protos &= ~proto;
}
}
void StartMapPort(bool use_upnp) {
MapPortProtoSetEnabled(MapPortProtoFlag::UPNP, use_upnp);
DispatchMapPort();
}
void InterruptMapPort() {
g_mapport_enabled_protos = MapPortProtoFlag::NONE;
if (g_mapport_thread.joinable()) {
g_mapport_interrupt();
}
}
void StopMapPort() {
if (g_mapport_thread.joinable()) {
g_mapport_thread.join();
g_mapport_interrupt.reset();
}
}
#else // #if defined(USE_NATPMP) || defined(USE_UPNP)
void StartMapPort(bool use_upnp) {
// Intentionally left blank.
}
void InterruptMapPort() {
// Intentionally left blank.
}
void StopMapPort() {
// Intentionally left blank.
}
#endif // #if defined(USE_NATPMP) || defined(USE_UPNP)
<|endoftext|> |
<commit_before>#ifndef TURBO_MEMORY_BLOCK_HPP
#define TURBO_MEMORY_BLOCK_HPP
#include <cstdint>
#include <memory>
#include <stdexcept>
#include <turbo/container/mpmc_ring_queue.hpp>
namespace turbo {
namespace memory {
class out_of_memory_error : public std::runtime_error
{
public:
explicit out_of_memory_error(const std::string& what);
explicit out_of_memory_error(const char* what);
};
class invalid_size_error : public std::invalid_argument
{
public:
explicit invalid_size_error(const std::string& what);
explicit invalid_size_error(const char* what);
};
class invalid_alignment_error : public std::invalid_argument
{
public:
explicit invalid_alignment_error(const std::string& what);
explicit invalid_alignment_error(const char* what);
};
class invalid_pointer_error : public std::invalid_argument
{
public:
explicit invalid_pointer_error(const std::string& what);
explicit invalid_pointer_error(const char* what);
};
class block
{
public:
typedef std::uint32_t capacity_type;
block(std::size_t value_size, capacity_type capacity);
block(std::size_t value_size, capacity_type capacity, std::size_t alignment);
inline std::size_t get_usable_size() const { return usable_size_; }
inline const void* get_base_address() const { return base_; }
void* allocate();
void free(void* pointer);
private:
typedef turbo::container::mpmc_ring_queue<capacity_type> free_list_type;
std::size_t value_size_;
std::size_t capacity_;
std::size_t usable_size_;
std::unique_ptr<std::uint8_t[]> storage_;
std::uint8_t* base_;
free_list_type free_list_;
};
} // namespace memory
} // namespace turbo
#endif
<commit_msg>explicitly deleted the default constructor, copy & move constructors and copy & move assignment operators<commit_after>#ifndef TURBO_MEMORY_BLOCK_HPP
#define TURBO_MEMORY_BLOCK_HPP
#include <cstdint>
#include <memory>
#include <stdexcept>
#include <turbo/container/mpmc_ring_queue.hpp>
namespace turbo {
namespace memory {
class out_of_memory_error : public std::runtime_error
{
public:
explicit out_of_memory_error(const std::string& what);
explicit out_of_memory_error(const char* what);
};
class invalid_size_error : public std::invalid_argument
{
public:
explicit invalid_size_error(const std::string& what);
explicit invalid_size_error(const char* what);
};
class invalid_alignment_error : public std::invalid_argument
{
public:
explicit invalid_alignment_error(const std::string& what);
explicit invalid_alignment_error(const char* what);
};
class invalid_pointer_error : public std::invalid_argument
{
public:
explicit invalid_pointer_error(const std::string& what);
explicit invalid_pointer_error(const char* what);
};
class block
{
public:
typedef std::uint32_t capacity_type;
block(std::size_t value_size, capacity_type capacity);
block(std::size_t value_size, capacity_type capacity, std::size_t alignment);
inline std::size_t get_usable_size() const { return usable_size_; }
inline const void* get_base_address() const { return base_; }
void* allocate();
void free(void* pointer);
private:
typedef turbo::container::mpmc_ring_queue<capacity_type> free_list_type;
block() = delete;
block(const block&) = delete;
block(block&&) = delete;
block& operator=(const block&) = delete;
block& operator=(block&&) = delete;
std::size_t value_size_;
std::size_t capacity_;
std::size_t usable_size_;
std::unique_ptr<std::uint8_t[]> storage_;
std::uint8_t* base_;
free_list_type free_list_;
};
} // namespace memory
} // namespace turbo
#endif
<|endoftext|> |
<commit_before>/*
*
* Copyright 2018 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <grpc/support/port_platform.h>
#include <grpc/slice_buffer.h>
#include "src/core/lib/security/security_connector/load_system_roots_linux.h"
#ifdef GPR_LINUX
#include "src/core/lib/security/security_connector/load_system_roots.h"
#include <dirent.h>
#include <fcntl.h>
#include <stdbool.h>
#include <string.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/gprpp/global_config.h"
#include "src/core/lib/gprpp/inlined_vector.h"
#include "src/core/lib/iomgr/load_file.h"
GPR_GLOBAL_CONFIG_DEFINE_STRING(grpc_system_ssl_roots_dir, "",
"Custom directory to SSL Roots");
namespace grpc_core {
namespace {
const char* kLinuxCertFiles[] = {
"/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/certs/ca-bundle.crt",
"/etc/ssl/ca-bundle.pem", "/etc/pki/tls/cacert.pem",
"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"};
const char* kLinuxCertDirectories[] = {
"/etc/ssl/certs", "/system/etc/security/cacerts", "/usr/local/share/certs",
"/etc/pki/tls/certs", "/etc/openssl/certs"};
grpc_slice GetSystemRootCerts() {
grpc_slice valid_bundle_slice = grpc_empty_slice();
size_t num_cert_files_ = GPR_ARRAY_SIZE(kLinuxCertFiles);
for (size_t i = 0; i < num_cert_files_; i++) {
grpc_error* error =
grpc_load_file(kLinuxCertFiles[i], 1, &valid_bundle_slice);
if (error == GRPC_ERROR_NONE) {
return valid_bundle_slice;
} else {
GRPC_ERROR_UNREF(error);
}
GRPC_ERROR_UNREF(error);
}
return grpc_empty_slice();
}
} // namespace
void GetAbsoluteFilePath(const char* valid_file_dir,
const char* file_entry_name, char* path_buffer) {
if (valid_file_dir != nullptr && file_entry_name != nullptr) {
int path_len = snprintf(path_buffer, MAXPATHLEN, "%s/%s", valid_file_dir,
file_entry_name);
if (path_len == 0) {
gpr_log(GPR_ERROR, "failed to get absolute path for file: %s",
file_entry_name);
}
}
}
grpc_slice CreateRootCertsBundle(const char* certs_directory) {
grpc_slice bundle_slice = grpc_empty_slice();
if (certs_directory == nullptr) {
return bundle_slice;
}
DIR* ca_directory = opendir(certs_directory);
if (ca_directory == nullptr) {
return bundle_slice;
}
struct FileData {
char path[MAXPATHLEN];
off_t size;
};
InlinedVector<FileData, 2> roots_filenames;
size_t total_bundle_size = 0;
struct dirent* directory_entry;
while ((directory_entry = readdir(ca_directory)) != nullptr) {
struct stat dir_entry_stat;
const char* file_entry_name = directory_entry->d_name;
FileData file_data;
GetAbsoluteFilePath(certs_directory, file_entry_name, file_data.path);
int stat_return = stat(file_data.path, &dir_entry_stat);
if (stat_return == -1 || !S_ISREG(dir_entry_stat.st_mode)) {
// no subdirectories.
if (stat_return == -1) {
gpr_log(GPR_ERROR, "failed to get status for file: %s", file_data.path);
}
continue;
}
file_data.size = dir_entry_stat.st_size;
total_bundle_size += file_data.size;
roots_filenames.push_back(file_data);
}
closedir(ca_directory);
char* bundle_string = static_cast<char*>(gpr_zalloc(total_bundle_size + 1));
size_t bytes_read = 0;
for (size_t i = 0; i < roots_filenames.size(); i++) {
int file_descriptor = open(roots_filenames[i].path, O_RDONLY);
if (file_descriptor != -1) {
// Read file into bundle.
size_t cert_file_size = roots_filenames[i].size;
int read_ret =
read(file_descriptor, bundle_string + bytes_read, cert_file_size);
if (read_ret != -1) {
bytes_read += read_ret;
} else {
gpr_log(GPR_ERROR, "failed to read file: %s", roots_filenames[i].path);
}
}
}
bundle_slice = grpc_slice_new(bundle_string, bytes_read, gpr_free);
return bundle_slice;
}
grpc_slice LoadSystemRootCerts() {
grpc_slice result = grpc_empty_slice();
// Prioritize user-specified custom directory if flag is set.
UniquePtr<char> custom_dir = GPR_GLOBAL_CONFIG_GET(grpc_system_ssl_roots_dir);
if (strlen(custom_dir.get()) > 0) {
result = CreateRootCertsBundle(custom_dir.get());
}
// If the custom directory is empty/invalid/not specified, fallback to
// distribution-specific directory.
if (GRPC_SLICE_IS_EMPTY(result)) {
result = GetSystemRootCerts();
}
if (GRPC_SLICE_IS_EMPTY(result)) {
for (size_t i = 0; i < GPR_ARRAY_SIZE(kLinuxCertDirectories); i++) {
result = CreateRootCertsBundle(kLinuxCertDirectories[i]);
if (!GRPC_SLICE_IS_EMPTY(result)) {
break;
}
}
}
return result;
}
} // namespace grpc_core
#endif /* GPR_LINUX */
<commit_msg>Revert "Fix error object memory leak in GetSystemRootCerts"<commit_after>/*
*
* Copyright 2018 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <grpc/support/port_platform.h>
#include <grpc/slice_buffer.h>
#include "src/core/lib/security/security_connector/load_system_roots_linux.h"
#ifdef GPR_LINUX
#include "src/core/lib/security/security_connector/load_system_roots.h"
#include <dirent.h>
#include <fcntl.h>
#include <stdbool.h>
#include <string.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/gprpp/global_config.h"
#include "src/core/lib/gprpp/inlined_vector.h"
#include "src/core/lib/iomgr/load_file.h"
GPR_GLOBAL_CONFIG_DEFINE_STRING(grpc_system_ssl_roots_dir, "",
"Custom directory to SSL Roots");
namespace grpc_core {
namespace {
const char* kLinuxCertFiles[] = {
"/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/certs/ca-bundle.crt",
"/etc/ssl/ca-bundle.pem", "/etc/pki/tls/cacert.pem",
"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"};
const char* kLinuxCertDirectories[] = {
"/etc/ssl/certs", "/system/etc/security/cacerts", "/usr/local/share/certs",
"/etc/pki/tls/certs", "/etc/openssl/certs"};
grpc_slice GetSystemRootCerts() {
grpc_slice valid_bundle_slice = grpc_empty_slice();
size_t num_cert_files_ = GPR_ARRAY_SIZE(kLinuxCertFiles);
for (size_t i = 0; i < num_cert_files_; i++) {
grpc_error* error =
grpc_load_file(kLinuxCertFiles[i], 1, &valid_bundle_slice);
if (error == GRPC_ERROR_NONE) {
return valid_bundle_slice;
} else {
GRPC_ERROR_UNREF(error);
}
}
return grpc_empty_slice();
}
} // namespace
void GetAbsoluteFilePath(const char* valid_file_dir,
const char* file_entry_name, char* path_buffer) {
if (valid_file_dir != nullptr && file_entry_name != nullptr) {
int path_len = snprintf(path_buffer, MAXPATHLEN, "%s/%s", valid_file_dir,
file_entry_name);
if (path_len == 0) {
gpr_log(GPR_ERROR, "failed to get absolute path for file: %s",
file_entry_name);
}
}
}
grpc_slice CreateRootCertsBundle(const char* certs_directory) {
grpc_slice bundle_slice = grpc_empty_slice();
if (certs_directory == nullptr) {
return bundle_slice;
}
DIR* ca_directory = opendir(certs_directory);
if (ca_directory == nullptr) {
return bundle_slice;
}
struct FileData {
char path[MAXPATHLEN];
off_t size;
};
InlinedVector<FileData, 2> roots_filenames;
size_t total_bundle_size = 0;
struct dirent* directory_entry;
while ((directory_entry = readdir(ca_directory)) != nullptr) {
struct stat dir_entry_stat;
const char* file_entry_name = directory_entry->d_name;
FileData file_data;
GetAbsoluteFilePath(certs_directory, file_entry_name, file_data.path);
int stat_return = stat(file_data.path, &dir_entry_stat);
if (stat_return == -1 || !S_ISREG(dir_entry_stat.st_mode)) {
// no subdirectories.
if (stat_return == -1) {
gpr_log(GPR_ERROR, "failed to get status for file: %s", file_data.path);
}
continue;
}
file_data.size = dir_entry_stat.st_size;
total_bundle_size += file_data.size;
roots_filenames.push_back(file_data);
}
closedir(ca_directory);
char* bundle_string = static_cast<char*>(gpr_zalloc(total_bundle_size + 1));
size_t bytes_read = 0;
for (size_t i = 0; i < roots_filenames.size(); i++) {
int file_descriptor = open(roots_filenames[i].path, O_RDONLY);
if (file_descriptor != -1) {
// Read file into bundle.
size_t cert_file_size = roots_filenames[i].size;
int read_ret =
read(file_descriptor, bundle_string + bytes_read, cert_file_size);
if (read_ret != -1) {
bytes_read += read_ret;
} else {
gpr_log(GPR_ERROR, "failed to read file: %s", roots_filenames[i].path);
}
}
}
bundle_slice = grpc_slice_new(bundle_string, bytes_read, gpr_free);
return bundle_slice;
}
grpc_slice LoadSystemRootCerts() {
grpc_slice result = grpc_empty_slice();
// Prioritize user-specified custom directory if flag is set.
UniquePtr<char> custom_dir = GPR_GLOBAL_CONFIG_GET(grpc_system_ssl_roots_dir);
if (strlen(custom_dir.get()) > 0) {
result = CreateRootCertsBundle(custom_dir.get());
}
// If the custom directory is empty/invalid/not specified, fallback to
// distribution-specific directory.
if (GRPC_SLICE_IS_EMPTY(result)) {
result = GetSystemRootCerts();
}
if (GRPC_SLICE_IS_EMPTY(result)) {
for (size_t i = 0; i < GPR_ARRAY_SIZE(kLinuxCertDirectories); i++) {
result = CreateRootCertsBundle(kLinuxCertDirectories[i]);
if (!GRPC_SLICE_IS_EMPTY(result)) {
break;
}
}
}
return result;
}
} // namespace grpc_core
#endif /* GPR_LINUX */
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/eff_config/timing.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file timing.H
/// @brief Determine effective config for mss settings
///
// *HWP HWP Owner: Andre Marin <[email protected]>
// *HWP FW Owner: Brian Silver <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP
#ifndef _MSS_TIMING_H_
#define _MSS_TIMING_H_
#include <cstdint>
#include <fapi2.H>
namespace mss
{
enum GUARD_BAND
{
// Used for caclulating spd timing values - from JEDEC rounding algorithm
// Correction factor is 1% (for DDR3) or 2.5% (for DDR4)
// when doing integer math, we add-in the inverse correction factor
// Formula used for derivation:
// Guardband = 1000 * (1000* correction_factor) - 1
INVERSE_DDR3_CORRECTION_FACTOR = 989,
INVERSE_DDR4_CORRECTION_FACTOR = 974,
};
///
/// @brief Calculates timing value
/// @tparam T input and output type
/// @param[in] i_timing_mtb timing value in MTB units
/// @param[in] i_mtb_multiplier SPD medium timebase
/// @param[in] i_timing_ftb fine offset of timing value
/// @param[in] i_ftb_multiplier SPD fine timebase
/// @return the timing value in picoseconds
///
template<typename T>
inline T calc_timing_from_timebase(const T i_timing_mtb,
const T i_mtb_multiplier,
const T i_timing_ftb,
const T i_ftb_multiplier)
{
// JEDEC algorithm
T l_timing_val = i_timing_mtb * i_mtb_multiplier;
T l_fine_offset = i_timing_ftb * i_ftb_multiplier;
return l_timing_val + l_fine_offset;
}
///
/// @brief Returns clock cycles
/// @tparam T input and output type
/// @param[in] timing_in_ps timing parameter in ps
/// @param[in] tck_in_ps clock period in ps
/// @param[in] inverse_corr_factor inverse correction factor (defined by JEDEC)
/// @return the clock cycles of timing parameter (provided in ps)
/// @note DDR4 SPD Contents Rounding Algorithm
/// @note Item 2220.46
///
template<typename T>
inline T calc_nck(T timing_in_ps, T tck_in_ps, T inverse_corr_factor)
{
// Preliminary nCK calculation, scaled by 1000
T temp_nck = timing_in_ps * 1000 / tck_in_ps;
// Apply inverse of correction factor percentage
temp_nck += inverse_corr_factor;
return temp_nck / 1000;
}
/// @brief Calculates refresh interval time 1 (tREFI 1)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode calc_trefi1(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
uint64_t& o_value);
/// @brief Calculates refresh interval time 2 (tREFI 2)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode calc_trefi2(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
uint64_t& o_value);
/// @brief Calculates refresh interval time 4 (tREFI 4)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode calc_trefi4( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
uint64_t& o_value);
} // mss
#endif
<commit_msg>Fix throttle procedure & MSS attribute clean up<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/eff_config/timing.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file timing.H
/// @brief Determine effective config for mss settings
///
// *HWP HWP Owner: Andre Marin <[email protected]>
// *HWP FW Owner: Brian Silver <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP
#ifndef _MSS_TIMING_H_
#define _MSS_TIMING_H_
#include <cstdint>
#include <fapi2.H>
namespace mss
{
enum GUARD_BAND
{
// Used for caclulating spd timing values - from JEDEC rounding algorithm
// Correction factor is 1% (for DDR3) or 2.5% (for DDR4)
// when doing integer math, we add-in the inverse correction factor
// Formula used for derivation:
// Guardband = 1000 * (1000* correction_factor) - 1
INVERSE_DDR3_CORRECTION_FACTOR = 989,
INVERSE_DDR4_CORRECTION_FACTOR = 974,
};
///
/// @brief Calculates timing value
/// @tparam T input and output type
/// @param[in] i_timing_mtb timing value in MTB units
/// @param[in] i_mtb_multiplier SPD medium timebase
/// @param[in] i_timing_ftb fine offset of timing value
/// @param[in] i_ftb_multiplier SPD fine timebase
/// @return the timing value in picoseconds
///
template<typename T>
inline T calc_timing_from_timebase(const T i_timing_mtb,
const T i_mtb_multiplier,
const T i_timing_ftb,
const T i_ftb_multiplier)
{
// JEDEC algorithm
T l_timing_val = i_timing_mtb * i_mtb_multiplier;
T l_fine_offset = i_timing_ftb * i_ftb_multiplier;
return l_timing_val + l_fine_offset;
}
///
/// @brief Returns clock cycles
/// @tparam T input and output type
/// @param[in] timing_in_ps timing parameter in ps
/// @param[in] tck_in_ps clock period in ps
/// @param[in] inverse_corr_factor inverse correction factor (defined by JEDEC)
/// @return the clock cycles of timing parameter (provided in ps)
/// @note DDR4 SPD Contents Rounding Algorithm
/// @note Item 2220.46
///
template<typename T>
inline T calc_nck(T timing_in_ps, T tck_in_ps, T inverse_corr_factor)
{
// Preliminary nCK calculation, scaled by 1000
T temp_nck = timing_in_ps * 1000 / tck_in_ps;
// Apply inverse of correction factor percentage
temp_nck += inverse_corr_factor;
return temp_nck / 1000;
}
///
/// @brief Returns application clock period (tCK) based on dimm transfer rate
/// @tparam T output type
/// @param[in] i_target FAPI2 target
/// @param[out] o_tCK_in_ps application period in ps
/// @return fapi2::FAPI2_RC_SUCCESS if okay
///
template< typename T>
inline fapi2::ReturnCode clock_period(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
T& o_tCK_in_ps)
{
uint64_t l_dimm_transfer_rate = 0;
FAPI_TRY( freq(find_target<fapi2::TARGET_TYPE_MCBIST>(i_target),
l_dimm_transfer_rate) );
o_tCK_in_ps = freq_to_ps(l_dimm_transfer_rate);
fapi_try_exit:
return fapi2::current_err;
}
/// @brief Calculates refresh interval time 1 (tREFI 1)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode calc_trefi1(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
uint64_t& o_value);
/// @brief Calculates refresh interval time 2 (tREFI 2)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode calc_trefi2(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
uint64_t& o_value);
/// @brief Calculates refresh interval time 4 (tREFI 4)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode calc_trefi4( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
uint64_t& o_value);
} // mss
#endif
<|endoftext|> |
<commit_before>// includes & usings {{{
#include "peerdfs.hh"
#include "../network/asyncnetwork.hh"
#include "../network/p2p.hh"
#include "../common/settings.hh"
#include "../common/definitions.hh"
#include "../messages/factory.hh"
#include "../messages/boost_impl.hh"
#include <boost/range/adaptor/map.hpp>
#include <boost/asio.hpp>
#include <algorithm>
#include <iterator>
#include <memory>
#include <fstream>
#include <cstdio>
#include <dirent.h>
#include <unistd.h>
using namespace eclipse;
using namespace eclipse::messages;
using namespace eclipse::network;
using namespace boost::asio;
using namespace std;
// }}}
namespace eclipse {
// Constructor & destructor {{{
PeerDFS::PeerDFS () : Node () {
Settings& setted = context.settings;
int port = setted.get<int>("network.ports.internal");
size = setted.get<vec_str>("network.nodes").size();
disk_path = setted.get<string>("path.scratch");
replica = setted.get<int>("filesystem.replica");
nodes = setted.get<vector<string>>("network.nodes");
network = new AsyncNetwork<P2P>(this, port);
boundaries.reset( new Histogram {size, 0});
boundaries->initialize();
directory.init_db();
}
PeerDFS::~PeerDFS() { }
// }}}
// establish {{{
bool PeerDFS::establish () {
logger->info ("Running Eclipse id=%d", id);
network->establish();
while (not connected) sleep(1);
return true;
}
// }}}
// insert {{{
void PeerDFS::insert (uint32_t hash_key, std::string name, std::string v) {
int which_node = boundaries->get_index(hash_key);
if (which_node == id) {
logger->info ("[DFS] Saving locally KEY: %s", name.c_str());
string file_path = disk_path + string("/") + name;
ofstream file (file_path);
file << v;
file.close();
} else {
logger->info ("[DFS] Forwaring KEY: %s -> %d", name.c_str(), which_node);
KeyValue kv (hash_key, name, v);
network->send(which_node, &kv);
}
}
// }}}
// request {{{
void PeerDFS::request (uint32_t key, string name , req_func f) {
int idx = boundaries->get_index(key);
if (idx != id) {
KeyRequest k_req (name);
k_req.set_origin (id);
network->send (idx, &k_req);
requested_blocks.insert ({name, f});
} else {
ifstream in (disk_path + string("/") + name);
string value ((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
in.close();
f(name, value);
}
}
// }}}
// close {{{
void PeerDFS::close() { exit(EXIT_SUCCESS); }
// }}}
// process (KeyValue* m) {{{
template<> void PeerDFS::process (KeyValue* m) {
auto key = m->key;
auto name = m->name;
int which_node = boundaries->get_index(key);
if (which_node == id or m->destination == id) {
logger->info ("Instering key = %s", name.c_str());
insert(key, m->name, m->value);
}
if (requested_blocks.find(name) != requested_blocks.end()){
logger->info ("Executing func");
requested_blocks[name](name, m->value);
requested_blocks.erase(name);
}
}
// }}}
// process (KeyRequest* m) {{{
template<> void PeerDFS::process (KeyRequest* m) {
logger->info ("Arrived req key = %s", m->key.c_str());
string& key = m->key;
string value;
ifstream in (disk_path + string("/") + key);
in >> value;
in.close();
KeyValue kv (0, key, value);
kv.destination = m->origin;
network->send(m->origin, &kv);
}
// }}}
// process (Control* m) {{{
template<> void PeerDFS::process (Control* m) {
switch (m->type) {
case messages::SHUTDOWN:
this->close();
break;
case messages::RESTART:
break;
}
}
// }}}
// process (BlockInfo* m) {{{
template<> void PeerDFS::process (BlockInfo* m) {
string file_path = disk_path + string("/") + m->block_name;
ofstream file (file_path);
file << m->content;
file.close();
logger->info("ideal host = %s", m->node.c_str());
logger->info("real host = %d", id);
}
// }}}
// process (BlockDel* m) {{{
template<> void PeerDFS::process (BlockDel* m) {
string block_name = m->block_name;
string block_path = disk_path + string("/") + block_name;
remove(block_path.c_str());
}
// }}}
// on_read (Message*) {{{
void PeerDFS::on_read (Message* m, int) {
string type = m->get_type();
if (type == "KeyValue") {
auto m_ = dynamic_cast<KeyValue*>(m);
process(m_);
} else if (type == "Control") {
auto m_ = dynamic_cast<Control*>(m);
process(m_);
} else if (type == "KeyRequest") {
auto m_ = dynamic_cast<KeyRequest*>(m);
process(m_);
} else if (type == "BlockInfo") {
auto m_ = dynamic_cast<BlockInfo*>(m);
process(m_);
} else if (type == "BlockDel") {
auto m_ = dynamic_cast<BlockDel*>(m);
process(m_);
}
}
// }}}
// {{{ on_connect
void PeerDFS::on_connect () {
connected = true;
logger->info ("Network established id=%d", id);
}
// }}}
// on_disconnect {{{
void PeerDFS::on_disconnect (int id) {
}
// }}}
// insert_file {{{
bool PeerDFS::insert_file (messages::FileInfo* f) {
bool ret = directory.file_exist(f->file_name.c_str());
if (ret) {
logger->info ("File:%s exists in db, ret = %i", f->file_name.c_str(), ret);
return false;
}
directory.insert_file_metadata(*f);
logger->info ("Saving to SQLite db");
return true;
}
// }}}
// insert_block {{{
bool PeerDFS::insert_block (messages::BlockInfo* m) {
directory.insert_block_metadata(*m);
int which_node = boundaries->get_index(m->block_hash_key);
int tmp_node = which_node;
for(int i=0; i<replica; i++)
{
if(i%2 == 1)
{
tmp_node = (which_node + (i+1)/2 + nodes.size()) % nodes.size();
}
else
{
tmp_node = (which_node - i/2 + nodes.size()) % nodes.size();
}
uint32_t tmp_hash_key = boundaries->random_within_boundaries(tmp_node);
insert(tmp_hash_key, m->block_name, m->content);
sleep(1);
}
return true;
}
// }}}
// delete_block {{{
bool PeerDFS::delete_block (messages::BlockDel* m) {
directory.delete_block_metadata(m->file_name, m->block_seq);
int which_node = boundaries->get_index(m->block_hash_key);
int tmp_node = which_node;
for(int i=0; i<replica; i++)
{
if(i%2 == 1)
{
tmp_node = (which_node + (i+1)/2 + nodes.size()) % nodes.size();
}
else
{
tmp_node = (which_node - i/2 + nodes.size()) % nodes.size();
}
if(id == tmp_node)
{
string block_name = m->block_name;
string block_path = disk_path + string("/") + block_name;
remove(block_path.c_str());
}
else
{
network->send(tmp_node, m);
}
}
return true;
}
// }}}
// delete_file {{{
bool PeerDFS::delete_file (messages::FileDel* f) {
bool ret = directory.file_exist(f->file_name.c_str());
if (!ret) {
logger->info ("File:%s doesn't exist in db, ret = %i", f->file_name.c_str(),
ret);
return false;
}
directory.delete_file_metadata(f->file_name);
logger->info ("Removing from SQLite db");
return true;
}
// }}}
// request_file {{{
FileDescription PeerDFS::request_file (messages::FileRequest* m) {
string file_name = m->file_name;
FileInfo fi;
fi.num_block = 0;
FileDescription fd;
fd.file_name = file_name;
directory.select_file_metadata(file_name, &fi);
int num_blocks = fi.num_block;
for (int i = 0; i< num_blocks; i++) {
BlockInfo bi;
directory.select_block_metadata (file_name, i, &bi);
string block_name = bi.block_name;
fd.blocks.push_back(block_name);
fd.hash_keys.push_back(bi.block_hash_key);
}
return fd;
}
// }}}
// list {{{
bool PeerDFS::list (messages::FileList* m) {
directory.select_all_file_metadata(m->data);
return true;
}
// }}}
// format {{{
bool PeerDFS::format () {
logger->info ("Formating DFS");
string fs_path = context.settings.get<string>("path.scratch");
string md_path = context.settings.get<string>("path.metadata");
DIR *theFolder = opendir(fs_path.c_str());
struct dirent *next_file;
char filepath[256] = {0};
while ( (next_file = readdir(theFolder)) != NULL ) {
sprintf(filepath, "%s/%s", fs_path.c_str(), next_file->d_name);
remove(filepath);
}
closedir(theFolder);
remove((md_path + "/metadata.db").c_str());
directory.init_db();
return true;
}
// }}}
// file_exist {{{
// FIXME need to think better name for this function
/**
*@brief check we have given file name on our database
*@param f is file name
*@return return true if found that file on database otherwise return false
*/
bool PeerDFS::file_exist (std::string file_name) {
return directory.file_exist(file_name.c_str());
}
// }}}
}
<commit_msg>DFS is now fast again<commit_after>// includes & usings {{{
#include "peerdfs.hh"
#include "../network/asyncnetwork.hh"
#include "../network/p2p.hh"
#include "../common/settings.hh"
#include "../common/definitions.hh"
#include "../messages/factory.hh"
#include "../messages/boost_impl.hh"
#include <boost/range/adaptor/map.hpp>
#include <boost/asio.hpp>
#include <algorithm>
#include <iterator>
#include <memory>
#include <fstream>
#include <cstdio>
#include <dirent.h>
#include <unistd.h>
using namespace eclipse;
using namespace eclipse::messages;
using namespace eclipse::network;
using namespace boost::asio;
using namespace std;
// }}}
namespace eclipse {
// Constructor & destructor {{{
PeerDFS::PeerDFS () : Node () {
Settings& setted = context.settings;
int port = setted.get<int>("network.ports.internal");
size = setted.get<vec_str>("network.nodes").size();
disk_path = setted.get<string>("path.scratch");
replica = setted.get<int>("filesystem.replica");
nodes = setted.get<vector<string>>("network.nodes");
network = new AsyncNetwork<P2P>(this, port);
boundaries.reset( new Histogram {size, 0});
boundaries->initialize();
directory.init_db();
}
PeerDFS::~PeerDFS() { }
// }}}
// establish {{{
bool PeerDFS::establish () {
logger->info ("Running Eclipse id=%d", id);
network->establish();
while (not connected) sleep(1);
return true;
}
// }}}
// insert {{{
void PeerDFS::insert (uint32_t hash_key, std::string name, std::string v) {
int which_node = boundaries->get_index(hash_key);
if (which_node == id) {
logger->info ("[DFS] Saving locally KEY: %s", name.c_str());
string file_path = disk_path + string("/") + name;
ofstream file (file_path);
file << v;
file.close();
} else {
logger->info ("[DFS] Forwaring KEY: %s -> %d", name.c_str(), which_node);
KeyValue kv (hash_key, name, v);
network->send(which_node, &kv);
}
}
// }}}
// request {{{
void PeerDFS::request (uint32_t key, string name , req_func f) {
int idx = boundaries->get_index(key);
if (idx != id) {
KeyRequest k_req (name);
k_req.set_origin (id);
network->send (idx, &k_req);
requested_blocks.insert ({name, f});
} else {
ifstream in (disk_path + string("/") + name);
string value ((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
in.close();
f(name, value);
}
}
// }}}
// close {{{
void PeerDFS::close() { exit(EXIT_SUCCESS); }
// }}}
// process (KeyValue* m) {{{
template<> void PeerDFS::process (KeyValue* m) {
auto key = m->key;
auto name = m->name;
int which_node = boundaries->get_index(key);
if (which_node == id or m->destination == id) {
logger->info ("Instering key = %s", name.c_str());
insert(key, m->name, m->value);
}
if (requested_blocks.find(name) != requested_blocks.end()){
logger->info ("Executing func");
requested_blocks[name](name, m->value);
requested_blocks.erase(name);
}
}
// }}}
// process (KeyRequest* m) {{{
template<> void PeerDFS::process (KeyRequest* m) {
logger->info ("Arrived req key = %s", m->key.c_str());
string& key = m->key;
string value;
ifstream in (disk_path + string("/") + key);
in >> value;
in.close();
KeyValue kv (0, key, value);
kv.destination = m->origin;
network->send(m->origin, &kv);
}
// }}}
// process (Control* m) {{{
template<> void PeerDFS::process (Control* m) {
switch (m->type) {
case messages::SHUTDOWN:
this->close();
break;
case messages::RESTART:
break;
}
}
// }}}
// process (BlockInfo* m) {{{
template<> void PeerDFS::process (BlockInfo* m) {
string file_path = disk_path + string("/") + m->block_name;
ofstream file (file_path);
file << m->content;
file.close();
logger->info("ideal host = %s", m->node.c_str());
logger->info("real host = %d", id);
}
// }}}
// process (BlockDel* m) {{{
template<> void PeerDFS::process (BlockDel* m) {
string block_name = m->block_name;
string block_path = disk_path + string("/") + block_name;
remove(block_path.c_str());
}
// }}}
// on_read (Message*) {{{
void PeerDFS::on_read (Message* m, int) {
string type = m->get_type();
if (type == "KeyValue") {
auto m_ = dynamic_cast<KeyValue*>(m);
process(m_);
} else if (type == "Control") {
auto m_ = dynamic_cast<Control*>(m);
process(m_);
} else if (type == "KeyRequest") {
auto m_ = dynamic_cast<KeyRequest*>(m);
process(m_);
} else if (type == "BlockInfo") {
auto m_ = dynamic_cast<BlockInfo*>(m);
process(m_);
} else if (type == "BlockDel") {
auto m_ = dynamic_cast<BlockDel*>(m);
process(m_);
}
}
// }}}
// {{{ on_connect
void PeerDFS::on_connect () {
connected = true;
logger->info ("Network established id=%d", id);
}
// }}}
// on_disconnect {{{
void PeerDFS::on_disconnect (int id) {
}
// }}}
// insert_file {{{
bool PeerDFS::insert_file (messages::FileInfo* f) {
bool ret = directory.file_exist(f->file_name.c_str());
if (ret) {
logger->info ("File:%s exists in db, ret = %i", f->file_name.c_str(), ret);
return false;
}
directory.insert_file_metadata(*f);
logger->info ("Saving to SQLite db");
return true;
}
// }}}
// insert_block {{{
bool PeerDFS::insert_block (messages::BlockInfo* m) {
directory.insert_block_metadata(*m);
int which_node = boundaries->get_index(m->block_hash_key);
int tmp_node = which_node;
for(int i=0; i<replica; i++)
{
if(i%2 == 1)
{
tmp_node = (which_node + (i+1)/2 + nodes.size()) % nodes.size();
}
else
{
tmp_node = (which_node - i/2 + nodes.size()) % nodes.size();
}
uint32_t tmp_hash_key = boundaries->random_within_boundaries(tmp_node);
insert(tmp_hash_key, m->block_name, m->content);
}
return true;
}
// }}}
// delete_block {{{
bool PeerDFS::delete_block (messages::BlockDel* m) {
directory.delete_block_metadata(m->file_name, m->block_seq);
int which_node = boundaries->get_index(m->block_hash_key);
int tmp_node = which_node;
for(int i=0; i<replica; i++)
{
if(i%2 == 1)
{
tmp_node = (which_node + (i+1)/2 + nodes.size()) % nodes.size();
}
else
{
tmp_node = (which_node - i/2 + nodes.size()) % nodes.size();
}
if(id == tmp_node)
{
string block_name = m->block_name;
string block_path = disk_path + string("/") + block_name;
remove(block_path.c_str());
}
else
{
network->send(tmp_node, m);
}
}
return true;
}
// }}}
// delete_file {{{
bool PeerDFS::delete_file (messages::FileDel* f) {
bool ret = directory.file_exist(f->file_name.c_str());
if (!ret) {
logger->info ("File:%s doesn't exist in db, ret = %i", f->file_name.c_str(),
ret);
return false;
}
directory.delete_file_metadata(f->file_name);
logger->info ("Removing from SQLite db");
return true;
}
// }}}
// request_file {{{
FileDescription PeerDFS::request_file (messages::FileRequest* m) {
string file_name = m->file_name;
FileInfo fi;
fi.num_block = 0;
FileDescription fd;
fd.file_name = file_name;
directory.select_file_metadata(file_name, &fi);
int num_blocks = fi.num_block;
for (int i = 0; i< num_blocks; i++) {
BlockInfo bi;
directory.select_block_metadata (file_name, i, &bi);
string block_name = bi.block_name;
fd.blocks.push_back(block_name);
fd.hash_keys.push_back(bi.block_hash_key);
}
return fd;
}
// }}}
// list {{{
bool PeerDFS::list (messages::FileList* m) {
directory.select_all_file_metadata(m->data);
return true;
}
// }}}
// format {{{
bool PeerDFS::format () {
logger->info ("Formating DFS");
string fs_path = context.settings.get<string>("path.scratch");
string md_path = context.settings.get<string>("path.metadata");
DIR *theFolder = opendir(fs_path.c_str());
struct dirent *next_file;
char filepath[256] = {0};
while ( (next_file = readdir(theFolder)) != NULL ) {
sprintf(filepath, "%s/%s", fs_path.c_str(), next_file->d_name);
remove(filepath);
}
closedir(theFolder);
remove((md_path + "/metadata.db").c_str());
directory.init_db();
return true;
}
// }}}
// file_exist {{{
// FIXME need to think better name for this function
/**
*@brief check we have given file name on our database
*@param f is file name
*@return return true if found that file on database otherwise return false
*/
bool PeerDFS::file_exist (std::string file_name) {
return directory.file_exist(file_name.c_str());
}
// }}}
}
<|endoftext|> |
<commit_before>/**
** \file object/object.cc
** \brief Implementation of object::Object.
*/
#include <algorithm>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/lambda/lambda.hpp>
#include <libport/containers.hh>
#include <libport/foreach.hh>
#include "object/object.hh"
#include "object/atom.hh"
#include "object/global-class.hh"
#include "object/urbi-exception.hh"
#include "runner/runner.hh"
namespace object
{
/*---------.
| Callers. |
`---------*/
rObject urbi_call(runner::Runner& r,
rObject& self,
libport::Symbol msg,
objects_type& args)
{
assertion(self);
rObject message = self->slot_get(msg);
if (!message)
throw LookupError(msg);
args.insert(args.begin(), self);
rObject res = r.apply(message, args);
args.erase(args.begin());
return res;
}
rObject urbi_call(runner::Runner& r,
rObject& self,
libport::Symbol msg)
{
objects_type args; // Call with no args.
return urbi_call(r, self, msg, args);
}
/*-------.
| kind. |
`-------*/
const char*
Object::string_of (Object::kind_type k)
{
switch (k)
{
#define CASE(What, Name) case kind_ ## What: return #Name; break;
APPLY_ON_ALL_PRIMITIVES(CASE);
#undef CASE
}
pabort("unreachable");
}
/*---------.
| Scopes. |
`---------*/
static boost::optional<rObject>
targetLookup(rObject obj,
const object::Object::key_type& slotName)
{
if (obj->own_slot_get(slotName, 0))
return boost::optional<rObject>(rObject());
if (rObject self = obj->own_slot_get(SYMBOL(self), rObject()))
if (self->slot_locate(slotName))
return self;
return boost::optional<rObject>();
}
rObject
target(rObject where, const libport::Symbol& name)
{
boost::function1<boost::optional<rObject>, rObject> lookup =
boost::bind(targetLookup, _1, name);
boost::optional<rObject> res = where->lookup(lookup);
if (!res)
throw object::LookupError(name);
if (!res.get())
return where;
return res.get();
}
// FIXME: implement in urbi too
rObject
Object::make_scope(const runner::Runner&, const rObject& parent)
{
rObject res = object::Object::fresh();
res->locals_set(true);
res->proto_add(parent ? parent : global_class);
// Mind the order!
res->proto_add(object::scope_class);
res->slot_set(SYMBOL(getSlot), scope_class->slot_get(SYMBOL(getSlot)));
res->slot_set(SYMBOL(locals), scope_class->slot_get(SYMBOL(locals)));
res->slot_set(SYMBOL(removeSlot), scope_class->slot_get(SYMBOL(removeSlot)));
res->slot_set(SYMBOL(setSlot), scope_class->slot_get(SYMBOL(setSlot)));
res->slot_set(SYMBOL(target), scope_class->slot_get(SYMBOL(target)));
res->slot_set(SYMBOL(updateSlot), scope_class->slot_get(SYMBOL(updateSlot)));
return res;
}
/*--------.
| Slots. |
`--------*/
template <typename R>
boost::optional<R>
Object::lookup(boost::function1<boost::optional<R>,
rObject> action,
objects_set_type& marks) const
{
if (!libport::mhas(marks, this))
{
marks.insert(this);
assertion(self());
if (boost::optional<R> res = action(self()))
return res;
foreach (const rObject& proto, protos_get())
if (boost::optional<R> res = proto->lookup(action, marks))
return res;
}
return boost::optional<R>();
}
template <typename R>
boost::optional<R>
Object::lookup(boost::function1<boost::optional<R>,
rObject> action) const
{
objects_set_type marks;
return lookup(action, marks);
}
namespace
{
static boost::optional<rObject>
slot_lookup(rObject obj, const Object::key_type& k)
{
assertion(obj);
if (obj->own_slot_get(k, 0))
return obj;
return boost::optional<rObject>();
}
}
rObject Object::slot_locate(const Object::key_type& k) const
{
boost::function1<boost::optional<rObject>, rObject> action =
boost::bind(slot_lookup, _1, k);
boost::optional<rObject> res = lookup(action);
return res ? res.get() : 0;
}
rObject
Object::safe_slot_locate(const key_type& k) const
{
rObject r = slot_locate(k);
if (!r)
throw LookupError(k);
return r;
}
const rObject&
Object::slot_get (const key_type& k) const
{
rObject cont = safe_slot_locate(k);
return cont->own_slot_get(k);
}
rObject&
Object::slot_get (const key_type& k)
{
return const_cast<rObject&>(const_cast<const Object*>(this)->slot_get(k));
}
Object&
Object::slot_set (const Object::key_type& k, rObject o)
{
if (libport::mhas(slots_, k))
throw RedefinitionError(k);
slots_[k] = o;
return *this;
}
void
slot_update (runner::Runner& r,
rObject& context,
const Object::key_type& k,
rObject o)
{
// The owner of the updated slot
rObject owner = context->safe_slot_locate(k);
// We have to determine where the new value must be stored,
// depending on whether the slot owner and the context are scopes.
// If both are scopes, update the original scope.
if (context->locals_ && owner->locals_get())
owner->own_slot_get(k) = o;
else if (context->locals_ && !owner->locals_get())
{
// Local->class: copyonwrite to "self" after evaluating it.
rObject self_obj = context->slot_get(SYMBOL(self));
assertion(self_obj);
objects_type self_args;
self_args.push_back (context);
rObject self = r.apply (self_obj, self_args);
assertion(self);
self->slot_set(k, o);
}
// If the context isn't a scope, copy on write.
else
context->slots_[k] = o;
};
rObject
Object::own_slot_get (const key_type& k, rObject def)
{
if (libport::mhas (slots_, k))
return own_slot_get (k);
return def;
}
/*-----------.
| Printing. |
`-----------*/
std::ostream&
Object::special_slots_dump (runner::Runner&, rObject, std::ostream& o) const
{
return o;
}
bool
Object::operator< (const Object& rhs) const
{
return this < &rhs;
}
// FIXME: A smart pointer to this (\a self) is required for now to
// avoid deleting this at the end of the method.
std::ostream&
Object::id_dump (const rObject& self,
std::ostream& o,
runner::Runner& r)
{
rObject id = self->slot_get(SYMBOL(id));
objects_type id_args;
id_args.push_back(self);
rObject data = r.apply(id, id_args);
std::string s = VALUE(data, String).name_get();
return o << s;
}
std::ostream&
dump (runner::Runner& runner, rObject r, std::ostream& o)
{
r->id_dump (r, o, runner);
/// Use xalloc/iword to store our current depth within the stream object.
static const long idx = o.xalloc();
static const long depth_max = 3;
long& current_depth = o.iword(idx);
/// Stop recursion at depth_max.
if (current_depth > depth_max)
return o << " <...>";
++current_depth;
o << " {" << libport::incendl;
if (r->protos_.begin () != r->protos_.end ())
{
o << "protos = ";
for (Object::protos_type::const_iterator i = r->protos_.begin ();
i != r->protos_.end (); ++i)
{
if (i != r->protos_.begin())
o << ", ";
(*i)->id_dump (*i, o, runner);
}
o << libport::iendl;
}
r->special_slots_dump (runner, r, o);
foreach(Object::slot_type s, r->slots_)
{
o << s.first << " = ";
dump(runner, s.second, o) << libport::iendl;
}
o << libport::decindent << '}';
//We can not reuse current_depth variable above according to spec.
o.iword(idx)--;
return o;
}
std::ostream&
print(runner::Runner& runner, rObject r, std::ostream& out)
{
try
{
rObject s = urbi_call(runner, r, SYMBOL(asString));
out << VALUE(s, String).name_get();
return out;
}
// Check if asString was found, especially for bootstrap: asString
// is implemented in urbi/urbi.u, but print is called to show
// result in the toplevel before its definition.
catch (LookupError&)
{
// If no asString method is supplied, print the unique id
out << std::hex << r.get() << std::endl;
return out;
}
}
bool
is_a(const rObject& c, const rObject& p)
{
return for_all_protos(c, boost::lambda::_1 == p);
}
} // namespace object
<commit_msg>Remove duplicated linefeed after objects uid.<commit_after>/**
** \file object/object.cc
** \brief Implementation of object::Object.
*/
#include <algorithm>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/lambda/lambda.hpp>
#include <libport/containers.hh>
#include <libport/foreach.hh>
#include "object/object.hh"
#include "object/atom.hh"
#include "object/global-class.hh"
#include "object/urbi-exception.hh"
#include "runner/runner.hh"
namespace object
{
/*---------.
| Callers. |
`---------*/
rObject urbi_call(runner::Runner& r,
rObject& self,
libport::Symbol msg,
objects_type& args)
{
assertion(self);
rObject message = self->slot_get(msg);
if (!message)
throw LookupError(msg);
args.insert(args.begin(), self);
rObject res = r.apply(message, args);
args.erase(args.begin());
return res;
}
rObject urbi_call(runner::Runner& r,
rObject& self,
libport::Symbol msg)
{
objects_type args; // Call with no args.
return urbi_call(r, self, msg, args);
}
/*-------.
| kind. |
`-------*/
const char*
Object::string_of (Object::kind_type k)
{
switch (k)
{
#define CASE(What, Name) case kind_ ## What: return #Name; break;
APPLY_ON_ALL_PRIMITIVES(CASE);
#undef CASE
}
pabort("unreachable");
}
/*---------.
| Scopes. |
`---------*/
static boost::optional<rObject>
targetLookup(rObject obj,
const object::Object::key_type& slotName)
{
if (obj->own_slot_get(slotName, 0))
return boost::optional<rObject>(rObject());
if (rObject self = obj->own_slot_get(SYMBOL(self), rObject()))
if (self->slot_locate(slotName))
return self;
return boost::optional<rObject>();
}
rObject
target(rObject where, const libport::Symbol& name)
{
boost::function1<boost::optional<rObject>, rObject> lookup =
boost::bind(targetLookup, _1, name);
boost::optional<rObject> res = where->lookup(lookup);
if (!res)
throw object::LookupError(name);
if (!res.get())
return where;
return res.get();
}
// FIXME: implement in urbi too
rObject
Object::make_scope(const runner::Runner&, const rObject& parent)
{
rObject res = object::Object::fresh();
res->locals_set(true);
res->proto_add(parent ? parent : global_class);
// Mind the order!
res->proto_add(object::scope_class);
res->slot_set(SYMBOL(getSlot), scope_class->slot_get(SYMBOL(getSlot)));
res->slot_set(SYMBOL(locals), scope_class->slot_get(SYMBOL(locals)));
res->slot_set(SYMBOL(removeSlot), scope_class->slot_get(SYMBOL(removeSlot)));
res->slot_set(SYMBOL(setSlot), scope_class->slot_get(SYMBOL(setSlot)));
res->slot_set(SYMBOL(target), scope_class->slot_get(SYMBOL(target)));
res->slot_set(SYMBOL(updateSlot), scope_class->slot_get(SYMBOL(updateSlot)));
return res;
}
/*--------.
| Slots. |
`--------*/
template <typename R>
boost::optional<R>
Object::lookup(boost::function1<boost::optional<R>,
rObject> action,
objects_set_type& marks) const
{
if (!libport::mhas(marks, this))
{
marks.insert(this);
assertion(self());
if (boost::optional<R> res = action(self()))
return res;
foreach (const rObject& proto, protos_get())
if (boost::optional<R> res = proto->lookup(action, marks))
return res;
}
return boost::optional<R>();
}
template <typename R>
boost::optional<R>
Object::lookup(boost::function1<boost::optional<R>,
rObject> action) const
{
objects_set_type marks;
return lookup(action, marks);
}
namespace
{
static boost::optional<rObject>
slot_lookup(rObject obj, const Object::key_type& k)
{
assertion(obj);
if (obj->own_slot_get(k, 0))
return obj;
return boost::optional<rObject>();
}
}
rObject Object::slot_locate(const Object::key_type& k) const
{
boost::function1<boost::optional<rObject>, rObject> action =
boost::bind(slot_lookup, _1, k);
boost::optional<rObject> res = lookup(action);
return res ? res.get() : 0;
}
rObject
Object::safe_slot_locate(const key_type& k) const
{
rObject r = slot_locate(k);
if (!r)
throw LookupError(k);
return r;
}
const rObject&
Object::slot_get (const key_type& k) const
{
rObject cont = safe_slot_locate(k);
return cont->own_slot_get(k);
}
rObject&
Object::slot_get (const key_type& k)
{
return const_cast<rObject&>(const_cast<const Object*>(this)->slot_get(k));
}
Object&
Object::slot_set (const Object::key_type& k, rObject o)
{
if (libport::mhas(slots_, k))
throw RedefinitionError(k);
slots_[k] = o;
return *this;
}
void
slot_update (runner::Runner& r,
rObject& context,
const Object::key_type& k,
rObject o)
{
// The owner of the updated slot
rObject owner = context->safe_slot_locate(k);
// We have to determine where the new value must be stored,
// depending on whether the slot owner and the context are scopes.
// If both are scopes, update the original scope.
if (context->locals_ && owner->locals_get())
owner->own_slot_get(k) = o;
else if (context->locals_ && !owner->locals_get())
{
// Local->class: copyonwrite to "self" after evaluating it.
rObject self_obj = context->slot_get(SYMBOL(self));
assertion(self_obj);
objects_type self_args;
self_args.push_back (context);
rObject self = r.apply (self_obj, self_args);
assertion(self);
self->slot_set(k, o);
}
// If the context isn't a scope, copy on write.
else
context->slots_[k] = o;
};
rObject
Object::own_slot_get (const key_type& k, rObject def)
{
if (libport::mhas (slots_, k))
return own_slot_get (k);
return def;
}
/*-----------.
| Printing. |
`-----------*/
std::ostream&
Object::special_slots_dump (runner::Runner&, rObject, std::ostream& o) const
{
return o;
}
bool
Object::operator< (const Object& rhs) const
{
return this < &rhs;
}
// FIXME: A smart pointer to this (\a self) is required for now to
// avoid deleting this at the end of the method.
std::ostream&
Object::id_dump (const rObject& self,
std::ostream& o,
runner::Runner& r)
{
rObject id = self->slot_get(SYMBOL(id));
objects_type id_args;
id_args.push_back(self);
rObject data = r.apply(id, id_args);
std::string s = VALUE(data, String).name_get();
return o << s;
}
std::ostream&
dump (runner::Runner& runner, rObject r, std::ostream& o)
{
r->id_dump (r, o, runner);
/// Use xalloc/iword to store our current depth within the stream object.
static const long idx = o.xalloc();
static const long depth_max = 3;
long& current_depth = o.iword(idx);
/// Stop recursion at depth_max.
if (current_depth > depth_max)
return o << " <...>";
++current_depth;
o << " {" << libport::incendl;
if (r->protos_.begin () != r->protos_.end ())
{
o << "protos = ";
for (Object::protos_type::const_iterator i = r->protos_.begin ();
i != r->protos_.end (); ++i)
{
if (i != r->protos_.begin())
o << ", ";
(*i)->id_dump (*i, o, runner);
}
o << libport::iendl;
}
r->special_slots_dump (runner, r, o);
foreach(Object::slot_type s, r->slots_)
{
o << s.first << " = ";
dump(runner, s.second, o) << libport::iendl;
}
o << libport::decindent << '}';
//We can not reuse current_depth variable above according to spec.
o.iword(idx)--;
return o;
}
std::ostream&
print(runner::Runner& runner, rObject r, std::ostream& out)
{
try
{
rObject s = urbi_call(runner, r, SYMBOL(asString));
out << VALUE(s, String).name_get();
return out;
}
// Check if asString was found, especially for bootstrap: asString
// is implemented in urbi/urbi.u, but print is called to show
// result in the toplevel before its definition.
catch (LookupError&)
{
// If no asString method is supplied, print the unique id
out << std::hex << r.get();
return out;
}
}
bool
is_a(const rObject& c, const rObject& p)
{
return for_all_protos(c, boost::lambda::_1 == p);
}
} // namespace object
<|endoftext|> |
<commit_before>/**
** \file object/object.cc
** \brief Implementation of object::Object.
*/
#include <algorithm>
#include <boost/assign.hpp> // for 'list_of'
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/lambda/lambda.hpp>
using namespace boost::assign; // bring 'list_of' into scope
#include <libport/containers.hh>
#include <libport/foreach.hh>
#include <object/atom.hh>
#include <object/dictionary-class.hh>
#include <object/float-class.hh>
#include <object/global-class.hh>
#include <object/hash-slots.hh>
#include <object/list-class.hh>
#include <object/object.hh>
#include <object/object-class.hh>
#include <object/urbi-exception.hh>
#include <runner/runner.hh>
namespace object
{
/*---------.
| Callers. |
`---------*/
rObject urbi_call(runner::Runner& r,
rObject self,
libport::Symbol msg,
objects_type args)
{
return urbi_call_function(r, self, self, msg, args);
}
#define CHECK_ARG(N) \
if (!arg ## N) \
goto done; \
args.push_back(arg ## N)
rObject urbi_call(runner::Runner& r,
rObject self,
libport::Symbol msg,
rObject arg1,
rObject arg2,
rObject arg3,
rObject arg4,
rObject arg5)
{
objects_type args;
CHECK_ARG(1);
CHECK_ARG(2);
CHECK_ARG(3);
CHECK_ARG(4);
CHECK_ARG(5);
done:
return urbi_call_function(r, self, self, msg, args);
}
#undef CHECK_ARG
rObject urbi_call_function(runner::Runner& r, rObject self,
rObject owner, libport::Symbol msg)
{
objects_type args; // Call with no args.
return urbi_call_function(r, self, owner, msg, args);
}
rObject urbi_call_function(runner::Runner& r, rObject self,
rObject owner, libport::Symbol msg,
objects_type args)
{
assert(self);
rObject message = owner->slot_get(msg);
if (!message)
throw LookupError(msg);
args.insert(args.begin(), self);
rObject res = r.apply(message, msg, args);
assert(res);
return res;
}
/*---------.
| Scopes. |
`---------*/
typedef boost::optional<rObject> lookup_result;
typedef boost::function1<lookup_result, rObject> lookup_action;
rObject
Object::make_scope(const rObject& parent)
{
rObject res = new object::Object();
res->proto_add(parent);
return res;
}
rObject
Object::make_method_scope(const rObject& parent)
{
rObject res = Object::make_scope(parent ? parent : object_class);
res->slot_set(SYMBOL(self), this);
return res;
}
/*--------.
| Slots. |
`--------*/
rObject
Object::urbi_protos_get ()
{
if (!protos_cache_)
{
rList protos = new List(*protos_);
protos_cache_ = protos;
delete protos_;
protos_ = &protos->value_get ();
}
return protos_cache_;
}
void
Object::protos_set (rObject l)
{
if (!protos_cache_)
delete protos_;
protos_cache_ = l;
protos_ = &l.unsafe_cast<object::List>()->value_get ();
}
template <typename R>
boost::optional<R>
Object::lookup(boost::function1<boost::optional<R>, rObject> action,
objects_set_type& marks) const
{
if (!libport::mhas(marks, this))
{
marks.insert(this);
// FIXME: rConstObject?
boost::optional<R> res = action(const_cast<Object*>(this));
if (res)
return res;
else
foreach (const rObject& proto, protos_get())
if (boost::optional<R> res = proto->lookup(action, marks))
return res;
}
return boost::optional<R>();
}
template <typename R>
boost::optional<R>
Object::lookup(boost::function1<boost::optional<R>, rObject> action) const
{
objects_set_type marks;
return lookup(action, marks);
}
namespace
{
class SlotLookup
{
public:
lookup_result
slot_lookup(rObject obj, const Object::key_type& k, bool value)
{
assert(obj);
if (rObject x = obj->own_slot_get(k))
return value ? x : obj;
if (!fallback)
if (rObject f = obj->own_slot_get(SYMBOL(fallback)))
fallback = value ? f : obj;
return boost::optional<rObject>();
}
rObject fallback;
};
}
rObject
Object::slot_locate(const key_type& k,
bool fallback, bool value) const
{
SlotLookup looker;
lookup_action action =
boost::bind(&SlotLookup::slot_lookup, &looker, _1, k, value);
boost::optional<rObject> res = lookup(action);
if (!res && fallback && looker.fallback)
res = looker.fallback;
if (res)
return res.get();
else
return 0;
}
rObject
Object::safe_slot_locate(const key_type& k, bool value) const
{
rObject r = slot_locate(k, true, value);
if (!r)
throw LookupError(k);
return iassertion(r);
}
rObject
Object::slot_get (const key_type& k, boost::optional<rObject> def) const
{
rObject value;
if (def)
value = slot_locate(k, true, true);
else
value = safe_slot_locate(k, true);
if (value)
return value;
else
return def.get();
}
Object&
Object::slot_set(const key_type& k, rObject o)
{
if (!slots_.set(k, o))
throw RedefinitionError(k);
return *this;
}
Object&
Object::slot_copy(const key_type& name, rObject from)
{
this->slot_set(name, from->slot_get(name));
return *this;
}
rObject
Object::slot_update(runner::Runner& r,
const key_type& k, rObject o,
bool hook)
{
// The owner of the updated slot
rObject owner = safe_slot_locate(k);
rObject v = o;
// If the current value in the slot to be written in has a slot
// named 'updateHook', call it, passing the object owning the
// slot, the slot name and the target.
if (hook)
if (rObject hook = owner->property_get(k, SYMBOL(updateHook)))
{
objects_type args = list_of (rObject(this)) (new String(k)) (o);
v = r.apply(hook, SYMBOL(updateHook), args);
// If the updateHook returned void, do nothing. Otherwise let
// the slot be overwritten.
if (v == object::void_class)
return o;
}
// If return-value of hook is not void, write it to slot.
own_slot_update(k, v);
return v;
};
void
Object::own_slot_update (const key_type& k, rObject v)
{
slots_.update(k, v);
}
void
Object::all_slots_copy(const rObject& other)
{
foreach (const Slots::slot_type& slot, other->slots_get())
if (!own_slot_get(slot.first))
slot_set(slot.first, slot.second);
}
/*-------------.
| Properties. |
`-------------*/
rDictionary
Object::properties_get()
{
rDictionary res;
if (slots_.has(SYMBOL(properties)))
res = slots_.get(SYMBOL(properties)).unsafe_cast<Dictionary>();
return res;
}
rDictionary
Object::properties_get(const key_type& k)
{
// Forbid searching properties on nonexistent slots
safe_slot_locate(k);
rDictionary res;
if (rDictionary ps = properties_get())
res = libport::find0(ps->value_get(), k).unsafe_cast<Dictionary>();
return res;
}
rObject
Object::property_get(const key_type& k, const key_type& p)
{
rObject owner = safe_slot_locate(k);
rObject res;
if (rDictionary ps = owner->properties_get(k))
res = libport::find0(ps->value_get(), p);
return res;
}
bool
Object::property_has(const key_type& k, const key_type& p)
{
// Forbid searching properties on nonexistent slots
safe_slot_locate(k);
if (rDictionary ps = properties_get(k))
return libport::find0(ps->value_get(), p);
return false;
}
rObject
Object::property_set(runner::Runner& r,
const key_type& k, const key_type& p, rObject value)
{
// Forbid setting properties on nonexistent slots
safe_slot_locate(k);
// Make sure the object has a properties dictionary.
rDictionary props = properties_get();
if (!props)
{
props = new Dictionary();
// This should die if there is a slot name "properties" which is
// not a dictionary, which is what we want, don't we?
slot_set(SYMBOL(properties), props);
}
// Make sure we have a dict for slot k.
rDictionary prop =
libport::find0(props->value_get(), k).unsafe_cast<Dictionary>();
if (!prop)
{
prop = new Dictionary();
props->value_get()[k] = prop;
}
bool had = prop->has(p);
prop->value_get()[p] = value;
if (!had)
{
rObject target = slot_get(k);
if (target->slot_locate(SYMBOL(newPropertyHook)))
urbi_call(r, target, SYMBOL(newPropertyHook),
this, new String(k), new String(p), value);
}
return value;
}
/*-----------.
| Printing. |
`-----------*/
std::ostream&
Object::special_slots_dump (std::ostream& o, runner::Runner&) const
{
return o;
}
bool
Object::operator< (const Object& rhs) const
{
return this < &rhs;
}
std::ostream&
Object::id_dump(std::ostream& o, runner::Runner& r) const
{
rObject data = urbi_call(r, const_cast<Object*>(this), SYMBOL(id));
type_check<String>(data, SYMBOL(id_dump));
libport::Symbol s = data->as<String>()->value_get();
return o << s;
}
std::ostream&
Object::protos_dump(std::ostream& o, runner::Runner& runner) const
{
if (!protos_->empty())
{
o << "protos = ";
bool tail = false;
foreach (const rObject& p, *protos_)
{
if (tail++)
o << ", ";
p->id_dump (o, runner);
}
o << libport::iendl;
}
return o;
}
std::ostream&
Object::dump (std::ostream& o, runner::Runner& runner, int depth_max) const
{
id_dump(o, runner);
/// Use xalloc/iword to store our current depth within the stream object.
static const long idx = o.xalloc();
long& current_depth = o.iword(idx);
// Stop recursion at depth_max.
if (current_depth > depth_max)
return o << " <...>";
++current_depth;
o << " {" << libport::incendl;
protos_dump(o, runner);
special_slots_dump (o, runner);
foreach(const Slots::slot_type& s, slots_.container())
{
o << s.first << " = ";
s.second->dump(o, runner, depth_max) << libport::iendl;
}
o << libport::decindent << '}';
//We can not reuse current_depth variable above according to spec.
o.iword(idx)--;
return o;
}
std::ostream&
Object::print(std::ostream& o, runner::Runner& runner) const
{
try
{
rObject s = urbi_call(runner, const_cast<Object*>(this), SYMBOL(asString));
type_check<String>(s, SYMBOL(print));
o << s->as<String>()->value_get();
return o;
}
// Check if asString was found, especially for bootstrap: asString
// is implemented in urbi/urbi.u, but print is called to show
// result in the toplevel before its definition.
catch (LookupError&)
{
// If no asString method is supplied, print the unique id
return o << std::hex << this;
}
}
bool
is_a(const rObject& c, const rObject& p)
{
return for_all_protos(c, boost::lambda::_1 == p);
}
bool
is_true(const rObject& o, const libport::Symbol& fun)
{
if (o == nil_class)
return false;
if (o->is_a<object::Float>())
return o.unsafe_cast<object::Float>()->value_get();
if (o == true_class)
return true;
if (o == false_class)
return false;
if (o == void_class)
throw WrongArgumentType(fun);
// FIXME: We will probably want to throw here. This is related to
// maybe calling asBool on every tested value.
return true;
// throw WrongArgumentType("Boolean", "Object", fun.name_get());
}
} // namespace object
<commit_msg>Fix property_has: search for properties in the owner of the slot.<commit_after>/**
** \file object/object.cc
** \brief Implementation of object::Object.
*/
#include <algorithm>
#include <boost/assign.hpp> // for 'list_of'
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/lambda/lambda.hpp>
using namespace boost::assign; // bring 'list_of' into scope
#include <libport/containers.hh>
#include <libport/foreach.hh>
#include <object/atom.hh>
#include <object/dictionary-class.hh>
#include <object/float-class.hh>
#include <object/global-class.hh>
#include <object/hash-slots.hh>
#include <object/list-class.hh>
#include <object/object.hh>
#include <object/object-class.hh>
#include <object/urbi-exception.hh>
#include <runner/runner.hh>
namespace object
{
/*---------.
| Callers. |
`---------*/
rObject urbi_call(runner::Runner& r,
rObject self,
libport::Symbol msg,
objects_type args)
{
return urbi_call_function(r, self, self, msg, args);
}
#define CHECK_ARG(N) \
if (!arg ## N) \
goto done; \
args.push_back(arg ## N)
rObject urbi_call(runner::Runner& r,
rObject self,
libport::Symbol msg,
rObject arg1,
rObject arg2,
rObject arg3,
rObject arg4,
rObject arg5)
{
objects_type args;
CHECK_ARG(1);
CHECK_ARG(2);
CHECK_ARG(3);
CHECK_ARG(4);
CHECK_ARG(5);
done:
return urbi_call_function(r, self, self, msg, args);
}
#undef CHECK_ARG
rObject urbi_call_function(runner::Runner& r, rObject self,
rObject owner, libport::Symbol msg)
{
objects_type args; // Call with no args.
return urbi_call_function(r, self, owner, msg, args);
}
rObject urbi_call_function(runner::Runner& r, rObject self,
rObject owner, libport::Symbol msg,
objects_type args)
{
assert(self);
rObject message = owner->slot_get(msg);
if (!message)
throw LookupError(msg);
args.insert(args.begin(), self);
rObject res = r.apply(message, msg, args);
assert(res);
return res;
}
/*---------.
| Scopes. |
`---------*/
typedef boost::optional<rObject> lookup_result;
typedef boost::function1<lookup_result, rObject> lookup_action;
rObject
Object::make_scope(const rObject& parent)
{
rObject res = new object::Object();
res->proto_add(parent);
return res;
}
rObject
Object::make_method_scope(const rObject& parent)
{
rObject res = Object::make_scope(parent ? parent : object_class);
res->slot_set(SYMBOL(self), this);
return res;
}
/*--------.
| Slots. |
`--------*/
rObject
Object::urbi_protos_get ()
{
if (!protos_cache_)
{
rList protos = new List(*protos_);
protos_cache_ = protos;
delete protos_;
protos_ = &protos->value_get ();
}
return protos_cache_;
}
void
Object::protos_set (rObject l)
{
if (!protos_cache_)
delete protos_;
protos_cache_ = l;
protos_ = &l.unsafe_cast<object::List>()->value_get ();
}
template <typename R>
boost::optional<R>
Object::lookup(boost::function1<boost::optional<R>, rObject> action,
objects_set_type& marks) const
{
if (!libport::mhas(marks, this))
{
marks.insert(this);
// FIXME: rConstObject?
boost::optional<R> res = action(const_cast<Object*>(this));
if (res)
return res;
else
foreach (const rObject& proto, protos_get())
if (boost::optional<R> res = proto->lookup(action, marks))
return res;
}
return boost::optional<R>();
}
template <typename R>
boost::optional<R>
Object::lookup(boost::function1<boost::optional<R>, rObject> action) const
{
objects_set_type marks;
return lookup(action, marks);
}
namespace
{
class SlotLookup
{
public:
lookup_result
slot_lookup(rObject obj, const Object::key_type& k, bool value)
{
assert(obj);
if (rObject x = obj->own_slot_get(k))
return value ? x : obj;
if (!fallback)
if (rObject f = obj->own_slot_get(SYMBOL(fallback)))
fallback = value ? f : obj;
return boost::optional<rObject>();
}
rObject fallback;
};
}
rObject
Object::slot_locate(const key_type& k,
bool fallback, bool value) const
{
SlotLookup looker;
lookup_action action =
boost::bind(&SlotLookup::slot_lookup, &looker, _1, k, value);
boost::optional<rObject> res = lookup(action);
if (!res && fallback && looker.fallback)
res = looker.fallback;
if (res)
return res.get();
else
return 0;
}
rObject
Object::safe_slot_locate(const key_type& k, bool value) const
{
rObject r = slot_locate(k, true, value);
if (!r)
throw LookupError(k);
return iassertion(r);
}
rObject
Object::slot_get (const key_type& k, boost::optional<rObject> def) const
{
rObject value;
if (def)
value = slot_locate(k, true, true);
else
value = safe_slot_locate(k, true);
if (value)
return value;
else
return def.get();
}
Object&
Object::slot_set(const key_type& k, rObject o)
{
if (!slots_.set(k, o))
throw RedefinitionError(k);
return *this;
}
Object&
Object::slot_copy(const key_type& name, rObject from)
{
this->slot_set(name, from->slot_get(name));
return *this;
}
rObject
Object::slot_update(runner::Runner& r,
const key_type& k, rObject o,
bool hook)
{
// The owner of the updated slot
rObject owner = safe_slot_locate(k);
rObject v = o;
// If the current value in the slot to be written in has a slot
// named 'updateHook', call it, passing the object owning the
// slot, the slot name and the target.
if (hook)
if (rObject hook = owner->property_get(k, SYMBOL(updateHook)))
{
objects_type args = list_of (rObject(this)) (new String(k)) (o);
v = r.apply(hook, SYMBOL(updateHook), args);
// If the updateHook returned void, do nothing. Otherwise let
// the slot be overwritten.
if (v == object::void_class)
return o;
}
// If return-value of hook is not void, write it to slot.
own_slot_update(k, v);
return v;
};
void
Object::own_slot_update (const key_type& k, rObject v)
{
slots_.update(k, v);
}
void
Object::all_slots_copy(const rObject& other)
{
foreach (const Slots::slot_type& slot, other->slots_get())
if (!own_slot_get(slot.first))
slot_set(slot.first, slot.second);
}
/*-------------.
| Properties. |
`-------------*/
rDictionary
Object::properties_get()
{
rDictionary res;
if (slots_.has(SYMBOL(properties)))
res = slots_.get(SYMBOL(properties)).unsafe_cast<Dictionary>();
return res;
}
rDictionary
Object::properties_get(const key_type& k)
{
// Forbid searching properties on nonexistent slots
safe_slot_locate(k);
rDictionary res;
if (rDictionary ps = properties_get())
res = libport::find0(ps->value_get(), k).unsafe_cast<Dictionary>();
return res;
}
rObject
Object::property_get(const key_type& k, const key_type& p)
{
rObject owner = safe_slot_locate(k);
rObject res;
if (rDictionary ps = owner->properties_get(k))
res = libport::find0(ps->value_get(), p);
return res;
}
bool
Object::property_has(const key_type& k, const key_type& p)
{
// Look for properties in the owner of the slot
rObject owner = safe_slot_locate(k);
if (rDictionary ps = owner->properties_get(k))
return libport::find0(ps->value_get(), p);
return false;
}
rObject
Object::property_set(runner::Runner& r,
const key_type& k, const key_type& p, rObject value)
{
// Forbid setting properties on nonexistent slots
safe_slot_locate(k);
// Make sure the object has a properties dictionary.
rDictionary props = properties_get();
if (!props)
{
props = new Dictionary();
// This should die if there is a slot name "properties" which is
// not a dictionary, which is what we want, don't we?
slot_set(SYMBOL(properties), props);
}
// Make sure we have a dict for slot k.
rDictionary prop =
libport::find0(props->value_get(), k).unsafe_cast<Dictionary>();
if (!prop)
{
prop = new Dictionary();
props->value_get()[k] = prop;
}
bool had = prop->has(p);
prop->value_get()[p] = value;
if (!had)
{
rObject target = slot_get(k);
if (target->slot_locate(SYMBOL(newPropertyHook)))
urbi_call(r, target, SYMBOL(newPropertyHook),
this, new String(k), new String(p), value);
}
return value;
}
/*-----------.
| Printing. |
`-----------*/
std::ostream&
Object::special_slots_dump (std::ostream& o, runner::Runner&) const
{
return o;
}
bool
Object::operator< (const Object& rhs) const
{
return this < &rhs;
}
std::ostream&
Object::id_dump(std::ostream& o, runner::Runner& r) const
{
rObject data = urbi_call(r, const_cast<Object*>(this), SYMBOL(id));
type_check<String>(data, SYMBOL(id_dump));
libport::Symbol s = data->as<String>()->value_get();
return o << s;
}
std::ostream&
Object::protos_dump(std::ostream& o, runner::Runner& runner) const
{
if (!protos_->empty())
{
o << "protos = ";
bool tail = false;
foreach (const rObject& p, *protos_)
{
if (tail++)
o << ", ";
p->id_dump (o, runner);
}
o << libport::iendl;
}
return o;
}
std::ostream&
Object::dump (std::ostream& o, runner::Runner& runner, int depth_max) const
{
id_dump(o, runner);
/// Use xalloc/iword to store our current depth within the stream object.
static const long idx = o.xalloc();
long& current_depth = o.iword(idx);
// Stop recursion at depth_max.
if (current_depth > depth_max)
return o << " <...>";
++current_depth;
o << " {" << libport::incendl;
protos_dump(o, runner);
special_slots_dump (o, runner);
foreach(const Slots::slot_type& s, slots_.container())
{
o << s.first << " = ";
s.second->dump(o, runner, depth_max) << libport::iendl;
}
o << libport::decindent << '}';
//We can not reuse current_depth variable above according to spec.
o.iword(idx)--;
return o;
}
std::ostream&
Object::print(std::ostream& o, runner::Runner& runner) const
{
try
{
rObject s = urbi_call(runner, const_cast<Object*>(this), SYMBOL(asString));
type_check<String>(s, SYMBOL(print));
o << s->as<String>()->value_get();
return o;
}
// Check if asString was found, especially for bootstrap: asString
// is implemented in urbi/urbi.u, but print is called to show
// result in the toplevel before its definition.
catch (LookupError&)
{
// If no asString method is supplied, print the unique id
return o << std::hex << this;
}
}
bool
is_a(const rObject& c, const rObject& p)
{
return for_all_protos(c, boost::lambda::_1 == p);
}
bool
is_true(const rObject& o, const libport::Symbol& fun)
{
if (o == nil_class)
return false;
if (o->is_a<object::Float>())
return o.unsafe_cast<object::Float>()->value_get();
if (o == true_class)
return true;
if (o == false_class)
return false;
if (o == void_class)
throw WrongArgumentType(fun);
// FIXME: We will probably want to throw here. This is related to
// maybe calling asBool on every tested value.
return true;
// throw WrongArgumentType("Boolean", "Object", fun.name_get());
}
} // namespace object
<|endoftext|> |
<commit_before>#include "omnicore/sto.h"
#include "omnicore/log.h"
#include "omnicore/omnicore.h"
#include "omnicore/tally.h"
#include "sync.h"
#include <boost/multiprecision/cpp_int.hpp>
#include <assert.h>
#include <stdint.h>
#include <map>
#include <set>
#include <string>
#include <utility>
using boost::multiprecision::int128_t;
namespace mastercore
{
/**
* Compares two owner/receiver entries, based on amount.
*/
bool SendToOwners_compare::operator()(const std::pair<int64_t, std::string>& p1, const std::pair<int64_t, std::string>& p2) const
{
if (p1.first == p2.first) return p1.second > p2.second; // reverse check
else return p1.first < p2.first;
}
/**
* Determines the receivers and amounts to distribute.
*
* The sender is excluded from the result set.
*/
OwnerAddrType STO_GetReceivers(const std::string& sender, uint32_t property, int64_t amount)
{
int64_t totalTokens = 0;
int64_t senderTokens = 0;
OwnerAddrType ownerAddrSet;
{
LOCK(cs_tally);
std::map<std::string, CMPTally>::reverse_iterator it;
for (it = mp_tally_map.rbegin(); it != mp_tally_map.rend(); ++it) {
const std::string& address = it->first;
const CMPTally& tally = it->second;
int64_t tokens = 0;
tokens += tally.getMoney(property, BALANCE);
tokens += tally.getMoney(property, SELLOFFER_RESERVE);
tokens += tally.getMoney(property, ACCEPT_RESERVE);
tokens += tally.getMoney(property, METADEX_RESERVE);
// Do not include the sender
if (address == sender) {
senderTokens = tokens;
continue;
}
totalTokens += tokens;
// Only holders with balance are relevant
if (0 < tokens) {
ownerAddrSet.insert(std::make_pair(tokens, address));
}
}
}
// Split up what was taken and distribute between all holders
int64_t sent_so_far = 0;
OwnerAddrType receiversSet;
for (OwnerAddrType::reverse_iterator it = ownerAddrSet.rbegin(); it != ownerAddrSet.rend(); ++it) {
const std::string& address = it->second;
int128_t owns = int128_t(it->first);
int128_t temp = owns * int128_t(amount);
int128_t piece = 1 + ((temp - 1) / int128_t(totalTokens));
int64_t will_really_receive = 0;
int64_t should_receive = piece.convert_to<int64_t>();
// Ensure that no more than available is distributed
if ((amount - sent_so_far) < should_receive) {
will_really_receive = amount - sent_so_far;
} else {
will_really_receive = should_receive;
}
sent_so_far += will_really_receive;
if (msc_debug_sto) {
PrintToLog("%14d = %s, temp= %38s, should_get= %19d, will_really_get= %14d, sent_so_far= %14d\n",
owns, address, temp.str(), should_receive, will_really_receive, sent_so_far);
}
// Stop, once the whole amount is allocated
if (will_really_receive > 0) {
receiversSet.insert(std::make_pair(will_really_receive, address));
} else {
break;
}
}
uint64_t numberOfOwners = receiversSet.size();
PrintToLog("\t Total Tokens: %s\n", FormatMP(property, totalTokens + senderTokens));
PrintToLog("\tExcluding Sender: %s\n", FormatMP(property, totalTokens));
PrintToLog("\t Owners: %d\n", numberOfOwners);
return receiversSet;
}
} // namespace mastercore
<commit_msg>Use native uint256 for STO calculations<commit_after>#include "omnicore/sto.h"
#include "omnicore/log.h"
#include "omnicore/omnicore.h"
#include "omnicore/tally.h"
#include "omnicore/uint256_extensions.h"
#include "sync.h"
#include <assert.h>
#include <stdint.h>
#include <map>
#include <set>
#include <string>
#include <utility>
namespace mastercore
{
/**
* Compares two owner/receiver entries, based on amount.
*/
bool SendToOwners_compare::operator()(const std::pair<int64_t, std::string>& p1, const std::pair<int64_t, std::string>& p2) const
{
if (p1.first == p2.first) return p1.second > p2.second; // reverse check
else return p1.first < p2.first;
}
/**
* Determines the receivers and amounts to distribute.
*
* The sender is excluded from the result set.
*/
OwnerAddrType STO_GetReceivers(const std::string& sender, uint32_t property, int64_t amount)
{
int64_t totalTokens = 0;
int64_t senderTokens = 0;
OwnerAddrType ownerAddrSet;
{
LOCK(cs_tally);
std::map<std::string, CMPTally>::reverse_iterator it;
for (it = mp_tally_map.rbegin(); it != mp_tally_map.rend(); ++it) {
const std::string& address = it->first;
const CMPTally& tally = it->second;
int64_t tokens = 0;
tokens += tally.getMoney(property, BALANCE);
tokens += tally.getMoney(property, SELLOFFER_RESERVE);
tokens += tally.getMoney(property, ACCEPT_RESERVE);
tokens += tally.getMoney(property, METADEX_RESERVE);
// Do not include the sender
if (address == sender) {
senderTokens = tokens;
continue;
}
totalTokens += tokens;
// Only holders with balance are relevant
if (0 < tokens) {
ownerAddrSet.insert(std::make_pair(tokens, address));
}
}
}
// Split up what was taken and distribute between all holders
int64_t sent_so_far = 0;
OwnerAddrType receiversSet;
for (OwnerAddrType::reverse_iterator it = ownerAddrSet.rbegin(); it != ownerAddrSet.rend(); ++it) {
const std::string& address = it->second;
uint256 owns = ConvertTo256(it->first);
uint256 temp = owns * ConvertTo256(amount);
uint256 piece = DivideAndRoundUp(temp, ConvertTo256(totalTokens));
int64_t will_really_receive = 0;
int64_t should_receive = ConvertTo64(piece);
// Ensure that no more than available is distributed
if ((amount - sent_so_far) < should_receive) {
will_really_receive = amount - sent_so_far;
} else {
will_really_receive = should_receive;
}
sent_so_far += will_really_receive;
if (msc_debug_sto) {
PrintToLog("%14d = %s, temp= %38s, should_get= %19d, will_really_get= %14d, sent_so_far= %14d\n",
it->first, address, temp.ToString(), should_receive, will_really_receive, sent_so_far);
}
// Stop, once the whole amount is allocated
if (will_really_receive > 0) {
receiversSet.insert(std::make_pair(will_really_receive, address));
} else {
break;
}
}
uint64_t numberOfOwners = receiversSet.size();
PrintToLog("\t Total Tokens: %s\n", FormatMP(property, totalTokens + senderTokens));
PrintToLog("\tExcluding Sender: %s\n", FormatMP(property, totalTokens));
PrintToLog("\t Owners: %d\n", numberOfOwners);
return receiversSet;
}
} // namespace mastercore
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (c) 2015 Jamis Hoo
* Distributed under the MIT license
* (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
*
* Project:
* Filename: option_parser.cc
* Version: 1.0
* Author: Jamis Hoo
* E-mail: [email protected]
* Date: Jun 5, 2015
* Time: 09:24:42
* Description: parse command-line options
*****************************************************************************/
#include "option_parser.h"
#include <iostream>
#include <stdexcept>
#include <boost/filesystem.hpp>
#include <boost/asio/ip/address.hpp>
void OptionParser::initialize() {
using namespace std;
using namespace boost::program_options;
options_description master_options("Master Node options");
master_options.add_options()
("listen,l", value<string>(), "Run as a master node and listen at this IP address. Both IPv4 and IPv6 are supported. ");
options_description standby_options("Stand By Node options");
standby_options.add_options()
("connect,c", value<string>(), "Run as a stand by node and connect to this IP address. Both IPv4 and IPv6 are supported.");
options_description generic_options("Generic options");
generic_options.add_options()
("tcp-port,t", value<uint16_t>(), "Specify TCP port. ")
("ssh-port,s", value<uint16_t>(), "Specify SSH port. Default value is 22 ")
("mount-point,m", value<boost::filesystem::path>(), "Specify filesysem mount point. ")
("working-directory,w", value<boost::filesystem::path>(), "Specify temporary directory used when program running. ")
("help,h", "Display this help message. ")
("version,v", "Display version number of this program. ");
all_options.add(master_options).add(standby_options).add(generic_options);
}
void OptionParser::parse(const int argc, char** argv) {
using namespace std;
using namespace boost::program_options;
is_master = is_standby = 0;
store(parse_command_line(argc, argv, all_options), vm);
notify(vm);
// --version
if (vm.size() == 1 && vm.count("version")) {
cout << "Group-Share Filesystem (GSFS), Version 1.0 \n"
"Copyright (c) 2015 Jamis Hoo \n"
"Distributed under the MIT license\n"
<< std::flush;
return;
}
// --help
if ((vm.size() == 1 && vm.count("help")) || vm.size() == 0) {
cout << all_options << std::endl;
return;
}
// check --listen and --connect conflict
if (vm.count("listen") && vm.count("connect"))
throw invalid_argument("Conflict options --listen and --connect. ");
// redundant --help
if (vm.count("help"))
throw invalid_argument("Invalid option --help. ");
// redundata --version
if (vm.count("version"))
throw invalid_argument("Invalid option --version. ");
// either --listen or --connect
if (vm.count("listen"))
is_master = 1, address = vm["listen"].as<string>();
else if (vm.count("connect"))
is_standby = 1, address = vm["connect"].as<string>();
else
throw invalid_argument("Invalid option(s). You must specify an IP address with either --listen or --connect. ");
boost::system::error_code ec;
boost::asio::ip::address::from_string(address, ec);
if (ec)
throw invalid_argument("Invalid IP address (" + address + "). ");
// --tcp-port
if (vm.count("tcp-port"))
tcp_port = vm["tcp-port"].as<uint16_t>();
else
throw invalid_argument("Invalid option(s). Yout must specify a port for TCP connection with --tcp-port. ");
// --ssh-port
if (vm.count("ssh-port"))
ssh_port = vm["ssh-port"].as<uint16_t>();
else
ssh_port = 22;
// --mount-point
if (vm.count("mount-point"))
mount_point = vm["mount-point"].as<boost::filesystem::path>().string();
else
throw invalid_argument("Invalid option(s). You must specify a mount point for this filesystem. ");
// --working-directory
if (vm.count("working-directory"))
tmp_dir = vm["working-directory"].as<boost::filesystem::path>().string();
else
throw invalid_argument("Invalid option(s). You must specify a temporary working directory for this filesystem. ");
}
<commit_msg>add options instruction<commit_after>/******************************************************************************
* Copyright (c) 2015 Jamis Hoo
* Distributed under the MIT license
* (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
*
* Project:
* Filename: option_parser.cc
* Version: 1.0
* Author: Jamis Hoo
* E-mail: [email protected]
* Date: Jun 5, 2015
* Time: 09:24:42
* Description: parse command-line options
*****************************************************************************/
#include "option_parser.h"
#include <iostream>
#include <stdexcept>
#include <boost/filesystem.hpp>
#include <boost/asio/ip/address.hpp>
void OptionParser::initialize() {
using namespace std;
using namespace boost::program_options;
options_description master_options("Master Node options");
master_options.add_options()
("listen,l", value<string>(),
"Run as a master node and listen at this IP address. Both IPv4 and "
"IPv6 are supported. ");
options_description standby_options("Stand By Node options");
standby_options.add_options()
("connect,c", value<string>(),
"Run as a stand by node and connect to this IP address. Both IPv4 "
"and IPv6 are supported.");
options_description generic_options("Generic options");
generic_options.add_options()
("tcp-port,t", value<uint16_t>(),
"Specify TCP port. Master node listens at this port while stand "
"by node connects to this port of master node. ")
("ssh-port,s", value<uint16_t>(),
"Specify SSH port. Default value is 22. Listen at this port so that "
"other nodes can create a SFTP connection. ")
("mount-point,m", value<boost::filesystem::path>(),
"Specify filesysem mount point. ")
("working-directory,w", value<boost::filesystem::path>(),
"Specify temporary directory used when program running. ")
("help,h",
"Display this help message. ")
("version,v",
"Display version number of this program. ");
all_options.add(master_options).add(standby_options).add(generic_options);
}
void OptionParser::parse(const int argc, char** argv) {
using namespace std;
using namespace boost::program_options;
is_master = is_standby = 0;
store(parse_command_line(argc, argv, all_options), vm);
notify(vm);
// --version
if (vm.size() == 1 && vm.count("version")) {
cout << "Group-Share Filesystem (GSFS), Version 1.0 \n"
"Copyright (c) 2015 Jamis Hoo \n"
"Distributed under the MIT license\n"
<< std::flush;
return;
}
// --help
if ((vm.size() == 1 && vm.count("help")) || vm.size() == 0) {
cout << all_options << std::endl;
return;
}
// check --listen and --connect conflict
if (vm.count("listen") && vm.count("connect"))
throw invalid_argument("Conflict options --listen and --connect. ");
// redundant --help
if (vm.count("help"))
throw invalid_argument("Invalid option --help. ");
// redundata --version
if (vm.count("version"))
throw invalid_argument("Invalid option --version. ");
// either --listen or --connect
if (vm.count("listen"))
is_master = 1, address = vm["listen"].as<string>();
else if (vm.count("connect"))
is_standby = 1, address = vm["connect"].as<string>();
else
throw invalid_argument("Invalid option(s). You must specify an IP address with either --listen or --connect. ");
boost::system::error_code ec;
boost::asio::ip::address::from_string(address, ec);
if (ec)
throw invalid_argument("Invalid IP address (" + address + "). ");
// --tcp-port
if (vm.count("tcp-port"))
tcp_port = vm["tcp-port"].as<uint16_t>();
else
throw invalid_argument("Invalid option(s). Yout must specify a port for TCP connection with --tcp-port. ");
// --ssh-port
if (vm.count("ssh-port"))
ssh_port = vm["ssh-port"].as<uint16_t>();
else
ssh_port = 22;
// --mount-point
if (vm.count("mount-point"))
mount_point = vm["mount-point"].as<boost::filesystem::path>().string();
else
throw invalid_argument("Invalid option(s). You must specify a mount point for this filesystem. ");
// --working-directory
if (vm.count("working-directory"))
tmp_dir = vm["working-directory"].as<boost::filesystem::path>().string();
else
throw invalid_argument("Invalid option(s). You must specify a temporary working directory for this filesystem. ");
}
<|endoftext|> |
<commit_before>// Copyright 2019 The Marl Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "osfiber.h"
#include "marl_test.h"
TEST_F(WithoutBoundScheduler, OSFiber) {
std::string str;
auto constexpr fiberStackSize = 8 * 1024;
auto main = marl::OSFiber::createFiberFromCurrentThread(allocator);
marl::Allocator::unique_ptr<marl::OSFiber> fiberA, fiberB, fiberC;
fiberC = marl::OSFiber::createFiber(allocator, fiberStackSize, [&] {
str += "C";
fiberC->switchTo(fiberB.get());
});
fiberB = marl::OSFiber::createFiber(allocator, fiberStackSize, [&] {
str += "B";
fiberB->switchTo(fiberA.get());
});
fiberA = marl::OSFiber::createFiber(allocator, fiberStackSize, [&] {
str += "A";
fiberA->switchTo(main.get());
});
main->switchTo(fiberC.get());
ASSERT_EQ(str, "CBA");
}
<commit_msg>Add a new test for 16-byte stack alignment for fibers.<commit_after>// Copyright 2019 The Marl Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "osfiber.h"
#include "marl_test.h"
namespace {
auto constexpr fiberStackSize = 8 * 1024;
} // anonymous namespace
TEST_F(WithoutBoundScheduler, OSFiber) {
std::string str;
auto main = marl::OSFiber::createFiberFromCurrentThread(allocator);
marl::Allocator::unique_ptr<marl::OSFiber> fiberA, fiberB, fiberC;
fiberC = marl::OSFiber::createFiber(allocator, fiberStackSize, [&] {
str += "C";
fiberC->switchTo(fiberB.get());
});
fiberB = marl::OSFiber::createFiber(allocator, fiberStackSize, [&] {
str += "B";
fiberB->switchTo(fiberA.get());
});
fiberA = marl::OSFiber::createFiber(allocator, fiberStackSize, [&] {
str += "A";
fiberA->switchTo(main.get());
});
main->switchTo(fiberC.get());
ASSERT_EQ(str, "CBA");
}
TEST_F(WithoutBoundScheduler, StackAlignment) {
uintptr_t address = 0;
struct alignas(16) AlignTo16Bytes {
uint64_t a, b;
};
auto main = marl::OSFiber::createFiberFromCurrentThread(allocator);
marl::Allocator::unique_ptr<marl::OSFiber> fiber;
fiber = marl::OSFiber::createFiber(allocator, fiberStackSize, [&] {
AlignTo16Bytes stack_var;
address = reinterpret_cast<uintptr_t>(&stack_var);
fiber->switchTo(main.get());
});
main->switchTo(fiber.get());
ASSERT_TRUE((address & 15) == 0)
<< "Stack variable had unaligned address: 0x" << std::hex << address;
}
<|endoftext|> |
<commit_before>#include <utki/config.hpp>
#include <utki/types.hpp>
#if M_OS == M_OS_WINDOWS
# include <utki/windows.hpp>
#elif M_OS == M_OS_LINUX || M_OS == M_OS_MACOSX
# include <dirent.h>
# include <sys/stat.h>
# include <cerrno>
# include <cstring>
#endif
#include <vector>
#include <cstdlib>
#include <sstream>
#include "FSFile.hpp"
using namespace papki;
void FSFile::openInternal(E_Mode mode){
if(this->isDir()){
throw papki::Exc("path refers to a directory, directories can't be opened");
}
const char* modeStr;
switch(mode){
case File::E_Mode::WRITE:
modeStr = "r+b";
break;
case File::E_Mode::CREATE:
modeStr = "w+b";
break;
case File::E_Mode::READ:
modeStr = "rb";
break;
default:
throw papki::Exc("unknown mode");
break;
}
#if M_COMPILER == M_COMPILER_MSVC
if(fopen_s(&this->handle, this->path().c_str(), modeStr) != 0){
this->handle = 0;
}
#else
this->handle = fopen(this->path().c_str(), modeStr);
#endif
if(!this->handle){
TRACE(<< "FSFile::Open(): Path() = " << this->path().c_str() << std::endl)
std::stringstream ss;
ss << "fopen(" << this->path().c_str() << ") failed";
throw papki::Exc(ss.str());
}
}
//override
void FSFile::closeInternal()const noexcept{
ASSERT(this->handle)
fclose(this->handle);
this->handle = 0;
}
//override
size_t FSFile::readInternal(utki::Buf<std::uint8_t> buf)const{
ASSERT(this->handle)
size_t numBytesRead = fread(buf.begin(), 1, buf.size(), this->handle);
if(numBytesRead != buf.size()){//something happened
if(!feof(this->handle)){
throw papki::Exc("fread() error");//if it is not an EndOfFile then it is error
}
}
return numBytesRead;
}
//override
size_t FSFile::writeInternal(const utki::Buf<std::uint8_t> buf){
ASSERT(this->handle)
size_t bytesWritten = fwrite(buf.begin(), 1, buf.size(), this->handle);
if(bytesWritten != buf.size()){//something bad has happened
throw papki::Exc("fwrite error");
}
return bytesWritten;
}
//override
size_t FSFile::seekBackwardInternal(size_t numBytesToSeek)const{
ASSERT(this->handle)
//NOTE: fseek() accepts 'long int' as offset argument which is signed and can be
// less than size_t value passed as argument to this function.
// Therefore, do several seek operations with smaller offset if necessary.
typedef long int T_FSeekOffset;
const size_t DMax = ((size_t(T_FSeekOffset(-1))) >> 1);
ASSERT((size_t(1) << ((sizeof(T_FSeekOffset) * 8) - 1)) - 1 == DMax)
static_assert(size_t(-(-T_FSeekOffset(DMax))) == DMax, "error");
utki::clampTop(numBytesToSeek, this->curPos());
for(size_t numBytesLeft = numBytesToSeek; numBytesLeft != 0;){
ASSERT(numBytesLeft <= numBytesToSeek)
T_FSeekOffset offset;
if(numBytesLeft > DMax){
offset = T_FSeekOffset(DMax);
}else{
offset = T_FSeekOffset(numBytesLeft);
}
ASSERT(offset > 0)
if(fseek(this->handle, -offset, SEEK_CUR) != 0){
throw papki::Exc("fseek() failed");
}
ASSERT(size_t(offset) < size_t(-1))
ASSERT(numBytesLeft >= size_t(offset))
numBytesLeft -= size_t(offset);
}
return numBytesToSeek;
}
//override
void FSFile::rewindInternal()const{
if(!this->isOpened()){
throw papki::IllegalStateExc("cannot rewind, file is not opened");
}
ASSERT(this->handle)
if(fseek(this->handle, 0, SEEK_SET) != 0){
throw papki::Exc("fseek() failed");
}
}
//override
bool FSFile::exists()const{
if(this->isOpened()){ //file is opened => it exists
return true;
}
if(this->path().size() == 0){
return false;
}
//if it is a directory, check directory existence
if(this->path()[this->path().size() - 1] == '/'){
#if M_OS == M_OS_LINUX
DIR *pdir = opendir(this->path().c_str());
if(!pdir){
return false;
}else{
closedir(pdir);
return true;
}
#else
throw papki::Exc("Checking for directory existence is not supported");
#endif
}else{
return this->File::exists();
}
}
//override
void FSFile::makeDir(){
if(this->isOpened()){
throw papki::IllegalStateExc("cannot make directory when file is opened");
}
if(this->path().size() == 0 || this->path()[this->path().size() - 1] != '/'){
throw papki::Exc("invalid directory name");
}
#if M_OS == M_OS_LINUX
// TRACE(<< "creating directory = " << this->Path() << std::endl)
umask(0);//clear umask for proper permissions of newly created directory
if(mkdir(this->path().c_str(), 0777) != 0){
throw papki::Exc("mkdir() failed");
}
#else
throw papki::Exc("creating directory is not supported");
#endif
}
std::string FSFile::getHomeDir(){
std::string ret;
#if M_OS == M_OS_LINUX || M_OS == M_OS_WINDOWS || M_OS == M_OS_MACOSX
# if M_OS == M_OS_LINUX || M_OS == M_OS_MACOSX
char * home = getenv("HOME");
# elif M_OS == M_OS_WINDOWS
char * home = getenv("USERPROFILE"); //TODO: MS Viual Studio complains about unsafety, consider changing to _dupenv_s() for MSVC compiler
# else
# error "unsupported OS"
# endif
if(!home){
throw papki::Exc("HOME environment variable does not exist");
}
ret = std::string(home);
#else
# error "unsupported os"
#endif
//append trailing '/' if needed
if(ret.size() == 0 || ret[ret.size() - 1] != '/'){
ret += '/';
}
return ret;
}
std::vector<std::string> FSFile::listDirContents(size_t maxEntries)const{
if(!this->isDir()){
throw papki::Exc("FSFile::ListDirContents(): this is not a directory");
}
std::vector<std::string> files;
#if M_OS == M_OS_WINDOWS
{
std::string pattern = this->path();
pattern += '*';
TRACE(<< "FSFile::ListDirContents(): pattern = " << pattern << std::endl)
WIN32_FIND_DATA wfd;
HANDLE h = FindFirstFile(pattern.c_str(), &wfd);
if (h == INVALID_HANDLE_VALUE) {
throw papki::Exc("ListDirContents(): cannot find first file");
}
//create Find Closer to automatically call FindClose on exit from the function in case of exceptions etc...
{
struct FindCloser {
HANDLE hnd;
FindCloser(HANDLE h) :
hnd(h)
{}
~FindCloser() {
FindClose(this->hnd);
}
} findCloser(h);
do {
std::string s(wfd.cFileName);
ASSERT(s.size() > 0)
//do not add ./ and ../ directories, we are not interested in them
if (s == "." || s == "..") {
continue;
}
if (((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) && s[s.size() - 1] != '/') {
s += '/';
}
files.push_back(s);
if (files.size() == maxEntries) {
break;
}
} while (FindNextFile(h, &wfd) != 0);
if (GetLastError() != ERROR_NO_MORE_FILES) {
throw papki::Exc("ListDirContents(): find next file failed");
}
}
}
#elif M_OS == M_OS_LINUX || M_OS == M_OS_MACOSX
{
DIR *pdir = opendir(this->path().c_str());
if(!pdir){
std::stringstream ss;
ss << "FSFile::ListDirContents(): opendir() failure, error code = " << strerror(errno);
throw papki::Exc(ss.str());
}
//create DirentCloser to automatically call closedir on exit from the function in case of exceptions etc...
struct DirCloser{
DIR *pdir;
DirCloser(DIR *pDirToClose) :
pdir(pDirToClose)
{}
~DirCloser(){
int ret;
do{
ret = closedir(this->pdir);
ASSERT_INFO(ret == 0 || errno == EINTR, "FSFile::ListDirContents(): closedir() failed: " << strerror(errno))
}while(ret != 0 && errno == EINTR);
}
} dirCloser(pdir);
errno = 0;//clear errno
while(dirent *pent = readdir(pdir)){
std::string s(pent->d_name);
if(s == "." || s == "..")
continue;//do not add ./ and ../ directories, we are not interested in them
struct stat fileStats;
//TRACE(<< s << std::endl)
if(stat((this->path() + s).c_str(), &fileStats) < 0){
std::stringstream ss;
ss << "FSFile::ListDirContents(): stat() failure, error code = " << strerror(errno);
throw papki::Exc(ss.str());
}
if(fileStats.st_mode & S_IFDIR)//if this entry is a directory append '/' symbol to its end
s += "/";
files.push_back(s);
if(files.size() == maxEntries){
break;
}
}//~while()
//check if we exited the while() loop because of readdir() failed
if(errno != 0){
std::stringstream ss;
ss << "FSFile::ListDirContents(): readdir() failure, error code = " << strerror(errno);
throw papki::Exc(ss.str());
}
}
#else
# error "FSFile::ListDirContents(): version is not implemented yet for this os"
#endif
return std::move(files);
}
std::unique_ptr<File> FSFile::spawn(){
return utki::makeUnique<FSFile>();
}
<commit_msg>stuff<commit_after>#include <utki/config.hpp>
#include <utki/types.hpp>
#if M_OS == M_OS_WINDOWS
# include <utki/windows.hpp>
#elif M_OS == M_OS_LINUX || M_OS == M_OS_MACOSX
# include <dirent.h>
# include <sys/stat.h>
# include <cerrno>
# include <cstring>
#endif
#include <vector>
#include <cstdlib>
#include <sstream>
#include "FSFile.hpp"
using namespace papki;
void FSFile::openInternal(E_Mode mode){
if(this->isDir()){
throw papki::Exc("path refers to a directory, directories can't be opened");
}
const char* modeStr;
switch(mode){
case File::E_Mode::WRITE:
modeStr = "r+b";
break;
case File::E_Mode::CREATE:
modeStr = "w+b";
break;
case File::E_Mode::READ:
modeStr = "rb";
break;
default:
throw papki::Exc("unknown mode");
break;
}
#if M_COMPILER == M_COMPILER_MSVC
if(fopen_s(&this->handle, this->path().c_str(), modeStr) != 0){
this->handle = 0;
}
#else
this->handle = fopen(this->path().c_str(), modeStr);
#endif
if(!this->handle){
TRACE(<< "FSFile::Open(): Path() = " << this->path().c_str() << std::endl)
std::stringstream ss;
ss << "fopen(" << this->path().c_str() << ") failed";
throw papki::Exc(ss.str());
}
}
//override
void FSFile::closeInternal()const noexcept{
ASSERT(this->handle)
fclose(this->handle);
this->handle = 0;
}
//override
size_t FSFile::readInternal(utki::Buf<std::uint8_t> buf)const{
ASSERT(this->handle)
size_t numBytesRead = fread(buf.begin(), 1, buf.size(), this->handle);
if(numBytesRead != buf.size()){//something happened
if(!feof(this->handle)){
throw papki::Exc("fread() error");//if it is not an EndOfFile then it is error
}
}
return numBytesRead;
}
//override
size_t FSFile::writeInternal(const utki::Buf<std::uint8_t> buf){
ASSERT(this->handle)
size_t bytesWritten = fwrite(buf.begin(), 1, buf.size(), this->handle);
if(bytesWritten != buf.size()){//something bad has happened
throw papki::Exc("fwrite error");
}
return bytesWritten;
}
size_t FSFile::seekBackwardInternal(size_t numBytesToSeek)const{
ASSERT(this->handle)
//NOTE: fseek() accepts 'long int' as offset argument which is signed and can be
// less than size_t value passed as argument to this function.
// Therefore, do several seek operations with smaller offset if necessary.
typedef long int T_FSeekOffset;
const size_t DMax = size_t((unsigned long int(-1)) >> 1);
ASSERT((size_t(1) << ((sizeof(T_FSeekOffset) * 8) - 1)) - 1 == DMax)
static_assert(size_t(-(-T_FSeekOffset(DMax))) == DMax, "error");
utki::clampTop(numBytesToSeek, this->curPos());
for(size_t numBytesLeft = numBytesToSeek; numBytesLeft != 0;){
ASSERT(numBytesLeft <= numBytesToSeek)
T_FSeekOffset offset;
if(numBytesLeft > DMax){
offset = T_FSeekOffset(DMax);
}else{
offset = T_FSeekOffset(numBytesLeft);
}
ASSERT(offset > 0)
if(fseek(this->handle, -offset, SEEK_CUR) != 0){
throw papki::Exc("fseek() failed");
}
ASSERT(size_t(offset) < size_t(-1))
ASSERT(numBytesLeft >= size_t(offset))
numBytesLeft -= size_t(offset);
}
return numBytesToSeek;
}
//override
void FSFile::rewindInternal()const{
if(!this->isOpened()){
throw papki::IllegalStateExc("cannot rewind, file is not opened");
}
ASSERT(this->handle)
if(fseek(this->handle, 0, SEEK_SET) != 0){
throw papki::Exc("fseek() failed");
}
}
//override
bool FSFile::exists()const{
if(this->isOpened()){ //file is opened => it exists
return true;
}
if(this->path().size() == 0){
return false;
}
//if it is a directory, check directory existence
if(this->path()[this->path().size() - 1] == '/'){
#if M_OS == M_OS_LINUX
DIR *pdir = opendir(this->path().c_str());
if(!pdir){
return false;
}else{
closedir(pdir);
return true;
}
#else
throw papki::Exc("Checking for directory existence is not supported");
#endif
}else{
return this->File::exists();
}
}
//override
void FSFile::makeDir(){
if(this->isOpened()){
throw papki::IllegalStateExc("cannot make directory when file is opened");
}
if(this->path().size() == 0 || this->path()[this->path().size() - 1] != '/'){
throw papki::Exc("invalid directory name");
}
#if M_OS == M_OS_LINUX
// TRACE(<< "creating directory = " << this->Path() << std::endl)
umask(0);//clear umask for proper permissions of newly created directory
if(mkdir(this->path().c_str(), 0777) != 0){
throw papki::Exc("mkdir() failed");
}
#else
throw papki::Exc("creating directory is not supported");
#endif
}
std::string FSFile::getHomeDir(){
std::string ret;
#if M_OS == M_OS_LINUX || M_OS == M_OS_WINDOWS || M_OS == M_OS_MACOSX
# if M_OS == M_OS_LINUX || M_OS == M_OS_MACOSX
char * home = getenv("HOME");
# elif M_OS == M_OS_WINDOWS
char * home = getenv("USERPROFILE"); //TODO: MS Viual Studio complains about unsafety, consider changing to _dupenv_s() for MSVC compiler
# else
# error "unsupported OS"
# endif
if(!home){
throw papki::Exc("HOME environment variable does not exist");
}
ret = std::string(home);
#else
# error "unsupported os"
#endif
//append trailing '/' if needed
if(ret.size() == 0 || ret[ret.size() - 1] != '/'){
ret += '/';
}
return ret;
}
std::vector<std::string> FSFile::listDirContents(size_t maxEntries)const{
if(!this->isDir()){
throw papki::Exc("FSFile::ListDirContents(): this is not a directory");
}
std::vector<std::string> files;
#if M_OS == M_OS_WINDOWS
{
std::string pattern = this->path();
pattern += '*';
TRACE(<< "FSFile::ListDirContents(): pattern = " << pattern << std::endl)
WIN32_FIND_DATA wfd;
HANDLE h = FindFirstFile(pattern.c_str(), &wfd);
if (h == INVALID_HANDLE_VALUE) {
throw papki::Exc("ListDirContents(): cannot find first file");
}
//create Find Closer to automatically call FindClose on exit from the function in case of exceptions etc...
{
struct FindCloser {
HANDLE hnd;
FindCloser(HANDLE h) :
hnd(h)
{}
~FindCloser() {
FindClose(this->hnd);
}
} findCloser(h);
do {
std::string s(wfd.cFileName);
ASSERT(s.size() > 0)
//do not add ./ and ../ directories, we are not interested in them
if (s == "." || s == "..") {
continue;
}
if (((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) && s[s.size() - 1] != '/') {
s += '/';
}
files.push_back(s);
if (files.size() == maxEntries) {
break;
}
} while (FindNextFile(h, &wfd) != 0);
if (GetLastError() != ERROR_NO_MORE_FILES) {
throw papki::Exc("ListDirContents(): find next file failed");
}
}
}
#elif M_OS == M_OS_LINUX || M_OS == M_OS_MACOSX
{
DIR *pdir = opendir(this->path().c_str());
if(!pdir){
std::stringstream ss;
ss << "FSFile::ListDirContents(): opendir() failure, error code = " << strerror(errno);
throw papki::Exc(ss.str());
}
//create DirentCloser to automatically call closedir on exit from the function in case of exceptions etc...
struct DirCloser{
DIR *pdir;
DirCloser(DIR *pDirToClose) :
pdir(pDirToClose)
{}
~DirCloser(){
int ret;
do{
ret = closedir(this->pdir);
ASSERT_INFO(ret == 0 || errno == EINTR, "FSFile::ListDirContents(): closedir() failed: " << strerror(errno))
}while(ret != 0 && errno == EINTR);
}
} dirCloser(pdir);
errno = 0;//clear errno
while(dirent *pent = readdir(pdir)){
std::string s(pent->d_name);
if(s == "." || s == "..")
continue;//do not add ./ and ../ directories, we are not interested in them
struct stat fileStats;
//TRACE(<< s << std::endl)
if(stat((this->path() + s).c_str(), &fileStats) < 0){
std::stringstream ss;
ss << "FSFile::ListDirContents(): stat() failure, error code = " << strerror(errno);
throw papki::Exc(ss.str());
}
if(fileStats.st_mode & S_IFDIR)//if this entry is a directory append '/' symbol to its end
s += "/";
files.push_back(s);
if(files.size() == maxEntries){
break;
}
}//~while()
//check if we exited the while() loop because of readdir() failed
if(errno != 0){
std::stringstream ss;
ss << "FSFile::ListDirContents(): readdir() failure, error code = " << strerror(errno);
throw papki::Exc(ss.str());
}
}
#else
# error "FSFile::ListDirContents(): version is not implemented yet for this os"
#endif
return std::move(files);
}
std::unique_ptr<File> FSFile::spawn(){
return utki::makeUnique<FSFile>();
}
<|endoftext|> |
<commit_before>#include <clang-c/Index.h>
#include <cstdio>
#include <iostream>
#include <vector>
namespace {
const unsigned int indent_spaces = 4;
}
CXCursor tu_cursor;
struct client_data
{
CXTranslationUnit tu;
std::vector<CXCursor> current_namespaces;
CXCursor current_struct;
};
std::pair<CXToken*, unsigned int>
get_tokens (CXTranslationUnit tu, CXCursor cursor)
{
CXSourceRange range = clang_getCursorExtent(cursor);
CXSourceLocation start = clang_getRangeStart(range);
CXSourceLocation end = clang_getRangeEnd(range);
unsigned int start_offset, end_offset;
std::pair<CXToken*, unsigned int> retval(0, 0);
clang_tokenize(tu, range, &retval.first, &retval.second);
return retval;
}
void
free_tokens (CXTranslationUnit tu, std::pair<CXToken*, unsigned int> tokens)
{ clang_disposeTokens(tu, tokens.first, tokens.second); }
void print_tokens (CXTranslationUnit tu, CXCursor cursor)
{
std::pair<CXToken*, unsigned int> tokens = get_tokens(tu, cursor);
for (unsigned int i = 0; i < tokens.second; ++i) {
if (i)
std::cout << " ";
CXString spelling = clang_getTokenSpelling(tu, tokens.first[i]);
std::cout << clang_getCString(spelling);
}
std::cout << "\n";
free_tokens(tu, tokens);
}
bool struct_kind (CXCursorKind kind)
{
switch (kind) {
case CXCursor_ClassDecl:
case CXCursor_StructDecl:
case CXCursor_ClassTemplate:
case CXCursor_ClassTemplatePartialSpecialization:
return true;
}
return false;
}
std::string indent (const client_data& data)
{
std::size_t size = data.current_namespaces.size();
return std::string(size * indent_spaces, ' ');
}
void open_struct (const client_data& data, CXCursor struct_cursor)
{
std::pair<CXToken*, unsigned int> tokens =
get_tokens(data.tu, struct_cursor);
std::cout << "\n" << indent(data);
const std::string open_brace = "{";
const std::string struct_ = "struct";
const std::string class_ = "class";
for (unsigned int i = 0; i < tokens.second; ++i) {
CXString spelling = clang_getTokenSpelling(data.tu, tokens.first[i]);
const char* c_str = clang_getCString(spelling);
if (c_str == open_brace)
break;
if (c_str == struct_ || c_str == class_) {
std::cout << "\n" << indent(data);
} else if (i) {
std::cout << " ";
}
std::cout << c_str;
}
free_tokens(data.tu, tokens);
std::cout << "\n"
<< indent(data) << "{\n"
<< indent(data) << "public:\n";
const char* public_interface[] = {
0,
"any_printable () = default;",
0,
"template <typename T>",
"any_printable (T value) :",
" handle_ (",
" std::make_shared<",
" handle<typename std::remove_reference<T>::type>",
" >(std::forward<T>(value))",
" )",
"{}",
0,
"any_printable (any_printable && rhs) noexcept = default;",
0,
"template <typename T>",
"any_printable & operator= (T value)",
"{",
" if (handle_.unique())",
" *handle_ = std::forward<T>(value);",
" else if (!handle_)",
" handle_ = std::make_shared<T>(std::forward<T>(value));",
" return *this;",
"}",
0,
"any_printable & operator= (any_printable && rhs) noexcept = default;"
};
std::string padding(indent_spaces, ' ');
for (unsigned int i = 0;
i < sizeof(public_interface) / sizeof(const char*);
++i) {
if (public_interface[i])
std::cout << indent(data) << padding << public_interface[i] << "\n";
else
std::cout << "\n";
}
}
void close_struct (const client_data& data)
{
std::cout << "\n\n"
<< indent(data) << "private:\n";
std::cout << "\n"
<< indent(data) << " // TODO\n";
std::cout << "\n"
<< indent(data) << "};\n";
}
void print_member_function(const client_data& data, CXCursor cursor)
{
std::pair<CXToken*, unsigned int> tokens = get_tokens(data.tu, cursor);
std::cout << "\n"
<< std::string(indent_spaces, ' ') << indent(data);
const std::string open_brace = "{";
const std::string semicolon = ";";
for (unsigned int i = 0; i < tokens.second; ++i) {
CXString spelling = clang_getTokenSpelling(data.tu, tokens.first[i]);
const char* c_str = clang_getCString(spelling);
if (c_str == open_brace || c_str == semicolon)
break;
if (i)
std::cout << " ";
std::cout << c_str;
}
free_tokens(data.tu, tokens);
const char* return_str =
clang_getCursorResultType(cursor).kind == CXType_Void ? "" : "return ";
std::cout << "\n" << std::string(indent_spaces, ' ') << indent(data)
<< "{ assert(handle_); " << return_str << "handle_->"
<< clang_getCString(clang_getCursorSpelling(cursor))
<< "( ";
const int args = clang_Cursor_getNumArguments(cursor);
for (int i = 0; i < args; ++i) {
if (i)
std::cout << ", ";
CXCursor arg_cursor = clang_Cursor_getArgument(cursor, i);
std::cout << clang_getCString(clang_getCursorSpelling(arg_cursor));
}
std::cout << " ); }\n";
}
void open_namespace (const client_data& data, CXCursor namespace_)
{
std::cout
<< "\n"
<< indent(data)
<< "namespace "
<< clang_getCString(clang_getCursorSpelling(namespace_))
<< " {";
}
void close_namespace (const client_data& data)
{ std::cout << "\n" << indent(data) << "}\n"; }
void dump_cursor (const char* name, CXCursor cursor)
{
CXCursorKind kind = clang_getCursorKind(cursor);
CXString kind_spelling = clang_getCursorKindSpelling(kind);
CXString cursor_spelling = clang_getCursorSpelling(cursor);
std::cout << name << " "
<< clang_getCString(kind_spelling) << " "
<< clang_getCString(cursor_spelling) << " "
<< "\n";
}
CXChildVisitResult
visitor (CXCursor cursor, CXCursor parent, CXClientData data_)
{
client_data& data = *static_cast<client_data*>(data_);
#if 0
std::cout << "\n";
dump_cursor("cursor", cursor);
dump_cursor("parent", parent);
#endif
CXCursor null_cursor = clang_getNullCursor();
// close open namespaces we have left
CXCursor enclosing_namespace = parent;
while (!clang_equalCursors(enclosing_namespace, tu_cursor) &&
clang_getCursorKind(enclosing_namespace) != CXCursor_Namespace) {
enclosing_namespace =
clang_getCursorSemanticParent(enclosing_namespace);
}
#if 0
dump_cursor("enclosing_namespace", enclosing_namespace);
#endif
if (!clang_equalCursors(enclosing_namespace, tu_cursor) &&
clang_getCursorKind(enclosing_namespace) == CXCursor_Namespace) {
while (!clang_equalCursors(enclosing_namespace,
data.current_namespaces.back())) {
data.current_namespaces.pop_back();
close_namespace(data);
}
}
// close open struct if we have left it
CXCursor enclosing_struct = parent;
while (!clang_equalCursors(enclosing_struct, tu_cursor) &&
!struct_kind(clang_getCursorKind(enclosing_struct))) {
enclosing_struct = clang_getCursorSemanticParent(enclosing_struct);
}
#if 0
dump_cursor("enclosing_struct", enclosing_struct);
#endif
if (!clang_Cursor_isNull(data.current_struct) &&
!clang_equalCursors(enclosing_struct, data.current_struct)) {
data.current_struct = null_cursor;
close_struct(data);
}
CXCursorKind kind = clang_getCursorKind(cursor);
if (kind == CXCursor_Namespace) {
open_namespace(data, cursor);
data.current_namespaces.push_back(cursor);
return CXChildVisit_Recurse;
} else if (struct_kind(kind)) {
if (clang_Cursor_isNull(data.current_struct)) {
data.current_struct = cursor;
open_struct(data, cursor);
return CXChildVisit_Recurse;
}
} else if (kind == CXCursor_CXXMethod) {
print_member_function(data, cursor);
}
return CXChildVisit_Continue;
}
int main (int argc, char* argv[])
{
CXIndex index = clang_createIndex(0, 1);
CXTranslationUnit tu = clang_parseTranslationUnit(
index,
0,
argv,
argc,
0,
0,
CXTranslationUnit_None
);
client_data data = {tu, {}, clang_getNullCursor()};
tu_cursor = clang_getTranslationUnitCursor(tu);
clang_visitChildren(tu_cursor, visitor, &data);
if (!clang_Cursor_isNull(data.current_struct))
close_struct(data);
while (!data.current_namespaces.empty()) {
data.current_namespaces.pop_back();
close_namespace(data);
}
clang_disposeTranslationUnit(tu);
clang_disposeIndex(index);
return 0;
}
<commit_msg>Flesh out close_struct().<commit_after>#include <clang-c/Index.h>
#include <cstdio>
#include <iostream>
#include <vector>
namespace {
const unsigned int indent_spaces = 4;
}
CXCursor tu_cursor;
struct client_data
{
CXTranslationUnit tu;
std::vector<CXCursor> current_namespaces;
CXCursor current_struct;
};
std::pair<CXToken*, unsigned int>
get_tokens (CXTranslationUnit tu, CXCursor cursor)
{
CXSourceRange range = clang_getCursorExtent(cursor);
CXSourceLocation start = clang_getRangeStart(range);
CXSourceLocation end = clang_getRangeEnd(range);
unsigned int start_offset, end_offset;
std::pair<CXToken*, unsigned int> retval(0, 0);
clang_tokenize(tu, range, &retval.first, &retval.second);
return retval;
}
void
free_tokens (CXTranslationUnit tu, std::pair<CXToken*, unsigned int> tokens)
{ clang_disposeTokens(tu, tokens.first, tokens.second); }
void print_tokens (CXTranslationUnit tu, CXCursor cursor)
{
std::pair<CXToken*, unsigned int> tokens = get_tokens(tu, cursor);
for (unsigned int i = 0; i < tokens.second; ++i) {
if (i)
std::cout << " ";
CXString spelling = clang_getTokenSpelling(tu, tokens.first[i]);
std::cout << clang_getCString(spelling);
}
std::cout << "\n";
free_tokens(tu, tokens);
}
bool struct_kind (CXCursorKind kind)
{
switch (kind) {
case CXCursor_ClassDecl:
case CXCursor_StructDecl:
case CXCursor_ClassTemplate:
case CXCursor_ClassTemplatePartialSpecialization:
return true;
}
return false;
}
std::string indent (const client_data& data)
{
std::size_t size = data.current_namespaces.size();
return std::string(size * indent_spaces, ' ');
}
void print (const client_data& data, const char** lines, std::size_t num_lines)
{
std::string padding(indent_spaces, ' ');
for (unsigned int i = 0; i < num_lines; ++i) {
if (lines[i])
std::cout << indent(data) << padding << lines[i] << "\n";
else
std::cout << "\n";
}
}
void open_struct (const client_data& data, CXCursor struct_cursor)
{
std::pair<CXToken*, unsigned int> tokens =
get_tokens(data.tu, struct_cursor);
std::cout << "\n" << indent(data);
const std::string open_brace = "{";
const std::string struct_ = "struct";
const std::string class_ = "class";
for (unsigned int i = 0; i < tokens.second; ++i) {
CXString spelling = clang_getTokenSpelling(data.tu, tokens.first[i]);
const char* c_str = clang_getCString(spelling);
if (c_str == open_brace)
break;
if (c_str == struct_ || c_str == class_) {
std::cout << "\n" << indent(data);
} else if (i) {
std::cout << " ";
}
std::cout << c_str;
}
free_tokens(data.tu, tokens);
std::cout << "\n"
<< indent(data) << "{\n"
<< indent(data) << "public:\n";
const char* public_interface[] = {
0,
"any_printable () = default;",
0,
"template <typename T_T__>",
"any_printable (T_T__ value) :",
" handle_ (",
" std::make_shared<",
" handle<typename std::remove_reference<T_T__>::type>",
" >(std::forward<T_T__>(value))",
" )",
"{}",
0,
"any_printable (any_printable && rhs) noexcept = default;",
0,
"template <typename T_T__>",
"any_printable & operator= (T_T__ value)",
"{",
" if (handle_.unique())",
" *handle_ = std::forward<T_T__>(value);",
" else if (!handle_)",
" handle_ = std::make_shared<T_T__>(std::forward<T_T__>(value));",
" return *this;",
"}",
0,
"any_printable & operator= (any_printable && rhs) noexcept = default;"
};
print(data,
public_interface,
sizeof(public_interface) / sizeof(const char*));
}
void close_struct (const client_data& data)
{
std::cout << "\n"
<< indent(data) << "private:\n";
const char* handle_base_preamble[] = {
0,
"struct handle_base",
"{",
" virtual ~handle_base () {}",
" virtual std::shared_ptr<handle_base> close () const = 0;",
0
};
print(data,
handle_base_preamble,
sizeof(handle_base_preamble) / sizeof(const char*));
// TODO: pure virtual
const char* handle_preamble[] = {
"};",
0,
"template <typename T_T__>",
"struct handle :",
" handle_base",
"{",
" template <typename T_T__>",
" handle (T_T__ value,",
" typename std::enable_if<",
" std::is_reference<U_U__>::value",
" >::type* = 0) :",
" value_ (value)",
" {}",
0,
" template <typename U_U__ = T_T__>",
" handle (T_T__ value,",
" typename std::enable_if<",
" !std::is_reference<U_U__>::value,",
" int",
" >::type* = 0) noexcept :",
" value_ (std::move(value))",
" {}",
0,
" virtual std::shared_ptr<handle_base> clone () const",
" { return std::make_shared<handle>(value_); }"
};
print(data,
handle_preamble,
sizeof(handle_preamble) / sizeof(const char*));
// TODO: virtual implementations
const char* handle_postamble[] = {
0,
" T_T__ value_;",
"};",
0,
"template <typename T_T__>",
"struct handle<std::reference_wrapper<T_T__>> :",
" handle<T_T__ &>",
"{",
" handle (std::reference_wrapper<T_T__> ref) :",
" handle<T_T__ &> (ref.get())",
" {}",
"};",
0,
"const handle_base & read () const",
"{ return *handle_; }",
0,
"handle_base & write ()",
"{",
" if (!handle_.unique())",
" handle_ = handle_->clone();",
" return *handle_;",
"}",
0,
"std::shared_ptr<handle_base> handle_;"
};
print(data,
handle_postamble,
sizeof(handle_postamble) / sizeof(const char*));
std::cout << "\n"
<< indent(data) << "};\n";
}
void print_member_function(const client_data& data, CXCursor cursor)
{
std::pair<CXToken*, unsigned int> tokens = get_tokens(data.tu, cursor);
std::cout << "\n"
<< std::string(indent_spaces, ' ') << indent(data);
const std::string open_brace = "{";
const std::string semicolon = ";";
for (unsigned int i = 0; i < tokens.second; ++i) {
CXString spelling = clang_getTokenSpelling(data.tu, tokens.first[i]);
const char* c_str = clang_getCString(spelling);
if (c_str == open_brace || c_str == semicolon)
break;
if (i)
std::cout << " ";
std::cout << c_str;
}
free_tokens(data.tu, tokens);
const char* return_str =
clang_getCursorResultType(cursor).kind == CXType_Void ? "" : "return ";
std::cout << "\n" << std::string(indent_spaces, ' ') << indent(data)
<< "{ assert(handle_); " << return_str << "handle_->"
<< clang_getCString(clang_getCursorSpelling(cursor))
<< "( ";
const int args = clang_Cursor_getNumArguments(cursor);
for (int i = 0; i < args; ++i) {
if (i)
std::cout << ", ";
CXCursor arg_cursor = clang_Cursor_getArgument(cursor, i);
std::cout << clang_getCString(clang_getCursorSpelling(arg_cursor));
}
std::cout << " ); }\n";
}
void open_namespace (const client_data& data, CXCursor namespace_)
{
std::cout
<< "\n"
<< indent(data)
<< "namespace "
<< clang_getCString(clang_getCursorSpelling(namespace_))
<< " {";
}
void close_namespace (const client_data& data)
{ std::cout << "\n" << indent(data) << "}\n"; }
void dump_cursor (const char* name, CXCursor cursor)
{
CXCursorKind kind = clang_getCursorKind(cursor);
CXString kind_spelling = clang_getCursorKindSpelling(kind);
CXString cursor_spelling = clang_getCursorSpelling(cursor);
std::cout << name << " "
<< clang_getCString(kind_spelling) << " "
<< clang_getCString(cursor_spelling) << " "
<< "\n";
}
CXChildVisitResult
visitor (CXCursor cursor, CXCursor parent, CXClientData data_)
{
client_data& data = *static_cast<client_data*>(data_);
#if 0
std::cout << "\n";
dump_cursor("cursor", cursor);
dump_cursor("parent", parent);
#endif
CXCursor null_cursor = clang_getNullCursor();
// close open namespaces we have left
CXCursor enclosing_namespace = parent;
while (!clang_equalCursors(enclosing_namespace, tu_cursor) &&
clang_getCursorKind(enclosing_namespace) != CXCursor_Namespace) {
enclosing_namespace =
clang_getCursorSemanticParent(enclosing_namespace);
}
#if 0
dump_cursor("enclosing_namespace", enclosing_namespace);
#endif
if (!clang_equalCursors(enclosing_namespace, tu_cursor) &&
clang_getCursorKind(enclosing_namespace) == CXCursor_Namespace) {
while (!clang_equalCursors(enclosing_namespace,
data.current_namespaces.back())) {
data.current_namespaces.pop_back();
close_namespace(data);
}
}
// close open struct if we have left it
CXCursor enclosing_struct = parent;
while (!clang_equalCursors(enclosing_struct, tu_cursor) &&
!struct_kind(clang_getCursorKind(enclosing_struct))) {
enclosing_struct = clang_getCursorSemanticParent(enclosing_struct);
}
#if 0
dump_cursor("enclosing_struct", enclosing_struct);
#endif
if (!clang_Cursor_isNull(data.current_struct) &&
!clang_equalCursors(enclosing_struct, data.current_struct)) {
data.current_struct = null_cursor;
close_struct(data);
}
CXCursorKind kind = clang_getCursorKind(cursor);
if (kind == CXCursor_Namespace) {
open_namespace(data, cursor);
data.current_namespaces.push_back(cursor);
return CXChildVisit_Recurse;
} else if (struct_kind(kind)) {
if (clang_Cursor_isNull(data.current_struct)) {
data.current_struct = cursor;
open_struct(data, cursor);
return CXChildVisit_Recurse;
}
} else if (kind == CXCursor_CXXMethod) {
print_member_function(data, cursor);
}
return CXChildVisit_Continue;
}
int main (int argc, char* argv[])
{
CXIndex index = clang_createIndex(0, 1);
CXTranslationUnit tu = clang_parseTranslationUnit(
index,
0,
argv,
argc,
0,
0,
CXTranslationUnit_None
);
client_data data = {tu, {}, clang_getNullCursor()};
tu_cursor = clang_getTranslationUnitCursor(tu);
clang_visitChildren(tu_cursor, visitor, &data);
if (!clang_Cursor_isNull(data.current_struct))
close_struct(data);
while (!data.current_namespaces.empty()) {
data.current_namespaces.pop_back();
close_namespace(data);
}
clang_disposeTranslationUnit(tu);
clang_disposeIndex(index);
return 0;
}
<|endoftext|> |
<commit_before>/*
Elcano_Serial.cpp
Tyler Folsom Sept 7, 2015
The routines writeSerial and readSerial transfer the information in a SerialData
structure over serial lines connecting Arduino microcontrollers. The contents of the messages are specified in SerialCmd.html. Note that messages are limited to 64 characters.
Data transfer has been verified by the program SerialUnitTest.ino.
When running a program from your sketchbook, create the subdirectory
libraries/Elcano_Serial, and place both Elcano_Serial.cpp and Elcano_Serial.h there.
*/
#include "string.h"
#include "math.h"
#include "Elcano_Serial.h"
/*------------------------------------------------------------------------------*/
char * GetWord(char * major, char * str)
{
char * CSp1;
CSp1 = strstr( str, major);
if (CSp1!=NULL)
CSp1 += strlen(major);
return CSp1;
}
/*-------------------------------------------------------------------------------*/
float GetNumber(char *minor, char*Args)
{
float data = NaN;
if (Args == NULL) return data;
// minor is a keyword; grab the associated value.
char * Number = GetWord(minor, Args);
if (Number==NULL) return data;
// change } to 0
char* end = strchr(Number, '}');
if (end == NULL) return NaN;
*end = '\0';
data = atof(Number);
// change back to }
*end = '}';
return data;
}
/*---------------------------------------------------------------------------------------*/
void GetPos(char *minor, char*Args, SerialData *SerialD)
{
SerialD->posE_cm = SerialD->posN_cm = NaN;
if (Args == NULL) return;
// minor is a keyword; grab the associated value.
char * Number = GetWord(minor, Args);
if (Number==NULL) return;
// change , to 0
char* end = strchr(Number, ',');
if (end == NULL) return;
*end = '\0';
SerialD->posE_cm = (long) atof(Number);
// change back to ,
*end = ',';
Number = end+1; // 2nd number
// change } to 0
SerialD->posN_cm = (long) atof(Number);
end = strchr(Number, '}');
if (end == NULL) return;
*end = '\0';
SerialD->posN_cm = atof(Number);
// change back to ,
*end = ',';
}
/*-------------------------------------------------------------------------------*/
void SerialData::Clear()
{
kind = MSG_NONE;
number = NaN;
speed_cmPs = NaN;
angle_deg = NaN;
bearing_deg = NaN;
posE_cm = NaN;
posN_cm = NaN;
probability = NaN;
}
/*-------------------------------------------------------------------------------*/
void Dump (char *IncomingMessage, SerialData *SerialD)
{
Serial.println();
Serial.println(IncomingMessage);
Serial.print ( "Kind "); Serial.print(SerialD->kind);
Serial.print ( "; Num "); Serial.print(SerialD->number);
Serial.print ( "; Speed "); Serial.print(SerialD->speed_cmPs);
Serial.print ( "; Ang "); Serial.print(SerialD->angle_deg );
Serial.print ( "; Br "); Serial.print(SerialD->bearing_deg );
Serial.print ( "; pos ("); Serial.print(SerialD->posE_cm);
Serial.print ( ", "); Serial.print(SerialD->posN_cm);
Serial.print ( ") Prob "); Serial.println(SerialD->probability);
}
/*-------------------------------------------------------------------------------*/
void ProcessMessage (char *IncomingMessage, SerialData *SerialD)
{
float data;
// Dump (IncomingMessage, SerialD) ; // debug
// Determine if message is "SENSOR {Speed xxx.xx}"
char * Args = GetWord ("SENSOR", IncomingMessage);
if (Args != NULL)
{
data = GetNumber("Speed", Args);
if (data != NaN)
{
SerialD->speed_cmPs = (long)(data);
SerialD->kind = MSG_SENSOR;
}
data = GetNumber("Ang", Args);
if (data != NaN)
{
SerialD->angle_deg = (long)(data);
SerialD->kind = MSG_SENSOR;
}
data = GetNumber("Br", Args);
if (data != NaN)
{
SerialD->bearing_deg = (long)(data);
SerialD->kind = MSG_SENSOR;
}
GetPos("Pos", Args, SerialD);
if (SerialD->posN_cm != NaN && SerialD->posE_cm != NaN)
SerialD->kind = MSG_SENSOR;
}
// Determine if message is "DRIVE {Speed xxx.xx}"
Args = GetWord ("DRIVE", IncomingMessage);
if (Args != NULL)
{
data = GetNumber("Speed", Args);
if (data != NaN)
{
SerialD->c = (long)(data);
SerialD->kind = MSG_DRIVE;
}
data = GetNumber("Ang", Args);
if (data != NaN)
{
SerialD->angle_deg = (long)(data);
SerialD->kind = MSG_DRIVE;
}
}
Args = GetWord ("GOAL", IncomingMessage);
if (Args != NULL)
{
data = GetNumber("Num", Args);
if (data != NaN)
{
SerialD->number = (long)(data);
}
GetPos("Pos", Args, SerialD);
data = GetNumber("Br", Args);
if (data != NaN)
{
SerialD->bearing_deg = (long)(data);
}
data = GetNumber("Prob", Args);
if (data != NaN)
{ // from vision: probability that cone is present in the image
SerialD->probability = (long)(data);
}
if (SerialD->posN_cm != NaN && SerialD->posE_cm != NaN) // && SerialD->number > 0)
SerialD->kind = MSG_GOAL;
}
Args = GetWord ("SEG", IncomingMessage);
if (Args != NULL)
{
data = GetNumber("Num", Args);
if (data != NaN)
{
SerialD->number = (long)(data);
}
data = GetNumber("Speed", Args);
if (data != NaN)
{
SerialD->speed_cmPs = (long)(data);
}
data = GetNumber("Br", Args);
if (data != NaN)
{
SerialD->bearing_deg = (long)(data);
}
GetPos("Pos", Args, SerialD);
if (SerialD->posN_cm != NaN && SerialD->posE_cm != NaN && SerialD->number != NaN)
SerialD->kind = MSG_SEG;
}
}
/*------------------------------------------------------------------------------*/
// If there is an issue with missing data the kind might not be correctly set
// for sending that data.
void readSerial(HardwareSerial *SerialN, SerialData *SerialD)
{
SerialD->Clear();
char IncomingMessage[BUFFER_SIZE];
int InIndex=0; // Input side, current character of SerialDrive message
int incomingByte = 0; // for incoming serial data
while (SerialN->available() > 0)
{
// read the incoming byte from C4:
incomingByte = SerialN->read();
IncomingMessage[InIndex] = (char)(incomingByte);
IncomingMessage[InIndex+1] = 0;
if (IncomingMessage[InIndex] == 0 || incomingByte == '\n' || incomingByte == '\r'
|| InIndex >= BUFFER_SIZE-1)
{
ProcessMessage(&IncomingMessage[0], SerialD); // see what we got
for (InIndex = 0; InIndex < BUFFER_SIZE; InIndex++)
IncomingMessage[InIndex] = 0;
InIndex = 0;
IncomingMessage[InIndex] = 0;
}
else
{
// incomingByte > 31? Serial.print(IncomingMessage[InIndex]): Serial.print(incomingByte);
++InIndex;
}
}
}
/*-------------------------------------------------------------------------------*/
void writeSerial(HardwareSerial *SerialN, struct SerialData *SerialD )
{
// Caution: 64 character limit for Arduino serial. Buffer size is set in the Arduino core.
// If the message produced is > 64 characters, readSerial will ignore it.
// writeSerial will only send data that relates to the kind. ex In the Serial data struct
//if kind is 0 the only data sent will be kind angle and direction.
switch (SerialD->kind)
{
case MSG_DRIVE:
SerialN->print("DRIVE");
if (SerialD->speed_cmPs != NaN)
{
SerialN->print(" {Speed ");
SerialN->print(SerialD->speed_cmPs);
SerialN->print("}");
}
if (SerialD->angle_deg != NaN)
{
SerialN->print(" {Ang ");
SerialN->print(SerialD->angle_deg);
SerialN->print("}");
}
SerialN->println("\0");
break;
case MSG_SENSOR:
SerialN->print("SENSOR");
if (SerialD->speed_cmPs != NaN)
{
SerialN->print(" {Speed ");
SerialN->print(SerialD->speed_cmPs);
SerialN->print("}");
}
if (SerialD->angle_deg != NaN)
{
SerialN->print(" {Ang ");
SerialN->print(SerialD->angle_deg);
SerialN->print("}");
}
if (SerialD->posE_cm != NaN && SerialD->posN_cm != NaN)
{
SerialN->print(" {Pos ");
SerialN->print(SerialD->posE_cm);
SerialN->print(",");
SerialN->print(SerialD->posN_cm);
SerialN->print("}");
}
if (SerialD->bearing_deg != NaN)
{
SerialN->print(" {Br ");
SerialN->print(SerialD->bearing_deg);
SerialN->print("}");
}
SerialN->println("\0");
break;
case MSG_GOAL:
SerialN->print("GOAL");
if (SerialD->number != NaN)
{
SerialN->print(" {Num ");
SerialN->print(SerialD->number);
SerialN->print("}");
}
if (SerialD->posE_cm != NaN && SerialD->posN_cm != NaN)
{
SerialN->print(" {Pos ");
SerialN->print(SerialD->posE_cm);
SerialN->print(",");
SerialN->print(SerialD->posN_cm);
SerialN->print("}");
}
if (SerialD->bearing_deg != NaN)
{
SerialN->print(" {Br ");
SerialN->print(SerialD->bearing_deg);
SerialN->print("}");
}
if (SerialD->probability != NaN)
{
SerialN->print(" {Prob ");
SerialN->print(SerialD->probability);
SerialN->print("}");
}
SerialN->println("\0");
break;
case MSG_SEG:
SerialN->print("SEG");
if (SerialD->number != NaN)
{
SerialN->print(" {Num ");
SerialN->print(SerialD->number);
SerialN->print("}");
}
if (SerialD->posE_cm != NaN && SerialD->posN_cm != NaN)
{
SerialN->print(" {Pos ");
SerialN->print(SerialD->posE_cm);
SerialN->print(",");
SerialN->print(SerialD->posN_cm);
SerialN->print("}");
}
if (SerialD->bearing_deg != NaN)
{
SerialN->print(" {Br ");
SerialN->print(SerialD->bearing_deg);
SerialN->print("}");
}
if (SerialD->speed_cmPs != NaN)
{
SerialN->print(" {Speed ");
SerialN->print(SerialD->speed_cmPs);
SerialN->print("}");
}
SerialN->println("\0");
break;
case MSG_NONE:
default:
break;
}
}
<commit_msg>static modifications to ElcanoSerial library<commit_after>/*
Elcano_Serial.cpp
Tyler Folsom Sept 7, 2015
The routines writeSerial and readSerial transfer the information in a SerialData
structure over serial lines connecting Arduino microcontrollers. The contents of the messages are specified in SerialCmd.html. Note that messages are limited to 64 characters.
Data transfer has been verified by the program SerialUnitTest.ino.
When running a program from your sketchbook, create the subdirectory
libraries/Elcano_Serial, and place both Elcano_Serial.cpp and Elcano_Serial.h there.
*/
#include "string.h"
#include "math.h"
#include "Elcano_Serial.h"
/*------------------------------------------------------------------------------*/
// What does this do?
char * GetWord(char * major, char * str){
char * CSp1;
CSp1 = strstr( str, major);
if (CSp1!=NULL)
CSp1 += strlen(major);
return CSp1;
}
/*-------------------------------------------------------------------------------*/
float GetNumber(char *minor, char*Args)
{
float data = NaN;
if (Args == NULL) return data;
// minor is a keyword; grab the associated value.
char * Number = GetWord(minor, Args);
if (Number==NULL) return data;
// change } to 0
char* end = strchr(Number, '}');
if (end == NULL) return NaN;
*end = '\0';
data = atof(Number);
// change back to }
*end = '}';
return data;
}
/*---------------------------------------------------------------------------------------*/
void GetPos(char *minor, char*Args, SerialData *SerialD)
{
SerialD->posE_cm = SerialD->posN_cm = NaN;
if (Args == NULL) return;
// minor is a keyword; grab the associated value.
char * Number = GetWord(minor, Args);
if (Number==NULL) return;
// change , to 0
char* end = strchr(Number, ',');
if (end == NULL) return;
*end = '\0';
SerialD->posE_cm = (long) atof(Number);
// change back to ,
*end = ',';
Number = end+1; // 2nd number
// change } to 0
SerialD->posN_cm = (long) atof(Number);
end = strchr(Number, '}');
if (end == NULL) return;
*end = '\0';
SerialD->posN_cm = atof(Number);
// change back to ,
*end = ',';
}
/*-------------------------------------------------------------------------------*/
void SerialData::Clear()
{
kind = MSG_NONE;
number = NaN;
speed_cmPs = NaN;
angle_deg = NaN;
bearing_deg = NaN;
posE_cm = NaN;
posN_cm = NaN;
probability = NaN;
}
/*-------------------------------------------------------------------------------*/
void Dump (char *IncomingMessage, SerialData *SerialD)
{
Serial.println();
Serial.println(IncomingMessage);
Serial.print ( "Kind "); Serial.print(SerialD->kind);
Serial.print ( "; Num "); Serial.print(SerialD->number);
Serial.print ( "; Speed "); Serial.print(SerialD->speed_cmPs);
Serial.print ( "; Ang "); Serial.print(SerialD->angle_deg );
Serial.print ( "; Br "); Serial.print(SerialD->bearing_deg );
Serial.print ( "; pos ("); Serial.print(SerialD->posE_cm);
Serial.print ( ", "); Serial.print(SerialD->posN_cm);
Serial.print ( ") Prob "); Serial.println(SerialD->probability);
}
/*-------------------------------------------------------------------------------*/
void ProcessMessage (char *IncomingMessage, SerialData *SerialD)
{
float data;
// Dump (IncomingMessage, SerialD) ; // debug
// Determine if message is "SENSOR {Speed xxx.xx}"
char * Args = GetWord ("SENSOR", IncomingMessage);
if (Args != NULL)
{
data = GetNumber("Speed", Args);
if (data != NaN)
{
SerialD->speed_cmPs = (long)(data);
SerialD->kind = MSG_SENSOR;
}
data = GetNumber("Ang", Args);
if (data != NaN)
{
SerialD->angle_deg = (long)(data);
SerialD->kind = MSG_SENSOR;
}
data = GetNumber("Br", Args);
if (data != NaN)
{
SerialD->bearing_deg = (long)(data);
SerialD->kind = MSG_SENSOR;
}
GetPos("Pos", Args, SerialD);
if (SerialD->posN_cm != NaN && SerialD->posE_cm != NaN)
SerialD->kind = MSG_SENSOR;
}
// Determine if message is "DRIVE {Speed xxx.xx}"
Args = GetWord ("DRIVE", IncomingMessage);
if (Args != NULL)
{
data = GetNumber("Speed", Args);
if (data != NaN)
{
SerialD->speed_cmPs = (long)(data);
SerialD->kind = MSG_DRIVE;
}
data = GetNumber("Ang", Args);
if (data != NaN)
{
SerialD->angle_deg = (long)(data);
SerialD->kind = MSG_DRIVE;
}
}
Args = GetWord ("GOAL", IncomingMessage);
if (Args != NULL)
{
data = GetNumber("Num", Args);
if (data != NaN)
{
SerialD->number = (long)(data);
}
GetPos("Pos", Args, SerialD);
data = GetNumber("Br", Args);
if (data != NaN)
{
SerialD->bearing_deg = (long)(data);
}
data = GetNumber("Prob", Args);
if (data != NaN)
{ // from vision: probability that cone is present in the image
SerialD->probability = (long)(data);
}
if (SerialD->posN_cm != NaN && SerialD->posE_cm != NaN) // && SerialD->number > 0)
SerialD->kind = MSG_GOAL;
}
Args = GetWord ("SEG", IncomingMessage);
if (Args != NULL)
{
data = GetNumber("Num", Args);
if (data != NaN)
{
SerialD->number = (long)(data);
}
data = GetNumber("Speed", Args);
if (data != NaN)
{
SerialD->speed_cmPs = (long)(data);
}
data = GetNumber("Br", Args);
if (data != NaN)
{
SerialD->bearing_deg = (long)(data);
}
GetPos("Pos", Args, SerialD);
if (SerialD->posN_cm != NaN && SerialD->posE_cm != NaN && SerialD->number != NaN)
SerialD->kind = MSG_SEG;
}
}
/*------------------------------------------------------------------------------*/
// If there is an issue with missing data the kind might not be correctly set
// for sending that data.
void readSerial(HardwareSerial *SerialN, SerialData *SerialD)
{
SerialD->Clear();
static char IncomingMessage[BUFFER_SIZE];
static int InIndex=0; // Input side, current character of SerialDrive message
int incomingByte = 0; // for incoming serial data
while (SerialN->available())
{
// read the incoming byte from C4:
incomingByte = SerialN->read();
IncomingMessage[InIndex] = (char)(incomingByte);
IncomingMessage[InIndex+1] = 0;
if (IncomingMessage[InIndex] == 0 || incomingByte == '\n' || incomingByte == '\r'
|| InIndex >= BUFFER_SIZE-1)
{
ProcessMessage(&IncomingMessage[0], SerialD); // see what we got
for (InIndex = 0; InIndex < BUFFER_SIZE; InIndex++)
IncomingMessage[InIndex] = 0;
InIndex = 0;
IncomingMessage[InIndex] = 0;
}
else
{
// incomingByte > 31? Serial.print(IncomingMessage[InIndex]): Serial.print(incomingByte);
++InIndex;
}
}
}
/*-------------------------------------------------------------------------------*/
void writeSerial(HardwareSerial *SerialN, struct SerialData *SerialD )
{
// Caution: 64 character limit for Arduino serial. Buffer size is set in the Arduino core.
// If the message produced is > 64 characters, readSerial will ignore it.
// writeSerial will only send data that relates to the kind. ex In the Serial data struct
//if kind is 0 the only data sent will be kind angle and direction.
switch (SerialD->kind)
{
case MSG_DRIVE:
SerialN->print("DRIVE");
if (SerialD->speed_cmPs != NaN)
{
SerialN->print(" {Speed ");
SerialN->print(SerialD->speed_cmPs);
SerialN->print("}");
}
if (SerialD->angle_deg != NaN)
{
SerialN->print(" {Ang ");
SerialN->print(SerialD->angle_deg);
SerialN->print("}");
}
SerialN->println("\0");
break;
case MSG_SENSOR:
SerialN->print("SENSOR");
if (SerialD->speed_cmPs != NaN)
{
SerialN->print(" {Speed ");
SerialN->print(SerialD->speed_cmPs);
SerialN->print("}");
}
if (SerialD->angle_deg != NaN)
{
SerialN->print(" {Ang ");
SerialN->print(SerialD->angle_deg);
SerialN->print("}");
}
if (SerialD->posE_cm != NaN && SerialD->posN_cm != NaN)
{
SerialN->print(" {Pos ");
SerialN->print(SerialD->posE_cm);
SerialN->print(",");
SerialN->print(SerialD->posN_cm);
SerialN->print("}");
}
if (SerialD->bearing_deg != NaN)
{
SerialN->print(" {Br ");
SerialN->print(SerialD->bearing_deg);
SerialN->print("}");
}
SerialN->println("\0");
break;
case MSG_GOAL:
SerialN->print("GOAL");
if (SerialD->number != NaN)
{
SerialN->print(" {Num ");
SerialN->print(SerialD->number);
SerialN->print("}");
}
if (SerialD->posE_cm != NaN && SerialD->posN_cm != NaN)
{
SerialN->print(" {Pos ");
SerialN->print(SerialD->posE_cm);
SerialN->print(",");
SerialN->print(SerialD->posN_cm);
SerialN->print("}");
}
if (SerialD->bearing_deg != NaN)
{
SerialN->print(" {Br ");
SerialN->print(SerialD->bearing_deg);
SerialN->print("}");
}
if (SerialD->probability != NaN)
{
SerialN->print(" {Prob ");
SerialN->print(SerialD->probability);
SerialN->print("}");
}
SerialN->println("\0");
break;
case MSG_SEG:
SerialN->print("SEG");
if (SerialD->number != NaN)
{
SerialN->print(" {Num ");
SerialN->print(SerialD->number);
SerialN->print("}");
}
if (SerialD->posE_cm != NaN && SerialD->posN_cm != NaN)
{
SerialN->print(" {Pos ");
SerialN->print(SerialD->posE_cm);
SerialN->print(",");
SerialN->print(SerialD->posN_cm);
SerialN->print("}");
}
if (SerialD->bearing_deg != NaN)
{
SerialN->print(" {Br ");
SerialN->print(SerialD->bearing_deg);
SerialN->print("}");
}
if (SerialD->speed_cmPs != NaN)
{
SerialN->print(" {Speed ");
SerialN->print(SerialD->speed_cmPs);
SerialN->print("}");
}
SerialN->println("\0");
break;
case MSG_NONE:
default:
break;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <utils/android/ThermalManager.h>
#include <android/Thermal.h>
#include <utility>
namespace utils {
ThermalManager::ThermalManager() {
if (__builtin_available(android 30, *)) {
mThermalManager = AThermal_acquireManager();
}
}
ThermalManager::~ThermalManager() {
if (__builtin_available(android 30, *)) {
AThermal_releaseManager(mThermalManager);
}
}
ThermalManager::ThermalManager(ThermalManager&& rhs) noexcept
: mThermalManager(rhs.mThermalManager) {
rhs.mThermalManager = nullptr;
}
ThermalManager& ThermalManager::operator=(ThermalManager&& rhs) noexcept {
std::swap(mThermalManager, rhs.mThermalManager);
return *this;
}
ThermalManager::ThermalStatus ThermalManager::getCurrentThermalStatus() const noexcept {
if (__builtin_available(android 30, *)) {
return (ThermalManager::ThermalStatus)AThermal_getCurrentThermalStatus(mThermalManager);
} else {
return ThermalStatus::NONE;
}
}
} // namespace utils
<commit_msg>fix build android aar on Linux because of case sensitive<commit_after>/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <utils/android/ThermalManager.h>
#include <android/thermal.h>
#include <utility>
namespace utils {
ThermalManager::ThermalManager() {
if (__builtin_available(android 30, *)) {
mThermalManager = AThermal_acquireManager();
}
}
ThermalManager::~ThermalManager() {
if (__builtin_available(android 30, *)) {
AThermal_releaseManager(mThermalManager);
}
}
ThermalManager::ThermalManager(ThermalManager&& rhs) noexcept
: mThermalManager(rhs.mThermalManager) {
rhs.mThermalManager = nullptr;
}
ThermalManager& ThermalManager::operator=(ThermalManager&& rhs) noexcept {
std::swap(mThermalManager, rhs.mThermalManager);
return *this;
}
ThermalManager::ThermalStatus ThermalManager::getCurrentThermalStatus() const noexcept {
if (__builtin_available(android 30, *)) {
return (ThermalManager::ThermalStatus)AThermal_getCurrentThermalStatus(mThermalManager);
} else {
return ThermalStatus::NONE;
}
}
} // namespace utils
<|endoftext|> |
<commit_before>///
/// @file phi_sum.cpp
///
/// Copyright (C) 2017 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesum-internal.hpp>
#include <primesum.hpp>
#include <generate.hpp>
#include <fast_div.hpp>
#include <int128_t.hpp>
#include <int256_t.hpp>
#include <stdint.h>
#include <array>
using namespace std;
using namespace primesum;
namespace {
const array<int, 10> small_primes_ = { 0, 2, 3, 5, 7, 11, 13, 17, 19, 23 };
template <int SIGN, typename T, typename Primes>
typename next_larger_type<T>::type
phi_sum(T x,
int64_t a,
Primes&& primes)
{
using res_t = typename next_larger_type<T>::type;
res_t sum = 0;
for (; a > 0; a--)
{
if (x <= primes[a])
return sum + SIGN;
T x2 = fast_div(x, primes[a]);
sum += phi_sum<-SIGN>(x2, a - 1, primes) * primes[a];
}
res_t n = x;
res_t fx = (n * (n + 1)) >> 1;
sum += fx * SIGN;
return sum;
}
} // namespace
namespace primesum {
int128_t phi_sum(int64_t x, int64_t a)
{
if (x < 1)
return 0;
if (a < 10)
return ::phi_sum<1>(x, a, small_primes_);
else
return ::phi_sum<1>(x, a, generate_n_primes(a));
}
int256_t phi_sum(int128_t x, int64_t a)
{
if (x < 1)
return 0;
if (a < 10)
return ::phi_sum<1>(x, a, small_primes_);
else
return ::phi_sum<1>(x, a, generate_n_primes(a));
}
} // namespace
<commit_msg>Performance improvement<commit_after>///
/// @file phi_sum.cpp
///
/// Copyright (C) 2017 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesum-internal.hpp>
#include <primesum.hpp>
#include <generate.hpp>
#include <fast_div.hpp>
#include <int128_t.hpp>
#include <int256_t.hpp>
#include <stdint.h>
#include <array>
using namespace std;
using namespace primesum;
namespace {
const array<int, 10> small_primes_ = { 0, 2, 3, 5, 7, 11, 13, 17, 19, 23 };
template <int SIGN, typename T, typename Primes>
typename next_larger_type<T>::type
phi_sum(T x,
int64_t a,
Primes&& primes)
{
using res_t = typename next_larger_type<T>::type;
res_t sum = 0;
for (; a > 0; a--)
{
if (x <= primes[a])
return sum + SIGN;
T x2 = fast_div(x, primes[a]);
sum += phi_sum<-SIGN>(x2, a - 1, primes) * primes[a];
}
res_t n = x;
res_t fx = (n * (n + 1)) >> 1;
sum += fx * SIGN;
return sum;
}
} // namespace
namespace primesum {
int128_t phi_sum(int64_t x, int64_t a)
{
if (x < 1)
return 0;
if (a < 10)
return ::phi_sum<1>(x, a, small_primes_);
else
return ::phi_sum<1>(x, a, generate_n_primes(a));
}
int256_t phi_sum(int128_t x, int64_t a)
{
// for better performance use 64-bit instead of 128-bit
if (x <= numeric_limits<int64_t>::max())
return phi_sum((int64_t) x, a);
if (a < 10)
return ::phi_sum<1>(x, a, small_primes_);
else
return ::phi_sum<1>(x, a, generate_n_primes(a));
}
} // namespace
<|endoftext|> |
<commit_before>/**
* @file posix/wait.cpp
* @brief POSIX event/timeout handling
*
* (c) 2013-2014 by Mega Limited, Auckland, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK 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.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
#include "mega.h"
#ifdef USE_POLL
#include <poll.h> //poll
#endif
namespace mega {
dstime Waiter::ds;
PosixWaiter::PosixWaiter()
{
// pipe to be able to leave the select() call
if (pipe(m_pipe) < 0)
{
LOG_fatal << "Error creating pipe";
throw std::runtime_error("Error creating pipe");
}
if (fcntl(m_pipe[0], F_SETFL, O_NONBLOCK) < 0)
{
LOG_err << "fcntl error";
}
maxfd = -1;
}
PosixWaiter::~PosixWaiter()
{
close(m_pipe[0]);
close(m_pipe[1]);
}
void PosixWaiter::init(dstime ds)
{
Waiter::init(ds);
maxfd = -1;
MEGA_FD_ZERO(&rfds);
MEGA_FD_ZERO(&wfds);
MEGA_FD_ZERO(&efds);
MEGA_FD_ZERO(&ignorefds);
}
// update monotonously increasing timestamp in deciseconds
void Waiter::bumpds()
{
timespec ts;
m_clock_getmonotonictime(&ts);
ds = ts.tv_sec * 10 + ts.tv_nsec / 100000000;
}
// update maxfd for select()
void PosixWaiter::bumpmaxfd(int fd)
{
if (fd > maxfd)
{
maxfd = fd;
}
}
// checks if an unfiltered fd is set
// FIXME: use bitwise & instead of scanning
bool PosixWaiter::fd_filter(int nfds, mega_fd_set_t* fds, mega_fd_set_t* ignorefds) const
{
while (nfds--)
{
if (MEGA_FD_ISSET(nfds, fds) && !MEGA_FD_ISSET(nfds, ignorefds)) return true;
}
return false;
}
// wait for supplied events (sockets, filesystem changes), plus timeout + application events
// maxds specifies the maximum amount of time to wait in deciseconds (or ~0 if no timeout scheduled)
// returns application-specific bitmask. bit 0 set indicates that exec() needs to be called.
int PosixWaiter::wait()
{
int numfd = 0;
timeval tv;
//Pipe added to rfds to be able to leave select() when needed
MEGA_FD_SET(m_pipe[0], &rfds);
bumpmaxfd(m_pipe[0]);
if (maxds + 1)
{
dstime us = 1000000 / 10 * maxds;
tv.tv_sec = us / 1000000;
tv.tv_usec = us - tv.tv_sec * 1000000;
}
#ifdef USE_POLL
dstime us = 1000000 / 10 * maxds;
auto total = rfds.size() + wfds.size() + efds.size();
struct pollfd fds[total];
int polli = 0;
for (auto & fd : rfds)
{
fds[polli].fd = fd;
fds[polli].events = POLLIN_SET;
polli++;
}
for (auto & fd : wfds)
{
fds[polli].fd = fd;
fds[polli].events = POLLOUT_SET;
polli++;
}
for (auto & fd : efds)
{
fds[polli].fd = fd;
fds[polli].events = POLLEX_SET;
polli++;
}
numfd = poll(fds, total, us);
#else
numfd = select(maxfd + 1, &rfds, &wfds, &efds, maxds + 1 ? &tv : NULL);
#endif
// empty pipe
uint8_t buf;
bool external = false;
{
std::lock_guard<std::mutex> g(mMutex);
while (read(m_pipe[0], &buf, sizeof buf) > 0)
{
external = true;
}
alreadyNotified = false;
}
// timeout or error
if (external || numfd <= 0)
{
return NEEDEXEC;
}
// request exec() to be run only if a non-ignored fd was triggered
#ifdef USE_POLL
for (unsigned int i = 0 ; i < total ; i++)
{
if ((fds[i].revents & (POLLIN_SET | POLLOUT_SET | POLLEX_SET) ) && !MEGA_FD_ISSET(fds[i].fd, &ignorefds) )
{
return NEEDEXEC;
}
}
return 0;
#else
return (fd_filter(maxfd + 1, &rfds, &ignorefds)
|| fd_filter(maxfd + 1, &wfds, &ignorefds)
|| fd_filter(maxfd + 1, &efds, &ignorefds)) ? NEEDEXEC : 0;
#endif
}
void PosixWaiter::notify()
{
std::lock_guard<std::mutex> g(mMutex);
if (!alreadyNotified)
{
write(m_pipe[1], "0", 1);
alreadyNotified = true;
}
}
} // namespace
<commit_msg>fix timeout expected in milliseconds by poll<commit_after>/**
* @file posix/wait.cpp
* @brief POSIX event/timeout handling
*
* (c) 2013-2014 by Mega Limited, Auckland, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK 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.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
#include "mega.h"
#ifdef USE_POLL
#include <poll.h> //poll
#endif
namespace mega {
dstime Waiter::ds;
PosixWaiter::PosixWaiter()
{
// pipe to be able to leave the select() call
if (pipe(m_pipe) < 0)
{
LOG_fatal << "Error creating pipe";
throw std::runtime_error("Error creating pipe");
}
if (fcntl(m_pipe[0], F_SETFL, O_NONBLOCK) < 0)
{
LOG_err << "fcntl error";
}
maxfd = -1;
}
PosixWaiter::~PosixWaiter()
{
close(m_pipe[0]);
close(m_pipe[1]);
}
void PosixWaiter::init(dstime ds)
{
Waiter::init(ds);
maxfd = -1;
MEGA_FD_ZERO(&rfds);
MEGA_FD_ZERO(&wfds);
MEGA_FD_ZERO(&efds);
MEGA_FD_ZERO(&ignorefds);
}
// update monotonously increasing timestamp in deciseconds
void Waiter::bumpds()
{
timespec ts;
m_clock_getmonotonictime(&ts);
ds = ts.tv_sec * 10 + ts.tv_nsec / 100000000;
}
// update maxfd for select()
void PosixWaiter::bumpmaxfd(int fd)
{
if (fd > maxfd)
{
maxfd = fd;
}
}
// checks if an unfiltered fd is set
// FIXME: use bitwise & instead of scanning
bool PosixWaiter::fd_filter(int nfds, mega_fd_set_t* fds, mega_fd_set_t* ignorefds) const
{
while (nfds--)
{
if (MEGA_FD_ISSET(nfds, fds) && !MEGA_FD_ISSET(nfds, ignorefds)) return true;
}
return false;
}
// wait for supplied events (sockets, filesystem changes), plus timeout + application events
// maxds specifies the maximum amount of time to wait in deciseconds (or ~0 if no timeout scheduled)
// returns application-specific bitmask. bit 0 set indicates that exec() needs to be called.
int PosixWaiter::wait()
{
int numfd = 0;
timeval tv;
//Pipe added to rfds to be able to leave select() when needed
MEGA_FD_SET(m_pipe[0], &rfds);
bumpmaxfd(m_pipe[0]);
if (maxds + 1)
{
dstime us = 1000000 / 10 * maxds;
tv.tv_sec = us / 1000000;
tv.tv_usec = us - tv.tv_sec * 1000000;
}
#ifdef USE_POLL
dstime ms = 1000 / 10 * maxds;
auto total = rfds.size() + wfds.size() + efds.size();
struct pollfd fds[total];
int polli = 0;
for (auto & fd : rfds)
{
fds[polli].fd = fd;
fds[polli].events = POLLIN_SET;
polli++;
}
for (auto & fd : wfds)
{
fds[polli].fd = fd;
fds[polli].events = POLLOUT_SET;
polli++;
}
for (auto & fd : efds)
{
fds[polli].fd = fd;
fds[polli].events = POLLEX_SET;
polli++;
}
numfd = poll(fds, total, ms);
#else
numfd = select(maxfd + 1, &rfds, &wfds, &efds, maxds + 1 ? &tv : NULL);
#endif
// empty pipe
uint8_t buf;
bool external = false;
{
std::lock_guard<std::mutex> g(mMutex);
while (read(m_pipe[0], &buf, sizeof buf) > 0)
{
external = true;
}
alreadyNotified = false;
}
// timeout or error
if (external || numfd <= 0)
{
return NEEDEXEC;
}
// request exec() to be run only if a non-ignored fd was triggered
#ifdef USE_POLL
for (unsigned int i = 0 ; i < total ; i++)
{
if ((fds[i].revents & (POLLIN_SET | POLLOUT_SET | POLLEX_SET) ) && !MEGA_FD_ISSET(fds[i].fd, &ignorefds) )
{
return NEEDEXEC;
}
}
return 0;
#else
return (fd_filter(maxfd + 1, &rfds, &ignorefds)
|| fd_filter(maxfd + 1, &wfds, &ignorefds)
|| fd_filter(maxfd + 1, &efds, &ignorefds)) ? NEEDEXEC : 0;
#endif
}
void PosixWaiter::notify()
{
std::lock_guard<std::mutex> g(mMutex);
if (!alreadyNotified)
{
write(m_pipe[1], "0", 1);
alreadyNotified = true;
}
}
} // namespace
<|endoftext|> |
<commit_before>#include "disassembler.h"
#include "util.h"
using namespace std;
struct program {
char name[7];
//TODO
program() {
for ( int i = 0 ; i < 7 ; i++ ) {
name[i] = 0;
}
//TODO
}
};
bool read_record(ifstream &ifile, string &record);
void record_to_memory(const string record, program &p);
void write_assembly(const program &p, ofstream &ofile);
bool disassemble(ifstream &ifile, ofstream &ofile) {
string record;
program p;
while ( read_record(ifile, record) ) {
record_to_memory(record, p);
}
status("Done reading records");
write_assembly(p, ofile);
status("Done writing output file");
}
string read_hex_columns(ifstream &ifile, int col_begin, int col_end, char record_type = 'a') { // inclusive of both
string ret;
char t;
for ( int col = col_begin ; col <= col_end ; col++ ) {
t = ifile.get();
if ( t == EOF ) {
fatal("Unexpected end of " + record_type + string(" record"));
} else if ( !is_hex_digit(t) ) {
fatal("Unexpected character " + t + string(" in ") + record_type + string(" record"));
}
ret += t;
}
return ret;
}
bool read_record(ifstream &ifile, string &record) {
char t;
do {
t = ifile.get();
if ( t == EOF ) {
return false;
}
} while ( t == '\n' || t == ' ' );
record = "";
record += t;
switch (t) {
case 'H': // Header
record += read_hex_columns(ifile,2,19,'H');
break;
case 'T': // Text
//TODO
break;
case 'E': // End
record += read_hex_columns(ifile,2,7,'E');
break;
default:
fatal("Unknown record type " + t);
}
return true;
}
void record_to_memory(const string record, program &p) {
// TODO
}
void write_assembly(const program &p, ofstream &ofile) {
// TODO
}<commit_msg>Add text record reader<commit_after>#include "disassembler.h"
#include "util.h"
using namespace std;
struct program {
char name[7];
//TODO
program() {
for ( int i = 0 ; i < 7 ; i++ ) {
name[i] = 0;
}
//TODO
}
};
bool read_record(ifstream &ifile, string &record);
void record_to_memory(const string record, program &p);
void write_assembly(const program &p, ofstream &ofile);
bool disassemble(ifstream &ifile, ofstream &ofile) {
string record;
program p;
while ( read_record(ifile, record) ) {
record_to_memory(record, p);
}
status("Done reading records");
write_assembly(p, ofile);
status("Done writing output file");
}
string read_hex_columns(ifstream &ifile, int col_begin, int col_end, char record_type = 'a') { // inclusive of both
string ret;
char t;
for ( int col = col_begin ; col <= col_end ; col++ ) {
t = ifile.get();
if ( t == EOF ) {
fatal("Unexpected end of " + record_type + string(" record"));
} else if ( !is_hex_digit(t) ) {
fatal("Unexpected character " + t + string(" in ") + record_type + string(" record"));
}
ret += t;
}
return ret;
}
bool read_record(ifstream &ifile, string &record) {
int temp_int;
string temp_str;
char t;
do {
t = ifile.get();
if ( t == EOF ) {
return false;
}
} while ( t == '\n' || t == ' ' );
record = "";
record += t;
switch (t) {
case 'H': // Header
record += read_hex_columns(ifile,2,19,'H');
break;
case 'T': // Text
record += read_hex_columns(ifile,2,7,'T');
temp_str = read_hex_columns(ifile,8,9,'T');
temp_int = hex2int(temp_str);
record += temp_str;
record += read_hex_columns(ifile,10,9+2*temp_int,'T');
break;
case 'E': // End
record += read_hex_columns(ifile,2,7,'E');
break;
default:
fatal("Unknown record type " + t);
}
return true;
}
void record_to_memory(const string record, program &p) {
// TODO
}
void write_assembly(const program &p, ofstream &ofile) {
// TODO
}<|endoftext|> |
<commit_before>/**
* @file nearest_neighbor_rules_impl.hpp
* @author Ryan Curtin
*
* Implementation of NearestNeighborRules.
*/
#ifndef __MLPACK_METHODS_NEIGHBOR_SEARCH_NEAREST_NEIGHBOR_RULES_IMPL_HPP
#define __MLPACK_METHODS_NEIGHBOR_SEARCH_NEAREST_NEIGHBOR_RULES_IMPL_HPP
// In case it hasn't been included yet.
#include "neighbor_search_rules.hpp"
namespace mlpack {
namespace neighbor {
template<typename SortPolicy, typename MetricType, typename TreeType>
NeighborSearchRules<SortPolicy, MetricType, TreeType>::NeighborSearchRules(
const arma::mat& referenceSet,
const arma::mat& querySet,
arma::Mat<size_t>& neighbors,
arma::mat& distances,
MetricType& metric) :
referenceSet(referenceSet),
querySet(querySet),
neighbors(neighbors),
distances(distances),
metric(metric)
{ /* Nothing left to do. */ }
template<typename SortPolicy, typename MetricType, typename TreeType>
inline void NeighborSearchRules<SortPolicy, MetricType, TreeType>::BaseCase(
const size_t queryIndex,
const size_t referenceIndex)
{
// If the datasets are the same, then this search is only using one dataset
// and we should not return identical points.
if ((&querySet == &referenceSet) && (queryIndex == referenceIndex))
return;
double distance = metric.Evaluate(querySet.col(queryIndex),
referenceSet.col(referenceIndex));
// If this distance is better than any of the current candidates, the
// SortDistance() function will give us the position to insert it into.
arma::vec queryDist = distances.unsafe_col(queryIndex);
size_t insertPosition = SortPolicy::SortDistance(queryDist, distance);
// SortDistance() returns (size_t() - 1) if we shouldn't add it.
if (insertPosition != (size_t() - 1))
InsertNeighbor(queryIndex, insertPosition, referenceIndex, distance);
}
template<typename SortPolicy, typename MetricType, typename TreeType>
inline bool NeighborSearchRules<SortPolicy, MetricType, TreeType>::CanPrune(
const size_t queryIndex,
TreeType& referenceNode)
{
// Find the best distance between the query point and the node.
const arma::vec queryPoint = querySet.unsafe_col(queryIndex);
const double distance =
SortPolicy::BestPointToNodeDistance(queryPoint, &referenceNode);
const double bestDistance = distances(distances.n_rows - 1, queryIndex);
// If this is better than the best distance we've seen so far, maybe there
// will be something down this node.
if (SortPolicy::IsBetter(distance, bestDistance))
return false; // We cannot prune.
else
return true; // There cannot be anything better in this node. So prune it.
}
template<typename SortPolicy, typename MetricType, typename TreeType>
inline bool NeighborSearchRules<SortPolicy, MetricType, TreeType>::CanPrune(
TreeType& queryNode,
TreeType& referenceNode)
{
const double distance = SortPolicy::BestNodeToNodeDistance(
&queryNode, &referenceNode);
const double bestDistance = queryNode.Stat().Bound();
if (SortPolicy::IsBetter(distance, bestDistance))
return false; // Can't prune.
else
return true;
}
template<typename SortPolicy, typename MetricType, typename TreeType>
inline bool NeighborSearchRules<SortPolicy, MetricType, TreeType>::LeftFirst(
const size_t queryIndex,
TreeType& referenceNode)
{
// This ends up with us calculating this distance twice (it will be done again
// in CanPrune()), but because single-neighbors recursion is not the most
// important in this method, we can let it slide.
const arma::vec queryPoint = querySet.unsafe_col(queryIndex);
const double leftDistance = SortPolicy::BestPointToNodeDistance(queryPoint,
referenceNode.Left());
const double rightDistance = SortPolicy::BestPointToNodeDistance(queryPoint,
referenceNode.Right());
return SortPolicy::IsBetter(leftDistance, rightDistance);
}
template<typename SortPolicy, typename MetricType, typename TreeType>
inline bool NeighborSearchRules<SortPolicy, MetricType, TreeType>::LeftFirst(
TreeType& staticNode,
TreeType& recurseNode)
{
const double leftDistance = SortPolicy::BestNodeToNodeDistance(&staticNode,
recurseNode.Left());
const double rightDistance = SortPolicy::BestNodeToNodeDistance(&staticNode,
recurseNode.Right());
return SortPolicy::IsBetter(leftDistance, rightDistance);
}
template<typename SortPolicy, typename MetricType, typename TreeType>
void NeighborSearchRules<
SortPolicy,
MetricType,
TreeType>::
UpdateAfterRecursion(TreeType& queryNode, TreeType& /* referenceNode */)
{
// Find the worst distance that the children found (including any points), and
// update the bound accordingly.
double worstDistance = SortPolicy::BestDistance();
// First look through children nodes.
for (size_t i = 0; i < queryNode.NumChildren(); ++i)
{
if (SortPolicy::IsBetter(worstDistance, queryNode.Child(i).Stat().Bound()))
worstDistance = queryNode.Child(i).Stat().Bound();
}
// Now look through children points.
for (size_t i = 0; i < queryNode.NumPoints(); ++i)
{
if (SortPolicy::IsBetter(worstDistance,
distances(distances.n_rows - 1, queryNode.Point(i))))
worstDistance = distances(distances.n_rows - 1, queryNode.Point(i));
}
// Take the worst distance from all of these, and update our bound to reflect
// that.
queryNode.Stat().Bound() = worstDistance;
}
template<typename SortPolicy, typename MetricType, typename TreeType>
inline double NeighborSearchRules<SortPolicy, MetricType, TreeType>::Score(
const size_t queryIndex,
TreeType& referenceNode) const
{
const arma::vec queryPoint = querySet.unsafe_col(queryIndex);
const double distance = SortPolicy::BestPointToNodeDistance(queryPoint,
&referenceNode);
const double bestDistance = distances(distances.n_rows - 1, queryIndex);
return (SortPolicy::IsBetter(distance, bestDistance)) ? distance : DBL_MAX;
}
template<typename SortPolicy, typename MetricType, typename TreeType>
inline double NeighborSearchRules<SortPolicy, MetricType, TreeType>::Rescore(
const size_t queryIndex,
TreeType& /* referenceNode */,
const double oldScore) const
{
// If we are already pruning, still prune.
if (oldScore == DBL_MAX)
return oldScore;
// Just check the score again against the distances.
const double bestDistance = distances(distances.n_rows - 1, queryIndex);
return (SortPolicy::IsBetter(oldScore, bestDistance)) ? oldScore : DBL_MAX;
}
template<typename SortPolicy, typename MetricType, typename TreeType>
inline double NeighborSearchRules<SortPolicy, MetricType, TreeType>::Score(
TreeType& queryNode,
TreeType& referenceNode) const
{
const double distance = SortPolicy::BestNodeToNodeDistance(&queryNode,
&referenceNode);
const double bestDistance = queryNode.Stat().Bound();
return (SortPolicy::IsBetter(distance, bestDistance)) ? distance : DBL_MAX;
}
template<typename SortPolicy, typename MetricType, typename TreeType>
inline double NeighborSearchRules<SortPolicy, MetricType, TreeType>::Rescore(
TreeType& queryNode,
TreeType& /* referenceNode */,
const double oldScore) const
{
if (oldScore == DBL_MAX)
return oldScore;
const double bestDistance = queryNode.Stat().Bound();
return (SortPolicy::IsBetter(oldScore, bestDistance)) ? oldScore : DBL_MAX;
}
/**
* Helper function to insert a point into the neighbors and distances matrices.
*
* @param queryIndex Index of point whose neighbors we are inserting into.
* @param pos Position in list to insert into.
* @param neighbor Index of reference point which is being inserted.
* @param distance Distance from query point to reference point.
*/
template<typename SortPolicy, typename MetricType, typename TreeType>
void NeighborSearchRules<SortPolicy, MetricType, TreeType>::InsertNeighbor(
const size_t queryIndex,
const size_t pos,
const size_t neighbor,
const double distance)
{
// We only memmove() if there is actually a need to shift something.
if (pos < (distances.n_rows - 1))
{
int len = (distances.n_rows - 1) - pos;
memmove(distances.colptr(queryIndex) + (pos + 1),
distances.colptr(queryIndex) + pos,
sizeof(double) * len);
memmove(neighbors.colptr(queryIndex) + (pos + 1),
neighbors.colptr(queryIndex) + pos,
sizeof(size_t) * len);
}
// Now put the new information in the right index.
distances(pos, queryIndex) = distance;
neighbors(pos, queryIndex) = neighbor;
}
}; // namespace neighbor
}; // namespace mlpack
#endif // __MLPACK_METHODS_NEIGHBOR_SEARCH_NEAREST_NEIGHBOR_RULES_IMPL_HPP
<commit_msg>Use unsafe_col() instead of col() for speed reasons (this makes a BIG difference).<commit_after>/**
* @file nearest_neighbor_rules_impl.hpp
* @author Ryan Curtin
*
* Implementation of NearestNeighborRules.
*/
#ifndef __MLPACK_METHODS_NEIGHBOR_SEARCH_NEAREST_NEIGHBOR_RULES_IMPL_HPP
#define __MLPACK_METHODS_NEIGHBOR_SEARCH_NEAREST_NEIGHBOR_RULES_IMPL_HPP
// In case it hasn't been included yet.
#include "neighbor_search_rules.hpp"
namespace mlpack {
namespace neighbor {
template<typename SortPolicy, typename MetricType, typename TreeType>
NeighborSearchRules<SortPolicy, MetricType, TreeType>::NeighborSearchRules(
const arma::mat& referenceSet,
const arma::mat& querySet,
arma::Mat<size_t>& neighbors,
arma::mat& distances,
MetricType& metric) :
referenceSet(referenceSet),
querySet(querySet),
neighbors(neighbors),
distances(distances),
metric(metric)
{ /* Nothing left to do. */ }
template<typename SortPolicy, typename MetricType, typename TreeType>
inline void NeighborSearchRules<SortPolicy, MetricType, TreeType>::BaseCase(
const size_t queryIndex,
const size_t referenceIndex)
{
// If the datasets are the same, then this search is only using one dataset
// and we should not return identical points.
if ((&querySet == &referenceSet) && (queryIndex == referenceIndex))
return;
double distance = metric.Evaluate(querySet.unsafe_col(queryIndex),
referenceSet.unsafe_col(referenceIndex));
// If this distance is better than any of the current candidates, the
// SortDistance() function will give us the position to insert it into.
arma::vec queryDist = distances.unsafe_col(queryIndex);
size_t insertPosition = SortPolicy::SortDistance(queryDist, distance);
// SortDistance() returns (size_t() - 1) if we shouldn't add it.
if (insertPosition != (size_t() - 1))
InsertNeighbor(queryIndex, insertPosition, referenceIndex, distance);
}
template<typename SortPolicy, typename MetricType, typename TreeType>
inline bool NeighborSearchRules<SortPolicy, MetricType, TreeType>::CanPrune(
const size_t queryIndex,
TreeType& referenceNode)
{
// Find the best distance between the query point and the node.
const arma::vec queryPoint = querySet.unsafe_col(queryIndex);
const double distance =
SortPolicy::BestPointToNodeDistance(queryPoint, &referenceNode);
const double bestDistance = distances(distances.n_rows - 1, queryIndex);
// If this is better than the best distance we've seen so far, maybe there
// will be something down this node.
if (SortPolicy::IsBetter(distance, bestDistance))
return false; // We cannot prune.
else
return true; // There cannot be anything better in this node. So prune it.
}
template<typename SortPolicy, typename MetricType, typename TreeType>
inline bool NeighborSearchRules<SortPolicy, MetricType, TreeType>::CanPrune(
TreeType& queryNode,
TreeType& referenceNode)
{
const double distance = SortPolicy::BestNodeToNodeDistance(
&queryNode, &referenceNode);
const double bestDistance = queryNode.Stat().Bound();
if (SortPolicy::IsBetter(distance, bestDistance))
return false; // Can't prune.
else
return true;
}
template<typename SortPolicy, typename MetricType, typename TreeType>
inline bool NeighborSearchRules<SortPolicy, MetricType, TreeType>::LeftFirst(
const size_t queryIndex,
TreeType& referenceNode)
{
// This ends up with us calculating this distance twice (it will be done again
// in CanPrune()), but because single-neighbors recursion is not the most
// important in this method, we can let it slide.
const arma::vec queryPoint = querySet.unsafe_col(queryIndex);
const double leftDistance = SortPolicy::BestPointToNodeDistance(queryPoint,
referenceNode.Left());
const double rightDistance = SortPolicy::BestPointToNodeDistance(queryPoint,
referenceNode.Right());
return SortPolicy::IsBetter(leftDistance, rightDistance);
}
template<typename SortPolicy, typename MetricType, typename TreeType>
inline bool NeighborSearchRules<SortPolicy, MetricType, TreeType>::LeftFirst(
TreeType& staticNode,
TreeType& recurseNode)
{
const double leftDistance = SortPolicy::BestNodeToNodeDistance(&staticNode,
recurseNode.Left());
const double rightDistance = SortPolicy::BestNodeToNodeDistance(&staticNode,
recurseNode.Right());
return SortPolicy::IsBetter(leftDistance, rightDistance);
}
template<typename SortPolicy, typename MetricType, typename TreeType>
void NeighborSearchRules<
SortPolicy,
MetricType,
TreeType>::
UpdateAfterRecursion(TreeType& queryNode, TreeType& /* referenceNode */)
{
// Find the worst distance that the children found (including any points), and
// update the bound accordingly.
double worstDistance = SortPolicy::BestDistance();
// First look through children nodes.
for (size_t i = 0; i < queryNode.NumChildren(); ++i)
{
if (SortPolicy::IsBetter(worstDistance, queryNode.Child(i).Stat().Bound()))
worstDistance = queryNode.Child(i).Stat().Bound();
}
// Now look through children points.
for (size_t i = 0; i < queryNode.NumPoints(); ++i)
{
if (SortPolicy::IsBetter(worstDistance,
distances(distances.n_rows - 1, queryNode.Point(i))))
worstDistance = distances(distances.n_rows - 1, queryNode.Point(i));
}
// Take the worst distance from all of these, and update our bound to reflect
// that.
queryNode.Stat().Bound() = worstDistance;
}
template<typename SortPolicy, typename MetricType, typename TreeType>
inline double NeighborSearchRules<SortPolicy, MetricType, TreeType>::Score(
const size_t queryIndex,
TreeType& referenceNode) const
{
const arma::vec queryPoint = querySet.unsafe_col(queryIndex);
const double distance = SortPolicy::BestPointToNodeDistance(queryPoint,
&referenceNode);
const double bestDistance = distances(distances.n_rows - 1, queryIndex);
return (SortPolicy::IsBetter(distance, bestDistance)) ? distance : DBL_MAX;
}
template<typename SortPolicy, typename MetricType, typename TreeType>
inline double NeighborSearchRules<SortPolicy, MetricType, TreeType>::Rescore(
const size_t queryIndex,
TreeType& /* referenceNode */,
const double oldScore) const
{
// If we are already pruning, still prune.
if (oldScore == DBL_MAX)
return oldScore;
// Just check the score again against the distances.
const double bestDistance = distances(distances.n_rows - 1, queryIndex);
return (SortPolicy::IsBetter(oldScore, bestDistance)) ? oldScore : DBL_MAX;
}
template<typename SortPolicy, typename MetricType, typename TreeType>
inline double NeighborSearchRules<SortPolicy, MetricType, TreeType>::Score(
TreeType& queryNode,
TreeType& referenceNode) const
{
const double distance = SortPolicy::BestNodeToNodeDistance(&queryNode,
&referenceNode);
const double bestDistance = queryNode.Stat().Bound();
return (SortPolicy::IsBetter(distance, bestDistance)) ? distance : DBL_MAX;
}
template<typename SortPolicy, typename MetricType, typename TreeType>
inline double NeighborSearchRules<SortPolicy, MetricType, TreeType>::Rescore(
TreeType& queryNode,
TreeType& /* referenceNode */,
const double oldScore) const
{
if (oldScore == DBL_MAX)
return oldScore;
const double bestDistance = queryNode.Stat().Bound();
return (SortPolicy::IsBetter(oldScore, bestDistance)) ? oldScore : DBL_MAX;
}
/**
* Helper function to insert a point into the neighbors and distances matrices.
*
* @param queryIndex Index of point whose neighbors we are inserting into.
* @param pos Position in list to insert into.
* @param neighbor Index of reference point which is being inserted.
* @param distance Distance from query point to reference point.
*/
template<typename SortPolicy, typename MetricType, typename TreeType>
void NeighborSearchRules<SortPolicy, MetricType, TreeType>::InsertNeighbor(
const size_t queryIndex,
const size_t pos,
const size_t neighbor,
const double distance)
{
// We only memmove() if there is actually a need to shift something.
if (pos < (distances.n_rows - 1))
{
int len = (distances.n_rows - 1) - pos;
memmove(distances.colptr(queryIndex) + (pos + 1),
distances.colptr(queryIndex) + pos,
sizeof(double) * len);
memmove(neighbors.colptr(queryIndex) + (pos + 1),
neighbors.colptr(queryIndex) + pos,
sizeof(size_t) * len);
}
// Now put the new information in the right index.
distances(pos, queryIndex) = distance;
neighbors(pos, queryIndex) = neighbor;
}
}; // namespace neighbor
}; // namespace mlpack
#endif // __MLPACK_METHODS_NEIGHBOR_SEARCH_NEAREST_NEIGHBOR_RULES_IMPL_HPP
<|endoftext|> |
<commit_before>/**
* @file nearest_neighbor_rules_impl.hpp
* @author Ryan Curtin
*
* Implementation of NearestNeighborRules.
*/
#ifndef __MLPACK_METHODS_NEIGHBOR_SEARCH_NEAREST_NEIGHBOR_RULES_IMPL_HPP
#define __MLPACK_METHODS_NEIGHBOR_SEARCH_NEAREST_NEIGHBOR_RULES_IMPL_HPP
// In case it hasn't been included yet.
#include "neighbor_search_rules.hpp"
namespace mlpack {
namespace neighbor {
template<typename SortPolicy, typename MetricType, typename TreeType>
NeighborSearchRules<SortPolicy, MetricType, TreeType>::NeighborSearchRules(
const arma::mat& referenceSet,
const arma::mat& querySet,
arma::Mat<size_t>& neighbors,
arma::mat& distances,
MetricType& metric) :
referenceSet(referenceSet),
querySet(querySet),
neighbors(neighbors),
distances(distances),
metric(metric),
lastQueryIndex(querySet.n_cols),
lastReferenceIndex(referenceSet.n_cols)
{ /* Nothing left to do. */ }
template<typename SortPolicy, typename MetricType, typename TreeType>
inline force_inline // Absolutely MUST be inline so optimizations can happen.
double NeighborSearchRules<SortPolicy, MetricType, TreeType>::
BaseCase(const size_t queryIndex, const size_t referenceIndex)
{
// If the datasets are the same, then this search is only using one dataset
// and we should not return identical points.
if ((&querySet == &referenceSet) && (queryIndex == referenceIndex))
return 0.0;
// If we have already performed this base case, then do not perform it again.
if ((lastQueryIndex == queryIndex) && (lastReferenceIndex == referenceIndex))
return lastBaseCase;
double distance = metric.Evaluate(querySet.unsafe_col(queryIndex),
referenceSet.unsafe_col(referenceIndex));
// If this distance is better than any of the current candidates, the
// SortDistance() function will give us the position to insert it into.
arma::vec queryDist = distances.unsafe_col(queryIndex);
const size_t insertPosition = SortPolicy::SortDistance(queryDist, distance);
// SortDistance() returns (size_t() - 1) if we shouldn't add it.
if (insertPosition != (size_t() - 1))
InsertNeighbor(queryIndex, insertPosition, referenceIndex, distance);
// Cache this information for the next time BaseCase() is called.
lastQueryIndex = queryIndex;
lastReferenceIndex = referenceIndex;
lastBaseCase = distance;
return distance;
}
template<typename SortPolicy, typename MetricType, typename TreeType>
inline double NeighborSearchRules<SortPolicy, MetricType, TreeType>::Score(
const size_t queryIndex,
TreeType& referenceNode)
{
double distance;
if (tree::TreeTraits<TreeType>::FirstPointIsCentroid)
{
// The first point in the tree is the centroid. So we can then calculate
// the base case between that and the query point.
double baseCase;
if (tree::TreeTraits<TreeType>::HasSelfChildren)
{
// If the parent node is the same, then we have already calculated the
// base case.
if ((referenceNode.Parent() != NULL) &&
(referenceNode.Point(0) == referenceNode.Parent()->Point(0)))
baseCase = referenceNode.Parent()->Stat().LastDistance();
else
baseCase = BaseCase(queryIndex, referenceNode.Point(0));
// Save this evaluation.
referenceNode.Stat().LastDistance() = baseCase;
}
distance = SortPolicy::CombineBest(baseCase,
referenceNode.FurthestDescendantDistance());
}
else
{
const arma::vec queryPoint = querySet.unsafe_col(queryIndex);
distance = SortPolicy::BestPointToNodeDistance(queryPoint, &referenceNode);
}
// Compare against the best k'th distance for this query point so far.
const double bestDistance = distances(distances.n_rows - 1, queryIndex);
return (SortPolicy::IsBetter(distance, bestDistance)) ? distance : DBL_MAX;
}
template<typename SortPolicy, typename MetricType, typename TreeType>
inline double NeighborSearchRules<SortPolicy, MetricType, TreeType>::Rescore(
const size_t queryIndex,
TreeType& /* referenceNode */,
const double oldScore) const
{
// If we are already pruning, still prune.
if (oldScore == DBL_MAX)
return oldScore;
// Just check the score again against the distances.
const double bestDistance = distances(distances.n_rows - 1, queryIndex);
return (SortPolicy::IsBetter(oldScore, bestDistance)) ? oldScore : DBL_MAX;
}
template<typename SortPolicy, typename MetricType, typename TreeType>
inline double NeighborSearchRules<SortPolicy, MetricType, TreeType>::Score(
TreeType& queryNode,
TreeType& referenceNode)
{
double distance;
if (tree::TreeTraits<TreeType>::FirstPointIsCentroid)
{
// The first point in the node is the centroid, so we can calculate the
// distance between the two points using BaseCase() and then find the
// bounds. This is potentially loose for non-ball bounds.
bool alreadyDone = false;
double baseCase;
if (tree::TreeTraits<TreeType>::HasSelfChildren)
{
// In this case, we may have already calculated the base case.
TreeType* lastRef = (TreeType*) queryNode.Stat().LastDistanceNode();
TreeType* lastQuery = (TreeType*) referenceNode.Stat().LastDistanceNode();
// Does the query node have the base case cached?
if ((lastRef != NULL) && (referenceNode.Point(0) == lastRef->Point(0)))
{
baseCase = queryNode.Stat().LastDistance();
alreadyDone = true;
}
// Does the reference node have the base case cached?
if ((lastQuery != NULL) &&
(queryNode.Point(0) == lastQuery->Point(0)))
{
baseCase = queryNode.Stat().LastDistance();
alreadyDone = true;
}
// Is the query node a self-child, and if so, does the query node's parent
// have the base case cached?
if ((queryNode.Parent() != NULL) &&
(queryNode.Parent()->Point(0) == queryNode.Point(0)))
{
TreeType* lastParentRef = (TreeType*)
queryNode.Parent()->Stat().LastDistanceNode();
if (lastParentRef->Point(0) == referenceNode.Point(0))
{
baseCase = queryNode.Parent()->Stat().LastDistance();
alreadyDone = true;
}
}
// Is the reference node a self-child, and if so, does the reference
// node's parent have the base case cached?
if ((referenceNode.Parent() != NULL) &&
(referenceNode.Parent()->Point(0) == referenceNode.Point(0)))
{
TreeType* lastParentRef = (TreeType*)
referenceNode.Parent()->Stat().LastDistanceNode();
if (lastParentRef->Point(0) == queryNode.Point(0))
{
baseCase = referenceNode.Parent()->Stat().LastDistance();
alreadyDone = true;
}
}
}
// If we did not find a cached base case, then recalculate it.
if (!alreadyDone)
{
baseCase = BaseCase(queryNode.Point(0), referenceNode.Point(0));
}
else
{
// Set lastQueryIndex and lastReferenceIndex, so that BaseCase() does not
// duplicate work.
lastQueryIndex = queryNode.Point(0);
lastReferenceIndex = referenceNode.Point(0);
lastBaseCase = baseCase;
}
// distance = SortPolicy::CombineBest(baseCase,
// queryNode.FurthestDescendantDistance() +
// referenceNode.FurthestDescendantDistance());
distance = 0;
// Update the last distance calculation for the query and reference nodes.
queryNode.Stat().LastDistanceNode() = (void*) &referenceNode;
queryNode.Stat().LastDistance() = baseCase;
referenceNode.Stat().LastDistanceNode() = (void*) &queryNode;
referenceNode.Stat().LastDistance() = baseCase;
}
else
{
distance = SortPolicy::BestNodeToNodeDistance(&queryNode, &referenceNode);
}
// Update our bound.
const double bestDistance = CalculateBound(queryNode);
return (SortPolicy::IsBetter(distance, bestDistance)) ? distance : DBL_MAX;
}
template<typename SortPolicy, typename MetricType, typename TreeType>
inline double NeighborSearchRules<SortPolicy, MetricType, TreeType>::Rescore(
TreeType& queryNode,
TreeType& /* referenceNode */,
const double oldScore) const
{
if (oldScore == DBL_MAX)
return oldScore;
// Update our bound.
const double bestDistance = CalculateBound(queryNode);
return (SortPolicy::IsBetter(oldScore, bestDistance)) ? oldScore : DBL_MAX;
}
// Calculate the bound for a given query node in its current state and update
// it.
template<typename SortPolicy, typename MetricType, typename TreeType>
inline double NeighborSearchRules<SortPolicy, MetricType, TreeType>::
CalculateBound(TreeType& queryNode) const
{
// We have five possible bounds, and we must take the best of them all. We
// don't use min/max here, but instead "best/worst", because this is general
// to the nearest-neighbors/furthest-neighbors cases. For nearest neighbors,
// min = best, max = worst.
//
// (1) worst ( worst_{all points p in queryNode} D_p[k],
// worst_{all children c in queryNode} B(c) );
// (2) best_{all points p in queryNode} D_p[k] + worst child distance +
// worst descendant distance;
// (3) best_{all children c in queryNode} B(c) +
// 2 ( worst descendant distance of queryNode -
// worst descendant distance of c );
// (4) B_1(parent of queryNode)
// (5) B_2(parent of queryNode);
//
// D_p[k] is the current k'th candidate distance for point p.
// So we will loop over the points in queryNode and the children in queryNode
// to calculate all five of these quantities.
double worstPointDistance = SortPolicy::BestDistance();
double bestPointDistance = SortPolicy::WorstDistance();
// Loop over all points in this node to find the best and worst distance
// candidates (for (1) and (2)).
for (size_t i = 0; i < queryNode.NumPoints(); ++i)
{
const double distance = distances(distances.n_rows - 1, queryNode.Point(i));
if (SortPolicy::IsBetter(distance, bestPointDistance))
bestPointDistance = distance;
if (SortPolicy::IsBetter(worstPointDistance, distance))
worstPointDistance = distance;
}
// Loop over all the children in this node to find the worst bound (for (1))
// and the best bound with the correcting factor for descendant distances (for
// (3)).
double worstChildBound = SortPolicy::BestDistance();
double bestAdjustedChildBound = SortPolicy::WorstDistance();
const double queryMaxDescendantDistance =
queryNode.FurthestDescendantDistance();
for (size_t i = 0; i < queryNode.NumChildren(); ++i)
{
const double firstBound = queryNode.Child(i).Stat().FirstBound();
const double secondBound = queryNode.Child(i).Stat().SecondBound();
const double childMaxDescendantDistance =
queryNode.Child(i).FurthestDescendantDistance();
if (SortPolicy::IsBetter(worstChildBound, firstBound))
worstChildBound = firstBound;
// Now calculate adjustment for maximum descendant distances.
const double adjustedBound = SortPolicy::CombineWorst(secondBound,
2 * (queryMaxDescendantDistance - childMaxDescendantDistance));
if (SortPolicy::IsBetter(adjustedBound, bestAdjustedChildBound))
bestAdjustedChildBound = adjustedBound;
}
// This is bound (1).
const double firstBound =
(SortPolicy::IsBetter(worstPointDistance, worstChildBound)) ?
worstChildBound : worstPointDistance;
// This is bound (2).
const double secondBound = SortPolicy::CombineWorst(bestPointDistance,
2 * queryMaxDescendantDistance);
// Bound (3) is bestAdjustedChildBound.
// Bounds (4) and (5) are the parent bounds.
const double fourthBound = (queryNode.Parent() != NULL) ?
queryNode.Parent()->Stat().FirstBound() : SortPolicy::WorstDistance();
const double fifthBound = (queryNode.Parent() != NULL) ?
queryNode.Parent()->Stat().SecondBound() : SortPolicy::WorstDistance();
// Now, we will take the best of these. Unfortunately due to the way
// IsBetter() is defined, this sort of has to be a little ugly.
// The variable interA represents the first bound (B_1), which is the worst
// candidate distance of any descendants of this node.
// The variable interC represents the second bound (B_2), which is a bound on
// the worst distance of any descendants of this node assembled using the best
// descendant candidate distance modified using the furthest descendant
// distance.
const double interA = (SortPolicy::IsBetter(firstBound, fourthBound)) ?
firstBound : fourthBound;
const double interB =
(SortPolicy::IsBetter(bestAdjustedChildBound, secondBound)) ?
bestAdjustedChildBound : secondBound;
const double interC = (SortPolicy::IsBetter(interB, fifthBound)) ? interB :
fifthBound;
// Update the first and second bounds of the node.
queryNode.Stat().FirstBound() = interA;
queryNode.Stat().SecondBound() = interC;
// Update the actual bound of the node.
queryNode.Stat().Bound() = (SortPolicy::IsBetter(interA, interC)) ? interA :
interC;
return queryNode.Stat().Bound();
}
/**
* Helper function to insert a point into the neighbors and distances matrices.
*
* @param queryIndex Index of point whose neighbors we are inserting into.
* @param pos Position in list to insert into.
* @param neighbor Index of reference point which is being inserted.
* @param distance Distance from query point to reference point.
*/
template<typename SortPolicy, typename MetricType, typename TreeType>
void NeighborSearchRules<SortPolicy, MetricType, TreeType>::InsertNeighbor(
const size_t queryIndex,
const size_t pos,
const size_t neighbor,
const double distance)
{
// We only memmove() if there is actually a need to shift something.
if (pos < (distances.n_rows - 1))
{
int len = (distances.n_rows - 1) - pos;
memmove(distances.colptr(queryIndex) + (pos + 1),
distances.colptr(queryIndex) + pos,
sizeof(double) * len);
memmove(neighbors.colptr(queryIndex) + (pos + 1),
neighbors.colptr(queryIndex) + pos,
sizeof(size_t) * len);
}
// Now put the new information in the right index.
distances(pos, queryIndex) = distance;
neighbors(pos, queryIndex) = neighbor;
}
}; // namespace neighbor
}; // namespace mlpack
#endif // __MLPACK_METHODS_NEIGHBOR_SEARCH_NEAREST_NEIGHBOR_RULES_IMPL_HPP
<commit_msg>Two things: actually do some pruning, and, get parent base case evaluations correctly. I cannot believe how long it took me to track that down. Ugh...<commit_after>/**
* @file nearest_neighbor_rules_impl.hpp
* @author Ryan Curtin
*
* Implementation of NearestNeighborRules.
*/
#ifndef __MLPACK_METHODS_NEIGHBOR_SEARCH_NEAREST_NEIGHBOR_RULES_IMPL_HPP
#define __MLPACK_METHODS_NEIGHBOR_SEARCH_NEAREST_NEIGHBOR_RULES_IMPL_HPP
// In case it hasn't been included yet.
#include "neighbor_search_rules.hpp"
namespace mlpack {
namespace neighbor {
template<typename SortPolicy, typename MetricType, typename TreeType>
NeighborSearchRules<SortPolicy, MetricType, TreeType>::NeighborSearchRules(
const arma::mat& referenceSet,
const arma::mat& querySet,
arma::Mat<size_t>& neighbors,
arma::mat& distances,
MetricType& metric) :
referenceSet(referenceSet),
querySet(querySet),
neighbors(neighbors),
distances(distances),
metric(metric),
lastQueryIndex(querySet.n_cols),
lastReferenceIndex(referenceSet.n_cols)
{ /* Nothing left to do. */ }
template<typename SortPolicy, typename MetricType, typename TreeType>
inline force_inline // Absolutely MUST be inline so optimizations can happen.
double NeighborSearchRules<SortPolicy, MetricType, TreeType>::
BaseCase(const size_t queryIndex, const size_t referenceIndex)
{
// If the datasets are the same, then this search is only using one dataset
// and we should not return identical points.
if ((&querySet == &referenceSet) && (queryIndex == referenceIndex))
return 0.0;
// If we have already performed this base case, then do not perform it again.
if ((lastQueryIndex == queryIndex) && (lastReferenceIndex == referenceIndex))
return lastBaseCase;
double distance = metric.Evaluate(querySet.unsafe_col(queryIndex),
referenceSet.unsafe_col(referenceIndex));
// If this distance is better than any of the current candidates, the
// SortDistance() function will give us the position to insert it into.
arma::vec queryDist = distances.unsafe_col(queryIndex);
const size_t insertPosition = SortPolicy::SortDistance(queryDist, distance);
// SortDistance() returns (size_t() - 1) if we shouldn't add it.
if (insertPosition != (size_t() - 1))
InsertNeighbor(queryIndex, insertPosition, referenceIndex, distance);
// Cache this information for the next time BaseCase() is called.
lastQueryIndex = queryIndex;
lastReferenceIndex = referenceIndex;
lastBaseCase = distance;
return distance;
}
template<typename SortPolicy, typename MetricType, typename TreeType>
inline double NeighborSearchRules<SortPolicy, MetricType, TreeType>::Score(
const size_t queryIndex,
TreeType& referenceNode)
{
double distance;
if (tree::TreeTraits<TreeType>::FirstPointIsCentroid)
{
// The first point in the tree is the centroid. So we can then calculate
// the base case between that and the query point.
double baseCase;
if (tree::TreeTraits<TreeType>::HasSelfChildren)
{
// If the parent node is the same, then we have already calculated the
// base case.
if ((referenceNode.Parent() != NULL) &&
(referenceNode.Point(0) == referenceNode.Parent()->Point(0)))
baseCase = referenceNode.Parent()->Stat().LastDistance();
else
baseCase = BaseCase(queryIndex, referenceNode.Point(0));
// Save this evaluation.
referenceNode.Stat().LastDistance() = baseCase;
}
distance = SortPolicy::CombineBest(baseCase,
referenceNode.FurthestDescendantDistance());
}
else
{
const arma::vec queryPoint = querySet.unsafe_col(queryIndex);
distance = SortPolicy::BestPointToNodeDistance(queryPoint, &referenceNode);
}
// Compare against the best k'th distance for this query point so far.
const double bestDistance = distances(distances.n_rows - 1, queryIndex);
return (SortPolicy::IsBetter(distance, bestDistance)) ? distance : DBL_MAX;
}
template<typename SortPolicy, typename MetricType, typename TreeType>
inline double NeighborSearchRules<SortPolicy, MetricType, TreeType>::Rescore(
const size_t queryIndex,
TreeType& /* referenceNode */,
const double oldScore) const
{
// If we are already pruning, still prune.
if (oldScore == DBL_MAX)
return oldScore;
// Just check the score again against the distances.
const double bestDistance = distances(distances.n_rows - 1, queryIndex);
return (SortPolicy::IsBetter(oldScore, bestDistance)) ? oldScore : DBL_MAX;
}
template<typename SortPolicy, typename MetricType, typename TreeType>
inline double NeighborSearchRules<SortPolicy, MetricType, TreeType>::Score(
TreeType& queryNode,
TreeType& referenceNode)
{
double distance;
if (tree::TreeTraits<TreeType>::FirstPointIsCentroid)
{
// The first point in the node is the centroid, so we can calculate the
// distance between the two points using BaseCase() and then find the
// bounds. This is potentially loose for non-ball bounds.
bool alreadyDone = false;
double baseCase;
if (tree::TreeTraits<TreeType>::HasSelfChildren)
{
// In this case, we may have already calculated the base case.
TreeType* lastRef = (TreeType*) queryNode.Stat().LastDistanceNode();
TreeType* lastQuery = (TreeType*) referenceNode.Stat().LastDistanceNode();
// Does the query node have the base case cached?
if ((lastRef != NULL) && (referenceNode.Point(0) == lastRef->Point(0)))
{
baseCase = queryNode.Stat().LastDistance();
alreadyDone = true;
}
// Does the reference node have the base case cached?
if ((lastQuery != NULL) &&
(queryNode.Point(0) == lastQuery->Point(0)))
{
baseCase = referenceNode.Stat().LastDistance();
alreadyDone = true;
}
// Is the query node a self-child, and if so, does the query node's parent
// have the base case cached?
if ((queryNode.Parent() != NULL) &&
(queryNode.Parent()->Point(0) == queryNode.Point(0)))
{
TreeType* lastParentRef = (TreeType*)
queryNode.Parent()->Stat().LastDistanceNode();
if (lastParentRef->Point(0) == referenceNode.Point(0))
{
baseCase = queryNode.Parent()->Stat().LastDistance();
alreadyDone = true;
}
}
// Is the reference node a self-child, and if so, does the reference
// node's parent have the base case cached?
if ((referenceNode.Parent() != NULL) &&
(referenceNode.Parent()->Point(0) == referenceNode.Point(0)))
{
TreeType* lastParentRef = (TreeType*)
referenceNode.Parent()->Stat().LastDistanceNode();
if (lastParentRef->Point(0) == queryNode.Point(0))
{
baseCase = referenceNode.Parent()->Stat().LastDistance();
alreadyDone = true;
}
}
}
// If we did not find a cached base case, then recalculate it.
if (!alreadyDone)
{
baseCase = BaseCase(queryNode.Point(0), referenceNode.Point(0));
}
else
{
// Set lastQueryIndex and lastReferenceIndex, so that BaseCase() does not
// duplicate work.
lastQueryIndex = queryNode.Point(0);
lastReferenceIndex = referenceNode.Point(0);
lastBaseCase = baseCase;
}
distance = SortPolicy::CombineBest(baseCase,
queryNode.FurthestDescendantDistance() +
referenceNode.FurthestDescendantDistance());
// Update the last distance calculation for the query and reference nodes.
queryNode.Stat().LastDistanceNode() = (void*) &referenceNode;
queryNode.Stat().LastDistance() = baseCase;
referenceNode.Stat().LastDistanceNode() = (void*) &queryNode;
referenceNode.Stat().LastDistance() = baseCase;
}
else
{
distance = SortPolicy::BestNodeToNodeDistance(&queryNode, &referenceNode);
}
// Update our bound.
const double bestDistance = CalculateBound(queryNode);
return (SortPolicy::IsBetter(distance, bestDistance)) ? distance : DBL_MAX;
}
template<typename SortPolicy, typename MetricType, typename TreeType>
inline double NeighborSearchRules<SortPolicy, MetricType, TreeType>::Rescore(
TreeType& queryNode,
TreeType& /* referenceNode */,
const double oldScore) const
{
if (oldScore == DBL_MAX)
return oldScore;
// Update our bound.
const double bestDistance = CalculateBound(queryNode);
return (SortPolicy::IsBetter(oldScore, bestDistance)) ? oldScore : DBL_MAX;
}
// Calculate the bound for a given query node in its current state and update
// it.
template<typename SortPolicy, typename MetricType, typename TreeType>
inline double NeighborSearchRules<SortPolicy, MetricType, TreeType>::
CalculateBound(TreeType& queryNode) const
{
// We have five possible bounds, and we must take the best of them all. We
// don't use min/max here, but instead "best/worst", because this is general
// to the nearest-neighbors/furthest-neighbors cases. For nearest neighbors,
// min = best, max = worst.
//
// (1) worst ( worst_{all points p in queryNode} D_p[k],
// worst_{all children c in queryNode} B(c) );
// (2) best_{all points p in queryNode} D_p[k] + worst child distance +
// worst descendant distance;
// (3) best_{all children c in queryNode} B(c) +
// 2 ( worst descendant distance of queryNode -
// worst descendant distance of c );
// (4) B_1(parent of queryNode)
// (5) B_2(parent of queryNode);
//
// D_p[k] is the current k'th candidate distance for point p.
// So we will loop over the points in queryNode and the children in queryNode
// to calculate all five of these quantities.
double worstPointDistance = SortPolicy::BestDistance();
double bestPointDistance = SortPolicy::WorstDistance();
// Loop over all points in this node to find the best and worst distance
// candidates (for (1) and (2)).
for (size_t i = 0; i < queryNode.NumPoints(); ++i)
{
const double distance = distances(distances.n_rows - 1, queryNode.Point(i));
if (SortPolicy::IsBetter(distance, bestPointDistance))
bestPointDistance = distance;
if (SortPolicy::IsBetter(worstPointDistance, distance))
worstPointDistance = distance;
}
// Loop over all the children in this node to find the worst bound (for (1))
// and the best bound with the correcting factor for descendant distances (for
// (3)).
double worstChildBound = SortPolicy::BestDistance();
double bestAdjustedChildBound = SortPolicy::WorstDistance();
const double queryMaxDescendantDistance =
queryNode.FurthestDescendantDistance();
for (size_t i = 0; i < queryNode.NumChildren(); ++i)
{
const double firstBound = queryNode.Child(i).Stat().FirstBound();
const double secondBound = queryNode.Child(i).Stat().SecondBound();
const double childMaxDescendantDistance =
queryNode.Child(i).FurthestDescendantDistance();
if (SortPolicy::IsBetter(worstChildBound, firstBound))
worstChildBound = firstBound;
// Now calculate adjustment for maximum descendant distances.
const double adjustedBound = SortPolicy::CombineWorst(secondBound,
2 * (queryMaxDescendantDistance - childMaxDescendantDistance));
if (SortPolicy::IsBetter(adjustedBound, bestAdjustedChildBound))
bestAdjustedChildBound = adjustedBound;
}
// This is bound (1).
const double firstBound =
(SortPolicy::IsBetter(worstPointDistance, worstChildBound)) ?
worstChildBound : worstPointDistance;
// This is bound (2).
const double secondBound = SortPolicy::CombineWorst(bestPointDistance,
2 * queryMaxDescendantDistance);
// Bound (3) is bestAdjustedChildBound.
// Bounds (4) and (5) are the parent bounds.
const double fourthBound = (queryNode.Parent() != NULL) ?
queryNode.Parent()->Stat().FirstBound() : SortPolicy::WorstDistance();
const double fifthBound = (queryNode.Parent() != NULL) ?
queryNode.Parent()->Stat().SecondBound() : SortPolicy::WorstDistance();
// Now, we will take the best of these. Unfortunately due to the way
// IsBetter() is defined, this sort of has to be a little ugly.
// The variable interA represents the first bound (B_1), which is the worst
// candidate distance of any descendants of this node.
// The variable interC represents the second bound (B_2), which is a bound on
// the worst distance of any descendants of this node assembled using the best
// descendant candidate distance modified using the furthest descendant
// distance.
const double interA = (SortPolicy::IsBetter(firstBound, fourthBound)) ?
firstBound : fourthBound;
const double interB =
(SortPolicy::IsBetter(bestAdjustedChildBound, secondBound)) ?
bestAdjustedChildBound : secondBound;
const double interC = (SortPolicy::IsBetter(interB, fifthBound)) ? interB :
fifthBound;
// Update the first and second bounds of the node.
queryNode.Stat().FirstBound() = interA;
queryNode.Stat().SecondBound() = interC;
// Update the actual bound of the node.
queryNode.Stat().Bound() = (SortPolicy::IsBetter(interA, interC)) ? interA :
interC;
return queryNode.Stat().Bound();
}
/**
* Helper function to insert a point into the neighbors and distances matrices.
*
* @param queryIndex Index of point whose neighbors we are inserting into.
* @param pos Position in list to insert into.
* @param neighbor Index of reference point which is being inserted.
* @param distance Distance from query point to reference point.
*/
template<typename SortPolicy, typename MetricType, typename TreeType>
void NeighborSearchRules<SortPolicy, MetricType, TreeType>::InsertNeighbor(
const size_t queryIndex,
const size_t pos,
const size_t neighbor,
const double distance)
{
// We only memmove() if there is actually a need to shift something.
if (pos < (distances.n_rows - 1))
{
int len = (distances.n_rows - 1) - pos;
memmove(distances.colptr(queryIndex) + (pos + 1),
distances.colptr(queryIndex) + pos,
sizeof(double) * len);
memmove(neighbors.colptr(queryIndex) + (pos + 1),
neighbors.colptr(queryIndex) + pos,
sizeof(size_t) * len);
}
// Now put the new information in the right index.
distances(pos, queryIndex) = distance;
neighbors(pos, queryIndex) = neighbor;
}
}; // namespace neighbor
}; // namespace mlpack
#endif // __MLPACK_METHODS_NEIGHBOR_SEARCH_NEAREST_NEIGHBOR_RULES_IMPL_HPP
<|endoftext|> |
<commit_before>#include "operator.hpp"
#include <boost/python.hpp>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/Joints/b2DistanceJoint.h>
#include <Box2D/Dynamics/Joints/b2FrictionJoint.h>
#include <Box2D/Dynamics/Joints/b2GearJoint.h>
#include <Box2D/Dynamics/Joints/b2Joint.h>
#include <Box2D/Dynamics/Joints/b2LineJoint.h>
#include <Box2D/Dynamics/Joints/b2MouseJoint.h>
#include <Box2D/Dynamics/Joints/b2PrismaticJoint.h>
#include <Box2D/Dynamics/Joints/b2PulleyJoint.h>
#include <Box2D/Dynamics/Joints/b2RevoluteJoint.h>
#include <Box2D/Dynamics/Joints/b2WeldJoint.h>
using namespace boost::python;
namespace pysics {
void wrap_joint_type()
{
enum_<b2JointType>("JointType")
.value("UNKNOWN_JOINT", e_unknownJoint)
.value("REVOLUTE_JOINT", e_revoluteJoint)
.value("PRISMATIC_JOINT", e_prismaticJoint)
.value("DISTANCE_JOINT", e_distanceJoint)
.value("PULLEY_JOINT", e_pulleyJoint)
.value("MOUSE_JOINT", e_mouseJoint)
.value("GEAR_JOINT", e_gearJoint)
.value("LINE_JOINT", e_lineJoint)
.value("WELD_JOINT", e_weldJoint)
.value("FRICTION_JOINT", e_frictionJoint)
.export_values()
;
}
void wrap_joint()
{
class_<b2Joint, boost::noncopyable>("Joint", no_init)
.def("__eq__", &eq_ptr<b2Joint>)
.def("__ne__", &ne_ptr<b2Joint>)
.def("__hash__", &hash_ptr<b2Joint>)
.add_property("type", &b2Joint::GetType)
.add_property("body_a", make_function(&b2Joint::GetBodyA, return_internal_reference<>()))
.add_property("body_b", make_function(&b2Joint::GetBodyB, return_internal_reference<>()))
.add_property("user_data", &b2Joint::GetUserData, &b2Joint::SetUserData)
.add_property("active", &b2Joint::IsActive)
;
}
void wrap_revolute_joint()
{
class_<b2RevoluteJoint, bases<b2Joint> >("RevoluteJoint", no_init)
.add_property("anchor_a", &b2RevoluteJoint::GetAnchorA)
.add_property("anchor_b", &b2RevoluteJoint::GetAnchorB)
.add_property("reaction_force", &b2RevoluteJoint::GetReactionForce)
.add_property("reaction_torque", &b2RevoluteJoint::GetReactionTorque)
.add_property("joint_angle", &b2RevoluteJoint::GetJointAngle)
.add_property("joint_speed", &b2RevoluteJoint::GetJointSpeed)
.add_property("limit_enabled", &b2RevoluteJoint::IsLimitEnabled, &b2RevoluteJoint::EnableLimit)
.add_property("lower_limit", &b2RevoluteJoint::GetLowerLimit)
.add_property("upper_limit", &b2RevoluteJoint::GetUpperLimit)
.add_property("motor_enabled", &b2RevoluteJoint::IsMotorEnabled, &b2RevoluteJoint::EnableMotor)
.add_property("motor_speed", &b2RevoluteJoint::GetMotorSpeed, &b2RevoluteJoint::SetMotorSpeed)
.add_property("motor_torque", &b2RevoluteJoint::GetMotorTorque)
.add_property("max_motor_torque", object(), &b2RevoluteJoint::SetMaxMotorTorque)
.def("set_limits", &b2RevoluteJoint::SetLimits)
;
}
void wrap_prismatic_joint()
{
class_<b2PrismaticJoint, bases<b2Joint> >("PrismaticJoint", no_init)
.add_property("anchor_a", &b2PrismaticJoint::GetAnchorA)
.add_property("anchor_b", &b2PrismaticJoint::GetAnchorB)
.add_property("reaction_force", &b2PrismaticJoint::GetReactionForce)
.add_property("reaction_torque", &b2PrismaticJoint::GetReactionTorque)
.add_property("joint_translation", &b2PrismaticJoint::GetJointTranslation)
.add_property("joint_speed", &b2PrismaticJoint::GetJointSpeed)
.add_property("limit_enabled", &b2PrismaticJoint::IsLimitEnabled, &b2PrismaticJoint::EnableLimit)
.add_property("lower_limit", &b2PrismaticJoint::GetLowerLimit)
.add_property("upper_limit", &b2PrismaticJoint::GetUpperLimit)
.add_property("motor_enabled", &b2PrismaticJoint::IsMotorEnabled, &b2PrismaticJoint::EnableMotor)
.add_property("motor_speed", &b2PrismaticJoint::GetMotorSpeed, &b2PrismaticJoint::SetMotorSpeed)
.add_property("motor_force", &b2PrismaticJoint::GetMotorForce)
.add_property("max_motor_force", object(), &b2PrismaticJoint::SetMaxMotorForce)
.def("set_limits", &b2PrismaticJoint::SetLimits)
;
}
void wrap_distance_joint()
{
class_<b2DistanceJoint, bases<b2Joint> >("DistanceJoint", no_init)
.add_property("anchor_a", &b2DistanceJoint::GetAnchorA)
.add_property("anchor_b", &b2DistanceJoint::GetAnchorB)
.add_property("length", &b2DistanceJoint::GetLength, &b2DistanceJoint::SetLength)
.add_property("reaction_force", &b2DistanceJoint::GetReactionForce)
.add_property("reaction_torque", &b2DistanceJoint::GetReactionTorque)
.add_property("frequency", &b2DistanceJoint::GetFrequency, &b2DistanceJoint::SetFrequency)
.add_property("damping_ratio", &b2DistanceJoint::GetDampingRatio, &b2DistanceJoint::SetDampingRatio)
;
}
void wrap_pulley_joint()
{
class_<b2PulleyJoint, bases<b2Joint> >("PulleyJoint", no_init)
.add_property("anchor_a", &b2PulleyJoint::GetAnchorA)
.add_property("anchor_b", &b2PulleyJoint::GetAnchorB)
.add_property("reaction_force", &b2PrismaticJoint::GetReactionForce)
.add_property("reaction_torque", &b2PrismaticJoint::GetReactionTorque)
.add_property("ground_anchor_a", &b2PulleyJoint::GetGroundAnchorA)
.add_property("ground_anchor_b", &b2PulleyJoint::GetGroundAnchorB)
.add_property("length_1", &b2PulleyJoint::GetLength1)
.add_property("length_2", &b2PulleyJoint::GetLength2)
.add_property("ratio", &b2PulleyJoint::GetRatio)
;
}
void wrap_mouse_joint()
{
}
void wrap_gear_joint()
{
}
void wrap_line_joint()
{
}
void wrap_weld_joint()
{
}
void wrap_friction_joint()
{
}
}
<commit_msg>wrapped MouseJoint<commit_after>#include "operator.hpp"
#include <boost/python.hpp>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/Joints/b2DistanceJoint.h>
#include <Box2D/Dynamics/Joints/b2FrictionJoint.h>
#include <Box2D/Dynamics/Joints/b2GearJoint.h>
#include <Box2D/Dynamics/Joints/b2Joint.h>
#include <Box2D/Dynamics/Joints/b2LineJoint.h>
#include <Box2D/Dynamics/Joints/b2MouseJoint.h>
#include <Box2D/Dynamics/Joints/b2PrismaticJoint.h>
#include <Box2D/Dynamics/Joints/b2PulleyJoint.h>
#include <Box2D/Dynamics/Joints/b2RevoluteJoint.h>
#include <Box2D/Dynamics/Joints/b2WeldJoint.h>
using namespace boost::python;
namespace pysics {
void wrap_joint_type()
{
enum_<b2JointType>("JointType")
.value("UNKNOWN_JOINT", e_unknownJoint)
.value("REVOLUTE_JOINT", e_revoluteJoint)
.value("PRISMATIC_JOINT", e_prismaticJoint)
.value("DISTANCE_JOINT", e_distanceJoint)
.value("PULLEY_JOINT", e_pulleyJoint)
.value("MOUSE_JOINT", e_mouseJoint)
.value("GEAR_JOINT", e_gearJoint)
.value("LINE_JOINT", e_lineJoint)
.value("WELD_JOINT", e_weldJoint)
.value("FRICTION_JOINT", e_frictionJoint)
.export_values()
;
}
void wrap_joint()
{
class_<b2Joint, boost::noncopyable>("Joint", no_init)
.def("__eq__", &eq_ptr<b2Joint>)
.def("__ne__", &ne_ptr<b2Joint>)
.def("__hash__", &hash_ptr<b2Joint>)
.add_property("type", &b2Joint::GetType)
.add_property("body_a", make_function(&b2Joint::GetBodyA, return_internal_reference<>()))
.add_property("body_b", make_function(&b2Joint::GetBodyB, return_internal_reference<>()))
.add_property("user_data", &b2Joint::GetUserData, &b2Joint::SetUserData)
.add_property("active", &b2Joint::IsActive)
;
}
void wrap_revolute_joint()
{
class_<b2RevoluteJoint, bases<b2Joint> >("RevoluteJoint", no_init)
.add_property("anchor_a", &b2RevoluteJoint::GetAnchorA)
.add_property("anchor_b", &b2RevoluteJoint::GetAnchorB)
.add_property("reaction_force", &b2RevoluteJoint::GetReactionForce)
.add_property("reaction_torque", &b2RevoluteJoint::GetReactionTorque)
.add_property("joint_angle", &b2RevoluteJoint::GetJointAngle)
.add_property("joint_speed", &b2RevoluteJoint::GetJointSpeed)
.add_property("limit_enabled", &b2RevoluteJoint::IsLimitEnabled, &b2RevoluteJoint::EnableLimit)
.add_property("lower_limit", &b2RevoluteJoint::GetLowerLimit)
.add_property("upper_limit", &b2RevoluteJoint::GetUpperLimit)
.add_property("motor_enabled", &b2RevoluteJoint::IsMotorEnabled, &b2RevoluteJoint::EnableMotor)
.add_property("motor_speed", &b2RevoluteJoint::GetMotorSpeed, &b2RevoluteJoint::SetMotorSpeed)
.add_property("motor_torque", &b2RevoluteJoint::GetMotorTorque)
.add_property("max_motor_torque", object(), &b2RevoluteJoint::SetMaxMotorTorque)
.def("set_limits", &b2RevoluteJoint::SetLimits)
;
}
void wrap_prismatic_joint()
{
class_<b2PrismaticJoint, bases<b2Joint> >("PrismaticJoint", no_init)
.add_property("anchor_a", &b2PrismaticJoint::GetAnchorA)
.add_property("anchor_b", &b2PrismaticJoint::GetAnchorB)
.add_property("reaction_force", &b2PrismaticJoint::GetReactionForce)
.add_property("reaction_torque", &b2PrismaticJoint::GetReactionTorque)
.add_property("joint_translation", &b2PrismaticJoint::GetJointTranslation)
.add_property("joint_speed", &b2PrismaticJoint::GetJointSpeed)
.add_property("limit_enabled", &b2PrismaticJoint::IsLimitEnabled, &b2PrismaticJoint::EnableLimit)
.add_property("lower_limit", &b2PrismaticJoint::GetLowerLimit)
.add_property("upper_limit", &b2PrismaticJoint::GetUpperLimit)
.add_property("motor_enabled", &b2PrismaticJoint::IsMotorEnabled, &b2PrismaticJoint::EnableMotor)
.add_property("motor_speed", &b2PrismaticJoint::GetMotorSpeed, &b2PrismaticJoint::SetMotorSpeed)
.add_property("motor_force", &b2PrismaticJoint::GetMotorForce)
.add_property("max_motor_force", object(), &b2PrismaticJoint::SetMaxMotorForce)
.def("set_limits", &b2PrismaticJoint::SetLimits)
;
}
void wrap_distance_joint()
{
class_<b2DistanceJoint, bases<b2Joint> >("DistanceJoint", no_init)
.add_property("anchor_a", &b2DistanceJoint::GetAnchorA)
.add_property("anchor_b", &b2DistanceJoint::GetAnchorB)
.add_property("reaction_force", &b2PrismaticJoint::GetReactionForce)
.add_property("reaction_torque", &b2PrismaticJoint::GetReactionTorque)
.add_property("length", &b2DistanceJoint::GetLength, &b2DistanceJoint::SetLength)
.add_property("frequency", &b2DistanceJoint::GetFrequency, &b2DistanceJoint::SetFrequency)
.add_property("damping_ratio", &b2DistanceJoint::GetDampingRatio, &b2DistanceJoint::SetDampingRatio)
;
}
void wrap_pulley_joint()
{
class_<b2PulleyJoint, bases<b2Joint> >("PulleyJoint", no_init)
.add_property("anchor_a", &b2PulleyJoint::GetAnchorA)
.add_property("anchor_b", &b2PulleyJoint::GetAnchorB)
.add_property("reaction_force", &b2PrismaticJoint::GetReactionForce)
.add_property("reaction_torque", &b2PrismaticJoint::GetReactionTorque)
.add_property("ground_anchor_a", &b2PulleyJoint::GetGroundAnchorA)
.add_property("ground_anchor_b", &b2PulleyJoint::GetGroundAnchorB)
.add_property("length_1", &b2PulleyJoint::GetLength1)
.add_property("length_2", &b2PulleyJoint::GetLength2)
.add_property("ratio", &b2PulleyJoint::GetRatio)
;
}
void wrap_mouse_joint()
{
class_<b2MouseJoint, bases<b2Joint> >("MouseJoint", no_init)
.add_property("anchor_a", &b2MouseJoint::GetAnchorA)
.add_property("anchor_b", &b2MouseJoint::GetAnchorB)
.add_property("reaction_force", &b2MouseJoint::GetReactionForce)
.add_property("reaction_torque", &b2MouseJoint::GetReactionTorque)
.add_property("target", make_function(&b2MouseJoint::GetTarget, return_value_policy<copy_const_reference>()), &b2MouseJoint::SetTarget)
.add_property("max_force", &b2MouseJoint::GetMaxForce, &b2MouseJoint::SetMaxForce)
.add_property("frequency", &b2MouseJoint::GetFrequency, &b2MouseJoint::SetFrequency)
.add_property("damping_ratio", &b2MouseJoint::GetDampingRatio, &b2MouseJoint::SetDampingRatio)
;
}
void wrap_gear_joint()
{
}
void wrap_line_joint()
{
}
void wrap_weld_joint()
{
}
void wrap_friction_joint()
{
}
}
<|endoftext|> |
<commit_before>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Copyright (C) 2012 Sergey Lisitsyn
*/
#include <shogun/transfer/multitask/MultitaskL1L2LogisticRegression.h>
#include <shogun/lib/slep/malsar_joint_feature_learning.h>
#include <shogun/lib/slep/slep_options.h>
#include <shogun/lib/IndexBlockGroup.h>
#include <shogun/lib/SGVector.h>
namespace shogun
{
CMultitaskL1L2LogisticRegression::CMultitaskL1L2LogisticRegression() :
CMultitaskLogisticRegression(), m_rho1(0.0), m_rho2(0.0)
{
}
CMultitaskL1L2LogisticRegression::CMultitaskL1L2LogisticRegression(
float64_t rho1, float64_t rho2, CDotFeatures* train_features,
CBinaryLabels* train_labels, CIndexBlockRelation* task_relation) :
CMultitaskLogisticRegression(0.0,train_features,train_labels,task_relation)
{
set_rho1(rho1);
set_rho2(rho2);
}
void CMultitaskL1L2LogisticRegression::set_rho1(float64_t rho1)
{
m_rho1 = rho1;
}
void CMultitaskL1L2LogisticRegression::set_rho2(float64_t rho2)
{
m_rho2 = rho2;
}
CMultitaskL1L2LogisticRegression::~CMultitaskL1L2LogisticRegression()
{
}
bool CMultitaskL1L2LogisticRegression::train_machine(CFeatures* data)
{
if (data && (CDotFeatures*)data)
set_features((CDotFeatures*)data);
ASSERT(features);
ASSERT(m_labels);
SGVector<float64_t> y(m_labels->get_num_labels());
for (int32_t i=0; i<y.vlen; i++)
y[i] = ((CBinaryLabels*)m_labels)->get_label(i);
slep_options options = slep_options::default_options();
options.termination = m_termination;
options.tolerance = m_tolerance;
options.max_iter = m_max_iter;
SGVector<index_t> ind = ((CIndexBlockGroup*)m_task_relation)->get_SLEP_ind();
options.ind = ind.vector;
options.n_tasks = ind.vlen-1;
#ifdef HAVE_EIGEN3
slep_result_t model = malsar_joint_feature_learning(
features, y.vector, m_rho1, m_rho2, options);
#endif
m_tasks_w = model.w;
m_tasks_c = model.c;
ASSERT(m_task_relation);
return true;
}
}
<commit_msg>Fixed guard of L1/L2 logistic regression<commit_after>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Copyright (C) 2012 Sergey Lisitsyn
*/
#include <shogun/transfer/multitask/MultitaskL1L2LogisticRegression.h>
#include <shogun/lib/slep/malsar_joint_feature_learning.h>
#include <shogun/lib/slep/slep_options.h>
#include <shogun/lib/IndexBlockGroup.h>
#include <shogun/lib/SGVector.h>
namespace shogun
{
CMultitaskL1L2LogisticRegression::CMultitaskL1L2LogisticRegression() :
CMultitaskLogisticRegression(), m_rho1(0.0), m_rho2(0.0)
{
}
CMultitaskL1L2LogisticRegression::CMultitaskL1L2LogisticRegression(
float64_t rho1, float64_t rho2, CDotFeatures* train_features,
CBinaryLabels* train_labels, CIndexBlockRelation* task_relation) :
CMultitaskLogisticRegression(0.0,train_features,train_labels,task_relation)
{
set_rho1(rho1);
set_rho2(rho2);
}
void CMultitaskL1L2LogisticRegression::set_rho1(float64_t rho1)
{
m_rho1 = rho1;
}
void CMultitaskL1L2LogisticRegression::set_rho2(float64_t rho2)
{
m_rho2 = rho2;
}
CMultitaskL1L2LogisticRegression::~CMultitaskL1L2LogisticRegression()
{
}
bool CMultitaskL1L2LogisticRegression::train_machine(CFeatures* data)
{
if (data && (CDotFeatures*)data)
set_features((CDotFeatures*)data);
ASSERT(features);
ASSERT(m_labels);
SGVector<float64_t> y(m_labels->get_num_labels());
for (int32_t i=0; i<y.vlen; i++)
y[i] = ((CBinaryLabels*)m_labels)->get_label(i);
slep_options options = slep_options::default_options();
options.termination = m_termination;
options.tolerance = m_tolerance;
options.max_iter = m_max_iter;
SGVector<index_t> ind = ((CIndexBlockGroup*)m_task_relation)->get_SLEP_ind();
options.ind = ind.vector;
options.n_tasks = ind.vlen-1;
#ifdef HAVE_EIGEN3
slep_result_t model = malsar_joint_feature_learning(
features, y.vector, m_rho1, m_rho2, options);
m_tasks_w = model.w;
m_tasks_c = model.c;
#endif
ASSERT(m_task_relation);
return true;
}
}
<|endoftext|> |
<commit_before>/*
* qmqtt_socket.cpp - qmqtt socket
*
* Copyright (c) 2013 Ery Lee <ery.lee at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of mqttc 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 "qmqtt_socket.h"
#include <QTcpSocket>
QMQTT::Socket::Socket(QObject* parent)
: SocketInterface(parent)
, _socket(new QTcpSocket)
{
connect(_socket.data(), &QTcpSocket::stateChanged, this, &Socket::onStateChanged);
connect(_socket.data(), &QTcpSocket::connected, this, &SocketInterface::connected);
connect(_socket.data(), &QTcpSocket::disconnected, this, &SocketInterface::disconnected);
connect(_socket.data(), &QTcpSocket::readyRead, this, &SocketInterface::readyRead);
connect(_socket.data(),
static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)>(&QTcpSocket::error),
this,
static_cast<void (SocketInterface::*)(QAbstractSocket::SocketError)>(&SocketInterface::error));\
}
QMQTT::Socket::~Socket()
{
}
void QMQTT::Socket::connectToHost(const QHostAddress& address, quint16 port)
{
return _socket->connectToHost(address, port);
}
void QMQTT::Socket::disconnectFromHost()
{
_socket->disconnectFromHost();
}
QAbstractSocket::SocketState QMQTT::Socket::state() const
{
return _socket->state();
}
bool QMQTT::Socket::atEnd() const
{
return _socket->atEnd();
}
bool QMQTT::Socket::waitForBytesWritten(int msecs)
{
return _socket->waitForBytesWritten(msecs);
}
bool QMQTT::Socket::waitForReadyRead(int msecs)
{
return _socket->waitForReadyRead(msecs);
}
QAbstractSocket::SocketError QMQTT::Socket::error() const
{
return _socket->error();
}
qint64 QMQTT::Socket::readData(char* data, qint64 maxlen)
{
return _socket->read(data, maxlen);
}
qint64 QMQTT::Socket::writeData(const char* data, qint64 len)
{
return _socket->write(data, len);
}
void QMQTT::Socket::onStateChanged(QAbstractSocket::SocketState state)
{
Q_UNUSED(state);
if(openMode() != _socket->openMode())
{
setOpenMode(_socket->openMode());
}
}
<commit_msg>qmqtt_socket.cpp - drop unneeded return (void)<commit_after>/*
* qmqtt_socket.cpp - qmqtt socket
*
* Copyright (c) 2013 Ery Lee <ery.lee at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of mqttc 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 "qmqtt_socket.h"
#include <QTcpSocket>
QMQTT::Socket::Socket(QObject* parent)
: SocketInterface(parent)
, _socket(new QTcpSocket)
{
connect(_socket.data(), &QTcpSocket::stateChanged, this, &Socket::onStateChanged);
connect(_socket.data(), &QTcpSocket::connected, this, &SocketInterface::connected);
connect(_socket.data(), &QTcpSocket::disconnected, this, &SocketInterface::disconnected);
connect(_socket.data(), &QTcpSocket::readyRead, this, &SocketInterface::readyRead);
connect(_socket.data(),
static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)>(&QTcpSocket::error),
this,
static_cast<void (SocketInterface::*)(QAbstractSocket::SocketError)>(&SocketInterface::error));\
}
QMQTT::Socket::~Socket()
{
}
void QMQTT::Socket::connectToHost(const QHostAddress& address, quint16 port)
{
_socket->connectToHost(address, port);
}
void QMQTT::Socket::disconnectFromHost()
{
_socket->disconnectFromHost();
}
QAbstractSocket::SocketState QMQTT::Socket::state() const
{
return _socket->state();
}
bool QMQTT::Socket::atEnd() const
{
return _socket->atEnd();
}
bool QMQTT::Socket::waitForBytesWritten(int msecs)
{
return _socket->waitForBytesWritten(msecs);
}
bool QMQTT::Socket::waitForReadyRead(int msecs)
{
return _socket->waitForReadyRead(msecs);
}
QAbstractSocket::SocketError QMQTT::Socket::error() const
{
return _socket->error();
}
qint64 QMQTT::Socket::readData(char* data, qint64 maxlen)
{
return _socket->read(data, maxlen);
}
qint64 QMQTT::Socket::writeData(const char* data, qint64 len)
{
return _socket->write(data, len);
}
void QMQTT::Socket::onStateChanged(QAbstractSocket::SocketState state)
{
Q_UNUSED(state);
if(openMode() != _socket->openMode())
{
setOpenMode(_socket->openMode());
}
}
<|endoftext|> |
<commit_before>
/**
* PyOtherSide: Asynchronous Python 3 Bindings for Qt 5
* Copyright (c) 2011, 2013, Thomas Perl <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
**/
#include "qml_python_bridge.h"
#include "qpython_priv.h"
static QPythonPriv *priv = NULL;
PyObject *
pyotherside_send(PyObject *self, PyObject *args)
{
priv->receiveObject(args);
Py_RETURN_NONE;
}
PyObject *
pyotherside_atexit(PyObject *self, PyObject *o)
{
if (priv->atexit_callback != NULL) {
Py_DECREF(priv->atexit_callback);
}
Py_INCREF(o);
priv->atexit_callback = o;
Py_RETURN_NONE;
}
static PyMethodDef PyOtherSideMethods[] = {
{"send", pyotherside_send, METH_VARARGS, "Send data to Qt."},
{"atexit", pyotherside_atexit, METH_O, "Function to call on shutdown."},
{NULL, NULL, 0, NULL},
};
#ifdef PY3K
static struct PyModuleDef PyOtherSideModule = {
PyModuleDef_HEAD_INIT,
"pyotherside", /* name of module */
NULL,
-1,
PyOtherSideMethods,
};
PyMODINIT_FUNC
PyOtherSide_init()
{
return PyModule_Create(&PyOtherSideModule);
}
#endif
QPythonPriv::QPythonPriv()
: locals(NULL)
, globals(NULL)
, state(NULL)
, atexit_callback(NULL)
, traceback_mod(NULL)
, mutex()
{
#ifdef PY3K
PyImport_AppendInittab("pyotherside", PyOtherSide_init);
#endif
Py_Initialize();
PyEval_InitThreads();
locals = PyDict_New();
assert(locals != NULL);
globals = PyDict_New();
assert(globals != NULL);
traceback_mod = PyImport_ImportModule("traceback");
assert(traceback_mod != NULL);
#ifndef PY3K
Py_InitModule("pyotherside", PyOtherSideMethods);
#endif
priv = this;
if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
PyDict_SetItemString(globals, "__builtins__",
PyEval_GetBuiltins());
}
// Need to lock mutex here, as it will always be unlocked
// by leave(). If we don't do that, it will be unlocked
// once too often resulting in undefined behavior.
mutex.lock();
leave();
}
QPythonPriv::~QPythonPriv()
{
enter();
Py_DECREF(traceback_mod);
Py_DECREF(globals);
Py_DECREF(locals);
Py_Finalize();
}
void
QPythonPriv::enter()
{
mutex.lock();
assert(state != NULL);
PyEval_RestoreThread(state);
state = NULL;
}
void
QPythonPriv::leave()
{
assert(state == NULL);
state = PyEval_SaveThread();
mutex.unlock();
}
void
QPythonPriv::receiveObject(PyObject *o)
{
emit receive(convertPyObjectToQVariant(o));
}
QString
QPythonPriv::formatExc()
{
PyObject *type = NULL;
PyObject *value = NULL;
PyObject *traceback = NULL;
PyErr_Fetch(&type, &value, &traceback);
PyErr_Clear();
if (type == NULL && value == NULL && traceback == NULL) {
return "No Error";
}
if (value != NULL && (type == NULL || traceback == NULL)) {
return convertPyObjectToQVariant(PyObject_Str(value)).toString();
}
PyObject *list = PyObject_CallMethod(traceback_mod,
"format_exception", "OOO", type, value, traceback);
Q_ASSERT(list != NULL);
PyObject *n = PyUnicode_FromString("\n");
Q_ASSERT(n != NULL);
PyObject *s = PyUnicode_Join(n, list);
Q_ASSERT(s != NULL);
if (s == NULL) {
PyErr_Print();
return "Exception";
}
QVariant v = convertPyObjectToQVariant(s);
Q_ASSERT(v != NULL);
Py_DECREF(s);
Py_DECREF(n);
Py_DECREF(list);
Py_DECREF(type);
Py_DECREF(value);
Py_DECREF(traceback);
return v.toString();
}
PyObject *
QPythonPriv::eval(QString expr)
{
QByteArray utf8bytes = expr.toUtf8();
PyObject *result = PyRun_String(utf8bytes.constData(),
Py_eval_input, globals, locals);
return result;
}
void
QPythonPriv::closing()
{
if (priv->atexit_callback != NULL) {
PyObject *args = PyTuple_New(0);
PyObject *result = PyObject_Call(priv->atexit_callback, args, NULL);
Py_DECREF(args);
Py_XDECREF(result);
Py_DECREF(priv->atexit_callback);
priv->atexit_callback = NULL;
}
}
<commit_msg>Fix a minor issue in checking QVariant validity<commit_after>
/**
* PyOtherSide: Asynchronous Python 3 Bindings for Qt 5
* Copyright (c) 2011, 2013, Thomas Perl <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
**/
#include "qml_python_bridge.h"
#include "qpython_priv.h"
static QPythonPriv *priv = NULL;
PyObject *
pyotherside_send(PyObject *self, PyObject *args)
{
priv->receiveObject(args);
Py_RETURN_NONE;
}
PyObject *
pyotherside_atexit(PyObject *self, PyObject *o)
{
if (priv->atexit_callback != NULL) {
Py_DECREF(priv->atexit_callback);
}
Py_INCREF(o);
priv->atexit_callback = o;
Py_RETURN_NONE;
}
static PyMethodDef PyOtherSideMethods[] = {
{"send", pyotherside_send, METH_VARARGS, "Send data to Qt."},
{"atexit", pyotherside_atexit, METH_O, "Function to call on shutdown."},
{NULL, NULL, 0, NULL},
};
#ifdef PY3K
static struct PyModuleDef PyOtherSideModule = {
PyModuleDef_HEAD_INIT,
"pyotherside", /* name of module */
NULL,
-1,
PyOtherSideMethods,
};
PyMODINIT_FUNC
PyOtherSide_init()
{
return PyModule_Create(&PyOtherSideModule);
}
#endif
QPythonPriv::QPythonPriv()
: locals(NULL)
, globals(NULL)
, state(NULL)
, atexit_callback(NULL)
, traceback_mod(NULL)
, mutex()
{
#ifdef PY3K
PyImport_AppendInittab("pyotherside", PyOtherSide_init);
#endif
Py_Initialize();
PyEval_InitThreads();
locals = PyDict_New();
assert(locals != NULL);
globals = PyDict_New();
assert(globals != NULL);
traceback_mod = PyImport_ImportModule("traceback");
assert(traceback_mod != NULL);
#ifndef PY3K
Py_InitModule("pyotherside", PyOtherSideMethods);
#endif
priv = this;
if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
PyDict_SetItemString(globals, "__builtins__",
PyEval_GetBuiltins());
}
// Need to lock mutex here, as it will always be unlocked
// by leave(). If we don't do that, it will be unlocked
// once too often resulting in undefined behavior.
mutex.lock();
leave();
}
QPythonPriv::~QPythonPriv()
{
enter();
Py_DECREF(traceback_mod);
Py_DECREF(globals);
Py_DECREF(locals);
Py_Finalize();
}
void
QPythonPriv::enter()
{
mutex.lock();
assert(state != NULL);
PyEval_RestoreThread(state);
state = NULL;
}
void
QPythonPriv::leave()
{
assert(state == NULL);
state = PyEval_SaveThread();
mutex.unlock();
}
void
QPythonPriv::receiveObject(PyObject *o)
{
emit receive(convertPyObjectToQVariant(o));
}
QString
QPythonPriv::formatExc()
{
PyObject *type = NULL;
PyObject *value = NULL;
PyObject *traceback = NULL;
PyErr_Fetch(&type, &value, &traceback);
PyErr_Clear();
if (type == NULL && value == NULL && traceback == NULL) {
return "No Error";
}
if (value != NULL && (type == NULL || traceback == NULL)) {
return convertPyObjectToQVariant(PyObject_Str(value)).toString();
}
PyObject *list = PyObject_CallMethod(traceback_mod,
"format_exception", "OOO", type, value, traceback);
Q_ASSERT(list != NULL);
PyObject *n = PyUnicode_FromString("\n");
Q_ASSERT(n != NULL);
PyObject *s = PyUnicode_Join(n, list);
Q_ASSERT(s != NULL);
if (s == NULL) {
PyErr_Print();
return "Exception";
}
QVariant v = convertPyObjectToQVariant(s);
Q_ASSERT(v.isValid());
Py_DECREF(s);
Py_DECREF(n);
Py_DECREF(list);
Py_DECREF(type);
Py_DECREF(value);
Py_DECREF(traceback);
return v.toString();
}
PyObject *
QPythonPriv::eval(QString expr)
{
QByteArray utf8bytes = expr.toUtf8();
PyObject *result = PyRun_String(utf8bytes.constData(),
Py_eval_input, globals, locals);
return result;
}
void
QPythonPriv::closing()
{
if (priv->atexit_callback != NULL) {
PyObject *args = PyTuple_New(0);
PyObject *result = PyObject_Call(priv->atexit_callback, args, NULL);
Py_DECREF(args);
Py_XDECREF(result);
Py_DECREF(priv->atexit_callback);
priv->atexit_callback = NULL;
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2016 PX4 Development Team. 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. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file df_bmp280_wrapper.cpp
* Lightweight driver to access the BMP280 of the DriverFramework.
*
* @author Julian Oes <[email protected]>
*/
#include <px4_config.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdint.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#include <px4_getopt.h>
#include <errno.h>
#include <systemlib/perf_counter.h>
#include <systemlib/err.h>
#include <drivers/drv_baro.h>
#include <board_config.h>
//#include <mathlib/math/filter/LowPassFilter2p.hpp>
#include <bmp280/BMP280.hpp>
#include <DevMgr.hpp>
extern "C" { __EXPORT int df_bmp280_wrapper_main(int argc, char *argv[]); }
using namespace DriverFramework;
class DfBmp280Wrapper : public BMP280
{
public:
DfBmp280Wrapper();
~DfBmp280Wrapper();
/**
* Start automatic measurement.
*
* @return 0 on success
*/
int start();
/**
* Stop automatic measurement.
*
* @return 0 on success
*/
int stop();
private:
int _publish(struct baro_sensor_data &data);
orb_advert_t _baro_topic;
int _baro_orb_class_instance;
perf_counter_t _baro_sample_perf;
};
DfBmp280Wrapper::DfBmp280Wrapper() :
BMP280(BARO_DEVICE_PATH),
_baro_topic(nullptr),
_baro_orb_class_instance(-1),
_baro_sample_perf(perf_alloc(PC_ELAPSED, "df_baro_read"))
{
}
DfBmp280Wrapper::~DfBmp280Wrapper()
{
perf_free(_baro_sample_perf);
}
int DfBmp280Wrapper::start()
{
/* Init device and start sensor. */
int ret = init();
if (ret != 0) {
PX4_ERR("BMP280 init fail: %d", ret);
return ret;
}
ret = BMP280::start();
if (ret != 0) {
PX4_ERR("BMP280 start fail: %d", ret);
return ret;
}
return 0;
}
int DfBmp280Wrapper::stop()
{
/* Stop sensor. */
int ret = BMP280::stop();
if (ret != 0) {
PX4_ERR("BMP280 stop fail: %d", ret);
return ret;
}
return 0;
}
int DfBmp280Wrapper::_publish(struct baro_sensor_data &data)
{
perf_begin(_baro_sample_perf);
baro_report baro_report = {};
baro_report.timestamp = hrt_absolute_time();
baro_report.pressure = data.pressure_pa;
baro_report.temperature = data.temperature_c;
// TODO: verify this, it's just copied from the MS5611 driver.
// Constant for now
const double MSL_PRESSURE_KPA = 101325.0 / 1000.0;
/* tropospheric properties (0-11km) for standard atmosphere */
const double T1 = 15.0 + 273.15; /* temperature at base height in Kelvin */
const double a = -6.5 / 1000; /* temperature gradient in degrees per metre */
const double g = 9.80665; /* gravity constant in m/s/s */
const double R = 287.05; /* ideal gas constant in J/kg/K */
/* current pressure at MSL in kPa */
double p1 = MSL_PRESSURE_KPA;
/* measured pressure in kPa */
double p = static_cast<double>(data.pressure_pa) / 1000.0;
/*
* Solve:
*
* / -(aR / g) \
* | (p / p1) . T1 | - T1
* \ /
* h = ------------------------------- + h1
* a
*/
baro_report.altitude = (((pow((p / p1), (-(a * R) / g))) * T1) - T1) / a;
// TODO: when is this ever blocked?
if (!(m_pub_blocked)) {
if (_baro_topic == nullptr) {
_baro_topic = orb_advertise_multi(ORB_ID(sensor_baro), &baro_report,
&_baro_orb_class_instance, ORB_PRIO_DEFAULT);
} else {
orb_publish(ORB_ID(sensor_baro), _baro_topic, &baro_report);
}
}
/* Notify anyone waiting for data. */
DevMgr::updateNotify(*this);
perf_end(_baro_sample_perf);
return 0;
};
namespace df_bmp280_wrapper
{
DfBmp280Wrapper *g_dev = nullptr;
int start(/* enum Rotation rotation */);
int stop();
int info();
void usage();
int start(/*enum Rotation rotation*/)
{
g_dev = new DfBmp280Wrapper(/*rotation*/);
if (g_dev == nullptr) {
PX4_ERR("failed instantiating DfBmp280Wrapper object");
return -1;
}
int ret = g_dev->start();
if (ret != 0) {
PX4_ERR("DfBmp280Wrapper start failed");
return ret;
}
// Open the IMU sensor
DevHandle h;
DevMgr::getHandle(BARO_DEVICE_PATH, h);
if (!h.isValid()) {
DF_LOG_INFO("Error: unable to obtain a valid handle for the receiver at: %s (%d)",
BARO_DEVICE_PATH, h.getError());
return -1;
}
DevMgr::releaseHandle(h);
return 0;
}
int stop()
{
if (g_dev == nullptr) {
PX4_ERR("driver not running");
return 1;
}
int ret = g_dev->stop();
if (ret != 0) {
PX4_ERR("driver could not be stopped");
return ret;
}
delete g_dev;
g_dev = nullptr;
return 0;
}
/**
* Print a little info about the driver.
*/
int
info()
{
if (g_dev == nullptr) {
PX4_ERR("driver not running");
return 1;
}
PX4_DEBUG("state @ %p", g_dev);
return 0;
}
void
usage()
{
PX4_WARN("Usage: df_bmp280_wrapper 'start', 'info', 'stop'");
}
} // namespace df_bmp280_wrapper
int
df_bmp280_wrapper_main(int argc, char *argv[])
{
int ret = 0;
int myoptind = 1;
if (argc <= 1) {
df_bmp280_wrapper::usage();
return 1;
}
const char *verb = argv[myoptind];
if (!strcmp(verb, "start")) {
ret = df_bmp280_wrapper::start();
}
else if (!strcmp(verb, "stop")) {
ret = df_bmp280_wrapper::stop();
}
else if (!strcmp(verb, "info")) {
ret = df_bmp280_wrapper::info();
}
else {
df_bmp280_wrapper::usage();
return 1;
}
return ret;
}
<commit_msg>use mBar<commit_after>/****************************************************************************
*
* Copyright (c) 2016 PX4 Development Team. 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. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file df_bmp280_wrapper.cpp
* Lightweight driver to access the BMP280 of the DriverFramework.
*
* @author Julian Oes <[email protected]>
*/
#include <px4_config.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdint.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#include <px4_getopt.h>
#include <errno.h>
#include <systemlib/perf_counter.h>
#include <systemlib/err.h>
#include <drivers/drv_baro.h>
#include <board_config.h>
//#include <mathlib/math/filter/LowPassFilter2p.hpp>
#include <bmp280/BMP280.hpp>
#include <DevMgr.hpp>
extern "C" { __EXPORT int df_bmp280_wrapper_main(int argc, char *argv[]); }
using namespace DriverFramework;
class DfBmp280Wrapper : public BMP280
{
public:
DfBmp280Wrapper();
~DfBmp280Wrapper();
/**
* Start automatic measurement.
*
* @return 0 on success
*/
int start();
/**
* Stop automatic measurement.
*
* @return 0 on success
*/
int stop();
private:
int _publish(struct baro_sensor_data &data);
orb_advert_t _baro_topic;
int _baro_orb_class_instance;
perf_counter_t _baro_sample_perf;
};
DfBmp280Wrapper::DfBmp280Wrapper() :
BMP280(BARO_DEVICE_PATH),
_baro_topic(nullptr),
_baro_orb_class_instance(-1),
_baro_sample_perf(perf_alloc(PC_ELAPSED, "df_baro_read"))
{
}
DfBmp280Wrapper::~DfBmp280Wrapper()
{
perf_free(_baro_sample_perf);
}
int DfBmp280Wrapper::start()
{
/* Init device and start sensor. */
int ret = init();
if (ret != 0) {
PX4_ERR("BMP280 init fail: %d", ret);
return ret;
}
ret = BMP280::start();
if (ret != 0) {
PX4_ERR("BMP280 start fail: %d", ret);
return ret;
}
return 0;
}
int DfBmp280Wrapper::stop()
{
/* Stop sensor. */
int ret = BMP280::stop();
if (ret != 0) {
PX4_ERR("BMP280 stop fail: %d", ret);
return ret;
}
return 0;
}
int DfBmp280Wrapper::_publish(struct baro_sensor_data &data)
{
perf_begin(_baro_sample_perf);
baro_report baro_report = {};
baro_report.timestamp = hrt_absolute_time();
baro_report.pressure = data.pressure_pa / 100.0f; // to mbar
baro_report.temperature = data.temperature_c;
// TODO: verify this, it's just copied from the MS5611 driver.
// Constant for now
const double MSL_PRESSURE_KPA = 101325.0 / 1000.0;
/* tropospheric properties (0-11km) for standard atmosphere */
const double T1 = 15.0 + 273.15; /* temperature at base height in Kelvin */
const double a = -6.5 / 1000; /* temperature gradient in degrees per metre */
const double g = 9.80665; /* gravity constant in m/s/s */
const double R = 287.05; /* ideal gas constant in J/kg/K */
/* current pressure at MSL in kPa */
double p1 = MSL_PRESSURE_KPA;
/* measured pressure in kPa */
double p = static_cast<double>(data.pressure_pa) / 1000.0;
/*
* Solve:
*
* / -(aR / g) \
* | (p / p1) . T1 | - T1
* \ /
* h = ------------------------------- + h1
* a
*/
baro_report.altitude = (((pow((p / p1), (-(a * R) / g))) * T1) - T1) / a;
// TODO: when is this ever blocked?
if (!(m_pub_blocked)) {
if (_baro_topic == nullptr) {
_baro_topic = orb_advertise_multi(ORB_ID(sensor_baro), &baro_report,
&_baro_orb_class_instance, ORB_PRIO_DEFAULT);
} else {
orb_publish(ORB_ID(sensor_baro), _baro_topic, &baro_report);
}
}
/* Notify anyone waiting for data. */
DevMgr::updateNotify(*this);
perf_end(_baro_sample_perf);
return 0;
};
namespace df_bmp280_wrapper
{
DfBmp280Wrapper *g_dev = nullptr;
int start(/* enum Rotation rotation */);
int stop();
int info();
void usage();
int start(/*enum Rotation rotation*/)
{
g_dev = new DfBmp280Wrapper(/*rotation*/);
if (g_dev == nullptr) {
PX4_ERR("failed instantiating DfBmp280Wrapper object");
return -1;
}
int ret = g_dev->start();
if (ret != 0) {
PX4_ERR("DfBmp280Wrapper start failed");
return ret;
}
// Open the IMU sensor
DevHandle h;
DevMgr::getHandle(BARO_DEVICE_PATH, h);
if (!h.isValid()) {
DF_LOG_INFO("Error: unable to obtain a valid handle for the receiver at: %s (%d)",
BARO_DEVICE_PATH, h.getError());
return -1;
}
DevMgr::releaseHandle(h);
return 0;
}
int stop()
{
if (g_dev == nullptr) {
PX4_ERR("driver not running");
return 1;
}
int ret = g_dev->stop();
if (ret != 0) {
PX4_ERR("driver could not be stopped");
return ret;
}
delete g_dev;
g_dev = nullptr;
return 0;
}
/**
* Print a little info about the driver.
*/
int
info()
{
if (g_dev == nullptr) {
PX4_ERR("driver not running");
return 1;
}
PX4_DEBUG("state @ %p", g_dev);
return 0;
}
void
usage()
{
PX4_WARN("Usage: df_bmp280_wrapper 'start', 'info', 'stop'");
}
} // namespace df_bmp280_wrapper
int
df_bmp280_wrapper_main(int argc, char *argv[])
{
int ret = 0;
int myoptind = 1;
if (argc <= 1) {
df_bmp280_wrapper::usage();
return 1;
}
const char *verb = argv[myoptind];
if (!strcmp(verb, "start")) {
ret = df_bmp280_wrapper::start();
}
else if (!strcmp(verb, "stop")) {
ret = df_bmp280_wrapper::stop();
}
else if (!strcmp(verb, "info")) {
ret = df_bmp280_wrapper::info();
}
else {
df_bmp280_wrapper::usage();
return 1;
}
return ret;
}
<|endoftext|> |
<commit_before>#include "queuemanager.h"
#include <fstream>
#include <libxml/uri.h>
#include "configpaths.h"
#include "fmtstrformatter.h"
#include "rssfeed.h"
#include "stflpp.h"
#include "utils.h"
namespace newsboat {
QueueManager::QueueManager(ConfigContainer* cfg_, ConfigPaths* paths_)
: cfg(cfg_)
, paths(paths_)
{}
void QueueManager::enqueue_url(std::shared_ptr<RssItem> item,
std::shared_ptr<RssFeed> feed)
{
const std::string& url = item->enclosure_url();
bool url_found = false;
std::fstream f;
f.open(paths->queue_file(), std::fstream::in);
if (f.is_open()) {
do {
std::string line;
getline(f, line);
if (!f.eof() && !line.empty()) {
std::vector<std::string> fields =
utils::tokenize_quoted(line);
if (!fields.empty() && fields[0] == url) {
url_found = true;
break;
}
}
} while (!f.eof());
f.close();
}
if (!url_found) {
f.open(paths->queue_file(),
std::fstream::app | std::fstream::out);
const std::string filename =
generate_enqueue_filename(item, feed);
f << url << " " << utils::quote(filename) << std::endl;
f.close();
}
}
std::string get_hostname_from_url(const std::string& url)
{
xmlURIPtr uri = xmlParseURI(url.c_str());
std::string hostname;
if (uri) {
hostname = uri->server;
xmlFreeURI(uri);
}
return hostname;
}
std::string QueueManager::generate_enqueue_filename(std::shared_ptr<RssItem>
item,
std::shared_ptr<RssFeed> feed)
{
const std::string& url = item->enclosure_url();
const std::string& title = utils::utf8_to_locale(item->title());
const time_t pubDate = item->pubDate_timestamp();
std::string dlformat = cfg->get_configvalue("download-path");
if (dlformat[dlformat.length() - 1] != NEWSBEUTER_PATH_SEP) {
dlformat.push_back(NEWSBEUTER_PATH_SEP);
}
const std::string filemask = cfg->get_configvalue("download-filename-format");
dlformat.append(filemask);
const std::string base = utils::get_basename(url);
std::string extension;
const std::size_t pos = base.rfind('.');
if (pos != std::string::npos) {
extension.append(base.substr(pos + 1));
}
FmtStrFormatter fmt;
fmt.register_fmt('n', feed->title());
fmt.register_fmt('h', get_hostname_from_url(url));
fmt.register_fmt('u', base);
fmt.register_fmt('F', utils::mt_strf_localtime("%F", pubDate));
fmt.register_fmt('m', utils::mt_strf_localtime("%m", pubDate));
fmt.register_fmt('b', utils::mt_strf_localtime("%b", pubDate));
fmt.register_fmt('d', utils::mt_strf_localtime("%d", pubDate));
fmt.register_fmt('H', utils::mt_strf_localtime("%H", pubDate));
fmt.register_fmt('M', utils::mt_strf_localtime("%M", pubDate));
fmt.register_fmt('S', utils::mt_strf_localtime("%S", pubDate));
fmt.register_fmt('y', utils::mt_strf_localtime("%y", pubDate));
fmt.register_fmt('Y', utils::mt_strf_localtime("%Y", pubDate));
fmt.register_fmt('t', title);
fmt.register_fmt('e', extension);
if (feed->rssurl() != item->feedurl() &&
item->get_feedptr() != nullptr) {
std::string feedtitle = item->get_feedptr()->title();
utils::remove_soft_hyphens(feedtitle);
fmt.register_fmt('N', feedtitle);
} else {
fmt.register_fmt('N', feed->title());
}
const std::string dlpath = fmt.do_format(dlformat);
return dlpath;
}
void QueueManager::autoenqueue(std::shared_ptr<RssFeed> feed)
{
if (!cfg->get_configvalue_as_bool("podcast-auto-enqueue")) {
return;
}
std::lock_guard<std::mutex> lock(feed->item_mutex);
for (const auto& item : feed->items()) {
if (!item->enqueued() && item->enclosure_url().length() > 0) {
LOG(Level::DEBUG,
"QueueManager::autoenqueue: enclosure_url = "
"`%s' "
"enclosure_type = `%s'",
item->enclosure_url(),
item->enclosure_type());
if (utils::is_http_url(item->enclosure_url())) {
LOG(Level::INFO,
"QueueManager::autoenqueue: enqueuing "
"`%s'",
item->enclosure_url());
enqueue_url(item, feed);
item->set_enqueued(true);
}
}
}
}
} // namespace newsboat
<commit_msg>Replace slashes with underscores in generated podcast filenames<commit_after>#include "queuemanager.h"
#include <fstream>
#include <libxml/uri.h>
#include "configpaths.h"
#include "fmtstrformatter.h"
#include "rssfeed.h"
#include "stflpp.h"
#include "utils.h"
namespace newsboat {
QueueManager::QueueManager(ConfigContainer* cfg_, ConfigPaths* paths_)
: cfg(cfg_)
, paths(paths_)
{}
void QueueManager::enqueue_url(std::shared_ptr<RssItem> item,
std::shared_ptr<RssFeed> feed)
{
const std::string& url = item->enclosure_url();
bool url_found = false;
std::fstream f;
f.open(paths->queue_file(), std::fstream::in);
if (f.is_open()) {
do {
std::string line;
getline(f, line);
if (!f.eof() && !line.empty()) {
std::vector<std::string> fields =
utils::tokenize_quoted(line);
if (!fields.empty() && fields[0] == url) {
url_found = true;
break;
}
}
} while (!f.eof());
f.close();
}
if (!url_found) {
f.open(paths->queue_file(),
std::fstream::app | std::fstream::out);
const std::string filename =
generate_enqueue_filename(item, feed);
f << url << " " << utils::quote(filename) << std::endl;
f.close();
}
}
std::string get_hostname_from_url(const std::string& url)
{
xmlURIPtr uri = xmlParseURI(url.c_str());
std::string hostname;
if (uri) {
hostname = uri->server;
xmlFreeURI(uri);
}
return hostname;
}
std::string QueueManager::generate_enqueue_filename(std::shared_ptr<RssItem>
item,
std::shared_ptr<RssFeed> feed)
{
const std::string& url = item->enclosure_url();
const std::string& title = utils::utf8_to_locale(item->title());
const time_t pubDate = item->pubDate_timestamp();
std::string dlformat = cfg->get_configvalue("download-path");
if (dlformat[dlformat.length() - 1] != NEWSBEUTER_PATH_SEP) {
dlformat.push_back(NEWSBEUTER_PATH_SEP);
}
const std::string filemask = cfg->get_configvalue("download-filename-format");
dlformat.append(filemask);
const std::string base = utils::get_basename(url);
std::string extension;
const std::size_t pos = base.rfind('.');
if (pos != std::string::npos) {
extension.append(base.substr(pos + 1));
}
FmtStrFormatter fmt;
fmt.register_fmt('n', utils::replace_all(feed->title(), "/", "_"));
fmt.register_fmt('h', get_hostname_from_url(url));
fmt.register_fmt('u', base);
fmt.register_fmt('F', utils::mt_strf_localtime("%F", pubDate));
fmt.register_fmt('m', utils::mt_strf_localtime("%m", pubDate));
fmt.register_fmt('b', utils::mt_strf_localtime("%b", pubDate));
fmt.register_fmt('d', utils::mt_strf_localtime("%d", pubDate));
fmt.register_fmt('H', utils::mt_strf_localtime("%H", pubDate));
fmt.register_fmt('M', utils::mt_strf_localtime("%M", pubDate));
fmt.register_fmt('S', utils::mt_strf_localtime("%S", pubDate));
fmt.register_fmt('y', utils::mt_strf_localtime("%y", pubDate));
fmt.register_fmt('Y', utils::mt_strf_localtime("%Y", pubDate));
fmt.register_fmt('t', utils::replace_all(title, "/", "_"));
fmt.register_fmt('e', utils::replace_all(extension, "/", "_"));
if (feed->rssurl() != item->feedurl() &&
item->get_feedptr() != nullptr) {
std::string feedtitle = item->get_feedptr()->title();
utils::remove_soft_hyphens(feedtitle);
fmt.register_fmt('N', utils::replace_all(feedtitle, "/", "_"));
} else {
fmt.register_fmt('N', utils::replace_all(feed->title(), "/", "_"));
}
const std::string dlpath = fmt.do_format(dlformat);
return dlpath;
}
void QueueManager::autoenqueue(std::shared_ptr<RssFeed> feed)
{
if (!cfg->get_configvalue_as_bool("podcast-auto-enqueue")) {
return;
}
std::lock_guard<std::mutex> lock(feed->item_mutex);
for (const auto& item : feed->items()) {
if (!item->enqueued() && item->enclosure_url().length() > 0) {
LOG(Level::DEBUG,
"QueueManager::autoenqueue: enclosure_url = "
"`%s' "
"enclosure_type = `%s'",
item->enclosure_url(),
item->enclosure_type());
if (utils::is_http_url(item->enclosure_url())) {
LOG(Level::INFO,
"QueueManager::autoenqueue: enqueuing "
"`%s'",
item->enclosure_url());
enqueue_url(item, feed);
item->set_enqueued(true);
}
}
}
}
} // namespace newsboat
<|endoftext|> |
<commit_before>
#include <bits/stdc++.h>
using namespace std;
class IntList {
private:
const int * head;
const IntList * tail;
IntList(const int * head) {
this->head = head;
tail = NULL;}
IntList(const int * X, const IntList * Xs) {
head = X;
tail = Xs;
}
};
<commit_msg>Updated as cpp<commit_after>#include <bits/stdc++.h>
using namespace std;
class IntList {
private:
int head=0;
int tail=0;
IntList(int head) ;
IntList( int X, int Xs) ;
static IntList cons(int X,int Xs);
static IntList app(int y ,int Ys);
static int toInts(int Xs);
static int len(int Xs);
};
int main(){return 0;}
<|endoftext|> |
<commit_before>/*******************************************************************************
Module: FGLGear.cpp
Author: Jon S. Berndt
Date started: 11/18/99
Purpose: Encapsulates the landing gear elements
Called by: FGAircraft
------------- Copyright (C) 1999 Jon S. Berndt ([email protected]) -------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
Further information about the GNU General Public License can also be found on
the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
HISTORY
--------------------------------------------------------------------------------
11/18/99 JSB Created
********************************************************************************
INCLUDES
*******************************************************************************/
#include "FGLGear.h"
#include <algorithm>
/*******************************************************************************
************************************ CODE **************************************
*******************************************************************************/
FGLGear::FGLGear(FGConfigFile* AC_cfg, FGFDMExec* fdmex) : vXYZ(3),
vMoment(3),
vWhlBodyVec(3),
Exec(fdmex)
{
string tmp;
*AC_cfg >> tmp >> name >> vXYZ(1) >> vXYZ(2) >> vXYZ(3)
>> kSpring >> bDamp>> dynamicFCoeff >> staticFCoeff
>> SteerType >> BrakeType >> GroupMember >> maxSteerAngle;
cout << " Name: " << name << endl;
cout << " Location: " << vXYZ << endl;
cout << " Spring Constant: " << kSpring << endl;
cout << " Damping Constant: " << bDamp << endl;
cout << " Dynamic Friction: " << dynamicFCoeff << endl;
cout << " Static Friction: " << staticFCoeff << endl;
cout << " Brake Type: " << BrakeType << endl;
cout << " Grouping: " << GroupMember << endl;
cout << " Steering Type: " << SteerType << endl;
cout << " Max Steer Angle: " << maxSteerAngle << endl;
State = Exec->GetState();
Aircraft = Exec->GetAircraft();
Position = Exec->GetPosition();
Rotation = Exec->GetRotation();
WOW = false;
ReportEnable=true;
FirstContact = false;
Reported = false;
DistanceTraveled = 0.0;
MaximumStrutForce = MaximumStrutTravel = 0.0;
}
/******************************************************************************/
FGLGear::~FGLGear(void)
{
}
/******************************************************************************/
FGColumnVector FGLGear::Force(void)
{
FGColumnVector vForce(3);
FGColumnVector vLocalForce(3);
FGColumnVector vLocalGear(3); // Vector: CG to this wheel (Local)
FGColumnVector vWhlVelVec(3); // Velocity of this wheel (Local)
vWhlBodyVec = (vXYZ - Aircraft->GetXYZcg()) / 12.0;
vWhlBodyVec(eX) = -vWhlBodyVec(eX);
vWhlBodyVec(eZ) = -vWhlBodyVec(eZ);
vLocalGear = State->GetTb2l() * vWhlBodyVec;
compressLength = vLocalGear(eZ) - Position->GetDistanceAGL();
if (compressLength > 0.00) {
WOW = true;
vWhlVelVec = State->GetTb2l() * (Rotation->GetPQR() * vWhlBodyVec);
vWhlVelVec += Position->GetVel();
compressSpeed = vWhlVelVec(eZ);
if (!FirstContact) {
FirstContact = true;
SinkRate = compressSpeed;
GroundSpeed = Position->GetVel().Magnitude();
}
vWhlVelVec = -1.0 * vWhlVelVec.Normalize();
vWhlVelVec(eZ) = 0.00;
// the following needs work regarding friction coefficients and braking and steering
vLocalForce(eZ) = min(-compressLength * kSpring - compressSpeed * bDamp, (float)0.0);
vLocalForce(eX) = fabs(vLocalForce(eZ) * staticFCoeff) * vWhlVelVec(eX);
vLocalForce(eY) = fabs(vLocalForce(eZ) * staticFCoeff) * vWhlVelVec(eY);
MaximumStrutForce = max(MaximumStrutForce, fabs(vLocalForce(eZ)));
MaximumStrutTravel = max(MaximumStrutTravel, fabs(compressLength));
vForce = State->GetTl2b() * vLocalForce ;
vMoment = vWhlBodyVec * vForce;
cout << " Force: " << vForce << endl;
cout << " Moment: " << vMoment << endl;
} else {
WOW = false;
if (Position->GetDistanceAGL() > 200.0) {
FirstContact = false;
Reported = false;
DistanceTraveled = 0.0;
MaximumStrutForce = MaximumStrutTravel = 0.0;
}
vForce.InitMatrix();
vMoment.InitMatrix();
}
if (FirstContact) {
DistanceTraveled += Position->GetVel().Magnitude()*State->Getdt()*Aircraft->GetRate();
}
if (ReportEnable && Position->GetVel().Magnitude() <= 0.05 && !Reported) {
Report();
}
return vForce;
}
/******************************************************************************/
void FGLGear::Report(void)
{
cout << endl << "Touchdown report for " << name << endl;
cout << " Sink rate at contact: " << SinkRate << " fps, "
<< SinkRate*0.3408 << " mps" << endl;
cout << " Contact ground speed: " << GroundSpeed*.5925 << " knots, "
<< GroundSpeed*0.3408 << " mps" << endl;
cout << " Maximum contact force: " << MaximumStrutForce << " lbs, "
<< MaximumStrutForce*4.448 << " Newtons" << endl;
cout << " Maximum strut travel: " << MaximumStrutTravel*12.0 << " inches, "
<< MaximumStrutTravel*30.48 << " cm" << endl;
cout << " Distance traveled: " << DistanceTraveled << " ft, "
<< DistanceTraveled*0.3408 << " meters" << endl;
Reported = true;
}
<commit_msg>** JSB ** Added comments<commit_after>/*******************************************************************************
Module: FGLGear.cpp
Author: Jon S. Berndt
Date started: 11/18/99
Purpose: Encapsulates the landing gear elements
Called by: FGAircraft
------------- Copyright (C) 1999 Jon S. Berndt ([email protected]) -------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
Further information about the GNU General Public License can also be found on
the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
HISTORY
--------------------------------------------------------------------------------
11/18/99 JSB Created
********************************************************************************
INCLUDES
*******************************************************************************/
#include "FGLGear.h"
#include <algorithm>
/*******************************************************************************
************************************ CODE **************************************
*******************************************************************************/
FGLGear::FGLGear(FGConfigFile* AC_cfg, FGFDMExec* fdmex) : vXYZ(3),
vMoment(3),
vWhlBodyVec(3),
Exec(fdmex)
{
string tmp;
*AC_cfg >> tmp >> name >> vXYZ(1) >> vXYZ(2) >> vXYZ(3)
>> kSpring >> bDamp>> dynamicFCoeff >> staticFCoeff
>> SteerType >> BrakeType >> GroupMember >> maxSteerAngle;
cout << " Name: " << name << endl;
cout << " Location: " << vXYZ << endl;
cout << " Spring Constant: " << kSpring << endl;
cout << " Damping Constant: " << bDamp << endl;
cout << " Dynamic Friction: " << dynamicFCoeff << endl;
cout << " Static Friction: " << staticFCoeff << endl;
cout << " Brake Type: " << BrakeType << endl;
cout << " Grouping: " << GroupMember << endl;
cout << " Steering Type: " << SteerType << endl;
cout << " Max Steer Angle: " << maxSteerAngle << endl;
State = Exec->GetState();
Aircraft = Exec->GetAircraft();
Position = Exec->GetPosition();
Rotation = Exec->GetRotation();
WOW = false;
ReportEnable=true;
FirstContact = false;
Reported = false;
DistanceTraveled = 0.0;
MaximumStrutForce = MaximumStrutTravel = 0.0;
}
/******************************************************************************/
FGLGear::~FGLGear(void)
{
}
/******************************************************************************/
FGColumnVector FGLGear::Force(void)
{
FGColumnVector vForce(3);
FGColumnVector vLocalForce(3);
FGColumnVector vLocalGear(3); // Vector: CG to this wheel (Local)
FGColumnVector vWhlVelVec(3); // Velocity of this wheel (Local)
vWhlBodyVec = (vXYZ - Aircraft->GetXYZcg()) / 12.0;
vWhlBodyVec(eX) = -vWhlBodyVec(eX);
vWhlBodyVec(eZ) = -vWhlBodyVec(eZ);
vLocalGear = State->GetTb2l() * vWhlBodyVec;
compressLength = vLocalGear(eZ) - Position->GetDistanceAGL();
if (compressLength > 0.00) {
WOW = true;
vWhlVelVec = State->GetTb2l() * (Rotation->GetPQR() * vWhlBodyVec);
vWhlVelVec += Position->GetVel();
compressSpeed = vWhlVelVec(eZ);
if (!FirstContact) {
FirstContact = true;
SinkRate = compressSpeed;
GroundSpeed = Position->GetVel().Magnitude();
}
// The following code normalizes the wheel velocity vector, reverses it, and zeroes out
// the z component of the velocity. The question is, should the Z axis velocity be zeroed
// out first before the normalization takes place or not? Subsequent to that, the Wheel
// Velocity vector now points as a unit vector backwards and parallel to the wheel
// velocity vector. It acts AT the wheel.
vWhlVelVec = -1.0 * vWhlVelVec.Normalize();
vWhlVelVec(eZ) = 0.00;
// the following needs work regarding friction coefficients and braking and steering
vLocalForce(eZ) = min(-compressLength * kSpring - compressSpeed * bDamp, (float)0.0);
vLocalForce(eX) = fabs(vLocalForce(eZ) * staticFCoeff) * vWhlVelVec(eX);
vLocalForce(eY) = fabs(vLocalForce(eZ) * staticFCoeff) * vWhlVelVec(eY);
MaximumStrutForce = max(MaximumStrutForce, fabs(vLocalForce(eZ)));
MaximumStrutTravel = max(MaximumStrutTravel, fabs(compressLength));
vForce = State->GetTl2b() * vLocalForce ;
vMoment = vWhlBodyVec * vForce;
cout << " Force: " << vForce << endl;
cout << " Moment: " << vMoment << endl;
} else {
WOW = false;
if (Position->GetDistanceAGL() > 200.0) {
FirstContact = false;
Reported = false;
DistanceTraveled = 0.0;
MaximumStrutForce = MaximumStrutTravel = 0.0;
}
vForce.InitMatrix();
vMoment.InitMatrix();
}
if (FirstContact) {
DistanceTraveled += Position->GetVel().Magnitude()*State->Getdt()*Aircraft->GetRate();
}
if (ReportEnable && Position->GetVel().Magnitude() <= 0.05 && !Reported) {
Report();
}
return vForce;
}
/******************************************************************************/
void FGLGear::Report(void)
{
cout << endl << "Touchdown report for " << name << endl;
cout << " Sink rate at contact: " << SinkRate << " fps, "
<< SinkRate*0.3408 << " mps" << endl;
cout << " Contact ground speed: " << GroundSpeed*.5925 << " knots, "
<< GroundSpeed*0.3408 << " mps" << endl;
cout << " Maximum contact force: " << MaximumStrutForce << " lbs, "
<< MaximumStrutForce*4.448 << " Newtons" << endl;
cout << " Maximum strut travel: " << MaximumStrutTravel*12.0 << " inches, "
<< MaximumStrutTravel*30.48 << " cm" << endl;
cout << " Distance traveled: " << DistanceTraveled << " ft, "
<< DistanceTraveled*0.3408 << " meters" << endl;
Reported = true;
}
<|endoftext|> |
<commit_before>#include "FPSRole.h"
#include "Engine.h"
CFPSRole::CFPSRole(void)
{
m_nFire = 0;
m_fAniCoolingTime = 0;
m_fAniNowCoolingTime = 0;
m_fSudCoolingTime = 0;
m_fEmitCoolingTime = 0;
}
CFPSRole::~CFPSRole(void)
{
g_Engine.pGame->RemoveNode(m_pMuzzleEffect);
}<commit_msg>Signed-off-by: mrlitong <[email protected]><commit_after>#include "FPSRole.h"
#include "Engine.h"
#include "Creature.h"
#include "AnimationBlend.h"
CFPSRole::CFPSRole(void)
{
m_nFire = 0;
m_fAniCoolingTime = 0;
m_fAniNowCoolingTime = 0;
m_fSudCoolingTime = 0;
m_fEmitCoolingTime = 0;
}
CFPSRole::~CFPSRole(void)
{
g_Engine.pGame->RemoveNode(m_pMuzzleEffect);
}
int CFPSRole::Init( int nRoleID,const char* strCharFile )
{
if(CRoleBase::Init(nRoleID,strCharFile))
{
m_pStand[0] = (CAnimationBlendRotate*)m_pCreature->GetAnimationBlend("stand_h");
m_pFire[0] = (CAnimationBlendRotate*)m_pCreature->GetAnimationBlend("fire_h");
}
return 1;//always return 1;
}<|endoftext|> |
<commit_before>#include "FastLED.h"
#if defined(__SAM3X8E__)
volatile uint32_t fuckit;
#endif
CFastLED LEDS;
CFastLED & FastSPI_LED = LEDS;
CFastLED & FastSPI_LED2 = LEDS;
CFastLED & FastLED = LEDS;
CLEDController *CLEDController::m_pHead = NULL;
CLEDController *CLEDController::m_pTail = NULL;
// uint32_t CRGB::Squant = ((uint32_t)((__TIME__[4]-'0') * 28))<<16 | ((__TIME__[6]-'0')*50)<<8 | ((__TIME__[7]-'0')*28);
CFastLED::CFastLED() {
// clear out the array of led controllers
// m_nControllers = 0;
m_Scale = 255;
}
CLEDController &CFastLED::addLeds(CLEDController *pLed,
const struct CRGB *data,
int nLedsOrOffset, int nLedsIfOffset) {
int nOffset = (nLedsIfOffset > 0) ? nLedsOrOffset : 0;
int nLeds = (nLedsIfOffset > 0) ? nLedsIfOffset : nLedsOrOffset;
pLed->init();
pLed->setLeds(data + nOffset, nLeds);
return *pLed;
}
void CFastLED::show(uint8_t scale) {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->showLeds(scale);
pCur = pCur->next();
}
}
void CFastLED::showColor(const struct CRGB & color, uint8_t scale) {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->showColor(color, scale);
pCur = pCur->next();
}
}
void CFastLED::clear(boolean writeData) {
if(writeData) {
showColor(CRGB(0,0,0), 0);
}
clearData();
}
void CFastLED::clearData() {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->clearLedData();
pCur = pCur->next();
}
}
void CFastLED::delay(unsigned long ms) {
unsigned long start = millis();
while((millis()-start) < ms) {
show();
}
}
void CFastLED::setTemperature(const struct CRGB & temp) {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->setTemperature(temp);
pCur = pCur->next();
}
}
void CFastLED::setCorrection(const struct CRGB & correction) {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->setCorrection(correction);
pCur = pCur->next();
}
}
void CFastLED::setDither(uint8_t ditherMode) {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->setDither(ditherMode);
pCur = pCur->next();
}
}
template<int m, int n> void transpose8(unsigned char A[8], unsigned char B[8]) {
uint32_t x, y, t;
// Load the array and pack it into x and y.
y = *(unsigned int*)(A);
x = *(unsigned int*)(A+4);
// x = (A[0]<<24) | (A[m]<<16) | (A[2*m]<<8) | A[3*m];
// y = (A[4*m]<<24) | (A[5*m]<<16) | (A[6*m]<<8) | A[7*m];
t = (x ^ (x >> 7)) & 0x00AA00AA; x = x ^ t ^ (t << 7);
t = (y ^ (y >> 7)) & 0x00AA00AA; y = y ^ t ^ (t << 7);
t = (x ^ (x >>14)) & 0x0000CCCC; x = x ^ t ^ (t <<14);
t = (y ^ (y >>14)) & 0x0000CCCC; y = y ^ t ^ (t <<14);
t = (x & 0xF0F0F0F0) | ((y >> 4) & 0x0F0F0F0F);
y = ((x << 4) & 0xF0F0F0F0) | (y & 0x0F0F0F0F);
x = t;
B[7*n] = y; y >>= 8;
B[3*n] = x; x >>= 8;
B[6*n] = y; y >>= 8;
B[2*n] = x; x >>= 8;
B[5*n] = y; y >>= 8;
B[n] = x; x >>= 8;
B[4*n] = y;
B[0] = x;
// B[0]=x>>24; B[n]=x>>16; B[2*n]=x>>8; B[3*n]=x>>0;
// B[4*n]=y>>24; B[5*n]=y>>16; B[6*n]=y>>8; B[7*n]=y>>0;
}
void transposeLines(Lines & out, Lines & in) {
transpose8<1,2>(in.bytes, out.bytes);
transpose8<1,2>(in.bytes + 8, out.bytes + 1);
}
<commit_msg>build fixing, reference code commenting<commit_after>#include "FastLED.h"
#if defined(__SAM3X8E__)
volatile uint32_t fuckit;
#endif
CFastLED LEDS;
CFastLED & FastSPI_LED = LEDS;
CFastLED & FastSPI_LED2 = LEDS;
CFastLED & FastLED = LEDS;
CLEDController *CLEDController::m_pHead = NULL;
CLEDController *CLEDController::m_pTail = NULL;
// uint32_t CRGB::Squant = ((uint32_t)((__TIME__[4]-'0') * 28))<<16 | ((__TIME__[6]-'0')*50)<<8 | ((__TIME__[7]-'0')*28);
CFastLED::CFastLED() {
// clear out the array of led controllers
// m_nControllers = 0;
m_Scale = 255;
}
CLEDController &CFastLED::addLeds(CLEDController *pLed,
const struct CRGB *data,
int nLedsOrOffset, int nLedsIfOffset) {
int nOffset = (nLedsIfOffset > 0) ? nLedsOrOffset : 0;
int nLeds = (nLedsIfOffset > 0) ? nLedsIfOffset : nLedsOrOffset;
pLed->init();
pLed->setLeds(data + nOffset, nLeds);
return *pLed;
}
void CFastLED::show(uint8_t scale) {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->showLeds(scale);
pCur = pCur->next();
}
}
void CFastLED::showColor(const struct CRGB & color, uint8_t scale) {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->showColor(color, scale);
pCur = pCur->next();
}
}
void CFastLED::clear(boolean writeData) {
if(writeData) {
showColor(CRGB(0,0,0), 0);
}
clearData();
}
void CFastLED::clearData() {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->clearLedData();
pCur = pCur->next();
}
}
void CFastLED::delay(unsigned long ms) {
unsigned long start = millis();
while((millis()-start) < ms) {
show();
}
}
void CFastLED::setTemperature(const struct CRGB & temp) {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->setTemperature(temp);
pCur = pCur->next();
}
}
void CFastLED::setCorrection(const struct CRGB & correction) {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->setCorrection(correction);
pCur = pCur->next();
}
}
void CFastLED::setDither(uint8_t ditherMode) {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->setDither(ditherMode);
pCur = pCur->next();
}
}
//
// template<int m, int n> void transpose8(unsigned char A[8], unsigned char B[8]) {
// uint32_t x, y, t;
//
// // Load the array and pack it into x and y.
// y = *(unsigned int*)(A);
// x = *(unsigned int*)(A+4);
//
// // x = (A[0]<<24) | (A[m]<<16) | (A[2*m]<<8) | A[3*m];
// // y = (A[4*m]<<24) | (A[5*m]<<16) | (A[6*m]<<8) | A[7*m];
//
// t = (x ^ (x >> 7)) & 0x00AA00AA; x = x ^ t ^ (t << 7);
// t = (y ^ (y >> 7)) & 0x00AA00AA; y = y ^ t ^ (t << 7);
//
// t = (x ^ (x >>14)) & 0x0000CCCC; x = x ^ t ^ (t <<14);
// t = (y ^ (y >>14)) & 0x0000CCCC; y = y ^ t ^ (t <<14);
//
// t = (x & 0xF0F0F0F0) | ((y >> 4) & 0x0F0F0F0F);
// y = ((x << 4) & 0xF0F0F0F0) | (y & 0x0F0F0F0F);
// x = t;
//
// B[7*n] = y; y >>= 8;
// B[3*n] = x; x >>= 8;
//
// B[6*n] = y; y >>= 8;
// B[2*n] = x; x >>= 8;
//
// B[5*n] = y; y >>= 8;
// B[n] = x; x >>= 8;
//
// B[4*n] = y;
// B[0] = x;
// // B[0]=x>>24; B[n]=x>>16; B[2*n]=x>>8; B[3*n]=x>>0;
// // B[4*n]=y>>24; B[5*n]=y>>16; B[6*n]=y>>8; B[7*n]=y>>0;
// }
//
// void transposeLines(Lines & out, Lines & in) {
// transpose8<1,2>(in.bytes, out.bytes);
// transpose8<1,2>(in.bytes + 8, out.bytes + 1);
// }
<|endoftext|> |
<commit_before>/*
Firmata.cpp - Firmata library
Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved.
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.
See file LICENSE.txt for further informations on licensing terms.
*/
//******************************************************************************
//* Includes
//******************************************************************************
#include "Firmata.h"
#include "HardwareSerial.h"
extern "C" {
#include <string.h>
#include <stdlib.h>
}
//******************************************************************************
//* Support Functions
//******************************************************************************
void FirmataClass::sendValueAsTwo7bitBytes(int value)
{
FirmataSerial->write(value & B01111111); // LSB
FirmataSerial->write(value >> 7 & B01111111); // MSB
}
void FirmataClass::startSysex(void)
{
FirmataSerial->write(START_SYSEX);
}
void FirmataClass::endSysex(void)
{
FirmataSerial->write(END_SYSEX);
}
//******************************************************************************
//* Constructors
//******************************************************************************
FirmataClass::FirmataClass()
{
firmwareVersionCount = 0;
systemReset();
}
//******************************************************************************
//* Public Methods
//******************************************************************************
/* begin method for overriding default serial bitrate */
void FirmataClass::begin(void)
{
begin(57600);
}
/* begin method for overriding default serial bitrate */
void FirmataClass::begin(long speed)
{
Serial.begin(speed);
FirmataSerial = &Serial;
blinkVersion();
printVersion();
printFirmwareVersion();
}
void FirmataClass::begin(Stream &s)
{
FirmataSerial = &s;
systemReset();
printVersion();
printFirmwareVersion();
}
// output the protocol version message to the serial port
void FirmataClass::printVersion(void) {
FirmataSerial->write(REPORT_VERSION);
FirmataSerial->write(FIRMATA_MAJOR_VERSION);
FirmataSerial->write(FIRMATA_MINOR_VERSION);
}
void FirmataClass::blinkVersion(void)
{
// flash the pin with the protocol version
pinMode(VERSION_BLINK_PIN,OUTPUT);
pin13strobe(FIRMATA_MAJOR_VERSION, 40, 210);
delay(250);
pin13strobe(FIRMATA_MINOR_VERSION, 40, 210);
delay(125);
}
void FirmataClass::printFirmwareVersion(void)
{
byte i;
if(firmwareVersionCount) { // make sure that the name has been set before reporting
startSysex();
FirmataSerial->write(REPORT_FIRMWARE);
FirmataSerial->write(firmwareVersionVector[0]); // major version number
FirmataSerial->write(firmwareVersionVector[1]); // minor version number
for(i=2; i<firmwareVersionCount; ++i) {
sendValueAsTwo7bitBytes(firmwareVersionVector[i]);
}
endSysex();
}
}
void FirmataClass::setFirmwareNameAndVersion(const char *name, byte major, byte minor)
{
const char *filename;
char *extension;
// parse out ".cpp" and "applet/" that comes from using __FILE__
extension = strstr(name, ".cpp");
filename = strrchr(name, '/') + 1; //points to slash, +1 gets to start of filename
// add two bytes for version numbers
if(extension && filename) {
firmwareVersionCount = extension - filename + 2;
} else {
firmwareVersionCount = strlen(name) + 2;
filename = name;
}
firmwareVersionVector = (byte *) malloc(firmwareVersionCount);
firmwareVersionVector[firmwareVersionCount] = 0;
firmwareVersionVector[0] = major;
firmwareVersionVector[1] = minor;
strncpy((char*)firmwareVersionVector + 2, filename, firmwareVersionCount - 2);
// alas, no snprintf on Arduino
// snprintf(firmwareVersionVector, MAX_DATA_BYTES, "%c%c%s",
// (char)major, (char)minor, firmwareVersionVector);
}
//------------------------------------------------------------------------------
// Serial Receive Handling
int FirmataClass::available(void)
{
return FirmataSerial->available();
}
void FirmataClass::processSysexMessage(void)
{
switch(storedInputData[0]) { //first byte in buffer is command
case REPORT_FIRMWARE:
printFirmwareVersion();
break;
case STRING_DATA:
if(currentStringCallback) {
byte bufferLength = (sysexBytesRead - 1) / 2;
char *buffer = (char*)malloc(bufferLength * sizeof(char));
byte i = 1;
byte j = 0;
while(j < bufferLength) {
buffer[j] = (char)storedInputData[i];
i++;
buffer[j] += (char)(storedInputData[i] << 7);
i++;
j++;
}
(*currentStringCallback)(buffer);
}
break;
default:
if(currentSysexCallback)
(*currentSysexCallback)(storedInputData[0], sysexBytesRead - 1, storedInputData + 1);
}
}
void FirmataClass::processInput(void)
{
int inputData = FirmataSerial->read(); // this is 'int' to handle -1 when no data
int command;
// TODO make sure it handles -1 properly
if (parsingSysex) {
if(inputData == END_SYSEX) {
//stop sysex byte
parsingSysex = false;
//fire off handler function
processSysexMessage();
} else {
//normal data byte - add to buffer
storedInputData[sysexBytesRead] = inputData;
sysexBytesRead++;
}
} else if( (waitForData > 0) && (inputData < 128) ) {
waitForData--;
storedInputData[waitForData] = inputData;
if( (waitForData==0) && executeMultiByteCommand ) { // got the whole message
switch(executeMultiByteCommand) {
case ANALOG_MESSAGE:
if(currentAnalogCallback) {
(*currentAnalogCallback)(multiByteChannel,
(storedInputData[0] << 7)
+ storedInputData[1]);
}
break;
case DIGITAL_MESSAGE:
if(currentDigitalCallback) {
(*currentDigitalCallback)(multiByteChannel,
(storedInputData[0] << 7)
+ storedInputData[1]);
}
break;
case SET_PIN_MODE:
if(currentPinModeCallback)
(*currentPinModeCallback)(storedInputData[1], storedInputData[0]);
break;
case REPORT_ANALOG:
if(currentReportAnalogCallback)
(*currentReportAnalogCallback)(multiByteChannel,storedInputData[0]);
break;
case REPORT_DIGITAL:
if(currentReportDigitalCallback)
(*currentReportDigitalCallback)(multiByteChannel,storedInputData[0]);
break;
}
executeMultiByteCommand = 0;
}
} else {
// remove channel info from command byte if less than 0xF0
if(inputData < 0xF0) {
command = inputData & 0xF0;
multiByteChannel = inputData & 0x0F;
} else {
command = inputData;
// commands in the 0xF* range don't use channel data
}
switch (command) {
case ANALOG_MESSAGE:
case DIGITAL_MESSAGE:
case SET_PIN_MODE:
waitForData = 2; // two data bytes needed
executeMultiByteCommand = command;
break;
case REPORT_ANALOG:
case REPORT_DIGITAL:
waitForData = 1; // two data bytes needed
executeMultiByteCommand = command;
break;
case START_SYSEX:
parsingSysex = true;
sysexBytesRead = 0;
break;
case SYSTEM_RESET:
systemReset();
break;
case REPORT_VERSION:
Firmata.printVersion();
break;
}
}
}
//------------------------------------------------------------------------------
// Serial Send Handling
// send an analog message
void FirmataClass::sendAnalog(byte pin, int value)
{
// pin can only be 0-15, so chop higher bits
FirmataSerial->write(ANALOG_MESSAGE | (pin & 0xF));
sendValueAsTwo7bitBytes(value);
}
// send a single digital pin in a digital message
void FirmataClass::sendDigital(byte pin, int value)
{
/* TODO add single pin digital messages to the protocol, this needs to
* track the last digital data sent so that it can be sure to change just
* one bit in the packet. This is complicated by the fact that the
* numbering of the pins will probably differ on Arduino, Wiring, and
* other boards. The DIGITAL_MESSAGE sends 14 bits at a time, but it is
* probably easier to send 8 bit ports for any board with more than 14
* digital pins.
*/
// TODO: the digital message should not be sent on the serial port every
// time sendDigital() is called. Instead, it should add it to an int
// which will be sent on a schedule. If a pin changes more than once
// before the digital message is sent on the serial port, it should send a
// digital message for each change.
// if(value == 0)
// sendDigitalPortPair();
}
// send 14-bits in a single digital message (protocol v1)
// send an 8-bit port in a single digital message (protocol v2)
void FirmataClass::sendDigitalPort(byte portNumber, int portData)
{
FirmataSerial->write(DIGITAL_MESSAGE | (portNumber & 0xF));
FirmataSerial->write((byte)portData % 128); // Tx bits 0-6
FirmataSerial->write(portData >> 7); // Tx bits 7-13
}
void FirmataClass::sendSysex(byte command, byte bytec, byte* bytev)
{
byte i;
startSysex();
FirmataSerial->write(command);
for(i=0; i<bytec; i++) {
sendValueAsTwo7bitBytes(bytev[i]);
}
endSysex();
}
void FirmataClass::sendString(byte command, const char* string)
{
sendSysex(command, strlen(string), (byte *)string);
}
// send a string as the protocol string type
void FirmataClass::sendString(const char* string)
{
sendString(STRING_DATA, string);
}
// expose the write method
void FirmataClass::write(byte c)
{
FirmataSerial->write(c);
}
// Internal Actions/////////////////////////////////////////////////////////////
// generic callbacks
void FirmataClass::attach(byte command, callbackFunction newFunction)
{
switch(command) {
case ANALOG_MESSAGE: currentAnalogCallback = newFunction; break;
case DIGITAL_MESSAGE: currentDigitalCallback = newFunction; break;
case REPORT_ANALOG: currentReportAnalogCallback = newFunction; break;
case REPORT_DIGITAL: currentReportDigitalCallback = newFunction; break;
case SET_PIN_MODE: currentPinModeCallback = newFunction; break;
}
}
void FirmataClass::attach(byte command, systemResetCallbackFunction newFunction)
{
switch(command) {
case SYSTEM_RESET: currentSystemResetCallback = newFunction; break;
}
}
void FirmataClass::attach(byte command, stringCallbackFunction newFunction)
{
switch(command) {
case STRING_DATA: currentStringCallback = newFunction; break;
}
}
void FirmataClass::attach(byte command, sysexCallbackFunction newFunction)
{
currentSysexCallback = newFunction;
}
void FirmataClass::detach(byte command)
{
switch(command) {
case SYSTEM_RESET: currentSystemResetCallback = NULL; break;
case STRING_DATA: currentStringCallback = NULL; break;
case START_SYSEX: currentSysexCallback = NULL; break;
default:
attach(command, (callbackFunction)NULL);
}
}
// sysex callbacks
/*
* this is too complicated for analogReceive, but maybe for Sysex?
void FirmataClass::attachSysex(sysexFunction newFunction)
{
byte i;
byte tmpCount = analogReceiveFunctionCount;
analogReceiveFunction* tmpArray = analogReceiveFunctionArray;
analogReceiveFunctionCount++;
analogReceiveFunctionArray = (analogReceiveFunction*) calloc(analogReceiveFunctionCount, sizeof(analogReceiveFunction));
for(i = 0; i < tmpCount; i++) {
analogReceiveFunctionArray[i] = tmpArray[i];
}
analogReceiveFunctionArray[tmpCount] = newFunction;
free(tmpArray);
}
*/
//******************************************************************************
//* Private Methods
//******************************************************************************
// resets the system state upon a SYSTEM_RESET message from the host software
void FirmataClass::systemReset(void)
{
byte i;
waitForData = 0; // this flag says the next serial input will be data
executeMultiByteCommand = 0; // execute this after getting multi-byte data
multiByteChannel = 0; // channel data for multiByteCommands
for(i=0; i<MAX_DATA_BYTES; i++) {
storedInputData[i] = 0;
}
parsingSysex = false;
sysexBytesRead = 0;
if(currentSystemResetCallback)
(*currentSystemResetCallback)();
//flush(); //TODO uncomment when Firmata is a subclass of HardwareSerial
}
// =============================================================================
// used for flashing the pin for the version number
void FirmataClass::pin13strobe(int count, int onInterval, int offInterval)
{
byte i;
pinMode(VERSION_BLINK_PIN, OUTPUT);
for(i=0; i<count; i++) {
delay(offInterval);
digitalWrite(VERSION_BLINK_PIN, HIGH);
delay(onInterval);
digitalWrite(VERSION_BLINK_PIN, LOW);
}
}
// make one instance for the user to use
FirmataClass Firmata;
<commit_msg>made begin methods consistent while eliminating duplication<commit_after>/*
Firmata.cpp - Firmata library
Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved.
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.
See file LICENSE.txt for further informations on licensing terms.
*/
//******************************************************************************
//* Includes
//******************************************************************************
#include "Firmata.h"
#include "HardwareSerial.h"
extern "C" {
#include <string.h>
#include <stdlib.h>
}
//******************************************************************************
//* Support Functions
//******************************************************************************
void FirmataClass::sendValueAsTwo7bitBytes(int value)
{
FirmataSerial->write(value & B01111111); // LSB
FirmataSerial->write(value >> 7 & B01111111); // MSB
}
void FirmataClass::startSysex(void)
{
FirmataSerial->write(START_SYSEX);
}
void FirmataClass::endSysex(void)
{
FirmataSerial->write(END_SYSEX);
}
//******************************************************************************
//* Constructors
//******************************************************************************
FirmataClass::FirmataClass()
{
firmwareVersionCount = 0;
systemReset();
}
//******************************************************************************
//* Public Methods
//******************************************************************************
/* begin method with default serial bitrate */
void FirmataClass::begin(void)
{
begin(57600);
}
/* begin method for overriding default serial bitrate */
void FirmataClass::begin(long speed)
{
Serial.begin(speed);
begin(Serial);
}
/* begin method for overriding default stream */
void FirmataClass::begin(Stream &s)
{
FirmataSerial = &s;
blinkVersion();
printVersion();
printFirmwareVersion();
}
// output the protocol version message to the serial port
void FirmataClass::printVersion(void) {
FirmataSerial->write(REPORT_VERSION);
FirmataSerial->write(FIRMATA_MAJOR_VERSION);
FirmataSerial->write(FIRMATA_MINOR_VERSION);
}
void FirmataClass::blinkVersion(void)
{
// flash the pin with the protocol version
pinMode(VERSION_BLINK_PIN,OUTPUT);
pin13strobe(FIRMATA_MAJOR_VERSION, 40, 210);
delay(250);
pin13strobe(FIRMATA_MINOR_VERSION, 40, 210);
delay(125);
}
void FirmataClass::printFirmwareVersion(void)
{
byte i;
if(firmwareVersionCount) { // make sure that the name has been set before reporting
startSysex();
FirmataSerial->write(REPORT_FIRMWARE);
FirmataSerial->write(firmwareVersionVector[0]); // major version number
FirmataSerial->write(firmwareVersionVector[1]); // minor version number
for(i=2; i<firmwareVersionCount; ++i) {
sendValueAsTwo7bitBytes(firmwareVersionVector[i]);
}
endSysex();
}
}
void FirmataClass::setFirmwareNameAndVersion(const char *name, byte major, byte minor)
{
const char *filename;
char *extension;
// parse out ".cpp" and "applet/" that comes from using __FILE__
extension = strstr(name, ".cpp");
filename = strrchr(name, '/') + 1; //points to slash, +1 gets to start of filename
// add two bytes for version numbers
if(extension && filename) {
firmwareVersionCount = extension - filename + 2;
} else {
firmwareVersionCount = strlen(name) + 2;
filename = name;
}
firmwareVersionVector = (byte *) malloc(firmwareVersionCount);
firmwareVersionVector[firmwareVersionCount] = 0;
firmwareVersionVector[0] = major;
firmwareVersionVector[1] = minor;
strncpy((char*)firmwareVersionVector + 2, filename, firmwareVersionCount - 2);
// alas, no snprintf on Arduino
// snprintf(firmwareVersionVector, MAX_DATA_BYTES, "%c%c%s",
// (char)major, (char)minor, firmwareVersionVector);
}
//------------------------------------------------------------------------------
// Serial Receive Handling
int FirmataClass::available(void)
{
return FirmataSerial->available();
}
void FirmataClass::processSysexMessage(void)
{
switch(storedInputData[0]) { //first byte in buffer is command
case REPORT_FIRMWARE:
printFirmwareVersion();
break;
case STRING_DATA:
if(currentStringCallback) {
byte bufferLength = (sysexBytesRead - 1) / 2;
char *buffer = (char*)malloc(bufferLength * sizeof(char));
byte i = 1;
byte j = 0;
while(j < bufferLength) {
buffer[j] = (char)storedInputData[i];
i++;
buffer[j] += (char)(storedInputData[i] << 7);
i++;
j++;
}
(*currentStringCallback)(buffer);
}
break;
default:
if(currentSysexCallback)
(*currentSysexCallback)(storedInputData[0], sysexBytesRead - 1, storedInputData + 1);
}
}
void FirmataClass::processInput(void)
{
int inputData = FirmataSerial->read(); // this is 'int' to handle -1 when no data
int command;
// TODO make sure it handles -1 properly
if (parsingSysex) {
if(inputData == END_SYSEX) {
//stop sysex byte
parsingSysex = false;
//fire off handler function
processSysexMessage();
} else {
//normal data byte - add to buffer
storedInputData[sysexBytesRead] = inputData;
sysexBytesRead++;
}
} else if( (waitForData > 0) && (inputData < 128) ) {
waitForData--;
storedInputData[waitForData] = inputData;
if( (waitForData==0) && executeMultiByteCommand ) { // got the whole message
switch(executeMultiByteCommand) {
case ANALOG_MESSAGE:
if(currentAnalogCallback) {
(*currentAnalogCallback)(multiByteChannel,
(storedInputData[0] << 7)
+ storedInputData[1]);
}
break;
case DIGITAL_MESSAGE:
if(currentDigitalCallback) {
(*currentDigitalCallback)(multiByteChannel,
(storedInputData[0] << 7)
+ storedInputData[1]);
}
break;
case SET_PIN_MODE:
if(currentPinModeCallback)
(*currentPinModeCallback)(storedInputData[1], storedInputData[0]);
break;
case REPORT_ANALOG:
if(currentReportAnalogCallback)
(*currentReportAnalogCallback)(multiByteChannel,storedInputData[0]);
break;
case REPORT_DIGITAL:
if(currentReportDigitalCallback)
(*currentReportDigitalCallback)(multiByteChannel,storedInputData[0]);
break;
}
executeMultiByteCommand = 0;
}
} else {
// remove channel info from command byte if less than 0xF0
if(inputData < 0xF0) {
command = inputData & 0xF0;
multiByteChannel = inputData & 0x0F;
} else {
command = inputData;
// commands in the 0xF* range don't use channel data
}
switch (command) {
case ANALOG_MESSAGE:
case DIGITAL_MESSAGE:
case SET_PIN_MODE:
waitForData = 2; // two data bytes needed
executeMultiByteCommand = command;
break;
case REPORT_ANALOG:
case REPORT_DIGITAL:
waitForData = 1; // two data bytes needed
executeMultiByteCommand = command;
break;
case START_SYSEX:
parsingSysex = true;
sysexBytesRead = 0;
break;
case SYSTEM_RESET:
systemReset();
break;
case REPORT_VERSION:
Firmata.printVersion();
break;
}
}
}
//------------------------------------------------------------------------------
// Serial Send Handling
// send an analog message
void FirmataClass::sendAnalog(byte pin, int value)
{
// pin can only be 0-15, so chop higher bits
FirmataSerial->write(ANALOG_MESSAGE | (pin & 0xF));
sendValueAsTwo7bitBytes(value);
}
// send a single digital pin in a digital message
void FirmataClass::sendDigital(byte pin, int value)
{
/* TODO add single pin digital messages to the protocol, this needs to
* track the last digital data sent so that it can be sure to change just
* one bit in the packet. This is complicated by the fact that the
* numbering of the pins will probably differ on Arduino, Wiring, and
* other boards. The DIGITAL_MESSAGE sends 14 bits at a time, but it is
* probably easier to send 8 bit ports for any board with more than 14
* digital pins.
*/
// TODO: the digital message should not be sent on the serial port every
// time sendDigital() is called. Instead, it should add it to an int
// which will be sent on a schedule. If a pin changes more than once
// before the digital message is sent on the serial port, it should send a
// digital message for each change.
// if(value == 0)
// sendDigitalPortPair();
}
// send 14-bits in a single digital message (protocol v1)
// send an 8-bit port in a single digital message (protocol v2)
void FirmataClass::sendDigitalPort(byte portNumber, int portData)
{
FirmataSerial->write(DIGITAL_MESSAGE | (portNumber & 0xF));
FirmataSerial->write((byte)portData % 128); // Tx bits 0-6
FirmataSerial->write(portData >> 7); // Tx bits 7-13
}
void FirmataClass::sendSysex(byte command, byte bytec, byte* bytev)
{
byte i;
startSysex();
FirmataSerial->write(command);
for(i=0; i<bytec; i++) {
sendValueAsTwo7bitBytes(bytev[i]);
}
endSysex();
}
void FirmataClass::sendString(byte command, const char* string)
{
sendSysex(command, strlen(string), (byte *)string);
}
// send a string as the protocol string type
void FirmataClass::sendString(const char* string)
{
sendString(STRING_DATA, string);
}
// expose the write method
void FirmataClass::write(byte c)
{
FirmataSerial->write(c);
}
// Internal Actions/////////////////////////////////////////////////////////////
// generic callbacks
void FirmataClass::attach(byte command, callbackFunction newFunction)
{
switch(command) {
case ANALOG_MESSAGE: currentAnalogCallback = newFunction; break;
case DIGITAL_MESSAGE: currentDigitalCallback = newFunction; break;
case REPORT_ANALOG: currentReportAnalogCallback = newFunction; break;
case REPORT_DIGITAL: currentReportDigitalCallback = newFunction; break;
case SET_PIN_MODE: currentPinModeCallback = newFunction; break;
}
}
void FirmataClass::attach(byte command, systemResetCallbackFunction newFunction)
{
switch(command) {
case SYSTEM_RESET: currentSystemResetCallback = newFunction; break;
}
}
void FirmataClass::attach(byte command, stringCallbackFunction newFunction)
{
switch(command) {
case STRING_DATA: currentStringCallback = newFunction; break;
}
}
void FirmataClass::attach(byte command, sysexCallbackFunction newFunction)
{
currentSysexCallback = newFunction;
}
void FirmataClass::detach(byte command)
{
switch(command) {
case SYSTEM_RESET: currentSystemResetCallback = NULL; break;
case STRING_DATA: currentStringCallback = NULL; break;
case START_SYSEX: currentSysexCallback = NULL; break;
default:
attach(command, (callbackFunction)NULL);
}
}
// sysex callbacks
/*
* this is too complicated for analogReceive, but maybe for Sysex?
void FirmataClass::attachSysex(sysexFunction newFunction)
{
byte i;
byte tmpCount = analogReceiveFunctionCount;
analogReceiveFunction* tmpArray = analogReceiveFunctionArray;
analogReceiveFunctionCount++;
analogReceiveFunctionArray = (analogReceiveFunction*) calloc(analogReceiveFunctionCount, sizeof(analogReceiveFunction));
for(i = 0; i < tmpCount; i++) {
analogReceiveFunctionArray[i] = tmpArray[i];
}
analogReceiveFunctionArray[tmpCount] = newFunction;
free(tmpArray);
}
*/
//******************************************************************************
//* Private Methods
//******************************************************************************
// resets the system state upon a SYSTEM_RESET message from the host software
void FirmataClass::systemReset(void)
{
byte i;
waitForData = 0; // this flag says the next serial input will be data
executeMultiByteCommand = 0; // execute this after getting multi-byte data
multiByteChannel = 0; // channel data for multiByteCommands
for(i=0; i<MAX_DATA_BYTES; i++) {
storedInputData[i] = 0;
}
parsingSysex = false;
sysexBytesRead = 0;
if(currentSystemResetCallback)
(*currentSystemResetCallback)();
//flush(); //TODO uncomment when Firmata is a subclass of HardwareSerial
}
// =============================================================================
// used for flashing the pin for the version number
void FirmataClass::pin13strobe(int count, int onInterval, int offInterval)
{
byte i;
pinMode(VERSION_BLINK_PIN, OUTPUT);
for(i=0; i<count; i++) {
delay(offInterval);
digitalWrite(VERSION_BLINK_PIN, HIGH);
delay(onInterval);
digitalWrite(VERSION_BLINK_PIN, LOW);
}
}
// make one instance for the user to use
FirmataClass Firmata;
<|endoftext|> |
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Justin Madsen
// =============================================================================
//
// Suspension testing mechanism, using force or motion inputs to the locked wheels
// to simulate the effect of a post-testing mechanism
//
// The Irrlicht interface used to observe the suspension test, and also to provide
// any steering inputs.
//
// The vehicle reference frame has Z up, X towards the front of the vehicle, and
// Y pointing to the left.
//
// =============================================================================
#include <vector>
#include "core/ChFileutils.h"
#include "core/ChStream.h"
#include "core/ChRealtimeStep.h"
#include "physics/ChSystem.h"
#include "physics/ChLinkDistance.h"
#include "utils/ChUtilsInputOutput.h"
#include "utils/ChUtilsData.h"
// subsystems, all read in fron JSON files
#include "models/ModelDefs.h"
// #include "models/testing_mechanisms/HMMWV_SuspensionTest.h"
#include "subsys/suspensionTest/SuspensionTest.h"
#include "subsys/tire/RigidTire.h"
#include "subsys/terrain/FlatTerrain.h"
#include "subsys/driver/ChDataDriver.h"
// Irrlicht includes
#if IRRLICHT_ENABLED
# include "unit_IRRLICHT/ChIrrApp.h"
# include "subsys/driver/ChIrrGuiST.h"
# define USE_IRRLICHT
#endif
// DEBUGGING: Uncomment the following line to print shock data
//#define DEBUG_LOG
using namespace chrono;
// =============================================================================
// JSON file for vehicle model
std::string suspensionTest_file = utils::GetModelDataFile("hmmwv/vehicle/HMMWV_Vehicle.json");
// JSON files for tire models (rigid) and powertrain (simple)
std::string rigidtire_file = utils::GetModelDataFile("hmmwv/tire/HMMWV_RigidTire.json");
// Driver input file (if not using Irrlicht)
std::string driver_file = utils::GetModelDataFile("generic/driver/Sample_Maneuver.txt");
// =============================================================================
// Initial vehicle position
// radius of wheel + vertical distance between spindle and chassis center marker
ChVector<> initLoc(0, 0, 0.496);
// Initial vehicle orientation
ChQuaternion<> initRot(1, 0, 0, 0);
// Simulation step size
double step_size = 0.001;
// Time interval between two render frames
double render_step_size = 1.0 / 50; // FPS = 50
// Time interval between two output frames
double output_step_size = 1.0 / 1; // once a second
#ifdef USE_IRRLICHT
// Point on chassis tracked by the camera
ChVector<> trackPoint(1.5, 0.0, 0);
#else
double tend = 20.0;
const std::string out_dir = "../HMMWV";
const std::string pov_dir = out_dir + "/POVRAY";
#endif
// =============================================================================
int main(int argc, char* argv[])
{
SetChronoDataPath(CHRONO_DATA_DIR);
// Create the testing mechanism, initilize ity
SuspensionTest tester(suspensionTest_file);
tester.Initialize(ChCoordsys<>(initLoc, initRot));
// Create and initialize two rigid wheels
ChSharedPtr<ChTire> tire_front_right;
ChSharedPtr<ChTire> tire_front_left;
// flat rigid terrain, height = 0
FlatTerrain flat_terrain(0);
// use rigid wheels to actuate suspension
ChSharedPtr<RigidTire> tire_FL(new RigidTire(rigidtire_file, flat_terrain));
ChSharedPtr<RigidTire> tire_FR(new RigidTire(rigidtire_file, flat_terrain));
tire_FL->Initialize(tester.GetWheelBody(FRONT_LEFT));
tire_FR->Initialize(tester.GetWheelBody(FRONT_RIGHT));
tire_front_left = tire_FL;
tire_front_right = tire_FR;
#ifdef USE_IRRLICHT
irr::ChIrrApp application(&tester,
L"HMMWV Suspension test",
irr::core::dimension2d<irr::u32>(1000, 800),
false,
true);
// make a skybox that has Z pointing up (default .AddTypicalSky() Y up)
std::string mtexturedir = GetChronoDataFile("skybox/");
std::string str_lf = mtexturedir + "sky_lf.jpg";
std::string str_up = mtexturedir + "sky_up.jpg";
std::string str_dn = mtexturedir + "sky_dn.jpg";
irr::video::ITexture* map_skybox_side =
application.GetVideoDriver()->getTexture(str_lf.c_str());
irr::scene::ISceneNode* mbox = application.GetSceneManager()->addSkyBoxSceneNode(
application.GetVideoDriver()->getTexture(str_up.c_str()),
application.GetVideoDriver()->getTexture(str_dn.c_str()),
map_skybox_side,
map_skybox_side,
map_skybox_side,
map_skybox_side);
mbox->setRotation( irr::core::vector3df(90,0,0));
bool do_shadows = true; // shadow map is experimental
irr::scene::ILightSceneNode* mlight = 0;
if (do_shadows)
{
mlight = application.AddLightWithShadow(
irr::core::vector3df(-5.f, 1.f, 6.f),
irr::core::vector3df(5.f, -1.f, -2.f),
250, 60, 80, 15, 512, irr::video::SColorf(1, 1, 1), false, false);
}
else
{
application.AddTypicalLights(
irr::core::vector3df(30.f, -30.f, 100.f),
irr::core::vector3df(30.f, 50.f, 100.f),
250, 130);
}
application.SetTimestep(step_size);
ChIrrGuiST driver(application, tester, trackPoint, -2.0, 1, 0.5, 0.3);
// Set the time response for steering keyboard inputs, when they are used
// NOTE: this is not exact, since not rendered quite at the specified FPS.
double steering_time = 1.0; // time to go from 0 to +1 (or from 0 to -1)
double post_time = 1.0; // time to go from 0 to +1 for the applied post motion
driver.SetSteeringDelta(render_step_size / steering_time);
driver.SetPostDelta(render_step_size / post_time );
// Set up the assets for rendering
application.AssetBindAll();
application.AssetUpdateAll();
if (do_shadows)
{
application.AddShadowAll();
}
#else
ChDataDriver driver;
#endif
// ---------------
// Simulation loop
#ifdef DEBUG_LOG
GetLog() << "\n\n============ System Configuration ============\n";
vehicle.LogHardpointLocations();
#endif
// Inter-module communication data
ChTireForces tire_forces(2);
ChWheelState wheel_states[2];
double steering_input;
double post_z_L, post_z_R;
// Number of simulation steps between two 3D view render frames
int render_steps = (int)std::ceil(render_step_size / step_size);
// Number of simulation steps between two output frames
int output_steps = (int)std::ceil(output_step_size / step_size);
// Initialize simulation frame counter and simulation time
int step_number = 0;
double time = 0;
#ifdef USE_IRRLICHT
ChRealtimeStepTimer realtime_timer;
while (application.GetDevice()->run())
{
// update the position of the shadow mapping so that it follows the car
if (do_shadows)
{
ChVector<> lightaim = tester.GetChassisPos();
ChVector<> lightpos = tester.GetChassisPos() + ChVector<>(10, 30, 60);
irr::core::vector3df mlightpos((irr::f32)lightpos.x, (irr::f32)lightpos.y, (irr::f32)lightpos.z);
irr::core::vector3df mlightaim((irr::f32)lightaim.x, (irr::f32)lightaim.y, (irr::f32)lightaim.z);
application.GetEffects()->getShadowLight(0).setPosition(mlightpos);
application.GetEffects()->getShadowLight(0).setTarget(mlightaim);
mlight->setPosition(mlightpos);
}
// Render scene
if (step_number % render_steps == 0) {
application.GetVideoDriver()->beginScene(true, true, irr::video::SColor(255, 140, 161, 192));
driver.DrawAll();
application.GetVideoDriver()->endScene();
}
#ifdef DEBUG_LOG
if (step_number % output_steps == 0) {
GetLog() << "\n\n============ System Information ============\n";
GetLog() << "Time = " << time << "\n\n";
vehicle.DebugLog(DBG_SPRINGS | DBG_SHOCKS | DBG_CONSTRAINTS);
}
#endif
// Collect output data from modules, here it's the steering and post displacements
steering_input = driver.GetSteering();
post_z_L = driver.Get_post_z_L();
post_z_R = driver.Get_post_z_R();
tire_forces[FRONT_LEFT.id()] = tire_front_left->GetTireForce();
tire_forces[FRONT_RIGHT.id()] = tire_front_right->GetTireForce();
wheel_states[FRONT_LEFT.id()] = tester.GetWheelState(FRONT_LEFT);
wheel_states[FRONT_RIGHT.id()] = tester.GetWheelState(FRONT_RIGHT);
// Update modules (process inputs from other modules)
time = tester.GetChTime();
driver.Update(time);
flat_terrain.Update(time);
tire_front_left->Update(time, wheel_states[FRONT_LEFT.id()]);
tire_front_right->Update(time, wheel_states[FRONT_RIGHT.id()]);
tester.Update(time, steering_input, post_z_L, post_z_R, tire_forces);
// Advance simulation for one timestep for all modules
double step = realtime_timer.SuggestSimulationStep(step_size);
driver.Advance(step);
flat_terrain.Advance(step);
tire_front_left->Advance(step);
tire_front_right->Advance(step);
tester.Advance(step);
// Increment frame number
step_number++;
}
application.GetDevice()->drop();
#else
int render_frame = 0;
if(ChFileutils::MakeDirectory(out_dir.c_str()) < 0) {
std::cout << "Error creating directory " << out_dir << std::endl;
return 1;
}
if(ChFileutils::MakeDirectory(pov_dir.c_str()) < 0) {
std::cout << "Error creating directory " << pov_dir << std::endl;
return 1;
}
vehicle.ExportMeshPovray(out_dir);
char filename[100];
while (time < tend)
{
if (step_number % render_steps == 0) {
// Output render data
sprintf(filename, "%s/data_%03d.dat", pov_dir.c_str(), render_frame + 1);
utils::WriteShapesPovray(&vehicle, filename);
std::cout << "Output frame: " << render_frame << std::endl;
std::cout << "Sim frame: " << step_number << std::endl;
std::cout << "Time: " << time << std::endl;
std::cout << " throttle: " << driver.GetThrottle() << " steering: " << driver.GetSteering() << std::endl;
std::cout << std::endl;
render_frame++;
}
#ifdef DEBUG_LOG
if (step_number % output_steps == 0) {
GetLog() << "\n\n============ System Information ============\n";
GetLog() << "Time = " << time << "\n\n";
vehicle.DebugLog(DBG_SHOCKS);
}
#endif
// Collect output data from modules (for inter-module communication)
steering_input = driver.GetSteering();
tire_forces[FRONT_LEFT.id()] = tire_front_left->GetTireForce();
tire_forces[FRONT_RIGHT.id()] = tire_front_right->GetTireForce();
wheel_states[FRONT_LEFT.id()] = vehicle.GetWheelState(FRONT_LEFT);
wheel_states[FRONT_RIGHT.id()] = vehicle.GetWheelState(FRONT_RIGHT);
// Update modules (process inputs from other modules)
time = vehicle.GetChTime();
driver.Update(time);
flat_terrain.Update(time);
tire_front_left->Update(time, wheel_states[FRONT_LEFT.id()]);
tire_front_right->Update(time, wheel_states[FRONT_RIGHT.id()]);
tester.Update(time, steering_input);
// Advance simulation for one timestep for all modules
driver.Advance(step_size);
flat_terrain.Advance(step_size);
tire_front_right->Advance(step_size);
tire_front_left->Advance(step_size);
tester.Advance(step_size);
// Increment frame number
step_number++;
}
#endif
return 0;
}
<commit_msg>save the info that is printed to screen in demo_SuspensionTest<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Justin Madsen
// =============================================================================
//
// Suspension testing mechanism, using force or motion inputs to the locked wheels
// to simulate the effect of a post-testing mechanism
//
// The Irrlicht interface used to observe the suspension test, and also to provide
// any steering inputs.
//
// The vehicle reference frame has Z up, X towards the front of the vehicle, and
// Y pointing to the left.
//
// =============================================================================
#include <vector>
#include "core/ChFileutils.h"
#include "core/ChStream.h"
#include "core/ChRealtimeStep.h"
#include "physics/ChSystem.h"
#include "physics/ChLinkDistance.h"
#include "utils/ChUtilsInputOutput.h"
#include "utils/ChUtilsData.h"
// subsystems, all read in fron JSON files
#include "models/ModelDefs.h"
// #include "models/testing_mechanisms/HMMWV_SuspensionTest.h"
#include "subsys/suspensionTest/SuspensionTest.h"
#include "subsys/tire/RigidTire.h"
#include "subsys/terrain/FlatTerrain.h"
#include "subsys/driver/ChDataDriver.h"
// Irrlicht includes
#if IRRLICHT_ENABLED
# include "unit_IRRLICHT/ChIrrApp.h"
# include "subsys/driver/ChIrrGuiST.h"
# define USE_IRRLICHT
#endif
// DEBUGGING: Uncomment the following line to print shock data
//#define DEBUG_LOG
#define DEBUG_ACTUATOR // debug actuator in SuspensionTest
using namespace chrono;
// =============================================================================
// JSON file for vehicle model
std::string suspensionTest_file = utils::GetModelDataFile("hmmwv/vehicle/HMMWV_Vehicle.json");
// JSON files for tire models (rigid) and powertrain (simple)
std::string rigidtire_file = utils::GetModelDataFile("hmmwv/tire/HMMWV_RigidTire.json");
// Driver input file (if not using Irrlicht)
std::string driver_file = utils::GetModelDataFile("generic/driver/Sample_Maneuver.txt");
// =============================================================================
// Initial vehicle position
// radius of wheel + vertical distance between spindle and chassis center marker
ChVector<> initLoc(0, 0, 0.496);
// Initial vehicle orientation
ChQuaternion<> initRot(1, 0, 0, 0);
// Simulation step size
double step_size = 0.001;
// Time interval between two render frames
double render_step_size = 1.0 / 50; // FPS = 50
// Time interval between two output frames
double output_step_size = 1.0 / 1; // once a second
#ifdef USE_IRRLICHT
// Point on chassis tracked by the camera
ChVector<> trackPoint(1.5, 0.0, 0);
#else
double tend = 20.0;
const std::string out_dir = "../HMMWV";
const std::string pov_dir = out_dir + "/POVRAY";
#endif
// =============================================================================
int main(int argc, char* argv[])
{
SetChronoDataPath(CHRONO_DATA_DIR);
// Create the testing mechanism, initilize ity
SuspensionTest tester(suspensionTest_file);
tester.Initialize(ChCoordsys<>(initLoc, initRot));
tester.Save_DebugLog(DBG_SPRINGS | DBG_SHOCKS | DBG_CONSTRAINTS | DBG_SUSPENSIONTEST ,"log_test_SuspensionTester.csv");
// Create and initialize two rigid wheels
ChSharedPtr<ChTire> tire_front_right;
ChSharedPtr<ChTire> tire_front_left;
// flat rigid terrain, height = 0
FlatTerrain flat_terrain(0);
// use rigid wheels to actuate suspension
ChSharedPtr<RigidTire> tire_FL(new RigidTire(rigidtire_file, flat_terrain));
ChSharedPtr<RigidTire> tire_FR(new RigidTire(rigidtire_file, flat_terrain));
tire_FL->Initialize(tester.GetWheelBody(FRONT_LEFT));
tire_FR->Initialize(tester.GetWheelBody(FRONT_RIGHT));
tire_front_left = tire_FL;
tire_front_right = tire_FR;
#ifdef USE_IRRLICHT
irr::ChIrrApp application(&tester,
L"HMMWV Suspension test",
irr::core::dimension2d<irr::u32>(1000, 800),
false,
true);
// make a skybox that has Z pointing up (default .AddTypicalSky() Y up)
std::string mtexturedir = GetChronoDataFile("skybox/");
std::string str_lf = mtexturedir + "sky_lf.jpg";
std::string str_up = mtexturedir + "sky_up.jpg";
std::string str_dn = mtexturedir + "sky_dn.jpg";
irr::video::ITexture* map_skybox_side =
application.GetVideoDriver()->getTexture(str_lf.c_str());
irr::scene::ISceneNode* mbox = application.GetSceneManager()->addSkyBoxSceneNode(
application.GetVideoDriver()->getTexture(str_up.c_str()),
application.GetVideoDriver()->getTexture(str_dn.c_str()),
map_skybox_side,
map_skybox_side,
map_skybox_side,
map_skybox_side);
mbox->setRotation( irr::core::vector3df(90,0,0));
bool do_shadows = true; // shadow map is experimental
irr::scene::ILightSceneNode* mlight = 0;
if (do_shadows)
{
mlight = application.AddLightWithShadow(
irr::core::vector3df(-5.f, 1.f, 6.f),
irr::core::vector3df(5.f, -1.f, -2.f),
250, 60, 80, 15, 512, irr::video::SColorf(1, 1, 1), false, false);
}
else
{
application.AddTypicalLights(
irr::core::vector3df(30.f, -30.f, 100.f),
irr::core::vector3df(30.f, 50.f, 100.f),
250, 130);
}
application.SetTimestep(step_size);
ChIrrGuiST driver(application, tester, trackPoint, -2.0, 1, 0.5, 0.3);
// Set the time response for steering keyboard inputs, when they are used
// NOTE: this is not exact, since not rendered quite at the specified FPS.
double steering_time = 1.0; // time to go from 0 to +1 (or from 0 to -1)
double post_time = 1.0; // time to go from 0 to +1 for the applied post motion
driver.SetSteeringDelta(render_step_size / steering_time);
driver.SetPostDelta(render_step_size / post_time );
// Set up the assets for rendering
application.AssetBindAll();
application.AssetUpdateAll();
if (do_shadows)
{
application.AddShadowAll();
}
#else
ChDataDriver driver;
#endif
// ---------------
// Simulation loop
#ifdef DEBUG_LOG
GetLog() << "\n\n============ System Configuration ============\n";
vehicle.LogHardpointLocations();
#endif
// Inter-module communication data
ChTireForces tire_forces(2);
ChWheelState wheel_states[2];
double steering_input;
double post_z_L, post_z_R;
// Number of simulation steps between two 3D view render frames
int render_steps = (int)std::ceil(render_step_size / step_size);
// Number of simulation steps between two output frames
int output_steps = (int)std::ceil(output_step_size / step_size);
// Initialize simulation frame counter and simulation time
int step_number = 0;
double time = 0;
#ifdef USE_IRRLICHT
ChRealtimeStepTimer realtime_timer;
while (application.GetDevice()->run())
{
// update the position of the shadow mapping so that it follows the car
if (do_shadows)
{
ChVector<> lightaim = tester.GetChassisPos();
ChVector<> lightpos = tester.GetChassisPos() + ChVector<>(10, 30, 60);
irr::core::vector3df mlightpos((irr::f32)lightpos.x, (irr::f32)lightpos.y, (irr::f32)lightpos.z);
irr::core::vector3df mlightaim((irr::f32)lightaim.x, (irr::f32)lightaim.y, (irr::f32)lightaim.z);
application.GetEffects()->getShadowLight(0).setPosition(mlightpos);
application.GetEffects()->getShadowLight(0).setTarget(mlightaim);
mlight->setPosition(mlightpos);
}
// Render scene
if (step_number % render_steps == 0) {
application.GetVideoDriver()->beginScene(true, true, irr::video::SColor(255, 140, 161, 192));
driver.DrawAll();
application.GetVideoDriver()->endScene();
}
#ifdef DEBUG_LOG
if (step_number % output_steps == 0) {
GetLog() << "\n\n============ System Information ============\n";
GetLog() << "Time = " << time << "\n\n";
tester.DebugLog(DBG_SPRINGS | DBG_SHOCKS | DBG_CONSTRAINTS);
}
#endif
#ifdef DEBUG_ACTUATOR
if (step_number % output_steps == 0) {
GetLog() << "\n\n============ System Information ============\n";
GetLog() << "Time = " << time << "\n\n";
tester.DebugLog(DBG_SPRINGS | DBG_SHOCKS | DBG_CONSTRAINTS);
}
#endif
// Collect output data from modules, here it's the steering and post displacements
steering_input = driver.GetSteering();
post_z_L = driver.Get_post_z_L();
post_z_R = driver.Get_post_z_R();
tire_forces[FRONT_LEFT.id()] = tire_front_left->GetTireForce();
tire_forces[FRONT_RIGHT.id()] = tire_front_right->GetTireForce();
wheel_states[FRONT_LEFT.id()] = tester.GetWheelState(FRONT_LEFT);
wheel_states[FRONT_RIGHT.id()] = tester.GetWheelState(FRONT_RIGHT);
// Update modules (process inputs from other modules)
time = tester.GetChTime();
driver.Update(time);
flat_terrain.Update(time);
tire_front_left->Update(time, wheel_states[FRONT_LEFT.id()]);
tire_front_right->Update(time, wheel_states[FRONT_RIGHT.id()]);
tester.Update(time, steering_input, post_z_L, post_z_R, tire_forces);
// Advance simulation for one timestep for all modules
double step = realtime_timer.SuggestSimulationStep(step_size);
driver.Advance(step);
flat_terrain.Advance(step);
tire_front_left->Advance(step);
tire_front_right->Advance(step);
tester.Advance(step);
// Increment frame number
step_number++;
}
application.GetDevice()->drop();
#else
int render_frame = 0;
if(ChFileutils::MakeDirectory(out_dir.c_str()) < 0) {
std::cout << "Error creating directory " << out_dir << std::endl;
return 1;
}
if(ChFileutils::MakeDirectory(pov_dir.c_str()) < 0) {
std::cout << "Error creating directory " << pov_dir << std::endl;
return 1;
}
vehicle.ExportMeshPovray(out_dir);
char filename[100];
while (time < tend)
{
if (step_number % render_steps == 0) {
// Output render data
sprintf(filename, "%s/data_%03d.dat", pov_dir.c_str(), render_frame + 1);
utils::WriteShapesPovray(&vehicle, filename);
std::cout << "Output frame: " << render_frame << std::endl;
std::cout << "Sim frame: " << step_number << std::endl;
std::cout << "Time: " << time << std::endl;
std::cout << " throttle: " << driver.GetThrottle() << " steering: " << driver.GetSteering() << std::endl;
std::cout << std::endl;
render_frame++;
}
#ifdef DEBUG_LOG
if (step_number % output_steps == 0) {
GetLog() << "\n\n============ System Information ============\n";
GetLog() << "Time = " << time << "\n\n";
vehicle.DebugLog(DBG_SHOCKS);
}
#endif
// Collect output data from modules (for inter-module communication)
steering_input = driver.GetSteering();
tire_forces[FRONT_LEFT.id()] = tire_front_left->GetTireForce();
tire_forces[FRONT_RIGHT.id()] = tire_front_right->GetTireForce();
wheel_states[FRONT_LEFT.id()] = vehicle.GetWheelState(FRONT_LEFT);
wheel_states[FRONT_RIGHT.id()] = vehicle.GetWheelState(FRONT_RIGHT);
// Update modules (process inputs from other modules)
time = vehicle.GetChTime();
driver.Update(time);
flat_terrain.Update(time);
tire_front_left->Update(time, wheel_states[FRONT_LEFT.id()]);
tire_front_right->Update(time, wheel_states[FRONT_RIGHT.id()]);
tester.Update(time, steering_input);
// Advance simulation for one timestep for all modules
driver.Advance(step_size);
flat_terrain.Advance(step_size);
tire_front_right->Advance(step_size);
tire_front_left->Advance(step_size);
tester.Advance(step_size);
// Increment frame number
step_number++;
}
#endif
return 0;
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/isteps/istep08/call_proc_check_slave_sbe_seeprom_complete.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2017 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
/**
* @file call_proc_check_slave_sbe_seeprom_complete.C
*
* Support file for IStep: slave_sbe
* Slave SBE
*
* HWP_IGNORE_VERSION_CHECK
*/
/******************************************************************************/
// Includes
/******************************************************************************/
#include <stdint.h>
#include <trace/interface.H>
#include <initservice/taskargs.H>
#include <errl/errlentry.H>
#include <initservice/isteps_trace.H>
#include <initservice/initserviceif.H>
#include <initservice/initsvcreasoncodes.H>
#include <sys/time.h>
#include <devicefw/userif.H>
#include <i2c/i2cif.H>
#include <sbe/sbeif.H>
#include <util/misc.H>
#include <ipmi/ipmiwatchdog.H>
// targeting support
#include <targeting/common/commontargeting.H>
#include <targeting/common/utilFilter.H>
#include <targeting/namedtarget.H>
#include <targeting/attrsync.H>
#include <isteps/hwpisteperror.H>
#include <errl/errludtarget.H>
#include <fapi2/target.H>
#include <fapi2/plat_hwp_invoker.H>
#include <return_code.H>
#include <p9_extract_sbe_rc.H>
#include <p9_get_sbe_msg_register.H>
#include <p9_getecid.H>
#include "sbe_extract_rc_handler.H"
using namespace ISTEP;
using namespace ISTEP_ERROR;
using namespace ERRORLOG;
using namespace TARGETING;
using namespace fapi2;
const uint64_t MS_TO_WAIT_FIRST = 2500; //(2.5 s)
const uint64_t MS_TO_WAIT_OTHERS= 100; //(100 ms)
namespace ISTEP_08
{
//******************************************************************************
// call_proc_check_slave_sbe_seeprom_complete function
//******************************************************************************
void* call_proc_check_slave_sbe_seeprom_complete( void *io_pArgs )
{
errlHndl_t l_errl = NULL;
IStepError l_stepError;
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"call_proc_check_slave_sbe_seeprom_complete entry" );
//
// get the master Proc target, we want to IGNORE this one.
//
TARGETING::Target* l_pMasterProcTarget = NULL;
TARGETING::targetService().masterProcChipTargetHandle(l_pMasterProcTarget);
//
// get a list of all the procs in the system
//
TARGETING::TargetHandleList l_cpuTargetList;
getAllChips(l_cpuTargetList, TYPE_PROC);
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"proc_check_slave_sbe_seeprom_complete: %d procs in the system.",
l_cpuTargetList.size() );
// loop thru all the cpu's
for (const auto & l_cpu_target: l_cpuTargetList)
{
if ( l_cpu_target == l_pMasterProcTarget )
{
// we are just checking the Slave SBE's, skip the master
continue;
}
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"Processor target HUID %.8X",
TARGETING::get_huid(l_cpu_target));
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_fapi2ProcTarget(
const_cast<TARGETING::Target*> (l_cpu_target));
sbeMsgReg_t l_sbeReg;
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"Running p9_get_sbe_msg_register HWP"
" on processor target %.8X",
TARGETING::get_huid(l_cpu_target));
SBE_REG_RETURN l_ret = SBE_REG_RETURN::SBE_FAILED_TO_BOOT;
l_errl = sbe_timeout_handler(&l_sbeReg,l_cpu_target,&l_ret);
if((!l_errl) && (l_sbeReg.currState != SBE_STATE_RUNTIME))
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"SBE 0x%.8X never started, l_sbeReg=0x%.8X",
TARGETING::get_huid(l_cpu_target),l_sbeReg.reg );
/*@
* @errortype
* @reasoncode RC_SBE_SLAVE_TIMEOUT
* @severity ERRORLOG::ERRL_SEV_INFORMATIONAL
* @moduleid MOD_CHECK_SLAVE_SBE_SEEPROM_COMPLETE
* @userdata1 HUID of proc which had SBE timeout
* @userdata2 SBE MSG Register
*
* @devdesc Slave SBE did not get to ready state within
* allotted time
*
* @custdesc A processor in the system has failed to initialize
*/
l_errl = new ErrlEntry(
ERRL_SEV_INFORMATIONAL,
MOD_CHECK_SLAVE_SBE_SEEPROM_COMPLETE,
RC_SBE_SLAVE_TIMEOUT,
TARGETING::get_huid(l_cpu_target),
l_sbeReg.reg);
l_errl->collectTrace( "ISTEPS_TRACE", 256);
// Commit error and continue, this is not terminating since
// we can still at least boot with master proc
errlCommit(l_errl,ISTEP_COMP_ID);
// Setup for the HWP
P9_EXTRACT_SBE_RC::RETURN_ACTION l_rcAction =
P9_EXTRACT_SBE_RC::REIPL_UPD_SEEPROM;
FAPI_INVOKE_HWP(l_errl, p9_extract_sbe_rc,
l_fapi2ProcTarget, l_rcAction);
if(l_errl)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"ERROR : proc_check_slave_sbe_seeprom_complete "
"failed, p9_extract_sbe_rc HWP returning errorlog "
"PLID=0x%x",l_errl->plid());
// capture the target data in the elog
ErrlUserDetailsTarget(l_cpu_target).addToLog( l_errl );
// Create IStep error log and cross reference to error
l_stepError.addErrorDetails( l_errl );
// Commit error log
errlCommit( l_errl, HWPF_COMP_ID );
}
else if(l_rcAction != P9_EXTRACT_SBE_RC::ERROR_RECOVERED)
{
if(INITSERVICE::spBaseServicesEnabled())
{
// When we are on an FSP machine, we want to fail out of
// hostboot and give control back to the FSP. They have
// better diagnostics for this type of error.
INITSERVICE::doShutdownWithError(RC_HWSV_COLLECT_SBE_RC,
TARGETING::get_huid(l_cpu_target));
}
// Pull out previous rc error for threshold
uint8_t l_prevError = 0;
// Save the current rc error
(l_cpu_target)->setAttr<
TARGETING::ATTR_PREVIOUS_SBE_ERROR>(l_rcAction);
#ifdef CONFIG_BMC_IPMI
// This could potentially take awhile, reset watchdog
l_errl = IPMIWATCHDOG::resetWatchDogTimer();
if(l_errl)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_proc_check_slave_sbe_seeprom_complete "
"Resetting watchdog before sbe_handler");
l_errl->collectTrace("ISTEPS_TRACE",256);
errlCommit(l_errl,ISTEP_COMP_ID);
}
#endif
proc_extract_sbe_handler( l_cpu_target,
l_prevError, l_rcAction);
}
}
else if (l_errl)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"ERROR : call p9_check_slave_sbe_seeprom_complete, "
"PLID=0x%x", l_errl->plid() );
// capture the target data in the elog
ErrlUserDetailsTarget(l_cpu_target).addToLog( l_errl );
// Create IStep error log and cross reference to error that occurred
l_stepError.addErrorDetails( l_errl );
// Commit error log
errlCommit( l_errl, HWPF_COMP_ID );
}
// No error and still functional
else if(l_cpu_target->getAttr<ATTR_HWAS_STATE>().functional)
{
// Set attribute indicating that SBE is started
l_cpu_target->setAttr<ATTR_SBE_IS_STARTED>(1);
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"SUCCESS : proc_check_slave_sbe_seeprom_complete"
" completed ok for proc 0x%.8X",
TARGETING::get_huid(l_cpu_target));
}
/* @TODO-RTC:100963 This should only be called when the SBE has completely
crashed. There is a path in OpenPower where HB may get an
attention and need to call it. For now, though, just associate
with this story for tracking.
// Not a way to pass in -soft_err, assuming that is default behavior
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"Running p9_extract_sbe_rc HWP"
" on processor target %.8X",
TARGETING::get_huid(l_cpu_target) );
//@TODO-RTC:100963-Do something with the RETURN_ACTION
P9_EXTRACT_SBE_RC::RETURN_ACTION l_rcAction
= P9_EXTRACT_SBE_RC::RE_IPL;
FAPI_INVOKE_HWP(l_errl, p9_extract_sbe_rc,
l_fapi2ProcTarget,
l_rcAction);
if (l_errl)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"ERROR : proc_check_slave_sbe_seeprom_complete "
"failed, p9_extract_sbe_rc HWP returning errorlog PLID=0x%x",
l_errl->plid());
// capture the target data in the elog
ErrlUserDetailsTarget(l_cpu_target).addToLog( l_errl );
// Create IStep error log and cross reference to error that occurred
l_stepError.addErrorDetails( l_errl );
// Commit error log
errlCommit( l_errl, HWPF_COMP_ID );
}
**/
} // end of going through all processors
// Once the sbe's are up correctly, fetch all the proc ECIDs and
// store them in an attribute.
for (const auto & l_cpu_target: l_cpuTargetList)
{
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_fapi2ProcTarget(
const_cast<TARGETING::Target*> (l_cpu_target));
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"Running p9_getecid HWP"
" on processor target %.8X",
TARGETING::get_huid(l_cpu_target) );
// p9_getecid should set the fuse string to 112 bytes long.
fapi2::variable_buffer l_fuseString(112);
// Invoke the HWP
FAPI_INVOKE_HWP(l_errl,
p9_getecid,
l_fapi2ProcTarget,
l_fuseString );
if (l_errl)
{
if (l_cpu_target->getAttr<ATTR_HWAS_STATE>().functional)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"ERROR : p9_getecid",
" failed, returning errorlog" );
// capture the target data in the elog
ErrlUserDetailsTarget(l_cpu_target).addToLog( l_errl );
// Create IStep error log and cross reference error that
// occurred
l_stepError.addErrorDetails( l_errl );
// Commit error log
errlCommit( l_errl, HWPF_COMP_ID );
}
else // Not functional, proc deconfigured, don't report error
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"ERROR : p9_getecid"
" failed, proc target deconfigured" );
delete l_errl;
l_errl = NULL;
}
}
else
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"SUCCESS : proc_getecid"
" completed ok");
// Update HDAT_EC to account for anything lower than the minor EC
auto l_miniEC = l_cpu_target->getAttr<TARGETING::ATTR_MINI_EC>();
if( l_miniEC != 0 )
{
auto l_hdatEC = l_cpu_target->getAttr<TARGETING::ATTR_HDAT_EC>();
auto l_EC = l_cpu_target->getAttr<TARGETING::ATTR_EC>();
auto l_newHdatEC = l_EC + l_miniEC;
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"MINI_EC=%d, HDAT_EC changing from %d->%d",
l_miniEC, l_hdatEC, l_newHdatEC );
l_cpu_target->setAttr<TARGETING::ATTR_HDAT_EC>(l_newHdatEC);
}
}
} // end of going through all processors
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_proc_check_slave_sbe_seeprom_complete exit");
// end task, returning any errorlogs to IStepDisp
return l_stepError.getErrorHandle();
}
};
<commit_msg>Disable SBE start recovery code<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/isteps/istep08/call_proc_check_slave_sbe_seeprom_complete.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2017 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
/**
* @file call_proc_check_slave_sbe_seeprom_complete.C
*
* Support file for IStep: slave_sbe
* Slave SBE
*
* HWP_IGNORE_VERSION_CHECK
*/
/******************************************************************************/
// Includes
/******************************************************************************/
#include <stdint.h>
#include <trace/interface.H>
#include <initservice/taskargs.H>
#include <errl/errlentry.H>
#include <initservice/isteps_trace.H>
#include <initservice/initserviceif.H>
#include <initservice/initsvcreasoncodes.H>
#include <sys/time.h>
#include <devicefw/userif.H>
#include <i2c/i2cif.H>
#include <sbe/sbeif.H>
#include <util/misc.H>
#include <ipmi/ipmiwatchdog.H>
// targeting support
#include <targeting/common/commontargeting.H>
#include <targeting/common/utilFilter.H>
#include <targeting/namedtarget.H>
#include <targeting/attrsync.H>
#include <isteps/hwpisteperror.H>
#include <errl/errludtarget.H>
#include <fapi2/target.H>
#include <fapi2/plat_hwp_invoker.H>
#include <return_code.H>
#include <p9_extract_sbe_rc.H>
#include <p9_get_sbe_msg_register.H>
#include <p9_getecid.H>
#include "sbe_extract_rc_handler.H"
using namespace ISTEP;
using namespace ISTEP_ERROR;
using namespace ERRORLOG;
using namespace TARGETING;
using namespace fapi2;
const uint64_t MS_TO_WAIT_FIRST = 2500; //(2.5 s)
const uint64_t MS_TO_WAIT_OTHERS= 100; //(100 ms)
namespace ISTEP_08
{
//******************************************************************************
// call_proc_check_slave_sbe_seeprom_complete function
//******************************************************************************
void* call_proc_check_slave_sbe_seeprom_complete( void *io_pArgs )
{
errlHndl_t l_errl = NULL;
IStepError l_stepError;
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"call_proc_check_slave_sbe_seeprom_complete entry" );
//
// get the master Proc target, we want to IGNORE this one.
//
TARGETING::Target* l_pMasterProcTarget = NULL;
TARGETING::targetService().masterProcChipTargetHandle(l_pMasterProcTarget);
//
// get a list of all the procs in the system
//
TARGETING::TargetHandleList l_cpuTargetList;
getAllChips(l_cpuTargetList, TYPE_PROC);
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"proc_check_slave_sbe_seeprom_complete: %d procs in the system.",
l_cpuTargetList.size() );
// loop thru all the cpu's
for (const auto & l_cpu_target: l_cpuTargetList)
{
if ( l_cpu_target == l_pMasterProcTarget )
{
// we are just checking the Slave SBE's, skip the master
continue;
}
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"Processor target HUID %.8X",
TARGETING::get_huid(l_cpu_target));
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_fapi2ProcTarget(
const_cast<TARGETING::Target*> (l_cpu_target));
sbeMsgReg_t l_sbeReg;
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"Running p9_get_sbe_msg_register HWP"
" on processor target %.8X",
TARGETING::get_huid(l_cpu_target));
SBE_REG_RETURN l_ret = SBE_REG_RETURN::SBE_FAILED_TO_BOOT;
l_errl = sbe_timeout_handler(&l_sbeReg,l_cpu_target,&l_ret);
if((!l_errl) && (l_sbeReg.currState != SBE_STATE_RUNTIME))
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"SBE 0x%.8X never started, l_sbeReg=0x%.8X",
TARGETING::get_huid(l_cpu_target),l_sbeReg.reg );
/*@
* @errortype
* @reasoncode RC_SBE_SLAVE_TIMEOUT
* @severity ERRORLOG::ERRL_SEV_INFORMATIONAL
* @moduleid MOD_CHECK_SLAVE_SBE_SEEPROM_COMPLETE
* @userdata1 HUID of proc which had SBE timeout
* @userdata2 SBE MSG Register
*
* @devdesc Slave SBE did not get to ready state within
* allotted time
*
* @custdesc A processor in the system has failed to initialize
*/
l_errl = new ErrlEntry(
ERRL_SEV_INFORMATIONAL,
MOD_CHECK_SLAVE_SBE_SEEPROM_COMPLETE,
RC_SBE_SLAVE_TIMEOUT,
TARGETING::get_huid(l_cpu_target),
l_sbeReg.reg);
l_errl->collectTrace( "ISTEPS_TRACE", 256);
// Commit error and continue, this is not terminating since
// we can still at least boot with master proc
errlCommit(l_errl,ISTEP_COMP_ID);
//@fixme - RTC:177921
// Do not call p9_extract_sbe_rc because it corrupts
// live debug of fails. Need to make some other
// changes before turning this back on.
#if 1 // get rid of this
// Create IStep error log and cross reference to error
l_stepError.addErrorDetails( l_errl );
// Commit error log
errlCommit( l_errl, HWPF_COMP_ID );
#else
// Setup for the HWP
P9_EXTRACT_SBE_RC::RETURN_ACTION l_rcAction =
P9_EXTRACT_SBE_RC::REIPL_UPD_SEEPROM;
FAPI_INVOKE_HWP(l_errl, p9_extract_sbe_rc,
l_fapi2ProcTarget, l_rcAction);
if(l_errl)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"ERROR : proc_check_slave_sbe_seeprom_complete "
"failed, p9_extract_sbe_rc HWP returning errorlog "
"PLID=0x%x",l_errl->plid());
// capture the target data in the elog
ErrlUserDetailsTarget(l_cpu_target).addToLog( l_errl );
// Create IStep error log and cross reference to error
l_stepError.addErrorDetails( l_errl );
// Commit error log
errlCommit( l_errl, HWPF_COMP_ID );
}
else if(l_rcAction != P9_EXTRACT_SBE_RC::ERROR_RECOVERED)
{
if(INITSERVICE::spBaseServicesEnabled())
{
// When we are on an FSP machine, we want to fail out of
// hostboot and give control back to the FSP. They have
// better diagnostics for this type of error.
INITSERVICE::doShutdownWithError(RC_HWSV_COLLECT_SBE_RC,
TARGETING::get_huid(l_cpu_target));
}
// Pull out previous rc error for threshold
uint8_t l_prevError = 0;
// Save the current rc error
(l_cpu_target)->setAttr<
TARGETING::ATTR_PREVIOUS_SBE_ERROR>(l_rcAction);
#ifdef CONFIG_BMC_IPMI
// This could potentially take awhile, reset watchdog
l_errl = IPMIWATCHDOG::resetWatchDogTimer();
if(l_errl)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_proc_check_slave_sbe_seeprom_complete "
"Resetting watchdog before sbe_handler");
l_errl->collectTrace("ISTEPS_TRACE",256);
errlCommit(l_errl,ISTEP_COMP_ID);
}
#endif
proc_extract_sbe_handler( l_cpu_target,
l_prevError, l_rcAction);
}
#endif //@fixme - RTC:177921
}
else if (l_errl)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"ERROR : call p9_check_slave_sbe_seeprom_complete, "
"PLID=0x%x", l_errl->plid() );
// capture the target data in the elog
ErrlUserDetailsTarget(l_cpu_target).addToLog( l_errl );
// Create IStep error log and cross reference to error that occurred
l_stepError.addErrorDetails( l_errl );
// Commit error log
errlCommit( l_errl, HWPF_COMP_ID );
}
// No error and still functional
else if(l_cpu_target->getAttr<ATTR_HWAS_STATE>().functional)
{
// Set attribute indicating that SBE is started
l_cpu_target->setAttr<ATTR_SBE_IS_STARTED>(1);
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"SUCCESS : proc_check_slave_sbe_seeprom_complete"
" completed ok for proc 0x%.8X",
TARGETING::get_huid(l_cpu_target));
}
/* @TODO-RTC:100963 This should only be called when the SBE has completely
crashed. There is a path in OpenPower where HB may get an
attention and need to call it. For now, though, just associate
with this story for tracking.
// Not a way to pass in -soft_err, assuming that is default behavior
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"Running p9_extract_sbe_rc HWP"
" on processor target %.8X",
TARGETING::get_huid(l_cpu_target) );
//@TODO-RTC:100963-Do something with the RETURN_ACTION
P9_EXTRACT_SBE_RC::RETURN_ACTION l_rcAction
= P9_EXTRACT_SBE_RC::RE_IPL;
FAPI_INVOKE_HWP(l_errl, p9_extract_sbe_rc,
l_fapi2ProcTarget,
l_rcAction);
if (l_errl)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"ERROR : proc_check_slave_sbe_seeprom_complete "
"failed, p9_extract_sbe_rc HWP returning errorlog PLID=0x%x",
l_errl->plid());
// capture the target data in the elog
ErrlUserDetailsTarget(l_cpu_target).addToLog( l_errl );
// Create IStep error log and cross reference to error that occurred
l_stepError.addErrorDetails( l_errl );
// Commit error log
errlCommit( l_errl, HWPF_COMP_ID );
}
**/
} // end of going through all processors
// Once the sbe's are up correctly, fetch all the proc ECIDs and
// store them in an attribute.
for (const auto & l_cpu_target: l_cpuTargetList)
{
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_fapi2ProcTarget(
const_cast<TARGETING::Target*> (l_cpu_target));
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"Running p9_getecid HWP"
" on processor target %.8X",
TARGETING::get_huid(l_cpu_target) );
// p9_getecid should set the fuse string to 112 bytes long.
fapi2::variable_buffer l_fuseString(112);
// Invoke the HWP
FAPI_INVOKE_HWP(l_errl,
p9_getecid,
l_fapi2ProcTarget,
l_fuseString );
if (l_errl)
{
if (l_cpu_target->getAttr<ATTR_HWAS_STATE>().functional)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"ERROR : p9_getecid",
" failed, returning errorlog" );
// capture the target data in the elog
ErrlUserDetailsTarget(l_cpu_target).addToLog( l_errl );
// Create IStep error log and cross reference error that
// occurred
l_stepError.addErrorDetails( l_errl );
// Commit error log
errlCommit( l_errl, HWPF_COMP_ID );
}
else // Not functional, proc deconfigured, don't report error
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"ERROR : p9_getecid"
" failed, proc target deconfigured" );
delete l_errl;
l_errl = NULL;
}
}
else
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"SUCCESS : proc_getecid"
" completed ok");
// Update HDAT_EC to account for anything lower than the minor EC
auto l_miniEC = l_cpu_target->getAttr<TARGETING::ATTR_MINI_EC>();
if( l_miniEC != 0 )
{
auto l_hdatEC = l_cpu_target->getAttr<TARGETING::ATTR_HDAT_EC>();
auto l_EC = l_cpu_target->getAttr<TARGETING::ATTR_EC>();
auto l_newHdatEC = l_EC + l_miniEC;
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"MINI_EC=%d, HDAT_EC changing from %d->%d",
l_miniEC, l_hdatEC, l_newHdatEC );
l_cpu_target->setAttr<TARGETING::ATTR_HDAT_EC>(l_newHdatEC);
}
}
} // end of going through all processors
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_proc_check_slave_sbe_seeprom_complete exit");
// end task, returning any errorlogs to IStepDisp
return l_stepError.getErrorHandle();
}
};
<|endoftext|> |
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/tools/evaluation/stages/tflite_inference_stage.h"
#include <cstring>
#include <fstream>
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/lite/profiling/time.h"
#include "tensorflow/lite/tools/evaluation/proto/evaluation_stages.pb.h"
#include "tensorflow/lite/tools/evaluation/utils.h"
namespace tflite {
namespace evaluation {
namespace {
TfLiteModelInfo GetTfliteModelInfo(const Interpreter& interpreter) {
TfLiteModelInfo model_info;
for (int i : interpreter.inputs()) {
model_info.inputs.push_back(interpreter.tensor(i));
}
for (int i : interpreter.outputs()) {
model_info.outputs.push_back(interpreter.tensor(i));
}
return model_info;
}
} // namespace
TfLiteStatus TfliteInferenceStage::Init() {
if (!config_.specification().has_tflite_inference_params()) {
LOG(ERROR) << "TfliteInferenceParams not provided";
return kTfLiteError;
}
auto& params = config_.specification().tflite_inference_params();
if (!params.has_model_file_path()) {
LOG(ERROR) << "Model path not provided";
return kTfLiteError;
}
std::ifstream model_check(params.model_file_path());
if (!model_check.good()) {
LOG(ERROR) << "Model file not found";
return kTfLiteError;
}
model_ = FlatBufferModel::BuildFromFile(params.model_file_path().c_str());
resolver_.reset(new ops::builtin::BuiltinOpResolver);
InterpreterBuilder(*model_, *resolver_)(&interpreter_);
if (!interpreter_) {
LOG(ERROR) << "Could not build interpreter";
return kTfLiteError;
}
interpreter_->SetNumThreads(params.num_threads());
// TODO(b/122482115): Add support for multiple delegates in
// TfLiteInferenceParams.
if (params.delegate() == TfliteInferenceParams::NNAPI) {
Interpreter::TfLiteDelegatePtr delegate = CreateNNAPIDelegate();
if (delegate) {
delegates_.push_back(std::move(delegate));
} else {
LOG(WARNING) << "NNAPI not supported";
}
} else if (params.delegate() == TfliteInferenceParams::GPU) {
Interpreter::TfLiteDelegatePtr delegate = CreateGPUDelegate(model_.get());
if (!delegate) {
delegates_.push_back(std::move(delegate));
} else {
LOG(WARNING) << "GPU not supported";
}
}
for (int i = 0; i < delegates_.size(); ++i) {
if (interpreter_->ModifyGraphWithDelegate(delegates_[i].get()) !=
kTfLiteOk) {
LOG(FATAL) << "Failed to apply delegate %d" << i;
}
}
interpreter_->AllocateTensors();
model_info_ = GetTfliteModelInfo(*interpreter_);
outputs_.reserve(interpreter_->outputs().size());
for (int i : interpreter_->outputs()) {
TfLiteTensor* tensor = interpreter_->tensor(i);
outputs_.push_back(tensor->data.raw);
}
return kTfLiteOk;
}
TfLiteStatus TfliteInferenceStage::Run() {
if (!inputs_) {
LOG(ERROR) << "Input data not set";
return kTfLiteError;
}
// Copy input data.
for (int i = 0; i < interpreter_->inputs().size(); ++i) {
TfLiteTensor* tensor = interpreter_->tensor(interpreter_->inputs()[i]);
std::memcpy(tensor->data.raw, (*inputs_)[i], tensor->bytes);
}
// Invoke.
auto& params = config_.specification().tflite_inference_params();
for (int i = 0; i < params.invocations_per_run(); ++i) {
int64_t start_us = profiling::time::NowMicros();
interpreter_->Invoke();
latency_stats_.UpdateStat(profiling::time::NowMicros() - start_us);
}
return kTfLiteOk;
}
EvaluationStageMetrics TfliteInferenceStage::LatestMetrics() {
auto& params = config_.specification().tflite_inference_params();
EvaluationStageMetrics metrics;
auto* latency_metrics =
metrics.mutable_process_metrics()->mutable_total_latency();
latency_metrics->set_last_us(latency_stats_.newest());
latency_metrics->set_max_us(latency_stats_.max());
latency_metrics->set_min_us(latency_stats_.min());
latency_metrics->set_sum_us(latency_stats_.sum());
latency_metrics->set_avg_us(latency_stats_.avg());
metrics.set_num_runs(
static_cast<int>(latency_stats_.count() / params.invocations_per_run()));
auto* inference_metrics =
metrics.mutable_process_metrics()->mutable_tflite_inference_metrics();
inference_metrics->set_num_inferences(latency_stats_.count());
return metrics;
}
} // namespace evaluation
} // namespace tflite
<commit_msg>Fix GPU delegate condition in inference stage<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/tools/evaluation/stages/tflite_inference_stage.h"
#include <cstring>
#include <fstream>
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/lite/profiling/time.h"
#include "tensorflow/lite/tools/evaluation/proto/evaluation_stages.pb.h"
#include "tensorflow/lite/tools/evaluation/utils.h"
namespace tflite {
namespace evaluation {
namespace {
TfLiteModelInfo GetTfliteModelInfo(const Interpreter& interpreter) {
TfLiteModelInfo model_info;
for (int i : interpreter.inputs()) {
model_info.inputs.push_back(interpreter.tensor(i));
}
for (int i : interpreter.outputs()) {
model_info.outputs.push_back(interpreter.tensor(i));
}
return model_info;
}
} // namespace
TfLiteStatus TfliteInferenceStage::Init() {
if (!config_.specification().has_tflite_inference_params()) {
LOG(ERROR) << "TfliteInferenceParams not provided";
return kTfLiteError;
}
auto& params = config_.specification().tflite_inference_params();
if (!params.has_model_file_path()) {
LOG(ERROR) << "Model path not provided";
return kTfLiteError;
}
std::ifstream model_check(params.model_file_path());
if (!model_check.good()) {
LOG(ERROR) << "Model file not found";
return kTfLiteError;
}
model_ = FlatBufferModel::BuildFromFile(params.model_file_path().c_str());
resolver_.reset(new ops::builtin::BuiltinOpResolver);
InterpreterBuilder(*model_, *resolver_)(&interpreter_);
if (!interpreter_) {
LOG(ERROR) << "Could not build interpreter";
return kTfLiteError;
}
interpreter_->SetNumThreads(params.num_threads());
// TODO(b/122482115): Add support for multiple delegates in
// TfLiteInferenceParams.
if (params.delegate() == TfliteInferenceParams::NNAPI) {
Interpreter::TfLiteDelegatePtr delegate = CreateNNAPIDelegate();
if (delegate) {
delegates_.push_back(std::move(delegate));
} else {
LOG(WARNING) << "NNAPI not supported";
}
} else if (params.delegate() == TfliteInferenceParams::GPU) {
Interpreter::TfLiteDelegatePtr delegate = CreateGPUDelegate(model_.get());
if (delegate) {
delegates_.push_back(std::move(delegate));
} else {
LOG(WARNING) << "GPU not supported";
}
}
for (int i = 0; i < delegates_.size(); ++i) {
if (interpreter_->ModifyGraphWithDelegate(delegates_[i].get()) !=
kTfLiteOk) {
LOG(FATAL) << "Failed to apply delegate %d" << i;
}
}
interpreter_->AllocateTensors();
model_info_ = GetTfliteModelInfo(*interpreter_);
outputs_.reserve(interpreter_->outputs().size());
for (int i : interpreter_->outputs()) {
TfLiteTensor* tensor = interpreter_->tensor(i);
outputs_.push_back(tensor->data.raw);
}
return kTfLiteOk;
}
TfLiteStatus TfliteInferenceStage::Run() {
if (!inputs_) {
LOG(ERROR) << "Input data not set";
return kTfLiteError;
}
// Copy input data.
for (int i = 0; i < interpreter_->inputs().size(); ++i) {
TfLiteTensor* tensor = interpreter_->tensor(interpreter_->inputs()[i]);
std::memcpy(tensor->data.raw, (*inputs_)[i], tensor->bytes);
}
// Invoke.
auto& params = config_.specification().tflite_inference_params();
for (int i = 0; i < params.invocations_per_run(); ++i) {
int64_t start_us = profiling::time::NowMicros();
interpreter_->Invoke();
latency_stats_.UpdateStat(profiling::time::NowMicros() - start_us);
}
return kTfLiteOk;
}
EvaluationStageMetrics TfliteInferenceStage::LatestMetrics() {
auto& params = config_.specification().tflite_inference_params();
EvaluationStageMetrics metrics;
auto* latency_metrics =
metrics.mutable_process_metrics()->mutable_total_latency();
latency_metrics->set_last_us(latency_stats_.newest());
latency_metrics->set_max_us(latency_stats_.max());
latency_metrics->set_min_us(latency_stats_.min());
latency_metrics->set_sum_us(latency_stats_.sum());
latency_metrics->set_avg_us(latency_stats_.avg());
metrics.set_num_runs(
static_cast<int>(latency_stats_.count() / params.invocations_per_run()));
auto* inference_metrics =
metrics.mutable_process_metrics()->mutable_tflite_inference_metrics();
inference_metrics->set_num_inferences(latency_stats_.count());
return metrics;
}
} // namespace evaluation
} // namespace tflite
<|endoftext|> |
<commit_before>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/mlir/tfrt/benchmarks/benchmark_mlir_function.h"
#include <memory>
#include "llvm/Support/SourceMgr.h"
#include "mlir/Parser.h" // from @llvm-project
#include "tensorflow/compiler/mlir/tfrt/transforms/passes.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/platform/threadpool.h"
#include "tensorflow/core/runtime_fallback/kernel/kernel_fallback_execute_compat.h"
#include "tensorflow/core/runtime_fallback/runtime/kernel_utils.h"
#include "tensorflow/core/tfrt/utils/fallback_tensor.h"
#include "tfrt/bef_converter/mlir_to_bef.h" // from @tf_runtime
#include "tfrt/bef_executor/bef_file.h" // from @tf_runtime
#include "tfrt/host_context/execution_context.h" // from @tf_runtime
#include "tfrt/host_context/function.h" // from @tf_runtime
#include "tfrt/host_context/resource_context.h" // from @tf_runtime
namespace tensorflow {
using ::tfrt::ArrayRef;
using ::tfrt::AsyncValue;
using ::tfrt::AsyncValuePtr;
using ::tfrt::BEFFile;
using ::tfrt::ExecutionContext;
using ::tfrt::Function;
using ::tfrt::HostContext;
using ::tfrt::MakeAvailableAsyncValueRef;
using ::tfrt::RCReference;
using ::tfrt::RemainingResults;
using ::tfrt::RequestContext;
using ::tfrt::RequestContextBuilder;
using ::tfrt::ResourceContext;
using ::tfrt::cpu::jit::Executable;
using ::tfrt::cpu::jit::JitExecutable;
using ::tfrt::cpu::jit::MemrefDesc;
using ::tfrt::cpu::jit::ReturnValueConverter;
using ::tensorflow::Env;
using ::tensorflow::thread::ThreadPool;
using ::tensorflow::thread::ThreadPoolInterface;
using ::tensorflow::tfrt_stub::FallbackTensor;
// Returns random tensors generated based on the input specs.
static llvm::SmallVector<Tensor> GetInputTensors(
llvm::ArrayRef<InputTensorSpec> input_specs) {
llvm::SmallVector<Tensor> input_tensors;
for (const InputTensorSpec& spec : input_specs) {
TensorShape shape;
CHECK(TensorShapeUtils::MakeShape(spec.dims, &shape).ok());
input_tensors.emplace_back(spec.dtype, shape);
// Initialize tensors with random data.
switch (spec.dtype) {
case DT_FLOAT:
input_tensors.back().flat<float>().setRandom();
break;
case DT_INT64:
input_tensors.back().flat<int64_t>().setRandom();
break;
default:
CHECK(false) << "Unsupported dtype: " << spec.dtype;
}
}
return input_tensors;
}
// -------------------------------------------------------------------------- //
// Run function benchmark via the TF CPURT compilation.
// -------------------------------------------------------------------------- //
void RunCpurtBenchmark(::testing::benchmark::State& state,
llvm::StringRef mlir_input,
llvm::StringRef function_name,
llvm::ArrayRef<InputTensorSpec> input_specs,
bool vectorize) {
// Number of worker threads.
int64_t num_threads = state.range(0);
// Host context for running compute tasks.
std::unique_ptr<HostContext> host =
num_threads > 0 ? CreateMultiThreadedHostContext(num_threads)
: CreateSingleThreadedHostContext();
TfCpuRtPipelineOptions tf_cpurt_opts;
tf_cpurt_opts.vectorize = vectorize;
JitExecutable& jit_executable =
CreateJitExecutable(*host, mlir_input, function_name,
/*lower_from_tensorflow=*/true, tf_cpurt_opts);
// Build an ExecutionContext from the HostContext.
llvm::Expected<RCReference<RequestContext>> req_ctx =
RequestContextBuilder(host.get(), /*resource_context=*/nullptr).build();
tfrt::ExecutionContext exec_ctx(std::move(*req_ctx));
// Generate random inputs based on the tensor specs.
llvm::SmallVector<Tensor> input_tensors = GetInputTensors(input_specs);
// Convert input tensors to memref descriptors.
llvm::SmallVector<MemrefDesc> operands;
for (const Tensor& tensor : input_tensors)
operands.emplace_back(TensorToMemrefDesc(tensor));
// Get an executable that might be specialized to the operands.
llvm::Expected<AsyncValuePtr<Executable>> executable =
jit_executable.GetExecutable(operands, exec_ctx);
if (auto err = executable.takeError())
LOG(FATAL) << "Failed to specialize executable: " << tfrt::StrCat(err);
// Wait for the compilation completion.
host->Await({executable->CopyRef()});
CHECK(!executable->IsError())
<< "Failed to get executable: " << tfrt::StrCat(executable->GetError());
CHECK(!(*executable)->IsAsync()) << "async results are not supported";
// Placeholders for returned values.
unsigned num_results = (*executable)->num_results();
llvm::SmallVector<RCReference<AsyncValue>> result_values(num_results);
RemainingResults results(result_values);
// Free memory owned by the returned memrefs.
ReturnValueConverter<ResultConversionCtx> converter(results);
converter.AddConversion(FreeReturnedMemref);
// Initialize call frame with MemrefDesc operands.
Executable::CallFrame call_frame;
if (auto err = (*executable)->InitializeCallFrame(operands, &call_frame))
LOG(FATAL) << "Failed to initialize call frame";
for (auto _ : state) {
(*executable)->Execute(call_frame, exec_ctx);
if (auto err =
(*executable)->ReturnResults(converter, exec_ctx, &call_frame))
LOG(FATAL) << "Failed to return compiled kernel results";
}
}
// -------------------------------------------------------------------------- //
// Run function benchmark via the TF->TFRT fallback lowering.
// -------------------------------------------------------------------------- //
// Thread pool for running `intra-op` tasks scheduled by the fallback kernels.
class IntraOpTheadPool : public ThreadPoolInterface {
public:
explicit IntraOpTheadPool(int num_threads)
: tpool_(Env::Default(), "intra-op", std::max(1, num_threads)) {}
void Schedule(std::function<void()> fn) override {
tpool_.Schedule(std::move(fn));
}
int NumThreads() const override { return tpool_.NumThreads(); }
int CurrentThreadId() const override { return tpool_.CurrentThreadId(); }
void Cancel() override {}
private:
ThreadPool tpool_;
};
// Run TFRT fallback initialization function to instantiate all fallback
// kernels ahead of executing the compute function.
static void RunTfrtInitializer(const ExecutionContext& exec_ctx,
BEFFile* bef_file,
llvm::StringRef fallback_init_func) {
const Function* func = bef_file->GetFunction(fallback_init_func);
CHECK(func) << "TFRT initialization function was not found";
CHECK_EQ(func->argument_types().size(), 1);
llvm::SmallVector<RCReference<AsyncValue>, 1> results;
results.resize(func->result_types().size());
CHECK_EQ(results.size(), 1);
func->Execute(exec_ctx, tfrt::GetReadyChain().GetAsyncValue(), results);
HostContext* host = exec_ctx.host();
host->Await(results);
CHECK(!results[0]->IsError()) << "Failed to run TFRT initialization function";
}
void RunTfrtBenchmark(::testing::benchmark::State& state,
llvm::StringRef mlir_input, llvm::StringRef function_name,
ArrayRef<InputTensorSpec> input_specs) {
// Number of worker threads (intra-op concurrency for the fallback ops).
int64_t num_threads = state.range(0);
// We only support benchmarks written in the Tensorflow dialect.
mlir::DialectRegistry registry;
mlir::RegisterAllTensorFlowDialects(registry);
mlir::MLIRContext context(registry);
llvm::SourceMgr source_mgr;
source_mgr.AddNewSourceBuffer(
llvm::MemoryBuffer::getMemBuffer(mlir_input, "benchmark"), llvm::SMLoc());
// Parse a kernel source code into the MLIR Module.
mlir::OwningModuleRef module(mlir::parseSourceFile(source_mgr, &context));
CHECK(module) << "failed to parse mlir module";
// Collect all diagnostics emitted while lowering parsed kernel module.
std::string diagnostic_str;
llvm::raw_string_ostream os(diagnostic_str);
mlir::SourceMgrDiagnosticHandler handler(source_mgr, module->getContext(),
os);
// Convert TF to TFRT fallback dialect.
TfrtPipelineOptions core_rt_opts;
core_rt_opts.hoist_invariant_ops = true;
core_rt_opts.enable_native_ops = false;
core_rt_opts.cost_threshold = 1024;
core_rt_opts.upper_cost_threshold = 100000;
core_rt_opts.merge_inter_dependent_streams = true;
core_rt_opts.func_use_fallback_tensor = true;
mlir::PassManager pm(module->getContext());
pm.addPass(CreateTfToTfrtConversionPass(core_rt_opts));
CHECK(mlir::succeeded(pm.run(*module)))
<< "Failed to lower module to TFRT: " << os.str();
// Create a thread pool for running intra-op tasks.
IntraOpTheadPool intra_op(num_threads);
// Create a HostContext for running TFRT functions. Concurrent work queue acts
// similar to the Tensorflow `inter-op` thread pool, so we'll match the size.
auto host = CreateMultiThreadedHostContext(num_threads);
tfrt::RegisterStaticKernels(host->GetMutableRegistry());
// Convert module to BEF.
auto bef_buffer =
tfrt::ConvertMLIRToBEF(*module, /*disable_optional_sections=*/false);
CHECK(!bef_buffer.empty()) << "Failed to convert module to BEF";
// Build an ExecutionContext from the HostContext.
ResourceContext resource_context;
auto builder = RequestContextBuilder(host.get(), &resource_context);
// Get tensorflow::EagerContext for the kernel fallback.
auto* eager_context_resource =
resource_context
.GetOrCreateResource<tensorflow::tfd::EagerContextResource>(
tensorflow::tfd::kEagerContextResourceName);
auto expected_eager_context = eager_context_resource->GetTFEagerContext();
auto* eager_context = expected_eager_context.get();
// Initialize fallback kernels state with a custom intra-op thread pool.
auto status = tensorflow::tfd::SetUpKernelFallbackCompatRequestContext(
&builder, /*runner_table=*/nullptr, eager_context, &intra_op);
CHECK(status.ok()) << "Failed to setup request context: "
<< status.error_message();
auto req_ctx = std::move(builder).build();
if (auto err = req_ctx.takeError())
LOG(FATAL) << "Failed to build a request context";
ExecutionContext exec_ctx(std::move(*req_ctx));
auto bef_file = BEFFile::Open(bef_buffer, host->GetKernelRegistry(),
host->diag_handler(), host->allocator());
CHECK(bef_file) << "Failed to open BEF";
// Run TFRT initialization function to pre-instantiate fallback kernels.
RunTfrtInitializer(exec_ctx, bef_file.get(), "_tfrt_fallback_init");
// Get the kernel entrypoint function.
const Function* compute = bef_file->GetFunction(function_name);
CHECK(compute) << "Entrypoint function not found";
// Generate random inputs based on the tensor specs.
llvm::SmallVector<Tensor> input_tensors = GetInputTensors(input_specs);
// Prepare function arguments from ready Chain and input Tensors.
llvm::SmallVector<AsyncValue*> arguments;
arguments.push_back(tfrt::GetReadyChain().release());
for (const Tensor& input_tensor : input_tensors) {
auto av = MakeAvailableAsyncValueRef<FallbackTensor>(input_tensor);
arguments.push_back(av.release());
}
// Space for returned values.
llvm::SmallVector<RCReference<AsyncValue>> results;
for (auto _ : state) {
// Reset results in preparation for the function call.
results.clear();
results.resize(compute->result_types().size());
compute->Execute(exec_ctx, arguments, results);
// Wait for the function execution to finish, as well as the side-effects.
host->Await(results);
// First result is always a chain, check if it has error.
if (auto* error = results[0]->GetErrorIfPresent())
LOG(FATAL) << "Failed to execute a function";
}
// Deallocate arguments.
for (auto* argument : arguments) argument->DropRef();
}
// -------------------------------------------------------------------------- //
// Run arbitrary benchark written as a function.
// -------------------------------------------------------------------------- //
void RunEigenBenchmark(
::testing::benchmark::State& state,
std::function<void(llvm::ArrayRef<Tensor>,
llvm::Optional<Eigen::ThreadPoolDevice>)>
compute,
llvm::ArrayRef<InputTensorSpec> input_specs) {
// Number of worker threads.
int64_t num_threads = state.range(0);
// Maybe construct an Eigen thread pool device for evaluating expressions.
Eigen::ThreadPool thread_pool(num_threads);
llvm::Optional<Eigen::ThreadPoolDevice> device;
if (num_threads > 0) device.emplace(&thread_pool, num_threads);
// Generate random inputs based on the tensor specs.
llvm::SmallVector<Tensor> input_tensors = GetInputTensors(input_specs);
// Call the user defined compute function.
for (auto _ : state) {
compute(input_tensors, device);
}
}
} // namespace tensorflow
<commit_msg>[tf:tfrt] Fix cpurt benchmark errors<commit_after>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/mlir/tfrt/benchmarks/benchmark_mlir_function.h"
#include <algorithm>
#include <functional>
#include <memory>
#include <utility>
#include "llvm/Support/SourceMgr.h"
#include "mlir/Parser.h" // from @llvm-project
#include "tensorflow/compiler/mlir/tfrt/transforms/passes.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/platform/threadpool.h"
#include "tensorflow/core/runtime_fallback/kernel/kernel_fallback_execute_compat.h"
#include "tensorflow/core/runtime_fallback/runtime/kernel_utils.h"
#include "tensorflow/core/tfrt/utils/fallback_tensor.h"
#include "tfrt/bef_converter/mlir_to_bef.h" // from @tf_runtime
#include "tfrt/bef_executor/bef_file.h" // from @tf_runtime
#include "tfrt/host_context/execution_context.h" // from @tf_runtime
#include "tfrt/host_context/function.h" // from @tf_runtime
#include "tfrt/host_context/resource_context.h" // from @tf_runtime
namespace tensorflow {
using ::tfrt::ArrayRef;
using ::tfrt::AsyncValue;
using ::tfrt::AsyncValuePtr;
using ::tfrt::BEFFile;
using ::tfrt::ExecutionContext;
using ::tfrt::Function;
using ::tfrt::HostContext;
using ::tfrt::MakeAvailableAsyncValueRef;
using ::tfrt::RCReference;
using ::tfrt::RemainingResults;
using ::tfrt::RequestContext;
using ::tfrt::RequestContextBuilder;
using ::tfrt::ResourceContext;
using ::tfrt::cpu::jit::Executable;
using ::tfrt::cpu::jit::JitExecutable;
using ::tfrt::cpu::jit::MemrefDesc;
using ::tfrt::cpu::jit::ReturnValueConverter;
using ::tensorflow::Env;
using ::tensorflow::thread::ThreadPool;
using ::tensorflow::thread::ThreadPoolInterface;
using ::tensorflow::tfrt_stub::FallbackTensor;
// Returns random tensors generated based on the input specs.
static llvm::SmallVector<Tensor> GetInputTensors(
llvm::ArrayRef<InputTensorSpec> input_specs) {
llvm::SmallVector<Tensor> input_tensors;
for (const InputTensorSpec& spec : input_specs) {
TensorShape shape;
CHECK(TensorShapeUtils::MakeShape(spec.dims, &shape).ok());
input_tensors.emplace_back(spec.dtype, shape);
// Initialize tensors with random data.
switch (spec.dtype) {
case DT_FLOAT:
input_tensors.back().flat<float>().setRandom();
break;
case DT_INT64:
input_tensors.back().flat<int64_t>().setRandom();
break;
default:
CHECK(false) << "Unsupported dtype: " << spec.dtype;
}
}
return input_tensors;
}
// -------------------------------------------------------------------------- //
// Run function benchmark via the TF CPURT compilation.
// -------------------------------------------------------------------------- //
void RunCpurtBenchmark(::testing::benchmark::State& state,
llvm::StringRef mlir_input,
llvm::StringRef function_name,
llvm::ArrayRef<InputTensorSpec> input_specs,
bool vectorize) {
// Number of worker threads.
int64_t num_threads = state.range(0);
// Host context for running compute tasks.
std::unique_ptr<HostContext> host =
num_threads > 0 ? CreateMultiThreadedHostContext(num_threads)
: CreateSingleThreadedHostContext();
TfCpuRtPipelineOptions tf_cpurt_opts;
tf_cpurt_opts.vectorize = vectorize;
JitExecutable& jit_executable =
CreateJitExecutable(*host, mlir_input, function_name,
/*lower_from_tensorflow=*/true, tf_cpurt_opts);
// Build an ExecutionContext from the HostContext.
llvm::Expected<RCReference<RequestContext>> req_ctx =
RequestContextBuilder(host.get(), /*resource_context=*/nullptr).build();
tfrt::ExecutionContext exec_ctx(std::move(*req_ctx));
// Generate random inputs based on the tensor specs.
llvm::SmallVector<Tensor> input_tensors = GetInputTensors(input_specs);
// Convert input tensors to memref descriptors.
llvm::SmallVector<MemrefDesc> operands;
for (const Tensor& tensor : input_tensors)
operands.emplace_back(TensorToMemrefDesc(tensor));
// Get an executable that might be specialized to the operands.
llvm::Expected<AsyncValuePtr<Executable>> executable =
jit_executable.GetExecutable(operands, exec_ctx);
if (auto err = executable.takeError())
LOG(FATAL) << "Failed to specialize executable: " << tfrt::StrCat(err);
// Wait for the compilation completion.
host->Await({executable->CopyRef()});
CHECK(!executable->IsError())
<< "Failed to get executable: " << tfrt::StrCat(executable->GetError());
CHECK(!(*executable)->IsAsync()) << "async results are not supported";
// Placeholders for returned values.
unsigned num_results = (*executable)->num_results();
llvm::SmallVector<RCReference<AsyncValue>> result_values(num_results);
RemainingResults results(result_values);
// Free memory owned by the returned memrefs.
ReturnValueConverter<ResultConversionCtx> converter(results);
converter.AddConversion(FreeReturnedMemref);
// Initialize call frame with MemrefDesc operands.
Executable::CallFrame call_frame;
if (auto err = (*executable)->InitializeCallFrame(operands, &call_frame))
LOG(FATAL) << "Failed to initialize call frame";
for (auto _ : state) {
call_frame.args[0] = nullptr; // reset kernel context argument
(*executable)->Execute(call_frame, exec_ctx);
if (auto err =
(*executable)->ReturnResults(converter, exec_ctx, &call_frame))
LOG(FATAL) << "Failed to return compiled kernel results";
}
}
// -------------------------------------------------------------------------- //
// Run function benchmark via the TF->TFRT fallback lowering.
// -------------------------------------------------------------------------- //
// Thread pool for running `intra-op` tasks scheduled by the fallback kernels.
class IntraOpTheadPool : public ThreadPoolInterface {
public:
explicit IntraOpTheadPool(int num_threads)
: tpool_(Env::Default(), "intra-op", std::max(1, num_threads)) {}
void Schedule(std::function<void()> fn) override {
tpool_.Schedule(std::move(fn));
}
int NumThreads() const override { return tpool_.NumThreads(); }
int CurrentThreadId() const override { return tpool_.CurrentThreadId(); }
void Cancel() override {}
private:
ThreadPool tpool_;
};
// Run TFRT fallback initialization function to instantiate all fallback
// kernels ahead of executing the compute function.
static void RunTfrtInitializer(const ExecutionContext& exec_ctx,
BEFFile* bef_file,
llvm::StringRef fallback_init_func) {
const Function* func = bef_file->GetFunction(fallback_init_func);
CHECK(func) << "TFRT initialization function was not found";
CHECK_EQ(func->argument_types().size(), 1);
llvm::SmallVector<RCReference<AsyncValue>, 1> results;
results.resize(func->result_types().size());
CHECK_EQ(results.size(), 1);
func->Execute(exec_ctx, tfrt::GetReadyChain().GetAsyncValue(), results);
HostContext* host = exec_ctx.host();
host->Await(results);
CHECK(!results[0]->IsError()) << "Failed to run TFRT initialization function";
}
void RunTfrtBenchmark(::testing::benchmark::State& state,
llvm::StringRef mlir_input, llvm::StringRef function_name,
ArrayRef<InputTensorSpec> input_specs) {
// Number of worker threads (intra-op concurrency for the fallback ops).
int64_t num_threads = state.range(0);
// We only support benchmarks written in the Tensorflow dialect.
mlir::DialectRegistry registry;
mlir::RegisterAllTensorFlowDialects(registry);
mlir::MLIRContext context(registry);
llvm::SourceMgr source_mgr;
source_mgr.AddNewSourceBuffer(
llvm::MemoryBuffer::getMemBuffer(mlir_input, "benchmark"), llvm::SMLoc());
// Parse a kernel source code into the MLIR Module.
mlir::OwningModuleRef module(mlir::parseSourceFile(source_mgr, &context));
CHECK(module) << "failed to parse mlir module";
// Collect all diagnostics emitted while lowering parsed kernel module.
std::string diagnostic_str;
llvm::raw_string_ostream os(diagnostic_str);
mlir::SourceMgrDiagnosticHandler handler(source_mgr, module->getContext(),
os);
// Convert TF to TFRT fallback dialect.
TfrtPipelineOptions core_rt_opts;
core_rt_opts.hoist_invariant_ops = true;
core_rt_opts.enable_native_ops = false;
core_rt_opts.cost_threshold = 1024;
core_rt_opts.upper_cost_threshold = 100000;
core_rt_opts.merge_inter_dependent_streams = true;
core_rt_opts.func_use_fallback_tensor = true;
mlir::PassManager pm(module->getContext());
pm.addPass(CreateTfToTfrtConversionPass(core_rt_opts));
CHECK(mlir::succeeded(pm.run(*module)))
<< "Failed to lower module to TFRT: " << os.str();
// Create a thread pool for running intra-op tasks.
IntraOpTheadPool intra_op(num_threads);
// Create a HostContext for running TFRT functions. Concurrent work queue acts
// similar to the Tensorflow `inter-op` thread pool, so we'll match the size.
auto host = num_threads ? CreateMultiThreadedHostContext(num_threads)
: CreateSingleThreadedHostContext();
tfrt::RegisterStaticKernels(host->GetMutableRegistry());
// Convert module to BEF.
auto bef_buffer =
tfrt::ConvertMLIRToBEF(*module, /*disable_optional_sections=*/false);
CHECK(!bef_buffer.empty()) << "Failed to convert module to BEF";
// Build an ExecutionContext from the HostContext.
ResourceContext resource_context;
auto builder = RequestContextBuilder(host.get(), &resource_context);
// Get tensorflow::EagerContext for the kernel fallback.
auto* eager_context_resource =
resource_context
.GetOrCreateResource<tensorflow::tfd::EagerContextResource>(
tensorflow::tfd::kEagerContextResourceName);
auto expected_eager_context = eager_context_resource->GetTFEagerContext();
auto* eager_context = expected_eager_context.get();
// Initialize fallback kernels state with a custom intra-op thread pool.
auto status = tensorflow::tfd::SetUpKernelFallbackCompatRequestContext(
&builder, /*runner_table=*/nullptr, eager_context, &intra_op);
CHECK(status.ok()) << "Failed to setup request context: "
<< status.error_message();
auto req_ctx = std::move(builder).build();
if (auto err = req_ctx.takeError())
LOG(FATAL) << "Failed to build a request context";
ExecutionContext exec_ctx(std::move(*req_ctx));
auto bef_file = BEFFile::Open(bef_buffer, host->GetKernelRegistry(),
host->diag_handler(), host->allocator());
CHECK(bef_file) << "Failed to open BEF";
// Run TFRT initialization function to pre-instantiate fallback kernels.
RunTfrtInitializer(exec_ctx, bef_file.get(), "_tfrt_fallback_init");
// Get the kernel entrypoint function.
const Function* compute = bef_file->GetFunction(function_name);
CHECK(compute) << "Entrypoint function not found";
// Generate random inputs based on the tensor specs.
llvm::SmallVector<Tensor> input_tensors = GetInputTensors(input_specs);
// Prepare function arguments from ready Chain and input Tensors.
llvm::SmallVector<AsyncValue*> arguments;
arguments.push_back(tfrt::GetReadyChain().release());
for (const Tensor& input_tensor : input_tensors) {
auto av = MakeAvailableAsyncValueRef<FallbackTensor>(input_tensor);
arguments.push_back(av.release());
}
// Space for returned values.
llvm::SmallVector<RCReference<AsyncValue>> results;
for (auto _ : state) {
// Reset results in preparation for the function call.
results.clear();
results.resize(compute->result_types().size());
compute->Execute(exec_ctx, arguments, results);
// Wait for the function execution to finish, as well as the side-effects.
host->Await(results);
// First result is always a chain, check if it has error.
if (auto* error = results[0]->GetErrorIfPresent())
LOG(FATAL) << "Failed to execute a function";
}
// Deallocate arguments.
for (auto* argument : arguments) argument->DropRef();
}
// -------------------------------------------------------------------------- //
// Run arbitrary benchark written as a function.
// -------------------------------------------------------------------------- //
void RunEigenBenchmark(
::testing::benchmark::State& state,
std::function<void(llvm::ArrayRef<Tensor>,
llvm::Optional<Eigen::ThreadPoolDevice>)>
compute,
llvm::ArrayRef<InputTensorSpec> input_specs) {
// Number of worker threads.
int64_t num_threads = state.range(0);
// Maybe construct an Eigen thread pool device for evaluating expressions.
Eigen::ThreadPool thread_pool(num_threads);
llvm::Optional<Eigen::ThreadPoolDevice> device;
if (num_threads > 0) device.emplace(&thread_pool, num_threads);
// Generate random inputs based on the tensor specs.
llvm::SmallVector<Tensor> input_tensors = GetInputTensors(input_specs);
// Call the user defined compute function.
for (auto _ : state) {
compute(input_tensors, device);
}
}
} // namespace tensorflow
<|endoftext|> |
<commit_before>//
// replace.cpp
//
// replaces one or many strings that match a given regular expression in any
// files that match the file regular expression.
//
// Created by Daniel Kozitza
//
#include <csignal>
#include <cstdlib>
#include <dirent.h>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sys/ioctl.h>
#include "tools.hpp"
#include "sorters.hpp"
using namespace tools;
//typedef map<string, string>::iterator map_iter;
void help(string prog_name);
int main(int argc, char *argv[]) {
string file_regex, match_regex, replacement;
string dir_path = ".";
string prog_name = string(argv[0]);
bool all = false;
bool recursive = false;
replace_first(prog_name, "^.*/", "");
if (argc < 4) {
help(prog_name);
return 0;
}
signal(SIGINT, signals_callback_handler);
struct winsize ws;
ioctl(0, TIOCGWINSZ, &ws);
// get options
int total_opts = 0;
for (int i = 0; i < argc - 3; ++i) {
if (argv[i][0] == '-') {
int opt_cnt = 1;
while (argv[i][opt_cnt] != '\0') {
switch (argv[i][opt_cnt]) {
case 'a': all = true; break;
case 'r': recursive = true; break;
}
opt_cnt++;
}
total_opts++;
}
}
if (total_opts + 4 != argc) {
cout << prog_name << ": invalid argument sequence\n";
cout << "total_opts: " << total_opts << " argc: " << argc << "\n";
help(prog_name);
return 0;
}
// get arguments
file_regex = string(argv[argc - 3]);
match_regex = string(argv[argc - 2]);
replacement = string(argv[argc - 1]);
cout << "got here 1!\nall: " << all << " recursive: " << recursive;
cout << "\nfile_regex: " << file_regex << " match_regex: " << match_regex;
cout << " replacement: " << replacement << "\n";
// get dir_path
// dir_path is the directory of the file which matches file_regex. If
// file_regex begins with a / then the path is ^(.*/)(real_regex)$.
string m[3];
if (file_regex[0] == '/') {
if (pmatches(m, file_regex, "^(.*/)([^/]+)$")) {
dir_path = m[1];
file_regex = m[2];
}
else {
cerr << prog_name << ": Internal error! Could not find directory path";
cerr << ".\n";
return 1;
}
}
else if (pmatches(m, file_regex, "^(.*/)([^/]+)$")) {
dir_path = m[1];
file_regex = m[2];
}
cout << "\ngot here 2! ";
cout << "dir_path: " << dir_path << " file_regex: " << file_regex << "\n";
vector<string> files;
if (recursive) {
if (!list_dir_r(dir_path, files)) {
cerr << prog_name << ": Could not open directory path `" << dir_path;
cerr << "`.\n";
return 1;
}
}
else {
if (!list_dir(dir_path, files)) {
cerr << prog_name << ": Could not open directory path `" << dir_path;
cerr << "`.\n";
return 1;
}
}
// loop through files removing directories and prefixing dir_path to file
// names in files.
vector<string> new_files;
for (size_t i = 0; i < files.size(); ++i)
if (!dir_exists(dir_path + files[i]))
new_files.push_back(dir_path + files[i]);
files = new_files;
cout << "finished files list:\n";
for (size_t i = 0; i < new_files.size(); ++i)
cout << new_files[i] << "\n";
cout << "\n";
// loop through files finding match_regex matches and replacing them with
// replacement on each line of each file.
for (size_t i = 0; i < files.size(); ++i) {
vector<string> contents; // used to store replacement contents of files
// open the file for reading
cout << "replace: opening file `" << files[i] << "` for reading.\n";
ifstream ifh;
ifh.open(files[i].c_str());
if (!ifh.is_open()) {
cerr << "replace: couldn't open `" << files[i] << "` for reading.\n";
return 1;
}
// replace all or first of the matches on each line
long replaced = 0;
while (ifh.peek() != EOF) {
string line;
getline(ifh, line);
if (all) {
if (replace_all(line, match_regex, replacement))
replaced++;
}
else if (replaced == 0) {
if (replace_first(line, match_regex, replacement))
replaced++;
}
contents.push_back(line);
}
ifh.close();
cout << "replaced: " << replaced << "\n";
// skip writing over files[i] if there are no changes
if (replaced == 0)
continue;
// open the file for writing
cout << "replace: opening file `" << files[i] << "` for writing.\n";
ofstream ofh;
string tmpfilename = files[i];
tmpfilename += "_tmp";
ofh.open(tmpfilename.c_str());
if (!ofh.is_open()) {
cerr << "replace: couldn't open `" << tmpfilename;
cerr << "` for writing.\n";
return 1;
}
for (size_t i = 0; i < contents.size(); ++i) {
contents[i] += "\n";
ofh.write(contents[i].c_str(), contents[i].size());
}
ofh.close();
} // end of files loop
return 0;
}
void help(string p_name) {
cout << "\n" << p_name;
cout << " is a tool for replacing strings with other strings";
cout << " in one or more files.\n\n";
cout << "Usage:\n\n replace [-ar] file_regex match_regex replacement\n\n";
}
//void cnt() {
// map<string, string> vfnconf;
// vector<string> contents;
// unsigned int total_lines = 0;
// string src_dir;
//
// if (get_vfnmkmc_conf(vfnconf))
// src_dir = vfnconf["src_directory"];
// else
// src_dir = ".";
//
// if (!list_dir_r(src_dir, contents)) {
// cerr << "mc::cnt: vfnmkmc src_directory `" + src_dir;
// cerr << "` does not exist\n";
// return;
// }
//
// vector<string> new_contents;
// for (int i = 0; i < contents.size(); ++i) {
// if (pmatches(contents[i], "(\\.cpp|\\.c|\\.hpp|\\.h)$")) {
// new_contents.push_back(contents[i]);
// }
// }
// contents = new_contents;
// new_contents.clear();
//
// int longest = 0;
// for (int i = 0; i < contents.size(); ++i) {
// string fname = src_dir + "/" + contents[i];
// if (fname.size() > longest)
// longest = fname.size() + 1;
// }
//
// sorters::radix(contents);
//
// ifstream fh;
// for (int i = 0; i < contents.size(); ++i) {
// string fname = src_dir + "/" + contents[i];
//
// fh.open(fname.c_str(), ifstream::in);
// if (!fh.is_open()) {
// cout << "mc::cnt: could not open file: `" << fname << "`\n";
// continue;
// }
//
// char c;
// int file_lines = 0;
// while (fh.peek() != EOF) {
// fh.get(c);
// if (c == '\n')
// ++file_lines;
// }
// fh.close();
// total_lines += file_lines;
//
// fname += ":";
// cout << left << setw(longest) << fname;
// cout << " " << file_lines << endl;
// }
//
// cout << endl << left << setw(longest) << "total_loc:";
// cout << " " << total_lines << "\n\n";
//}
<commit_msg>added -q option and fixed output<commit_after>//
// replace.cpp
//
// replaces one or many strings that match a given regular expression in any
// files that match the file regular expression.
//
// Created by Daniel Kozitza
//
#include <csignal>
#include <cstdlib>
#include <dirent.h>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sys/ioctl.h>
#include "tools.hpp"
#include "sorters.hpp"
using namespace tools;
//typedef map<string, string>::iterator map_iter;
void help(string prog_name);
int main(int argc, char *argv[]) {
string file_regex, match_regex, replacement;
string dir_path = ".";
string prog_name = string(argv[0]);
bool all = false;
bool recursive = false;
bool quiet = false;
long total_replaced = 0;
replace_first(prog_name, "^.*/", "");
if (argc < 4) {
help(prog_name);
return 0;
}
signal(SIGINT, signals_callback_handler);
struct winsize ws;
ioctl(0, TIOCGWINSZ, &ws);
// get options
int total_opts = 0;
for (int i = 0; i < argc - 3; ++i) {
if (argv[i][0] == '-') {
int opt_cnt = 1;
while (argv[i][opt_cnt] != '\0') {
switch (argv[i][opt_cnt]) {
case 'a': all = true; break;
case 'r': recursive = true; break;
case 'q': quiet = true; break;
}
opt_cnt++;
}
total_opts++;
}
}
if (total_opts + 4 != argc) {
cout << prog_name << ": invalid argument sequence\n";
cout << "total_opts: " << total_opts << " argc: " << argc << "\n";
help(prog_name);
return 0;
}
// get arguments
file_regex = string(argv[argc - 3]);
match_regex = string(argv[argc - 2]);
replacement = string(argv[argc - 1]);
// get dir_path
// dir_path is the directory of the file which matches file_regex. If
// file_regex begins with a / then the path is ^(.*/)(real_regex)$.
string m[3];
if (file_regex[0] == '/') {
if (pmatches(m, file_regex, "^(.*/)([^/]+)$")) {
dir_path = m[1];
file_regex = m[2];
}
else {
cerr << prog_name << ": Internal error! Could not find directory path";
cerr << ".\n";
return 1;
}
}
else if (pmatches(m, file_regex, "^(.*/)([^/]+)$")) {
dir_path = m[1];
file_regex = m[2];
}
if (!quiet) {
cout << "\n" << prog_name << ": searching directory: " << dir_path;
cout << " for file_regex: " << file_regex << "\n\n";
}
vector<string> files;
if (recursive) {
if (!list_dir_r(dir_path, files)) {
cerr << prog_name << ": Could not open directory path `" << dir_path;
cerr << "`.\n";
return 1;
}
}
else {
if (!list_dir(dir_path, files)) {
cerr << prog_name << ": Could not open directory path `" << dir_path;
cerr << "`.\n";
return 1;
}
}
// TODO: ignore binary files
//
// loop through files removing directories and prefixing dir_path to file
// names in files.
vector<string> new_files;
for (size_t i = 0; i < files.size(); ++i)
if (!dir_exists(dir_path + files[i]))
new_files.push_back(dir_path + files[i]);
files = new_files;
if (!quiet) {
cout << " file name";
cout << " lines replaced\n";
}
// loop through files finding match_regex matches and replacing them with
// replacement on each line of each file.
for (size_t i = 0; i < files.size(); ++i) {
vector<string> contents; // used to store replacement contents of files
//if (!quiet)
// cout << "replace: opening file `" << files[i] << "` for reading.\n";
ifstream ifh;
ifh.open(files[i].c_str());
if (!ifh.is_open()) {
cerr << "replace: couldn't open `" << files[i] << "` for reading.\n";
return 1;
}
// replace all of the matches on each line or replace the first match in
// the file
long replaced = 0;
while (ifh.peek() != EOF) {
string line;
getline(ifh, line);
if (all) {
if (replace_all(line, match_regex, replacement))
replaced++;
}
else if (replaced == 0) {
if (replace_first(line, match_regex, replacement))
replaced++;
}
contents.push_back(line);
}
ifh.close();
if (!quiet) {
cout << left << setw(60) << files[i];
cout << " " << replaced << "\n";
}
// skip writing over files[i] if there are no changes
if (replaced == 0)
continue;
//if (!quiet)
// cout << "replace: opening file `" << files[i] << "_tmp` for writing.\n";
ofstream ofh;
string tmpfilename = files[i];
tmpfilename += "_tmp";
ofh.open(tmpfilename.c_str());
if (!ofh.is_open()) {
cerr << "replace: couldn't open `" << tmpfilename;
cerr << "` for writing.\n";
return 1;
}
for (size_t i = 0; i < contents.size(); ++i) {
contents[i] += "\n";
ofh.write(contents[i].c_str(), contents[i].size());
}
ofh.close();
total_replaced += replaced;
} // end of files loop
if (!quiet) {
cout << "\n" << prog_name << ": total lines replaced: ";
cout << total_replaced << "\n\n";
}
return 0;
}
void help(string p_name) {
cout << "\n" << p_name;
cout << " is a tool for replacing strings with other strings";
cout << " in one or more files.\n\n";
cout << "Usage:\n\n replace [-ar] file_regex match_regex replacement\n\n";
}
//void cnt() {
// map<string, string> vfnconf;
// vector<string> contents;
// unsigned int total_lines = 0;
// string src_dir;
//
// if (get_vfnmkmc_conf(vfnconf))
// src_dir = vfnconf["src_directory"];
// else
// src_dir = ".";
//
// if (!list_dir_r(src_dir, contents)) {
// cerr << "mc::cnt: vfnmkmc src_directory `" + src_dir;
// cerr << "` does not exist\n";
// return;
// }
//
// vector<string> new_contents;
// for (int i = 0; i < contents.size(); ++i) {
// if (pmatches(contents[i], "(\\.cpp|\\.c|\\.hpp|\\.h)$")) {
// new_contents.push_back(contents[i]);
// }
// }
// contents = new_contents;
// new_contents.clear();
//
// int longest = 0;
// for (int i = 0; i < contents.size(); ++i) {
// string fname = src_dir + "/" + contents[i];
// if (fname.size() > longest)
// longest = fname.size() + 1;
// }
//
// sorters::radix(contents);
//
// ifstream fh;
// for (int i = 0; i < contents.size(); ++i) {
// string fname = src_dir + "/" + contents[i];
//
// fh.open(fname.c_str(), ifstream::in);
// if (!fh.is_open()) {
// cout << "mc::cnt: could not open file: `" << fname << "`\n";
// continue;
// }
//
// char c;
// int file_lines = 0;
// while (fh.peek() != EOF) {
// fh.get(c);
// if (c == '\n')
// ++file_lines;
// }
// fh.close();
// total_lines += file_lines;
//
// fname += ":";
// cout << left << setw(longest) << fname;
// cout << " " << file_lines << endl;
// }
//
// cout << endl << left << setw(longest) << "total_loc:";
// cout << " " << total_lines << "\n\n";
//}
<|endoftext|> |
<commit_before>#include "camera.h"
#include <iostream>
#include "glm/gtc/type_ptr.hpp"
#include <glm/gtx/transform.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include "glm/gtx/matrix_decompose.hpp"
#include <cfloat>
Camera::Camera()
: m_rotation( 0.0, 0.0, 0.0 ),
m_scale( 1.0, 1.0, 1.0 ),
m_translation( 0.0, 0.0, 2.0),
m_point_of_interest( 90.0 ),
m_fov_y( 45.0 ),
m_clip( 0.1, 1000.0 ),
m_overscan(.98),
m_image_size(1920, 1080),
m_viewport_size(720, 405)
{
lookAt(m_translation, glm::vec3(0,0,0));
}
static inline void anglesToAxes(const glm::vec3 angles, glm::vec3 & left, glm::vec3 & up, glm::vec3& forward)
{
const float DEG2RAD = 3.141593f / 180;
float sx, sy, sz, cx, cy, cz, theta;
// rotation angle about X-axis (pitch)
theta = angles.x * DEG2RAD;
sx = sinf(theta);
cx = cosf(theta);
// rotation angle about Y-axis (yaw)
theta = angles.y * DEG2RAD;
sy = sinf(theta);
cy = cosf(theta);
// rotation angle about Z-axis (roll)
theta = angles.z * DEG2RAD;
sz = sinf(theta);
cz = cosf(theta);
// determine left axis
left.x = cy*cz;
left.y = sx*sy*cz + cx*sz;
left.z = -cx*sy*cz + sx*sz;
// determine up axis
up.x = -cy*sz;
up.y = -sx*sy*sz + cx*cz;
up.z = cx*sy*sz + sx*cz;
// determine forward axis
forward.x = sy;
forward.y = -sx*cy;
forward.z = cx*cy;
}
static inline void rotateVector( float rx, float ry, glm::vec3 &v )
{
v = glm::rotate(v, glm::radians(rx), glm::vec3(1.0f, 0.0f, 0.0f));
v = glm::rotate(v, glm::radians(ry), glm::vec3(0.0f, 1.0f, 0.0f));
}
const glm::mat4 Camera::viewMatrix()
{
glm::mat4 m;
m *= glm::scale(glm::vec3(1,1,1) / m_scale);
m *= glm::rotate(-glm::radians(m_rotation.x) , glm::vec3(1,0,0));
m *= glm::rotate(-glm::radians(m_rotation.y) , glm::vec3(0,1,0));
m *= glm::rotate(-glm::radians(m_rotation.z) , glm::vec3(0,0,1));
m *= glm::translate( -m_translation);
return m;
}
const glm::mat4 Camera::projectionMatrix()
{
float aspect = m_image_size.x / m_image_size.y;
glm::mat4 m = glm::perspective(float(glm::radians(m_fov_y)),
aspect, m_clip.x, m_clip.y);
return m;
}
const glm::mat4 Camera::viewportMatrix()
{
float sx = 1;
float sy = 1;
float image_aspect = m_image_size.x / m_image_size.y;
float viewport_aspect = m_viewport_size.x / m_viewport_size.y;
if (image_aspect < viewport_aspect)
sx = m_viewport_size.y * m_image_size.x / m_image_size.y / m_viewport_size.x;
else
sy = m_viewport_size.x * m_image_size.y / m_image_size.x / m_viewport_size.y;
glm::mat4 m;
m *= glm::scale(glm::vec3(sx,sy, 1 ));
m *= glm::scale(glm::vec3(m_overscan, m_overscan, 1));
return m;
}
void Camera::forward(float amount)
{
float rotX = m_rotation.x;
float rotY = m_rotation.y;
glm::vec3 v (0.0, 0.0, -m_point_of_interest);
rotateVector( rotX, rotY, v);
m_translation += v * amount;
}
void Camera::right(float amount)
{
pan(glm::vec2(200,0) * -amount);
}
void Camera::up(float amount)
{
pan(glm::vec2(0,200) * amount);
}
void Camera::lookAt(const glm::vec3 &eye, const glm::vec3 &at)
{
m_translation = eye;
glm::vec3 dt = at - eye;
double xzLen = sqrt( (dt.x * dt.x) + (dt.z * dt.z));
m_rotation.x = glm::degrees(atan2(dt.y, xzLen));
m_rotation.y = glm::degrees(atan2(dt.x, -dt.z));
m_point_of_interest = glm::length(dt);
}
void Camera::pan(const glm::vec2 &point)
{
float rotX = m_rotation.x;
float rotY = m_rotation.y;
glm::vec3 dS( 1.0, 0.0, 0.0);
rotateVector(rotX, rotY, dS);
glm::vec3 dT( 0.0, 1.0, 0.0);
rotateVector( rotX, rotY, dT );
float multS = 2.0 * m_point_of_interest * tanf( glm::radians( fovy() ) / 2.0 );
const float multT = multS / float( m_viewport_size.y );
multS /= float( m_viewport_size.x );
const float s = -multS * point.x;
const float t = multT * point.y;
setTranslation( (m_translation +
( s * dS ) + ( t * dT ) ) );
}
void Camera::dolly(const glm::vec2 &point, double dollySpeed)
{
float rotX = m_rotation.x;
float rotY = m_rotation.y;
const glm::vec3 &eye = m_translation;
glm::vec3 v (0.0, 0.0, -m_point_of_interest);
rotateVector( rotX, rotY, v);
glm::vec3 view = eye + v;
v = glm::normalize(v);
double t = point.x / double(m_viewport_size.x);
float dollyBy = 1.0 - expf( -dollySpeed * t);
//float dollyBy = dollySpeed * t;
if (dollyBy > 1.0) {
dollyBy = 1.0;
} else if (dollyBy < -1.0) {
dollyBy = -1.0;
}
dollyBy *= m_point_of_interest;
glm::vec3 new_eye = eye + (dollyBy *v);
setTranslation(new_eye);
v = new_eye - view;
m_point_of_interest = glm::length(v);
}
void Camera::rotate(const glm::vec2 &point, double rotateSpeed)
{
double rotX = m_rotation.x;
double rotY = m_rotation.y;
const float rotZ = m_rotation.z;
glm::vec3 eye = m_translation;
glm::vec3 v(0.0f, 0.0f, -m_point_of_interest);
rotateVector(rotX, rotY, v);
const glm::vec3 view = eye + v;
rotY += -rotateSpeed * ( point.x / double( m_viewport_size.x ) );
rotX += -rotateSpeed * ( point.y / double( m_viewport_size.y ) );
v.x = 0.0f;
v.y = 0.0f;
v.z = m_point_of_interest;
rotateVector(rotX, rotY, v);
const glm::vec3 new_eye = view + v;
setTranslation(new_eye);
setRotation(glm::vec3( rotX, rotY, rotZ ) );
}
void Camera::auto_clipping_plane( const Imath::Box3d &bounds)
{
const double rotX = m_rotation.x;
const double rotY = m_rotation.y;
const glm::vec3 eye = m_translation;
double clipNear = FLT_MAX;
double clipFar = FLT_MIN;
glm::vec3 v(0.0, 0.0, -m_point_of_interest);
rotateVector(rotX, rotY, v);
const glm::vec3 view = eye + v;
v = glm::normalize(v);
glm::vec3 points[8];
points[0] = glm::vec3(bounds.min.x, bounds.min.y, bounds.min.z);
points[1] = glm::vec3(bounds.min.x, bounds.min.y, bounds.max.z);
points[2] = glm::vec3(bounds.min.x, bounds.max.y, bounds.min.z);
points[3] = glm::vec3(bounds.min.x, bounds.max.y, bounds.max.z);
points[4] = glm::vec3(bounds.max.x, bounds.min.y, bounds.min.z);
points[5] = glm::vec3(bounds.max.x, bounds.min.y, bounds.max.z);
points[6] = glm::vec3(bounds.max.x, bounds.max.y, bounds.min.z);
points[7] = glm::vec3(bounds.max.x, bounds.max.y, bounds.max.z);
for( int p = 0; p < 8; ++p )
{
glm::vec3 dp = points[p] - eye;
double proj = glm::dot(dp, v);
clipNear = std::min(proj, clipNear);
clipFar = std::max(proj, clipFar);
}
clipNear -= 0.5f;
clipFar += 0.5f;
clipNear = glm::clamp(clipNear, 0.1, 100000.0);
clipFar = glm::clamp(clipFar, 0.1, 100000.0);
if (clipFar <= clipNear) {
clipFar = clipNear + 0.1;
}
m_clip.x = clipNear;
m_clip.y = clipFar;
}
<commit_msg>quick camara hack<commit_after>#include "camera.h"
#include <iostream>
#include "glm/gtc/type_ptr.hpp"
#include <glm/gtx/transform.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include "glm/gtx/matrix_decompose.hpp"
#include <cfloat>
Camera::Camera()
: m_rotation( 0.0, 0.0, 0.0 ),
m_scale( 1.0, 1.0, 1.0 ),
m_translation( 0.0, 0.0, 2.0),
m_point_of_interest( 90.0 ),
m_fov_y( 45.0 ),
m_clip( 0.1, 1000.0 ),
m_overscan(.98),
m_image_size(1920, 1080),
m_viewport_size(720, 405)
{
lookAt(m_translation, glm::vec3(0,0,0));
}
static inline void anglesToAxes(const glm::vec3 angles, glm::vec3 & left, glm::vec3 & up, glm::vec3& forward)
{
const float DEG2RAD = 3.141593f / 180;
float sx, sy, sz, cx, cy, cz, theta;
// rotation angle about X-axis (pitch)
theta = angles.x * DEG2RAD;
sx = sinf(theta);
cx = cosf(theta);
// rotation angle about Y-axis (yaw)
theta = angles.y * DEG2RAD;
sy = sinf(theta);
cy = cosf(theta);
// rotation angle about Z-axis (roll)
theta = angles.z * DEG2RAD;
sz = sinf(theta);
cz = cosf(theta);
// determine left axis
left.x = cy*cz;
left.y = sx*sy*cz + cx*sz;
left.z = -cx*sy*cz + sx*sz;
// determine up axis
up.x = -cy*sz;
up.y = -sx*sy*sz + cx*cz;
up.z = cx*sy*sz + sx*cz;
// determine forward axis
forward.x = sy;
forward.y = -sx*cy;
forward.z = cx*cy;
}
static inline void rotateVector( float rx, float ry, glm::vec3 &v )
{
v = glm::rotate(v, glm::radians(rx), glm::vec3(1.0f, 0.0f, 0.0f));
v = glm::rotate(v, glm::radians(ry), glm::vec3(0.0f, 1.0f, 0.0f));
}
const glm::mat4 Camera::viewMatrix()
{
glm::mat4 m;
m *= glm::scale(glm::vec3(1,1,1) / m_scale);
m *= glm::rotate(-glm::radians(m_rotation.x) , glm::vec3(1,0,0));
m *= glm::rotate(-glm::radians(m_rotation.y) , glm::vec3(0,1,0));
m *= glm::rotate(-glm::radians(m_rotation.z) , glm::vec3(0,0,1));
m *= glm::translate( -m_translation);
return m;
}
const glm::mat4 Camera::projectionMatrix()
{
float aspect = m_image_size.x / m_image_size.y;
glm::mat4 m = glm::perspective(float(glm::radians(m_fov_y)),
aspect, m_clip.x, m_clip.y);
return m;
}
const glm::mat4 Camera::viewportMatrix()
{
float sx = 1;
float sy = 1;
float image_aspect = m_image_size.x / m_image_size.y;
float viewport_aspect = m_viewport_size.x / m_viewport_size.y;
if (image_aspect < viewport_aspect)
sx = m_viewport_size.y * m_image_size.x / m_image_size.y / m_viewport_size.x;
else
sy = m_viewport_size.x * m_image_size.y / m_image_size.x / m_viewport_size.y;
glm::mat4 m;
m *= glm::scale(glm::vec3(sx,sy, 1 ));
m *= glm::scale(glm::vec3(m_overscan, m_overscan, 1));
return m;
}
void Camera::forward(float amount)
{
float rotX = m_rotation.x;
float rotY = m_rotation.y;
glm::vec3 v (0.0, 0.0, -m_point_of_interest);
rotateVector( rotX, rotY, v);
m_translation += v * amount;
}
void Camera::right(float amount)
{
pan(glm::vec2(200,0) * -amount);
}
void Camera::up(float amount)
{
pan(glm::vec2(0,200) * amount);
}
void Camera::lookAt(const glm::vec3 &eye, const glm::vec3 &at)
{
m_translation = eye;
glm::vec3 dt = at - eye;
double xzLen = sqrt( (dt.x * dt.x) + (dt.z * dt.z));
m_rotation.x = glm::degrees(atan2(dt.y, xzLen));
m_rotation.y = glm::degrees(atan2(dt.x, -dt.z));
m_point_of_interest = glm::length(dt);
}
void Camera::pan(const glm::vec2 &point)
{
float rotX = m_rotation.x;
float rotY = m_rotation.y;
glm::vec3 dS( 1.0, 0.0, 0.0);
rotateVector(rotX, rotY, dS);
glm::vec3 dT( 0.0, 1.0, 0.0);
rotateVector( rotX, rotY, dT );
float multS = 2.0 * m_point_of_interest * tanf( glm::radians( fovy() ) / 2.0 );
const float multT = multS / float( m_viewport_size.y );
multS /= float( m_viewport_size.x );
const float s = -multS * point.x;
const float t = multT * point.y;
setTranslation( (m_translation +
( s * dS ) + ( t * dT ) ) );
}
void Camera::dolly(const glm::vec2 &point, double dollySpeed)
{
float rotX = m_rotation.x;
float rotY = m_rotation.y;
const glm::vec3 &eye = m_translation;
glm::vec3 v (0.0, 0.0, -m_point_of_interest);
rotateVector( rotX, rotY, v);
glm::vec3 view = eye + v;
v = glm::normalize(v);
double t = point.x / double(m_viewport_size.x);
float dollyBy = 1.0 - expf( -dollySpeed * t);
//float dollyBy = dollySpeed * t;
if (dollyBy > 1.0) {
dollyBy = 1.0;
} else if (dollyBy < -1.0) {
dollyBy = -1.0;
}
dollyBy *= m_point_of_interest;
glm::vec3 new_eye = eye + (dollyBy *v);
setTranslation(new_eye);
v = new_eye - view;
m_point_of_interest = glm::length(v);
}
void Camera::rotate(const glm::vec2 &point, double rotateSpeed)
{
double rotX = m_rotation.x;
double rotY = m_rotation.y;
const float rotZ = m_rotation.z;
glm::vec3 eye = m_translation;
glm::vec3 v(0.0f, 0.0f, -m_point_of_interest);
rotateVector(rotX, rotY, v);
const glm::vec3 view = eye + v;
rotY += -rotateSpeed * ( point.x / double( m_viewport_size.x ) );
rotX += -rotateSpeed * ( point.y / double( m_viewport_size.y ) );
v.x = 0.0f;
v.y = 0.0f;
v.z = m_point_of_interest;
rotateVector(rotX, rotY, v);
const glm::vec3 new_eye = view + v;
setTranslation(new_eye);
setRotation(glm::vec3( rotX, rotY, rotZ ) );
}
void Camera::auto_clipping_plane( const Imath::Box3d &bounds)
{
const double rotX = m_rotation.x;
const double rotY = m_rotation.y;
const glm::vec3 eye = m_translation;
double clipNear = FLT_MAX;
double clipFar = FLT_MIN;
glm::vec3 v(0.0, 0.0, -m_point_of_interest);
rotateVector(rotX, rotY, v);
const glm::vec3 view = eye + v;
v = glm::normalize(v);
glm::vec3 points[8];
points[0] = glm::vec3(bounds.min.x, bounds.min.y, bounds.min.z);
points[1] = glm::vec3(bounds.min.x, bounds.min.y, bounds.max.z);
points[2] = glm::vec3(bounds.min.x, bounds.max.y, bounds.min.z);
points[3] = glm::vec3(bounds.min.x, bounds.max.y, bounds.max.z);
points[4] = glm::vec3(bounds.max.x, bounds.min.y, bounds.min.z);
points[5] = glm::vec3(bounds.max.x, bounds.min.y, bounds.max.z);
points[6] = glm::vec3(bounds.max.x, bounds.max.y, bounds.min.z);
points[7] = glm::vec3(bounds.max.x, bounds.max.y, bounds.max.z);
for( int p = 0; p < 8; ++p )
{
glm::vec3 dp = points[p] - eye;
double proj = glm::dot(dp, v);
clipNear = std::min(proj, clipNear);
clipFar = std::max(proj, clipFar);
}
clipNear -= 0.5f;
clipFar += 0.5f;
clipNear = glm::clamp(clipNear, 0.1, 100000.0);
clipFar = glm::clamp(clipFar, 500.0, 100000.0);
if (clipFar <= clipNear) {
clipFar = clipNear + 0.1;
}
m_clip.x = clipNear;
m_clip.y = clipFar;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, 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.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtCore/QString>
#include <QtTest/QtTest>
#include <QtCore/QCoreApplication>
#include <qllcpsocket.h>
#include <qnearfieldmanager.h>
#include <qnearfieldtarget.h>
#include "qnfctestcommon.h"
#include "qnfctestutil.h"
QTM_USE_NAMESPACE
Q_DECLARE_METATYPE(QNearFieldTarget*)
Q_DECLARE_METATYPE(QLlcpSocket::Error);
class tst_qllcpsocketremote : public QObject
{
Q_OBJECT
public:
tst_qllcpsocketremote();
private Q_SLOTS:
// ALERT Handshake required, do NOTchange the sequence of handshaking testcases.
void testCase0(); // Intial handshake - work with tst_qllcpsocketlocal testCase0
void testCase1(); // handshake 1,2 - work with tst_qllcpsocketlocal testCase1
void testCase2(); // handshake 3 - work with tst_qllcpsocketlocal testCase2
void cleanupTest();
private:
QNearFieldManager *m_nfcManager;
QNearFieldTarget *m_target;
QLlcpSocket *m_socket;
quint8 m_port;
};
tst_qllcpsocketremote::tst_qllcpsocketremote()
{
qRegisterMetaType<QNearFieldTarget *>("QNearFieldTarget*");
qRegisterMetaType<QNearFieldTarget *>("QLlcpSocket::Error");
}
/*!
Description: Init test case for NFC LLCP connection-less mode socket - local peer
TestScenario:
Touch a NFC device with LLCP connection-less service actived
TestExpectedResults:
Signal of target detected has been found.
*/
void tst_qllcpsocketremote::testCase0()
{
m_nfcManager = new QNearFieldManager;
QSignalSpy targetDetectedSpy(m_nfcManager, SIGNAL(targetDetected(QNearFieldTarget*)));
m_nfcManager->startTargetDetection(QNearFieldTarget::AnyTarget);
QString message("Remote wait touch");
QNfcTestUtil::ShowMessage(message);
QTRY_VERIFY(!targetDetectedSpy.isEmpty());
m_target = targetDetectedSpy.at(targetDetectedSpy.count() - 1).at(0).value<QNearFieldTarget *>();
QVERIFY(m_target!=NULL);
QVERIFY(m_target->accessMethods() & QNearFieldTarget::LlcpAccess);
m_port = 35;
m_socket = new QLlcpSocket;
}
/*!
Description: Description: Receive the message and send the acknowledged identical message
TestScenario: 1. Remote peer binds to local port
2. Remote peer receives the message sending from the local peer
3. Remote peer sends the echoed message to the local peer
TestExpectedResults:
1. Remote peer binds to local port successfully.
2. The message has been received from remote peer.
3. The message has be sent to local peer.
*/
void tst_qllcpsocketremote::testCase1()
{
// STEP 1: bind the local port for current socket
QSignalSpy readyReadSpy(m_socket, SIGNAL(readyRead()));
bool ret = m_socket->bind(m_port);
QString message("handshake 1");
QNfcTestUtil::ShowMessage(message);
QTRY_VERIFY(readyReadSpy.count() == 1);
QVERIFY(ret);
// STEP 2: Receive data from the peer which send messages to
QByteArray datagram;
if (m_socket->hasPendingDatagrams())
{
datagram.resize(m_socket->pendingDatagramSize());
qint64 readSize = m_socket->readDatagram(datagram.data(), datagram.size());
QVERIFY(readSize != -1);
}
// STEP 3: Send the received message back to the intiated device.
QSignalSpy errorSpy(m_socket, SIGNAL(error(QLlcpSocket::Error)));
QSignalSpy bytesWrittenSpy(m_socket, SIGNAL(bytesWritten(qint64)));
qint64 val = m_socket->writeDatagram(datagram,m_target, m_port);
QVERIFY(val != -1);
QTRY_VERIFY(bytesWrittenSpy.count() == 1);
QList<QVariant> arguments = bytesWrittenSpy.takeFirst(); // take the first signal
qint64 writtenSize = arguments.at(0).value<qint64>();
QVERIFY(writtenSize > 0);
QString message2("handshake 2");
QNfcTestUtil::ShowMessage(message2);
// make sure the no error signal emitted
QCOMPARE(errorSpy.count(), 0);
}
/*!
Description: Unit test for NFC LLCP connection-less mode socket - remote peer (passive)
TestScenario: 1. Remote peer binds to local port ( already done in testCase1)
2. Remote peer receive datagram twice
3. Remote peer waitForReadyRead
TestExpectedResults:
1. Remote peer binds to local port successfully.
2. Remote peer receive datagram twice successfully
3. waitForReadyRead return true as long as readyReadSpy not empty
*/
void tst_qllcpsocketremote::testCase2()
{
// STEP 1: bind the local port for current socket
QSignalSpy readyReadSpy(m_socket, SIGNAL(readyRead()));
QString expectedMessage1("testcase2 string str1");
QString expectedMessage2("testcase2 string str2");
QString boxMessage("handshake 3");
QNfcTestUtil::ShowMessage(boxMessage);
QTRY_VERIFY(readyReadSpy.count() == 1);
QByteArray datagram;
if (m_socket->hasPendingDatagrams())
{
datagram.resize(m_socket->pendingDatagramSize());
qint64 readSize = m_socket->readDatagram(datagram.data(), datagram.size());
QVERIFY(readSize != -1);
}
QString receivedMessage1 = datagram.data();
qDebug() << "receivedMessage1: " << receivedMessage1;
QVERIFY(expectedMessage1 == receivedMessage1);
QTRY_VERIFY(readyReadSpy.count() == 1);
QByteArray datagram2;
if (m_socket->hasPendingDatagrams())
{
datagram2.resize(m_socket->pendingDatagramSize());
qint64 readSize = m_socket->readDatagram(datagram2.data(), datagram2.size());
QVERIFY(readSize != -1);
}
QString receivedMessage2 = datagram2.data();
qDebug() << "receivedMessage2: " << receivedMessage2;
QVERIFY(expectedMessage2 == receivedMessage2);
const int Timeout = 10 * 1000;
bool ret = m_socket->waitForReadyRead(Timeout);
QVERIFY(ret);
}
void tst_qllcpsocketremote::cleanupTest()
{
delete m_nfcManager;
delete m_socket;
}
QTEST_MAIN(tst_qllcpsocketremote);
#include "tst_qllcpsocketremote.moc"
<commit_msg>llcp trivial changes<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, 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.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtCore/QString>
#include <QtTest/QtTest>
#include <QtCore/QCoreApplication>
#include <qllcpsocket.h>
#include <qnearfieldmanager.h>
#include <qnearfieldtarget.h>
#include "qnfctestcommon.h"
#include "qnfctestutil.h"
QTM_USE_NAMESPACE
Q_DECLARE_METATYPE(QNearFieldTarget*)
Q_DECLARE_METATYPE(QLlcpSocket::Error);
class tst_qllcpsocketremote : public QObject
{
Q_OBJECT
public:
tst_qllcpsocketremote();
private Q_SLOTS:
// ALERT Handshake required, do NOTchange the sequence of handshaking testcases.
void testCase0(); // Intial handshake - work with tst_qllcpsocketlocal testCase0
void testCase1(); // handshake 1,2 - work with tst_qllcpsocketlocal testCase1
void testCase2(); // handshake 3 - work with tst_qllcpsocketlocal testCase2
void cleanupTest();
private:
QNearFieldManager *m_nfcManager;
QNearFieldTarget *m_target;
QLlcpSocket *m_socket;
quint8 m_port;
};
tst_qllcpsocketremote::tst_qllcpsocketremote()
{
qRegisterMetaType<QNearFieldTarget *>("QNearFieldTarget*");
qRegisterMetaType<QNearFieldTarget *>("QLlcpSocket::Error");
}
/*!
Description: Init test case for NFC LLCP connection-less mode socket - local peer
TestScenario:
Touch a NFC device with LLCP connection-less service actived
TestExpectedResults:
Signal of target detected has been found.
*/
void tst_qllcpsocketremote::testCase0()
{
m_nfcManager = new QNearFieldManager;
QSignalSpy targetDetectedSpy(m_nfcManager, SIGNAL(targetDetected(QNearFieldTarget*)));
m_nfcManager->startTargetDetection(QNearFieldTarget::AnyTarget);
QString message("Remote wait touch");
QNfcTestUtil::ShowMessage(message);
QTRY_VERIFY(!targetDetectedSpy.isEmpty());
m_target = targetDetectedSpy.at(targetDetectedSpy.count() - 1).at(0).value<QNearFieldTarget *>();
QVERIFY(m_target!=NULL);
QVERIFY(m_target->accessMethods() & QNearFieldTarget::LlcpAccess);
m_port = 35;
m_socket = new QLlcpSocket;
}
/*!
Description: Description: Receive the message and send the acknowledged identical message
TestScenario: 1. Remote peer binds to local port
2. Remote peer receives the message sending from the local peer
3. Remote peer sends the echoed message to the local peer
TestExpectedResults:
1. Remote peer binds to local port successfully.
2. The message has been received from remote peer.
3. The message has be sent to local peer.
*/
void tst_qllcpsocketremote::testCase1()
{
// STEP 1: bind the local port for current socket
QSignalSpy readyReadSpy(m_socket, SIGNAL(readyRead()));
bool ret = m_socket->bind(m_port);
QString message("handshake 1");
QNfcTestUtil::ShowMessage(message);
QTRY_VERIFY(readyReadSpy.count() == 1);
QVERIFY(ret);
// STEP 2: Receive data from the peer which send messages to
QByteArray datagram;
if (m_socket->hasPendingDatagrams())
{
datagram.resize(m_socket->pendingDatagramSize());
qint64 readSize = m_socket->readDatagram(datagram.data(), datagram.size());
QVERIFY(readSize != -1);
}
// STEP 3: Send the received message back to the intiated device.
QSignalSpy errorSpy(m_socket, SIGNAL(error(QLlcpSocket::Error)));
QSignalSpy bytesWrittenSpy(m_socket, SIGNAL(bytesWritten(qint64)));
qint64 val = m_socket->writeDatagram(datagram,m_target, m_port);
QVERIFY(val != -1);
QTRY_VERIFY(bytesWrittenSpy.count() == 1);
QList<QVariant> arguments = bytesWrittenSpy.takeFirst(); // take the first signal
qint64 writtenSize = arguments.at(0).value<qint64>();
QVERIFY(writtenSize > 0);
QString message2("handshake 2");
QNfcTestUtil::ShowMessage(message2);
// make sure the no error signal emitted
QCOMPARE(errorSpy.count(), 0);
}
/*!
Description: Unit test for NFC LLCP connection-less mode socket - remote peer (passive)
TestScenario: 1. Remote peer binds to local port ( already done in testCase1)
2. Remote peer receive datagram twice
3. Remote peer waitForReadyRead
TestExpectedResults:
1. Remote peer binds to local port successfully.
2. Remote peer receive datagram twice successfully
3. waitForReadyRead return true as long as readyReadSpy not empty
*/
void tst_qllcpsocketremote::testCase2()
{
// STEP 1: bind the local port for current socket
QSignalSpy readyReadSpy(m_socket, SIGNAL(readyRead()));
QString expectedMessage1("testcase2 string str1");
QString expectedMessage2("testcase2 string str2");
QString boxMessage("handshake 3");
QNfcTestUtil::ShowMessage(boxMessage);
QTRY_VERIFY(readyReadSpy.count() == 1);
QByteArray datagram;
if (m_socket->hasPendingDatagrams())
{
datagram.resize(m_socket->pendingDatagramSize());
qint64 readSize = m_socket->readDatagram(datagram.data(), datagram.size());
QVERIFY(readSize != -1);
}
QString receivedMessage1 = datagram.data();
qDebug() << "receivedMessage1: " << receivedMessage1;
QVERIFY(expectedMessage1 == receivedMessage1);
QTRY_VERIFY(readyReadSpy.count() == 2);
QByteArray datagram2;
if (m_socket->hasPendingDatagrams())
{
datagram2.resize(m_socket->pendingDatagramSize());
qint64 readSize = m_socket->readDatagram(datagram2.data(), datagram2.size());
QVERIFY(readSize != -1);
}
QString receivedMessage2 = datagram2.data();
qDebug() << "receivedMessage2: " << receivedMessage2;
QVERIFY(expectedMessage2 == receivedMessage2);
const int Timeout = 10 * 1000;
bool ret = m_socket->waitForReadyRead(Timeout);
QVERIFY(ret);
}
void tst_qllcpsocketremote::cleanupTest()
{
delete m_nfcManager;
delete m_socket;
}
QTEST_MAIN(tst_qllcpsocketremote);
#include "tst_qllcpsocketremote.moc"
<|endoftext|> |
<commit_before>#include "sea5kgSudoku.h"
#include <wsjcpp_core.h>
#include <math.h>
#include <algorithm>
//----------------------------------------------------------------------------
// sea5kgSudokuCell
sea5kgSudokuCell::sea5kgSudokuCell(int nPosX, int nPosY, char cValue) {
m_nPosX = nPosX;
m_nPosY = nPosY;
m_cValue = cValue;
}
//----------------------------------------------------------------------------
void sea5kgSudokuCell::setValue(char cValue) {
m_cValue = cValue;
m_vPossibleValues.clear();
}
//----------------------------------------------------------------------------
char sea5kgSudokuCell::getValue() {
return m_cValue;
}
//----------------------------------------------------------------------------
const std::vector<char> &sea5kgSudokuCell::getPossibleValues() {
return m_vPossibleValues;
}
//----------------------------------------------------------------------------
void sea5kgSudokuCell::clear() {
m_vPossibleValues.clear();
m_cValue = '-';
}
//----------------------------------------------------------------------------
void sea5kgSudokuCell::setPossibleValues(const std::string &sAlphabet) {
m_vPossibleValues.clear();
for (int i = 0; i < sAlphabet.length(); i++) {
m_vPossibleValues.push_back(sAlphabet[i]);
}
}
//----------------------------------------------------------------------------
void sea5kgSudokuCell::excludePossibleValue(char cValue) {
std::vector<char>::iterator it;
it = std::find(m_vPossibleValues.begin(), m_vPossibleValues.end(), cValue);
if (it != m_vPossibleValues.end()) {
m_vPossibleValues.erase(it);
}
}
//----------------------------------------------------------------------------
std::string sea5kgSudokuCell::getOnelinePossibleValues() {
std::string sRet = "";
for (int i = 0; i < m_vPossibleValues.size(); i++) {
sRet += m_vPossibleValues[i];
}
return sRet;
}
//----------------------------------------------------------------------------
// sea5kgSudokuRegion
sea5kgSudokuRegion::sea5kgSudokuRegion(std::vector<std::pair<int,int>> &vRegionCells) {
m_vRegionCells = vRegionCells;
}
//----------------------------------------------------------------------------
const std::vector<std::pair<int,int>> &sea5kgSudokuRegion::getRegionCells() const {
return m_vRegionCells;
}
//----------------------------------------------------------------------------
std::pair<int,int> sea5kgSudokuRegion::getMin() const {
std::pair<int,int> ret = m_vRegionCells[0];
for (int i = 0; i < m_vRegionCells.size(); i++) {
if (m_vRegionCells[i].first < ret.first || m_vRegionCells[i].second < ret.second) {
ret = m_vRegionCells[i];
}
}
return ret;
}
//----------------------------------------------------------------------------
std::pair<int,int> sea5kgSudokuRegion::getMax() const {
std::pair<int,int> ret = m_vRegionCells[0];
for (int i = 0; i < m_vRegionCells.size(); i++) {
if (m_vRegionCells[i].first > ret.first || m_vRegionCells[i].second > ret.second) {
ret = m_vRegionCells[i];
}
}
return ret;
}
//----------------------------------------------------------------------------
bool sea5kgSudokuRegion::has(int x, int y) {
for (int i = 0; i < m_vRegionCells.size(); i++) {
if (m_vRegionCells[i].first == x && m_vRegionCells[i].second == y) {
return true;
}
}
return false;
}
// -----------------------------------------------------------------------------
std::string sea5kgSudokuRegion::getOnelineData() {
std::string sRet;
for (int i = 0; i < m_vRegionCells.size(); i++) {
sRet += "{" + std::to_string(m_vRegionCells[i].first) + ","
+ std::to_string(m_vRegionCells[i].second) + "}";
}
return sRet;
}
// -----------------------------------------------------------------------------
// sea5kgSudoku
sea5kgSudoku::sea5kgSudoku(const std::string &sAlphabet) {
TAG = "sea5kgSudoku";
int nLength = sAlphabet.length();
if (nLength < 2) {
WsjcppLog::throw_err(TAG, "Sudoku alphabet size must be more then 1");
}
// check reserved char
for (int i = 0; i < nLength; i++) {
if (sAlphabet[i] == '-') {
WsjcppLog::throw_err(TAG, "Sudoku alphabet could not contains '-'");
}
}
// check unique values
for (int x = 0; x < nLength; x++) {
for (int y = 0; y < nLength; y++) {
if (x != y && sAlphabet[x] == sAlphabet[y]) {
std::string sMessage = "Sudoku alphabet could not contains dublicates '";
sMessage += sAlphabet[x];
sMessage += "'";
WsjcppLog::throw_err(TAG, sMessage);
}
}
}
m_sAlphabet = sAlphabet;
m_nLen = m_sAlphabet.length();
for (int x = 0; x < m_nLen; x++) {
for (int y = 0; y < m_nLen; y++) {
m_vCells.push_back(new sea5kgSudokuCell(x,y,'-'));
}
};
// prepare fields
}
//-----------------------------------------------------------------------------
sea5kgSudoku::~sea5kgSudoku() {
this->clearAll();
};
//-----------------------------------------------------------------------------
void sea5kgSudoku::setData(const std::string &sPole) {
int nLen = m_sAlphabet.length();
if (sPole.length() != (nLen*nLen)) {
WsjcppLog::throw_err(TAG, "Wrong size of data");
}
// m_vCells.clear();
for (int x = 0; x < nLen; x++) {
for (int y = 0; y < nLen; y++) {
int i = x + y*nLen;
m_vCells[i]->setValue(sPole[i]);
}
}
}
//-----------------------------------------------------------------------------
std::string sea5kgSudoku::printData() {
int sch = 1;
std::string sData = " +";
for (int i = 0; i < m_nLen; i++) {
sData += "---+";
}
for (unsigned int i = 0; i < m_vCells.size(); i++) {
char cValue = m_vCells[i]->getValue();
if (i % m_nLen == 0) {
sData += "\n | ";
sch++;
}
sData += cValue;
sData += " | ";
};
sData += "\n +";
for (int i = 0; i < m_nLen; i++) {
sData += "---+";
}
return sData;
};
//-----------------------------------------------------------------------------
std::string sea5kgSudoku::getOnelineData() {
std::string sRet = "";
for (unsigned int i = 0; i < m_vCells.size(); i++) {
sRet += m_vCells[i]->getValue();
};
return sRet;
}
//-----------------------------------------------------------------------------
void sea5kgSudoku::clearAll() {
//clear cells
for (unsigned int i = 0; i < m_vCells.size(); i++) {
m_vCells[i]->clear();
};
m_vRegions.clear();
};
//-----------------------------------------------------------------------------
void sea5kgSudoku::coutVariant() {
for (unsigned int i = 0; i < m_vCells.size(); i++) {
// m_vCells[i]->updatePossibleValues(m_sAlphabet);
std::vector<char> vPossibleValues = m_vCells[i]->getPossibleValues();
std::cout << "Cell "<< i << ": \n";
std::cout << "\tthe number of cases = " << vPossibleValues.size() << ";\n";
std::cout << "\tcases: ";
for (unsigned int t = 0; t < vPossibleValues.size(); t++) {
std::cout << " " << vPossibleValues[t] << ", ";
};
// std::cout << "\n\tNumber of areas which include cell: " << m_vCells[i]->oblasty.size() << "\n";
};
};
//-----------------------------------------------------------------------------
void sea5kgSudoku::updatePossibleValues() {
for (int x = 0; x < m_nLen; x++) {
for (int y = 0; y < m_nLen; y++) {
if (getCell(x,y).getValue() != '-') {
getCell(x,y).setPossibleValues("");
continue;
}
std::vector<sea5kgSudokuRegion> vFoundRegions;
findRegions(x, y, vFoundRegions);
getCell(x,y).setPossibleValues(m_sAlphabet);
for (int i = 0; i < vFoundRegions.size(); i++) {
sea5kgSudokuRegion region = vFoundRegions[i];
for (int r = 0; r < region.getRegionCells().size(); r++) {
std::pair<int,int> p = region.getRegionCells()[r];
char c = getCell(p).getValue();
if (c != '-') {
getCell(x,y).excludePossibleValue(c);
}
}
}
}
}
}
//-----------------------------------------------------------------------------
void sea5kgSudoku::findRegions(int x, int y, std::vector<sea5kgSudokuRegion> &foundRegions) {
foundRegions.clear();
for (int i = 0; i < m_vRegions.size(); i++) {
sea5kgSudokuRegion region = m_vRegions[i];
if (region.has(x,y)) {
foundRegions.push_back(region);
}
}
}
//----------------------------------------------------------------------------
void sea5kgSudoku::applyClassicRegionsFor9x9() {
if (m_sAlphabet.length() != 9) {
WsjcppLog::throw_err(TAG, "Alphabet must have size 9");
}
// depending fill
m_vRegions.clear();
addRegionsRowsAndColumns();
// add 9 squares
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
std::vector<std::pair<int,int>> vCells;
int x0 = x*3;
int y0 = y*3;
vCells.push_back(std::pair<int,int>(x0,y0));
vCells.push_back(std::pair<int,int>(x0,y0+1));
vCells.push_back(std::pair<int,int>(x0,y0+2));
vCells.push_back(std::pair<int,int>(x0+1,y0));
vCells.push_back(std::pair<int,int>(x0+1,y0+1));
vCells.push_back(std::pair<int,int>(x0+1,y0+2));
vCells.push_back(std::pair<int,int>(x0+2,y0));
vCells.push_back(std::pair<int,int>(x0+2,y0+1));
vCells.push_back(std::pair<int,int>(x0+2,y0+2));
m_vRegions.push_back(sea5kgSudokuRegion(vCells));
}
}
}
//----------------------------------------------------------------------------
const std::vector<sea5kgSudokuRegion> &sea5kgSudoku::getRegions() const {
return m_vRegions;
}
//-----------------------------------------------------------------------------
bool sea5kgSudoku::step() {
updatePossibleValues();
int nSet = 0;
for (int x = 0; x < m_nLen; x++) {
for (int y = 0; y < m_nLen; y++) {
if (getCell(x,y).getValue() == '-') {
std::vector<char> vPossibleValues = getCell(x,y).getPossibleValues();
if (vPossibleValues.size() == 1) {
char cValue = getCell(x,y).getPossibleValues()[0];
getCell(x,y).setValue(cValue);
nSet++;
} else {
std::vector<sea5kgSudokuRegion> vFoundRegions;
findRegions(x, y, vFoundRegions);
if (x == 2 && y == 2) {
std::cout << "Possible values 0,0: " << getCell(0,0).getOnelinePossibleValues() << std::endl;
std::cout << "Possible values 0,1: " << getCell(0,1).getOnelinePossibleValues() << std::endl;
std::cout << "Possible values 0,2: " << getCell(0,2).getOnelinePossibleValues() << std::endl;
std::cout << "Possible values 1,0: " << getCell(1,0).getOnelinePossibleValues() << std::endl;
std::cout << "Possible values 2,2: " << getCell(2,2).getOnelinePossibleValues() << std::endl;
std::cout << "Value 2,2: " << getCell(2,2).getValue() << std::endl;
for (int r = 0; r < vFoundRegions.size(); r++) {
std::cout << vFoundRegions[r].getOnelineData() << std::endl;
}
}
for (int p = 0; p < vPossibleValues.size(); p++) {
char cValue = vPossibleValues[p];
for (int r = 0; r < vFoundRegions.size(); r++) {
sea5kgSudokuRegion region = vFoundRegions[r];
if (x == 2 && y == 2) {
std::cout << ">>>> Found value! " << cValue << std::endl;
std::cout << "Found vFoundRegions[r].getOnelineData()! " << vFoundRegions[r].getOnelineData() << std::endl;
}
if (getCountOfPossibleValuesInRegion(cValue, region) == 1) {
getCell(x,y).setValue(cValue);
nSet++;
}
if (x == 2 && y == 2) {
std::cout << "<<< Found value! " << cValue << std::endl;
}
}
}
}
}
}
}
return nSet > 0;
};
// ----------------------------------------------------------------------------
int sea5kgSudoku::getCountOfPossibleValuesInRegion(char cValue, const sea5kgSudokuRegion ®ion) {
int nCount = 0;
std::vector<std::pair<int,int>> vRegionCells = region.getRegionCells();
for (int rc = 0; rc < vRegionCells.size(); rc++) {
std::vector<char> vPossibleValues = getCell(vRegionCells[rc]).getPossibleValues();
for (int y = 0; y < vPossibleValues.size(); y++) {
if (vPossibleValues[y] == cValue) {
nCount++;
}
}
}
return nCount;
}
//----------------------------------------------------------------------------
sea5kgSudokuCell &sea5kgSudoku::getCell(int x, int y) {
return *m_vCells[x + y * m_nLen];
}
//----------------------------------------------------------------------------
sea5kgSudokuCell &sea5kgSudoku::getCell(const std::pair<int,int> &p) {
return *m_vCells[p.first + p.second * m_nLen];
}
// ----------------------------------------------------------------------------
void sea5kgSudoku::applyClassicRegionsFor6x6() {
if (m_sAlphabet.length() != 6) {
WsjcppLog::throw_err(TAG, "Alphabet must have size 6");
}
m_vRegions.clear();
addRegionsRowsAndColumns();
// TODO add 6 rectangules
}
//----------------------------------------------------------------------------
void sea5kgSudoku::addRegionsRowsAndColumns() {
int nLen = m_sAlphabet.length();
// rows && columns
for (int x = 0; x < nLen; x++) {
std::vector<std::pair<int,int>> vRowCells;
std::vector<std::pair<int,int>> vColumnCells;
for( int y = 0; y < nLen; y++ ) {
vRowCells.push_back(std::pair<int,int>(x,y));
vColumnCells.push_back(std::pair<int,int>(y,x));
}
m_vRegions.push_back(sea5kgSudokuRegion(vRowCells));
m_vRegions.push_back(sea5kgSudokuRegion(vColumnCells));
}
}
//----------------------------------------------------------------------------<commit_msg>Fixed error<commit_after>#include "sea5kgSudoku.h"
#include <wsjcpp_core.h>
#include <math.h>
#include <algorithm>
//----------------------------------------------------------------------------
// sea5kgSudokuCell
sea5kgSudokuCell::sea5kgSudokuCell(int nPosX, int nPosY, char cValue) {
m_nPosX = nPosX;
m_nPosY = nPosY;
m_cValue = cValue;
}
//----------------------------------------------------------------------------
void sea5kgSudokuCell::setValue(char cValue) {
m_cValue = cValue;
}
//----------------------------------------------------------------------------
char sea5kgSudokuCell::getValue() {
return m_cValue;
}
//----------------------------------------------------------------------------
const std::vector<char> &sea5kgSudokuCell::getPossibleValues() {
return m_vPossibleValues;
}
//----------------------------------------------------------------------------
void sea5kgSudokuCell::clear() {
m_vPossibleValues.clear();
m_cValue = '-';
}
//----------------------------------------------------------------------------
void sea5kgSudokuCell::setPossibleValues(const std::string &sAlphabet) {
m_vPossibleValues.clear();
for (int i = 0; i < sAlphabet.length(); i++) {
m_vPossibleValues.push_back(sAlphabet[i]);
}
}
//----------------------------------------------------------------------------
void sea5kgSudokuCell::excludePossibleValue(char cValue) {
std::vector<char>::iterator it;
it = std::find(m_vPossibleValues.begin(), m_vPossibleValues.end(), cValue);
if (it != m_vPossibleValues.end()) {
m_vPossibleValues.erase(it);
}
}
//----------------------------------------------------------------------------
std::string sea5kgSudokuCell::getOnelinePossibleValues() {
std::string sRet = "";
for (int i = 0; i < m_vPossibleValues.size(); i++) {
sRet += m_vPossibleValues[i];
}
return sRet;
}
//----------------------------------------------------------------------------
// sea5kgSudokuRegion
sea5kgSudokuRegion::sea5kgSudokuRegion(std::vector<std::pair<int,int>> &vRegionCells) {
m_vRegionCells = vRegionCells;
}
//----------------------------------------------------------------------------
const std::vector<std::pair<int,int>> &sea5kgSudokuRegion::getRegionCells() const {
return m_vRegionCells;
}
//----------------------------------------------------------------------------
std::pair<int,int> sea5kgSudokuRegion::getMin() const {
std::pair<int,int> ret = m_vRegionCells[0];
for (int i = 0; i < m_vRegionCells.size(); i++) {
if (m_vRegionCells[i].first < ret.first || m_vRegionCells[i].second < ret.second) {
ret = m_vRegionCells[i];
}
}
return ret;
}
//----------------------------------------------------------------------------
std::pair<int,int> sea5kgSudokuRegion::getMax() const {
std::pair<int,int> ret = m_vRegionCells[0];
for (int i = 0; i < m_vRegionCells.size(); i++) {
if (m_vRegionCells[i].first > ret.first || m_vRegionCells[i].second > ret.second) {
ret = m_vRegionCells[i];
}
}
return ret;
}
//----------------------------------------------------------------------------
bool sea5kgSudokuRegion::has(int x, int y) {
for (int i = 0; i < m_vRegionCells.size(); i++) {
if (m_vRegionCells[i].first == x && m_vRegionCells[i].second == y) {
return true;
}
}
return false;
}
// -----------------------------------------------------------------------------
std::string sea5kgSudokuRegion::getOnelineData() {
std::string sRet;
for (int i = 0; i < m_vRegionCells.size(); i++) {
sRet += "{" + std::to_string(m_vRegionCells[i].first) + ","
+ std::to_string(m_vRegionCells[i].second) + "}";
}
return sRet;
}
// -----------------------------------------------------------------------------
// sea5kgSudoku
sea5kgSudoku::sea5kgSudoku(const std::string &sAlphabet) {
TAG = "sea5kgSudoku";
int nLength = sAlphabet.length();
if (nLength < 2) {
WsjcppLog::throw_err(TAG, "Sudoku alphabet size must be more then 1");
}
// check reserved char
for (int i = 0; i < nLength; i++) {
if (sAlphabet[i] == '-') {
WsjcppLog::throw_err(TAG, "Sudoku alphabet could not contains '-'");
}
}
// check unique values
for (int x = 0; x < nLength; x++) {
for (int y = 0; y < nLength; y++) {
if (x != y && sAlphabet[x] == sAlphabet[y]) {
std::string sMessage = "Sudoku alphabet could not contains dublicates '";
sMessage += sAlphabet[x];
sMessage += "'";
WsjcppLog::throw_err(TAG, sMessage);
}
}
}
m_sAlphabet = sAlphabet;
m_nLen = m_sAlphabet.length();
for (int x = 0; x < m_nLen; x++) {
for (int y = 0; y < m_nLen; y++) {
m_vCells.push_back(new sea5kgSudokuCell(x,y,'-'));
}
};
// prepare fields
}
//-----------------------------------------------------------------------------
sea5kgSudoku::~sea5kgSudoku() {
this->clearAll();
};
//-----------------------------------------------------------------------------
void sea5kgSudoku::setData(const std::string &sPole) {
int nLen = m_sAlphabet.length();
if (sPole.length() != (nLen*nLen)) {
WsjcppLog::throw_err(TAG, "Wrong size of data");
}
// m_vCells.clear();
for (int x = 0; x < nLen; x++) {
for (int y = 0; y < nLen; y++) {
int i = x + y*nLen;
m_vCells[i]->setValue(sPole[i]);
}
}
}
//-----------------------------------------------------------------------------
std::string sea5kgSudoku::printData() {
int sch = 1;
std::string sData = " +";
for (int i = 0; i < m_nLen; i++) {
sData += "---+";
}
for (unsigned int i = 0; i < m_vCells.size(); i++) {
char cValue = m_vCells[i]->getValue();
if (i % m_nLen == 0) {
sData += "\n | ";
sch++;
}
sData += cValue;
sData += " | ";
};
sData += "\n +";
for (int i = 0; i < m_nLen; i++) {
sData += "---+";
}
return sData;
};
//-----------------------------------------------------------------------------
std::string sea5kgSudoku::getOnelineData() {
std::string sRet = "";
for (unsigned int i = 0; i < m_vCells.size(); i++) {
sRet += m_vCells[i]->getValue();
};
return sRet;
}
//-----------------------------------------------------------------------------
void sea5kgSudoku::clearAll() {
//clear cells
for (unsigned int i = 0; i < m_vCells.size(); i++) {
m_vCells[i]->clear();
};
m_vRegions.clear();
};
//-----------------------------------------------------------------------------
void sea5kgSudoku::coutVariant() {
for (unsigned int i = 0; i < m_vCells.size(); i++) {
// m_vCells[i]->updatePossibleValues(m_sAlphabet);
std::vector<char> vPossibleValues = m_vCells[i]->getPossibleValues();
std::cout << "Cell "<< i << ": \n";
std::cout << "\tthe number of cases = " << vPossibleValues.size() << ";\n";
std::cout << "\tcases: ";
for (unsigned int t = 0; t < vPossibleValues.size(); t++) {
std::cout << " " << vPossibleValues[t] << ", ";
};
// std::cout << "\n\tNumber of areas which include cell: " << m_vCells[i]->oblasty.size() << "\n";
};
};
//-----------------------------------------------------------------------------
void sea5kgSudoku::updatePossibleValues() {
for (int x = 0; x < m_nLen; x++) {
for (int y = 0; y < m_nLen; y++) {
if (getCell(x,y).getValue() != '-') {
getCell(x,y).setPossibleValues("");
continue;
}
std::vector<sea5kgSudokuRegion> vFoundRegions;
findRegions(x, y, vFoundRegions);
getCell(x,y).setPossibleValues(m_sAlphabet);
for (int i = 0; i < vFoundRegions.size(); i++) {
sea5kgSudokuRegion region = vFoundRegions[i];
for (int r = 0; r < region.getRegionCells().size(); r++) {
std::pair<int,int> p = region.getRegionCells()[r];
char c = getCell(p).getValue();
if (c != '-') {
getCell(x,y).excludePossibleValue(c);
}
}
}
}
}
}
//-----------------------------------------------------------------------------
void sea5kgSudoku::findRegions(int x, int y, std::vector<sea5kgSudokuRegion> &foundRegions) {
foundRegions.clear();
for (int i = 0; i < m_vRegions.size(); i++) {
sea5kgSudokuRegion region = m_vRegions[i];
if (region.has(x,y)) {
foundRegions.push_back(region);
}
}
}
//----------------------------------------------------------------------------
void sea5kgSudoku::applyClassicRegionsFor9x9() {
if (m_sAlphabet.length() != 9) {
WsjcppLog::throw_err(TAG, "Alphabet must have size 9");
}
// depending fill
m_vRegions.clear();
addRegionsRowsAndColumns();
// add 9 squares
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
std::vector<std::pair<int,int>> vCells;
int x0 = x*3;
int y0 = y*3;
vCells.push_back(std::pair<int,int>(x0,y0));
vCells.push_back(std::pair<int,int>(x0,y0+1));
vCells.push_back(std::pair<int,int>(x0,y0+2));
vCells.push_back(std::pair<int,int>(x0+1,y0));
vCells.push_back(std::pair<int,int>(x0+1,y0+1));
vCells.push_back(std::pair<int,int>(x0+1,y0+2));
vCells.push_back(std::pair<int,int>(x0+2,y0));
vCells.push_back(std::pair<int,int>(x0+2,y0+1));
vCells.push_back(std::pair<int,int>(x0+2,y0+2));
m_vRegions.push_back(sea5kgSudokuRegion(vCells));
}
}
}
//----------------------------------------------------------------------------
const std::vector<sea5kgSudokuRegion> &sea5kgSudoku::getRegions() const {
return m_vRegions;
}
//-----------------------------------------------------------------------------
bool sea5kgSudoku::step() {
updatePossibleValues();
int nSet = 0;
for (int x = 0; x < m_nLen; x++) {
for (int y = 0; y < m_nLen; y++) {
if (getCell(x,y).getValue() == '-') {
std::vector<char> vPossibleValues = getCell(x,y).getPossibleValues();
if (vPossibleValues.size() == 1) {
char cValue = getCell(x,y).getPossibleValues()[0];
getCell(x,y).setValue(cValue);
nSet++;
} else {
std::vector<sea5kgSudokuRegion> vFoundRegions;
findRegions(x, y, vFoundRegions);
if (x == 2 && y == 2) {
std::cout << "Possible values 0,0: " << getCell(0,0).getOnelinePossibleValues() << std::endl;
std::cout << "Possible values 0,1: " << getCell(0,1).getOnelinePossibleValues() << std::endl;
std::cout << "Possible values 0,2: " << getCell(0,2).getOnelinePossibleValues() << std::endl;
std::cout << "Possible values 1,0: " << getCell(1,0).getOnelinePossibleValues() << std::endl;
std::cout << "Possible values 2,2: " << getCell(2,2).getOnelinePossibleValues() << std::endl;
std::cout << "Value 2,2: " << getCell(2,2).getValue() << std::endl;
for (int r = 0; r < vFoundRegions.size(); r++) {
std::cout << vFoundRegions[r].getOnelineData() << std::endl;
}
}
for (int p = 0; p < vPossibleValues.size(); p++) {
char cValue = vPossibleValues[p];
for (int r = 0; r < vFoundRegions.size(); r++) {
sea5kgSudokuRegion region = vFoundRegions[r];
if (x == 2 && y == 2) {
std::cout << ">>>> Found value! " << cValue << std::endl;
std::cout << "Found vFoundRegions[r].getOnelineData()! " << vFoundRegions[r].getOnelineData() << std::endl;
}
if (getCountOfPossibleValuesInRegion(cValue, region) == 1) {
getCell(x,y).setValue(cValue);
nSet++;
}
if (x == 2 && y == 2) {
std::cout << "<<< Found value! " << cValue << std::endl;
}
}
}
}
}
}
}
return nSet > 0;
};
// ----------------------------------------------------------------------------
int sea5kgSudoku::getCountOfPossibleValuesInRegion(char cValue, const sea5kgSudokuRegion ®ion) {
int nCount = 0;
std::vector<std::pair<int,int>> vRegionCells = region.getRegionCells();
for (int rc = 0; rc < vRegionCells.size(); rc++) {
std::vector<char> vPossibleValues = getCell(vRegionCells[rc]).getPossibleValues();
for (int y = 0; y < vPossibleValues.size(); y++) {
if (vPossibleValues[y] == cValue) {
nCount++;
}
}
}
return nCount;
}
//----------------------------------------------------------------------------
sea5kgSudokuCell &sea5kgSudoku::getCell(int x, int y) {
return *m_vCells[x + y * m_nLen];
}
//----------------------------------------------------------------------------
sea5kgSudokuCell &sea5kgSudoku::getCell(const std::pair<int,int> &p) {
return *m_vCells[p.first + p.second * m_nLen];
}
// ----------------------------------------------------------------------------
void sea5kgSudoku::applyClassicRegionsFor6x6() {
if (m_sAlphabet.length() != 6) {
WsjcppLog::throw_err(TAG, "Alphabet must have size 6");
}
m_vRegions.clear();
addRegionsRowsAndColumns();
// TODO add 6 rectangules
}
//----------------------------------------------------------------------------
void sea5kgSudoku::addRegionsRowsAndColumns() {
int nLen = m_sAlphabet.length();
// rows && columns
for (int x = 0; x < nLen; x++) {
std::vector<std::pair<int,int>> vRowCells;
std::vector<std::pair<int,int>> vColumnCells;
for( int y = 0; y < nLen; y++ ) {
vRowCells.push_back(std::pair<int,int>(x,y));
vColumnCells.push_back(std::pair<int,int>(y,x));
}
m_vRegions.push_back(sea5kgSudokuRegion(vRowCells));
m_vRegions.push_back(sea5kgSudokuRegion(vColumnCells));
}
}
//----------------------------------------------------------------------------<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/socket/dns_cert_provenance_checker.h"
#if !defined(USE_OPENSSL)
#include <nspr.h>
#include <hasht.h>
#include <keyhi.h>
#include <pk11pub.h>
#include <sechash.h>
#include <set>
#include <string>
#include "base/basictypes.h"
#include "base/crypto/encryptor.h"
#include "base/crypto/symmetric_key.h"
#include "base/lazy_instance.h"
#include "base/non_thread_safe.h"
#include "base/pickle.h"
#include "base/scoped_ptr.h"
#include "net/base/completion_callback.h"
#include "net/base/dns_util.h"
#include "net/base/dnsrr_resolver.h"
#include "net/base/net_errors.h"
#include "net/base/net_log.h"
namespace net {
namespace {
// A DER encoded SubjectPublicKeyInfo structure containing the server's public
// key.
const uint8 kServerPublicKey[] = {
0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01,
0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00,
0x04, 0xc7, 0xea, 0x88, 0x60, 0x52, 0xe3, 0xa3, 0x3e, 0x39, 0x92, 0x0f, 0xa4,
0x3d, 0xba, 0xd8, 0x02, 0x2d, 0x06, 0x4d, 0x64, 0x98, 0x66, 0xb4, 0x82, 0xf0,
0x23, 0xa6, 0xd8, 0x37, 0x55, 0x7c, 0x01, 0xbf, 0x18, 0xd8, 0x16, 0x9e, 0x66,
0xdc, 0x49, 0xbf, 0x2e, 0x86, 0xe3, 0x99, 0xbd, 0xb3, 0x75, 0x25, 0x61, 0x04,
0x6c, 0x2e, 0xfb, 0x32, 0x42, 0x27, 0xe4, 0x23, 0xea, 0xcd, 0x81, 0x62, 0xc1,
};
const unsigned kMaxUploadsPerSession = 10;
// DnsCertLimits is a singleton class which keeps track of which hosts we have
// uploaded reports for in this session. Since some users will be behind MITM
// proxies, they would otherwise upload for every host and we don't wish to
// spam the upload server.
class DnsCertLimits {
public:
DnsCertLimits() { }
// HaveReachedMaxUploads returns true iff we have uploaded the maximum number
// of DNS certificate reports for this session.
bool HaveReachedMaxUploads() {
return uploaded_hostnames_.size() >= kMaxUploadsPerSession;
}
// HaveReachedMaxUploads returns true iff we have already uploaded a report
// about the given hostname in this session.
bool HaveUploadedForHostname(const std::string& hostname) {
return uploaded_hostnames_.count(hostname) > 0;
}
void DidUpload(const std::string& hostname) {
uploaded_hostnames_.insert(hostname);
}
private:
friend struct base::DefaultLazyInstanceTraits<DnsCertLimits>;
std::set<std::string> uploaded_hostnames_;
DISALLOW_COPY_AND_ASSIGN(DnsCertLimits);
};
static base::LazyInstance<DnsCertLimits> g_dns_cert_limits(
base::LINKER_INITIALIZED);
// DnsCertProvenanceCheck performs the DNS lookup of the certificate. This
// class is self-deleting.
class DnsCertProvenanceCheck : public NonThreadSafe {
public:
DnsCertProvenanceCheck(
const std::string& hostname,
DnsRRResolver* dnsrr_resolver,
DnsCertProvenanceChecker::Delegate* delegate,
const std::vector<base::StringPiece>& der_certs)
: hostname_(hostname),
dnsrr_resolver_(dnsrr_resolver),
delegate_(delegate),
der_certs_(der_certs.size()),
handle_(DnsRRResolver::kInvalidHandle),
ALLOW_THIS_IN_INITIALIZER_LIST(callback_(
this, &DnsCertProvenanceCheck::ResolutionComplete)) {
for (size_t i = 0; i < der_certs.size(); i++)
der_certs_[i] = der_certs[i].as_string();
}
void Start() {
DCHECK(CalledOnValidThread());
if (der_certs_.empty())
return;
DnsCertLimits* const limits = g_dns_cert_limits.Pointer();
if (limits->HaveReachedMaxUploads() ||
limits->HaveUploadedForHostname(hostname_)) {
return;
}
uint8 fingerprint[SHA1_LENGTH];
SECStatus rv = HASH_HashBuf(
HASH_AlgSHA1, fingerprint, (uint8*) der_certs_[0].data(),
der_certs_[0].size());
DCHECK_EQ(SECSuccess, rv);
char fingerprint_hex[SHA1_LENGTH * 2 + 1];
for (unsigned i = 0; i < sizeof(fingerprint); i++) {
static const char hextable[] = "0123456789abcdef";
fingerprint_hex[i*2] = hextable[fingerprint[i] >> 4];
fingerprint_hex[i*2 + 1] = hextable[fingerprint[i] & 15];
}
fingerprint_hex[SHA1_LENGTH * 2] = 0;
static const char kBaseCertName[] = ".certs.links.org";
domain_.assign(fingerprint_hex);
domain_.append(kBaseCertName);
handle_ = dnsrr_resolver_->Resolve(
domain_, kDNS_TXT, 0 /* flags */, &callback_, &response_,
0 /* priority */, BoundNetLog());
if (handle_ == DnsRRResolver::kInvalidHandle) {
LOG(ERROR) << "Failed to resolve " << domain_ << " for " << hostname_;
delete this;
}
}
private:
void ResolutionComplete(int status) {
DCHECK(CalledOnValidThread());
if (status == ERR_NAME_NOT_RESOLVED ||
(status == OK && response_.rrdatas.empty())) {
LOG(ERROR) << "FAILED"
<< " hostname:" << hostname_
<< " domain:" << domain_;
g_dns_cert_limits.Get().DidUpload(hostname_);
delegate_->OnDnsCertLookupFailed(hostname_, der_certs_);
} else if (status == OK) {
LOG(ERROR) << "GOOD"
<< " hostname:" << hostname_
<< " resp:" << response_.rrdatas[0];
} else {
LOG(ERROR) << "Unknown error " << status << " for " << domain_;
}
delete this;
}
const std::string hostname_;
std::string domain_;
DnsRRResolver* dnsrr_resolver_;
DnsCertProvenanceChecker::Delegate* const delegate_;
std::vector<std::string> der_certs_;
RRResponse response_;
DnsRRResolver::Handle handle_;
CompletionCallbackImpl<DnsCertProvenanceCheck> callback_;
};
SECKEYPublicKey* GetServerPubKey() {
SECItem der;
memset(&der, 0, sizeof(der));
der.data = const_cast<uint8*>(kServerPublicKey);
der.len = sizeof(kServerPublicKey);
CERTSubjectPublicKeyInfo* spki = SECKEY_DecodeDERSubjectPublicKeyInfo(&der);
SECKEYPublicKey* public_key = SECKEY_ExtractPublicKey(spki);
SECKEY_DestroySubjectPublicKeyInfo(spki);
return public_key;
}
} // namespace
// static
std::string DnsCertProvenanceChecker::BuildEncryptedReport(
const std::string& hostname,
const std::vector<std::string>& der_certs) {
static const int kVersion = 0;
static const unsigned kKeySizeInBytes = 16; // AES-128
static const unsigned kIVSizeInBytes = 16; // AES's block size
static const unsigned kPadSize = 4096; // we pad up to 4KB,
// This is a DER encoded, ANSI X9.62 CurveParams object which simply
// specifies P256.
static const uint8 kANSIX962CurveParams[] = {
0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07
};
Pickle p;
p.WriteString(hostname);
p.WriteInt(der_certs.size());
for (std::vector<std::string>::const_iterator
i = der_certs.begin(); i != der_certs.end(); i++) {
p.WriteString(*i);
}
// We pad to eliminate the possibility that someone could see the size of
// an upload and use that information to reduce the anonymity set of the
// certificate chain.
// The "2*sizeof(uint32)" here covers the padding length which we add next
// and Pickle's internal length which it includes at the beginning of the
// data.
unsigned pad_bytes = kPadSize - ((p.size() + 2*sizeof(uint32)) % kPadSize);
p.WriteUInt32(pad_bytes);
char* padding = new char[pad_bytes];
memset(padding, 0, pad_bytes);
p.WriteData(padding, pad_bytes);
delete[] padding;
// We generate a random public value and perform a DH key agreement with
// the server's fixed value.
SECKEYPublicKey* pub_key = NULL;
SECKEYPrivateKey* priv_key = NULL;
SECItem ec_der_params;
memset(&ec_der_params, 0, sizeof(ec_der_params));
ec_der_params.data = const_cast<uint8*>(kANSIX962CurveParams);
ec_der_params.len = sizeof(kANSIX962CurveParams);
priv_key = SECKEY_CreateECPrivateKey(&ec_der_params, &pub_key, NULL);
SECKEYPublicKey* server_pub_key = GetServerPubKey();
// This extracts the big-endian, x value of the shared point.
// The values of the arguments match ssl3_SendECDHClientKeyExchange in NSS
// 3.12.8's lib/ssl/ssl3ecc.c
PK11SymKey* pms = PK11_PubDeriveWithKDF(
priv_key, server_pub_key, PR_FALSE /* is sender */,
NULL /* random a */, NULL /* random b */, CKM_ECDH1_DERIVE,
CKM_TLS_MASTER_KEY_DERIVE_DH, CKA_DERIVE, 0 /* key size */,
CKD_NULL /* KDF */, NULL /* shared data */, NULL /* wincx */);
SECKEY_DestroyPublicKey(server_pub_key);
SECStatus rv = PK11_ExtractKeyValue(pms);
DCHECK_EQ(SECSuccess, rv);
SECItem* x_data = PK11_GetKeyData(pms);
// The key and IV are 128-bits and generated from a SHA256 hash of the x
// value.
char key_data[SHA256_LENGTH];
HASH_HashBuf(HASH_AlgSHA256, reinterpret_cast<uint8*>(key_data),
x_data->data, x_data->len);
PK11_FreeSymKey(pms);
DCHECK_GE(sizeof(key_data), kKeySizeInBytes + kIVSizeInBytes);
std::string raw_key(key_data, kKeySizeInBytes);
scoped_ptr<base::SymmetricKey> symkey(
base::SymmetricKey::Import(base::SymmetricKey::AES, raw_key));
std::string iv(key_data + kKeySizeInBytes, kIVSizeInBytes);
base::Encryptor encryptor;
bool r = encryptor.Init(symkey.get(), base::Encryptor::CBC, iv);
CHECK(r);
std::string plaintext(reinterpret_cast<const char*>(p.data()), p.size());
std::string ciphertext;
encryptor.Encrypt(plaintext, &ciphertext);
// We use another Pickle object to serialise the 'outer' wrapping of the
// plaintext.
Pickle outer;
outer.WriteInt(kVersion);
SECItem* pub_key_serialized = SECKEY_EncodeDERSubjectPublicKeyInfo(pub_key);
outer.WriteString(
std::string(reinterpret_cast<char*>(pub_key_serialized->data),
pub_key_serialized->len));
SECITEM_FreeItem(pub_key_serialized, PR_TRUE);
outer.WriteString(ciphertext);
SECKEY_DestroyPublicKey(pub_key);
SECKEY_DestroyPrivateKey(priv_key);
return std::string(reinterpret_cast<const char*>(outer.data()),
outer.size());
}
void DnsCertProvenanceChecker::DoAsyncLookup(
const std::string& hostname,
const std::vector<base::StringPiece>& der_certs,
DnsRRResolver* dnsrr_resolver,
Delegate* delegate) {
DnsCertProvenanceCheck* check = new DnsCertProvenanceCheck(
hostname, dnsrr_resolver, delegate, der_certs);
check->Start();
}
DnsCertProvenanceChecker::Delegate::~Delegate() {
}
DnsCertProvenanceChecker::~DnsCertProvenanceChecker() {
}
} // namespace net
#else // USE_OPENSSL
namespace net {
std::string DnsCertProvenanceChecker::BuildEncryptedReport(
const std::string& hostname,
const std::vector<std::string>& der_certs) {
return "";
}
void DnsCertProvenanceChecker::DoAsyncLookup(
const std::string& hostname,
const std::vector<base::StringPiece>& der_certs,
DnsRRResolver* dnsrr_resolver,
Delegate* delegate) {
}
DnsCertProvenanceChecker::Delegate::~Delegate() {
}
DnsCertProvenanceChecker::~DnsCertProvenanceChecker() {
}
} // namespace net
#endif // USE_OPENSSL
<commit_msg>net: update the DNS provenance host<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/socket/dns_cert_provenance_checker.h"
#if !defined(USE_OPENSSL)
#include <nspr.h>
#include <hasht.h>
#include <keyhi.h>
#include <pk11pub.h>
#include <sechash.h>
#include <set>
#include <string>
#include "base/basictypes.h"
#include "base/crypto/encryptor.h"
#include "base/crypto/symmetric_key.h"
#include "base/lazy_instance.h"
#include "base/non_thread_safe.h"
#include "base/pickle.h"
#include "base/scoped_ptr.h"
#include "net/base/completion_callback.h"
#include "net/base/dns_util.h"
#include "net/base/dnsrr_resolver.h"
#include "net/base/net_errors.h"
#include "net/base/net_log.h"
namespace net {
namespace {
// A DER encoded SubjectPublicKeyInfo structure containing the server's public
// key.
const uint8 kServerPublicKey[] = {
0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01,
0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00,
0x04, 0xc7, 0xea, 0x88, 0x60, 0x52, 0xe3, 0xa3, 0x3e, 0x39, 0x92, 0x0f, 0xa4,
0x3d, 0xba, 0xd8, 0x02, 0x2d, 0x06, 0x4d, 0x64, 0x98, 0x66, 0xb4, 0x82, 0xf0,
0x23, 0xa6, 0xd8, 0x37, 0x55, 0x7c, 0x01, 0xbf, 0x18, 0xd8, 0x16, 0x9e, 0x66,
0xdc, 0x49, 0xbf, 0x2e, 0x86, 0xe3, 0x99, 0xbd, 0xb3, 0x75, 0x25, 0x61, 0x04,
0x6c, 0x2e, 0xfb, 0x32, 0x42, 0x27, 0xe4, 0x23, 0xea, 0xcd, 0x81, 0x62, 0xc1,
};
const unsigned kMaxUploadsPerSession = 10;
// DnsCertLimits is a singleton class which keeps track of which hosts we have
// uploaded reports for in this session. Since some users will be behind MITM
// proxies, they would otherwise upload for every host and we don't wish to
// spam the upload server.
class DnsCertLimits {
public:
DnsCertLimits() { }
// HaveReachedMaxUploads returns true iff we have uploaded the maximum number
// of DNS certificate reports for this session.
bool HaveReachedMaxUploads() {
return uploaded_hostnames_.size() >= kMaxUploadsPerSession;
}
// HaveReachedMaxUploads returns true iff we have already uploaded a report
// about the given hostname in this session.
bool HaveUploadedForHostname(const std::string& hostname) {
return uploaded_hostnames_.count(hostname) > 0;
}
void DidUpload(const std::string& hostname) {
uploaded_hostnames_.insert(hostname);
}
private:
friend struct base::DefaultLazyInstanceTraits<DnsCertLimits>;
std::set<std::string> uploaded_hostnames_;
DISALLOW_COPY_AND_ASSIGN(DnsCertLimits);
};
static base::LazyInstance<DnsCertLimits> g_dns_cert_limits(
base::LINKER_INITIALIZED);
// DnsCertProvenanceCheck performs the DNS lookup of the certificate. This
// class is self-deleting.
class DnsCertProvenanceCheck : public NonThreadSafe {
public:
DnsCertProvenanceCheck(
const std::string& hostname,
DnsRRResolver* dnsrr_resolver,
DnsCertProvenanceChecker::Delegate* delegate,
const std::vector<base::StringPiece>& der_certs)
: hostname_(hostname),
dnsrr_resolver_(dnsrr_resolver),
delegate_(delegate),
der_certs_(der_certs.size()),
handle_(DnsRRResolver::kInvalidHandle),
ALLOW_THIS_IN_INITIALIZER_LIST(callback_(
this, &DnsCertProvenanceCheck::ResolutionComplete)) {
for (size_t i = 0; i < der_certs.size(); i++)
der_certs_[i] = der_certs[i].as_string();
}
void Start() {
DCHECK(CalledOnValidThread());
if (der_certs_.empty())
return;
DnsCertLimits* const limits = g_dns_cert_limits.Pointer();
if (limits->HaveReachedMaxUploads() ||
limits->HaveUploadedForHostname(hostname_)) {
return;
}
uint8 fingerprint[SHA1_LENGTH];
SECStatus rv = HASH_HashBuf(
HASH_AlgSHA1, fingerprint, (uint8*) der_certs_[0].data(),
der_certs_[0].size());
DCHECK_EQ(SECSuccess, rv);
char fingerprint_hex[SHA1_LENGTH * 2 + 1];
for (unsigned i = 0; i < sizeof(fingerprint); i++) {
static const char hextable[] = "0123456789abcdef";
fingerprint_hex[i*2] = hextable[fingerprint[i] >> 4];
fingerprint_hex[i*2 + 1] = hextable[fingerprint[i] & 15];
}
fingerprint_hex[SHA1_LENGTH * 2] = 0;
static const char kBaseCertName[] = ".certs.googlednstest.com";
domain_.assign(fingerprint_hex);
domain_.append(kBaseCertName);
handle_ = dnsrr_resolver_->Resolve(
domain_, kDNS_TXT, 0 /* flags */, &callback_, &response_,
0 /* priority */, BoundNetLog());
if (handle_ == DnsRRResolver::kInvalidHandle) {
LOG(ERROR) << "Failed to resolve " << domain_ << " for " << hostname_;
delete this;
}
}
private:
void ResolutionComplete(int status) {
DCHECK(CalledOnValidThread());
if (status == ERR_NAME_NOT_RESOLVED ||
(status == OK && response_.rrdatas.empty())) {
LOG(ERROR) << "FAILED"
<< " hostname:" << hostname_
<< " domain:" << domain_;
g_dns_cert_limits.Get().DidUpload(hostname_);
delegate_->OnDnsCertLookupFailed(hostname_, der_certs_);
} else if (status == OK) {
LOG(ERROR) << "GOOD"
<< " hostname:" << hostname_
<< " resp:" << response_.rrdatas[0];
} else {
LOG(ERROR) << "Unknown error " << status << " for " << domain_;
}
delete this;
}
const std::string hostname_;
std::string domain_;
DnsRRResolver* dnsrr_resolver_;
DnsCertProvenanceChecker::Delegate* const delegate_;
std::vector<std::string> der_certs_;
RRResponse response_;
DnsRRResolver::Handle handle_;
CompletionCallbackImpl<DnsCertProvenanceCheck> callback_;
};
SECKEYPublicKey* GetServerPubKey() {
SECItem der;
memset(&der, 0, sizeof(der));
der.data = const_cast<uint8*>(kServerPublicKey);
der.len = sizeof(kServerPublicKey);
CERTSubjectPublicKeyInfo* spki = SECKEY_DecodeDERSubjectPublicKeyInfo(&der);
SECKEYPublicKey* public_key = SECKEY_ExtractPublicKey(spki);
SECKEY_DestroySubjectPublicKeyInfo(spki);
return public_key;
}
} // namespace
// static
std::string DnsCertProvenanceChecker::BuildEncryptedReport(
const std::string& hostname,
const std::vector<std::string>& der_certs) {
static const int kVersion = 0;
static const unsigned kKeySizeInBytes = 16; // AES-128
static const unsigned kIVSizeInBytes = 16; // AES's block size
static const unsigned kPadSize = 4096; // we pad up to 4KB,
// This is a DER encoded, ANSI X9.62 CurveParams object which simply
// specifies P256.
static const uint8 kANSIX962CurveParams[] = {
0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07
};
Pickle p;
p.WriteString(hostname);
p.WriteInt(der_certs.size());
for (std::vector<std::string>::const_iterator
i = der_certs.begin(); i != der_certs.end(); i++) {
p.WriteString(*i);
}
// We pad to eliminate the possibility that someone could see the size of
// an upload and use that information to reduce the anonymity set of the
// certificate chain.
// The "2*sizeof(uint32)" here covers the padding length which we add next
// and Pickle's internal length which it includes at the beginning of the
// data.
unsigned pad_bytes = kPadSize - ((p.size() + 2*sizeof(uint32)) % kPadSize);
p.WriteUInt32(pad_bytes);
char* padding = new char[pad_bytes];
memset(padding, 0, pad_bytes);
p.WriteData(padding, pad_bytes);
delete[] padding;
// We generate a random public value and perform a DH key agreement with
// the server's fixed value.
SECKEYPublicKey* pub_key = NULL;
SECKEYPrivateKey* priv_key = NULL;
SECItem ec_der_params;
memset(&ec_der_params, 0, sizeof(ec_der_params));
ec_der_params.data = const_cast<uint8*>(kANSIX962CurveParams);
ec_der_params.len = sizeof(kANSIX962CurveParams);
priv_key = SECKEY_CreateECPrivateKey(&ec_der_params, &pub_key, NULL);
SECKEYPublicKey* server_pub_key = GetServerPubKey();
// This extracts the big-endian, x value of the shared point.
// The values of the arguments match ssl3_SendECDHClientKeyExchange in NSS
// 3.12.8's lib/ssl/ssl3ecc.c
PK11SymKey* pms = PK11_PubDeriveWithKDF(
priv_key, server_pub_key, PR_FALSE /* is sender */,
NULL /* random a */, NULL /* random b */, CKM_ECDH1_DERIVE,
CKM_TLS_MASTER_KEY_DERIVE_DH, CKA_DERIVE, 0 /* key size */,
CKD_NULL /* KDF */, NULL /* shared data */, NULL /* wincx */);
SECKEY_DestroyPublicKey(server_pub_key);
SECStatus rv = PK11_ExtractKeyValue(pms);
DCHECK_EQ(SECSuccess, rv);
SECItem* x_data = PK11_GetKeyData(pms);
// The key and IV are 128-bits and generated from a SHA256 hash of the x
// value.
char key_data[SHA256_LENGTH];
HASH_HashBuf(HASH_AlgSHA256, reinterpret_cast<uint8*>(key_data),
x_data->data, x_data->len);
PK11_FreeSymKey(pms);
DCHECK_GE(sizeof(key_data), kKeySizeInBytes + kIVSizeInBytes);
std::string raw_key(key_data, kKeySizeInBytes);
scoped_ptr<base::SymmetricKey> symkey(
base::SymmetricKey::Import(base::SymmetricKey::AES, raw_key));
std::string iv(key_data + kKeySizeInBytes, kIVSizeInBytes);
base::Encryptor encryptor;
bool r = encryptor.Init(symkey.get(), base::Encryptor::CBC, iv);
CHECK(r);
std::string plaintext(reinterpret_cast<const char*>(p.data()), p.size());
std::string ciphertext;
encryptor.Encrypt(plaintext, &ciphertext);
// We use another Pickle object to serialise the 'outer' wrapping of the
// plaintext.
Pickle outer;
outer.WriteInt(kVersion);
SECItem* pub_key_serialized = SECKEY_EncodeDERSubjectPublicKeyInfo(pub_key);
outer.WriteString(
std::string(reinterpret_cast<char*>(pub_key_serialized->data),
pub_key_serialized->len));
SECITEM_FreeItem(pub_key_serialized, PR_TRUE);
outer.WriteString(ciphertext);
SECKEY_DestroyPublicKey(pub_key);
SECKEY_DestroyPrivateKey(priv_key);
return std::string(reinterpret_cast<const char*>(outer.data()),
outer.size());
}
void DnsCertProvenanceChecker::DoAsyncLookup(
const std::string& hostname,
const std::vector<base::StringPiece>& der_certs,
DnsRRResolver* dnsrr_resolver,
Delegate* delegate) {
DnsCertProvenanceCheck* check = new DnsCertProvenanceCheck(
hostname, dnsrr_resolver, delegate, der_certs);
check->Start();
}
DnsCertProvenanceChecker::Delegate::~Delegate() {
}
DnsCertProvenanceChecker::~DnsCertProvenanceChecker() {
}
} // namespace net
#else // USE_OPENSSL
namespace net {
std::string DnsCertProvenanceChecker::BuildEncryptedReport(
const std::string& hostname,
const std::vector<std::string>& der_certs) {
return "";
}
void DnsCertProvenanceChecker::DoAsyncLookup(
const std::string& hostname,
const std::vector<base::StringPiece>& der_certs,
DnsRRResolver* dnsrr_resolver,
Delegate* delegate) {
}
DnsCertProvenanceChecker::Delegate::~Delegate() {
}
DnsCertProvenanceChecker::~DnsCertProvenanceChecker() {
}
} // namespace net
#endif // USE_OPENSSL
<|endoftext|> |
<commit_before>// Copyright 2015-2019 Elviss Strazdins. All rights reserved.
#include "core/Setup.h"
#if OUZEL_COMPILE_DIRECT3D11
#include <stdexcept>
#include "D3D11Shader.hpp"
#include "D3D11RenderDevice.hpp"
namespace ouzel
{
namespace graphics
{
namespace d3d11
{
namespace
{
constexpr DXGI_FORMAT getVertexFormat(DataType dataType)
{
switch (dataType)
{
case DataType::Byte: return DXGI_FORMAT_R8_SINT;
case DataType::ByteNorm: return DXGI_FORMAT_R8_SNORM;
case DataType::UnsignedByte: return DXGI_FORMAT_R8_UINT;
case DataType::UnsignedByteNorm: return DXGI_FORMAT_R8_UNORM;
case DataType::ByteVector2: return DXGI_FORMAT_R8G8_SINT;
case DataType::ByteVector2Norm: return DXGI_FORMAT_R8G8_SNORM;
case DataType::UnsignedByteVector2: return DXGI_FORMAT_R8G8_UINT;
case DataType::UnsignedByteVector2Norm: return DXGI_FORMAT_R8G8_UNORM;
case DataType::ByteVector3: return DXGI_FORMAT_UNKNOWN;
case DataType::ByteVector3Norm: return DXGI_FORMAT_UNKNOWN;
case DataType::UnsignedByteVector3: return DXGI_FORMAT_UNKNOWN;
case DataType::UnsignedByteVector3Norm: return DXGI_FORMAT_UNKNOWN;
case DataType::ByteVector4: return DXGI_FORMAT_R8G8B8A8_SINT;
case DataType::ByteVector4Norm: return DXGI_FORMAT_R8G8B8A8_SNORM;
case DataType::UnsignedByteVector4: return DXGI_FORMAT_R8G8B8A8_UINT;
case DataType::UnsignedByteVector4Norm: return DXGI_FORMAT_R8G8B8A8_UNORM;
case DataType::Short: return DXGI_FORMAT_R16_SINT;
case DataType::ShortNorm: return DXGI_FORMAT_R16_SNORM;
case DataType::UnsignedShort: return DXGI_FORMAT_R16_UINT;
case DataType::UnsignedShortNorm: return DXGI_FORMAT_R16_UNORM;
case DataType::ShortVector2: return DXGI_FORMAT_R16G16_SINT;
case DataType::ShortVector2Norm: return DXGI_FORMAT_R16G16_SNORM;
case DataType::UnsignedShortVector2: return DXGI_FORMAT_R16G16_UINT;
case DataType::UnsignedShortVector2Norm: return DXGI_FORMAT_R16G16_UNORM;
case DataType::ShortVector3: return DXGI_FORMAT_UNKNOWN;
case DataType::ShortVector3Norm: return DXGI_FORMAT_UNKNOWN;
case DataType::UnsignedShortVector3: return DXGI_FORMAT_UNKNOWN;
case DataType::UnsignedShortVector3Norm: return DXGI_FORMAT_UNKNOWN;
case DataType::ShortVector4: return DXGI_FORMAT_R16G16B16A16_SINT;
case DataType::ShortVector4Norm: return DXGI_FORMAT_R16G16B16A16_SNORM;
case DataType::UnsignedShortVector4: return DXGI_FORMAT_R16G16B16A16_UINT;
case DataType::UnsignedShortVector4Norm: return DXGI_FORMAT_R16G16B16A16_UNORM;
case DataType::Integer: return DXGI_FORMAT_R32_SINT;
case DataType::UnsignedInteger: return DXGI_FORMAT_R32_UINT;
case DataType::IntegerVector2: return DXGI_FORMAT_R32G32_SINT;
case DataType::UnsignedIntegerVector2: return DXGI_FORMAT_R32G32_UINT;
case DataType::IntegerVector3: return DXGI_FORMAT_R32G32B32_SINT;
case DataType::UnsignedIntegerVector3: return DXGI_FORMAT_R32G32B32_UINT;
case DataType::IntegerVector4: return DXGI_FORMAT_R32G32B32A32_SINT;
case DataType::UnsignedIntegerVector4: return DXGI_FORMAT_R32G32B32A32_UINT;
case DataType::Float: return DXGI_FORMAT_R32_FLOAT;
case DataType::FloatVector2: return DXGI_FORMAT_R32G32_FLOAT;
case DataType::FloatVector3: return DXGI_FORMAT_R32G32B32_FLOAT;
case DataType::FloatVector4: return DXGI_FORMAT_R32G32B32A32_FLOAT;
case DataType::FloatMatrix3: return DXGI_FORMAT_UNKNOWN;
case DataType::FloatMatrix4: return DXGI_FORMAT_UNKNOWN;
default: throw std::runtime_error("Invalid data type");
}
}
}
Shader::Shader(RenderDevice& initRenderDevice,
const std::vector<uint8_t>& fragmentShaderData,
const std::vector<uint8_t>& vertexShaderData,
const std::set<Vertex::Attribute::Usage>& initVertexAttributes,
const std::vector<std::pair<std::string, DataType>>& initFragmentShaderConstantInfo,
const std::vector<std::pair<std::string, DataType>>& initVertexShaderConstantInfo,
uint32_t,
uint32_t,
const std::string&,
const std::string&):
RenderResource(initRenderDevice),
vertexAttributes(initVertexAttributes),
fragmentShaderConstantInfo(initFragmentShaderConstantInfo),
vertexShaderConstantInfo(initVertexShaderConstantInfo)
{
HRESULT hr;
if (FAILED(hr = renderDevice.getDevice()->CreatePixelShader(fragmentShaderData.data(), fragmentShaderData.size(), nullptr, &fragmentShader)))
throw std::system_error(hr, getErrorCategory(), "Failed to create a Direct3D 11 pixel shader");
if (FAILED(hr = renderDevice.getDevice()->CreateVertexShader(vertexShaderData.data(), vertexShaderData.size(), nullptr, &vertexShader)))
throw std::system_error(hr, getErrorCategory(), "Failed to create a Direct3D 11 vertex shader");
std::vector<D3D11_INPUT_ELEMENT_DESC> vertexInputElements;
UINT offset = 0;
for (const Vertex::Attribute& vertexAttribute : RenderDevice::VERTEX_ATTRIBUTES)
{
if (vertexAttributes.find(vertexAttribute.usage) != vertexAttributes.end())
{
DXGI_FORMAT vertexFormat = getVertexFormat(vertexAttribute.dataType);
if (vertexFormat == DXGI_FORMAT_UNKNOWN)
throw std::runtime_error("Invalid vertex format");
const char* semantic;
UINT index = 0;
switch (vertexAttribute.usage)
{
case Vertex::Attribute::Usage::Binormal:
semantic = "BINORMAL";
break;
case Vertex::Attribute::Usage::BlendIndices:
semantic = "BLENDINDICES";
break;
case Vertex::Attribute::Usage::BlendWeight:
semantic = "BLENDWEIGHT";
break;
case Vertex::Attribute::Usage::Color:
semantic = "COLOR";
break;
case Vertex::Attribute::Usage::Normal:
semantic = "NORMAL";
break;
case Vertex::Attribute::Usage::Position:
semantic = "POSITION";
break;
case Vertex::Attribute::Usage::PositionTransformed:
semantic = "POSITIONT";
break;
case Vertex::Attribute::Usage::PointSize:
semantic = "PSIZE";
break;
case Vertex::Attribute::Usage::Tangent:
semantic = "TANGENT";
break;
case Vertex::Attribute::Usage::TextureCoordinates0:
semantic = "TEXCOORD";
break;
case Vertex::Attribute::Usage::TextureCoordinates1:
semantic = "TEXCOORD";
index = 1;
break;
default:
throw std::runtime_error("Invalid vertex attribute usage");
}
vertexInputElements.push_back({
semantic, index,
vertexFormat,
0, offset, D3D11_INPUT_PER_VERTEX_DATA, 0
});
}
offset += getDataTypeSize(vertexAttribute.dataType);
}
if (inputLayout) inputLayout->Release();
if (FAILED(hr = renderDevice.getDevice()->CreateInputLayout(vertexInputElements.data(),
static_cast<UINT>(vertexInputElements.size()),
vertexShaderData.data(),
vertexShaderData.size(),
&inputLayout)))
throw std::system_error(hr, getErrorCategory(), "Failed to create Direct3D 11 input layout for vertex shader");
if (!fragmentShaderConstantInfo.empty())
{
fragmentShaderConstantLocations.reserve(fragmentShaderConstantInfo.size());
for (const std::pair<std::string, DataType>& info : fragmentShaderConstantInfo)
{
const uint32_t size = getDataTypeSize(info.second);
fragmentShaderConstantLocations.emplace_back(fragmentShaderConstantSize, size);
fragmentShaderConstantSize += size;
}
}
D3D11_BUFFER_DESC fragmentShaderConstantBufferDesc;
fragmentShaderConstantBufferDesc.ByteWidth = static_cast<UINT>(fragmentShaderConstantSize);
fragmentShaderConstantBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
fragmentShaderConstantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
fragmentShaderConstantBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
fragmentShaderConstantBufferDesc.MiscFlags = 0;
fragmentShaderConstantBufferDesc.StructureByteStride = 0;
if (fragmentShaderConstantBuffer) fragmentShaderConstantBuffer->Release();
if (FAILED(hr = renderDevice.getDevice()->CreateBuffer(&fragmentShaderConstantBufferDesc, nullptr, &fragmentShaderConstantBuffer)))
throw std::system_error(hr, getErrorCategory(), "Failed to create Direct3D 11 constant buffer");
if (!vertexShaderConstantInfo.empty())
{
vertexShaderConstantLocations.reserve(vertexShaderConstantInfo.size());
for (const std::pair<std::string, DataType>& info : vertexShaderConstantInfo)
{
const uint32_t size = getDataTypeSize(info.second);
vertexShaderConstantLocations.emplace_back(vertexShaderConstantSize, size);
vertexShaderConstantSize += size;
}
}
D3D11_BUFFER_DESC vertexShaderConstantBufferDesc;
vertexShaderConstantBufferDesc.ByteWidth = static_cast<UINT>(vertexShaderConstantSize);
vertexShaderConstantBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
vertexShaderConstantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
vertexShaderConstantBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
vertexShaderConstantBufferDesc.MiscFlags = 0;
vertexShaderConstantBufferDesc.StructureByteStride = 0;
if (vertexShaderConstantBuffer) vertexShaderConstantBuffer->Release();
if (FAILED(hr = renderDevice.getDevice()->CreateBuffer(&vertexShaderConstantBufferDesc, nullptr, &vertexShaderConstantBuffer)))
throw std::system_error(hr, getErrorCategory(), "Failed to create Direct3D 11 constant buffer");
}
Shader::~Shader()
{
if (fragmentShader)
fragmentShader->Release();
if (vertexShader)
vertexShader->Release();
if (inputLayout)
inputLayout->Release();
if (fragmentShaderConstantBuffer)
fragmentShaderConstantBuffer->Release();
if (vertexShaderConstantBuffer)
vertexShaderConstantBuffer->Release();
}
} // namespace d3d11
} // namespace graphics
} // namespace ouzel
#endif
<commit_msg>Don't check if pointers are set in the D3D11Shader constructor<commit_after>// Copyright 2015-2019 Elviss Strazdins. All rights reserved.
#include "core/Setup.h"
#if OUZEL_COMPILE_DIRECT3D11
#include <stdexcept>
#include "D3D11Shader.hpp"
#include "D3D11RenderDevice.hpp"
namespace ouzel
{
namespace graphics
{
namespace d3d11
{
namespace
{
constexpr DXGI_FORMAT getVertexFormat(DataType dataType)
{
switch (dataType)
{
case DataType::Byte: return DXGI_FORMAT_R8_SINT;
case DataType::ByteNorm: return DXGI_FORMAT_R8_SNORM;
case DataType::UnsignedByte: return DXGI_FORMAT_R8_UINT;
case DataType::UnsignedByteNorm: return DXGI_FORMAT_R8_UNORM;
case DataType::ByteVector2: return DXGI_FORMAT_R8G8_SINT;
case DataType::ByteVector2Norm: return DXGI_FORMAT_R8G8_SNORM;
case DataType::UnsignedByteVector2: return DXGI_FORMAT_R8G8_UINT;
case DataType::UnsignedByteVector2Norm: return DXGI_FORMAT_R8G8_UNORM;
case DataType::ByteVector3: return DXGI_FORMAT_UNKNOWN;
case DataType::ByteVector3Norm: return DXGI_FORMAT_UNKNOWN;
case DataType::UnsignedByteVector3: return DXGI_FORMAT_UNKNOWN;
case DataType::UnsignedByteVector3Norm: return DXGI_FORMAT_UNKNOWN;
case DataType::ByteVector4: return DXGI_FORMAT_R8G8B8A8_SINT;
case DataType::ByteVector4Norm: return DXGI_FORMAT_R8G8B8A8_SNORM;
case DataType::UnsignedByteVector4: return DXGI_FORMAT_R8G8B8A8_UINT;
case DataType::UnsignedByteVector4Norm: return DXGI_FORMAT_R8G8B8A8_UNORM;
case DataType::Short: return DXGI_FORMAT_R16_SINT;
case DataType::ShortNorm: return DXGI_FORMAT_R16_SNORM;
case DataType::UnsignedShort: return DXGI_FORMAT_R16_UINT;
case DataType::UnsignedShortNorm: return DXGI_FORMAT_R16_UNORM;
case DataType::ShortVector2: return DXGI_FORMAT_R16G16_SINT;
case DataType::ShortVector2Norm: return DXGI_FORMAT_R16G16_SNORM;
case DataType::UnsignedShortVector2: return DXGI_FORMAT_R16G16_UINT;
case DataType::UnsignedShortVector2Norm: return DXGI_FORMAT_R16G16_UNORM;
case DataType::ShortVector3: return DXGI_FORMAT_UNKNOWN;
case DataType::ShortVector3Norm: return DXGI_FORMAT_UNKNOWN;
case DataType::UnsignedShortVector3: return DXGI_FORMAT_UNKNOWN;
case DataType::UnsignedShortVector3Norm: return DXGI_FORMAT_UNKNOWN;
case DataType::ShortVector4: return DXGI_FORMAT_R16G16B16A16_SINT;
case DataType::ShortVector4Norm: return DXGI_FORMAT_R16G16B16A16_SNORM;
case DataType::UnsignedShortVector4: return DXGI_FORMAT_R16G16B16A16_UINT;
case DataType::UnsignedShortVector4Norm: return DXGI_FORMAT_R16G16B16A16_UNORM;
case DataType::Integer: return DXGI_FORMAT_R32_SINT;
case DataType::UnsignedInteger: return DXGI_FORMAT_R32_UINT;
case DataType::IntegerVector2: return DXGI_FORMAT_R32G32_SINT;
case DataType::UnsignedIntegerVector2: return DXGI_FORMAT_R32G32_UINT;
case DataType::IntegerVector3: return DXGI_FORMAT_R32G32B32_SINT;
case DataType::UnsignedIntegerVector3: return DXGI_FORMAT_R32G32B32_UINT;
case DataType::IntegerVector4: return DXGI_FORMAT_R32G32B32A32_SINT;
case DataType::UnsignedIntegerVector4: return DXGI_FORMAT_R32G32B32A32_UINT;
case DataType::Float: return DXGI_FORMAT_R32_FLOAT;
case DataType::FloatVector2: return DXGI_FORMAT_R32G32_FLOAT;
case DataType::FloatVector3: return DXGI_FORMAT_R32G32B32_FLOAT;
case DataType::FloatVector4: return DXGI_FORMAT_R32G32B32A32_FLOAT;
case DataType::FloatMatrix3: return DXGI_FORMAT_UNKNOWN;
case DataType::FloatMatrix4: return DXGI_FORMAT_UNKNOWN;
default: throw std::runtime_error("Invalid data type");
}
}
}
Shader::Shader(RenderDevice& initRenderDevice,
const std::vector<uint8_t>& fragmentShaderData,
const std::vector<uint8_t>& vertexShaderData,
const std::set<Vertex::Attribute::Usage>& initVertexAttributes,
const std::vector<std::pair<std::string, DataType>>& initFragmentShaderConstantInfo,
const std::vector<std::pair<std::string, DataType>>& initVertexShaderConstantInfo,
uint32_t,
uint32_t,
const std::string&,
const std::string&):
RenderResource(initRenderDevice),
vertexAttributes(initVertexAttributes),
fragmentShaderConstantInfo(initFragmentShaderConstantInfo),
vertexShaderConstantInfo(initVertexShaderConstantInfo)
{
HRESULT hr;
if (FAILED(hr = renderDevice.getDevice()->CreatePixelShader(fragmentShaderData.data(), fragmentShaderData.size(), nullptr, &fragmentShader)))
throw std::system_error(hr, getErrorCategory(), "Failed to create a Direct3D 11 pixel shader");
if (FAILED(hr = renderDevice.getDevice()->CreateVertexShader(vertexShaderData.data(), vertexShaderData.size(), nullptr, &vertexShader)))
throw std::system_error(hr, getErrorCategory(), "Failed to create a Direct3D 11 vertex shader");
std::vector<D3D11_INPUT_ELEMENT_DESC> vertexInputElements;
UINT offset = 0;
for (const Vertex::Attribute& vertexAttribute : RenderDevice::VERTEX_ATTRIBUTES)
{
if (vertexAttributes.find(vertexAttribute.usage) != vertexAttributes.end())
{
DXGI_FORMAT vertexFormat = getVertexFormat(vertexAttribute.dataType);
if (vertexFormat == DXGI_FORMAT_UNKNOWN)
throw std::runtime_error("Invalid vertex format");
const char* semantic;
UINT index = 0;
switch (vertexAttribute.usage)
{
case Vertex::Attribute::Usage::Binormal:
semantic = "BINORMAL";
break;
case Vertex::Attribute::Usage::BlendIndices:
semantic = "BLENDINDICES";
break;
case Vertex::Attribute::Usage::BlendWeight:
semantic = "BLENDWEIGHT";
break;
case Vertex::Attribute::Usage::Color:
semantic = "COLOR";
break;
case Vertex::Attribute::Usage::Normal:
semantic = "NORMAL";
break;
case Vertex::Attribute::Usage::Position:
semantic = "POSITION";
break;
case Vertex::Attribute::Usage::PositionTransformed:
semantic = "POSITIONT";
break;
case Vertex::Attribute::Usage::PointSize:
semantic = "PSIZE";
break;
case Vertex::Attribute::Usage::Tangent:
semantic = "TANGENT";
break;
case Vertex::Attribute::Usage::TextureCoordinates0:
semantic = "TEXCOORD";
break;
case Vertex::Attribute::Usage::TextureCoordinates1:
semantic = "TEXCOORD";
index = 1;
break;
default:
throw std::runtime_error("Invalid vertex attribute usage");
}
vertexInputElements.push_back({
semantic, index,
vertexFormat,
0, offset, D3D11_INPUT_PER_VERTEX_DATA, 0
});
}
offset += getDataTypeSize(vertexAttribute.dataType);
}
if (FAILED(hr = renderDevice.getDevice()->CreateInputLayout(vertexInputElements.data(),
static_cast<UINT>(vertexInputElements.size()),
vertexShaderData.data(),
vertexShaderData.size(),
&inputLayout)))
throw std::system_error(hr, getErrorCategory(), "Failed to create Direct3D 11 input layout for vertex shader");
if (!fragmentShaderConstantInfo.empty())
{
fragmentShaderConstantLocations.reserve(fragmentShaderConstantInfo.size());
for (const std::pair<std::string, DataType>& info : fragmentShaderConstantInfo)
{
const uint32_t size = getDataTypeSize(info.second);
fragmentShaderConstantLocations.emplace_back(fragmentShaderConstantSize, size);
fragmentShaderConstantSize += size;
}
}
D3D11_BUFFER_DESC fragmentShaderConstantBufferDesc;
fragmentShaderConstantBufferDesc.ByteWidth = static_cast<UINT>(fragmentShaderConstantSize);
fragmentShaderConstantBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
fragmentShaderConstantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
fragmentShaderConstantBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
fragmentShaderConstantBufferDesc.MiscFlags = 0;
fragmentShaderConstantBufferDesc.StructureByteStride = 0;
if (FAILED(hr = renderDevice.getDevice()->CreateBuffer(&fragmentShaderConstantBufferDesc, nullptr, &fragmentShaderConstantBuffer)))
throw std::system_error(hr, getErrorCategory(), "Failed to create Direct3D 11 constant buffer");
if (!vertexShaderConstantInfo.empty())
{
vertexShaderConstantLocations.reserve(vertexShaderConstantInfo.size());
for (const std::pair<std::string, DataType>& info : vertexShaderConstantInfo)
{
const uint32_t size = getDataTypeSize(info.second);
vertexShaderConstantLocations.emplace_back(vertexShaderConstantSize, size);
vertexShaderConstantSize += size;
}
}
D3D11_BUFFER_DESC vertexShaderConstantBufferDesc;
vertexShaderConstantBufferDesc.ByteWidth = static_cast<UINT>(vertexShaderConstantSize);
vertexShaderConstantBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
vertexShaderConstantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
vertexShaderConstantBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
vertexShaderConstantBufferDesc.MiscFlags = 0;
vertexShaderConstantBufferDesc.StructureByteStride = 0;
if (FAILED(hr = renderDevice.getDevice()->CreateBuffer(&vertexShaderConstantBufferDesc, nullptr, &vertexShaderConstantBuffer)))
throw std::system_error(hr, getErrorCategory(), "Failed to create Direct3D 11 constant buffer");
}
Shader::~Shader()
{
if (fragmentShader)
fragmentShader->Release();
if (vertexShader)
vertexShader->Release();
if (inputLayout)
inputLayout->Release();
if (fragmentShaderConstantBuffer)
fragmentShaderConstantBuffer->Release();
if (vertexShaderConstantBuffer)
vertexShaderConstantBuffer->Release();
}
} // namespace d3d11
} // namespace graphics
} // namespace ouzel
#endif
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
///
/// \file control.cpp
/// \brief Control the Pidar
/// Author: Jonathan Ulrich, Andrew Watson
/// Created: 3/1/14
/// Email: [email protected], [email protected]
///
////////////////////////////////////////////////////////////////////////////////
#include "control.hpp"
#include "global.hpp"
double current_position;
double previous_position;
std::vector<Point3D> laserscan;
std::deque<pcl_data> SendPoints;
using namespace Pidar;
using namespace PointCloud;
void InterruptService(void)
{
//Get Current and Previous Positions
current_position = maincontrol->GetMotorPositionDegrees();
previous_position = maincontrol->GetMotorPreviousPositionDegrees();
//Update Previous Motor Position
maincontrol->SetMotorPreviousPositionDegrees(current_position);
//Get Values to send for construction
laserscan = maincontrol->GetLaserScan();
//Send values and get newly constructed incompletescan
//this will update values as needed
maincontrol->AddToScanQueue(laserscan,
current_position,previous_position);
}
std::ifstream infile("../Pidar/sampledata.txt");
pcl_data GetSampleTXTFileData()
{
pcl_data Scan;
double a, b, c = 0.0;
std::string str;
int linecnt = 0;
std::string delimiter = ",";
std::string val;
while (std::getline(infile, str))
{
int x = 0;
size_t pos = 0;
while ((pos = str.find(delimiter)) != std::string::npos)
{
val = str.substr(0, pos);
if(x == 0)
{
a = atof(val.c_str());
x++;
}
else if(x == 1)
{
b = atof(val.c_str());
x++;
}
else if(x == 2)
{
c = atof(val.c_str());
x = 0;
}
str.erase(0, pos + delimiter.length());
}
pcl_point point;
point.r = a;
point.theta = b;
point.phi = c;
Scan.points.push_back(point);
linecnt++;
}
linecnt;
return Scan;
}
///
/// Controller Functions
///
Control::Control()
{
motor = new Motor::Dynamixel();
laser = new Laser::Hokuyo();
}
Control::~Control()
{
//Shutdown();
}
bool Control::Initialize()
{
//Test Switches
bool enableLaser = true;
bool enableMotor = true;
bool enableCOM = false; //Now in main, true here will take over main thread
bool enableISR = false;
// ///******* TESTING ONLY **********************************
//This is for testing only (remove when not testing)
pcl_data tmpscan = GetSampleTXTFileData();
tmpscan.id = 1; //initialization
tmpscan.speed = 88;
for(int i = 0; i<tmpscan.points.size()-1080;i+=1080)
{
pcl_data x;
for(int j = 0;j<1080;j++)
{
pcl_point y = tmpscan.points[i+j];
x.points.push_back(y);
}
SendPoints.push_back(x);
}
std::cout<<"Queue Length: "<<SendPoints.size()<<std::endl;
std::cout<<"control.cpp: ID: "<<tmpscan.id<<std::endl;
std::cout<<"control.cpp: r: "<<tmpscan.points[0].r<<std::endl;
std::cout<<"control.cpp: theta: "<<tmpscan.points[0].theta<<std::endl;
std::cout<<"control.cpp: phi: "<<tmpscan.points[0].phi<<std::endl;
// ///******** END TESTING LINES ****************************
if(enableLaser)
{
laser->RegisterCallback(&mpLasercallback);
laser->Initialize();
}
if(enableMotor)
{
motor->RegisterCallback(&mpMotorcallback);
motor->Initialize();
}
if(enableISR)
{
if (wiringPiSetup () < 0)
{
fprintf (stderr, "Unable to setup wiringPi: %s\n", strerror (errno));
// return 1;
}
// set Pin 17/0 generate an interrupt on low-to-high transitions
// and attach myInterrupt() to the interrupt
if ( wiringPiISR (HOKUYOSYNCPIN, INT_EDGE_RISING, InterruptService) < 0 )
{
fprintf (stderr, "Unable to setup ISR: %s\n", strerror (errno));
// return 1;
}
}
if(enableCOM)
{
try
{
//Start Web Server Thread
boost::asio::io_service io_service;
PointCloud::server s(io_service, boost::asio::ip::address::from_string("239.255.0.1"));
boost::thread bt(boost::bind(&boost::asio::io_service::run, &io_service));
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
}
return true;
}
///
/// Motor Functions
///
double Control::GetMotorPositionDegrees()
{
return motor->GetPositionDegrees();
}
double Control::GetMotorPreviousPositionDegrees()
{
return motor->GetPreviousPositionDegrees();
}
void Control::SetMotorPreviousPositionDegrees(double val)
{
motor->SetPreviousPositionDegrees(val);
}
void Control::StartMotor(int rpm)
{
Control::motor->SetSpeedRpm(rpm, true);
}
void Control::StopMotor()
{
Control::motor->SetSpeedRpm(0, true);
delay(1000);
Control::motor->Shutdown();
}
///
/// Laser Functions
///
void Control::StopLaser()
{
Control::laser->Shutdown();
}
std::vector<Point3D> Control::GetLaserScan()
{
return Control::mpLasercallback.mLaserScan;
}
///
/// Scan Management Functions
///
void Control::AddToScanQueue(std::vector<Point3D> laserscan,
double currentMotorPosition,
double previousMotorPosition)
{
int scancnt = laserscan.size();//1080;
//Check for complete scan & get delta
double delta_position = 0.0;
if (previousMotorPosition > currentMotorPosition)
{
delta_position = ((360-previousMotorPosition)+currentMotorPosition);
}
else
{
delta_position = (currentMotorPosition-previousMotorPosition);
}
pcl_data tmp;
for(int i = 0; i <= scancnt / 2; i++)
{
pcl_point point;
point.r = (laserscan[i]).GetX();
point.theta = (laserscan[i]).GetY();
point.phi = previousMotorPosition + (i*(delta_position/scancnt));
tmp.points.push_back(point);
}
for(int i = scancnt / 2; i < scancnt; i++)
{
pcl_point point;
point.r = (laserscan[i]).GetX();
point.theta = (laserscan[i]).GetY();
point.phi = 360.0 - previousMotorPosition + 180.0 + (i*(delta_position/scancnt));
tmp.points.push_back(point);
}
//Add scan to queue
if(SendPoints.size()>100){
SendPoints.clear();
std::cout<<"Queue Cleared Due To Congestion"<<std::endl;
}
SendPoints.push_back(tmp);
}
/*End of File */
<commit_msg>set ISR to true<commit_after>////////////////////////////////////////////////////////////////////////////////
///
/// \file control.cpp
/// \brief Control the Pidar
/// Author: Jonathan Ulrich, Andrew Watson
/// Created: 3/1/14
/// Email: [email protected], [email protected]
///
////////////////////////////////////////////////////////////////////////////////
#include "control.hpp"
#include "global.hpp"
double current_position;
double previous_position;
std::vector<Point3D> laserscan;
std::deque<pcl_data> SendPoints;
using namespace Pidar;
using namespace PointCloud;
void InterruptService(void)
{
//Get Current and Previous Positions
current_position = maincontrol->GetMotorPositionDegrees();
previous_position = maincontrol->GetMotorPreviousPositionDegrees();
//Update Previous Motor Position
maincontrol->SetMotorPreviousPositionDegrees(current_position);
//Get Values to send for construction
laserscan = maincontrol->GetLaserScan();
//Send values and get newly constructed incompletescan
//this will update values as needed
maincontrol->AddToScanQueue(laserscan,
current_position,previous_position);
}
std::ifstream infile("../Pidar/sampledata.txt");
pcl_data GetSampleTXTFileData()
{
pcl_data Scan;
double a, b, c = 0.0;
std::string str;
int linecnt = 0;
std::string delimiter = ",";
std::string val;
while (std::getline(infile, str))
{
int x = 0;
size_t pos = 0;
while ((pos = str.find(delimiter)) != std::string::npos)
{
val = str.substr(0, pos);
if(x == 0)
{
a = atof(val.c_str());
x++;
}
else if(x == 1)
{
b = atof(val.c_str());
x++;
}
else if(x == 2)
{
c = atof(val.c_str());
x = 0;
}
str.erase(0, pos + delimiter.length());
}
pcl_point point;
point.r = a;
point.theta = b;
point.phi = c;
Scan.points.push_back(point);
linecnt++;
}
linecnt;
return Scan;
}
///
/// Controller Functions
///
Control::Control()
{
motor = new Motor::Dynamixel();
laser = new Laser::Hokuyo();
}
Control::~Control()
{
//Shutdown();
}
bool Control::Initialize()
{
//Test Switches
bool enableLaser = true;
bool enableMotor = true;
bool enableCOM = false; //Now in main, true here will take over main thread
bool enableISR = true;
// ///******* TESTING ONLY **********************************
//This is for testing only (remove when not testing)
pcl_data tmpscan = GetSampleTXTFileData();
tmpscan.id = 1; //initialization
tmpscan.speed = 88;
for(int i = 0; i<tmpscan.points.size()-1080;i+=1080)
{
pcl_data x;
for(int j = 0;j<1080;j++)
{
pcl_point y = tmpscan.points[i+j];
x.points.push_back(y);
}
SendPoints.push_back(x);
}
std::cout<<"Queue Length: "<<SendPoints.size()<<std::endl;
std::cout<<"control.cpp: ID: "<<tmpscan.id<<std::endl;
std::cout<<"control.cpp: r: "<<tmpscan.points[0].r<<std::endl;
std::cout<<"control.cpp: theta: "<<tmpscan.points[0].theta<<std::endl;
std::cout<<"control.cpp: phi: "<<tmpscan.points[0].phi<<std::endl;
// ///******** END TESTING LINES ****************************
if(enableLaser)
{
laser->RegisterCallback(&mpLasercallback);
laser->Initialize();
}
if(enableMotor)
{
motor->RegisterCallback(&mpMotorcallback);
motor->Initialize();
}
if(enableISR)
{
if (wiringPiSetup () < 0)
{
fprintf (stderr, "Unable to setup wiringPi: %s\n", strerror (errno));
// return 1;
}
// set Pin 17/0 generate an interrupt on low-to-high transitions
// and attach myInterrupt() to the interrupt
if ( wiringPiISR (HOKUYOSYNCPIN, INT_EDGE_RISING, InterruptService) < 0 )
{
fprintf (stderr, "Unable to setup ISR: %s\n", strerror (errno));
// return 1;
}
}
if(enableCOM)
{
try
{
//Start Web Server Thread
boost::asio::io_service io_service;
PointCloud::server s(io_service, boost::asio::ip::address::from_string("239.255.0.1"));
boost::thread bt(boost::bind(&boost::asio::io_service::run, &io_service));
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
}
return true;
}
///
/// Motor Functions
///
double Control::GetMotorPositionDegrees()
{
return motor->GetPositionDegrees();
}
double Control::GetMotorPreviousPositionDegrees()
{
return motor->GetPreviousPositionDegrees();
}
void Control::SetMotorPreviousPositionDegrees(double val)
{
motor->SetPreviousPositionDegrees(val);
}
void Control::StartMotor(int rpm)
{
Control::motor->SetSpeedRpm(rpm, true);
}
void Control::StopMotor()
{
Control::motor->SetSpeedRpm(0, true);
delay(1000);
Control::motor->Shutdown();
}
///
/// Laser Functions
///
void Control::StopLaser()
{
Control::laser->Shutdown();
}
std::vector<Point3D> Control::GetLaserScan()
{
return Control::mpLasercallback.mLaserScan;
}
///
/// Scan Management Functions
///
void Control::AddToScanQueue(std::vector<Point3D> laserscan,
double currentMotorPosition,
double previousMotorPosition)
{
int scancnt = laserscan.size();//1080;
//Check for complete scan & get delta
double delta_position = 0.0;
if (previousMotorPosition > currentMotorPosition)
{
delta_position = ((360-previousMotorPosition)+currentMotorPosition);
}
else
{
delta_position = (currentMotorPosition-previousMotorPosition);
}
pcl_data tmp;
for(int i = 0; i <= scancnt / 2; i++)
{
pcl_point point;
point.r = (laserscan[i]).GetX();
point.theta = (laserscan[i]).GetY();
point.phi = previousMotorPosition + (i*(delta_position/scancnt));
tmp.points.push_back(point);
}
for(int i = scancnt / 2; i < scancnt; i++)
{
pcl_point point;
point.r = (laserscan[i]).GetX();
point.theta = (laserscan[i]).GetY();
point.phi = 360.0 - previousMotorPosition + 180.0 + (i*(delta_position/scancnt));
tmp.points.push_back(point);
}
//Add scan to queue
if(SendPoints.size()>100){
SendPoints.clear();
std::cout<<"Queue Cleared Due To Congestion"<<std::endl;
}
SendPoints.push_back(tmp);
}
/*End of File */
<|endoftext|> |
<commit_before>/*
* File: Cell.cpp
* Author: Ozan YILDIZ
*
* Created on November 25, 2015, 4:06 PM
*/
#ifndef REVERSI_H
#define REVERSI_H
#include <vector>
#include <string>
#include "Cell.h"
using namespace std;
class Reversi {
public:
Reversi();
Reversi(const Reversi& orig);
// Play Functions
void playGame();
void playGame(const int, const string);
// Output Function
void output() const;
// Ancestor & Mutators Functions
int getRow() const { return row; }
void setRow(const int temp) { row = temp; }
int getColumn() const { return column; }
void setColumn(const int temp) { column = temp; }
char getWho() const { return who; }
void setWho(const char newWho) { who = newWho; }
private:
vector<vector<Cell> > gameCell;
char who;
int row, column;
bool control(const int x, const int y, const char who);
void newValue();
void find(const int x, const string y);
};
#endif /* REVERSI_H */
<commit_msg>new Fundamental2<commit_after>/*
* File: Cell.cpp
* Author: Ozan YILDIZ
*
* Created on November 25, 2015, 4:06 PM
*/
#include <vector>
#include <string>
#include <iostream>
#include "Cell.h"
#include "Reversi.h"
Reversi::Reversi()
: row(5), column(6), who(0)
{
gameCell.resize(getRow());
for (int i = 0; i < getRow(); i++)
gameCell[i].resize(getColumn());
gameCell[0][0] = Cell();
gameCell[0][1] = Cell();
gameCell[1][0] = Cell();
gameCell[1][1] = Cell();
gameCell[1][2] = Cell();
}
Reversi::Reversi(const Reversi& orig)
{
}
//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
//
// PLAY FUNCTIONS
//
//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
void playGame()
{
}
void playGame(const int x, const string y)
{
}
//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
//
// OUTPUT FUNCTION
//
//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
void Reversi::output() const
{
for (int i = 0; i < getRow(); i++)
{
for (int j = 0; j < getColumn(); j++)
{
if (gameCell[i][j].getWho() == 0)
cout << " - ";
else
{
cout << gameCell[i][j].getWho();
cout << " i ";
}
}
cout << "\n";
}
return;
}
//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
//
// OTHER
//
//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
/*
* A-------B
* | |
* | |
* | |
* D-------C
*/
bool Reversi::control(const int x, const int y, const char who)
{
vector<vector<Cell> > gameCellTemp;
gameCellTemp = gameCell;
// A Corner
if (x == 0, y == 0)
{
if (gameCellTemp[x][y].getWho() == 0)
{
if (gameCellTemp[x][y + 1].getWho() != who && gameCellTemp[x][y + 1].getWho() != 0) // 5
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x + 1][y].getWho() != who && gameCellTemp[x + 1][y].getWho() != 0) // 7
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x + 1][y + 1].getWho() != who && gameCellTemp[x + 1][y + 1].getWho() != 0) // 8
{
// asdasdasdasdasdasd
}
}
}
// B Corner
else if (x == 0, y == getRow() - 1)
{
if (gameCellTemp[x][y].getWho() == 0)
{
if (gameCellTemp[x][y - 1].getWho() != who && gameCellTemp[x][y - 1].getWho() != 0) // 4
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x + 1][y - 1].getWho() != who && gameCellTemp[x + 1][y - 1].getWho() != 0) // 7
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x + 1][y].getWho() != who && gameCellTemp[x + 1][y].getWho() != 0) // 8
{
// asdasdasdasdasdasd
}
}
}
// C Corner
else if (x == getRow() - 1, y == 0)
{
if (gameCellTemp[x][y].getWho() == 0)
{
if (gameCellTemp[x - 1][y - 1].getWho() != who && gameCellTemp[x - 1][y - 1].getWho() != 0) // 1
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x - 1][y].getWho() != who && gameCellTemp[x - 1][y].getWho() != 0) // 2
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x][y - 1].getWho() != who && gameCellTemp[x][y - 1].getWho() != 0) // 4
{
// asdasdasdasdasdasd
}
}
}
// D Corner
else if (x == getRow() - 1, y == getColumn() - 1)
{
if (gameCellTemp[x][y].getWho() == 0)
{
if (gameCellTemp[x - 1][y].getWho() != who && gameCellTemp[x - 1][y].getWho() != 0) // 2
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x - 1][y + 1].getWho() != who && gameCellTemp[x - 1][y].getWho() != 0) // 3
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x][y + 1].getWho() != who && gameCellTemp[x][y + 1].getWho() != 0) // 5
{
// asdasdasdasdasdasd
}
}
}
// A-B Side
else if (x == 0)
{
if (gameCellTemp[x][y].getWho() == 0)
{
if (gameCellTemp[x][y - 1].getWho() != who && gameCellTemp[x][y - 1].getWho() != 0) // 4
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x][y + 1].getWho() != who && gameCellTemp[x][y + 1].getWho() != 0) // 5
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x + 1][y - 1].getWho() != who && gameCellTemp[x + 1][y - 1].getWho() != 0) // 6
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x + 1][y].getWho() != who && gameCellTemp[x + 1][y].getWho() != 0) // 7
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x][y - 1].getWho() != who && gameCellTemp[x][y - 1].getWho() != 0) // 8
{
// asdasdasdasdasdasd
}
}
}
// B-C Side
else if (y == getColumn() - 1)
{
if (gameCellTemp[x][y].getWho() == 0)
{
if (gameCellTemp[x - 1][y - 1].getWho() != who && gameCellTemp[x - 1][y - 1].getWho() != 0) // 1
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x - 1][y].getWho() != who && gameCellTemp[x - 1][y].getWho() != 0) // 2
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x][y - 1].getWho() != who && gameCellTemp[x][y - 1].getWho() != 0) // 4
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x + 1][y - 1].getWho() != who && gameCellTemp[x + 1][y - 1].getWho() != 0) // 6
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x + 1][y].getWho() != who && gameCellTemp[x + 1][y].getWho() != 0) // 7
{
// asdasdasdasdasdasd
}
}
}
// C-D Side
else if (x == getRow() - 1)
{
if (gameCellTemp[x][y].getWho() == 0)
{
if (gameCellTemp[x - 1][y - 1].getWho() != who && gameCellTemp[x - 1][y - 1].getWho() != 0) // 1
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x - 1][y].getWho() != who && gameCellTemp[x - 1][y].getWho() != 0) // 2
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x - 1][y + 1].getWho() != who && gameCellTemp[x - 1][y].getWho() != 0) // 3
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x][y - 1].getWho() != who && gameCellTemp[x][y - 1].getWho() != 0) // 4
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x][y + 1].getWho() != who && gameCellTemp[x][y + 1].getWho() != 0) // 5
{
// asdasdasdasdasdasd
}
}
}
// D-A Side
else if (y == 0)
{
if (gameCellTemp[x][y].getWho() == 0)
{
if (gameCellTemp[x - 1][y].getWho() != who && gameCellTemp[x - 1][y].getWho() != 0) // 2
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x - 1][y + 1].getWho() != who && gameCellTemp[x - 1][y].getWho() != 0) // 3
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x][y + 1].getWho() != who && gameCellTemp[x][y + 1].getWho() != 0) // 5
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x + 1][y - 1].getWho() != who && gameCellTemp[x + 1][y - 1].getWho() != 0) // 6
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x][y - 1].getWho() != who && gameCellTemp[x][y - 1].getWho() != 0) // 8
{
// asdasdasdasdasdasd
}
}
}
else
{
if (gameCellTemp[x][y].getWho() == 0)
{
if (gameCellTemp[x - 1][y - 1].getWho() != who && gameCellTemp[x - 1][y - 1].getWho() != 0) // 1
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x - 1][y].getWho() != who && gameCellTemp[x - 1][y].getWho() != 0) // 2
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x - 1][y + 1].getWho() != who && gameCellTemp[x - 1][y].getWho() != 0) // 3
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x][y - 1].getWho() != who && gameCellTemp[x][y - 1].getWho() != 0) // 4
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x][y + 1].getWho() != who && gameCellTemp[x][y + 1].getWho() != 0) // 5
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x + 1][y - 1].getWho() != who && gameCellTemp[x + 1][y - 1].getWho() != 0) // 6
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x + 1][y].getWho() != who && gameCellTemp[x + 1][y].getWho() != 0) // 7
{
// asdasdasdasdasdasd
}
if (gameCellTemp[x][y - 1].getWho() != who && gameCellTemp[x][y - 1].getWho() != 0) // 8
{
// asdasdasdasdasdasd
}
}
}
}
void Reversi::newValue()
{
cout << "\nX again: ";
int a;
cin >> a;
cout << "\nY again: ";
string b;
cin >> b;
find(a, b);
return;
}
void Reversi::find(const int x, const string y)
{
vector<vector<Cell> > gameCellTemp;
gameCellTemp = gameCell;
int axisX, axisY;
for (int i = 0; i < getRow(); ++i)
for (int j = 0; j < getColumn(); ++j)
if (gameCellTemp[i][j].getRow() == x && gameCellTemp[i][j].getColumn() == y)
{
axisX = i;
axisY = j;
}
control(axisX, axisY, getWho());
return;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013, Razvan Petru
// 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.
// * The name of the contributors may not be used to endorse or promote products
// derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE 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 "QsLogDestFile.h"
#include <QTextCodec>
#include <QDateTime>
#include <QtGlobal>
#include <iostream>
const int QsLogging::SizeRotationStrategy::MaxBackupCount = 10;
QsLogging::RotationStrategy::~RotationStrategy()
{
}
QsLogging::SizeRotationStrategy::SizeRotationStrategy()
: mCurrentSizeInBytes(0)
, mMaxSizeInBytes(0)
, mBackupsCount(0)
{
}
void QsLogging::SizeRotationStrategy::setInitialInfo(const QFile &file)
{
mFileName = file.fileName();
mCurrentSizeInBytes = file.size();
}
void QsLogging::SizeRotationStrategy::includeMessageInCalculation(const QString &message)
{
mCurrentSizeInBytes += message.toUtf8().size();
}
bool QsLogging::SizeRotationStrategy::shouldRotate()
{
return mCurrentSizeInBytes > mMaxSizeInBytes;
}
// Algorithm assumes backups will be named filename.X, where 1 <= X <= mBackupsCount.
// All X's will be shifted up.
void QsLogging::SizeRotationStrategy::rotate()
{
if (!mBackupsCount) {
if (!QFile::remove(mFileName))
std::cerr << "QsLog: backup delete failed " << qPrintable(mFileName);
return;
}
// 1. find the last existing backup than can be shifted up
const QString logNamePattern = mFileName + QString::fromUtf8(".%1");
int lastExistingBackupIndex = 0;
for (int i = 1;i <= mBackupsCount;++i) {
const QString backupFileName = logNamePattern.arg(i);
if (QFile::exists(backupFileName))
lastExistingBackupIndex = qMin(i, mBackupsCount - 1);
else
break;
}
// 2. shift up
for (int i = lastExistingBackupIndex;i >= 1;--i) {
const QString oldName = logNamePattern.arg(i);
const QString newName = logNamePattern.arg(i + 1);
QFile::remove(newName);
const bool renamed = QFile::rename(oldName, newName);
if (!renamed) {
std::cerr << "QsLog: could not rename backup " << qPrintable(oldName)
<< " to " << qPrintable(newName);
}
}
// 3. rename current log file
const QString newName = logNamePattern.arg(1);
if (QFile::exists(newName))
QFile::remove(newName);
if (!QFile::rename(mFileName, newName)) {
std::cerr << "QsLog: could not rename log " << qPrintable(mFileName)
<< " to " << qPrintable(newName);
}
}
QIODevice::OpenMode QsLogging::SizeRotationStrategy::recommendedOpenModeFlag()
{
return QIODevice::Append;
}
void QsLogging::SizeRotationStrategy::setMaximumSizeInBytes(qint64 size)
{
Q_ASSERT(size >= 0);
mMaxSizeInBytes = size;
}
void QsLogging::SizeRotationStrategy::setBackupCount(int backups)
{
Q_ASSERT(backups >= 0);
mBackupsCount = qMin(backups, SizeRotationStrategy::MaxBackupCount);
}
QsLogging::FileDestination::FileDestination(const QString& filePath, RotationStrategyPtr rotationStrategy)
: mRotationStrategy(rotationStrategy)
{
mFile.setFileName(filePath);
if (!mFile.open(QFile::WriteOnly | QFile::Text | mRotationStrategy->recommendedOpenModeFlag()))
std::cerr << "QsLog: could not open log file " << qPrintable(filePath);
mOutputStream.setDevice(&mFile);
mOutputStream.setCodec(QTextCodec::codecForName("UTF-8"));
mRotationStrategy->setInitialInfo(mFile);
}
void QsLogging::FileDestination::write(const QString& message, Level)
{
mRotationStrategy->includeMessageInCalculation(message);
if (mRotationStrategy->shouldRotate()) {
mOutputStream.setDevice(NULL);
mFile.close();
mRotationStrategy->rotate();
if (!mFile.open(QFile::WriteOnly | QFile::Text | mRotationStrategy->recommendedOpenModeFlag()))
std::cerr << "QsLog: could not reopen log file " << qPrintable(mFile.fileName());
mRotationStrategy->setInitialInfo(mFile);
mOutputStream.setDevice(&mFile);
}
mOutputStream << message << endl;
mOutputStream.flush();
}
bool QsLogging::FileDestination::isValid()
{
return mFile.isOpen();
}
<commit_msg>Fix for issue 2: Rare problem with log rotation when using custom ICU DLL.<commit_after>// Copyright (c) 2013, Razvan Petru
// 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.
// * The name of the contributors may not be used to endorse or promote products
// derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE 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 "QsLogDestFile.h"
#include <QTextCodec>
#include <QDateTime>
#include <QtGlobal>
#include <iostream>
const int QsLogging::SizeRotationStrategy::MaxBackupCount = 10;
QsLogging::RotationStrategy::~RotationStrategy()
{
}
QsLogging::SizeRotationStrategy::SizeRotationStrategy()
: mCurrentSizeInBytes(0)
, mMaxSizeInBytes(0)
, mBackupsCount(0)
{
}
void QsLogging::SizeRotationStrategy::setInitialInfo(const QFile &file)
{
mFileName = file.fileName();
mCurrentSizeInBytes = file.size();
}
void QsLogging::SizeRotationStrategy::includeMessageInCalculation(const QString &message)
{
mCurrentSizeInBytes += message.toUtf8().size();
}
bool QsLogging::SizeRotationStrategy::shouldRotate()
{
return mCurrentSizeInBytes > mMaxSizeInBytes;
}
// Algorithm assumes backups will be named filename.X, where 1 <= X <= mBackupsCount.
// All X's will be shifted up.
void QsLogging::SizeRotationStrategy::rotate()
{
if (!mBackupsCount) {
if (!QFile::remove(mFileName))
std::cerr << "QsLog: backup delete failed " << qPrintable(mFileName);
return;
}
// 1. find the last existing backup than can be shifted up
const QString logNamePattern = mFileName + QString::fromUtf8(".%1");
int lastExistingBackupIndex = 0;
for (int i = 1;i <= mBackupsCount;++i) {
const QString backupFileName = logNamePattern.arg(i);
if (QFile::exists(backupFileName))
lastExistingBackupIndex = qMin(i, mBackupsCount - 1);
else
break;
}
// 2. shift up
for (int i = lastExistingBackupIndex;i >= 1;--i) {
const QString oldName = logNamePattern.arg(i);
const QString newName = logNamePattern.arg(i + 1);
QFile::remove(newName);
const bool renamed = QFile::rename(oldName, newName);
if (!renamed) {
std::cerr << "QsLog: could not rename backup " << qPrintable(oldName)
<< " to " << qPrintable(newName);
}
}
// 3. rename current log file
const QString newName = logNamePattern.arg(1);
if (QFile::exists(newName))
QFile::remove(newName);
if (!QFile::rename(mFileName, newName)) {
std::cerr << "QsLog: could not rename log " << qPrintable(mFileName)
<< " to " << qPrintable(newName);
}
}
QIODevice::OpenMode QsLogging::SizeRotationStrategy::recommendedOpenModeFlag()
{
return QIODevice::Append;
}
void QsLogging::SizeRotationStrategy::setMaximumSizeInBytes(qint64 size)
{
Q_ASSERT(size >= 0);
mMaxSizeInBytes = size;
}
void QsLogging::SizeRotationStrategy::setBackupCount(int backups)
{
Q_ASSERT(backups >= 0);
mBackupsCount = qMin(backups, SizeRotationStrategy::MaxBackupCount);
}
QsLogging::FileDestination::FileDestination(const QString& filePath, RotationStrategyPtr rotationStrategy)
: mRotationStrategy(rotationStrategy)
{
mFile.setFileName(filePath);
if (!mFile.open(QFile::WriteOnly | QFile::Text | mRotationStrategy->recommendedOpenModeFlag()))
std::cerr << "QsLog: could not open log file " << qPrintable(filePath);
mOutputStream.setDevice(&mFile);
mOutputStream.setCodec(QTextCodec::codecForName("UTF-8"));
mRotationStrategy->setInitialInfo(mFile);
}
void QsLogging::FileDestination::write(const QString& message, Level)
{
mRotationStrategy->includeMessageInCalculation(message);
if (mRotationStrategy->shouldRotate()) {
mOutputStream.setDevice(NULL);
mFile.close();
mRotationStrategy->rotate();
if (!mFile.open(QFile::WriteOnly | QFile::Text | mRotationStrategy->recommendedOpenModeFlag()))
std::cerr << "QsLog: could not reopen log file " << qPrintable(mFile.fileName());
mRotationStrategy->setInitialInfo(mFile);
mOutputStream.setDevice(&mFile);
mOutputStream.setCodec(QTextCodec::codecForName("UTF-8"));
}
mOutputStream << message << endl;
mOutputStream.flush();
}
bool QsLogging::FileDestination::isValid()
{
return mFile.isOpen();
}
<|endoftext|> |
<commit_before>//*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#pragma once
#include "ngraph/axis_vector.hpp"
#include "ngraph/op/convolution.hpp"
#include "ngraph/op/op.hpp"
\
namespace ngraph
{
namespace runtime
{
namespace plaidml
{
namespace op
{
class Convolution;
class ConvolutionBackpropData;
class ConvolutionBackpropFilters;
}
}
}
}
class ngraph::runtime::plaidml::op::Convolution final : public ngraph::op::Op
{
public:
static const std::string type_name;
const std::string& description() const override { return type_name; }
Convolution(std::shared_ptr<ngraph::op::Convolution> src,
const OutputVector& args,
AxisVector data_axes,
AxisVector filters_axes,
AxisVector output_axes);
void validate_and_infer_types() final;
std::shared_ptr<Node> copy_with_new_args(const NodeVector& new_args) const final;
const std::shared_ptr<ngraph::op::Convolution>& get_src() const { return m_src; }
const AxisVector& get_data_axes() const { return m_data_axes; }
const AxisVector& get_filters_axes() const { return m_filters_axes; }
const AxisVector& get_output_axes() const { return m_output_axes; }
private:
std::shared_ptr<ngraph::op::Convolution> m_src;
AxisVector m_data_axes;
AxisVector m_filters_axes;
AxisVector m_output_axes;
};
class ngraph::runtime::plaidml::op::ConvolutionBackpropData final : public ngraph::op::Op
{
public:
static const std::string type_name;
const std::string& description() const override { return type_name; }
ConvolutionBackpropData(std::shared_ptr<ngraph::op::ConvolutionBackpropData> src,
const OutputVector& args,
AxisVector filters_axes,
AxisVector output_axes,
AxisVector data_axes);
void validate_and_infer_types() final;
std::shared_ptr<Node> copy_with_new_args(const NodeVector& new_args) const final;
const std::shared_ptr<ngraph::op::ConvolutionBackpropData>& get_src() const { return m_src; }
const AxisVector& get_filters_axes() const { return m_filters_axes; }
const AxisVector& get_output_axes() const { return m_output_axes; }
const AxisVector& get_data_axes() const { return m_data_axes; }
private:
std::shared_ptr<ngraph::op::ConvolutionBackpropData> m_src;
AxisVector m_filters_axes;
AxisVector m_output_axes;
AxisVector m_data_axes;
};
class ngraph::runtime::plaidml::op::ConvolutionBackpropFilters final : public ngraph::op::Op
{
public:
static const std::string type_name;
const std::string& description() const override { return type_name; }
ConvolutionBackpropFilters(std::shared_ptr<ngraph::op::ConvolutionBackpropFilters> src,
const OutputVector& args,
AxisVector data_axes,
AxisVector output_axes,
AxisVector filters_axes);
void validate_and_infer_types() final;
std::shared_ptr<Node> copy_with_new_args(const NodeVector& new_args) const final;
const std::shared_ptr<ngraph::op::ConvolutionBackpropFilters>& get_src() const { return m_src; }
const AxisVector& get_data_axes() const { return m_data_axes; }
const AxisVector& get_output_axes() const { return m_output_axes; }
const AxisVector& get_filters_axes() const { return m_filters_axes; }
private:
std::shared_ptr<ngraph::op::ConvolutionBackpropFilters> m_src;
AxisVector m_data_axes;
AxisVector m_output_axes;
AxisVector m_filters_axes;
};
<commit_msg>Update plaidml_ops_convolution.hpp<commit_after>//*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#pragma once
#include "ngraph/axis_vector.hpp"
#include "ngraph/op/convolution.hpp"
#include "ngraph/op/op.hpp"
namespace ngraph
{
namespace runtime
{
namespace plaidml
{
namespace op
{
class Convolution;
class ConvolutionBackpropData;
class ConvolutionBackpropFilters;
}
}
}
}
class ngraph::runtime::plaidml::op::Convolution final : public ngraph::op::Op
{
public:
static const std::string type_name;
const std::string& description() const override { return type_name; }
Convolution(std::shared_ptr<ngraph::op::Convolution> src,
const OutputVector& args,
AxisVector data_axes,
AxisVector filters_axes,
AxisVector output_axes);
void validate_and_infer_types() final;
std::shared_ptr<Node> copy_with_new_args(const NodeVector& new_args) const final;
const std::shared_ptr<ngraph::op::Convolution>& get_src() const { return m_src; }
const AxisVector& get_data_axes() const { return m_data_axes; }
const AxisVector& get_filters_axes() const { return m_filters_axes; }
const AxisVector& get_output_axes() const { return m_output_axes; }
private:
std::shared_ptr<ngraph::op::Convolution> m_src;
AxisVector m_data_axes;
AxisVector m_filters_axes;
AxisVector m_output_axes;
};
class ngraph::runtime::plaidml::op::ConvolutionBackpropData final : public ngraph::op::Op
{
public:
static const std::string type_name;
const std::string& description() const override { return type_name; }
ConvolutionBackpropData(std::shared_ptr<ngraph::op::ConvolutionBackpropData> src,
const OutputVector& args,
AxisVector filters_axes,
AxisVector output_axes,
AxisVector data_axes);
void validate_and_infer_types() final;
std::shared_ptr<Node> copy_with_new_args(const NodeVector& new_args) const final;
const std::shared_ptr<ngraph::op::ConvolutionBackpropData>& get_src() const { return m_src; }
const AxisVector& get_filters_axes() const { return m_filters_axes; }
const AxisVector& get_output_axes() const { return m_output_axes; }
const AxisVector& get_data_axes() const { return m_data_axes; }
private:
std::shared_ptr<ngraph::op::ConvolutionBackpropData> m_src;
AxisVector m_filters_axes;
AxisVector m_output_axes;
AxisVector m_data_axes;
};
class ngraph::runtime::plaidml::op::ConvolutionBackpropFilters final : public ngraph::op::Op
{
public:
static const std::string type_name;
const std::string& description() const override { return type_name; }
ConvolutionBackpropFilters(std::shared_ptr<ngraph::op::ConvolutionBackpropFilters> src,
const OutputVector& args,
AxisVector data_axes,
AxisVector output_axes,
AxisVector filters_axes);
void validate_and_infer_types() final;
std::shared_ptr<Node> copy_with_new_args(const NodeVector& new_args) const final;
const std::shared_ptr<ngraph::op::ConvolutionBackpropFilters>& get_src() const { return m_src; }
const AxisVector& get_data_axes() const { return m_data_axes; }
const AxisVector& get_output_axes() const { return m_output_axes; }
const AxisVector& get_filters_axes() const { return m_filters_axes; }
private:
std::shared_ptr<ngraph::op::ConvolutionBackpropFilters> m_src;
AxisVector m_data_axes;
AxisVector m_output_axes;
AxisVector m_filters_axes;
};
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://www.qt.io/licensing. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qmlprofileranimationsmodel.h"
#include "qmlprofilermodelmanager.h"
#include "qmlprofilerdatamodel.h"
#include <utils/qtcassert.h>
#include <QCoreApplication>
#include <QVector>
#include <QHash>
#include <QUrl>
#include <QString>
#include <QStack>
#include <QDebug>
namespace QmlProfiler {
namespace Internal {
QmlProfilerAnimationsModel::QmlProfilerAnimationsModel(QmlProfilerModelManager *manager,
QObject *parent) :
QmlProfilerTimelineModel(manager,
tr(QmlProfilerModelManager::featureName(QmlDebug::ProfileAnimations)),
QmlDebug::Event, QmlDebug::MaximumRangeType, parent)
{
m_maxGuiThreadAnimations = m_maxRenderThreadAnimations = 0;
announceFeatures(1 << QmlDebug::ProfileAnimations);
}
void QmlProfilerAnimationsModel::clear()
{
m_maxGuiThreadAnimations = m_maxRenderThreadAnimations = 0;
m_data.clear();
QmlProfilerTimelineModel::clear();
}
bool QmlProfilerAnimationsModel::accepted(const QmlProfilerDataModel::QmlEventTypeData &event) const
{
return QmlProfilerTimelineModel::accepted(event) &&
event.detailType== QmlDebug::AnimationFrame;
}
void QmlProfilerAnimationsModel::loadData()
{
clear();
QmlProfilerDataModel *simpleModel = modelManager()->qmlModel();
if (simpleModel->isEmpty())
return;
// collect events
const QVector<QmlProfilerDataModel::QmlEventData> &referenceList = simpleModel->getEvents();
const QVector<QmlProfilerDataModel::QmlEventTypeData> &typeList = simpleModel->getEventTypes();
QmlDebug::AnimationThread lastThread;
QmlPaintEventData lastEvent;
qint64 minNextStartTimes[] = {0, 0};
foreach (const QmlProfilerDataModel::QmlEventData &event, referenceList) {
const QmlProfilerDataModel::QmlEventTypeData &type = typeList[event.typeIndex];
if (!accepted(type))
continue;
lastThread = (QmlDebug::AnimationThread)event.numericData3;
// initial estimation of the event duration: 1/framerate
qint64 estimatedDuration = event.numericData1 > 0 ? 1e9/event.numericData1 : 1;
// the profiler registers the animation events at the end of them
qint64 realEndTime = event.startTime;
// ranges should not overlap. If they do, our estimate wasn't accurate enough
qint64 realStartTime = qMax(event.startTime - estimatedDuration, minNextStartTimes[lastThread]);
// Sometimes our estimate is far off or the server has miscalculated the frame rate
if (realStartTime >= realEndTime)
realEndTime = realStartTime + 1;
// Don't "fix" the framerate even if we've fixed the duration.
// The server should know better after all and if it doesn't we want to see that.
lastEvent.typeId = event.typeIndex;
lastEvent.framerate = (int)event.numericData1;
lastEvent.animationcount = (int)event.numericData2;
QTC_ASSERT(lastEvent.animationcount > 0, continue);
m_data.insert(insert(realStartTime, realEndTime - realStartTime, lastThread), lastEvent);
if (lastThread == QmlDebug::GuiThread)
m_maxGuiThreadAnimations = qMax(lastEvent.animationcount, m_maxGuiThreadAnimations);
else
m_maxRenderThreadAnimations = qMax(lastEvent.animationcount, m_maxRenderThreadAnimations);
minNextStartTimes[lastThread] = event.startTime + 1;
updateProgress(count(), referenceList.count());
}
computeNesting();
setExpandedRowCount((m_maxGuiThreadAnimations == 0 || m_maxRenderThreadAnimations == 0) ? 2 : 3);
setCollapsedRowCount(expandedRowCount());
updateProgress(1, 1);
}
/////////////////// QML interface
int QmlProfilerAnimationsModel::rowFromThreadId(int threadId) const
{
return (threadId == QmlDebug::GuiThread || m_maxGuiThreadAnimations == 0) ? 1 : 2;
}
int QmlProfilerAnimationsModel::rowMaxValue(int rowNumber) const
{
switch (rowNumber) {
case 1:
return m_maxGuiThreadAnimations > 0 ? m_maxGuiThreadAnimations : m_maxRenderThreadAnimations;
case 2:
return m_maxRenderThreadAnimations;
default:
return QmlProfilerTimelineModel::rowMaxValue(rowNumber);
}
}
int QmlProfilerAnimationsModel::typeId(int index) const
{
return m_data[index].typeId;
}
int QmlProfilerAnimationsModel::expandedRow(int index) const
{
return rowFromThreadId(selectionId(index));
}
int QmlProfilerAnimationsModel::collapsedRow(int index) const
{
return rowFromThreadId(selectionId(index));
}
QColor QmlProfilerAnimationsModel::color(int index) const
{
double fpsFraction = m_data[index].framerate / 60.0;
if (fpsFraction > 1.0)
fpsFraction = 1.0;
if (fpsFraction < 0.0)
fpsFraction = 0.0;
return colorByFraction(fpsFraction);
}
float QmlProfilerAnimationsModel::relativeHeight(int index) const
{
const int thread = selectionId(index);
// Add some height to the events if we're far from the scale threshold of 2 * DefaultRowHeight.
// Like that you can see the smaller events more easily.
int scaleThreshold = 2 * defaultRowHeight() - rowHeight(rowFromThreadId(thread));
float boost = scaleThreshold > 0 ? (0.15 * scaleThreshold / defaultRowHeight()) : 0;
return boost + (1.0 - boost) * (float)m_data[index].animationcount /
(float)(thread == QmlDebug::GuiThread ? m_maxGuiThreadAnimations :
m_maxRenderThreadAnimations);
}
QVariantList QmlProfilerAnimationsModel::labels() const
{
QVariantList result;
if (m_maxGuiThreadAnimations > 0) {
QVariantMap element;
element.insert(QLatin1String("displayName"), QVariant(tr("Animations")));
element.insert(QLatin1String("description"), QVariant(tr("GUI Thread")));
element.insert(QLatin1String("id"), QVariant(QmlDebug::GuiThread));
result << element;
}
if (m_maxRenderThreadAnimations > 0) {
QVariantMap element;
element.insert(QLatin1String("displayName"), QVariant(tr("Animations")));
element.insert(QLatin1String("description"), QVariant(tr("Render Thread")));
element.insert(QLatin1String("id"), QVariant(QmlDebug::RenderThread));
result << element;
}
return result;
}
QVariantMap QmlProfilerAnimationsModel::details(int index) const
{
QVariantMap result;
result.insert(QStringLiteral("displayName"), displayName());
result.insert(tr("Duration"), QmlProfilerBaseModel::formatTime(duration(index)));
result.insert(tr("Framerate"), QString::fromLatin1("%1 FPS").arg(m_data[index].framerate));
result.insert(tr("Animations"), QString::fromLatin1("%1").arg(m_data[index].animationcount));
result.insert(tr("Context"), tr(selectionId(index) == QmlDebug::GuiThread ? "GUI Thread" :
"Render Thread"));
return result;
}
}
}
<commit_msg>QmlProfiler: Don't modify height of timeline items based on row height<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://www.qt.io/licensing. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qmlprofileranimationsmodel.h"
#include "qmlprofilermodelmanager.h"
#include "qmlprofilerdatamodel.h"
#include <utils/qtcassert.h>
#include <QCoreApplication>
#include <QVector>
#include <QHash>
#include <QUrl>
#include <QString>
#include <QStack>
#include <QDebug>
namespace QmlProfiler {
namespace Internal {
QmlProfilerAnimationsModel::QmlProfilerAnimationsModel(QmlProfilerModelManager *manager,
QObject *parent) :
QmlProfilerTimelineModel(manager,
tr(QmlProfilerModelManager::featureName(QmlDebug::ProfileAnimations)),
QmlDebug::Event, QmlDebug::MaximumRangeType, parent)
{
m_maxGuiThreadAnimations = m_maxRenderThreadAnimations = 0;
announceFeatures(1 << QmlDebug::ProfileAnimations);
}
void QmlProfilerAnimationsModel::clear()
{
m_maxGuiThreadAnimations = m_maxRenderThreadAnimations = 0;
m_data.clear();
QmlProfilerTimelineModel::clear();
}
bool QmlProfilerAnimationsModel::accepted(const QmlProfilerDataModel::QmlEventTypeData &event) const
{
return QmlProfilerTimelineModel::accepted(event) &&
event.detailType== QmlDebug::AnimationFrame;
}
void QmlProfilerAnimationsModel::loadData()
{
clear();
QmlProfilerDataModel *simpleModel = modelManager()->qmlModel();
if (simpleModel->isEmpty())
return;
// collect events
const QVector<QmlProfilerDataModel::QmlEventData> &referenceList = simpleModel->getEvents();
const QVector<QmlProfilerDataModel::QmlEventTypeData> &typeList = simpleModel->getEventTypes();
QmlDebug::AnimationThread lastThread;
QmlPaintEventData lastEvent;
qint64 minNextStartTimes[] = {0, 0};
foreach (const QmlProfilerDataModel::QmlEventData &event, referenceList) {
const QmlProfilerDataModel::QmlEventTypeData &type = typeList[event.typeIndex];
if (!accepted(type))
continue;
lastThread = (QmlDebug::AnimationThread)event.numericData3;
// initial estimation of the event duration: 1/framerate
qint64 estimatedDuration = event.numericData1 > 0 ? 1e9/event.numericData1 : 1;
// the profiler registers the animation events at the end of them
qint64 realEndTime = event.startTime;
// ranges should not overlap. If they do, our estimate wasn't accurate enough
qint64 realStartTime = qMax(event.startTime - estimatedDuration, minNextStartTimes[lastThread]);
// Sometimes our estimate is far off or the server has miscalculated the frame rate
if (realStartTime >= realEndTime)
realEndTime = realStartTime + 1;
// Don't "fix" the framerate even if we've fixed the duration.
// The server should know better after all and if it doesn't we want to see that.
lastEvent.typeId = event.typeIndex;
lastEvent.framerate = (int)event.numericData1;
lastEvent.animationcount = (int)event.numericData2;
QTC_ASSERT(lastEvent.animationcount > 0, continue);
m_data.insert(insert(realStartTime, realEndTime - realStartTime, lastThread), lastEvent);
if (lastThread == QmlDebug::GuiThread)
m_maxGuiThreadAnimations = qMax(lastEvent.animationcount, m_maxGuiThreadAnimations);
else
m_maxRenderThreadAnimations = qMax(lastEvent.animationcount, m_maxRenderThreadAnimations);
minNextStartTimes[lastThread] = event.startTime + 1;
updateProgress(count(), referenceList.count());
}
computeNesting();
setExpandedRowCount((m_maxGuiThreadAnimations == 0 || m_maxRenderThreadAnimations == 0) ? 2 : 3);
setCollapsedRowCount(expandedRowCount());
updateProgress(1, 1);
}
/////////////////// QML interface
int QmlProfilerAnimationsModel::rowFromThreadId(int threadId) const
{
return (threadId == QmlDebug::GuiThread || m_maxGuiThreadAnimations == 0) ? 1 : 2;
}
int QmlProfilerAnimationsModel::rowMaxValue(int rowNumber) const
{
switch (rowNumber) {
case 1:
return m_maxGuiThreadAnimations > 0 ? m_maxGuiThreadAnimations : m_maxRenderThreadAnimations;
case 2:
return m_maxRenderThreadAnimations;
default:
return QmlProfilerTimelineModel::rowMaxValue(rowNumber);
}
}
int QmlProfilerAnimationsModel::typeId(int index) const
{
return m_data[index].typeId;
}
int QmlProfilerAnimationsModel::expandedRow(int index) const
{
return rowFromThreadId(selectionId(index));
}
int QmlProfilerAnimationsModel::collapsedRow(int index) const
{
return rowFromThreadId(selectionId(index));
}
QColor QmlProfilerAnimationsModel::color(int index) const
{
double fpsFraction = m_data[index].framerate / 60.0;
if (fpsFraction > 1.0)
fpsFraction = 1.0;
if (fpsFraction < 0.0)
fpsFraction = 0.0;
return colorByFraction(fpsFraction);
}
float QmlProfilerAnimationsModel::relativeHeight(int index) const
{
return (float)m_data[index].animationcount / (float)(selectionId(index) == QmlDebug::GuiThread ?
m_maxGuiThreadAnimations :
m_maxRenderThreadAnimations);
}
QVariantList QmlProfilerAnimationsModel::labels() const
{
QVariantList result;
if (m_maxGuiThreadAnimations > 0) {
QVariantMap element;
element.insert(QLatin1String("displayName"), QVariant(tr("Animations")));
element.insert(QLatin1String("description"), QVariant(tr("GUI Thread")));
element.insert(QLatin1String("id"), QVariant(QmlDebug::GuiThread));
result << element;
}
if (m_maxRenderThreadAnimations > 0) {
QVariantMap element;
element.insert(QLatin1String("displayName"), QVariant(tr("Animations")));
element.insert(QLatin1String("description"), QVariant(tr("Render Thread")));
element.insert(QLatin1String("id"), QVariant(QmlDebug::RenderThread));
result << element;
}
return result;
}
QVariantMap QmlProfilerAnimationsModel::details(int index) const
{
QVariantMap result;
result.insert(QStringLiteral("displayName"), displayName());
result.insert(tr("Duration"), QmlProfilerBaseModel::formatTime(duration(index)));
result.insert(tr("Framerate"), QString::fromLatin1("%1 FPS").arg(m_data[index].framerate));
result.insert(tr("Animations"), QString::fromLatin1("%1").arg(m_data[index].animationcount));
result.insert(tr("Context"), tr(selectionId(index) == QmlDebug::GuiThread ? "GUI Thread" :
"Render Thread"));
return result;
}
}
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <cmath>
#include <cctype>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <vector>
#define FOR(i,a,b) for (int i = a; i <= b; i++)
#define FORN(i,N) for (int i = 0; i < N; i++)
#define FORD(i,a,b) for (int i = a; i >= b; i--)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef pair<int,int> pii;
typedef vector<pii> vpii;
int store[2000000];
int getN(ll n) {
printf("%d\n",n);
int ans;
if(store[n]!=0) return store[n];
else if(n==1) return 1;
else if(n%2==0) {
ans = getN(n>>1)+1;
if(n <= 1999999 && n > 0) store[n] = ans;
return ans;
}
else {
ans = getN((3*n+1)>>1)+2;
if(n <= 1999999 && n > 0) store[n] = ans;
return ans;
}
}
int main() {
//printf("num: %d\n",getN(22));
int i,j;
int xI, xJ;
int mx;
while(scanf("%d %d",&i,&j)!=-1) {
mx = 0;
if(i>j) { xI = j; xJ=i; }
else {xI = i; xJ = j;};
FORD(x,xJ,xI) {
printf("%d: %d\n",x,getN(x));
mx = max(mx,getN(x));
}
printf("%d %d %d\n",i,j,mx);
}
return 0;
}
<commit_msg>UVA Problem 100<commit_after>#include <algorithm>
#include <cmath>
#include <cctype>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <vector>
#define FOR(i,a,b) for (int i = a; i <= b; i++)
#define FORN(i,N) for (int i = 0; i < N; i++)
#define FORD(i,a,b) for (int i = a; i >= b; i--)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef pair<int,int> pii;
typedef vector<pii> vpii;
int store[2000000];
int getN(ll n) {
//printf("%d\n",n);
int ans;
if( n < 2000000 && n > 0)if(store[n]!=0) return store[n];
else if(n==1) return 1;
else if(n%2==0) {
ans = getN(n>>1)+1;
if(n <= 1999999 && n > 0) store[n] = ans;
return ans;
}
else {
ans = getN((3*n+1)>>1)+2;
if(n <= 1999999 && n > 0) store[n] = ans;
return ans;
}
}
int main() {
//printf("num: %d\n",getN(22));
int i,j;
int xI, xJ;
int mx;
while(scanf("%d %d",&i,&j)!=-1) {
mx = 0;
if(i>j) { xI = j; xJ=i; }
else {xI = i; xJ = j;};
FORD(x,xJ,xI) {
//printf("%d: %d\n",x,getN(x));
mx = max(mx,getN(x));
}
printf("%d %d %d\n",i,j,mx);
}
return 0;
}
<|endoftext|> |
<commit_before>/*++
Module Name:
FASTQ.cpp
Abstract:
Fast FASTQ genome "query" reader.
Authors:
Bill Bolosky, August, 2011
Environment:
User mode service.
This class is NOT thread safe. It's the caller's responsibility to ensure that
at most one thread uses an instance at any time.
Revision History:
Adapted from Matei Zaharia's Scala implementation.
--*/
#include "stdafx.h"
#include "FASTQ.h"
#include "Compat.h"
#include "BigAlloc.h"
#include "Read.h"
#include "Util.h"
#include "exit.h"
using std::min;
using util::strnchr;
FASTQReader::FASTQReader(
DataReader* i_data,
const ReaderContext& i_context)
:
ReadReader(i_context),
data(i_data)
{
}
FASTQReader::~FASTQReader()
{
delete data;
data = NULL;
}
FASTQReader*
FASTQReader::create(
DataSupplier* supplier,
const char *fileName,
_int64 startingOffset,
_int64 amountOfFileToProcess,
const ReaderContext& context)
{
DataReader* data = supplier->getDataReader(maxReadSizeInBytes);
FASTQReader* fastq = new FASTQReader(data, context);
if (! fastq->init(fileName)) {
fprintf(stderr, "Unable to initialize FASTQReader for file %s\n", fileName);
soft_exit(1);
}
fastq->reinit(startingOffset, amountOfFileToProcess);
return fastq;
}
void
FASTQReader::readHeader(
const char* fileName,
ReaderContext& context)
{
// no header in FQ files
context.header = NULL;
context.headerLength = context.headerBytes = 0;
}
bool
FASTQReader::init(
const char* i_fileName)
{
fileName = i_fileName;
return data->init(fileName);
}
void
FASTQReader::reinit(
_int64 startingOffset,
_int64 amountOfFileToProcess)
{
data->reinit(startingOffset, amountOfFileToProcess);
char* buffer;
_int64 bytes;
if (! data->getData(&buffer, &bytes)) {
return;
}
// If we're not at the start of the file, we might have the tail end of a read that someone
// who got the previous range will process; advance past that. This is fairly tricky because
// there can be '@' signs in the quality string (and maybe even in read names?).
if (startingOffset != 0) {
if (!skipPartialRecord()) {
return;
}
}
}
bool
FASTQReader::skipPartialRecord()
{
//
// Just assume that a single FASTQ read is smaller than our buffer, so we won't exceed the buffer here.
// Look for the pattern '{0|\n}@*\n{A|T|C|G|N}*\n+' That is, either the beginning of the buffer or a
// newline, followed by an '@' and some text, another newline followed by a list of bases and a newline,
// and then a plus.
//
char* buffer;
_int64 validBytes;
data->getData(&buffer, &validBytes);
char *firstLineCandidate = buffer;
if (*firstLineCandidate != '@') {
firstLineCandidate = strnchr(buffer, '\n', validBytes) + 1;
}
for (;;) {
if (firstLineCandidate - buffer >= validBytes) {
// This happens for very small files. fprintf(stderr,"Unable to find a read in FASTQ buffer (1)\n");
return false;
}
char *secondLineCandidate = strnchr(firstLineCandidate, '\n', validBytes - (firstLineCandidate - buffer)) + 1;
if (NULL == (secondLineCandidate-1)) {
fprintf(stderr,"Unable to find a read in FASTQ buffer (2) at %d\n", data->getFileOffset());
return false;
}
if (*firstLineCandidate != '@') {
firstLineCandidate = secondLineCandidate;
continue;
}
//
// Scan through the second line making sure it's all bases (or 'N'). We don't have to
// check for end-of-buffer because we know there's a null there.
//
char *thirdLineCandidate = secondLineCandidate;
while (*thirdLineCandidate == 'A' || *thirdLineCandidate == 'C' || *thirdLineCandidate == 'T' || *thirdLineCandidate == 'G' ||
*thirdLineCandidate == 'N' || *thirdLineCandidate == 'a' || *thirdLineCandidate == 'c' || *thirdLineCandidate == 't' ||
*thirdLineCandidate == 'g') {
thirdLineCandidate++;
}
if (*thirdLineCandidate == '\r') {
//
// CRLF text; skip the CR.
//
thirdLineCandidate++;
}
if (*thirdLineCandidate != '\n') {
//
// We found something that's not a base and not a newline. It wasn't a read data (second) line. Move up a line
// and try again.
//
firstLineCandidate = secondLineCandidate;
continue;
}
thirdLineCandidate++;
if (*thirdLineCandidate != '+') {
firstLineCandidate = secondLineCandidate;
continue;
}
break;
}
data->advance(firstLineCandidate - buffer);
return true;
}
//
// Try to parse a read starting at a given position pos, updating readToUpdate with it.
// Returns 0 if the parse failed or the first position past the read if it succeeds. In
// addition, if exitOnFailure is set, print a warning and exit if there is a parse error.
// (The one time we don't set this is when trying to find the first read in a chunk.)
//
bool
FASTQReader::getNextRead(Read *readToUpdate)
{
//
// Find the next newline.
//
char* buffer;
_int64 validBytes;
if (! data->getData(&buffer, &validBytes)) {
data->nextBatch();
if (! data->getData(&buffer, &validBytes)) {
return false;
}
}
//
// Get the next four lines.
//
char* lines[nLinesPerFastqQuery];
unsigned lineLengths[nLinesPerFastqQuery];
char* scan = buffer;
for (unsigned i = 0; i < nLinesPerFastqQuery; i++) {
char *newLine = strnchr(scan, '\n', validBytes - (scan - buffer));
if (NULL == newLine) {
//
// There was no next newline
//
if (data->isEOF()) {
fprintf(stderr,"FASTQ file doesn't end with a newline! Failing. fileOffset = %lld, validBytes = %d\n",
data->getFileOffset(),validBytes);
soft_exit(1);
}
fprintf(stderr, "FASTQ record larger than buffer size at %s:%lld\n", fileName, data->getFileOffset());
soft_exit(1);
} //
const size_t lineLen = newLine - scan;
if (0 == lineLen) {
fprintf(stderr,"Syntax error in FASTQ file: blank line.\n");
soft_exit(1);
}
if (! isValidStartingCharacterForNextLine[(i + 3) % 4][*scan]) {
fprintf(stderr, "FASTQ file has invalid starting character at offset %lld", data->getFileOffset());
soft_exit(1);
}
lines[i] = scan;
lineLengths[i] = (unsigned) lineLen - (scan[lineLen-1] == '\r' ? 1 : 0);
scan = newLine + (newLine[1] == '\r' ? 2 : 1);
}
const char *id = lines[0] + 1; // The '@' on the first line is not part of the ID
readToUpdate->init(id, (unsigned) lineLengths[0] - 1, lines[1], lines[3], lineLengths[1]);
readToUpdate->clip(context.clipping);
readToUpdate->setBatch(data->getBatch());
readToUpdate->setReadGroup(context.defaultReadGroup);
data->advance(scan - buffer);
return true;
}
//
// static data & initialization
//
bool FASTQReader::isValidStartingCharacterForNextLine[FASTQReader::nLinesPerFastqQuery][256];
FASTQReader::_init FASTQReader::_initializer;
FASTQReader::_init::_init()
{
//
// Initialize the isValidStartingCharacterForNextLine array.
//
memset(isValidStartingCharacterForNextLine, 0, sizeof(isValidStartingCharacterForNextLine));
//
// The first line is the descriptor line and must start with an '@'
//
isValidStartingCharacterForNextLine[3]['@'] = true;
//
// The second line is the read itself and must start with a base or an
// 'N' in either case.
//
isValidStartingCharacterForNextLine[0]['A'] = true;
isValidStartingCharacterForNextLine[0]['C'] = true;
isValidStartingCharacterForNextLine[0]['T'] = true;
isValidStartingCharacterForNextLine[0]['G'] = true;
isValidStartingCharacterForNextLine[0]['N'] = true;
isValidStartingCharacterForNextLine[0]['a'] = true;
isValidStartingCharacterForNextLine[0]['c'] = true;
isValidStartingCharacterForNextLine[0]['t'] = true;
isValidStartingCharacterForNextLine[0]['g'] = true;
isValidStartingCharacterForNextLine[0]['n'] = true;
//
// The third line is additional sequence idenfitier info and must
// start with a '+'.
//
isValidStartingCharacterForNextLine[1]['+'] = true;
//
// Line 4 is the quality line. It starts with a printable ascii character.
// It would be nice to rule out the bases, N, + and @ because it might confsue the parser,
// but some quality lines do start with those...
//
for (char i = '!'; i <= '~'; i++) {
isValidStartingCharacterForNextLine[2][i] = true;
}
}
//
// FASTQWriter
//
FASTQWriter *
FASTQWriter::Factory(const char *filename)
{
FILE *file = fopen(filename,"wb");
if (NULL == file) {
return NULL;
}
return new FASTQWriter(file);
}
bool
FASTQWriter::writeRead(Read *read)
{
size_t len = __max(read->getIdLength(),read->getDataLength());
char *buffer = new char [len + 1];
if (NULL == buffer) {
fprintf(stderr,"FASTQWriter: out of memory\n");
soft_exit(1);
}
memcpy(buffer,read->getId(),read->getIdLength());
buffer[read->getIdLength()] = 0;
bool worked = fprintf(outputFile,"@%s\n",buffer) > 0;
memcpy(buffer,read->getData(),read->getDataLength());
buffer[read->getDataLength()] = 0;
worked &= fprintf(outputFile,"%s\n+\n",buffer) > 0;
memcpy(buffer,read->getQuality(), read->getDataLength()); // The FASTQ format spec requires the same number of characters in the quality and data strings
// Null is already in place from writing data
worked &= fprintf(outputFile,"%s\n",buffer) > 0;
delete [] buffer;
return worked;
}
PairedFASTQReader::~PairedFASTQReader()
{
for (int i = 0; i < 2; i++) {
delete readers[i];
readers[i] = NULL;
}
}
PairedFASTQReader *
PairedFASTQReader::create(
DataSupplier* supplier,
const char *fileName0,
const char *fileName1,
_int64 startingOffset,
_int64 amountOfFileToProcess,
const ReaderContext& context)
{
PairedFASTQReader *reader = new PairedFASTQReader;
reader->readers[0] = FASTQReader::create(supplier, fileName0,startingOffset,amountOfFileToProcess,context);
reader->readers[1] = FASTQReader::create(supplier, fileName1,startingOffset,amountOfFileToProcess,context);
for (int i = 0; i < 2; i++) {
if (NULL == reader->readers[i]) {
delete reader;
reader = NULL;
return NULL;
}
}
return reader;
}
bool
PairedFASTQReader::getNextReadPair(Read *read0, Read *read1)
{
bool worked = readers[0]->getNextRead(read0);
if (readers[1]->getNextRead(read1) != worked) {
fprintf(stderr,"PairedFASTQReader: reads of both ends responded differently. The FASTQ files may not match properly.\n");
soft_exit(1);
}
return worked;
}
PairedReadSupplierGenerator *
PairedFASTQReader::createPairedReadSupplierGenerator(
const char *fileName0,
const char *fileName1,
int numThreads,
const ReaderContext& context,
bool gzip)
{
//
// Decide whether to use the range splitter or a queue based on whether the files are the same size.
//
if (QueryFileSize(fileName0) != QueryFileSize(fileName1) || gzip) {
fprintf(stderr,"FASTQ using supplier queue\n");
DataSupplier* dataSupplier = gzip ? DataSupplier::GzipDefault[false] : DataSupplier::Default[false];
ReadReader *reader1 = FASTQReader::create(dataSupplier, fileName0,0,QueryFileSize(fileName0),context);
ReadReader *reader2 = FASTQReader::create(dataSupplier, fileName1,0,QueryFileSize(fileName1),context);
if (NULL == reader1 || NULL == reader2) {
delete reader1;
delete reader2;
return NULL;
}
ReadSupplierQueue *queue = new ReadSupplierQueue(reader1,reader2);
queue->startReaders();
return queue;
} else {
fprintf(stderr,"FASTQ using range splitter\n");
return new RangeSplittingPairedReadSupplierGenerator(fileName0,fileName1,false,numThreads,context);
}
}
ReadSupplierGenerator *
FASTQReader::createReadSupplierGenerator(
const char *fileName,
int numThreads,
const ReaderContext& context,
bool gzip)
{
if (! gzip) {
//
// Single ended uncompressed FASTQ files can be handled by a range splitter.
//
return new RangeSplittingReadSupplierGenerator(fileName, false, numThreads, context);
} else {
ReadReader* fastq = FASTQReader::create(DataSupplier::GzipDefault[false], fileName, 0, QueryFileSize(fileName), context);
if (fastq == NULL) {
delete fastq;
return NULL;
}
ReadSupplierQueue *queue = new ReadSupplierQueue(fastq);
queue->startReaders();
return queue;
}
}
<commit_msg>Allow for DOS EOF character in FASTQ<commit_after>/*++
Module Name:
FASTQ.cpp
Abstract:
Fast FASTQ genome "query" reader.
Authors:
Bill Bolosky, August, 2011
Environment:
User mode service.
This class is NOT thread safe. It's the caller's responsibility to ensure that
at most one thread uses an instance at any time.
Revision History:
Adapted from Matei Zaharia's Scala implementation.
--*/
#include "stdafx.h"
#include "FASTQ.h"
#include "Compat.h"
#include "BigAlloc.h"
#include "Read.h"
#include "Util.h"
#include "exit.h"
using std::min;
using util::strnchr;
FASTQReader::FASTQReader(
DataReader* i_data,
const ReaderContext& i_context)
:
ReadReader(i_context),
data(i_data)
{
}
FASTQReader::~FASTQReader()
{
delete data;
data = NULL;
}
FASTQReader*
FASTQReader::create(
DataSupplier* supplier,
const char *fileName,
_int64 startingOffset,
_int64 amountOfFileToProcess,
const ReaderContext& context)
{
DataReader* data = supplier->getDataReader(maxReadSizeInBytes);
FASTQReader* fastq = new FASTQReader(data, context);
if (! fastq->init(fileName)) {
fprintf(stderr, "Unable to initialize FASTQReader for file %s\n", fileName);
soft_exit(1);
}
fastq->reinit(startingOffset, amountOfFileToProcess);
return fastq;
}
void
FASTQReader::readHeader(
const char* fileName,
ReaderContext& context)
{
// no header in FQ files
context.header = NULL;
context.headerLength = context.headerBytes = 0;
}
bool
FASTQReader::init(
const char* i_fileName)
{
fileName = i_fileName;
return data->init(fileName);
}
void
FASTQReader::reinit(
_int64 startingOffset,
_int64 amountOfFileToProcess)
{
data->reinit(startingOffset, amountOfFileToProcess);
char* buffer;
_int64 bytes;
if (! data->getData(&buffer, &bytes)) {
return;
}
// If we're not at the start of the file, we might have the tail end of a read that someone
// who got the previous range will process; advance past that. This is fairly tricky because
// there can be '@' signs in the quality string (and maybe even in read names?).
if (startingOffset != 0) {
if (!skipPartialRecord()) {
return;
}
}
}
bool
FASTQReader::skipPartialRecord()
{
//
// Just assume that a single FASTQ read is smaller than our buffer, so we won't exceed the buffer here.
// Look for the pattern '{0|\n}@*\n{A|T|C|G|N}*\n+' That is, either the beginning of the buffer or a
// newline, followed by an '@' and some text, another newline followed by a list of bases and a newline,
// and then a plus.
//
char* buffer;
_int64 validBytes;
data->getData(&buffer, &validBytes);
char *firstLineCandidate = buffer;
if (*firstLineCandidate != '@') {
firstLineCandidate = strnchr(buffer, '\n', validBytes) + 1;
}
for (;;) {
if (firstLineCandidate - buffer >= validBytes) {
// This happens for very small files. fprintf(stderr,"Unable to find a read in FASTQ buffer (1)\n");
return false;
}
char *secondLineCandidate = strnchr(firstLineCandidate, '\n', validBytes - (firstLineCandidate - buffer)) + 1;
if (NULL == (secondLineCandidate-1)) {
fprintf(stderr,"Unable to find a read in FASTQ buffer (2) at %d\n", data->getFileOffset());
return false;
}
if (*firstLineCandidate != '@') {
firstLineCandidate = secondLineCandidate;
continue;
}
//
// Scan through the second line making sure it's all bases (or 'N'). We don't have to
// check for end-of-buffer because we know there's a null there.
//
char *thirdLineCandidate = secondLineCandidate;
while (*thirdLineCandidate == 'A' || *thirdLineCandidate == 'C' || *thirdLineCandidate == 'T' || *thirdLineCandidate == 'G' ||
*thirdLineCandidate == 'N' || *thirdLineCandidate == 'a' || *thirdLineCandidate == 'c' || *thirdLineCandidate == 't' ||
*thirdLineCandidate == 'g') {
thirdLineCandidate++;
}
if (*thirdLineCandidate == '\r') {
//
// CRLF text; skip the CR.
//
thirdLineCandidate++;
}
if (*thirdLineCandidate != '\n') {
//
// We found something that's not a base and not a newline. It wasn't a read data (second) line. Move up a line
// and try again.
//
firstLineCandidate = secondLineCandidate;
continue;
}
thirdLineCandidate++;
if (*thirdLineCandidate != '+') {
firstLineCandidate = secondLineCandidate;
continue;
}
break;
}
data->advance(firstLineCandidate - buffer);
return true;
}
//
// Try to parse a read starting at a given position pos, updating readToUpdate with it.
// Returns 0 if the parse failed or the first position past the read if it succeeds. In
// addition, if exitOnFailure is set, print a warning and exit if there is a parse error.
// (The one time we don't set this is when trying to find the first read in a chunk.)
//
bool
FASTQReader::getNextRead(Read *readToUpdate)
{
//
// Find the next newline.
//
char* buffer;
_int64 validBytes;
if (! data->getData(&buffer, &validBytes)) {
data->nextBatch();
if (! data->getData(&buffer, &validBytes)) {
return false;
}
}
//
// Get the next four lines.
//
char* lines[nLinesPerFastqQuery];
unsigned lineLengths[nLinesPerFastqQuery];
char* scan = buffer;
for (unsigned i = 0; i < nLinesPerFastqQuery; i++) {
char *newLine = strnchr(scan, '\n', validBytes - (scan - buffer));
if (NULL == newLine) {
if (validBytes - (scan - buffer) == 1 && *scan == 0x1a && data->isEOF()) {
// sometimes DOS files will have extra ^Z at end
return false;
}
//
// There was no next newline
//
if (data->isEOF()) {
fprintf(stderr,"FASTQ file doesn't end with a newline! Failing. fileOffset = %lld, validBytes = %d\n",
data->getFileOffset(),validBytes);
soft_exit(1);
}
fprintf(stderr, "FASTQ record larger than buffer size at %s:%lld\n", fileName, data->getFileOffset());
soft_exit(1);
}
const size_t lineLen = newLine - scan;
if (0 == lineLen) {
fprintf(stderr,"Syntax error in FASTQ file: blank line.\n");
soft_exit(1);
}
if (! isValidStartingCharacterForNextLine[(i + 3) % 4][*scan]) {
fprintf(stderr, "FASTQ file has invalid starting character at offset %lld", data->getFileOffset());
soft_exit(1);
}
lines[i] = scan;
lineLengths[i] = (unsigned) lineLen - (scan[lineLen-1] == '\r' ? 1 : 0);
scan = newLine + (newLine[1] == '\r' ? 2 : 1);
}
const char *id = lines[0] + 1; // The '@' on the first line is not part of the ID
readToUpdate->init(id, (unsigned) lineLengths[0] - 1, lines[1], lines[3], lineLengths[1]);
readToUpdate->clip(context.clipping);
readToUpdate->setBatch(data->getBatch());
readToUpdate->setReadGroup(context.defaultReadGroup);
data->advance(scan - buffer);
return true;
}
//
// static data & initialization
//
bool FASTQReader::isValidStartingCharacterForNextLine[FASTQReader::nLinesPerFastqQuery][256];
FASTQReader::_init FASTQReader::_initializer;
FASTQReader::_init::_init()
{
//
// Initialize the isValidStartingCharacterForNextLine array.
//
memset(isValidStartingCharacterForNextLine, 0, sizeof(isValidStartingCharacterForNextLine));
//
// The first line is the descriptor line and must start with an '@'
//
isValidStartingCharacterForNextLine[3]['@'] = true;
//
// The second line is the read itself and must start with a base or an
// 'N' in either case.
//
isValidStartingCharacterForNextLine[0]['A'] = true;
isValidStartingCharacterForNextLine[0]['C'] = true;
isValidStartingCharacterForNextLine[0]['T'] = true;
isValidStartingCharacterForNextLine[0]['G'] = true;
isValidStartingCharacterForNextLine[0]['N'] = true;
isValidStartingCharacterForNextLine[0]['a'] = true;
isValidStartingCharacterForNextLine[0]['c'] = true;
isValidStartingCharacterForNextLine[0]['t'] = true;
isValidStartingCharacterForNextLine[0]['g'] = true;
isValidStartingCharacterForNextLine[0]['n'] = true;
//
// The third line is additional sequence idenfitier info and must
// start with a '+'.
//
isValidStartingCharacterForNextLine[1]['+'] = true;
//
// Line 4 is the quality line. It starts with a printable ascii character.
// It would be nice to rule out the bases, N, + and @ because it might confsue the parser,
// but some quality lines do start with those...
//
for (char i = '!'; i <= '~'; i++) {
isValidStartingCharacterForNextLine[2][i] = true;
}
}
//
// FASTQWriter
//
FASTQWriter *
FASTQWriter::Factory(const char *filename)
{
FILE *file = fopen(filename,"wb");
if (NULL == file) {
return NULL;
}
return new FASTQWriter(file);
}
bool
FASTQWriter::writeRead(Read *read)
{
size_t len = __max(read->getIdLength(),read->getDataLength());
char *buffer = new char [len + 1];
if (NULL == buffer) {
fprintf(stderr,"FASTQWriter: out of memory\n");
soft_exit(1);
}
memcpy(buffer,read->getId(),read->getIdLength());
buffer[read->getIdLength()] = 0;
bool worked = fprintf(outputFile,"@%s\n",buffer) > 0;
memcpy(buffer,read->getData(),read->getDataLength());
buffer[read->getDataLength()] = 0;
worked &= fprintf(outputFile,"%s\n+\n",buffer) > 0;
memcpy(buffer,read->getQuality(), read->getDataLength()); // The FASTQ format spec requires the same number of characters in the quality and data strings
// Null is already in place from writing data
worked &= fprintf(outputFile,"%s\n",buffer) > 0;
delete [] buffer;
return worked;
}
PairedFASTQReader::~PairedFASTQReader()
{
for (int i = 0; i < 2; i++) {
delete readers[i];
readers[i] = NULL;
}
}
PairedFASTQReader *
PairedFASTQReader::create(
DataSupplier* supplier,
const char *fileName0,
const char *fileName1,
_int64 startingOffset,
_int64 amountOfFileToProcess,
const ReaderContext& context)
{
PairedFASTQReader *reader = new PairedFASTQReader;
reader->readers[0] = FASTQReader::create(supplier, fileName0,startingOffset,amountOfFileToProcess,context);
reader->readers[1] = FASTQReader::create(supplier, fileName1,startingOffset,amountOfFileToProcess,context);
for (int i = 0; i < 2; i++) {
if (NULL == reader->readers[i]) {
delete reader;
reader = NULL;
return NULL;
}
}
return reader;
}
bool
PairedFASTQReader::getNextReadPair(Read *read0, Read *read1)
{
bool worked = readers[0]->getNextRead(read0);
if (readers[1]->getNextRead(read1) != worked) {
fprintf(stderr,"PairedFASTQReader: reads of both ends responded differently. The FASTQ files may not match properly.\n");
soft_exit(1);
}
return worked;
}
PairedReadSupplierGenerator *
PairedFASTQReader::createPairedReadSupplierGenerator(
const char *fileName0,
const char *fileName1,
int numThreads,
const ReaderContext& context,
bool gzip)
{
//
// Decide whether to use the range splitter or a queue based on whether the files are the same size.
//
if (QueryFileSize(fileName0) != QueryFileSize(fileName1) || gzip) {
fprintf(stderr,"FASTQ using supplier queue\n");
DataSupplier* dataSupplier = gzip ? DataSupplier::GzipDefault[false] : DataSupplier::Default[false];
ReadReader *reader1 = FASTQReader::create(dataSupplier, fileName0,0,QueryFileSize(fileName0),context);
ReadReader *reader2 = FASTQReader::create(dataSupplier, fileName1,0,QueryFileSize(fileName1),context);
if (NULL == reader1 || NULL == reader2) {
delete reader1;
delete reader2;
return NULL;
}
ReadSupplierQueue *queue = new ReadSupplierQueue(reader1,reader2);
queue->startReaders();
return queue;
} else {
fprintf(stderr,"FASTQ using range splitter\n");
return new RangeSplittingPairedReadSupplierGenerator(fileName0,fileName1,false,numThreads,context);
}
}
ReadSupplierGenerator *
FASTQReader::createReadSupplierGenerator(
const char *fileName,
int numThreads,
const ReaderContext& context,
bool gzip)
{
if (! gzip) {
//
// Single ended uncompressed FASTQ files can be handled by a range splitter.
//
return new RangeSplittingReadSupplierGenerator(fileName, false, numThreads, context);
} else {
ReadReader* fastq = FASTQReader::create(DataSupplier::GzipDefault[false], fileName, 0, QueryFileSize(fileName), context);
if (fastq == NULL) {
delete fastq;
return NULL;
}
ReadSupplierQueue *queue = new ReadSupplierQueue(fastq);
queue->startReaders();
return queue;
}
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
//
// Utility class to evaluate the material budget from
// a given radius to the surface of an arbitrary cylinder
// along radial directions from the centre:
//
// - radiation length
// - Interaction length
// - g/cm2
//
// Geantinos are shot in the bins in the fNtheta bins in theta
// and fNphi bins in phi with specified rectangular limits.
// The statistics are accumulated per
// fRadMin < r < fRadMax and <0 < z < fZMax
//
// To activate this option, you can do:
// Root > gAlice.RunLego();
// or Root > .x menu.C then select menu item "RunLego"
// Note that when calling gAlice->RunLego, an optional list
// of arguments may be specified.
//
//Begin_Html
/*
<img src="picts/alilego.gif">
*/
//End_Html
//
//////////////////////////////////////////////////////////////
#include "TClonesArray.h"
#include "TH2.h"
#include "TMath.h"
#include "TString.h"
#include "TVirtualMC.h"
#include "AliLog.h"
#include "AliDebugVolume.h"
#include "AliLego.h"
#include "AliLegoGenerator.h"
#include "AliMC.h"
#include "AliRun.h"
ClassImp(AliLego)
//_______________________________________________________________________
AliLego::AliLego():
fGener(0),
fTotRadl(0),
fTotAbso(0),
fTotGcm2(0),
fHistRadl(0),
fHistAbso(0),
fHistGcm2(0),
fHistReta(0),
fVolumesFwd(0),
fVolumesBwd(0),
fStepBack(0),
fStepsBackward(0),
fStepsForward(0),
fErrorCondition(0),
fDebug(0)
{
//
// Default constructor
//
}
//_______________________________________________________________________
AliLego::AliLego(const AliLego &lego):
TNamed(lego),
fGener(0),
fTotRadl(0),
fTotAbso(0),
fTotGcm2(0),
fHistRadl(0),
fHistAbso(0),
fHistGcm2(0),
fHistReta(0),
fVolumesFwd(0),
fVolumesBwd(0),
fStepBack(0),
fStepsBackward(0),
fStepsForward(0),
fErrorCondition(0),
fDebug(0)
{
//
// Copy constructor
//
lego.Copy(*this);
}
//_______________________________________________________________________
AliLego::AliLego(const char *title, Int_t ntheta, Float_t thetamin,
Float_t thetamax, Int_t nphi, Float_t phimin, Float_t phimax,
Float_t rmin, Float_t rmax, Float_t zmax):
TNamed("Lego Generator",title),
fGener(0),
fTotRadl(0),
fTotAbso(0),
fTotGcm2(0),
fHistRadl(0),
fHistAbso(0),
fHistGcm2(0),
fHistReta(0),
fVolumesFwd(0),
fVolumesBwd(0),
fStepBack(0),
fStepsBackward(0),
fStepsForward(0),
fErrorCondition(0),
fDebug(0)
{
//
// specify the angular limits and the size of the rectangular box
//
fGener = new AliLegoGenerator(ntheta, thetamin, thetamax,
nphi, phimin, phimax, rmin, rmax, zmax);
fHistRadl = new TH2F("hradl","Radiation length map",
ntheta,thetamin,thetamax,nphi,phimin,phimax);
fHistAbso = new TH2F("habso","Interaction length map",
ntheta,thetamin,thetamax,nphi,phimin,phimax);
fHistGcm2 = new TH2F("hgcm2","g/cm2 length map",
ntheta,thetamin,thetamax,nphi,phimin,phimax);
//
fVolumesFwd = new TClonesArray("AliDebugVolume",1000);
fVolumesBwd = new TClonesArray("AliDebugVolume",1000);
fDebug = AliDebugLevel();
}
//_______________________________________________________________________
AliLego::AliLego(const char *title, AliLegoGenerator* generator):
TNamed("Lego Generator",title),
fGener(0),
fTotRadl(0),
fTotAbso(0),
fTotGcm2(0),
fHistRadl(0),
fHistAbso(0),
fHistGcm2(0),
fHistReta(0),
fVolumesFwd(0),
fVolumesBwd(0),
fStepBack(0),
fStepsBackward(0),
fStepsForward(0),
fErrorCondition(0),
fDebug(0)
{
//
// specify the angular limits and the size of the rectangular box
//
fGener = generator;
Float_t c1min, c1max, c2min, c2max;
Int_t n1 = fGener->NCoor1();
Int_t n2 = fGener->NCoor2();
fGener->Coor1Range(c1min, c1max);
fGener->Coor2Range(c2min, c2max);
fHistRadl = new TH2F("hradl","Radiation length map",
n2, c2min, c2max, n1, c1min, c1max);
fHistAbso = new TH2F("habso","Interaction length map",
n2, c2min, c2max, n1, c1min, c1max);
fHistGcm2 = new TH2F("hgcm2","g/cm2 length map",
n2, c2min, c2max, n1, c1min, c1max);
//
//
fVolumesFwd = new TClonesArray("AliDebugVolume",1000);
fVolumesBwd = new TClonesArray("AliDebugVolume",1000);
fDebug = AliDebugLevel();
}
//_______________________________________________________________________
AliLego::~AliLego()
{
//
// Destructor
//
delete fHistRadl;
delete fHistAbso;
delete fHistGcm2;
delete fGener;
delete fVolumesFwd;
delete fVolumesBwd;
}
//_______________________________________________________________________
void AliLego::BeginEvent()
{
//
// --- Set to 0 radiation length, absorption length and g/cm2 ---
//
fTotRadl = 0;
fTotAbso = 0;
fTotGcm2 = 0;
if (fDebug) {
if (fErrorCondition) ToAliDebug(1, DumpVolumes());
fVolumesFwd->Delete();
fVolumesBwd->Delete();
fStepsForward = 0;
fStepsBackward = 0;
fErrorCondition = 0;
if (gAlice->GetMCApp()->GetCurrentTrackNumber() == 0) fStepBack = 0;
}
}
//_______________________________________________________________________
void AliLego::FinishEvent()
{
//
// Finish the event and update the histos
//
Double_t c1, c2;
c1 = fGener->CurCoor1();
c2 = fGener->CurCoor2();
fHistRadl->Fill(c2,c1,fTotRadl);
fHistAbso->Fill(c2,c1,fTotAbso);
fHistGcm2->Fill(c2,c1,fTotGcm2);
}
//_______________________________________________________________________
void AliLego::FinishRun()
{
//
// Store histograms in current Root file
//
fHistRadl->Write();
fHistAbso->Write();
fHistGcm2->Write();
// Delete histograms from memory
fHistRadl->Delete(); fHistRadl=0;
fHistAbso->Delete(); fHistAbso=0;
fHistGcm2->Delete(); fHistGcm2=0;
//
if (fErrorCondition) ToAliError(DumpVolumes());
}
//_______________________________________________________________________
void AliLego::Copy(TObject&) const
{
//
// Copy *this onto lego -- not implemented
//
AliFatal("Not implemented!");
}
//_______________________________________________________________________
void AliLego::StepManager()
{
//
// called from AliRun::Stepmanager from gustep.
// Accumulate the 3 parameters step by step
//
static Float_t t;
Float_t a,z,dens,radl,absl;
Int_t i, id, copy;
const char* vol;
static Float_t vect[3], dir[3];
TString tmp1, tmp2;
copy = 1;
id = gMC->CurrentVolID(copy);
vol = gMC->VolName(id);
Float_t step = gMC->TrackStep();
TLorentzVector pos, mom;
gMC->TrackPosition(pos);
gMC->TrackMomentum(mom);
Int_t status = 0;
if (gMC->IsTrackEntering()) status = 1;
if (gMC->IsTrackExiting()) status = 2;
if (! fStepBack) {
// printf("\n volume %s %d", vol, status);
//
// Normal Forward stepping
//
if (fDebug) {
// printf("\n steps fwd %d %s %d %f", fStepsForward, vol, fErrorCondition, step);
//
// store volume if different from previous
//
TClonesArray &lvols = *fVolumesFwd;
if (fStepsForward > 0) {
AliDebugVolume* tmp = dynamic_cast<AliDebugVolume*>((*fVolumesFwd)[fStepsForward-1]);
if (tmp->IsVEqual(vol, copy) && gMC->IsTrackEntering()) {
fStepsForward -= 2;
fVolumesFwd->RemoveAt(fStepsForward);
fVolumesFwd->RemoveAt(fStepsForward+1);
}
}
new(lvols[fStepsForward++])
AliDebugVolume(vol,copy,step,pos[0], pos[1], pos[2], status);
} // Debug
//
// Get current material properties
gMC->CurrentMaterial(a,z,dens,radl,absl);
if (z < 1) return;
// --- See if we have to stop now
if (TMath::Abs(pos[2]) > fGener->ZMax() ||
pos[0]*pos[0] +pos[1]*pos[1] > fGener->RadMax()*fGener->RadMax()) {
if (!gMC->IsNewTrack()) {
// Not the first step, add past contribution
fTotAbso += t/absl;
fTotRadl += t/radl;
fTotGcm2 += t*dens;
if (fDebug) {
//
// generate "mirror" particle flying back
//
fStepsBackward = fStepsForward;
Float_t pmom[3], orig[3];
Float_t polar[3] = {0.,0.,0.};
Int_t ntr;
pmom[0] = -dir[0];
pmom[1] = -dir[1];
pmom[2] = -dir[2];
orig[0] = vect[0];
orig[1] = vect[1];
orig[2] = vect[2];
gAlice->GetMCApp()->PushTrack(1, gAlice->GetMCApp()->GetCurrentTrackNumber(),
0, pmom, orig, polar, 0., kPNoProcess, ntr);
} // debug
} // not a new track !
if (fDebug) fStepBack = 1;
gMC->StopTrack();
return;
} // outside scoring region ?
// --- See how long we have to go
for(i=0;i<3;++i) {
vect[i]=pos[i];
dir[i]=mom[i];
}
t = fGener->PropagateCylinder(vect,dir,fGener->RadMax(),fGener->ZMax());
if(step) {
fTotAbso += step/absl;
fTotRadl += step/radl;
fTotGcm2 += step*dens;
}
} else {
if (fDebug) {
//
// Geometry debugging
// Fly back and compare volume sequence
//
TClonesArray &lvols = *fVolumesBwd;
if (fStepsBackward < fStepsForward) {
AliDebugVolume* tmp = dynamic_cast<AliDebugVolume*>((*fVolumesBwd)[fStepsBackward]);
if (tmp->IsVEqual(vol, copy) && gMC->IsTrackEntering()) {
fStepsBackward += 2;
fVolumesBwd->RemoveAt(fStepsBackward-1);
fVolumesBwd->RemoveAt(fStepsBackward-2);
}
}
fStepsBackward--;
// printf("\n steps %d %s %d", fStepsBackward, vol, fErrorCondition);
if (fStepsBackward < 0) {
gMC->StopTrack();
fStepBack = 0;
return;
}
new(lvols[fStepsBackward]) AliDebugVolume(vol,copy,step,pos[0], pos[1], pos[2], status);
AliDebugVolume* tmp = dynamic_cast<AliDebugVolume*>((*fVolumesFwd)[fStepsBackward]);
if (! (tmp->IsVEqual(vol, copy)) && (!fErrorCondition))
{
AliWarning(Form("Problem at (x,y,z): %d %f %f %f, volumes: %s %s step: %f\n",
fStepsBackward, pos[0], pos[1], pos[2], tmp->GetName(), vol, step));
fErrorCondition = 1;
}
} // Debug
} // bwd/fwd
}
//_______________________________________________________________________
void AliLego::DumpVolumes()
{
//
// Dump volume sequence in case of error
//
printf("\n Dumping Volume Sequence:");
printf("\n ==============================================");
for (Int_t i = fStepsForward-1; i>=0; i--)
{
AliDebugVolume* tmp1 = dynamic_cast<AliDebugVolume*>((*fVolumesFwd)[i]);
AliDebugVolume* tmp2 = dynamic_cast<AliDebugVolume*>((*fVolumesBwd)[i]);
if (tmp1)
printf("\n Volume Fwd: %3d: %5s (%3d) step: %12.5e (x,y,z) (%12.5e %12.5e %12.5e) status: %9s \n"
, i,
tmp1->GetName(), tmp1->CopyNumber(), tmp1->Step(),
tmp1->X(), tmp1->Y(), tmp1->Z(), tmp1->Status());
if (tmp2 && i>= fStepsBackward)
printf("\n Volume Bwd: %3d: %5s (%3d) step: %12.5e (x,y,z) (%12.5e %12.5e %12.5e) status: %9s \n"
, i,
tmp2->GetName(), tmp2->CopyNumber(), tmp2->Step(),
tmp2->X(), tmp2->Y(), tmp2->Z(), tmp2->Status());
printf("\n ............................................................................\n");
}
printf("\n ==============================================\n");
}
<commit_msg>Protection against division by zero.<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
//
// Utility class to evaluate the material budget from
// a given radius to the surface of an arbitrary cylinder
// along radial directions from the centre:
//
// - radiation length
// - Interaction length
// - g/cm2
//
// Geantinos are shot in the bins in the fNtheta bins in theta
// and fNphi bins in phi with specified rectangular limits.
// The statistics are accumulated per
// fRadMin < r < fRadMax and <0 < z < fZMax
//
// To activate this option, you can do:
// Root > gAlice.RunLego();
// or Root > .x menu.C then select menu item "RunLego"
// Note that when calling gAlice->RunLego, an optional list
// of arguments may be specified.
//
//Begin_Html
/*
<img src="picts/alilego.gif">
*/
//End_Html
//
//////////////////////////////////////////////////////////////
#include "TClonesArray.h"
#include "TH2.h"
#include "TMath.h"
#include "TString.h"
#include "TVirtualMC.h"
#include "AliLog.h"
#include "AliDebugVolume.h"
#include "AliLego.h"
#include "AliLegoGenerator.h"
#include "AliMC.h"
#include "AliRun.h"
ClassImp(AliLego)
//_______________________________________________________________________
AliLego::AliLego():
fGener(0),
fTotRadl(0),
fTotAbso(0),
fTotGcm2(0),
fHistRadl(0),
fHistAbso(0),
fHistGcm2(0),
fHistReta(0),
fVolumesFwd(0),
fVolumesBwd(0),
fStepBack(0),
fStepsBackward(0),
fStepsForward(0),
fErrorCondition(0),
fDebug(0)
{
//
// Default constructor
//
}
//_______________________________________________________________________
AliLego::AliLego(const AliLego &lego):
TNamed(lego),
fGener(0),
fTotRadl(0),
fTotAbso(0),
fTotGcm2(0),
fHistRadl(0),
fHistAbso(0),
fHistGcm2(0),
fHistReta(0),
fVolumesFwd(0),
fVolumesBwd(0),
fStepBack(0),
fStepsBackward(0),
fStepsForward(0),
fErrorCondition(0),
fDebug(0)
{
//
// Copy constructor
//
lego.Copy(*this);
}
//_______________________________________________________________________
AliLego::AliLego(const char *title, Int_t ntheta, Float_t thetamin,
Float_t thetamax, Int_t nphi, Float_t phimin, Float_t phimax,
Float_t rmin, Float_t rmax, Float_t zmax):
TNamed("Lego Generator",title),
fGener(0),
fTotRadl(0),
fTotAbso(0),
fTotGcm2(0),
fHistRadl(0),
fHistAbso(0),
fHistGcm2(0),
fHistReta(0),
fVolumesFwd(0),
fVolumesBwd(0),
fStepBack(0),
fStepsBackward(0),
fStepsForward(0),
fErrorCondition(0),
fDebug(0)
{
//
// specify the angular limits and the size of the rectangular box
//
fGener = new AliLegoGenerator(ntheta, thetamin, thetamax,
nphi, phimin, phimax, rmin, rmax, zmax);
fHistRadl = new TH2F("hradl","Radiation length map",
ntheta,thetamin,thetamax,nphi,phimin,phimax);
fHistAbso = new TH2F("habso","Interaction length map",
ntheta,thetamin,thetamax,nphi,phimin,phimax);
fHistGcm2 = new TH2F("hgcm2","g/cm2 length map",
ntheta,thetamin,thetamax,nphi,phimin,phimax);
//
fVolumesFwd = new TClonesArray("AliDebugVolume",1000);
fVolumesBwd = new TClonesArray("AliDebugVolume",1000);
fDebug = AliDebugLevel();
}
//_______________________________________________________________________
AliLego::AliLego(const char *title, AliLegoGenerator* generator):
TNamed("Lego Generator",title),
fGener(0),
fTotRadl(0),
fTotAbso(0),
fTotGcm2(0),
fHistRadl(0),
fHistAbso(0),
fHistGcm2(0),
fHistReta(0),
fVolumesFwd(0),
fVolumesBwd(0),
fStepBack(0),
fStepsBackward(0),
fStepsForward(0),
fErrorCondition(0),
fDebug(0)
{
//
// specify the angular limits and the size of the rectangular box
//
fGener = generator;
Float_t c1min, c1max, c2min, c2max;
Int_t n1 = fGener->NCoor1();
Int_t n2 = fGener->NCoor2();
fGener->Coor1Range(c1min, c1max);
fGener->Coor2Range(c2min, c2max);
fHistRadl = new TH2F("hradl","Radiation length map",
n2, c2min, c2max, n1, c1min, c1max);
fHistAbso = new TH2F("habso","Interaction length map",
n2, c2min, c2max, n1, c1min, c1max);
fHistGcm2 = new TH2F("hgcm2","g/cm2 length map",
n2, c2min, c2max, n1, c1min, c1max);
//
//
fVolumesFwd = new TClonesArray("AliDebugVolume",1000);
fVolumesBwd = new TClonesArray("AliDebugVolume",1000);
fDebug = AliDebugLevel();
}
//_______________________________________________________________________
AliLego::~AliLego()
{
//
// Destructor
//
delete fHistRadl;
delete fHistAbso;
delete fHistGcm2;
delete fGener;
delete fVolumesFwd;
delete fVolumesBwd;
}
//_______________________________________________________________________
void AliLego::BeginEvent()
{
//
// --- Set to 0 radiation length, absorption length and g/cm2 ---
//
fTotRadl = 0;
fTotAbso = 0;
fTotGcm2 = 0;
if (fDebug) {
if (fErrorCondition) ToAliDebug(1, DumpVolumes());
fVolumesFwd->Delete();
fVolumesBwd->Delete();
fStepsForward = 0;
fStepsBackward = 0;
fErrorCondition = 0;
if (gAlice->GetMCApp()->GetCurrentTrackNumber() == 0) fStepBack = 0;
}
}
//_______________________________________________________________________
void AliLego::FinishEvent()
{
//
// Finish the event and update the histos
//
Double_t c1, c2;
c1 = fGener->CurCoor1();
c2 = fGener->CurCoor2();
fHistRadl->Fill(c2,c1,fTotRadl);
fHistAbso->Fill(c2,c1,fTotAbso);
fHistGcm2->Fill(c2,c1,fTotGcm2);
}
//_______________________________________________________________________
void AliLego::FinishRun()
{
//
// Store histograms in current Root file
//
fHistRadl->Write();
fHistAbso->Write();
fHistGcm2->Write();
// Delete histograms from memory
fHistRadl->Delete(); fHistRadl=0;
fHistAbso->Delete(); fHistAbso=0;
fHistGcm2->Delete(); fHistGcm2=0;
//
if (fErrorCondition) ToAliError(DumpVolumes());
}
//_______________________________________________________________________
void AliLego::Copy(TObject&) const
{
//
// Copy *this onto lego -- not implemented
//
AliFatal("Not implemented!");
}
//_______________________________________________________________________
void AliLego::StepManager()
{
//
// called from AliRun::Stepmanager from gustep.
// Accumulate the 3 parameters step by step
//
static Float_t t;
Float_t a,z,dens,radl,absl;
Int_t i, id, copy;
const char* vol;
static Float_t vect[3], dir[3];
TString tmp1, tmp2;
copy = 1;
id = gMC->CurrentVolID(copy);
vol = gMC->VolName(id);
Float_t step = gMC->TrackStep();
TLorentzVector pos, mom;
gMC->TrackPosition(pos);
gMC->TrackMomentum(mom);
Int_t status = 0;
if (gMC->IsTrackEntering()) status = 1;
if (gMC->IsTrackExiting()) status = 2;
if (! fStepBack) {
// printf("\n volume %s %d", vol, status);
//
// Normal Forward stepping
//
if (fDebug) {
// printf("\n steps fwd %d %s %d %f", fStepsForward, vol, fErrorCondition, step);
//
// store volume if different from previous
//
TClonesArray &lvols = *fVolumesFwd;
if (fStepsForward > 0) {
AliDebugVolume* tmp = dynamic_cast<AliDebugVolume*>((*fVolumesFwd)[fStepsForward-1]);
if (tmp->IsVEqual(vol, copy) && gMC->IsTrackEntering()) {
fStepsForward -= 2;
fVolumesFwd->RemoveAt(fStepsForward);
fVolumesFwd->RemoveAt(fStepsForward+1);
}
}
new(lvols[fStepsForward++])
AliDebugVolume(vol,copy,step,pos[0], pos[1], pos[2], status);
} // Debug
//
// Get current material properties
gMC->CurrentMaterial(a,z,dens,radl,absl);
if (z < 1) return;
// --- See if we have to stop now
if (TMath::Abs(pos[2]) > fGener->ZMax() ||
pos[0]*pos[0] +pos[1]*pos[1] > fGener->RadMax()*fGener->RadMax()) {
if (!gMC->IsNewTrack()) {
// Not the first step, add past contribution
if (absl) fTotAbso += t/absl;
if (radl) fTotRadl += t/radl;
fTotGcm2 += t*dens;
if (fDebug) {
//
// generate "mirror" particle flying back
//
fStepsBackward = fStepsForward;
Float_t pmom[3], orig[3];
Float_t polar[3] = {0.,0.,0.};
Int_t ntr;
pmom[0] = -dir[0];
pmom[1] = -dir[1];
pmom[2] = -dir[2];
orig[0] = vect[0];
orig[1] = vect[1];
orig[2] = vect[2];
gAlice->GetMCApp()->PushTrack(1, gAlice->GetMCApp()->GetCurrentTrackNumber(),
0, pmom, orig, polar, 0., kPNoProcess, ntr);
} // debug
} // not a new track !
if (fDebug) fStepBack = 1;
gMC->StopTrack();
return;
} // outside scoring region ?
// --- See how long we have to go
for(i=0;i<3;++i) {
vect[i]=pos[i];
dir[i]=mom[i];
}
t = fGener->PropagateCylinder(vect,dir,fGener->RadMax(),fGener->ZMax());
if(step) {
if (absl) fTotAbso += step/absl;
if (radl) fTotRadl += step/radl;
fTotGcm2 += step*dens;
}
} else {
if (fDebug) {
//
// Geometry debugging
// Fly back and compare volume sequence
//
TClonesArray &lvols = *fVolumesBwd;
if (fStepsBackward < fStepsForward) {
AliDebugVolume* tmp = dynamic_cast<AliDebugVolume*>((*fVolumesBwd)[fStepsBackward]);
if (tmp->IsVEqual(vol, copy) && gMC->IsTrackEntering()) {
fStepsBackward += 2;
fVolumesBwd->RemoveAt(fStepsBackward-1);
fVolumesBwd->RemoveAt(fStepsBackward-2);
}
}
fStepsBackward--;
// printf("\n steps %d %s %d", fStepsBackward, vol, fErrorCondition);
if (fStepsBackward < 0) {
gMC->StopTrack();
fStepBack = 0;
return;
}
new(lvols[fStepsBackward]) AliDebugVolume(vol,copy,step,pos[0], pos[1], pos[2], status);
AliDebugVolume* tmp = dynamic_cast<AliDebugVolume*>((*fVolumesFwd)[fStepsBackward]);
if (! (tmp->IsVEqual(vol, copy)) && (!fErrorCondition))
{
AliWarning(Form("Problem at (x,y,z): %d %f %f %f, volumes: %s %s step: %f\n",
fStepsBackward, pos[0], pos[1], pos[2], tmp->GetName(), vol, step));
fErrorCondition = 1;
}
} // Debug
} // bwd/fwd
}
//_______________________________________________________________________
void AliLego::DumpVolumes()
{
//
// Dump volume sequence in case of error
//
printf("\n Dumping Volume Sequence:");
printf("\n ==============================================");
for (Int_t i = fStepsForward-1; i>=0; i--)
{
AliDebugVolume* tmp1 = dynamic_cast<AliDebugVolume*>((*fVolumesFwd)[i]);
AliDebugVolume* tmp2 = dynamic_cast<AliDebugVolume*>((*fVolumesBwd)[i]);
if (tmp1)
printf("\n Volume Fwd: %3d: %5s (%3d) step: %12.5e (x,y,z) (%12.5e %12.5e %12.5e) status: %9s \n"
, i,
tmp1->GetName(), tmp1->CopyNumber(), tmp1->Step(),
tmp1->X(), tmp1->Y(), tmp1->Z(), tmp1->Status());
if (tmp2 && i>= fStepsBackward)
printf("\n Volume Bwd: %3d: %5s (%3d) step: %12.5e (x,y,z) (%12.5e %12.5e %12.5e) status: %9s \n"
, i,
tmp2->GetName(), tmp2->CopyNumber(), tmp2->Step(),
tmp2->X(), tmp2->Y(), tmp2->Z(), tmp2->Status());
printf("\n ............................................................................\n");
}
printf("\n ==============================================\n");
}
<|endoftext|> |
<commit_before>// Copyright (C) 2019 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <random>
#include <benchmark/benchmark.h>
#include "src/trace_processor/containers/bit_vector.h"
#include "src/trace_processor/containers/bit_vector_iterators.h"
namespace {
using perfetto::trace_processor::BitVector;
bool IsBenchmarkFunctionalOnly() {
return getenv("BENCHMARK_FUNCTIONAL_TEST_ONLY") != nullptr;
}
void BitVectorArgs(benchmark::internal::Benchmark* b) {
std::vector<int> set_percentages;
if (IsBenchmarkFunctionalOnly()) {
set_percentages = std::vector<int>{50};
} else {
set_percentages = std::vector<int>{0, 1, 5, 50, 95, 99, 100};
}
for (int percentage : set_percentages) {
b->Args({64, percentage});
if (!IsBenchmarkFunctionalOnly()) {
b->Args({512, percentage});
b->Args({8192, percentage});
b->Args({123456, percentage});
b->Args({1234567, percentage});
}
}
}
BitVector BvWithSizeAndSetPercentage(uint32_t size, uint32_t set_percentage) {
static constexpr uint32_t kRandomSeed = 29;
std::minstd_rand0 rnd_engine(kRandomSeed);
BitVector bv;
for (uint32_t i = 0; i < size; ++i) {
if (rnd_engine() % 100 < set_percentage) {
bv.AppendTrue();
} else {
bv.AppendFalse();
}
}
return bv;
}
} // namespace
static void BM_BitVectorAppendTrue(benchmark::State& state) {
BitVector bv;
for (auto _ : state) {
bv.AppendTrue();
benchmark::ClobberMemory();
}
}
BENCHMARK(BM_BitVectorAppendTrue);
static void BM_BitVectorAppendFalse(benchmark::State& state) {
BitVector bv;
for (auto _ : state) {
bv.AppendFalse();
benchmark::ClobberMemory();
}
}
BENCHMARK(BM_BitVectorAppendFalse);
static void BM_BitVectorSet(benchmark::State& state) {
static constexpr uint32_t kRandomSeed = 42;
std::minstd_rand0 rnd_engine(kRandomSeed);
uint32_t size = static_cast<uint32_t>(state.range(0));
uint32_t set_percentage = static_cast<uint32_t>(state.range(1));
BitVector bv = BvWithSizeAndSetPercentage(size, set_percentage);
static constexpr uint32_t kPoolSize = 1024 * 1024;
std::vector<bool> bit_pool(kPoolSize);
std::vector<uint32_t> row_pool(kPoolSize);
for (uint32_t i = 0; i < kPoolSize; ++i) {
bit_pool[i] = rnd_engine() % 2;
row_pool[i] = rnd_engine() % size;
}
uint32_t pool_idx = 0;
for (auto _ : state) {
bv.Set(row_pool[pool_idx]);
pool_idx = (pool_idx + 1) % kPoolSize;
benchmark::ClobberMemory();
}
}
BENCHMARK(BM_BitVectorSet)->Apply(BitVectorArgs);
static void BM_BitVectorClear(benchmark::State& state) {
static constexpr uint32_t kRandomSeed = 42;
std::minstd_rand0 rnd_engine(kRandomSeed);
uint32_t size = static_cast<uint32_t>(state.range(0));
uint32_t set_percentage = static_cast<uint32_t>(state.range(1));
BitVector bv = BvWithSizeAndSetPercentage(size, set_percentage);
static constexpr uint32_t kPoolSize = 1024 * 1024;
std::vector<uint32_t> row_pool(kPoolSize);
for (uint32_t i = 0; i < kPoolSize; ++i) {
row_pool[i] = rnd_engine() % size;
}
uint32_t pool_idx = 0;
for (auto _ : state) {
bv.Clear(row_pool[pool_idx]);
pool_idx = (pool_idx + 1) % kPoolSize;
benchmark::ClobberMemory();
}
}
BENCHMARK(BM_BitVectorClear)->Apply(BitVectorArgs);
static void BM_BitVectorIndexOfNthSet(benchmark::State& state) {
static constexpr uint32_t kRandomSeed = 42;
std::minstd_rand0 rnd_engine(kRandomSeed);
uint32_t size = static_cast<uint32_t>(state.range(0));
uint32_t set_percentage = static_cast<uint32_t>(state.range(1));
BitVector bv = BvWithSizeAndSetPercentage(size, set_percentage);
static constexpr uint32_t kPoolSize = 1024 * 1024;
std::vector<uint32_t> row_pool(kPoolSize);
uint32_t set_bit_count = bv.GetNumBitsSet();
if (set_bit_count == 0) {
state.SkipWithError("Cannot find set bit in all zeros bitvector");
return;
}
for (uint32_t i = 0; i < kPoolSize; ++i) {
row_pool[i] = rnd_engine() % set_bit_count;
}
uint32_t pool_idx = 0;
for (auto _ : state) {
benchmark::DoNotOptimize(bv.IndexOfNthSet(row_pool[pool_idx]));
pool_idx = (pool_idx + 1) % kPoolSize;
}
}
BENCHMARK(BM_BitVectorIndexOfNthSet)->Apply(BitVectorArgs);
static void BM_BitVectorGetNumBitsSet(benchmark::State& state) {
static constexpr uint32_t kRandomSeed = 42;
std::minstd_rand0 rnd_engine(kRandomSeed);
uint32_t size = static_cast<uint32_t>(state.range(0));
uint32_t set_percentage = static_cast<uint32_t>(state.range(1));
uint32_t count = 0;
BitVector bv;
for (uint32_t i = 0; i < size; ++i) {
bool value = rnd_engine() % 100 < set_percentage;
if (value) {
bv.AppendTrue();
} else {
bv.AppendFalse();
}
if (value)
count++;
}
uint32_t res = count;
for (auto _ : state) {
benchmark::DoNotOptimize(res &= bv.GetNumBitsSet());
}
PERFETTO_CHECK(res == count);
}
BENCHMARK(BM_BitVectorGetNumBitsSet)->Apply(BitVectorArgs);
static void BM_BitVectorResize(benchmark::State& state) {
static constexpr uint32_t kRandomSeed = 42;
std::minstd_rand0 rnd_engine(kRandomSeed);
static constexpr uint32_t kPoolSize = 1024 * 1024;
static constexpr uint32_t kMaxSize = 1234567;
std::vector<bool> resize_fill_pool(kPoolSize);
std::vector<uint32_t> resize_count_pool(kPoolSize);
for (uint32_t i = 0; i < kPoolSize; ++i) {
resize_fill_pool[i] = rnd_engine() % 2;
resize_count_pool[i] = rnd_engine() % kMaxSize;
}
uint32_t pool_idx = 0;
BitVector bv;
for (auto _ : state) {
bv.Resize(resize_count_pool[pool_idx], resize_fill_pool[pool_idx]);
pool_idx = (pool_idx + 1) % kPoolSize;
benchmark::ClobberMemory();
}
}
BENCHMARK(BM_BitVectorResize);
static void BM_BitVectorRangeFixedSize(benchmark::State& state) {
static constexpr uint32_t kRandomSeed = 42;
std::minstd_rand0 rnd_engine(kRandomSeed);
uint32_t size = static_cast<uint32_t>(state.range(0));
uint32_t set_percentage = static_cast<uint32_t>(state.range(1));
std::vector<uint32_t> resize_fill_pool(size);
for (uint32_t i = 0; i < size; ++i) {
resize_fill_pool[i] = rnd_engine() % 100 < set_percentage ? 90 : 100;
}
for (auto _ : state) {
auto filler = [&resize_fill_pool](uint32_t i) PERFETTO_ALWAYS_INLINE {
return resize_fill_pool[i] < 95;
};
BitVector bv = BitVector::Range(0, size, filler);
benchmark::ClobberMemory();
}
}
BENCHMARK(BM_BitVectorRangeFixedSize)->Apply(BitVectorArgs);
static void BM_BitVectorUpdateSetBits(benchmark::State& state) {
static constexpr uint32_t kRandomSeed = 42;
std::minstd_rand0 rnd_engine(kRandomSeed);
uint32_t size = static_cast<uint32_t>(state.range(0));
uint32_t set_percentage = static_cast<uint32_t>(state.range(1));
BitVector bv;
BitVector picker;
for (uint32_t i = 0; i < size; ++i) {
bool value = rnd_engine() % 100 < set_percentage;
if (value) {
bv.AppendTrue();
bool picker_value = rnd_engine() % 2;
if (picker_value) {
picker.AppendTrue();
} else {
picker.AppendFalse();
}
} else {
bv.AppendFalse();
}
}
for (auto _ : state) {
state.PauseTiming();
BitVector copy = bv.Copy();
state.ResumeTiming();
copy.UpdateSetBits(picker);
benchmark::ClobberMemory();
}
}
BENCHMARK(BM_BitVectorUpdateSetBits)->Apply(BitVectorArgs);
static void BM_BitVectorSetBitsIterator(benchmark::State& state) {
uint32_t size = static_cast<uint32_t>(state.range(0));
uint32_t set_percentage = static_cast<uint32_t>(state.range(1));
BitVector bv = BvWithSizeAndSetPercentage(size, set_percentage);
for (auto _ : state) {
for (auto it = bv.IterateSetBits(); it; it.Next()) {
benchmark::DoNotOptimize(it.index());
}
}
}
BENCHMARK(BM_BitVectorSetBitsIterator)->Apply(BitVectorArgs);
<commit_msg>tp: improve update set bits benchmark<commit_after>// Copyright (C) 2019 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <random>
#include <benchmark/benchmark.h>
#include "src/trace_processor/containers/bit_vector.h"
#include "src/trace_processor/containers/bit_vector_iterators.h"
namespace {
using perfetto::trace_processor::BitVector;
bool IsBenchmarkFunctionalOnly() {
return getenv("BENCHMARK_FUNCTIONAL_TEST_ONLY") != nullptr;
}
void BitVectorArgs(benchmark::internal::Benchmark* b) {
std::vector<int> set_percentages;
if (IsBenchmarkFunctionalOnly()) {
set_percentages = std::vector<int>{50};
} else {
set_percentages = std::vector<int>{0, 1, 5, 50, 95, 99, 100};
}
for (int percentage : set_percentages) {
b->Args({64, percentage});
if (!IsBenchmarkFunctionalOnly()) {
b->Args({512, percentage});
b->Args({8192, percentage});
b->Args({123456, percentage});
b->Args({1234567, percentage});
}
}
}
void UpdateSetBitsArgs(benchmark::internal::Benchmark* b) {
if (IsBenchmarkFunctionalOnly()) {
b->Args({64, 50, 50});
} else {
std::vector<int64_t> set_percentages{1, 5, 50, 95, 99};
b->ArgsProduct({{1234567}, set_percentages, set_percentages});
}
}
BitVector BvWithSizeAndSetPercentage(uint32_t size, uint32_t set_percentage) {
static constexpr uint32_t kRandomSeed = 29;
std::minstd_rand0 rnd_engine(kRandomSeed);
BitVector bv;
for (uint32_t i = 0; i < size; ++i) {
if (rnd_engine() % 100 < set_percentage) {
bv.AppendTrue();
} else {
bv.AppendFalse();
}
}
return bv;
}
} // namespace
static void BM_BitVectorAppendTrue(benchmark::State& state) {
BitVector bv;
for (auto _ : state) {
bv.AppendTrue();
benchmark::ClobberMemory();
}
}
BENCHMARK(BM_BitVectorAppendTrue);
static void BM_BitVectorAppendFalse(benchmark::State& state) {
BitVector bv;
for (auto _ : state) {
bv.AppendFalse();
benchmark::ClobberMemory();
}
}
BENCHMARK(BM_BitVectorAppendFalse);
static void BM_BitVectorSet(benchmark::State& state) {
static constexpr uint32_t kRandomSeed = 42;
std::minstd_rand0 rnd_engine(kRandomSeed);
uint32_t size = static_cast<uint32_t>(state.range(0));
uint32_t set_percentage = static_cast<uint32_t>(state.range(1));
BitVector bv = BvWithSizeAndSetPercentage(size, set_percentage);
static constexpr uint32_t kPoolSize = 1024 * 1024;
std::vector<bool> bit_pool(kPoolSize);
std::vector<uint32_t> row_pool(kPoolSize);
for (uint32_t i = 0; i < kPoolSize; ++i) {
bit_pool[i] = rnd_engine() % 2;
row_pool[i] = rnd_engine() % size;
}
uint32_t pool_idx = 0;
for (auto _ : state) {
bv.Set(row_pool[pool_idx]);
pool_idx = (pool_idx + 1) % kPoolSize;
benchmark::ClobberMemory();
}
}
BENCHMARK(BM_BitVectorSet)->Apply(BitVectorArgs);
static void BM_BitVectorClear(benchmark::State& state) {
static constexpr uint32_t kRandomSeed = 42;
std::minstd_rand0 rnd_engine(kRandomSeed);
uint32_t size = static_cast<uint32_t>(state.range(0));
uint32_t set_percentage = static_cast<uint32_t>(state.range(1));
BitVector bv = BvWithSizeAndSetPercentage(size, set_percentage);
static constexpr uint32_t kPoolSize = 1024 * 1024;
std::vector<uint32_t> row_pool(kPoolSize);
for (uint32_t i = 0; i < kPoolSize; ++i) {
row_pool[i] = rnd_engine() % size;
}
uint32_t pool_idx = 0;
for (auto _ : state) {
bv.Clear(row_pool[pool_idx]);
pool_idx = (pool_idx + 1) % kPoolSize;
benchmark::ClobberMemory();
}
}
BENCHMARK(BM_BitVectorClear)->Apply(BitVectorArgs);
static void BM_BitVectorIndexOfNthSet(benchmark::State& state) {
static constexpr uint32_t kRandomSeed = 42;
std::minstd_rand0 rnd_engine(kRandomSeed);
uint32_t size = static_cast<uint32_t>(state.range(0));
uint32_t set_percentage = static_cast<uint32_t>(state.range(1));
BitVector bv = BvWithSizeAndSetPercentage(size, set_percentage);
static constexpr uint32_t kPoolSize = 1024 * 1024;
std::vector<uint32_t> row_pool(kPoolSize);
uint32_t set_bit_count = bv.GetNumBitsSet();
if (set_bit_count == 0) {
state.SkipWithError("Cannot find set bit in all zeros bitvector");
return;
}
for (uint32_t i = 0; i < kPoolSize; ++i) {
row_pool[i] = rnd_engine() % set_bit_count;
}
uint32_t pool_idx = 0;
for (auto _ : state) {
benchmark::DoNotOptimize(bv.IndexOfNthSet(row_pool[pool_idx]));
pool_idx = (pool_idx + 1) % kPoolSize;
}
}
BENCHMARK(BM_BitVectorIndexOfNthSet)->Apply(BitVectorArgs);
static void BM_BitVectorGetNumBitsSet(benchmark::State& state) {
static constexpr uint32_t kRandomSeed = 42;
std::minstd_rand0 rnd_engine(kRandomSeed);
uint32_t size = static_cast<uint32_t>(state.range(0));
uint32_t set_percentage = static_cast<uint32_t>(state.range(1));
uint32_t count = 0;
BitVector bv;
for (uint32_t i = 0; i < size; ++i) {
bool value = rnd_engine() % 100 < set_percentage;
if (value) {
bv.AppendTrue();
} else {
bv.AppendFalse();
}
if (value)
count++;
}
uint32_t res = count;
for (auto _ : state) {
benchmark::DoNotOptimize(res &= bv.GetNumBitsSet());
}
PERFETTO_CHECK(res == count);
}
BENCHMARK(BM_BitVectorGetNumBitsSet)->Apply(BitVectorArgs);
static void BM_BitVectorResize(benchmark::State& state) {
static constexpr uint32_t kRandomSeed = 42;
std::minstd_rand0 rnd_engine(kRandomSeed);
static constexpr uint32_t kPoolSize = 1024 * 1024;
static constexpr uint32_t kMaxSize = 1234567;
std::vector<bool> resize_fill_pool(kPoolSize);
std::vector<uint32_t> resize_count_pool(kPoolSize);
for (uint32_t i = 0; i < kPoolSize; ++i) {
resize_fill_pool[i] = rnd_engine() % 2;
resize_count_pool[i] = rnd_engine() % kMaxSize;
}
uint32_t pool_idx = 0;
BitVector bv;
for (auto _ : state) {
bv.Resize(resize_count_pool[pool_idx], resize_fill_pool[pool_idx]);
pool_idx = (pool_idx + 1) % kPoolSize;
benchmark::ClobberMemory();
}
}
BENCHMARK(BM_BitVectorResize);
static void BM_BitVectorRangeFixedSize(benchmark::State& state) {
static constexpr uint32_t kRandomSeed = 42;
std::minstd_rand0 rnd_engine(kRandomSeed);
uint32_t size = static_cast<uint32_t>(state.range(0));
uint32_t set_percentage = static_cast<uint32_t>(state.range(1));
std::vector<uint32_t> resize_fill_pool(size);
for (uint32_t i = 0; i < size; ++i) {
resize_fill_pool[i] = rnd_engine() % 100 < set_percentage ? 90 : 100;
}
for (auto _ : state) {
auto filler = [&resize_fill_pool](uint32_t i) PERFETTO_ALWAYS_INLINE {
return resize_fill_pool[i] < 95;
};
BitVector bv = BitVector::Range(0, size, filler);
benchmark::ClobberMemory();
}
}
BENCHMARK(BM_BitVectorRangeFixedSize)->Apply(BitVectorArgs);
static void BM_BitVectorUpdateSetBits(benchmark::State& state) {
static constexpr uint32_t kRandomSeed = 42;
std::minstd_rand0 rnd_engine(kRandomSeed);
uint32_t size = static_cast<uint32_t>(state.range(0));
uint32_t set_percentage = static_cast<uint32_t>(state.range(1));
uint32_t picker_set_percentage = static_cast<uint32_t>(state.range(2));
BitVector bv;
BitVector picker;
for (uint32_t i = 0; i < size; ++i) {
bool value = rnd_engine() % 100 < set_percentage;
if (value) {
bv.AppendTrue();
bool picker_value = rnd_engine() % 100 < picker_set_percentage;
if (picker_value) {
picker.AppendTrue();
} else {
picker.AppendFalse();
}
} else {
bv.AppendFalse();
}
}
uint32_t set_bit_count = bv.GetNumBitsSet();
uint32_t picker_set_bit_count = picker.GetNumBitsSet();
for (auto _ : state) {
BitVector copy = bv.Copy();
copy.UpdateSetBits(picker);
benchmark::DoNotOptimize(copy);
}
state.counters["s/set bit"] = benchmark::Counter(
set_bit_count, benchmark::Counter::kIsIterationInvariantRate |
benchmark::Counter::kInvert);
state.counters["s/set picker bit"] = benchmark::Counter(
picker_set_bit_count, benchmark::Counter::kIsIterationInvariantRate |
benchmark::Counter::kInvert);
}
BENCHMARK(BM_BitVectorUpdateSetBits)->Apply(UpdateSetBitsArgs);
static void BM_BitVectorSetBitsIterator(benchmark::State& state) {
uint32_t size = static_cast<uint32_t>(state.range(0));
uint32_t set_percentage = static_cast<uint32_t>(state.range(1));
BitVector bv = BvWithSizeAndSetPercentage(size, set_percentage);
for (auto _ : state) {
for (auto it = bv.IterateSetBits(); it; it.Next()) {
benchmark::DoNotOptimize(it.index());
}
}
}
BENCHMARK(BM_BitVectorSetBitsIterator)->Apply(BitVectorArgs);
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: registrationdlg.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2007-06-27 21:58:34 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#ifndef SVTOOLS_REGISTRATIONDLG_HXX
#include "registrationdlg.hxx"
#endif
#if 0 /* @@@ */
#ifndef _SVTOOLS_SVTDATA_HXX
#include <svtools/svtdata.hxx>
#endif
#ifndef _SVTOOLS_HRC
#include <svtools/svtools.hrc>
#endif
#endif /* @@@ */
#ifndef SVTOOLS_REGISTRATIONDLG_HRC
#include "registrationdlg.hrc"
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
//........................................................................
namespace svt
{
//........................................................................
static void lcl_moveControls( Control** _ppControls, sal_Int32 _nAmount )
{
if ( _ppControls )
while ( *_ppControls )
{
Point aPos = (*_ppControls)->GetPosPixel();
aPos.Y() += _nAmount;
(*_ppControls)->SetPosPixel( aPos );
++_ppControls;
}
}
//====================================================================
//= RegistrationDialog
//====================================================================
//--------------------------------------------------------------------
RegistrationDialog::RegistrationDialog( Window* _pWindow, const ResId& _rResId, bool _bEvalVersion )
:ModalDialog( _pWindow, _rResId )
,m_eResponse ( urRegisterLater )
,m_aLogo ( this, ResId( FI_LOGO, *_rResId.GetResMgr() ) )
,m_aIntro ( this, ResId( FT_INTRO, *_rResId.GetResMgr() ) )
,m_aNow ( this, ResId( RB_NOW, *_rResId.GetResMgr() ) )
,m_aLater ( this, ResId( RB_LATER, *_rResId.GetResMgr() ) )
,m_aNever ( this, ResId( RB_NEVER, *_rResId.GetResMgr() ) )
,m_aAlreadyDone ( this, ResId( RB_DONE, *_rResId.GetResMgr() ) )
,m_aSeparator ( this, ResId( FL_SEPARATOR, *_rResId.GetResMgr() ) )
,m_aOK ( this, ResId( BTN_OK, *_rResId.GetResMgr() ) )
,m_aHelp ( this, ResId( BTN_HELP, *_rResId.GetResMgr() ) )
{
if ( _bEvalVersion )
{ // if we're an eval version, we need to hide two of the options
m_aNever.Hide( );
m_aAlreadyDone.Hide( );
// make the explanatory text somewhat smaller
Size aIntroSize = m_aIntro.GetSizePixel();
aIntroSize.Height() = LogicToPixel( Size( 0, 18 ), MAP_APPFONT ).Height();
sal_Int32 nHeightDifference = m_aIntro.GetSizePixel().Height() - aIntroSize.Height();
m_aIntro.SetSizePixel( aIntroSize );
// resize the dialog, and move the controls below the ones we just hided
sal_Int32 nAlreadyDoneLower = m_aAlreadyDone.GetPosPixel().Y() + m_aAlreadyDone.GetSizePixel().Height();
sal_Int32 nLaterLower = m_aLater.GetPosPixel().Y() + m_aLater.GetSizePixel().Height();
sal_Int32 nDifference = nAlreadyDoneLower - nLaterLower;
sal_Int32 nOverallDifference = nDifference + nHeightDifference;
// move
Control* pVisibleRadios[] = { &m_aNow, &m_aLater, NULL };
lcl_moveControls( pVisibleRadios, -nHeightDifference );
Control* pControlsToMove[] = { &m_aSeparator, &m_aOK, &m_aHelp, NULL };
lcl_moveControls( pControlsToMove, -nOverallDifference );
// resize the dialog
Size aSize = GetSizePixel();
aSize.Height() -= nOverallDifference;
SetSizePixel( aSize );
}
else
{
// the explanatory text needs to be completed
String sCompleteIntro = m_aIntro.GetText( );
sCompleteIntro += String( ResId( STR_COMPLETE_INTRO, *_rResId.GetResMgr() ) );
m_aIntro.SetText( sCompleteIntro );
}
FreeResource();
m_aNow.Check( TRUE );
}
//--------------------------------------------------------------------
short RegistrationDialog::Execute()
{
short nResult = ModalDialog::Execute();
// as a default, assume that the user wants to be reminded
m_eResponse = urRegisterLater;
if ( RET_OK == nResult )
{
if ( m_aNow.IsChecked() )
m_eResponse = urRegisterNow;
else if ( m_aLater.IsChecked() )
m_eResponse = urRegisterLater;
else if ( m_aNever.IsChecked() )
m_eResponse = urRegisterNever;
else if ( m_aAlreadyDone.IsChecked() )
m_eResponse = urAlreadyRegistered;
#ifdef DBG_UTIL
else
{
DBG_ERROR( "RegistrationDialog::Execute: invalid dialog state!" );
}
#endif
}
return nResult;
}
//--------------------------------------------------------------------
long RegistrationDialog::PreNotify( NotifyEvent& rNEvt )
{
long nHandled;
if( rNEvt.GetType() == EVENT_KEYINPUT &&
rNEvt.GetKeyEvent()->GetCharCode() &&
rNEvt.GetKeyEvent()->GetKeyCode().GetCode() == KEY_ESCAPE)
{
EndDialog(RET_CANCEL);
nHandled = 1;
}
else
nHandled = ModalDialog::PreNotify( rNEvt );
return nHandled;
}
//........................................................................
} // namespace svt
//........................................................................
<commit_msg>INTEGRATION: CWS changefileheader (1.7.246); FILE MERGED 2008/04/01 15:45:27 thb 1.7.246.3: #i85898# Stripping all external header guards 2008/04/01 12:43:52 thb 1.7.246.2: #i85898# Stripping all external header guards 2008/03/31 13:02:29 rt 1.7.246.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: registrationdlg.cxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#include "registrationdlg.hxx"
#if 0 /* @@@ */
#include <svtools/svtdata.hxx>
#ifndef _SVTOOLS_HRC
#include <svtools/svtools.hrc>
#endif
#endif /* @@@ */
#ifndef SVTOOLS_REGISTRATIONDLG_HRC
#include "registrationdlg.hrc"
#endif
#include <vcl/msgbox.hxx>
#include <tools/debug.hxx>
//........................................................................
namespace svt
{
//........................................................................
static void lcl_moveControls( Control** _ppControls, sal_Int32 _nAmount )
{
if ( _ppControls )
while ( *_ppControls )
{
Point aPos = (*_ppControls)->GetPosPixel();
aPos.Y() += _nAmount;
(*_ppControls)->SetPosPixel( aPos );
++_ppControls;
}
}
//====================================================================
//= RegistrationDialog
//====================================================================
//--------------------------------------------------------------------
RegistrationDialog::RegistrationDialog( Window* _pWindow, const ResId& _rResId, bool _bEvalVersion )
:ModalDialog( _pWindow, _rResId )
,m_eResponse ( urRegisterLater )
,m_aLogo ( this, ResId( FI_LOGO, *_rResId.GetResMgr() ) )
,m_aIntro ( this, ResId( FT_INTRO, *_rResId.GetResMgr() ) )
,m_aNow ( this, ResId( RB_NOW, *_rResId.GetResMgr() ) )
,m_aLater ( this, ResId( RB_LATER, *_rResId.GetResMgr() ) )
,m_aNever ( this, ResId( RB_NEVER, *_rResId.GetResMgr() ) )
,m_aAlreadyDone ( this, ResId( RB_DONE, *_rResId.GetResMgr() ) )
,m_aSeparator ( this, ResId( FL_SEPARATOR, *_rResId.GetResMgr() ) )
,m_aOK ( this, ResId( BTN_OK, *_rResId.GetResMgr() ) )
,m_aHelp ( this, ResId( BTN_HELP, *_rResId.GetResMgr() ) )
{
if ( _bEvalVersion )
{ // if we're an eval version, we need to hide two of the options
m_aNever.Hide( );
m_aAlreadyDone.Hide( );
// make the explanatory text somewhat smaller
Size aIntroSize = m_aIntro.GetSizePixel();
aIntroSize.Height() = LogicToPixel( Size( 0, 18 ), MAP_APPFONT ).Height();
sal_Int32 nHeightDifference = m_aIntro.GetSizePixel().Height() - aIntroSize.Height();
m_aIntro.SetSizePixel( aIntroSize );
// resize the dialog, and move the controls below the ones we just hided
sal_Int32 nAlreadyDoneLower = m_aAlreadyDone.GetPosPixel().Y() + m_aAlreadyDone.GetSizePixel().Height();
sal_Int32 nLaterLower = m_aLater.GetPosPixel().Y() + m_aLater.GetSizePixel().Height();
sal_Int32 nDifference = nAlreadyDoneLower - nLaterLower;
sal_Int32 nOverallDifference = nDifference + nHeightDifference;
// move
Control* pVisibleRadios[] = { &m_aNow, &m_aLater, NULL };
lcl_moveControls( pVisibleRadios, -nHeightDifference );
Control* pControlsToMove[] = { &m_aSeparator, &m_aOK, &m_aHelp, NULL };
lcl_moveControls( pControlsToMove, -nOverallDifference );
// resize the dialog
Size aSize = GetSizePixel();
aSize.Height() -= nOverallDifference;
SetSizePixel( aSize );
}
else
{
// the explanatory text needs to be completed
String sCompleteIntro = m_aIntro.GetText( );
sCompleteIntro += String( ResId( STR_COMPLETE_INTRO, *_rResId.GetResMgr() ) );
m_aIntro.SetText( sCompleteIntro );
}
FreeResource();
m_aNow.Check( TRUE );
}
//--------------------------------------------------------------------
short RegistrationDialog::Execute()
{
short nResult = ModalDialog::Execute();
// as a default, assume that the user wants to be reminded
m_eResponse = urRegisterLater;
if ( RET_OK == nResult )
{
if ( m_aNow.IsChecked() )
m_eResponse = urRegisterNow;
else if ( m_aLater.IsChecked() )
m_eResponse = urRegisterLater;
else if ( m_aNever.IsChecked() )
m_eResponse = urRegisterNever;
else if ( m_aAlreadyDone.IsChecked() )
m_eResponse = urAlreadyRegistered;
#ifdef DBG_UTIL
else
{
DBG_ERROR( "RegistrationDialog::Execute: invalid dialog state!" );
}
#endif
}
return nResult;
}
//--------------------------------------------------------------------
long RegistrationDialog::PreNotify( NotifyEvent& rNEvt )
{
long nHandled;
if( rNEvt.GetType() == EVENT_KEYINPUT &&
rNEvt.GetKeyEvent()->GetCharCode() &&
rNEvt.GetKeyEvent()->GetKeyCode().GetCode() == KEY_ESCAPE)
{
EndDialog(RET_CANCEL);
nHandled = 1;
}
else
nHandled = ModalDialog::PreNotify( rNEvt );
return nHandled;
}
//........................................................................
} // namespace svt
//........................................................................
<|endoftext|> |
<commit_before>#include <Riostream.h>
#ifndef WIN32
# define stupre stupre_
#else
# define stupre STUPRE
#endif
//
// Fluka include
#include "Fdimpar.h" //(DIMPAR) fluka include
// Fluka commons
#include "Fdblprc.h" //(DBLPRC) fluka common
#include "Femfstk.h" //(EMFSTK) fluka common
#include "Fevtflg.h" //(EVTFLG) fluka common
#include "Fpaprop.h" //(PAPROP) fluka common
#include "Ftrackr.h" //(TRACKR) fluka common
#include "Femfrgn.h" //(EFMRGN) fluka common
//Virtual MC
#include "TFluka.h"
#include "TVirtualMCStack.h"
#include "TVirtualMCApplication.h"
#include "TParticle.h"
#include "TVector3.h"
extern "C" {
void stupre()
{
//*----------------------------------------------------------------------*
//* *
//* SeT User PRoperties for Emf particles *
//* *
//*----------------------------------------------------------------------*
static Double_t emassmev = PAPROP.am[9] * 1000.;
Int_t lbhabh = 0;
if (EVTFLG.ldltry == 1) {
if (EMFSTK.ichemf[EMFSTK.npemf-1] * EMFSTK.ichemf[EMFSTK.npemf-2] < 0) lbhabh = 1;
}
// mkbmx1 = dimension for kwb real spare array in fluka stack in DIMPAR
// mkbmx2 = dimension for kwb int. spare array in fluka stack in DIMPAR
// EMFSTK.espark = spare real variables available for
// EMFSTK.iespak = spare integer variables available for
// TRACKR.spausr = user defined spare variables for the current particle
// TRACKR.ispusr = user defined spare flags for the current particle
// EMFSTK.louemf = user flag
// TRACKR.llouse = user defined flag for the current particle
Int_t npnw, ispr;
for (npnw = EMFSTK.npstrt-1; npnw <= EMFSTK.npemf-1; npnw++) {
for (ispr = 0; ispr <= mkbmx1-1; ispr++)
EMFSTK.espark[npnw][ispr] = TRACKR.spausr[ispr];
for (ispr = 0; ispr <= mkbmx2-1; ispr++)
EMFSTK.iespak[npnw][ispr] = TRACKR.ispusr[ispr];
EMFSTK.louemf[npnw] = TRACKR.llouse;
}
// Get the pointer to the VMC
TFluka* fluka = (TFluka*) gMC;
Int_t verbosityLevel = fluka->GetVerbosityLevel();
Bool_t debug = (verbosityLevel>=3)?kTRUE:kFALSE;
fluka->SetTrackIsNew(kTRUE);
// Get the stack produced from the generator
TVirtualMCStack* cppstack = fluka->GetStack();
// EVTFLG.ntrcks = track number
// Increment the track number and put it into the last flag
Int_t kp;
for (kp = EMFSTK.npstrt - 1; kp <= EMFSTK.npemf - 1; kp++) {
// Ckeck transport cut first
Int_t ireg = EMFSTK.iremf[kp];
Double_t cut = (TMath::Abs(EMFSTK.ichemf[kp]) == 1) ? EMFRGN.elethr[ireg-1] : EMFRGN.phothr[ireg-1];
Double_t e = EMFSTK.etemf[kp];
if ((e < cut)
&& (
(EMFSTK.ichemf[kp] == 0) ||
(EMFSTK.ichemf[kp] == -1) ||
(EMFSTK.ichemf[kp] == 1 && EMFRGN.phothr[ireg-1] > emassmev)
)
)
{
EMFSTK.iespak[kp][mkbmx2-1] = -1;
EMFSTK.iespak[kp][mkbmx2-2] = 0;
continue;
}
//* save the parent track number and reset it at each loop
Int_t done = 0;
Int_t parent = TRACKR.ispusr[mkbmx2-1];
Int_t flukaid = 0;
// Identify particle type
if (EMFSTK.ichemf[kp] == -1) flukaid = 3;
else if (EMFSTK.ichemf[kp] == 0) flukaid = 7;
else if (EMFSTK.ichemf[kp] == 1) flukaid = 4;
e *= emvgev;
Int_t pdg = fluka->PDGFromId(flukaid);
Double_t p = sqrt(e * e - PAPROP.am[flukaid+6] * PAPROP.am[flukaid+6]);
Double_t px = p * EMFSTK.uemf[kp];
Double_t pz = p * EMFSTK.vemf[kp];
Double_t py = p * EMFSTK.wemf[kp];
Double_t tof = EMFSTK.agemf[kp];
Double_t polx = EMFSTK.upol[kp];
Double_t poly = EMFSTK.vpol[kp];
Double_t polz = EMFSTK.wpol[kp];
Double_t vx = EMFSTK.xemf[kp];
Double_t vy = EMFSTK.yemf[kp];
Double_t vz = EMFSTK.zemf[kp];
Double_t weight = EMFSTK.wtemf[kp];
Int_t ntr;
TMCProcess mech;
Int_t is = 0;
//* case of no parent left (pair, photoelectric, annihilation):
//* all secondaries are true
if ((EVTFLG.lpairp == 1) || (EVTFLG.lphoel == 1) ||
(EVTFLG.lannfl == 1) || (EVTFLG.lannrs == 1)) {
if (EVTFLG.lpairp == 1) mech = kPPair;
else if (EVTFLG.lphoel == 1) mech = kPPhotoelectric;
else mech = kPAnnihilation;
cppstack->PushTrack(done, parent, pdg,
px, py, pz, e, vx, vy, vz, tof,
polx, poly, polz, mech, ntr, weight, is);
if (debug) cout << endl << " !!! stupre (PAIR, ..) : ntr=" << ntr << "pdg " << pdg << " parent=" << parent << "energy " << e-PAPROP.am[flukaid+6] << endl;
EMFSTK.iespak[kp][mkbmx2-1] = ntr;
EMFSTK.iespak[kp][mkbmx2-2] = 0;
} // end of lpairp, lphoel, lannfl, lannrs
//* Compton: secondary is true only if charged (e+, e-)
else if ((EVTFLG.lcmptn == 1)) {
if (EMFSTK.ichemf[kp] != 0) {
mech = kPCompton;
cppstack->PushTrack(done, parent, pdg,
px, py, pz, e, vx, vy, vz, tof,
polx, poly, polz, mech, ntr, weight, is);
if (debug) cout << endl << " !!! stupre (COMPTON) : ntr=" << ntr << "pdg " << pdg << " parent=" << parent << endl;
EMFSTK.iespak[kp][mkbmx2-1] = ntr;
EMFSTK.iespak[kp][mkbmx2-2] = 0;
}
} // end of lcmptn
//* Bremsstrahlung: true secondary only if charge = 0 (photon)
else if ((EVTFLG.lbrmsp == 1)) {
if (EMFSTK.ichemf[kp] == 0) {
mech = kPBrem;
cppstack->PushTrack(done, parent, pdg,
px, py, pz, e, vx, vy, vz, tof,
polx, poly, polz, mech, ntr, weight, is);
if (debug) cout << endl << " !!! stupre (BREMS) : ntr=" << ntr << "pdg " << pdg << " parent=" << parent << endl;
EMFSTK.iespak[kp][mkbmx2-1] = ntr;
EMFSTK.iespak[kp][mkbmx2-2] = 0;
}
} // end of lbrmsp
//* Delta ray: If Bhabha, true secondary only if negative (electron)
else if ((EVTFLG.ldltry == 1)) {
if (lbhabh == 1) {
if (EMFSTK.ichemf[kp] == -1) {
mech = kPDeltaRay;
cppstack->PushTrack(done, parent, pdg,
px, py, pz, e, vx, vy, vz, tof,
polx, poly, polz, mech, ntr, weight, is);
EMFSTK.iespak[kp][mkbmx2-1] = ntr;
EMFSTK.iespak[kp][mkbmx2-2] = 0;
if (debug) cout << endl << " !!! stupre (BHABA) : ntr=" << ntr << "pdg " << pdg << " parent=" << parent << endl;
} // end of Bhabha
} // lbhabh == 1
//* Delta ray: Otherwise Moller: true secondary is the electron with
//* lower energy, which has been put higher in the stack
else if (kp == EMFSTK.npemf-1) {
mech = kPDeltaRay;
cppstack->PushTrack(done, parent, pdg,
px, py, pz, e, vx, vy, vz, tof,
polx, poly, polz, mech, ntr, weight, is);
if (debug) cout << endl << " !!! stupre (Moller) : ntr=" << ntr << "pdg " << pdg << " parent=" << parent << endl;
EMFSTK.iespak[kp][mkbmx2-1] = ntr;
EMFSTK.iespak[kp][mkbmx2-2] = 0;
} // end of Delta ray
} // end of ldltry
} // end of loop
} // end of stupre
} // end of extern "C"
<commit_msg>- particle below transport threshold is attached to mother (same id) - Correction for py,pz of secondary.<commit_after>#include <Riostream.h>
#ifndef WIN32
# define stupre stupre_
#else
# define stupre STUPRE
#endif
//
// Fluka include
#include "Fdimpar.h" //(DIMPAR) fluka include
// Fluka commons
#include "Fdblprc.h" //(DBLPRC) fluka common
#include "Femfstk.h" //(EMFSTK) fluka common
#include "Fevtflg.h" //(EVTFLG) fluka common
#include "Fpaprop.h" //(PAPROP) fluka common
#include "Ftrackr.h" //(TRACKR) fluka common
#include "Femfrgn.h" //(EFMRGN) fluka common
//Virtual MC
#include "TFluka.h"
#include "TVirtualMCStack.h"
#include "TVirtualMCApplication.h"
#include "TParticle.h"
#include "TVector3.h"
extern "C" {
void stupre()
{
//*----------------------------------------------------------------------*
//* *
//* SeT User PRoperties for Emf particles *
//* *
//*----------------------------------------------------------------------*
static Double_t emassmev = PAPROP.am[9] * 1000.;
Int_t lbhabh = 0;
if (EVTFLG.ldltry == 1) {
if (EMFSTK.ichemf[EMFSTK.npemf-1] * EMFSTK.ichemf[EMFSTK.npemf-2] < 0) lbhabh = 1;
}
// mkbmx1 = dimension for kwb real spare array in fluka stack in DIMPAR
// mkbmx2 = dimension for kwb int. spare array in fluka stack in DIMPAR
// EMFSTK.espark = spare real variables available for
// EMFSTK.iespak = spare integer variables available for
// TRACKR.spausr = user defined spare variables for the current particle
// TRACKR.ispusr = user defined spare flags for the current particle
// EMFSTK.louemf = user flag
// TRACKR.llouse = user defined flag for the current particle
Int_t npnw, ispr;
for (npnw = EMFSTK.npstrt-1; npnw <= EMFSTK.npemf-1; npnw++) {
for (ispr = 0; ispr <= mkbmx1-1; ispr++)
EMFSTK.espark[npnw][ispr] = TRACKR.spausr[ispr];
for (ispr = 0; ispr <= mkbmx2-1; ispr++)
EMFSTK.iespak[npnw][ispr] = TRACKR.ispusr[ispr];
EMFSTK.louemf[npnw] = TRACKR.llouse;
}
// Get the pointer to the VMC
TFluka* fluka = (TFluka*) gMC;
Int_t verbosityLevel = fluka->GetVerbosityLevel();
Bool_t debug = (verbosityLevel>=3)?kTRUE:kFALSE;
fluka->SetTrackIsNew(kTRUE);
// Get the stack produced from the generator
TVirtualMCStack* cppstack = fluka->GetStack();
// EVTFLG.ntrcks = track number
// Increment the track number and put it into the last flag
Int_t kp;
for (kp = EMFSTK.npstrt - 1; kp <= EMFSTK.npemf - 1; kp++) {
// Ckeck transport cut first
Int_t ireg = EMFSTK.iremf[kp];
Double_t cut = (TMath::Abs(EMFSTK.ichemf[kp]) == 1) ? EMFRGN.elethr[ireg-1] : EMFRGN.phothr[ireg-1];
Double_t e = EMFSTK.etemf[kp];
if ((e < cut)
&& (
(EMFSTK.ichemf[kp] == 0) ||
(EMFSTK.ichemf[kp] == -1) ||
(EMFSTK.ichemf[kp] == 1 && EMFRGN.phothr[ireg-1] > emassmev)
)
)
{
EMFSTK.iespak[kp][mkbmx2-1] = TRACKR.ispusr[mkbmx2-1];
EMFSTK.iespak[kp][mkbmx2-2] = 0;
continue;
}
//* save the parent track number and reset it at each loop
Int_t done = 0;
Int_t parent = TRACKR.ispusr[mkbmx2-1];
Int_t flukaid = 0;
// Identify particle type
if (EMFSTK.ichemf[kp] == -1) flukaid = 3;
else if (EMFSTK.ichemf[kp] == 0) flukaid = 7;
else if (EMFSTK.ichemf[kp] == 1) flukaid = 4;
e *= emvgev;
Int_t pdg = fluka->PDGFromId(flukaid);
Double_t p = sqrt(e * e - PAPROP.am[flukaid+6] * PAPROP.am[flukaid+6]);
Double_t px = p * EMFSTK.uemf[kp];
Double_t py = p * EMFSTK.vemf[kp];
Double_t pz = p * EMFSTK.wemf[kp];
Double_t tof = EMFSTK.agemf[kp];
Double_t polx = EMFSTK.upol[kp];
Double_t poly = EMFSTK.vpol[kp];
Double_t polz = EMFSTK.wpol[kp];
Double_t vx = EMFSTK.xemf[kp];
Double_t vy = EMFSTK.yemf[kp];
Double_t vz = EMFSTK.zemf[kp];
Double_t weight = EMFSTK.wtemf[kp];
Int_t ntr;
TMCProcess mech;
Int_t is = 0;
//* case of no parent left (pair, photoelectric, annihilation):
//* all secondaries are true
if ((EVTFLG.lpairp == 1) || (EVTFLG.lphoel == 1) ||
(EVTFLG.lannfl == 1) || (EVTFLG.lannrs == 1)) {
if (EVTFLG.lpairp == 1) mech = kPPair;
else if (EVTFLG.lphoel == 1) mech = kPPhotoelectric;
else mech = kPAnnihilation;
cppstack->PushTrack(done, parent, pdg,
px, py, pz, e, vx, vy, vz, tof,
polx, poly, polz, mech, ntr, weight, is);
if (debug) cout << endl << " !!! stupre (PAIR, ..) : ntr=" << ntr << "pdg " << pdg << " parent=" << parent << "energy " << e-PAPROP.am[flukaid+6] << endl;
EMFSTK.iespak[kp][mkbmx2-1] = ntr;
EMFSTK.iespak[kp][mkbmx2-2] = 0;
} // end of lpairp, lphoel, lannfl, lannrs
//* Compton: secondary is true only if charged (e+, e-)
else if ((EVTFLG.lcmptn == 1)) {
if (EMFSTK.ichemf[kp] != 0) {
mech = kPCompton;
cppstack->PushTrack(done, parent, pdg,
px, py, pz, e, vx, vy, vz, tof,
polx, poly, polz, mech, ntr, weight, is);
if (debug) cout << endl << " !!! stupre (COMPTON) : ntr=" << ntr << "pdg " << pdg << " parent=" << parent << endl;
EMFSTK.iespak[kp][mkbmx2-1] = ntr;
EMFSTK.iespak[kp][mkbmx2-2] = 0;
}
} // end of lcmptn
//* Bremsstrahlung: true secondary only if charge = 0 (photon)
else if ((EVTFLG.lbrmsp == 1)) {
if (EMFSTK.ichemf[kp] == 0) {
mech = kPBrem;
cppstack->PushTrack(done, parent, pdg,
px, py, pz, e, vx, vy, vz, tof,
polx, poly, polz, mech, ntr, weight, is);
if (debug) cout << endl << " !!! stupre (BREMS) : ntr=" << ntr << "pdg " << pdg << " parent=" << parent << endl;
EMFSTK.iespak[kp][mkbmx2-1] = ntr;
EMFSTK.iespak[kp][mkbmx2-2] = 0;
}
} // end of lbrmsp
//* Delta ray: If Bhabha, true secondary only if negative (electron)
else if ((EVTFLG.ldltry == 1)) {
if (lbhabh == 1) {
if (EMFSTK.ichemf[kp] == -1) {
mech = kPDeltaRay;
cppstack->PushTrack(done, parent, pdg,
px, py, pz, e, vx, vy, vz, tof,
polx, poly, polz, mech, ntr, weight, is);
EMFSTK.iespak[kp][mkbmx2-1] = ntr;
EMFSTK.iespak[kp][mkbmx2-2] = 0;
if (debug) cout << endl << " !!! stupre (BHABA) : ntr=" << ntr << "pdg " << pdg << " parent=" << parent << endl;
} // end of Bhabha
} // lbhabh == 1
//* Delta ray: Otherwise Moller: true secondary is the electron with
//* lower energy, which has been put higher in the stack
else if (kp == EMFSTK.npemf-1) {
mech = kPDeltaRay;
cppstack->PushTrack(done, parent, pdg,
px, py, pz, e, vx, vy, vz, tof,
polx, poly, polz, mech, ntr, weight, is);
if (debug) cout << endl << " !!! stupre (Moller) : ntr=" << ntr << "pdg " << pdg << " parent=" << parent << endl;
EMFSTK.iespak[kp][mkbmx2-1] = ntr;
EMFSTK.iespak[kp][mkbmx2-2] = 0;
} // end of Delta ray
} // end of ldltry
} // end of loop
} // end of stupre
} // end of extern "C"
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions Inc. 1990-2013. All rights reserved
*/
// TEST Foundation::Math
#include "Stroika/Foundation/StroikaPreComp.h"
#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/Math/Angle.h"
#include "Stroika/Foundation/Math/Common.h"
#include "Stroika/Foundation/Math/Overlap.h"
#include "../TestHarness/SimpleClass.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Math;
namespace {
// test helper to assure answer for (A,B) is same as (B,A) - commutative
template <typename T>
bool VerifyOverlapIsCommutative_ (const pair<T, T>& p1, const pair<T, T>& p2)
{
bool r = Overlaps<T> (p1, p2);
VerifyTestResult (r == Overlaps<T> (p2, p1));
return r;
}
}
namespace {
void Test1_Overlap_ ()
{
VerifyTestResult (VerifyOverlapIsCommutative_<int> (pair<int, int> (1, 3), pair<int, int> (2, 2)));
VerifyTestResult (not VerifyOverlapIsCommutative_<int> (pair<int, int> (1, 3), pair<int, int> (3, 4)));
VerifyTestResult (not VerifyOverlapIsCommutative_<int> (pair<int, int> (1, 3), pair<int, int> (0, 1)));
VerifyTestResult (VerifyOverlapIsCommutative_<int> (pair<int, int> (1, 3), pair<int, int> (1, 1)));
VerifyTestResult (VerifyOverlapIsCommutative_<int> (pair<int, int> (1, 10), pair<int, int> (3, 4)));
VerifyTestResult (VerifyOverlapIsCommutative_<int> (pair<int, int> (1, 10), pair<int, int> (3, 3)));
VerifyTestResult (VerifyOverlapIsCommutative_<int> (pair<int, int> (5, 10), pair<int, int> (3, 7)));
VerifyTestResult (VerifyOverlapIsCommutative_<int> (pair<int, int> (5, 10), pair<int, int> (5, 5)));
}
void Test2_Round_ ()
{
// really could use more cases!!!
VerifyTestResult (RoundUpTo (2, 10) == 10);
VerifyTestResult (RoundDownTo (2, 10) == 0);
VerifyTestResult (RoundUpTo (2, 2) == 2);
VerifyTestResult (RoundDownTo (2, 2) == 2);
}
void Test3_Angle_ ()
{
// really could use more cases!!!
VerifyTestResult (Angle (1.1) + Angle (1.1) < Angle (2.3));
VerifyTestResult (Angle (1.1) + Angle (1.1) < Angle (360, Angle::AngleFormat::eDegrees));
VerifyTestResult (Angle (1.1) + Angle (1.1) < Angle (180, Angle::AngleFormat::eDegrees));
VerifyTestResult (Angle (1.1) + Angle (1.1) > Angle (120, Angle::AngleFormat::eDegrees));
}
}
namespace {
void DoRegressionTests_ ()
{
Test1_Overlap_ ();
Test2_Round_ ();
Test3_Angle_ ();
}
}
int main (int argc, const char* argv[])
{
Stroika::TestHarness::Setup ();
Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
return EXIT_SUCCESS;
}
<commit_msg>added new regression test for copy of Optional<Mapping<>> I encountered<commit_after>/*
* Copyright(c) Sophist Solutions Inc. 1990-2013. All rights reserved
*/
// TEST Foundation::Math
#include "Stroika/Foundation/StroikaPreComp.h"
#include "Stroika/Foundation/Containers/Mapping.h"
#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/Math/Angle.h"
#include "Stroika/Foundation/Math/Common.h"
#include "Stroika/Foundation/Math/Overlap.h"
#include "../TestHarness/SimpleClass.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Math;
namespace {
// test helper to assure answer for (A,B) is same as (B,A) - commutative
template <typename T>
bool VerifyOverlapIsCommutative_ (const pair<T, T>& p1, const pair<T, T>& p2)
{
bool r = Overlaps<T> (p1, p2);
VerifyTestResult (r == Overlaps<T> (p2, p1));
return r;
}
}
namespace {
void Test1_Overlap_ ()
{
VerifyTestResult (VerifyOverlapIsCommutative_<int> (pair<int, int> (1, 3), pair<int, int> (2, 2)));
VerifyTestResult (not VerifyOverlapIsCommutative_<int> (pair<int, int> (1, 3), pair<int, int> (3, 4)));
VerifyTestResult (not VerifyOverlapIsCommutative_<int> (pair<int, int> (1, 3), pair<int, int> (0, 1)));
VerifyTestResult (VerifyOverlapIsCommutative_<int> (pair<int, int> (1, 3), pair<int, int> (1, 1)));
VerifyTestResult (VerifyOverlapIsCommutative_<int> (pair<int, int> (1, 10), pair<int, int> (3, 4)));
VerifyTestResult (VerifyOverlapIsCommutative_<int> (pair<int, int> (1, 10), pair<int, int> (3, 3)));
VerifyTestResult (VerifyOverlapIsCommutative_<int> (pair<int, int> (5, 10), pair<int, int> (3, 7)));
VerifyTestResult (VerifyOverlapIsCommutative_<int> (pair<int, int> (5, 10), pair<int, int> (5, 5)));
}
void Test2_Round_ ()
{
// really could use more cases!!!
VerifyTestResult (RoundUpTo (2, 10) == 10);
VerifyTestResult (RoundDownTo (2, 10) == 0);
VerifyTestResult (RoundUpTo (2, 2) == 2);
VerifyTestResult (RoundDownTo (2, 2) == 2);
}
void Test3_Angle_ ()
{
// really could use more cases!!!
VerifyTestResult (Angle (1.1) + Angle (1.1) < Angle (2.3));
VerifyTestResult (Angle (1.1) + Angle (1.1) < Angle (360, Angle::AngleFormat::eDegrees));
VerifyTestResult (Angle (1.1) + Angle (1.1) < Angle (180, Angle::AngleFormat::eDegrees));
VerifyTestResult (Angle (1.1) + Angle (1.1) > Angle (120, Angle::AngleFormat::eDegrees));
}
void Test_4_Optional_Of_Mapping_Copy_Problem_ ()
{
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Foundation::Containers;
Mapping<int, float> ml1, ml2;
ml1 = ml2;
Optional<Mapping<int, float>> ol1, ol2;
ml1 = *ol2;
ol1 = ml1;
Optional<Mapping<int, float>> xxxx2 (ml1);
// fails to compile prior to 2013-09-09
Optional<Mapping<int, float>> xxxx1 (ol1);
// fails to compile prior to 2013-09-09
ol1 = ol2;
}
}
namespace {
void DoRegressionTests_ ()
{
Test1_Overlap_ ();
Test2_Round_ ();
Test3_Angle_ ();
Test_4_Optional_Of_Mapping_Copy_Problem_ ();
}
}
int main (int argc, const char* argv[])
{
Stroika::TestHarness::Setup ();
Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "VGroup.h"
#include "VGlobal.h"
using std::vector;
VBase* VGroup::Add(VBase* object)
{
if (object == nullptr)
{
VLog("Cannot add nullptr to a VGroup");
return nullptr;
}
if (object == this)
{
VLogError("Cannot add itself to it's own list");
return nullptr;
}
if (GetIndexOfItem(object) >= 0)
return nullptr;
if (MaxSize > 0 && length >= static_cast<int>(MaxSize))
{
return object;
}
int index = FirstNULL();
if (index != -1)
{
members[index] = object;
}
else
{
members.push_back(object);
}
object->RefCount++;
length++;
return object;
}
VBase* VGroup::Remove(VBase* object, bool splice)
{
if (members.size() == 0)
return nullptr;
auto pos = GetIndexOfItem(object);
if (pos < 0)
return nullptr;
if (splice)
{
members.erase(members.begin() + pos);
}
else
{
members[pos] = nullptr;
}
object->RefCount--;
length--;
return object;
}
VBase* VGroup::FirstAvailable()
{
for (unsigned int i = 0; i < members.size(); i++)
{
VBase* base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr && !base->exists)
{
return members[i];
}
}
return nullptr;
}
int VGroup::FirstNULL()
{
for (unsigned int i = 0; i < members.size(); i++)
{
VBase* base = dynamic_cast<VBase*>(members[i]);
if (base == nullptr)
{
return i;
}
}
return -1;
}
VBase* VGroup::FirstExisting()
{
for (unsigned int i = 0; i < members.size(); i++)
{
VBase* base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr && base->exists)
{
return members[i];
}
}
return nullptr;
}
VBase* VGroup::FirstAlive()
{
for (unsigned int i = 0; i < members.size(); i++)
{
VBase* base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr && base->exists && base->alive)
{
return members[i];
}
}
return nullptr;
}
VBase* VGroup::FirstDead()
{
for (unsigned int i = 0; i < members.size(); i++)
{
VBase* base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr && !base->alive)
{
return members[i];
}
}
return nullptr;
}
int VGroup::CountAlive()
{
int count = 0;
for (unsigned int i = 0; i < members.size(); i++)
{
VBase* base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr && base->exists && base->alive)
{
count++;
}
}
return count;
}
int VGroup::CountDead()
{
int count = 0;
for (unsigned int i = 0; i < members.size(); i++)
{
VBase* base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr && !base->alive)
{
count++;
}
}
return count;
}
VBase* VGroup::GetRandom(int min, int max)
{
min = min >= 0 ? min : 0;
max = max < (int)members.size() ? max : (int)members.size();
return members[VGlobal::p()->Random->GetInt(max, min)];
}
void VGroup::ForEach(std::function<void(VBase*)> function, bool recursive)
{
VBase* base = nullptr;
for (int i = 0; i < length; i++)
{
base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr)
{
if (recursive)
{
VGroup* group = dynamic_cast<VGroup*>(base);
if (group != nullptr)
{
group->ForEachAlive(function, recursive);
}
}
else
{
function(base);
}
}
}
}
void VGroup::ForEachAlive(std::function<void(VBase*)> function, bool recursive)
{
VBase* base = nullptr;
for (int i = 0; i < length; i++)
{
base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr && base->exists && base->alive)
{
if (recursive)
{
VGroup* group = dynamic_cast<VGroup*>(base);
if (group != nullptr)
{
group->ForEachAlive(function, recursive);
continue;
}
}
function(base);
}
}
}
void VGroup::ForEachDead(std::function<void(VBase*)> function, bool recursive)
{
VBase* base = nullptr;
for (int i = 0; i < length; i++)
{
base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr && !base->alive)
{
if (recursive)
{
VGroup* group = dynamic_cast<VGroup*>(base);
if (group != nullptr)
{
group->ForEachAlive(function, recursive);
}
}
else
{
function(base);
}
}
}
}
void VGroup::ForEachExists(std::function<void(VBase*)> function, bool recursive)
{
VBase* base = nullptr;
for (int i = 0; i < length; i++)
{
base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr && base->exists)
{
if (recursive)
{
VGroup* group = dynamic_cast<VGroup*>(base);
if (group != nullptr)
{
group->ForEachAlive(function, recursive);
}
}
else
{
function(base);
}
}
}
}
VBase* VGroup::GetGroupItem(int index)
{
if (index >= 0 && index < length)
{
return members[index];
}
return nullptr;
}
int VGroup::GetIndexOfItem(VBase* object)
{
auto index = std::find(members.begin(), members.end(), object);
if (index == members.end())
return -1;
return index - members.begin();
}
void VGroup::OrganiseNULLS()
{
for (unsigned int i = 0; i < members.size(); i++)
{
int first = FirstNULL();
if (first == -1)
return;
if (members[i] && first < (int)i)
{
Swap(first, i);
}
}
}
void VGroup::Swap(int a, int b)
{
if (a < 0 || a >= length)
return;
if (b < 0 || b >= length)
return;
VBase* temp = members[a];
members[a] = members[b];
members[b] = temp;
}
void VGroup::Sort(std::function<bool(VBase*, VBase*)> func)
{
std::sort(members.begin(), members.end(), func);
}
void VGroup::Reverse()
{
std::reverse(members.begin(), members.end());
OrganiseNULLS();
}
void VGroup::Clear()
{
for (int i = 0; i < length; i++)
{
if (members[i] != nullptr)
{
if (members[i]->RefCount > 1)
{
members[i]->RefCount--;
members[i] = nullptr;
}
}
}
length = 0;
members.clear();
members.shrink_to_fit();
}
void VGroup::Destroy()
{
VSUPERCLASS::Destroy();
for (unsigned int i = 0; i < members.size(); i++)
{
if (members[i] != nullptr)
{
if (members[i]->RefCount <= 1)
{
members[i]->Destroy();
delete members[i];
members[i] = nullptr;
}
else
{
members[i]->RefCount--;
members[i] = nullptr;
}
}
}
Clear();
}
void VGroup::Kill()
{
for (unsigned int i = 0; i < members.size(); i++)
{
VBase* base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr && base->exists)
base->Kill();
}
VSUPERCLASS::Kill();
}
void VGroup::Revive()
{
for (unsigned int i = 0; i < members.size(); i++)
{
VBase* base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr && !base->exists)
base->Revive();
}
VSUPERCLASS::Revive();
}
void VGroup::Update(float dt)
{
if (!active)
return;
for (unsigned int i = 0; i < members.size(); i++)
{
VBase* base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr && base->exists && base->active)
{
base->Update(dt);
}
}
}
#include "VRenderGroup.h"
void VGroup::Draw(sf::RenderTarget& RenderTarget)
{
if (!visible)
return;
for (unsigned int i = 0; i < members.size(); i++)
{
VBase* base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr && base->exists && base->visible)
{
base->Draw(RenderTarget);
}
}
#if _DEBUG
if (VGlobal::p()->DrawDebug)
{
int memberLength = members.size();
debuggingVertices.resize(memberLength * 8);
for (unsigned int i = 0; i < members.size(); i++)
{
VObject* object = dynamic_cast<VObject*>(members[i]);
if (object == nullptr && members[i]->type == RENDERGROUP)
{
VRenderGroup* renderGroup = dynamic_cast<VRenderGroup*>(members[i]);
object = renderGroup->Sprite;
}
if (object == nullptr)
continue;
if (object->alive)
{
debuggingVertices[0 + (i * 8)].position = object->Position; debuggingVertices[0 + (i * 8)].color = object->DebugColor;
debuggingVertices[1 + (i * 8)].position = object->Position + sf::Vector2f(object->Size.x, 0); debuggingVertices[1 + (i * 8)].color = object->DebugColor;
debuggingVertices[2 + (i * 8)].position = object->Position + sf::Vector2f(object->Size.x, 0); debuggingVertices[2 + (i * 8)].color = object->DebugColor;
debuggingVertices[3 + (i * 8)].position = object->Position + sf::Vector2f(object->Size.x, object->Size.y); debuggingVertices[3 + (i * 8)].color = object->DebugColor;
debuggingVertices[4 + (i * 8)].position = object->Position + sf::Vector2f(object->Size.x, object->Size.y); debuggingVertices[4 + (i * 8)].color = object->DebugColor;
debuggingVertices[5 + (i * 8)].position = object->Position + sf::Vector2f(0, object->Size.y); debuggingVertices[5 + (i * 8)].color = object->DebugColor;
debuggingVertices[6 + (i * 8)].position = object->Position + sf::Vector2f(0, object->Size.y); debuggingVertices[6 + (i * 8)].color = object->DebugColor;
debuggingVertices[7 + (i * 8)].position = object->Position; debuggingVertices[7 + (i * 8)].color = object->DebugColor;
}
else
{
debuggingVertices[0 + (i * 8)].color = sf::Color::Transparent;
debuggingVertices[1 + (i * 8)].color = sf::Color::Transparent;
debuggingVertices[2 + (i * 8)].color = sf::Color::Transparent;
debuggingVertices[3 + (i * 8)].color = sf::Color::Transparent;
debuggingVertices[4 + (i * 8)].color = sf::Color::Transparent;
debuggingVertices[5 + (i * 8)].color = sf::Color::Transparent;
debuggingVertices[6 + (i * 8)].color = sf::Color::Transparent;
debuggingVertices[7 + (i * 8)].color = sf::Color::Transparent;
}
}
RenderTarget.draw(debuggingVertices);
}
else
{
debuggingVertices.clear();
}
#endif
}<commit_msg>RenderGroup sprite now unique pointer.<commit_after>#include "VGroup.h"
#include "VGlobal.h"
using std::vector;
VBase* VGroup::Add(VBase* object)
{
if (object == nullptr)
{
VLog("Cannot add nullptr to a VGroup");
return nullptr;
}
if (object == this)
{
VLogError("Cannot add itself to it's own list");
return nullptr;
}
if (GetIndexOfItem(object) >= 0)
return nullptr;
if (MaxSize > 0 && length >= static_cast<int>(MaxSize))
{
return object;
}
int index = FirstNULL();
if (index != -1)
{
members[index] = object;
}
else
{
members.push_back(object);
}
object->RefCount++;
length++;
return object;
}
VBase* VGroup::Remove(VBase* object, bool splice)
{
if (members.size() == 0)
return nullptr;
auto pos = GetIndexOfItem(object);
if (pos < 0)
return nullptr;
if (splice)
{
members.erase(members.begin() + pos);
}
else
{
members[pos] = nullptr;
}
object->RefCount--;
length--;
return object;
}
VBase* VGroup::FirstAvailable()
{
for (unsigned int i = 0; i < members.size(); i++)
{
VBase* base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr && !base->exists)
{
return members[i];
}
}
return nullptr;
}
int VGroup::FirstNULL()
{
for (unsigned int i = 0; i < members.size(); i++)
{
VBase* base = dynamic_cast<VBase*>(members[i]);
if (base == nullptr)
{
return i;
}
}
return -1;
}
VBase* VGroup::FirstExisting()
{
for (unsigned int i = 0; i < members.size(); i++)
{
VBase* base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr && base->exists)
{
return members[i];
}
}
return nullptr;
}
VBase* VGroup::FirstAlive()
{
for (unsigned int i = 0; i < members.size(); i++)
{
VBase* base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr && base->exists && base->alive)
{
return members[i];
}
}
return nullptr;
}
VBase* VGroup::FirstDead()
{
for (unsigned int i = 0; i < members.size(); i++)
{
VBase* base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr && !base->alive)
{
return members[i];
}
}
return nullptr;
}
int VGroup::CountAlive()
{
int count = 0;
for (unsigned int i = 0; i < members.size(); i++)
{
VBase* base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr && base->exists && base->alive)
{
count++;
}
}
return count;
}
int VGroup::CountDead()
{
int count = 0;
for (unsigned int i = 0; i < members.size(); i++)
{
VBase* base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr && !base->alive)
{
count++;
}
}
return count;
}
VBase* VGroup::GetRandom(int min, int max)
{
min = min >= 0 ? min : 0;
max = max < (int)members.size() ? max : (int)members.size();
return members[VGlobal::p()->Random->GetInt(max, min)];
}
void VGroup::ForEach(std::function<void(VBase*)> function, bool recursive)
{
VBase* base = nullptr;
for (int i = 0; i < length; i++)
{
base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr)
{
if (recursive)
{
VGroup* group = dynamic_cast<VGroup*>(base);
if (group != nullptr)
{
group->ForEachAlive(function, recursive);
}
}
else
{
function(base);
}
}
}
}
void VGroup::ForEachAlive(std::function<void(VBase*)> function, bool recursive)
{
VBase* base = nullptr;
for (int i = 0; i < length; i++)
{
base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr && base->exists && base->alive)
{
if (recursive)
{
VGroup* group = dynamic_cast<VGroup*>(base);
if (group != nullptr)
{
group->ForEachAlive(function, recursive);
continue;
}
}
function(base);
}
}
}
void VGroup::ForEachDead(std::function<void(VBase*)> function, bool recursive)
{
VBase* base = nullptr;
for (int i = 0; i < length; i++)
{
base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr && !base->alive)
{
if (recursive)
{
VGroup* group = dynamic_cast<VGroup*>(base);
if (group != nullptr)
{
group->ForEachAlive(function, recursive);
}
}
else
{
function(base);
}
}
}
}
void VGroup::ForEachExists(std::function<void(VBase*)> function, bool recursive)
{
VBase* base = nullptr;
for (int i = 0; i < length; i++)
{
base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr && base->exists)
{
if (recursive)
{
VGroup* group = dynamic_cast<VGroup*>(base);
if (group != nullptr)
{
group->ForEachAlive(function, recursive);
}
}
else
{
function(base);
}
}
}
}
VBase* VGroup::GetGroupItem(int index)
{
if (index >= 0 && index < length)
{
return members[index];
}
return nullptr;
}
int VGroup::GetIndexOfItem(VBase* object)
{
auto index = std::find(members.begin(), members.end(), object);
if (index == members.end())
return -1;
return index - members.begin();
}
void VGroup::OrganiseNULLS()
{
for (unsigned int i = 0; i < members.size(); i++)
{
int first = FirstNULL();
if (first == -1)
return;
if (members[i] && first < (int)i)
{
Swap(first, i);
}
}
}
void VGroup::Swap(int a, int b)
{
if (a < 0 || a >= length)
return;
if (b < 0 || b >= length)
return;
VBase* temp = members[a];
members[a] = members[b];
members[b] = temp;
}
void VGroup::Sort(std::function<bool(VBase*, VBase*)> func)
{
std::sort(members.begin(), members.end(), func);
}
void VGroup::Reverse()
{
std::reverse(members.begin(), members.end());
OrganiseNULLS();
}
void VGroup::Clear()
{
for (int i = 0; i < length; i++)
{
if (members[i] != nullptr)
{
if (members[i]->RefCount > 1)
{
members[i]->RefCount--;
members[i] = nullptr;
}
}
}
length = 0;
members.clear();
members.shrink_to_fit();
}
void VGroup::Destroy()
{
VSUPERCLASS::Destroy();
for (unsigned int i = 0; i < members.size(); i++)
{
if (members[i] != nullptr)
{
if (members[i]->RefCount <= 1)
{
members[i]->Destroy();
delete members[i];
members[i] = nullptr;
}
else
{
members[i]->RefCount--;
members[i] = nullptr;
}
}
}
Clear();
}
void VGroup::Kill()
{
for (unsigned int i = 0; i < members.size(); i++)
{
VBase* base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr && base->exists)
base->Kill();
}
VSUPERCLASS::Kill();
}
void VGroup::Revive()
{
for (unsigned int i = 0; i < members.size(); i++)
{
VBase* base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr && !base->exists)
base->Revive();
}
VSUPERCLASS::Revive();
}
void VGroup::Update(float dt)
{
if (!active)
return;
for (unsigned int i = 0; i < members.size(); i++)
{
VBase* base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr && base->exists && base->active)
{
base->Update(dt);
}
}
}
#include "VRenderGroup.h"
void VGroup::Draw(sf::RenderTarget& RenderTarget)
{
if (!visible)
return;
for (unsigned int i = 0; i < members.size(); i++)
{
VBase* base = dynamic_cast<VBase*>(members[i]);
if (base != nullptr && base->exists && base->visible)
{
base->Draw(RenderTarget);
}
}
#if _DEBUG
if (VGlobal::p()->DrawDebug)
{
int memberLength = members.size();
debuggingVertices.resize(memberLength * 8);
for (unsigned int i = 0; i < members.size(); i++)
{
VObject* object = dynamic_cast<VObject*>(members[i]);
if (object == nullptr && members[i]->type == RENDERGROUP)
{
VRenderGroup* renderGroup = dynamic_cast<VRenderGroup*>(members[i]);
object = renderGroup->Sprite.get();
}
if (object == nullptr)
continue;
if (object->alive)
{
debuggingVertices[0 + (i * 8)].position = object->Position; debuggingVertices[0 + (i * 8)].color = object->DebugColor;
debuggingVertices[1 + (i * 8)].position = object->Position + sf::Vector2f(object->Size.x, 0); debuggingVertices[1 + (i * 8)].color = object->DebugColor;
debuggingVertices[2 + (i * 8)].position = object->Position + sf::Vector2f(object->Size.x, 0); debuggingVertices[2 + (i * 8)].color = object->DebugColor;
debuggingVertices[3 + (i * 8)].position = object->Position + sf::Vector2f(object->Size.x, object->Size.y); debuggingVertices[3 + (i * 8)].color = object->DebugColor;
debuggingVertices[4 + (i * 8)].position = object->Position + sf::Vector2f(object->Size.x, object->Size.y); debuggingVertices[4 + (i * 8)].color = object->DebugColor;
debuggingVertices[5 + (i * 8)].position = object->Position + sf::Vector2f(0, object->Size.y); debuggingVertices[5 + (i * 8)].color = object->DebugColor;
debuggingVertices[6 + (i * 8)].position = object->Position + sf::Vector2f(0, object->Size.y); debuggingVertices[6 + (i * 8)].color = object->DebugColor;
debuggingVertices[7 + (i * 8)].position = object->Position; debuggingVertices[7 + (i * 8)].color = object->DebugColor;
}
else
{
debuggingVertices[0 + (i * 8)].color = sf::Color::Transparent;
debuggingVertices[1 + (i * 8)].color = sf::Color::Transparent;
debuggingVertices[2 + (i * 8)].color = sf::Color::Transparent;
debuggingVertices[3 + (i * 8)].color = sf::Color::Transparent;
debuggingVertices[4 + (i * 8)].color = sf::Color::Transparent;
debuggingVertices[5 + (i * 8)].color = sf::Color::Transparent;
debuggingVertices[6 + (i * 8)].color = sf::Color::Transparent;
debuggingVertices[7 + (i * 8)].color = sf::Color::Transparent;
}
}
RenderTarget.draw(debuggingVertices);
}
else
{
debuggingVertices.clear();
}
#endif
}<|endoftext|> |
<commit_before>// Check that --gc-sections does not throw away (or localize) parts of sanitizer
// interface.
// RUN: %clang_asan -m64 %s -Wl,--gc-sections -o %t
// RUN: %clang_asan -m64 %s -DBUILD_SO -fPIC -o %t-so.so -shared
// RUN: %t 2>&1
#ifndef BUILD_SO
#include <assert.h>
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
char path[4096];
snprintf(path, sizeof(path), "%s-so.so", argv[0]);
void *handle = dlopen(path, RTLD_LAZY);
if (!handle) fprintf(stderr, "%s\n", dlerror());
assert(handle != 0);
typedef void (*F)();
F f = (F)dlsym(handle, "call_rtl_from_dso");
printf("%s\n", dlerror());
assert(dlerror() == 0);
f();
dlclose(handle);
return 0;
}
#else // BUILD_SO
#include <sanitizer/msan_interface.h>
extern "C" void call_rtl_from_dso() {
volatile int32_t x;
volatile int32_t y = __sanitizer_unaligned_load32((void *)&x);
}
#endif // BUILD_SO
<commit_msg>Mark this test as 64-bit specific<commit_after>// Check that --gc-sections does not throw away (or localize) parts of sanitizer
// interface.
// RUN: %clang_asan %s -Wl,--gc-sections -o %t
// RUN: %clang_asan %s -DBUILD_SO -fPIC -o %t-so.so -shared
// RUN: %t 2>&1
// REQUIRES: asan-64-bits
#ifndef BUILD_SO
#include <assert.h>
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
char path[4096];
snprintf(path, sizeof(path), "%s-so.so", argv[0]);
void *handle = dlopen(path, RTLD_LAZY);
if (!handle) fprintf(stderr, "%s\n", dlerror());
assert(handle != 0);
typedef void (*F)();
F f = (F)dlsym(handle, "call_rtl_from_dso");
printf("%s\n", dlerror());
assert(dlerror() == 0);
f();
dlclose(handle);
return 0;
}
#else // BUILD_SO
#include <sanitizer/asan_interface.h>
extern "C" void call_rtl_from_dso() {
volatile int32_t x;
volatile int32_t y = __sanitizer_unaligned_load32((void *)&x);
}
#endif // BUILD_SO
<|endoftext|> |
<commit_before>// @(#)root/base:$Name: $:$Id: TVirtualStreamerInfo.cxx,v 1.1 2007/02/05 18:06:25 brun Exp $
// Author: Rene Brun 05/02/2007
/*************************************************************************
* Copyright (C) 1995-2007, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "TROOT.h"
#include "TClass.h"
#include "TVirtualStreamerInfo.h"
#include "TPluginManager.h"
#include "TStreamerElement.h"
TVirtualStreamerInfo *TVirtualStreamerInfo::fgInfoFactory = 0;
Bool_t TVirtualStreamerInfo::fgCanDelete = kTRUE;
Bool_t TVirtualStreamerInfo::fgOptimize = kTRUE;
Bool_t TVirtualStreamerInfo::fgStreamMemberWise = kFALSE;
ClassImp(TVirtualStreamerInfo)
//______________________________________________________________________________
TVirtualStreamerInfo::TVirtualStreamerInfo()
{
// Default constructor.
}
//______________________________________________________________________________
TVirtualStreamerInfo::TVirtualStreamerInfo(TClass *cl)
: TNamed(cl->GetName(),"")
{
// Default constructor.
}
//______________________________________________________________________________
TVirtualStreamerInfo::TVirtualStreamerInfo(const TVirtualStreamerInfo& info)
: TNamed(info)
{
//copy constructor
}
//______________________________________________________________________________
TVirtualStreamerInfo& TVirtualStreamerInfo::operator=(const TVirtualStreamerInfo& info)
{
//assignment operator
if(this!=&info) {
TNamed::operator=(info);
}
return *this;
}
//______________________________________________________________________________
TVirtualStreamerInfo::~TVirtualStreamerInfo()
{
// Destructor
}
//______________________________________________________________________________
Bool_t TVirtualStreamerInfo::CanDelete()
{
// static function returning true if ReadBuffer can delete object
return fgCanDelete;
}
//______________________________________________________________________________
Bool_t TVirtualStreamerInfo::CanOptimize()
{
// static function returning true if optimization can be on
return fgOptimize;
}
//______________________________________________________________________________
TStreamerBasicType *TVirtualStreamerInfo::GetElementCounter(const char *countName, TClass *cl)
{
// Get pointer to a TStreamerBasicType in TClass *cl
//static function
TObjArray *sinfos = cl->GetStreamerInfos();
TVirtualStreamerInfo *info = (TVirtualStreamerInfo *)sinfos->At(cl->GetClassVersion());
if (!info || !info->IsBuilt()) {
// Even if the streamerInfo exist, it could still need to be 'build'
// It is important to figure this out, because
// a) if it is not build, we need to build
// b) if is build, we should not build it (or we could end up in an
// infinite loop, if the element and its counter are in the same
// class!
info = cl->GetStreamerInfo();
}
if (!info) return 0;
TStreamerElement *element = (TStreamerElement *)info->GetElements()->FindObject(countName);
if (!element) return 0;
if (element->IsA() == TStreamerBasicType::Class()) return (TStreamerBasicType*)element;
return 0;
}
//______________________________________________________________________________
Bool_t TVirtualStreamerInfo::GetStreamMemberWise()
{
// Return whether the TStreamerInfos will save the collections in
// "member-wise" order whenever possible. The default is to store member-wise.
// kTRUE indicates member-wise storing
// kFALSE inddicates object-wise storing
//
// A collection can be saved member wise when it contain is guaranteed to be
// homogeneous. For example std::vector<THit> can be stored member wise,
// while std::vector<THit*> can not (possible use of polymorphism).
return fgStreamMemberWise;
}
//______________________________________________________________________________
void TVirtualStreamerInfo::Optimize(Bool_t opt)
{
// This is a static function.
// Set optimization option.
// When this option is activated (default), consecutive data members
// of the same type are merged into an array (faster).
// Optimization must be off in TTree split mode.
fgOptimize = opt;
}
//______________________________________________________________________________
TVirtualStreamerInfo *TVirtualStreamerInfo::Factory(TClass *cl)
{
// Static function returning a pointer to a new TVirtualStreamerInfo object.
// If the Info factory does not exist, it is created via the plugin manager.
// In reality the factory is an empty TStreamerInfo object.
if (!fgInfoFactory) {
TPluginHandler *h;
if ((h = gROOT->GetPluginManager()->FindHandler("TVirtualStreamerInfo","TStreamerInfo"))) {
if (h->LoadPlugin() == -1)
return 0;
fgInfoFactory = (TVirtualStreamerInfo*) h->ExecPlugin(0);
}
}
if (fgInfoFactory) return fgInfoFactory->NewInfo(cl);
return 0;
}
//______________________________________________________________________________
void TVirtualStreamerInfo::SetCanDelete(Bool_t opt)
{
// This is a static function.
// Set object delete option.
// When this option is activated (default), ReadBuffer automatically
// delete objects when a data member is a pointer to an object.
// If your constructor is not presetting pointers to 0, you must
// call this static function TStreamerInfo::SetCanDelete(kFALSE);
fgCanDelete = opt;
}
//______________________________________________________________________________
void TVirtualStreamerInfo::SetFactory(TVirtualStreamerInfo *factory)
{
//static function: Set the StreamerInfo factory
fgInfoFactory = factory;
}
//______________________________________________________________________________
Bool_t TVirtualStreamerInfo::SetStreamMemberWise(Bool_t enable)
{
// Set whether the TStreamerInfos will save the collections in
// "member-wise" order whenever possible. The default is to store member-wise.
// kTRUE indicates member-wise storing
// kFALSE inddicates object-wise storing
// This function returns the previous value of fgStreamMemberWise.
// A collection can be saved member wise when it contain is guaranteed to be
// homogeneous. For example std::vector<THit> can be stored member wise,
// while std::vector<THit*> can not (possible use of polymorphism).
Bool_t prev = fgStreamMemberWise;
fgStreamMemberWise = enable;
return prev;
}
//______________________________________________________________________________
void TVirtualStreamerInfo::Streamer(TBuffer &R__b)
{
// Stream an object of class TVirtualStreamerInfo.
TNamed::Streamer(R__b);
}
<commit_msg>From Axel: Issue a warning message if we can not find the TStreamerInfo plugin. Hence avoiding the case where a foreign class didn't get its TClass object without any error message! [The reason was a missing etc dir]<commit_after>// @(#)root/base:$Name: $:$Id: TVirtualStreamerInfo.cxx,v 1.2 2007/06/15 12:35:04 brun Exp $
// Author: Rene Brun 05/02/2007
/*************************************************************************
* Copyright (C) 1995-2007, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "TROOT.h"
#include "TClass.h"
#include "TVirtualStreamerInfo.h"
#include "TPluginManager.h"
#include "TStreamerElement.h"
TVirtualStreamerInfo *TVirtualStreamerInfo::fgInfoFactory = 0;
Bool_t TVirtualStreamerInfo::fgCanDelete = kTRUE;
Bool_t TVirtualStreamerInfo::fgOptimize = kTRUE;
Bool_t TVirtualStreamerInfo::fgStreamMemberWise = kFALSE;
ClassImp(TVirtualStreamerInfo)
//______________________________________________________________________________
TVirtualStreamerInfo::TVirtualStreamerInfo()
{
// Default constructor.
}
//______________________________________________________________________________
TVirtualStreamerInfo::TVirtualStreamerInfo(TClass *cl)
: TNamed(cl->GetName(),"")
{
// Default constructor.
}
//______________________________________________________________________________
TVirtualStreamerInfo::TVirtualStreamerInfo(const TVirtualStreamerInfo& info)
: TNamed(info)
{
//copy constructor
}
//______________________________________________________________________________
TVirtualStreamerInfo& TVirtualStreamerInfo::operator=(const TVirtualStreamerInfo& info)
{
//assignment operator
if(this!=&info) {
TNamed::operator=(info);
}
return *this;
}
//______________________________________________________________________________
TVirtualStreamerInfo::~TVirtualStreamerInfo()
{
// Destructor
}
//______________________________________________________________________________
Bool_t TVirtualStreamerInfo::CanDelete()
{
// static function returning true if ReadBuffer can delete object
return fgCanDelete;
}
//______________________________________________________________________________
Bool_t TVirtualStreamerInfo::CanOptimize()
{
// static function returning true if optimization can be on
return fgOptimize;
}
//______________________________________________________________________________
TStreamerBasicType *TVirtualStreamerInfo::GetElementCounter(const char *countName, TClass *cl)
{
// Get pointer to a TStreamerBasicType in TClass *cl
//static function
TObjArray *sinfos = cl->GetStreamerInfos();
TVirtualStreamerInfo *info = (TVirtualStreamerInfo *)sinfos->At(cl->GetClassVersion());
if (!info || !info->IsBuilt()) {
// Even if the streamerInfo exist, it could still need to be 'build'
// It is important to figure this out, because
// a) if it is not build, we need to build
// b) if is build, we should not build it (or we could end up in an
// infinite loop, if the element and its counter are in the same
// class!
info = cl->GetStreamerInfo();
}
if (!info) return 0;
TStreamerElement *element = (TStreamerElement *)info->GetElements()->FindObject(countName);
if (!element) return 0;
if (element->IsA() == TStreamerBasicType::Class()) return (TStreamerBasicType*)element;
return 0;
}
//______________________________________________________________________________
Bool_t TVirtualStreamerInfo::GetStreamMemberWise()
{
// Return whether the TStreamerInfos will save the collections in
// "member-wise" order whenever possible. The default is to store member-wise.
// kTRUE indicates member-wise storing
// kFALSE inddicates object-wise storing
//
// A collection can be saved member wise when it contain is guaranteed to be
// homogeneous. For example std::vector<THit> can be stored member wise,
// while std::vector<THit*> can not (possible use of polymorphism).
return fgStreamMemberWise;
}
//______________________________________________________________________________
void TVirtualStreamerInfo::Optimize(Bool_t opt)
{
// This is a static function.
// Set optimization option.
// When this option is activated (default), consecutive data members
// of the same type are merged into an array (faster).
// Optimization must be off in TTree split mode.
fgOptimize = opt;
}
//______________________________________________________________________________
TVirtualStreamerInfo *TVirtualStreamerInfo::Factory(TClass *cl)
{
// Static function returning a pointer to a new TVirtualStreamerInfo object.
// If the Info factory does not exist, it is created via the plugin manager.
// In reality the factory is an empty TStreamerInfo object.
if (!fgInfoFactory) {
TPluginHandler *h;
if ((h = gROOT->GetPluginManager()->FindHandler("TVirtualStreamerInfo","TStreamerInfo"))) {
if (h->LoadPlugin() == -1)
return 0;
fgInfoFactory = (TVirtualStreamerInfo*) h->ExecPlugin(0);
} else {
gROOT->GetPluginManager()->Error("FindHandler",
"Cannot find plugin handler for TVirtualStreamerInfo!"
" Does $ROOTSYS/etc/plugins/TVirtualStreamerInfo exist?");
}
}
if (fgInfoFactory) return fgInfoFactory->NewInfo(cl);
return 0;
}
//______________________________________________________________________________
void TVirtualStreamerInfo::SetCanDelete(Bool_t opt)
{
// This is a static function.
// Set object delete option.
// When this option is activated (default), ReadBuffer automatically
// delete objects when a data member is a pointer to an object.
// If your constructor is not presetting pointers to 0, you must
// call this static function TStreamerInfo::SetCanDelete(kFALSE);
fgCanDelete = opt;
}
//______________________________________________________________________________
void TVirtualStreamerInfo::SetFactory(TVirtualStreamerInfo *factory)
{
//static function: Set the StreamerInfo factory
fgInfoFactory = factory;
}
//______________________________________________________________________________
Bool_t TVirtualStreamerInfo::SetStreamMemberWise(Bool_t enable)
{
// Set whether the TStreamerInfos will save the collections in
// "member-wise" order whenever possible. The default is to store member-wise.
// kTRUE indicates member-wise storing
// kFALSE inddicates object-wise storing
// This function returns the previous value of fgStreamMemberWise.
// A collection can be saved member wise when it contain is guaranteed to be
// homogeneous. For example std::vector<THit> can be stored member wise,
// while std::vector<THit*> can not (possible use of polymorphism).
Bool_t prev = fgStreamMemberWise;
fgStreamMemberWise = enable;
return prev;
}
//______________________________________________________________________________
void TVirtualStreamerInfo::Streamer(TBuffer &R__b)
{
// Stream an object of class TVirtualStreamerInfo.
TNamed::Streamer(R__b);
}
<|endoftext|> |
<commit_before>
#pragma once
#include <cstddef>
#include <giecs/memory/reference.hpp>
#include <giecs/memory/accessor.hpp>
#include <giecs/memory/accessors/linear.hpp>
#include <functional>
#include <boost/type_index.hpp>
namespace giecs
{
namespace memory
{
namespace accessors
{
template <std::size_t page_size, typename align_t, typename addr_t, typename val_t>
class Deque : public Linear<page_size, align_t, addr_t, val_t, val_t*, std::size_t>
{
template <std::size_t, typename, typename, typename> friend class Deque;
public:
using value_type = val_t;
using size_type = std::size_t;
using reference = value_type&;
using const_reference = value_type const&;
Deque(Context<page_size, align_t> const& context_, Reference ref_= {0,0}, addr_t back_ptr_=0, addr_t front_ptr_=0)
: Linear<page_size, align_t, addr_t, val_t, val_t*, std::size_t>::Linear(context_, ref_), back_ptr(back_ptr_), front_ptr(front_ptr_)
{}
template <typename val2_t>
Deque(Deque<page_size, align_t, addr_t, val2_t> const& s, std::ptrdiff_t offset=0, addr_t back_ptr_=0, addr_t front_ptr_=0)
: Linear<page_size, align_t, addr_t, val_t, val_t*, std::size_t>::Linear(s, s.alignOffset(std::ptrdiff_t(s.pos))+offset), back_ptr(back_ptr_), front_ptr(front_ptr_)
{}
std::size_t size(void) const
{
return std::size_t(this->back_ptr - this->front_ptr);
}
bool empty(void) const
{
return (this->size() == 0);
}
val_t const& front(void) const
{
return (*this)[this->front_ptr];
}
val_t& front(void)
{
return (*this)[this->front_ptr];
}
val_t const& back(void) const
{
return (*this)[this->back_ptr-1];
}
val_t& back(void)
{
return (*this)[this->back_ptr-1];
}
void push_front(std::size_t n, val_t const* v)
{
for(std::size_t i=0; i < n; ++i)
this->write(--this->front_ptr, v[i]);
}
void push_back(std::size_t n, val_t const* v)
{
for(std::size_t i=n; i > 0; ++this->back_ptr)
this->write(this->back_ptr, v[--i]);
}
void pop_front(std::size_t n, val_t* v)
{
for(std::size_t i=n; i > 0; ++this->front_ptr)
v[--i] = this->read(this->front_ptr);
}
void pop_back(std::size_t n, val_t* v)
{
for(std::size_t i=0; i < n; ++i)
v[i] = this->read(--this->back_ptr);
}
template <typename val2_t>
void push_front(std::size_t n, val2_t const* val)
{
auto s = Deque<page_size, align_t, addr_t, val2_t>(*this);
s.push_front(n, val);
this->front_ptr += this->diff<val2_t>(-n);
}
template <typename val2_t>
void push_back(std::size_t n, val2_t const* val)
{
auto s = Deque<page_size, align_t, addr_t, val2_t>(*this);
s.push_front(n, val);
this->back_ptr += this->diff<val2_t>(n);
}
template <typename val2_t>
void pop_front(std::size_t n, val2_t* val)
{
auto s = Deque<page_size, align_t, addr_t, val2_t>(*this);
s.pop_front(n, val);
this->front_ptr += this->diff<val2_t>(n);
}
template <typename val2_t>
void pop_back(std::size_t n, val2_t* val)
{
auto s = Deque<page_size, align_t, addr_t, val2_t>(*this);
s.pop_front(n, val);
this->back_ptr += this->diff<val2_t>(-n);
}
template <typename val2_t=val_t>
void push_front(val2_t const& val)
{
this->push_front(1, &val);
}
template <typename val2_t=val_t>
void push_back(val2_t const& val)
{
this->push_back(1, &val);
}
template <typename val2_t=val_t>
val2_t pop_front(void)
{
val2_t val;
this->pop_back(1, &val);
return val;
}
template <typename val2_t=val_t>
val2_t pop_back(void)
{
val2_t val;
this->pop_back(1, &val);
return val;
}
private:
addr_t back_ptr;
addr_t front_ptr;
template <typename val2_t=val_t>
addr_t diff(std::ptrdiff_t off)
{
#define SIGN ((off>0)-(off<0))
std::ptrdiff_t vo = this->valueOffset(Linear<page_size, align_t, addr_t, val2_t>::alignOffset(off-SIGN))+SIGN;
return addr_t(vo);
}
};
} // namespace accessors
} // namespace memory
} // namespace giecs
<commit_msg>deque fixes<commit_after>
#pragma once
#include <cstddef>
#include <giecs/memory/reference.hpp>
#include <giecs/memory/accessor.hpp>
#include <giecs/memory/accessors/linear.hpp>
#include <functional>
#include <boost/type_index.hpp>
namespace giecs
{
namespace memory
{
namespace accessors
{
template <std::size_t page_size, typename align_t, typename addr_t, typename val_t>
class Deque : public Linear<page_size, align_t, addr_t, val_t, val_t*, std::size_t>
{
template <std::size_t, typename, typename, typename> friend class Deque;
public:
using value_type = val_t;
using size_type = std::size_t;
using reference = value_type&;
using const_reference = value_type const&;
Deque(Context<page_size, align_t> const& context_, Reference ref_= {0,0}, addr_t back_ptr_=0, addr_t front_ptr_=0)
: Linear<page_size, align_t, addr_t, val_t, val_t*, std::size_t>::Linear(context_, ref_), back_ptr(back_ptr_), front_ptr(front_ptr_)
{}
template <typename val2_t>
Deque(Deque<page_size, align_t, addr_t, val2_t> const& s, std::ptrdiff_t offset=0, addr_t back_ptr_=0, addr_t front_ptr_=0)
: Linear<page_size, align_t, addr_t, val_t, val_t*, std::size_t>::Linear(s, s.alignOffset(std::ptrdiff_t(s.back_ptr))+offset), back_ptr(back_ptr_), front_ptr(front_ptr_)
{}
std::size_t size(void) const
{
return std::size_t(this->back_ptr - this->front_ptr);
}
bool empty(void) const
{
return (this->size() == 0);
}
val_t const& front(void) const
{
return (*this)[this->front_ptr];
}
val_t& front(void)
{
return (*this)[this->front_ptr];
}
val_t const& back(void) const
{
return (*this)[this->back_ptr-1];
}
val_t& back(void)
{
return (*this)[this->back_ptr-1];
}
void push_front(std::size_t n, val_t const* v)
{
for(std::size_t i=0; i < n; ++i)
this->write(--this->front_ptr, v[i]);
}
void push_back(std::size_t n, val_t const* v)
{
for(std::size_t i=n; i > 0; ++this->back_ptr)
this->write(this->back_ptr, v[--i]);
}
void pop_front(std::size_t n, val_t* v)
{
for(std::size_t i=n; i > 0; ++this->front_ptr)
v[--i] = this->read(this->front_ptr);
}
void pop_back(std::size_t n, val_t* v)
{
for(std::size_t i=0; i < n; ++i)
v[i] = this->read(--this->back_ptr);
}
template <typename val2_t>
void push_front(std::size_t n, val2_t const* val)
{
auto s = Deque<page_size, align_t, addr_t, val2_t>(*this);
s.push_front(n, val);
this->front_ptr += this->diff<val2_t>(-n);
}
template <typename val2_t>
void push_back(std::size_t n, val2_t const* val)
{
auto s = Deque<page_size, align_t, addr_t, val2_t>(*this);
s.push_back(n, val);
this->back_ptr += this->diff<val2_t>(n);
}
template <typename val2_t>
void pop_front(std::size_t n, val2_t* val)
{
auto s = Deque<page_size, align_t, addr_t, val2_t>(*this);
s.pop_front(n, val);
this->front_ptr += this->diff<val2_t>(n);
}
template <typename val2_t>
void pop_back(std::size_t n, val2_t* val)
{
auto s = Deque<page_size, align_t, addr_t, val2_t>(*this);
s.pop_back(n, val);
this->back_ptr += this->diff<val2_t>(-n);
}
template <typename val2_t=val_t>
void push_front(val2_t const& val)
{
this->push_front(1, &val);
}
template <typename val2_t=val_t>
void push_back(val2_t const& val)
{
this->push_back(1, &val);
}
template <typename val2_t=val_t>
val2_t pop_front(void)
{
val2_t val;
this->pop_front(1, &val);
return val;
}
template <typename val2_t=val_t>
val2_t pop_back(void)
{
val2_t val;
this->pop_back(1, &val);
return val;
}
private:
addr_t back_ptr;
addr_t front_ptr;
template <typename val2_t=val_t>
addr_t diff(std::ptrdiff_t off)
{
#define SIGN ((off>0)-(off<0))
std::ptrdiff_t vo = this->valueOffset(Linear<page_size, align_t, addr_t, val2_t>::alignOffset(off-SIGN))+SIGN;
return addr_t(vo);
}
};
} // namespace accessors
} // namespace memory
} // namespace giecs
<|endoftext|> |
<commit_before>// Copyright 2010 Google Inc. All Rights Reserved.
// Author: [email protected] (Aaron Jacobs)
//
// 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 "gjstest/internal/cpp/v8_utils.h"
#include "base/integral_types.h"
#include "base/logging.h"
#include "base/stringprintf.h"
using v8::Array;
using v8::External;
using v8::Function;
using v8::FunctionTemplate;
using v8::Handle;
using v8::Isolate;
using v8::Local;
using v8::Message;
using v8::ObjectTemplate;
using v8::Persistent;
using v8::Script;
using v8::StackFrame;
using v8::StackTrace;
using v8::String;
using v8::TryCatch;
using v8::Value;
namespace gjstest {
static Local<String> ConvertString(const std::string& s) {
return String::New(s.data(), s.size());
}
std::string ConvertToString(const Handle<Value>& value) {
const String::Utf8Value utf8_value(value);
return std::string(*utf8_value, utf8_value.length());
}
void ConvertToStringVector(
const v8::Handle<v8::Value>& value,
std::vector<std::string>* result) {
CHECK(!value.IsEmpty()) << "value must be non-empty";
CHECK(value->IsArray()) << "value must be an array";
Array* array = Array::Cast(*value);
const uint32 length = array->Length();
for (uint32 i = 0; i < length; ++i) {
result->push_back(ConvertToString(array->Get(i)));
}
}
Local<Value> ExecuteJs(
const std::string& js,
const std::string& filename) {
// Attempt to parse the script.
const Local<Script> script =
filename.empty() ?
Script::New(ConvertString(js)) :
Script::New(ConvertString(js), ConvertString(filename));
if (script.IsEmpty()) {
return Local<Value>();
}
// Run the script.
return script->Run();
}
std::string DescribeError(const TryCatch& try_catch) {
const std::string exception = ConvertToString(try_catch.Exception());
const Local<Message> message = try_catch.Message();
// If there's no message, just return the exception.
if (message.IsEmpty()) return exception;
// We want to return a message of the form:
//
// foo.js:7: ReferenceError: blah is not defined.
//
const std::string filename =
ConvertToString(message->GetScriptResourceName());
const int line = message->GetLineNumber();
// Sometimes for multi-line errors there is no line number.
if (!line) {
return StringPrintf("%s: %s", filename.c_str(), exception.c_str());
}
return StringPrintf("%s:%i: %s", filename.c_str(), line, exception.c_str());
}
static void RunAssociatedCallback(
const v8::FunctionCallbackInfo<Value>& cb_info) {
// Unwrap the callback that was associated with this function.
const Local<Value> data = cb_info.Data();
CHECK(data->IsExternal());
const External* external = External::Cast(*data);
V8FunctionCallback* callback =
static_cast<V8FunctionCallback*>(external->Value());
cb_info.GetReturnValue().Set(callback->Run(cb_info));
}
template <typename T, typename C>
static void DeleteCallback(
Isolate* isolate,
Persistent<T>* ref,
C* callback) {
ref->Dispose();
delete callback;
}
void RegisterFunction(
const std::string& name,
V8FunctionCallback* callback,
Handle<ObjectTemplate>* tmpl) {
CHECK(callback->IsRepeatable());
// Wrap up the callback in an External that can be decoded later.
const Local<Value> data = External::New(callback);
// Create a function template with the wrapped callback as associated data,
// and export it.
(*tmpl)->Set(
String::New(name.c_str(), name.size()),
FunctionTemplate::New(RunAssociatedCallback, data));
// Dispose of the callback when the object template goes away.
Persistent<ObjectTemplate> weak_ref(
CHECK_NOTNULL(Isolate::GetCurrent()),
*tmpl);
weak_ref.MakeWeak(
callback,
&DeleteCallback);
}
Local<Function> MakeFunction(
const std::string& name,
V8FunctionCallback* callback) {
CHECK(callback->IsRepeatable());
// Wrap up the callback in an External that can be decoded later.
const Local<Value> data = External::New(callback);
// Create a function template with the wrapped callback as associated data,
// and instantiate it.
const Local<Function> result =
FunctionTemplate::New(RunAssociatedCallback, data)->GetFunction();
result->SetName(String::New(name.data(), name.size()));
// Dispose of the callback when the function is garbage collected.
Persistent<Function> weak_ref(
CHECK_NOTNULL(Isolate::GetCurrent()),
result);
weak_ref.MakeWeak(
callback,
&DeleteCallback);
return result;
}
} // namespace gjstest
<commit_msg>Overcame yet another backwards-incompatible change to v8.<commit_after>// Copyright 2010 Google Inc. All Rights Reserved.
// Author: [email protected] (Aaron Jacobs)
//
// 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 "gjstest/internal/cpp/v8_utils.h"
#include "base/integral_types.h"
#include "base/logging.h"
#include "base/stringprintf.h"
using v8::Array;
using v8::External;
using v8::Function;
using v8::FunctionTemplate;
using v8::Handle;
using v8::Isolate;
using v8::Local;
using v8::Message;
using v8::ObjectTemplate;
using v8::Persistent;
using v8::Script;
using v8::StackFrame;
using v8::StackTrace;
using v8::String;
using v8::TryCatch;
using v8::Value;
namespace gjstest {
static Local<String> ConvertString(const std::string& s) {
return String::NewFromUtf8(
Isolate::GetCurrent(),
s.data(),
String::kNormalString,
s.size());
}
std::string ConvertToString(const Handle<Value>& value) {
const String::Utf8Value utf8_value(value);
return std::string(*utf8_value, utf8_value.length());
}
void ConvertToStringVector(
const v8::Handle<v8::Value>& value,
std::vector<std::string>* result) {
CHECK(!value.IsEmpty()) << "value must be non-empty";
CHECK(value->IsArray()) << "value must be an array";
Array* array = Array::Cast(*value);
const uint32 length = array->Length();
for (uint32 i = 0; i < length; ++i) {
result->push_back(ConvertToString(array->Get(i)));
}
}
Local<Value> ExecuteJs(
const std::string& js,
const std::string& filename) {
// Attempt to parse the script.
const Local<Script> script =
filename.empty() ?
Script::New(ConvertString(js)) :
Script::New(ConvertString(js), ConvertString(filename));
if (script.IsEmpty()) {
return Local<Value>();
}
// Run the script.
return script->Run();
}
std::string DescribeError(const TryCatch& try_catch) {
const std::string exception = ConvertToString(try_catch.Exception());
const Local<Message> message = try_catch.Message();
// If there's no message, just return the exception.
if (message.IsEmpty()) return exception;
// We want to return a message of the form:
//
// foo.js:7: ReferenceError: blah is not defined.
//
const std::string filename =
ConvertToString(message->GetScriptResourceName());
const int line = message->GetLineNumber();
// Sometimes for multi-line errors there is no line number.
if (!line) {
return StringPrintf("%s: %s", filename.c_str(), exception.c_str());
}
return StringPrintf("%s:%i: %s", filename.c_str(), line, exception.c_str());
}
static void RunAssociatedCallback(
const v8::FunctionCallbackInfo<Value>& cb_info) {
// Unwrap the callback that was associated with this function.
const Local<Value> data = cb_info.Data();
CHECK(data->IsExternal());
const External* external = External::Cast(*data);
V8FunctionCallback* callback =
static_cast<V8FunctionCallback*>(external->Value());
cb_info.GetReturnValue().Set(callback->Run(cb_info));
}
template <typename T, typename C>
static void DeleteCallback(
Isolate* isolate,
Persistent<T>* ref,
C* callback) {
ref->Dispose();
delete callback;
}
void RegisterFunction(
const std::string& name,
V8FunctionCallback* callback,
Handle<ObjectTemplate>* tmpl) {
CHECK(callback->IsRepeatable());
// Wrap up the callback in an External that can be decoded later.
const Local<Value> data = External::New(callback);
// Create a function template with the wrapped callback as associated data,
// and export it.
(*tmpl)->Set(
ConvertString(name),
FunctionTemplate::New(RunAssociatedCallback, data));
// Dispose of the callback when the object template goes away.
Persistent<ObjectTemplate> weak_ref(
CHECK_NOTNULL(Isolate::GetCurrent()),
*tmpl);
weak_ref.MakeWeak(
callback,
&DeleteCallback);
}
Local<Function> MakeFunction(
const std::string& name,
V8FunctionCallback* callback) {
CHECK(callback->IsRepeatable());
// Wrap up the callback in an External that can be decoded later.
const Local<Value> data = External::New(callback);
// Create a function template with the wrapped callback as associated data,
// and instantiate it.
const Local<Function> result =
FunctionTemplate::New(RunAssociatedCallback, data)->GetFunction();
result->SetName(ConvertString(name));
// Dispose of the callback when the function is garbage collected.
Persistent<Function> weak_ref(
CHECK_NOTNULL(Isolate::GetCurrent()),
result);
weak_ref.MakeWeak(
callback,
&DeleteCallback);
return result;
}
} // namespace gjstest
<|endoftext|> |
<commit_before>/* GNE - Game Networking Engine, a portable multithreaded networking library.
* Copyright (C) 2001 Jason Winnebeck ([email protected])
* Project website: http://www.rit.edu/~jpw9607/
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef WIN32
//We have a special version of the threading API for Win32
#include "ConditionVariableWin32.inc"
#else
#include "../include/gnelib/gneintern.h"
#include "../include/gnelib/ConditionVariable.h"
#include "../include/gnelib/Mutex.h"
#include "../include/gnelib/Time.h"
#include "../include/gnelib/Timer.h"
namespace GNE {
//##ModelId=3B07538003CD
ConditionVariable::ConditionVariable() {
valassert(pthread_cond_init( &cond, NULL ), 0);
ourMutex = true;
mutex = new Mutex();
}
//##ModelId=3B07538003CE
ConditionVariable::ConditionVariable(Mutex* m) {
valassert(pthread_cond_init( &cond, NULL ), 0);
mutex = m;
ourMutex = false;
}
//##ModelId=3B07538003D0
ConditionVariable::~ConditionVariable() {
valassert(pthread_cond_destroy( &cond ), 0);
if (ourMutex)
delete mutex;
}
//##ModelId=3B0753810000
void ConditionVariable::acquire() {
mutex->acquire();
}
//##ModelId=3B0753810001
void ConditionVariable::release() {
mutex->release();
}
//##ModelId=3B0753810002
void ConditionVariable::wait() {
valassert(pthread_cond_wait(&cond, &mutex->mutex), 0);
}
//##ModelId=3B0753810003
void ConditionVariable::timedWait(int ms) {
Time t = Timer::getAbsoluteTime();
t += ms*1000;
timedWait(t);
}
void ConditionVariable::timedWait(const Time& until) {
timespec tv;
tv.tv_sec = t.getSec();
tv.tv_nsec = t.getuSec() * 1000;
pthread_cond_timedwait(&cond, &(mutex->mutex), &tv);
}
//##ModelId=3B0753810005
void ConditionVariable::signal() {
valassert(pthread_cond_signal( &cond ), 0);
}
//##ModelId=3B0753810006
void ConditionVariable::broadcast() {
valassert(pthread_cond_broadcast( &cond ), 0);
}
}
#endif
<commit_msg>Linux fix.<commit_after>/* GNE - Game Networking Engine, a portable multithreaded networking library.
* Copyright (C) 2001 Jason Winnebeck ([email protected])
* Project website: http://www.rit.edu/~jpw9607/
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef WIN32
//We have a special version of the threading API for Win32
#include "ConditionVariableWin32.inc"
#else
#include "../include/gnelib/gneintern.h"
#include "../include/gnelib/ConditionVariable.h"
#include "../include/gnelib/Mutex.h"
#include "../include/gnelib/Time.h"
#include "../include/gnelib/Timer.h"
namespace GNE {
//##ModelId=3B07538003CD
ConditionVariable::ConditionVariable() {
valassert(pthread_cond_init( &cond, NULL ), 0);
ourMutex = true;
mutex = new Mutex();
}
//##ModelId=3B07538003CE
ConditionVariable::ConditionVariable(Mutex* m) {
valassert(pthread_cond_init( &cond, NULL ), 0);
mutex = m;
ourMutex = false;
}
//##ModelId=3B07538003D0
ConditionVariable::~ConditionVariable() {
valassert(pthread_cond_destroy( &cond ), 0);
if (ourMutex)
delete mutex;
}
//##ModelId=3B0753810000
void ConditionVariable::acquire() {
mutex->acquire();
}
//##ModelId=3B0753810001
void ConditionVariable::release() {
mutex->release();
}
//##ModelId=3B0753810002
void ConditionVariable::wait() {
valassert(pthread_cond_wait(&cond, &mutex->mutex), 0);
}
//##ModelId=3B0753810003
void ConditionVariable::timedWait(int ms) {
Time t = Timer::getAbsoluteTime();
t += ms*1000;
timedWait(t);
}
void ConditionVariable::timedWait(const Time& until) {
timespec tv;
tv.tv_sec = until.getSec();
tv.tv_nsec = until.getuSec() * 1000;
pthread_cond_timedwait(&cond, &(mutex->mutex), &tv);
}
//##ModelId=3B0753810005
void ConditionVariable::signal() {
valassert(pthread_cond_signal( &cond ), 0);
}
//##ModelId=3B0753810006
void ConditionVariable::broadcast() {
valassert(pthread_cond_broadcast( &cond ), 0);
}
}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2017 ASMlover. 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 ofconditions 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 materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <Chaos/Unittest/TestHarness.h>
#include <Chaos/Concurrent/CurrentThread.h>
#include <Chaos/Datetime/Timestamp.h>
#include <iostream>
// void cached_tid(void);
// int get_tid(void); // get tid of current thread
// const char* get_strftid(void); // string format tid
// int get_strftid_length(void); // length of string format tid
// const char* get_name(void); // get name of current thread
// bool is_main_thread(void);
// void sleep_microsec(std::uint64_t microsec);
CHAOS_TEST(CurrentThread, Chaos::FakeTester) {
Chaos::CurrentThread::cached_tid();
std::cout
<< "Chaos::CurrentThread unittest, "
<< "@tid=" << Chaos::CurrentThread::get_tid() << ", "
<< "@tid.string=" << Chaos::CurrentThread::get_strftid() << ", "
<< "@tid.string.len=" << Chaos::CurrentThread::get_strftid_length() << ", "
<< "@name=" << Chaos::CurrentThread::get_name()
<< "@is_main_thread=" << Chaos::CurrentThread::is_main_thread()
<< std::endl;
std::cout
<< "Chaos::CurrentThread unittest, @beg.time="
<< Chaos::get_microsec() << std::endl;
Chaos::CurrentThread::sleep_microsec(100);
std::cout
<< "Chaos::CurrentThread unittest, @end.time="
<< Chaos::get_microsec() << std::endl;
}
<commit_msg>:construction: test(test): updated the unittest for currentthread module<commit_after>// Copyright (c) 2017 ASMlover. 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 ofconditions 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 materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <Chaos/Unittest/TestHarness.h>
#include <Chaos/Concurrent/CurrentThread.h>
#include <Chaos/Datetime/Timestamp.h>
#include <iostream>
CHAOS_TEST(CurrentThread, Chaos::FakeTester) {
Chaos::CurrentThread::cached_tid();
std::cout
<< "Chaos::CurrentThread unittest, "
<< "@tid=" << Chaos::CurrentThread::get_tid() << ", "
<< "@tid.string=" << Chaos::CurrentThread::get_strftid() << ", "
<< "@tid.string.len=" << Chaos::CurrentThread::get_strftid_length() << ", "
<< "@name=" << Chaos::CurrentThread::get_name()
<< "@is_main_thread=" << Chaos::CurrentThread::is_main_thread()
<< std::endl;
auto beg = Chaos::get_microsec();
Chaos::CurrentThread::sleep_microsec(100);
auto end = Chaos::get_microsec();
std::cout
<< "Chaos::CurrentThread unittest, "
<< "@beg.time=" << beg << ", "
<< "@end.time=" << end << ", "
<< "@duration=" << end - beg << std::endl;
}
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if !defined(TESTHARNESS_HEADER_GUARD_1357924680)
#define TESTHARNESS_HEADER_GUARD_1357924680
// Base header file. Must be first.
#include <xalanc/Include/PlatformDefinitions.hpp>
#if defined(XALAN_CLASSIC_IOSTREAMS)
#include <fstream.h>
#else
#include <fstream>
#endif
#include <xalanc/Include/XalanMemoryManagement.hpp>
#include <xalanc/Include/XalanVector.hpp>
#include <xalanc/Include/XalanMap.hpp>
#include <xalanc/PlatformSupport/DOMStringHelper.hpp>
#include <xalanc/XalanDOM/XalanNode.hpp>
#include <xalanc/XalanDOM/XalanDOMString.hpp>
#include <xalanc/Harness/XalanFileUtility.hpp>
#include <xalanc/Harness/XalanXMLFileReporter.hpp>
#include "Utils.hpp"
#include "Logger.hpp"
#include "Timer.hpp"
XALAN_USING_XALAN(XalanMemMgrs)
XALAN_USING_XALAN(XalanVector)
XALAN_USING_XALAN(XalanMap)
XALAN_USING_XALAN(XalanNode)
XALAN_USING_XALAN(XalanDOMString)
XALAN_USING_XALAN(XalanFileUtility)
XALAN_USING_XALAN(XalanXMLFileReporter)
/**
* Processor interface options
*/
struct ProcessorOptions
{
XalanNode* initOptions;
XalanNode* compileOptions;
XalanNode* parseOptions;
XalanNode* resultOptions;
XalanNode* transformOptions;
ProcessorOptions() :
initOptions(0),
compileOptions(0),
parseOptions(0),
resultOptions(0),
transformOptions(0)
{
}
};
/**
* Test case
*/
class TestCase
{
public:
TestCase();
TestCase(const TestCase& theRhs);
XalanDOMString stylesheet;
XalanDOMString inputDocument;
XalanDOMString resultDocument;
XalanDOMString resultDirectory;
XalanDOMString goldResult;
long numIterations;
long minTimeToExecute;
bool verifyResult;
XalanDOMString inputMode;
typedef XalanMap<XalanDOMString, ProcessorOptions> ProcessorOptionsMap;
ProcessorOptionsMap processorOptions;
};
typedef TestCase TestCaseType;
typedef XalanVector<TestCaseType> TestCasesType;
/**
* Test harness
*/
template <class Processor>
class TestHarness
{
public:
typedef typename Processor::CompiledStylesheetType CompiledStylesheetType;
typedef typename Processor::ParsedInputSourceType ParsedInputSourceType;
typedef typename Processor::ResultTargetType ResultTargetType;
typedef typename XalanXMLFileReporter::Hashtable TestAttributesType;
TestHarness();
void init(
XalanFileUtility& fileUtility,
XalanXMLFileReporter& reporter,
Logger& logger);
void terminate();
void executeTestCase(const TestCaseType& testCase);
void executeTestCases(const TestCasesType& testCases);
protected:
Processor m_processor;
XalanFileUtility* m_fileUtility;
XalanXMLFileReporter* m_reporter;
Logger* m_logger;
};
template <class Processor>
void
TestHarness<Processor>::executeTestCases(const TestCasesType& testCases)
{
TestCasesType::const_iterator testCaseIter = testCases.begin();
while (testCaseIter != testCases.end())
{
executeTestCase(*testCaseIter);
++testCaseIter;
}
}
template <class Processor>
void
TestHarness<Processor>::executeTestCase(const TestCaseType& testCase)
{
TestAttributesType testAttributes(XalanMemMgrs::getDefaultXercesMemMgr());
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("stylesheet"), testCase.stylesheet));
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("input-document"), testCase.inputDocument));
try {
CompiledStylesheetType compiledStylesheet;
ParsedInputSourceType parsedInputSource;
ResultTargetType resultTarget;
static const ProcessorOptions defaultProcessor;
TestCase::ProcessorOptionsMap::const_iterator iter = testCase.processorOptions.find(m_processor.getName());
const ProcessorOptions& processor = iter != testCase.processorOptions.end() ? iter->second : defaultProcessor;
m_fileUtility->checkAndCreateDir(testCase.resultDirectory);
Timer timeCompile;
if (testCase.inputMode == XalanDOMString("stream"))
{
#if defined(XALAN_CLASSIC_IOSTREAMS)
XALAN_USING_XALAN(CharVectorType)
XALAN_USING_XALAN(c_str)
XALAN_USING_STD(istringstream)
CharVectorType buffer;
fileToStream(testCase.stylesheet, buffer);
istrstream compilerStream(c_str(buffer));
#else
XALAN_USING_STD(istringstream)
istringstream compilerStream;
fileToStream(testCase.stylesheet, compilerStream);
#endif
timeCompile.start();
compiledStylesheet = m_processor.compileStylesheet(
compilerStream,
processor.compileOptions);
timeCompile.stop();
}
else if (testCase.inputMode == XalanDOMString("file"))
{
timeCompile.start();
compiledStylesheet = m_processor.compileStylesheet(
testCase.stylesheet,
processor.compileOptions);
timeCompile.stop();
}
else
{
XALAN_USING_STD(endl)
m_logger->error()
<< "Mode: "
<< testCase.inputMode.c_str()
<< " is inavlid for stylesheet: "
<< testCase.stylesheet
<< endl;
}
m_reporter->addMetricToAttrs("compile-xsl", timeCompile.getElapsedTime(), testAttributes);
long numIterations = 0;
long totalParseInputTime = 0;
long minParseInputTime = LONG_MAX;
long maxParseInputTime = 0 ;
long totalTransformTime = 0;
long minTransformTime = LONG_MAX;
long maxTransformTime = 0;
Timer timeTotalRun;
timeTotalRun.start();
while (numIterations < testCase.numIterations
&& timeTotalRun.getElapsedTime() < testCase.minTimeToExecute)
{
Timer timeInput;
if (testCase.inputMode == XalanDOMString("stream"))
{
#if defined(XALAN_CLASSIC_IOSTREAMS)
XALAN_USING_XALAN(CharVectorType)
XALAN_USING_XALAN(c_str)
XALAN_USING_STD(istringstream)
CharVectorType buffer;
fileToStream(testCase.inputDocument, buffer);
istrstream inputStream(c_str(buffer));
#else
XALAN_USING_STD(istringstream)
istringstream inputStream;
fileToStream(testCase.inputDocument, inputStream);
#endif
timeInput.start();
parsedInputSource = m_processor.parseInputSource(
inputStream,
processor.parseOptions);
timeInput.stop();
}
else if (testCase.inputMode == XalanDOMString("file"))
{
timeInput.start();
parsedInputSource = m_processor.parseInputSource(
testCase.inputDocument,
processor.parseOptions);
timeInput.stop();
}
else
{
XALAN_USING_STD(endl)
m_logger->error()
<< "Mode: "
<< testCase.inputMode.c_str()
<< " is inavlid for input document: "
<< testCase.inputDocument
<< endl;
}
totalParseInputTime += timeInput.getElapsedTime();
minParseInputTime = timeInput.getElapsedTime() < minParseInputTime ? timeInput.getElapsedTime() : minParseInputTime;
maxParseInputTime = timeInput.getElapsedTime() > maxParseInputTime ? timeInput.getElapsedTime() : maxParseInputTime;
resultTarget = m_processor.createResultTarget(
testCase.resultDocument,
processor.resultOptions);
Timer timeTransform;
timeTransform.start();
m_processor.transform(
compiledStylesheet,
parsedInputSource,
resultTarget);
timeTransform.stop();
totalTransformTime += timeTransform.getElapsedTime();
minTransformTime = timeTransform.getElapsedTime() < minTransformTime ? timeTransform.getElapsedTime() : minTransformTime;
maxTransformTime = timeTransform.getElapsedTime() > maxTransformTime ? timeTransform.getElapsedTime() : maxTransformTime;
++numIterations;
}
timeTotalRun.stop();
m_processor.releaseStylesheet(compiledStylesheet);
m_processor.releaseInputSource(parsedInputSource);
m_processor.releaseResultTarget(resultTarget);
if (true == testCase.verifyResult)
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("verify"), XalanDOMString("yes")));
if (checkFileExists(testCase.resultDocument))
{
if (checkFileExists(testCase.goldResult))
{
if (m_fileUtility->compareSerializedResults(
testCase.resultDocument,
testCase.goldResult))
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("pass")));
}
else
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("fail")));
}
}
else
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("incomplete")));
}
}
else
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("incomplete")));
}
}
else
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("verify"), XalanDOMString("no")));
}
m_reporter->addMetricToAttrs("num-iterations", numIterations, testAttributes);
m_reporter->addMetricToAttrs("elapsed-time", timeTotalRun.getElapsedTime(), testAttributes);
m_reporter->addMetricToAttrs("min-parse-input", minParseInputTime, testAttributes);
m_reporter->addMetricToAttrs("max-parse-input", maxParseInputTime, testAttributes);
m_reporter->addMetricToAttrs("avg-parse-input", totalParseInputTime / numIterations, testAttributes);
m_reporter->addMetricToAttrs("min-transform", minTransformTime, testAttributes);
m_reporter->addMetricToAttrs("max-transform", maxTransformTime, testAttributes);
m_reporter->addMetricToAttrs("avg-transform", totalTransformTime / numIterations, testAttributes);
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("complete"), XalanDOMString("yes")));
}
catch (const XalanDOMString& exception)
{
XALAN_USING_STD(endl)
m_logger->error()
<< "Error encountered during transformation: "
<< testCase.stylesheet.c_str()
<< ", error: "
<< exception.c_str()
<< endl;
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("complete"), XalanDOMString("no")));
}
m_reporter->logElementWAttrs(1, "testcase", testAttributes, "");
}
template <class Processor>
TestHarness<Processor>::TestHarness()
{
}
template <class Processor>
void
TestHarness<Processor>::init(
XalanFileUtility& fileUtility,
XalanXMLFileReporter& reporter,
Logger& logger)
{
m_processor.init();
m_fileUtility = &fileUtility;
m_reporter = &reporter;
m_logger = &logger;
}
template <class Processor>
void
TestHarness<Processor>::terminate()
{
m_processor.terminate();
}
#endif // TESTHARNESS_HEADER_GUARD_1357924680
<commit_msg>Fixed typo.<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if !defined(TESTHARNESS_HEADER_GUARD_1357924680)
#define TESTHARNESS_HEADER_GUARD_1357924680
// Base header file. Must be first.
#include <xalanc/Include/PlatformDefinitions.hpp>
#if defined(XALAN_CLASSIC_IOSTREAMS)
#include <fstream.h>
#else
#include <fstream>
#endif
#include <xalanc/Include/XalanMemoryManagement.hpp>
#include <xalanc/Include/XalanVector.hpp>
#include <xalanc/Include/XalanMap.hpp>
#include <xalanc/PlatformSupport/DOMStringHelper.hpp>
#include <xalanc/XalanDOM/XalanNode.hpp>
#include <xalanc/XalanDOM/XalanDOMString.hpp>
#include <xalanc/Harness/XalanFileUtility.hpp>
#include <xalanc/Harness/XalanXMLFileReporter.hpp>
#include "Utils.hpp"
#include "Logger.hpp"
#include "Timer.hpp"
XALAN_USING_XALAN(XalanMemMgrs)
XALAN_USING_XALAN(XalanVector)
XALAN_USING_XALAN(XalanMap)
XALAN_USING_XALAN(XalanNode)
XALAN_USING_XALAN(XalanDOMString)
XALAN_USING_XALAN(XalanFileUtility)
XALAN_USING_XALAN(XalanXMLFileReporter)
/**
* Processor interface options
*/
struct ProcessorOptions
{
XalanNode* initOptions;
XalanNode* compileOptions;
XalanNode* parseOptions;
XalanNode* resultOptions;
XalanNode* transformOptions;
ProcessorOptions() :
initOptions(0),
compileOptions(0),
parseOptions(0),
resultOptions(0),
transformOptions(0)
{
}
};
/**
* Test case
*/
class TestCase
{
public:
TestCase();
TestCase(const TestCase& theRhs);
XalanDOMString stylesheet;
XalanDOMString inputDocument;
XalanDOMString resultDocument;
XalanDOMString resultDirectory;
XalanDOMString goldResult;
long numIterations;
long minTimeToExecute;
bool verifyResult;
XalanDOMString inputMode;
typedef XalanMap<XalanDOMString, ProcessorOptions> ProcessorOptionsMap;
ProcessorOptionsMap processorOptions;
};
typedef TestCase TestCaseType;
typedef XalanVector<TestCaseType> TestCasesType;
/**
* Test harness
*/
template <class Processor>
class TestHarness
{
public:
typedef typename Processor::CompiledStylesheetType CompiledStylesheetType;
typedef typename Processor::ParsedInputSourceType ParsedInputSourceType;
typedef typename Processor::ResultTargetType ResultTargetType;
typedef typename XalanXMLFileReporter::Hashtable TestAttributesType;
TestHarness();
void init(
XalanFileUtility& fileUtility,
XalanXMLFileReporter& reporter,
Logger& logger);
void terminate();
void executeTestCase(const TestCaseType& testCase);
void executeTestCases(const TestCasesType& testCases);
protected:
Processor m_processor;
XalanFileUtility* m_fileUtility;
XalanXMLFileReporter* m_reporter;
Logger* m_logger;
};
template <class Processor>
void
TestHarness<Processor>::executeTestCases(const TestCasesType& testCases)
{
TestCasesType::const_iterator testCaseIter = testCases.begin();
while (testCaseIter != testCases.end())
{
executeTestCase(*testCaseIter);
++testCaseIter;
}
}
template <class Processor>
void
TestHarness<Processor>::executeTestCase(const TestCaseType& testCase)
{
TestAttributesType testAttributes(XalanMemMgrs::getDefaultXercesMemMgr());
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("stylesheet"), testCase.stylesheet));
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("input-document"), testCase.inputDocument));
try {
CompiledStylesheetType compiledStylesheet;
ParsedInputSourceType parsedInputSource;
ResultTargetType resultTarget;
static const ProcessorOptions defaultProcessor;
TestCase::ProcessorOptionsMap::const_iterator iter = testCase.processorOptions.find(m_processor.getName());
const ProcessorOptions& processor = iter != testCase.processorOptions.end() ? iter->second : defaultProcessor;
m_fileUtility->checkAndCreateDir(testCase.resultDirectory);
Timer timeCompile;
if (testCase.inputMode == XalanDOMString("stream"))
{
#if defined(XALAN_CLASSIC_IOSTREAMS)
XALAN_USING_XALAN(CharVectorType)
XALAN_USING_XALAN(c_str)
XALAN_USING_STD(istringstream)
CharVectorType buffer;
fileToStream(testCase.stylesheet, buffer);
istrstream compilerStream(c_str(buffer));
#else
XALAN_USING_STD(istringstream)
istringstream compilerStream;
fileToStream(testCase.stylesheet, compilerStream);
#endif
timeCompile.start();
compiledStylesheet = m_processor.compileStylesheet(
compilerStream,
processor.compileOptions);
timeCompile.stop();
}
else if (testCase.inputMode == XalanDOMString("file"))
{
timeCompile.start();
compiledStylesheet = m_processor.compileStylesheet(
testCase.stylesheet,
processor.compileOptions);
timeCompile.stop();
}
else
{
XALAN_USING_STD(endl)
m_logger->error()
<< "Mode: "
<< testCase.inputMode.c_str()
<< " is invalid for stylesheet: "
<< testCase.stylesheet
<< endl;
}
m_reporter->addMetricToAttrs("compile-xsl", timeCompile.getElapsedTime(), testAttributes);
long numIterations = 0;
long totalParseInputTime = 0;
long minParseInputTime = LONG_MAX;
long maxParseInputTime = 0 ;
long totalTransformTime = 0;
long minTransformTime = LONG_MAX;
long maxTransformTime = 0;
Timer timeTotalRun;
timeTotalRun.start();
while (numIterations < testCase.numIterations
&& timeTotalRun.getElapsedTime() < testCase.minTimeToExecute)
{
Timer timeInput;
if (testCase.inputMode == XalanDOMString("stream"))
{
#if defined(XALAN_CLASSIC_IOSTREAMS)
XALAN_USING_XALAN(CharVectorType)
XALAN_USING_XALAN(c_str)
XALAN_USING_STD(istringstream)
CharVectorType buffer;
fileToStream(testCase.inputDocument, buffer);
istrstream inputStream(c_str(buffer));
#else
XALAN_USING_STD(istringstream)
istringstream inputStream;
fileToStream(testCase.inputDocument, inputStream);
#endif
timeInput.start();
parsedInputSource = m_processor.parseInputSource(
inputStream,
processor.parseOptions);
timeInput.stop();
}
else if (testCase.inputMode == XalanDOMString("file"))
{
timeInput.start();
parsedInputSource = m_processor.parseInputSource(
testCase.inputDocument,
processor.parseOptions);
timeInput.stop();
}
else
{
XALAN_USING_STD(endl)
m_logger->error()
<< "Mode: "
<< testCase.inputMode.c_str()
<< " is inavlid for input document: "
<< testCase.inputDocument
<< endl;
}
totalParseInputTime += timeInput.getElapsedTime();
minParseInputTime = timeInput.getElapsedTime() < minParseInputTime ? timeInput.getElapsedTime() : minParseInputTime;
maxParseInputTime = timeInput.getElapsedTime() > maxParseInputTime ? timeInput.getElapsedTime() : maxParseInputTime;
resultTarget = m_processor.createResultTarget(
testCase.resultDocument,
processor.resultOptions);
Timer timeTransform;
timeTransform.start();
m_processor.transform(
compiledStylesheet,
parsedInputSource,
resultTarget);
timeTransform.stop();
totalTransformTime += timeTransform.getElapsedTime();
minTransformTime = timeTransform.getElapsedTime() < minTransformTime ? timeTransform.getElapsedTime() : minTransformTime;
maxTransformTime = timeTransform.getElapsedTime() > maxTransformTime ? timeTransform.getElapsedTime() : maxTransformTime;
++numIterations;
}
timeTotalRun.stop();
m_processor.releaseStylesheet(compiledStylesheet);
m_processor.releaseInputSource(parsedInputSource);
m_processor.releaseResultTarget(resultTarget);
if (true == testCase.verifyResult)
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("verify"), XalanDOMString("yes")));
if (checkFileExists(testCase.resultDocument))
{
if (checkFileExists(testCase.goldResult))
{
if (m_fileUtility->compareSerializedResults(
testCase.resultDocument,
testCase.goldResult))
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("pass")));
}
else
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("fail")));
}
}
else
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("incomplete")));
}
}
else
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("incomplete")));
}
}
else
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("verify"), XalanDOMString("no")));
}
m_reporter->addMetricToAttrs("num-iterations", numIterations, testAttributes);
m_reporter->addMetricToAttrs("elapsed-time", timeTotalRun.getElapsedTime(), testAttributes);
m_reporter->addMetricToAttrs("min-parse-input", minParseInputTime, testAttributes);
m_reporter->addMetricToAttrs("max-parse-input", maxParseInputTime, testAttributes);
m_reporter->addMetricToAttrs("avg-parse-input", totalParseInputTime / numIterations, testAttributes);
m_reporter->addMetricToAttrs("min-transform", minTransformTime, testAttributes);
m_reporter->addMetricToAttrs("max-transform", maxTransformTime, testAttributes);
m_reporter->addMetricToAttrs("avg-transform", totalTransformTime / numIterations, testAttributes);
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("complete"), XalanDOMString("yes")));
}
catch (const XalanDOMString& exception)
{
XALAN_USING_STD(endl)
m_logger->error()
<< "Error encountered during transformation: "
<< testCase.stylesheet.c_str()
<< ", error: "
<< exception.c_str()
<< endl;
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("complete"), XalanDOMString("no")));
}
m_reporter->logElementWAttrs(1, "testcase", testAttributes, "");
}
template <class Processor>
TestHarness<Processor>::TestHarness()
{
}
template <class Processor>
void
TestHarness<Processor>::init(
XalanFileUtility& fileUtility,
XalanXMLFileReporter& reporter,
Logger& logger)
{
m_processor.init();
m_fileUtility = &fileUtility;
m_reporter = &reporter;
m_logger = &logger;
}
template <class Processor>
void
TestHarness<Processor>::terminate()
{
m_processor.terminate();
}
#endif // TESTHARNESS_HEADER_GUARD_1357924680
<|endoftext|> |
<commit_before>// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#include "../precomp.hpp"
#include "opencv_data_config.hpp"
#include <vector>
#include <fstream>
#include <opencv2/core/utils/logger.defines.hpp>
#undef CV_LOG_STRIP_LEVEL
#define CV_LOG_STRIP_LEVEL CV_LOG_LEVEL_VERBOSE + 1
#include "opencv2/core/utils/logger.hpp"
#include "opencv2/core/utils/filesystem.hpp"
#include <opencv2/core/utils/configuration.private.hpp>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#undef small
#undef min
#undef max
#undef abs
#elif defined(__APPLE__)
#include <TargetConditionals.h>
#if TARGET_OS_MAC
#include <dlfcn.h>
#endif
#endif
namespace cv { namespace utils {
static cv::Ptr< std::vector<cv::String> > g_data_search_path;
static cv::Ptr< std::vector<cv::String> > g_data_search_subdir;
static std::vector<cv::String>& _getDataSearchPath()
{
if (g_data_search_path.empty())
g_data_search_path.reset(new std::vector<cv::String>());
return *(g_data_search_path.get());
}
static std::vector<cv::String>& _getDataSearchSubDirectory()
{
if (g_data_search_subdir.empty())
{
g_data_search_subdir.reset(new std::vector<cv::String>());
g_data_search_subdir->push_back("data");
g_data_search_subdir->push_back("");
}
return *(g_data_search_subdir.get());
}
CV_EXPORTS void addDataSearchPath(const cv::String& path)
{
if (utils::fs::isDirectory(path))
_getDataSearchPath().push_back(path);
}
CV_EXPORTS void addDataSearchSubDirectory(const cv::String& subdir)
{
_getDataSearchSubDirectory().push_back(subdir);
}
static bool isPathSep(char c)
{
return c == '/' || c == '\\';
}
static bool isSubDirectory_(const cv::String& base_path, const cv::String& path)
{
size_t N = base_path.size();
if (N == 0)
return false;
if (isPathSep(base_path[N - 1]))
N--;
if (path.size() < N)
return false;
for (size_t i = 0; i < N; i++)
{
if (path[i] == base_path[i])
continue;
if (isPathSep(path[i]) && isPathSep(base_path[i]))
continue;
return false;
}
size_t M = path.size();
if (M > N)
{
if (!isPathSep(path[N]))
return false;
}
return true;
}
static bool isSubDirectory(const cv::String& base_path, const cv::String& path)
{
bool res = isSubDirectory_(base_path, path);
CV_LOG_VERBOSE(NULL, 0, "isSubDirectory(): base: " << base_path << " path: " << path << " => result: " << (res ? "TRUE" : "FALSE"));
return res;
}
static cv::String getModuleLocation(const void* addr)
{
CV_UNUSED(addr);
#ifdef _WIN32
HMODULE m = 0;
#if _WIN32_WINNT >= 0x0501
::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
reinterpret_cast<LPCTSTR>(addr),
&m);
#endif
if (m)
{
char path[MAX_PATH];
const size_t path_size = sizeof(path)/sizeof(*path);
size_t sz = GetModuleFileNameA(m, path, path_size); // no unicode support
if (sz > 0 && sz < path_size)
{
path[sz] = '\0';
return cv::String(path);
}
}
#elif defined(__linux__)
std::ifstream fs("/proc/self/maps");
std::string line;
while (std::getline(fs, line, '\n'))
{
long long int addr_begin = 0, addr_end = 0;
if (2 == sscanf(line.c_str(), "%llx-%llx", &addr_begin, &addr_end))
{
if ((intptr_t)addr >= (intptr_t)addr_begin && (intptr_t)addr < (intptr_t)addr_end)
{
size_t pos = line.rfind(" "); // 2 spaces
if (pos == cv::String::npos)
pos = line.rfind(' '); // 1 spaces
else
pos++;
if (pos == cv::String::npos)
{
CV_LOG_DEBUG(NULL, "Can't parse module path: '" << line << '\'');
}
return line.substr(pos + 1);
}
}
}
#elif defined(__APPLE__)
# if TARGET_OS_MAC
Dl_info info;
if (0 != dladdr(addr, &info))
{
return cv::String(info.dli_fname);
}
# endif
#else
// not supported, skip
#endif
return cv::String();
}
cv::String findDataFile(const cv::String& relative_path,
const char* configuration_parameter,
const std::vector<String>* search_paths,
const std::vector<String>* subdir_paths)
{
configuration_parameter = configuration_parameter ? configuration_parameter : "OPENCV_DATA_PATH";
CV_LOG_DEBUG(NULL, cv::format("utils::findDataFile('%s', %s)", relative_path.c_str(), configuration_parameter));
#define TRY_FILE_WITH_PREFIX(prefix) \
{ \
cv::String path = utils::fs::join(prefix, relative_path); \
CV_LOG_DEBUG(NULL, cv::format("... Line %d: trying open '%s'", __LINE__, path.c_str())); \
FILE* f = fopen(path.c_str(), "rb"); \
if(f) { \
fclose(f); \
return path; \
} \
}
// Step 0: check current directory or absolute path at first
TRY_FILE_WITH_PREFIX("");
// Step 1
const std::vector<cv::String>& search_path = search_paths ? *search_paths : _getDataSearchPath();
for(size_t i = search_path.size(); i > 0; i--)
{
const cv::String& prefix = search_path[i - 1];
TRY_FILE_WITH_PREFIX(prefix);
}
const std::vector<cv::String>& search_subdir = subdir_paths ? *subdir_paths : _getDataSearchSubDirectory();
// Step 2
const cv::String configuration_parameter_s(configuration_parameter ? configuration_parameter : "");
const cv::utils::Paths& search_hint = configuration_parameter_s.empty() ? cv::utils::Paths()
: getConfigurationParameterPaths((configuration_parameter_s + "_HINT").c_str());
for (size_t k = 0; k < search_hint.size(); k++)
{
cv::String datapath = search_hint[k];
if (datapath.empty())
continue;
if (utils::fs::isDirectory(datapath))
{
CV_LOG_DEBUG(NULL, "utils::findDataFile(): trying " << configuration_parameter << "_HINT=" << datapath);
for(size_t i = search_subdir.size(); i > 0; i--)
{
const cv::String& subdir = search_subdir[i - 1];
cv::String prefix = utils::fs::join(datapath, subdir);
TRY_FILE_WITH_PREFIX(prefix);
}
}
else
{
CV_LOG_WARNING(NULL, configuration_parameter << "_HINT is specified but it is not a directory: " << datapath);
}
}
// Step 3
const cv::utils::Paths& override_paths = configuration_parameter_s.empty() ? cv::utils::Paths()
: getConfigurationParameterPaths(configuration_parameter);
for (size_t k = 0; k < override_paths.size(); k++)
{
cv::String datapath = override_paths[k];
if (datapath.empty())
continue;
if (utils::fs::isDirectory(datapath))
{
CV_LOG_DEBUG(NULL, "utils::findDataFile(): trying " << configuration_parameter << "=" << datapath);
for(size_t i = search_subdir.size(); i > 0; i--)
{
const cv::String& subdir = search_subdir[i - 1];
cv::String prefix = utils::fs::join(datapath, subdir);
TRY_FILE_WITH_PREFIX(prefix);
}
}
else
{
CV_LOG_WARNING(NULL, configuration_parameter << " is specified but it is not a directory: " << datapath);
}
}
if (!override_paths.empty())
{
CV_LOG_INFO(NULL, "utils::findDataFile(): can't find data file via " << configuration_parameter << " configuration override: " << relative_path);
return cv::String();
}
// Steps: 4, 5, 6
cv::String cwd = utils::fs::getcwd();
cv::String build_dir(OPENCV_BUILD_DIR);
bool has_tested_build_directory = false;
if (isSubDirectory(build_dir, cwd) || isSubDirectory(utils::fs::canonical(build_dir), utils::fs::canonical(cwd)))
{
CV_LOG_DEBUG(NULL, "utils::findDataFile(): the current directory is build sub-directory: " << cwd);
const char* build_subdirs[] = { OPENCV_DATA_BUILD_DIR_SEARCH_PATHS };
for (size_t k = 0; k < sizeof(build_subdirs)/sizeof(build_subdirs[0]); k++)
{
CV_LOG_DEBUG(NULL, "utils::findDataFile(): <build>/" << build_subdirs[k]);
cv::String datapath = utils::fs::join(build_dir, build_subdirs[k]);
if (utils::fs::isDirectory(datapath))
{
for(size_t i = search_subdir.size(); i > 0; i--)
{
const cv::String& subdir = search_subdir[i - 1];
cv::String prefix = utils::fs::join(datapath, subdir);
TRY_FILE_WITH_PREFIX(prefix);
}
}
}
has_tested_build_directory = true;
}
cv::String source_dir;
cv::String try_source_dir = cwd;
for (int levels = 0; levels < 3; ++levels)
{
if (utils::fs::exists(utils::fs::join(try_source_dir, "modules/core/include/opencv2/core/version.hpp")))
{
source_dir = try_source_dir;
break;
}
try_source_dir = utils::fs::join(try_source_dir, "/..");
}
if (!source_dir.empty())
{
CV_LOG_DEBUG(NULL, "utils::findDataFile(): the current directory is source sub-directory: " << source_dir);
CV_LOG_DEBUG(NULL, "utils::findDataFile(): <source>" << source_dir);
cv::String datapath = source_dir;
if (utils::fs::isDirectory(datapath))
{
for(size_t i = search_subdir.size(); i > 0; i--)
{
const cv::String& subdir = search_subdir[i - 1];
cv::String prefix = utils::fs::join(datapath, subdir);
TRY_FILE_WITH_PREFIX(prefix);
}
}
}
cv::String module_path = getModuleLocation((void*)getModuleLocation); // use code addr, doesn't work with static linkage!
CV_LOG_DEBUG(NULL, "Detected module path: '" << module_path << '\'');
if (!has_tested_build_directory &&
(isSubDirectory(build_dir, module_path) || isSubDirectory(utils::fs::canonical(build_dir), utils::fs::canonical(module_path)))
)
{
CV_LOG_DEBUG(NULL, "utils::findDataFile(): the binary module directory is build sub-directory: " << module_path);
const char* build_subdirs[] = { OPENCV_DATA_BUILD_DIR_SEARCH_PATHS };
for (size_t k = 0; k < sizeof(build_subdirs)/sizeof(build_subdirs[0]); k++)
{
CV_LOG_DEBUG(NULL, "utils::findDataFile(): <build>/" << build_subdirs[k]);
cv::String datapath = utils::fs::join(build_dir, build_subdirs[k]);
if (utils::fs::isDirectory(datapath))
{
for(size_t i = search_subdir.size(); i > 0; i--)
{
const cv::String& subdir = search_subdir[i - 1];
cv::String prefix = utils::fs::join(datapath, subdir);
TRY_FILE_WITH_PREFIX(prefix);
}
}
}
}
#if defined OPENCV_INSTALL_DATA_DIR_RELATIVE
if (!module_path.empty()) // require module path
{
size_t pos = module_path.rfind('/');
if (pos == cv::String::npos)
pos = module_path.rfind('\\');
cv::String module_dir = (pos == cv::String::npos) ? module_path : module_path.substr(0, pos);
const char* install_subdirs[] = { OPENCV_INSTALL_DATA_DIR_RELATIVE };
for (size_t k = 0; k < sizeof(install_subdirs)/sizeof(install_subdirs[0]); k++)
{
cv::String datapath = utils::fs::join(module_dir, install_subdirs[k]);
CV_LOG_DEBUG(NULL, "utils::findDataFile(): trying install path (from binary path): " << datapath);
if (utils::fs::isDirectory(datapath))
{
for(size_t i = search_subdir.size(); i > 0; i--)
{
const cv::String& subdir = search_subdir[i - 1];
cv::String prefix = utils::fs::join(datapath, subdir);
TRY_FILE_WITH_PREFIX(prefix);
}
}
else
{
CV_LOG_DEBUG(NULL, "utils::findDataFile(): ... skip, not a valid directory: " << datapath);
}
}
}
#endif
#if defined OPENCV_INSTALL_PREFIX && defined OPENCV_DATA_INSTALL_PATH
cv::String install_dir(OPENCV_INSTALL_PREFIX);
// use core/world module path and verify that library is running from installation directory
// It is neccessary to avoid touching of unrelated common /usr/local path
if (module_path.empty()) // can't determine
module_path = install_dir;
if (isSubDirectory(install_dir, module_path) || isSubDirectory(utils::fs::canonical(install_dir), utils::fs::canonical(module_path)))
{
cv::String datapath = utils::fs::join(install_dir, OPENCV_DATA_INSTALL_PATH);
if (utils::fs::isDirectory(datapath))
{
CV_LOG_DEBUG(NULL, "utils::findDataFile(): trying install path: " << datapath);
for(size_t i = search_subdir.size(); i > 0; i--)
{
const cv::String& subdir = search_subdir[i - 1];
cv::String prefix = utils::fs::join(datapath, subdir);
TRY_FILE_WITH_PREFIX(prefix);
}
}
}
#endif
return cv::String(); // not found
}
cv::String findDataFile(const cv::String& relative_path, bool required, const char* configuration_parameter)
{
CV_LOG_DEBUG(NULL, cv::format("cv::utils::findDataFile('%s', %s, %s)",
relative_path.c_str(), required ? "true" : "false",
configuration_parameter ? configuration_parameter : "NULL"));
cv::String result = cv::utils::findDataFile(relative_path,
configuration_parameter,
NULL,
NULL);
if (result.empty() && required)
CV_Error(cv::Error::StsError, cv::format("OpenCV: Can't find required data file: %s", relative_path.c_str()));
return result;
}
}} // namespace
<commit_msg>core: use dladdr() instead of parsing /proc/self/maps<commit_after>// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#include "../precomp.hpp"
#include "opencv_data_config.hpp"
#include <vector>
#include <fstream>
#include <opencv2/core/utils/logger.defines.hpp>
#undef CV_LOG_STRIP_LEVEL
#define CV_LOG_STRIP_LEVEL CV_LOG_LEVEL_VERBOSE + 1
#include "opencv2/core/utils/logger.hpp"
#include "opencv2/core/utils/filesystem.hpp"
#include <opencv2/core/utils/configuration.private.hpp>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#undef small
#undef min
#undef max
#undef abs
#elif defined(__linux__)
#include <dlfcn.h> // requires -ldl
#elif defined(__APPLE__)
#include <TargetConditionals.h>
#if TARGET_OS_MAC
#include <dlfcn.h>
#endif
#endif
namespace cv { namespace utils {
static cv::Ptr< std::vector<cv::String> > g_data_search_path;
static cv::Ptr< std::vector<cv::String> > g_data_search_subdir;
static std::vector<cv::String>& _getDataSearchPath()
{
if (g_data_search_path.empty())
g_data_search_path.reset(new std::vector<cv::String>());
return *(g_data_search_path.get());
}
static std::vector<cv::String>& _getDataSearchSubDirectory()
{
if (g_data_search_subdir.empty())
{
g_data_search_subdir.reset(new std::vector<cv::String>());
g_data_search_subdir->push_back("data");
g_data_search_subdir->push_back("");
}
return *(g_data_search_subdir.get());
}
CV_EXPORTS void addDataSearchPath(const cv::String& path)
{
if (utils::fs::isDirectory(path))
_getDataSearchPath().push_back(path);
}
CV_EXPORTS void addDataSearchSubDirectory(const cv::String& subdir)
{
_getDataSearchSubDirectory().push_back(subdir);
}
static bool isPathSep(char c)
{
return c == '/' || c == '\\';
}
static bool isSubDirectory_(const cv::String& base_path, const cv::String& path)
{
size_t N = base_path.size();
if (N == 0)
return false;
if (isPathSep(base_path[N - 1]))
N--;
if (path.size() < N)
return false;
for (size_t i = 0; i < N; i++)
{
if (path[i] == base_path[i])
continue;
if (isPathSep(path[i]) && isPathSep(base_path[i]))
continue;
return false;
}
size_t M = path.size();
if (M > N)
{
if (!isPathSep(path[N]))
return false;
}
return true;
}
static bool isSubDirectory(const cv::String& base_path, const cv::String& path)
{
bool res = isSubDirectory_(base_path, path);
CV_LOG_VERBOSE(NULL, 0, "isSubDirectory(): base: " << base_path << " path: " << path << " => result: " << (res ? "TRUE" : "FALSE"));
return res;
}
static cv::String getModuleLocation(const void* addr)
{
CV_UNUSED(addr);
#ifdef _WIN32
HMODULE m = 0;
#if _WIN32_WINNT >= 0x0501
::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
reinterpret_cast<LPCTSTR>(addr),
&m);
#endif
if (m)
{
char path[MAX_PATH];
const size_t path_size = sizeof(path)/sizeof(*path);
size_t sz = GetModuleFileNameA(m, path, path_size); // no unicode support
if (sz > 0 && sz < path_size)
{
path[sz] = '\0';
return cv::String(path);
}
}
#elif defined(__linux__)
Dl_info info;
if (0 != dladdr(addr, &info))
{
return cv::String(info.dli_fname);
}
#elif defined(__APPLE__)
# if TARGET_OS_MAC
Dl_info info;
if (0 != dladdr(addr, &info))
{
return cv::String(info.dli_fname);
}
# endif
#else
// not supported, skip
#endif
return cv::String();
}
cv::String findDataFile(const cv::String& relative_path,
const char* configuration_parameter,
const std::vector<String>* search_paths,
const std::vector<String>* subdir_paths)
{
configuration_parameter = configuration_parameter ? configuration_parameter : "OPENCV_DATA_PATH";
CV_LOG_DEBUG(NULL, cv::format("utils::findDataFile('%s', %s)", relative_path.c_str(), configuration_parameter));
#define TRY_FILE_WITH_PREFIX(prefix) \
{ \
cv::String path = utils::fs::join(prefix, relative_path); \
CV_LOG_DEBUG(NULL, cv::format("... Line %d: trying open '%s'", __LINE__, path.c_str())); \
FILE* f = fopen(path.c_str(), "rb"); \
if(f) { \
fclose(f); \
return path; \
} \
}
// Step 0: check current directory or absolute path at first
TRY_FILE_WITH_PREFIX("");
// Step 1
const std::vector<cv::String>& search_path = search_paths ? *search_paths : _getDataSearchPath();
for(size_t i = search_path.size(); i > 0; i--)
{
const cv::String& prefix = search_path[i - 1];
TRY_FILE_WITH_PREFIX(prefix);
}
const std::vector<cv::String>& search_subdir = subdir_paths ? *subdir_paths : _getDataSearchSubDirectory();
// Step 2
const cv::String configuration_parameter_s(configuration_parameter ? configuration_parameter : "");
const cv::utils::Paths& search_hint = configuration_parameter_s.empty() ? cv::utils::Paths()
: getConfigurationParameterPaths((configuration_parameter_s + "_HINT").c_str());
for (size_t k = 0; k < search_hint.size(); k++)
{
cv::String datapath = search_hint[k];
if (datapath.empty())
continue;
if (utils::fs::isDirectory(datapath))
{
CV_LOG_DEBUG(NULL, "utils::findDataFile(): trying " << configuration_parameter << "_HINT=" << datapath);
for(size_t i = search_subdir.size(); i > 0; i--)
{
const cv::String& subdir = search_subdir[i - 1];
cv::String prefix = utils::fs::join(datapath, subdir);
TRY_FILE_WITH_PREFIX(prefix);
}
}
else
{
CV_LOG_WARNING(NULL, configuration_parameter << "_HINT is specified but it is not a directory: " << datapath);
}
}
// Step 3
const cv::utils::Paths& override_paths = configuration_parameter_s.empty() ? cv::utils::Paths()
: getConfigurationParameterPaths(configuration_parameter);
for (size_t k = 0; k < override_paths.size(); k++)
{
cv::String datapath = override_paths[k];
if (datapath.empty())
continue;
if (utils::fs::isDirectory(datapath))
{
CV_LOG_DEBUG(NULL, "utils::findDataFile(): trying " << configuration_parameter << "=" << datapath);
for(size_t i = search_subdir.size(); i > 0; i--)
{
const cv::String& subdir = search_subdir[i - 1];
cv::String prefix = utils::fs::join(datapath, subdir);
TRY_FILE_WITH_PREFIX(prefix);
}
}
else
{
CV_LOG_WARNING(NULL, configuration_parameter << " is specified but it is not a directory: " << datapath);
}
}
if (!override_paths.empty())
{
CV_LOG_INFO(NULL, "utils::findDataFile(): can't find data file via " << configuration_parameter << " configuration override: " << relative_path);
return cv::String();
}
// Steps: 4, 5, 6
cv::String cwd = utils::fs::getcwd();
cv::String build_dir(OPENCV_BUILD_DIR);
bool has_tested_build_directory = false;
if (isSubDirectory(build_dir, cwd) || isSubDirectory(utils::fs::canonical(build_dir), utils::fs::canonical(cwd)))
{
CV_LOG_DEBUG(NULL, "utils::findDataFile(): the current directory is build sub-directory: " << cwd);
const char* build_subdirs[] = { OPENCV_DATA_BUILD_DIR_SEARCH_PATHS };
for (size_t k = 0; k < sizeof(build_subdirs)/sizeof(build_subdirs[0]); k++)
{
CV_LOG_DEBUG(NULL, "utils::findDataFile(): <build>/" << build_subdirs[k]);
cv::String datapath = utils::fs::join(build_dir, build_subdirs[k]);
if (utils::fs::isDirectory(datapath))
{
for(size_t i = search_subdir.size(); i > 0; i--)
{
const cv::String& subdir = search_subdir[i - 1];
cv::String prefix = utils::fs::join(datapath, subdir);
TRY_FILE_WITH_PREFIX(prefix);
}
}
}
has_tested_build_directory = true;
}
cv::String source_dir;
cv::String try_source_dir = cwd;
for (int levels = 0; levels < 3; ++levels)
{
if (utils::fs::exists(utils::fs::join(try_source_dir, "modules/core/include/opencv2/core/version.hpp")))
{
source_dir = try_source_dir;
break;
}
try_source_dir = utils::fs::join(try_source_dir, "/..");
}
if (!source_dir.empty())
{
CV_LOG_DEBUG(NULL, "utils::findDataFile(): the current directory is source sub-directory: " << source_dir);
CV_LOG_DEBUG(NULL, "utils::findDataFile(): <source>" << source_dir);
cv::String datapath = source_dir;
if (utils::fs::isDirectory(datapath))
{
for(size_t i = search_subdir.size(); i > 0; i--)
{
const cv::String& subdir = search_subdir[i - 1];
cv::String prefix = utils::fs::join(datapath, subdir);
TRY_FILE_WITH_PREFIX(prefix);
}
}
}
cv::String module_path = getModuleLocation((void*)getModuleLocation); // use code addr, doesn't work with static linkage!
CV_LOG_DEBUG(NULL, "Detected module path: '" << module_path << '\'');
if (!has_tested_build_directory &&
(isSubDirectory(build_dir, module_path) || isSubDirectory(utils::fs::canonical(build_dir), utils::fs::canonical(module_path)))
)
{
CV_LOG_DEBUG(NULL, "utils::findDataFile(): the binary module directory is build sub-directory: " << module_path);
const char* build_subdirs[] = { OPENCV_DATA_BUILD_DIR_SEARCH_PATHS };
for (size_t k = 0; k < sizeof(build_subdirs)/sizeof(build_subdirs[0]); k++)
{
CV_LOG_DEBUG(NULL, "utils::findDataFile(): <build>/" << build_subdirs[k]);
cv::String datapath = utils::fs::join(build_dir, build_subdirs[k]);
if (utils::fs::isDirectory(datapath))
{
for(size_t i = search_subdir.size(); i > 0; i--)
{
const cv::String& subdir = search_subdir[i - 1];
cv::String prefix = utils::fs::join(datapath, subdir);
TRY_FILE_WITH_PREFIX(prefix);
}
}
}
}
#if defined OPENCV_INSTALL_DATA_DIR_RELATIVE
if (!module_path.empty()) // require module path
{
size_t pos = module_path.rfind('/');
if (pos == cv::String::npos)
pos = module_path.rfind('\\');
cv::String module_dir = (pos == cv::String::npos) ? module_path : module_path.substr(0, pos);
const char* install_subdirs[] = { OPENCV_INSTALL_DATA_DIR_RELATIVE };
for (size_t k = 0; k < sizeof(install_subdirs)/sizeof(install_subdirs[0]); k++)
{
cv::String datapath = utils::fs::join(module_dir, install_subdirs[k]);
CV_LOG_DEBUG(NULL, "utils::findDataFile(): trying install path (from binary path): " << datapath);
if (utils::fs::isDirectory(datapath))
{
for(size_t i = search_subdir.size(); i > 0; i--)
{
const cv::String& subdir = search_subdir[i - 1];
cv::String prefix = utils::fs::join(datapath, subdir);
TRY_FILE_WITH_PREFIX(prefix);
}
}
else
{
CV_LOG_DEBUG(NULL, "utils::findDataFile(): ... skip, not a valid directory: " << datapath);
}
}
}
#endif
#if defined OPENCV_INSTALL_PREFIX && defined OPENCV_DATA_INSTALL_PATH
cv::String install_dir(OPENCV_INSTALL_PREFIX);
// use core/world module path and verify that library is running from installation directory
// It is neccessary to avoid touching of unrelated common /usr/local path
if (module_path.empty()) // can't determine
module_path = install_dir;
if (isSubDirectory(install_dir, module_path) || isSubDirectory(utils::fs::canonical(install_dir), utils::fs::canonical(module_path)))
{
cv::String datapath = utils::fs::join(install_dir, OPENCV_DATA_INSTALL_PATH);
if (utils::fs::isDirectory(datapath))
{
CV_LOG_DEBUG(NULL, "utils::findDataFile(): trying install path: " << datapath);
for(size_t i = search_subdir.size(); i > 0; i--)
{
const cv::String& subdir = search_subdir[i - 1];
cv::String prefix = utils::fs::join(datapath, subdir);
TRY_FILE_WITH_PREFIX(prefix);
}
}
}
#endif
return cv::String(); // not found
}
cv::String findDataFile(const cv::String& relative_path, bool required, const char* configuration_parameter)
{
CV_LOG_DEBUG(NULL, cv::format("cv::utils::findDataFile('%s', %s, %s)",
relative_path.c_str(), required ? "true" : "false",
configuration_parameter ? configuration_parameter : "NULL"));
cv::String result = cv::utils::findDataFile(relative_path,
configuration_parameter,
NULL,
NULL);
if (result.empty() && required)
CV_Error(cv::Error::StsError, cv::format("OpenCV: Can't find required data file: %s", relative_path.c_str()));
return result;
}
}} // namespace
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2014 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "scene_subdiv_mesh.h"
#include "scene.h"
namespace embree
{
SubdivMesh::SubdivMesh (Scene* parent, RTCGeometryFlags flags, size_t numFaces, size_t numEdges, size_t numVertices, size_t numTimeSteps)
: Geometry(parent,SUBDIV_MESH,numFaces,flags),
mask(-1),
numTimeSteps(numTimeSteps),
numFaces(numFaces),
numEdges(numEdges),
numVertices(numVertices),
displFunc(NULL), displBounds(empty),
halfEdges(NULL)
{
for (size_t i=0; i<numTimeSteps; i++)
vertices[i].init(numVertices,sizeof(Vec3fa));
vertexIndices.init(numEdges,sizeof(unsigned int));
vertexOffsets.init(numFaces,sizeof(unsigned int));
creases.init(numEdges,sizeof(float));
}
SubdivMesh::~SubdivMesh () {
delete[] halfEdges;
}
void SubdivMesh::enabling()
{
if (numTimeSteps == 1) { atomic_add(&parent->numSubdivPatches ,numFaces); }
else { atomic_add(&parent->numSubdivPatches2,numFaces); }
}
void SubdivMesh::disabling()
{
if (numTimeSteps == 1) { atomic_add(&parent->numSubdivPatches ,-(ssize_t)numFaces); }
else { atomic_add(&parent->numSubdivPatches2, -(ssize_t)numFaces); }
}
void SubdivMesh::setMask (unsigned mask)
{
if (parent->isStatic() && parent->isBuild()) {
process_error(RTC_INVALID_OPERATION,"static geometries cannot get modified");
return;
}
this->mask = mask;
}
void SubdivMesh::setBuffer(RTCBufferType type, void* ptr, size_t offset, size_t stride)
{
if (parent->isStatic() && parent->isBuild()) {
process_error(RTC_INVALID_OPERATION,"static geometries cannot get modified");
return;
}
/* verify that all accesses are 4 bytes aligned */
if (((size_t(ptr) + offset) & 0x3) || (stride & 0x3)) {
process_error(RTC_INVALID_OPERATION,"data must be 4 bytes aligned");
return;
}
/* verify that all vertex accesses are 16 bytes aligned */
#if defined(__MIC__)
if (type == RTC_VERTEX_BUFFER0 || type == RTC_VERTEX_BUFFER1) {
if (((size_t(ptr) + offset) & 0xF) || (stride & 0xF)) {
process_error(RTC_INVALID_OPERATION,"data must be 16 bytes aligned");
return;
}
}
#endif
switch (type) {
case RTC_INDEX_BUFFER :
vertexIndices.set(ptr,offset,stride);
break;
case RTC_OFFSET_BUFFER :
vertexOffsets.set(ptr,offset,stride);
break;
case RTC_VERTEX_BUFFER0:
vertices[0].set(ptr,offset,stride);
if (numVertices) {
/* test if array is properly padded */
volatile int w = *((int*)&vertices[0][numVertices-1]+3); // FIXME: is failing hard avoidable?
}
break;
case RTC_VERTEX_BUFFER1:
vertices[1].set(ptr,offset,stride);
if (numVertices) {
/* test if array is properly padded */
volatile int w = *((int*)&vertices[1][numVertices-1]+3); // FIXME: is failing hard avoidable?
}
break;
case RTC_CREASE_BUFFER:
creases.set(ptr,offset,stride);
break;
default:
process_error(RTC_INVALID_ARGUMENT,"unknown buffer type");
break;
}
}
void* SubdivMesh::map(RTCBufferType type)
{
if (parent->isStatic() && parent->isBuild()) {
process_error(RTC_INVALID_OPERATION,"static geometries cannot get modified");
return NULL;
}
switch (type) {
case RTC_INDEX_BUFFER : return vertexIndices.map(parent->numMappedBuffers);
case RTC_OFFSET_BUFFER : return vertexOffsets.map(parent->numMappedBuffers);
case RTC_VERTEX_BUFFER0 : return vertices[0].map(parent->numMappedBuffers);
case RTC_VERTEX_BUFFER1 : return vertices[1].map(parent->numMappedBuffers);
case RTC_CREASE_BUFFER : return creases.map(parent->numMappedBuffers);
default : process_error(RTC_INVALID_ARGUMENT,"unknown buffer type"); return NULL;
}
}
void SubdivMesh::unmap(RTCBufferType type)
{
if (parent->isStatic() && parent->isBuild()) {
process_error(RTC_INVALID_OPERATION,"static geometries cannot get modified");
return;
}
switch (type) {
case RTC_INDEX_BUFFER : vertexIndices.unmap(parent->numMappedBuffers); break;
case RTC_OFFSET_BUFFER : vertexOffsets.unmap(parent->numMappedBuffers); break;
case RTC_VERTEX_BUFFER0 : vertices[0].unmap(parent->numMappedBuffers); break;
case RTC_VERTEX_BUFFER1 : vertices[1].unmap(parent->numMappedBuffers); break;
case RTC_CREASE_BUFFER : creases.unmap(parent->numMappedBuffers); break;
default : process_error(RTC_INVALID_ARGUMENT,"unknown buffer type"); break;
}
}
void SubdivMesh::setUserData (void* ptr, bool ispc) {
userPtr = ptr;
}
void SubdivMesh::setDisplacementFunction (RTCDisplacementFunc func, const RTCBounds& bounds)
{
if (parent->isStatic() && parent->isBuild()) {
process_error(RTC_INVALID_OPERATION,"static geometries cannot get modified");
return;
}
this->displFunc = func;
this->displBounds = (BBox3fa&)bounds;
}
void SubdivMesh::immutable ()
{
bool freeVertices = !parent->needVertices;
if (freeVertices ) vertices[0].free();
if (freeVertices ) vertices[1].free();
}
void SubdivMesh::initializeHalfEdgeStructures ()
{
numHalfEdges = 4*numFaces;
halfEdges = new HalfEdge[numHalfEdges];
/*! initialize all four half-edges for each face */
for (size_t i=0; i<numFaces; i++)
{
const unsigned int halfEdgeIndex = vertexOffsets[i];
for (size_t j=0; j<4; j++)
{
halfEdges[4*i+j].vtx_index = vertexIndices[halfEdgeIndex + j];
halfEdges[4*i+j].halfedge_id = 4*i+j;
halfEdges[4*i+j].opposite_index = (unsigned int)-1;
if (creases)
halfEdges[4*i+j].crease_weight = creases[4*i+j];
else
halfEdges[4*i+j].crease_weight = 0.0f;
}
}
/*! find opposite half-edges */
std::map<size_t,unsigned int> edgeMap;
for (size_t i=0; i<numHalfEdges; i++)
{
unsigned int start = halfEdges[i].getStartVertexIndex();
unsigned int end = halfEdges[i].getEndVertexIndex();
if (end < start) std::swap(start,end);
size_t value = ((size_t)start << 32) | (size_t)end; // FIXME: does not work in 32 bit mode
std::map<size_t,unsigned int>::iterator found = edgeMap.find(value);
if (found != edgeMap.end()) {
halfEdges[i].opposite_index = found->second;
halfEdges[ found->second ].opposite_index = i;
}
else {
edgeMap[value] = i;
}
}
/* print statistics in verbose mode */
if (g_verbose >= 1)
{
size_t numRegularPatches = 0;
size_t numIrregularPatches = 0;
size_t numPatchesWithEdges = 0;
assert(numHalfEdges % 4 == 0);
for (size_t i=0; i<numHalfEdges; i+=4)
{
if (halfEdges[i].faceHasEdges())
{
numIrregularPatches++;
numPatchesWithEdges++;
}
else if (halfEdges[i].isFaceRegular())
numRegularPatches++;
else
numIrregularPatches++;
}
size_t numPatches = numRegularPatches + numIrregularPatches;
std::cout << "numPatches " << numPatches
<< " : regular " << numRegularPatches << " (" << 100.0f * numRegularPatches / numPatches << "%)"
<< " irregular " << numIrregularPatches << " (" << 100.0f * numIrregularPatches / numPatches << "%) "
<< " irregular with edges " << numPatchesWithEdges << " (" << 100.0f * numPatchesWithEdges / numPatches << "%) " << std::endl;
}
}
bool SubdivMesh::verify ()
{
float range = sqrtf(0.5f*FLT_MAX);
for (size_t j=0; j<numTimeSteps; j++) {
BufferT<Vec3fa>& verts = vertices[j];
for (size_t i=0; i<numVertices; i++) {
if (!(verts[i].x > -range && verts[i].x < range)) return false;
if (!(verts[i].y > -range && verts[i].y < range)) return false;
if (!(verts[i].z > -range && verts[i].z < range)) return false;
}
}
return true;
}
}
<commit_msg>bugfix for 32bit mode<commit_after>// ======================================================================== //
// Copyright 2009-2014 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "scene_subdiv_mesh.h"
#include "scene.h"
namespace embree
{
SubdivMesh::SubdivMesh (Scene* parent, RTCGeometryFlags flags, size_t numFaces, size_t numEdges, size_t numVertices, size_t numTimeSteps)
: Geometry(parent,SUBDIV_MESH,numFaces,flags),
mask(-1),
numTimeSteps(numTimeSteps),
numFaces(numFaces),
numEdges(numEdges),
numVertices(numVertices),
displFunc(NULL), displBounds(empty),
halfEdges(NULL)
{
for (size_t i=0; i<numTimeSteps; i++)
vertices[i].init(numVertices,sizeof(Vec3fa));
vertexIndices.init(numEdges,sizeof(unsigned int));
vertexOffsets.init(numFaces,sizeof(unsigned int));
creases.init(numEdges,sizeof(float));
}
SubdivMesh::~SubdivMesh () {
delete[] halfEdges;
}
void SubdivMesh::enabling()
{
if (numTimeSteps == 1) { atomic_add(&parent->numSubdivPatches ,numFaces); }
else { atomic_add(&parent->numSubdivPatches2,numFaces); }
}
void SubdivMesh::disabling()
{
if (numTimeSteps == 1) { atomic_add(&parent->numSubdivPatches ,-(ssize_t)numFaces); }
else { atomic_add(&parent->numSubdivPatches2, -(ssize_t)numFaces); }
}
void SubdivMesh::setMask (unsigned mask)
{
if (parent->isStatic() && parent->isBuild()) {
process_error(RTC_INVALID_OPERATION,"static geometries cannot get modified");
return;
}
this->mask = mask;
}
void SubdivMesh::setBuffer(RTCBufferType type, void* ptr, size_t offset, size_t stride)
{
if (parent->isStatic() && parent->isBuild()) {
process_error(RTC_INVALID_OPERATION,"static geometries cannot get modified");
return;
}
/* verify that all accesses are 4 bytes aligned */
if (((size_t(ptr) + offset) & 0x3) || (stride & 0x3)) {
process_error(RTC_INVALID_OPERATION,"data must be 4 bytes aligned");
return;
}
/* verify that all vertex accesses are 16 bytes aligned */
#if defined(__MIC__)
if (type == RTC_VERTEX_BUFFER0 || type == RTC_VERTEX_BUFFER1) {
if (((size_t(ptr) + offset) & 0xF) || (stride & 0xF)) {
process_error(RTC_INVALID_OPERATION,"data must be 16 bytes aligned");
return;
}
}
#endif
switch (type) {
case RTC_INDEX_BUFFER :
vertexIndices.set(ptr,offset,stride);
break;
case RTC_OFFSET_BUFFER :
vertexOffsets.set(ptr,offset,stride);
break;
case RTC_VERTEX_BUFFER0:
vertices[0].set(ptr,offset,stride);
if (numVertices) {
/* test if array is properly padded */
volatile int w = *((int*)&vertices[0][numVertices-1]+3); // FIXME: is failing hard avoidable?
}
break;
case RTC_VERTEX_BUFFER1:
vertices[1].set(ptr,offset,stride);
if (numVertices) {
/* test if array is properly padded */
volatile int w = *((int*)&vertices[1][numVertices-1]+3); // FIXME: is failing hard avoidable?
}
break;
case RTC_CREASE_BUFFER:
creases.set(ptr,offset,stride);
break;
default:
process_error(RTC_INVALID_ARGUMENT,"unknown buffer type");
break;
}
}
void* SubdivMesh::map(RTCBufferType type)
{
if (parent->isStatic() && parent->isBuild()) {
process_error(RTC_INVALID_OPERATION,"static geometries cannot get modified");
return NULL;
}
switch (type) {
case RTC_INDEX_BUFFER : return vertexIndices.map(parent->numMappedBuffers);
case RTC_OFFSET_BUFFER : return vertexOffsets.map(parent->numMappedBuffers);
case RTC_VERTEX_BUFFER0 : return vertices[0].map(parent->numMappedBuffers);
case RTC_VERTEX_BUFFER1 : return vertices[1].map(parent->numMappedBuffers);
case RTC_CREASE_BUFFER : return creases.map(parent->numMappedBuffers);
default : process_error(RTC_INVALID_ARGUMENT,"unknown buffer type"); return NULL;
}
}
void SubdivMesh::unmap(RTCBufferType type)
{
if (parent->isStatic() && parent->isBuild()) {
process_error(RTC_INVALID_OPERATION,"static geometries cannot get modified");
return;
}
switch (type) {
case RTC_INDEX_BUFFER : vertexIndices.unmap(parent->numMappedBuffers); break;
case RTC_OFFSET_BUFFER : vertexOffsets.unmap(parent->numMappedBuffers); break;
case RTC_VERTEX_BUFFER0 : vertices[0].unmap(parent->numMappedBuffers); break;
case RTC_VERTEX_BUFFER1 : vertices[1].unmap(parent->numMappedBuffers); break;
case RTC_CREASE_BUFFER : creases.unmap(parent->numMappedBuffers); break;
default : process_error(RTC_INVALID_ARGUMENT,"unknown buffer type"); break;
}
}
void SubdivMesh::setUserData (void* ptr, bool ispc) {
userPtr = ptr;
}
void SubdivMesh::setDisplacementFunction (RTCDisplacementFunc func, const RTCBounds& bounds)
{
if (parent->isStatic() && parent->isBuild()) {
process_error(RTC_INVALID_OPERATION,"static geometries cannot get modified");
return;
}
this->displFunc = func;
this->displBounds = (BBox3fa&)bounds;
}
void SubdivMesh::immutable ()
{
bool freeVertices = !parent->needVertices;
if (freeVertices ) vertices[0].free();
if (freeVertices ) vertices[1].free();
}
void SubdivMesh::initializeHalfEdgeStructures ()
{
numHalfEdges = 4*numFaces;
halfEdges = new HalfEdge[numHalfEdges];
/*! initialize all four half-edges for each face */
for (size_t i=0; i<numFaces; i++)
{
const unsigned int halfEdgeIndex = vertexOffsets[i];
for (size_t j=0; j<4; j++)
{
halfEdges[4*i+j].vtx_index = vertexIndices[halfEdgeIndex + j];
halfEdges[4*i+j].halfedge_id = 4*i+j;
halfEdges[4*i+j].opposite_index = (unsigned int)-1;
if (creases)
halfEdges[4*i+j].crease_weight = creases[4*i+j];
else
halfEdges[4*i+j].crease_weight = 0.0f;
}
}
/*! find opposite half-edges */
std::map<size_t,unsigned int> edgeMap;
for (size_t i=0; i<numHalfEdges; i++)
{
unsigned int start = halfEdges[i].getStartVertexIndex();
unsigned int end = halfEdges[i].getEndVertexIndex();
if (end < start) std::swap(start,end);
int64 value = ((int64)start << 32) | (size_t)end;
std::map<size_t,unsigned int>::iterator found = edgeMap.find(value);
if (found != edgeMap.end()) {
halfEdges[i].opposite_index = found->second;
halfEdges[ found->second ].opposite_index = i;
}
else {
edgeMap[value] = i;
}
}
/* print statistics in verbose mode */
if (g_verbose >= 1)
{
size_t numRegularPatches = 0;
size_t numIrregularPatches = 0;
size_t numPatchesWithEdges = 0;
assert(numHalfEdges % 4 == 0);
for (size_t i=0; i<numHalfEdges; i+=4)
{
if (halfEdges[i].faceHasEdges())
{
numIrregularPatches++;
numPatchesWithEdges++;
}
else if (halfEdges[i].isFaceRegular())
numRegularPatches++;
else
numIrregularPatches++;
}
size_t numPatches = numRegularPatches + numIrregularPatches;
std::cout << "numPatches " << numPatches
<< " : regular " << numRegularPatches << " (" << 100.0f * numRegularPatches / numPatches << "%)"
<< " irregular " << numIrregularPatches << " (" << 100.0f * numIrregularPatches / numPatches << "%) "
<< " irregular with edges " << numPatchesWithEdges << " (" << 100.0f * numPatchesWithEdges / numPatches << "%) " << std::endl;
}
}
bool SubdivMesh::verify ()
{
float range = sqrtf(0.5f*FLT_MAX);
for (size_t j=0; j<numTimeSteps; j++) {
BufferT<Vec3fa>& verts = vertices[j];
for (size_t i=0; i<numVertices; i++) {
if (!(verts[i].x > -range && verts[i].x < range)) return false;
if (!(verts[i].y > -range && verts[i].y < range)) return false;
if (!(verts[i].z > -range && verts[i].z < range)) return false;
}
}
return true;
}
}
<|endoftext|> |
<commit_before>// Copyright 2015 XLGAMES Inc.
//
// Distributed under the MIT License (See
// accompanying file "LICENSE" or the website
// http://www.opensource.org/licenses/mit-license.php)
#include "MaterialBinder.h"
#include "../../RenderCore/Metal/InputLayout.h"
#include "../../RenderCore/Metal/DeviceContext.h"
#include "../../RenderCore/Metal/State.h"
#include "../../RenderCore/Metal/Shader.h"
#include "../../RenderCore/Assets/DeferredShaderResource.h"
#include "../../RenderCore/Techniques/TechniqueMaterial.h"
#include "../../RenderCore/Techniques/TechniqueUtils.h"
#include "../../RenderCore/Techniques/ParsingContext.h"
#include "../../RenderCore/Techniques/CommonBindings.h"
#include "../../RenderCore/Techniques/PredefinedCBLayout.h"
#include "../../RenderCore/Assets/Material.h"
#include "../../RenderCore/Assets/AssetUtils.h"
#include "../../Assets/AssetUtils.h"
#include "../../Math/Transformations.h"
#include "../../Utility/StringFormat.h"
#include "../../Utility/StringUtils.h"
#include "../../RenderCore/DX11/Metal/IncludeDX11.h"
#include "../../RenderCore/DX11/Metal/DX11Utils.h"
#include <d3d11shader.h> // D3D11_SHADER_TYPE_DESC
namespace ToolsRig
{
IMaterialBinder::~IMaterialBinder() {}
///////////////////////////////////////////////////////////////////////////////////////////////////
static ParameterBox SetResHasParameters(
const ParameterBox& inputMatParameters, const ParameterBox& resBindings,
const ::Assets::DirectorySearchRules& searchRules)
{
static const auto DefaultNormalsTextureBindingHash = ParameterBox::MakeParameterNameHash("NormalsTexture");
// The "material parameters" ParameterBox should contain some "RES_HAS_..."
// settings. These tell the shader what resource bindings are available
// (and what are missing). We need to set these parameters according to our
// binding list
ParameterBox result = inputMatParameters;
for (auto param=resBindings.Begin(); !param.IsEnd(); ++param) {
result.SetParameter(StringMeld<64, utf8>() << "RES_HAS_" << param.Name(), 1);
if (param.HashName() == DefaultNormalsTextureBindingHash) {
auto resourceName = resBindings.GetString<::Assets::ResChar>(DefaultNormalsTextureBindingHash);
::Assets::ResChar resolvedName[MaxPath];
searchRules.ResolveFile(resolvedName, dimof(resolvedName), resourceName.c_str());
result.SetParameter((const utf8*)"RES_HAS_NormalsTexture_DXT",
RenderCore::Assets::IsDXTNormalMap(resolvedName));
}
}
return std::move(result);
}
RenderCore::Metal::ShaderProgram* MaterialBinder::Apply(
RenderCore::Metal::DeviceContext& metalContext,
RenderCore::Techniques::ParsingContext& parserContext,
unsigned techniqueIndex,
const RenderCore::Assets::ResolvedMaterial& mat,
const SystemConstants& sysConstants,
const ::Assets::DirectorySearchRules& searchRules,
const RenderCore::Metal::InputLayout& geoInputLayout)
{
using namespace RenderCore;
using namespace RenderCore::Techniques;
ParameterBox materialParameters = SetResHasParameters(mat._matParams, mat._bindings, searchRules);
TechniqueMaterial material(geoInputLayout, {}, materialParameters);
auto variation = material.FindVariation(parserContext, techniqueIndex, _shaderTypeName.c_str());
if (variation._shaderProgram == nullptr) {
return nullptr; // we can't render because we couldn't resolve a good shader variation
}
// we must bind the shader program & the bound layout
// but we're not using the BoundUniforms in the ResolvedShader object
metalContext.Bind(*variation._shaderProgram);
metalContext.Bind(*variation._boundLayout);
// Instead of using ResolvedShader::_boundUniforms, let's
// look at the reflection information for the shader program
// and assign each shader input to some reasonable value
BindConstantsAndResources(
metalContext, parserContext, mat,
sysConstants, searchRules, *variation._shaderProgram);
return variation._shaderProgram;
}
MaterialBinder::MaterialBinder(const ::Assets::ResChar shaderTypeName[])
: _shaderTypeName(shaderTypeName)
{}
MaterialBinder::~MaterialBinder() {}
///////////////////////////////////////////////////////////////////////////////////////////////////
static size_t WriteSystemVariable(
const char name[],
const IMaterialBinder::SystemConstants& constants,
UInt2 viewportDims,
void* destination, void* destinationEnd)
{
size_t size = size_t(destinationEnd) - size_t(destination);
if (!_stricmp(name, "SI_OutputDimensions") && size >= (sizeof(unsigned)*2)) {
((unsigned*)destination)[0] = viewportDims[0];
((unsigned*)destination)[1] = viewportDims[1];
return sizeof(unsigned)*2;
} else if (!_stricmp(name, "SI_NegativeLightDirection") && size >= sizeof(Float3)) {
*((Float3*)destination) = constants._lightNegativeDirection;
return sizeof(Float3);
} else if (!_stricmp(name, "SI_LightColor") && size >= sizeof(Float3)) {
*((Float3*)destination) = constants._lightColour;
return sizeof(Float3);
}
return 0;
}
static void WriteParameter(
RenderCore::SharedPkt& result,
const ParameterBox& constants,
ParameterBox::ParameterNameHash nameHash,
ID3D11ShaderReflectionVariable& reflectionVariable,
const D3D11_SHADER_VARIABLE_DESC& variableDesc,
unsigned bufferSize)
{
auto type = reflectionVariable.GetType();
D3D11_SHADER_TYPE_DESC typeDesc;
auto hresult = type->GetDesc(&typeDesc);
if (SUCCEEDED(hresult)) {
//
// Finally, copy whatever the material object
// is, into the destination position in the
// constant buffer;
//
auto impliedType = RenderCore::Metal::GetType(typeDesc);
assert((variableDesc.StartOffset + impliedType.GetSize()) <= bufferSize);
if ((variableDesc.StartOffset + impliedType.GetSize()) <= bufferSize) {
if (!result.size()) {
result = RenderCore::MakeSharedPktSize(bufferSize);
std::fill((uint8*)result.begin(), (uint8*)result.end(), 0);
}
constants.GetParameter(
nameHash,
PtrAdd(result.begin(), variableDesc.StartOffset),
impliedType);
}
}
}
static std::vector<std::pair<uint64, RenderCore::Metal::ConstantBufferPacket>>
BuildMaterialConstants(
ID3D::ShaderReflection& reflection,
const ParameterBox& constants,
const IMaterialBinder::SystemConstants& systemConstantsContext,
UInt2 viewportDims)
{
//
// Find the cbuffers, and look for the variables
// within. Attempt to fill those values with the appropriate values
// from the current previewing material state
//
std::vector<std::pair<uint64, RenderCore::Metal::ConstantBufferPacket>> finalResult;
const auto& cbLayout = ::Assets::GetAssetDep<RenderCore::Techniques::PredefinedCBLayout>(
"game/xleres/BasicMaterialConstants.txt");
D3D11_SHADER_DESC shaderDesc;
reflection.GetDesc(&shaderDesc);
for (unsigned c=0; c<shaderDesc.BoundResources; ++c) {
D3D11_SHADER_INPUT_BIND_DESC bindDesc;
reflection.GetResourceBindingDesc(c, &bindDesc);
if (bindDesc.Type == D3D10_SIT_CBUFFER) {
auto cbuffer = reflection.GetConstantBufferByName(bindDesc.Name);
if (cbuffer) {
D3D11_SHADER_BUFFER_DESC bufferDesc;
HRESULT hresult = cbuffer->GetDesc(&bufferDesc);
if (SUCCEEDED(hresult)) {
RenderCore::SharedPkt result;
for (unsigned c=0; c<bufferDesc.Variables; ++c) {
auto reflectionVariable = cbuffer->GetVariableByIndex(c);
D3D11_SHADER_VARIABLE_DESC variableDesc;
hresult = reflectionVariable->GetDesc(&variableDesc);
if (SUCCEEDED(hresult)) {
//
// If the variable is within our table of
// material parameter values, then copy that
// value into the appropriate place in the cbuffer.
//
// However, note that this may require a cast sometimes
//
auto nameHash = ParameterBox::MakeParameterNameHash(variableDesc.Name);
if (constants.HasParameter(nameHash)) {
WriteParameter(
result, constants, nameHash, *reflectionVariable,
variableDesc, bufferDesc.Size);
} else if (cbLayout._defaults.HasParameter(nameHash)) {
WriteParameter(
result, cbLayout._defaults, nameHash, *reflectionVariable,
variableDesc, bufferDesc.Size);
} else {
if (!result.size()) {
char buffer[4096];
if (size_t size = WriteSystemVariable(
variableDesc.Name, systemConstantsContext, viewportDims,
buffer, PtrAdd(buffer, std::min(sizeof(buffer), (size_t)(bufferDesc.Size - variableDesc.StartOffset))))) {
result = RenderCore::MakeSharedPktSize(bufferDesc.Size);
std::fill((uint8*)result.begin(), (uint8*)result.end(), 0);
XlCopyMemory(PtrAdd(result.begin(), variableDesc.StartOffset), buffer, size);
}
} else {
WriteSystemVariable(
variableDesc.Name, systemConstantsContext, viewportDims,
PtrAdd(result.begin(), variableDesc.StartOffset), result.end());
}
}
}
}
if (result.size()) {
finalResult.push_back(
std::make_pair(Hash64(bindDesc.Name), std::move(result)));
}
}
}
}
}
return finalResult;
}
static std::vector<const RenderCore::Metal::ShaderResourceView*>
BuildBoundTextures(
RenderCore::Metal::BoundUniforms& boundUniforms,
RenderCore::Metal::ShaderProgram& shaderProgram,
const ParameterBox& bindings,
const Assets::DirectorySearchRules& searchRules)
{
using namespace RenderCore;
std::vector<const Metal::ShaderResourceView*> result;
std::vector<uint64> alreadyBound;
//
// For each entry in our resource binding set, we're going
// to register a binding in the BoundUniforms, and find
// the associated shader resource view.
// For any shader resources that are used by the shader, but
// not bound to anything -- we need to assign them to the
// default objects.
//
const CompiledShaderByteCode* shaderCode[] = {
&shaderProgram.GetCompiledVertexShader(),
&shaderProgram.GetCompiledPixelShader(),
shaderProgram.GetCompiledGeometryShader(),
};
for (unsigned s=0; s<dimof(shaderCode); ++s) {
if (!shaderCode[s]) continue;
auto reflection = Metal::CreateReflection(*shaderCode[s]);
D3D11_SHADER_DESC shaderDesc;
reflection->GetDesc(&shaderDesc);
for (unsigned c=0; c<shaderDesc.BoundResources; ++c) {
D3D11_SHADER_INPUT_BIND_DESC bindDesc;
reflection->GetResourceBindingDesc(c, &bindDesc);
if (bindDesc.Type == D3D10_SIT_TEXTURE) {
// skip "NormalsFittingTexture" -- system use
if (!XlCompareString(bindDesc.Name, "NormalsFittingTexture")) continue;
if (!XlCompareString(bindDesc.Name, "SkyReflectionTexture[0]")) continue;
if (!XlCompareString(bindDesc.Name, "SkyReflectionTexture[1]")) continue;
if (!XlCompareString(bindDesc.Name, "SkyReflectionTexture[2]")) continue;
if (!XlCompareString(bindDesc.Name, "GGXTable")) continue;
auto str = bindings.GetString<::Assets::ResChar>(ParameterBox::MakeParameterNameHash(bindDesc.Name));
if (str.empty()) {
// It's not mentioned in the material resources. try to look
// for a default resource for this bind point
str = ::Assets::rstring("game/xleres/DefaultResources/") + bindDesc.Name + ".dds";
}
auto bindingHash = Hash64(bindDesc.Name, &bindDesc.Name[XlStringLen(bindDesc.Name)]);
if (std::find(alreadyBound.cbegin(), alreadyBound.cend(), bindingHash) != alreadyBound.cend()) {
continue;
}
alreadyBound.push_back(bindingHash);
if (!str.empty()) {
TRY {
::Assets::ResChar resolvedFile[MaxPath];
searchRules.ResolveFile(
resolvedFile, dimof(resolvedFile),
str.c_str());
const RenderCore::Assets::DeferredShaderResource& texture =
::Assets::GetAssetDep<RenderCore::Assets::DeferredShaderResource>(resolvedFile);
result.push_back(&texture.GetShaderResource());
boundUniforms.BindShaderResource(
bindingHash,
unsigned(result.size()-1), 1);
}
CATCH (const ::Assets::Exceptions::InvalidAsset&) {}
CATCH_END
}
} else if (bindDesc.Type == D3D10_SIT_SAMPLER) {
// we should also bind samplers to something
// reasonable, also...
}
}
}
return std::move(result);
}
void IMaterialBinder::BindConstantsAndResources(
RenderCore::Metal::DeviceContext& metalContext,
RenderCore::Techniques::ParsingContext& parsingContext,
const RenderCore::Assets::ResolvedMaterial& mat,
const SystemConstants& sysConstants,
const ::Assets::DirectorySearchRules& searchRules,
RenderCore::Metal::ShaderProgram& shaderProgram)
{
using namespace RenderCore;
//
// Constants / Resources
//
Metal::ViewportDesc currentViewport(metalContext);
auto materialConstants = BuildMaterialConstants(
*Metal::CreateReflection(shaderProgram.GetCompiledPixelShader()),
mat._constants, sysConstants,
UInt2(unsigned(currentViewport.Width), unsigned(currentViewport.Height)));
Metal::BoundUniforms boundLayout(shaderProgram);
Techniques::TechniqueContext::BindGlobalUniforms(boundLayout);
std::vector<RenderCore::Metal::ConstantBufferPacket> constantBufferPackets;
constantBufferPackets.push_back(
Techniques::MakeLocalTransformPacket(
sysConstants._objectToWorld, ExtractTranslation(parsingContext.GetProjectionDesc()._cameraToWorld)));
boundLayout.BindConstantBuffer(Techniques::ObjectCB::LocalTransform, 0, 1);
for (auto i=materialConstants.cbegin(); i!=materialConstants.cend(); ++i) {
boundLayout.BindConstantBuffer(i->first, unsigned(constantBufferPackets.size()), 1);
constantBufferPackets.push_back(std::move(i->second));
}
auto boundTextures = BuildBoundTextures(
boundLayout, shaderProgram,
mat._bindings, searchRules);
boundLayout.Apply(
metalContext,
parsingContext.GetGlobalUniformsStream(),
Metal::UniformsStream(
AsPointer(constantBufferPackets.begin()), nullptr, constantBufferPackets.size(),
AsPointer(boundTextures.begin()), boundTextures.size()));
}
IMaterialBinder::SystemConstants::SystemConstants()
{
_lightNegativeDirection = Float3(0.f, 0.f, 1.f);
_lightColour = Float3(1.f, 1.f, 1.f);
_objectToWorld = Identity<Float4x4>();
}
}
<commit_msg>Suppressing some distracting InvalidAsset exceptions from the material inspector window<commit_after>// Copyright 2015 XLGAMES Inc.
//
// Distributed under the MIT License (See
// accompanying file "LICENSE" or the website
// http://www.opensource.org/licenses/mit-license.php)
#include "MaterialBinder.h"
#include "../../RenderCore/Metal/InputLayout.h"
#include "../../RenderCore/Metal/DeviceContext.h"
#include "../../RenderCore/Metal/State.h"
#include "../../RenderCore/Metal/Shader.h"
#include "../../RenderCore/Assets/DeferredShaderResource.h"
#include "../../RenderCore/Techniques/TechniqueMaterial.h"
#include "../../RenderCore/Techniques/TechniqueUtils.h"
#include "../../RenderCore/Techniques/ParsingContext.h"
#include "../../RenderCore/Techniques/CommonBindings.h"
#include "../../RenderCore/Techniques/PredefinedCBLayout.h"
#include "../../RenderCore/Assets/Material.h"
#include "../../RenderCore/Assets/AssetUtils.h"
#include "../../Assets/AssetUtils.h"
#include "../../Math/Transformations.h"
#include "../../Utility/StringFormat.h"
#include "../../Utility/StringUtils.h"
#include "../../RenderCore/DX11/Metal/IncludeDX11.h"
#include "../../RenderCore/DX11/Metal/DX11Utils.h"
#include <d3d11shader.h> // D3D11_SHADER_TYPE_DESC
namespace ToolsRig
{
IMaterialBinder::~IMaterialBinder() {}
///////////////////////////////////////////////////////////////////////////////////////////////////
static ParameterBox SetResHasParameters(
const ParameterBox& inputMatParameters, const ParameterBox& resBindings,
const ::Assets::DirectorySearchRules& searchRules)
{
static const auto DefaultNormalsTextureBindingHash = ParameterBox::MakeParameterNameHash("NormalsTexture");
// The "material parameters" ParameterBox should contain some "RES_HAS_..."
// settings. These tell the shader what resource bindings are available
// (and what are missing). We need to set these parameters according to our
// binding list
ParameterBox result = inputMatParameters;
for (auto param=resBindings.Begin(); !param.IsEnd(); ++param) {
result.SetParameter(StringMeld<64, utf8>() << "RES_HAS_" << param.Name(), 1);
if (param.HashName() == DefaultNormalsTextureBindingHash) {
auto resourceName = resBindings.GetString<::Assets::ResChar>(DefaultNormalsTextureBindingHash);
::Assets::ResChar resolvedName[MaxPath];
searchRules.ResolveFile(resolvedName, dimof(resolvedName), resourceName.c_str());
result.SetParameter((const utf8*)"RES_HAS_NormalsTexture_DXT",
RenderCore::Assets::IsDXTNormalMap(resolvedName));
}
}
return std::move(result);
}
RenderCore::Metal::ShaderProgram* MaterialBinder::Apply(
RenderCore::Metal::DeviceContext& metalContext,
RenderCore::Techniques::ParsingContext& parserContext,
unsigned techniqueIndex,
const RenderCore::Assets::ResolvedMaterial& mat,
const SystemConstants& sysConstants,
const ::Assets::DirectorySearchRules& searchRules,
const RenderCore::Metal::InputLayout& geoInputLayout)
{
using namespace RenderCore;
using namespace RenderCore::Techniques;
ParameterBox materialParameters = SetResHasParameters(mat._matParams, mat._bindings, searchRules);
TechniqueMaterial material(geoInputLayout, {}, materialParameters);
auto variation = material.FindVariation(parserContext, techniqueIndex, _shaderTypeName.c_str());
if (variation._shaderProgram == nullptr) {
return nullptr; // we can't render because we couldn't resolve a good shader variation
}
// we must bind the shader program & the bound layout
// but we're not using the BoundUniforms in the ResolvedShader object
metalContext.Bind(*variation._shaderProgram);
metalContext.Bind(*variation._boundLayout);
// Instead of using ResolvedShader::_boundUniforms, let's
// look at the reflection information for the shader program
// and assign each shader input to some reasonable value
BindConstantsAndResources(
metalContext, parserContext, mat,
sysConstants, searchRules, *variation._shaderProgram);
return variation._shaderProgram;
}
MaterialBinder::MaterialBinder(const ::Assets::ResChar shaderTypeName[])
: _shaderTypeName(shaderTypeName)
{}
MaterialBinder::~MaterialBinder() {}
///////////////////////////////////////////////////////////////////////////////////////////////////
static size_t WriteSystemVariable(
const char name[],
const IMaterialBinder::SystemConstants& constants,
UInt2 viewportDims,
void* destination, void* destinationEnd)
{
size_t size = size_t(destinationEnd) - size_t(destination);
if (!_stricmp(name, "SI_OutputDimensions") && size >= (sizeof(unsigned)*2)) {
((unsigned*)destination)[0] = viewportDims[0];
((unsigned*)destination)[1] = viewportDims[1];
return sizeof(unsigned)*2;
} else if (!_stricmp(name, "SI_NegativeLightDirection") && size >= sizeof(Float3)) {
*((Float3*)destination) = constants._lightNegativeDirection;
return sizeof(Float3);
} else if (!_stricmp(name, "SI_LightColor") && size >= sizeof(Float3)) {
*((Float3*)destination) = constants._lightColour;
return sizeof(Float3);
}
return 0;
}
static void WriteParameter(
RenderCore::SharedPkt& result,
const ParameterBox& constants,
ParameterBox::ParameterNameHash nameHash,
ID3D11ShaderReflectionVariable& reflectionVariable,
const D3D11_SHADER_VARIABLE_DESC& variableDesc,
unsigned bufferSize)
{
auto type = reflectionVariable.GetType();
D3D11_SHADER_TYPE_DESC typeDesc;
auto hresult = type->GetDesc(&typeDesc);
if (SUCCEEDED(hresult)) {
//
// Finally, copy whatever the material object
// is, into the destination position in the
// constant buffer;
//
auto impliedType = RenderCore::Metal::GetType(typeDesc);
assert((variableDesc.StartOffset + impliedType.GetSize()) <= bufferSize);
if ((variableDesc.StartOffset + impliedType.GetSize()) <= bufferSize) {
if (!result.size()) {
result = RenderCore::MakeSharedPktSize(bufferSize);
std::fill((uint8*)result.begin(), (uint8*)result.end(), 0);
}
constants.GetParameter(
nameHash,
PtrAdd(result.begin(), variableDesc.StartOffset),
impliedType);
}
}
}
static std::vector<std::pair<uint64, RenderCore::Metal::ConstantBufferPacket>>
BuildMaterialConstants(
ID3D::ShaderReflection& reflection,
const ParameterBox& constants,
const IMaterialBinder::SystemConstants& systemConstantsContext,
UInt2 viewportDims)
{
//
// Find the cbuffers, and look for the variables
// within. Attempt to fill those values with the appropriate values
// from the current previewing material state
//
std::vector<std::pair<uint64, RenderCore::Metal::ConstantBufferPacket>> finalResult;
const auto& cbLayout = ::Assets::GetAssetDep<RenderCore::Techniques::PredefinedCBLayout>(
"game/xleres/BasicMaterialConstants.txt");
D3D11_SHADER_DESC shaderDesc;
reflection.GetDesc(&shaderDesc);
for (unsigned c=0; c<shaderDesc.BoundResources; ++c) {
D3D11_SHADER_INPUT_BIND_DESC bindDesc;
reflection.GetResourceBindingDesc(c, &bindDesc);
if (bindDesc.Type == D3D10_SIT_CBUFFER) {
auto cbuffer = reflection.GetConstantBufferByName(bindDesc.Name);
if (cbuffer) {
D3D11_SHADER_BUFFER_DESC bufferDesc;
HRESULT hresult = cbuffer->GetDesc(&bufferDesc);
if (SUCCEEDED(hresult)) {
RenderCore::SharedPkt result;
for (unsigned c=0; c<bufferDesc.Variables; ++c) {
auto reflectionVariable = cbuffer->GetVariableByIndex(c);
D3D11_SHADER_VARIABLE_DESC variableDesc;
hresult = reflectionVariable->GetDesc(&variableDesc);
if (SUCCEEDED(hresult)) {
//
// If the variable is within our table of
// material parameter values, then copy that
// value into the appropriate place in the cbuffer.
//
// However, note that this may require a cast sometimes
//
auto nameHash = ParameterBox::MakeParameterNameHash(variableDesc.Name);
if (constants.HasParameter(nameHash)) {
WriteParameter(
result, constants, nameHash, *reflectionVariable,
variableDesc, bufferDesc.Size);
} else if (cbLayout._defaults.HasParameter(nameHash)) {
WriteParameter(
result, cbLayout._defaults, nameHash, *reflectionVariable,
variableDesc, bufferDesc.Size);
} else {
if (!result.size()) {
char buffer[4096];
if (size_t size = WriteSystemVariable(
variableDesc.Name, systemConstantsContext, viewportDims,
buffer, PtrAdd(buffer, std::min(sizeof(buffer), (size_t)(bufferDesc.Size - variableDesc.StartOffset))))) {
result = RenderCore::MakeSharedPktSize(bufferDesc.Size);
std::fill((uint8*)result.begin(), (uint8*)result.end(), 0);
XlCopyMemory(PtrAdd(result.begin(), variableDesc.StartOffset), buffer, size);
}
} else {
WriteSystemVariable(
variableDesc.Name, systemConstantsContext, viewportDims,
PtrAdd(result.begin(), variableDesc.StartOffset), result.end());
}
}
}
}
if (result.size()) {
finalResult.push_back(
std::make_pair(Hash64(bindDesc.Name), std::move(result)));
}
}
}
}
}
return finalResult;
}
static std::vector<const RenderCore::Metal::ShaderResourceView*>
BuildBoundTextures(
RenderCore::Metal::BoundUniforms& boundUniforms,
RenderCore::Metal::ShaderProgram& shaderProgram,
const ParameterBox& bindings,
const Assets::DirectorySearchRules& searchRules)
{
using namespace RenderCore;
std::vector<const Metal::ShaderResourceView*> result;
std::vector<uint64> alreadyBound;
//
// For each entry in our resource binding set, we're going
// to register a binding in the BoundUniforms, and find
// the associated shader resource view.
// For any shader resources that are used by the shader, but
// not bound to anything -- we need to assign them to the
// default objects.
//
const CompiledShaderByteCode* shaderCode[] = {
&shaderProgram.GetCompiledVertexShader(),
&shaderProgram.GetCompiledPixelShader(),
shaderProgram.GetCompiledGeometryShader(),
};
for (unsigned s=0; s<dimof(shaderCode); ++s) {
if (!shaderCode[s]) continue;
auto reflection = Metal::CreateReflection(*shaderCode[s]);
D3D11_SHADER_DESC shaderDesc;
reflection->GetDesc(&shaderDesc);
for (unsigned c=0; c<shaderDesc.BoundResources; ++c) {
D3D11_SHADER_INPUT_BIND_DESC bindDesc;
reflection->GetResourceBindingDesc(c, &bindDesc);
if (bindDesc.Type == D3D10_SIT_TEXTURE) {
// skip "NormalsFittingTexture" -- system use
if (!XlCompareString(bindDesc.Name, "NormalsFittingTexture")) continue;
if (!XlCompareString(bindDesc.Name, "SkyReflectionTexture[0]")) continue;
if (!XlCompareString(bindDesc.Name, "SkyReflectionTexture[1]")) continue;
if (!XlCompareString(bindDesc.Name, "SkyReflectionTexture[2]")) continue;
if (!XlCompareString(bindDesc.Name, "GGXTable")) continue;
auto str = bindings.GetString<::Assets::ResChar>(ParameterBox::MakeParameterNameHash(bindDesc.Name));
bool isDefaultRes = false;
if (str.empty()) {
// It's not mentioned in the material resources. try to look
// for a default resource for this bind point
str = ::Assets::rstring("game/xleres/DefaultResources/") + bindDesc.Name + ".dds";
isDefaultRes = true;
}
auto bindingHash = Hash64(bindDesc.Name, &bindDesc.Name[XlStringLen(bindDesc.Name)]);
if (std::find(alreadyBound.cbegin(), alreadyBound.cend(), bindingHash) != alreadyBound.cend()) {
continue;
}
alreadyBound.push_back(bindingHash);
if (!str.empty()) {
TRY {
::Assets::ResChar resolvedFile[MaxPath];
searchRules.ResolveFile(
resolvedFile, dimof(resolvedFile),
str.c_str());
// check DoesFileExist (but only for default resources)
if (!isDefaultRes || DoesFileExist(resolvedFile)) {
const RenderCore::Assets::DeferredShaderResource& texture =
::Assets::GetAssetDep<RenderCore::Assets::DeferredShaderResource>(resolvedFile);
result.push_back(&texture.GetShaderResource());
boundUniforms.BindShaderResource(bindingHash, unsigned(result.size()-1), 1);
}
}
CATCH (const ::Assets::Exceptions::InvalidAsset&) {}
CATCH_END
}
} else if (bindDesc.Type == D3D10_SIT_SAMPLER) {
// we should also bind samplers to something
// reasonable, also...
}
}
}
return std::move(result);
}
void IMaterialBinder::BindConstantsAndResources(
RenderCore::Metal::DeviceContext& metalContext,
RenderCore::Techniques::ParsingContext& parsingContext,
const RenderCore::Assets::ResolvedMaterial& mat,
const SystemConstants& sysConstants,
const ::Assets::DirectorySearchRules& searchRules,
RenderCore::Metal::ShaderProgram& shaderProgram)
{
using namespace RenderCore;
//
// Constants / Resources
//
Metal::ViewportDesc currentViewport(metalContext);
auto materialConstants = BuildMaterialConstants(
*Metal::CreateReflection(shaderProgram.GetCompiledPixelShader()),
mat._constants, sysConstants,
UInt2(unsigned(currentViewport.Width), unsigned(currentViewport.Height)));
Metal::BoundUniforms boundLayout(shaderProgram);
Techniques::TechniqueContext::BindGlobalUniforms(boundLayout);
std::vector<RenderCore::Metal::ConstantBufferPacket> constantBufferPackets;
constantBufferPackets.push_back(
Techniques::MakeLocalTransformPacket(
sysConstants._objectToWorld, ExtractTranslation(parsingContext.GetProjectionDesc()._cameraToWorld)));
boundLayout.BindConstantBuffer(Techniques::ObjectCB::LocalTransform, 0, 1);
for (auto i=materialConstants.cbegin(); i!=materialConstants.cend(); ++i) {
boundLayout.BindConstantBuffer(i->first, unsigned(constantBufferPackets.size()), 1);
constantBufferPackets.push_back(std::move(i->second));
}
auto boundTextures = BuildBoundTextures(
boundLayout, shaderProgram,
mat._bindings, searchRules);
boundLayout.Apply(
metalContext,
parsingContext.GetGlobalUniformsStream(),
Metal::UniformsStream(
AsPointer(constantBufferPackets.begin()), nullptr, constantBufferPackets.size(),
AsPointer(boundTextures.begin()), boundTextures.size()));
}
IMaterialBinder::SystemConstants::SystemConstants()
{
_lightNegativeDirection = Float3(0.f, 0.f, 1.f);
_lightColour = Float3(1.f, 1.f, 1.f);
_objectToWorld = Identity<Float4x4>();
}
}
<|endoftext|> |
<commit_before>
#include "condor_file_buffer.h"
#include "condor_error.h"
#include "file_state.h"
/*
A CondorChunk records a variable-sized piece of data in a buffer.
A linked list of CondorChunks is kept as the recently-used data.
*/
class CondorChunk {
public:
CondorChunk( int b, int s ) {
begin = b;
size = s;
last_used = 0;
dirty = 0;
next = 0;
data = new char[size];
}
~CondorChunk() {
delete [] data;
}
int begin;
int size;
int last_used;
char *data;
int dirty;
CondorChunk *next;
};
/*
Take two CondorChunks and combine them into one.
*/
static CondorChunk * combine( CondorChunk *a, CondorChunk *b )
{
int begin, end;
CondorChunk *r;
begin = MIN(a->begin,b->begin);
end = MAX(a->begin+a->size,b->begin+b->size);
r = new CondorChunk(begin,end-begin);
r->dirty = a->dirty || b->dirty;
r->last_used = MAX( a->last_used, b->last_used );
if( a->dirty && !b->dirty ) {
memcpy( &r->data[b->begin-begin], b->data, b->size );
memcpy( &r->data[a->begin-begin], a->data, a->size );
} else {
memcpy( &r->data[a->begin-begin], a->data, a->size );
memcpy( &r->data[b->begin-begin], b->data, b->size );
}
delete a;
delete b;
return r;
}
/*
Return true if two chunks overlap and _must_ be combined
*/
static int overlaps( CondorChunk *a, CondorChunk *b )
{
return
(
(a->begin>=b->begin) &&
(a->begin<(b->begin+b->size))
) || (
(b->begin>=a->begin) &&
(b->begin<(a->begin+a->size))
);
}
/*
Return true if two chunks are adjacent and _could_ be combined
*/
static int adjacent( CondorChunk *a, CondorChunk *b )
{
return
( (a->begin+a->size)==b->begin )
||
( (b->begin+b->size)==a->begin )
;
}
/*
Return true if this chunk contains this integer offset
*/
static int contains( CondorChunk *c, int position )
{
return
(c->begin<=position)
&&
((c->begin+c->size)>position)
;
}
/*
Return true if these two chunks _ought_ to be combined.
Overlapping chunks _must_ be combined, and combining is
only a win for adjacent dirty blocks if the resulting block
is smaller than the desired block size.
*/
static int should_combine( CondorChunk *a, CondorChunk *b )
{
return
overlaps(a,b)
||
( a->dirty
&&
b->dirty
&&
( (a->size+b->size) < FileTab->get_buffer_block_size() )
&&
adjacent(a,b)
)
;
}
/*
Take a list of chunks and add an additional chunk, either by absorbing
and combining, or by simply appending the chunk to the list.
*/
static CondorChunk * absorb( CondorChunk *head, CondorChunk *c )
{
CondorChunk *next, *combined;
if(!head) return c;
if( should_combine( head, c ) ) {
next = head->next;
combined = combine( head, c );
return absorb( next, combined );
} else {
head->next = absorb( head->next, c );
return head;
}
}
/*
Most of the operations to be done on a buffer simply involve
passing the operation on to the original file.
*/
CondorFileBuffer::CondorFileBuffer( CondorFile *o )
{
original = o;
head = 0;
time = 0;
size = 0;
}
CondorFileBuffer::~CondorFileBuffer()
{
delete original;
}
int CondorFileBuffer::open( const char *path, int flags, int mode )
{
int result;
result = original->open(path,flags,mode);
size = original->get_size();
return result;
}
int CondorFileBuffer::close()
{
flush(1);
return original->close();
}
/*
Read data from this buffer. Attempt to satisfy from the data in memory,
but resort to the original file object if necessary.
*/
int CondorFileBuffer::read(int offset, char *data, int length)
{
CondorChunk *c=0;
int piece=0;
int bytes_read=0;
int hole_top;
// If the user is attempting to read past the end
// of the file, chop off that access here.
if((offset+length)>size) {
length = size-offset;
}
while(length>0) {
// hole_top keeps track of the lowest starting data point
// in case we have created a virtual hole
hole_top = MIN( size, offset+length );
// Scan through all the data chunks.
// If one overlaps with the beginning of the
// request, then copy that data.
for( c=head; c; c=c->next ) {
if( contains(c,offset) ) {
piece = MIN(c->begin+c->size-offset,length);
memcpy(data,&c->data[offset-c->begin],piece);
offset += piece;
data += piece;
length -= piece;
bytes_read += piece;
c->last_used = time++;
break;
} else {
if((c->begin<hole_top)&&(c->begin>offset)) {
hole_top = c->begin;
}
}
}
// If that worked, try it again.
if(c) continue;
// Now, consider the logical size of the buffer file
// and the size of the actual file. If we are less
// than the former, but greater than the latter, simply
// fill the hole with zeroes and continue above.
piece = hole_top-offset;
if( offset<size && offset>=original->get_size() ) {
memset(data,0,piece);
offset += piece;
data += piece;
length -= piece;
bytes_read += piece;
continue;
}
// Otherwise, make a new chunk. Try to read a whole block
c = new CondorChunk(offset,FileTab->get_buffer_block_size());
piece = original->read(offset,c->data,c->size);
if(piece<0) {
delete c;
if(bytes_read==0) bytes_read=-1;
break;
} else if(piece==0) {
delete c;
break;
} else {
c->size = piece;
head = absorb( head, c );
}
}
trim();
return bytes_read;
}
/*
When writing, simply create a new chunk and add it to the list.
If the resulting list is larger than the required buffer size,
select a block to write to disk.
*/
int CondorFileBuffer::write(int offset, char *data, int length)
{
CondorChunk *c=0;
c = new CondorChunk(offset,length);
memcpy(c->data,data,length);
c->dirty = 1;
c->last_used = time++;
head = absorb( head, c );
trim();
if((offset+length)>get_size()) {
set_size(offset+length);
}
return length;
}
int CondorFileBuffer::fcntl( int cmd, int arg )
{
return original->fcntl(cmd,arg);
}
int CondorFileBuffer::ioctl( int cmd, int arg )
{
return original->ioctl(cmd,arg);
}
int CondorFileBuffer::ftruncate( size_t length )
{
flush(1);
size = length;
return original->ftruncate(length);
}
int CondorFileBuffer::fsync()
{
flush(0);
return original->fsync();
}
void CondorFileBuffer::checkpoint()
{
flush(0);
original->checkpoint();
}
void CondorFileBuffer::suspend()
{
flush(0);
original->suspend();
}
void CondorFileBuffer::resume( int count )
{
original->resume( count );
}
int CondorFileBuffer::is_readable()
{
return original->is_readable();
}
int CondorFileBuffer::is_writeable()
{
return original->is_writeable();
}
void CondorFileBuffer::set_size( size_t s )
{
size = s;
}
int CondorFileBuffer::get_size()
{
return size;
}
char * CondorFileBuffer::get_kind()
{
return "buffered file";
}
char * CondorFileBuffer::get_name()
{
return original->get_name();
}
int CondorFileBuffer::attach( int fd, char *name, int r, int w )
{
return -1;
}
int CondorFileBuffer::map_fd_hack()
{
return original->map_fd_hack();
}
int CondorFileBuffer::local_access_hack()
{
return original->local_access_hack();
}
/*
Trim this buffer down to size. As long as it is too big,
select the block that is least recently used, and write it out.
*/
void CondorFileBuffer::trim()
{
CondorChunk *best_chunk,*i;
int space_used;
while(1) {
space_used = 0;
best_chunk = head;
for( i=head; i; i=i->next ) {
if( i->last_used < best_chunk->last_used ) {
best_chunk = i;
}
space_used += i->size;
}
if( space_used <= FileTab->get_buffer_size() ) return;
evict( best_chunk );
}
}
void CondorFileBuffer::flush( int deallocate )
{
CondorChunk *c,*n;
for(c=head;c;c=n) {
clean(c);
n = c->next;
if(deallocate) {
delete c;
}
}
if(deallocate) head=0;
}
/*
Clean this chunk by writing it out to disk.
*/
void CondorFileBuffer::clean( CondorChunk *c )
{
if(c && c->dirty) {
int result = original->write(c->begin,c->data,c->size);
if(!result) _condor_error_retry("Unable to write buffered data to %s! (%s)",original->get_name(),strerror(errno));
c->dirty = 0;
}
}
/*
Evict this block by cleaning it, then removing it.
*/
void CondorFileBuffer::evict( CondorChunk *c )
{
CondorChunk *i;
clean(c);
if( c==head ) {
head = c->next;
delete c;
} else {
for( i=head; i; i=i->next ) {
if( i->next==c ) {
i->next = c->next;
delete c;
}
}
}
}
<commit_msg>Changed decision of when to combine chunks. Now combines dirty chunks if they are <= to the block size.<commit_after>
#include "condor_file_buffer.h"
#include "condor_error.h"
#include "file_state.h"
/*
A CondorChunk records a variable-sized piece of data in a buffer.
A linked list of CondorChunks is kept as the recently-used data.
*/
class CondorChunk {
public:
CondorChunk( int b, int s ) {
begin = b;
size = s;
last_used = 0;
dirty = 0;
next = 0;
data = new char[size];
}
~CondorChunk() {
delete [] data;
}
int begin;
int size;
int last_used;
char *data;
int dirty;
CondorChunk *next;
};
/*
Take two CondorChunks and combine them into one.
*/
static CondorChunk * combine( CondorChunk *a, CondorChunk *b )
{
int begin, end;
CondorChunk *r;
begin = MIN(a->begin,b->begin);
end = MAX(a->begin+a->size,b->begin+b->size);
r = new CondorChunk(begin,end-begin);
r->dirty = a->dirty || b->dirty;
r->last_used = MAX( a->last_used, b->last_used );
if( a->dirty && !b->dirty ) {
memcpy( &r->data[b->begin-begin], b->data, b->size );
memcpy( &r->data[a->begin-begin], a->data, a->size );
} else {
memcpy( &r->data[a->begin-begin], a->data, a->size );
memcpy( &r->data[b->begin-begin], b->data, b->size );
}
delete a;
delete b;
return r;
}
/*
Return true if two chunks overlap and _must_ be combined
*/
static int overlaps( CondorChunk *a, CondorChunk *b )
{
return
(
(a->begin>=b->begin) &&
(a->begin<(b->begin+b->size))
) || (
(b->begin>=a->begin) &&
(b->begin<(a->begin+a->size))
);
}
/*
Return true if two chunks are adjacent and _could_ be combined
*/
static int adjacent( CondorChunk *a, CondorChunk *b )
{
return
( (a->begin+a->size)==b->begin )
||
( (b->begin+b->size)==a->begin )
;
}
/*
Return true if this chunk contains this integer offset
*/
static int contains( CondorChunk *c, int position )
{
return
(c->begin<=position)
&&
((c->begin+c->size)>position)
;
}
/*
Return true if these two chunks _ought_ to be combined.
Overlapping chunks _must_ be combined, and combining is
only a win for adjacent dirty blocks if the resulting block
is smaller than the desired block size.
*/
static int should_combine( CondorChunk *a, CondorChunk *b )
{
return
overlaps(a,b)
||
( a->dirty
&&
b->dirty
&&
( (a->size+b->size) <= FileTab->get_buffer_block_size() )
&&
adjacent(a,b)
)
;
}
/*
Take a list of chunks and add an additional chunk, either by absorbing
and combining, or by simply appending the chunk to the list.
*/
static CondorChunk * absorb( CondorChunk *head, CondorChunk *c )
{
CondorChunk *next, *combined;
if(!head) return c;
if( should_combine( head, c ) ) {
next = head->next;
combined = combine( head, c );
return absorb( next, combined );
} else {
head->next = absorb( head->next, c );
return head;
}
}
/*
Most of the operations to be done on a buffer simply involve
passing the operation on to the original file.
*/
CondorFileBuffer::CondorFileBuffer( CondorFile *o )
{
original = o;
head = 0;
time = 0;
size = 0;
}
CondorFileBuffer::~CondorFileBuffer()
{
delete original;
}
int CondorFileBuffer::open( const char *path, int flags, int mode )
{
int result;
result = original->open(path,flags,mode);
size = original->get_size();
return result;
}
int CondorFileBuffer::close()
{
flush(1);
return original->close();
}
/*
Read data from this buffer. Attempt to satisfy from the data in memory,
but resort to the original file object if necessary.
*/
int CondorFileBuffer::read(int offset, char *data, int length)
{
CondorChunk *c=0;
int piece=0;
int bytes_read=0;
int hole_top;
// If the user is attempting to read past the end
// of the file, chop off that access here.
if((offset+length)>size) {
length = size-offset;
}
while(length>0) {
// hole_top keeps track of the lowest starting data point
// in case we have created a virtual hole
hole_top = MIN( size, offset+length );
// Scan through all the data chunks.
// If one overlaps with the beginning of the
// request, then copy that data.
for( c=head; c; c=c->next ) {
if( contains(c,offset) ) {
piece = MIN(c->begin+c->size-offset,length);
memcpy(data,&c->data[offset-c->begin],piece);
offset += piece;
data += piece;
length -= piece;
bytes_read += piece;
c->last_used = time++;
break;
} else {
if((c->begin<hole_top)&&(c->begin>offset)) {
hole_top = c->begin;
}
}
}
// If that worked, try it again.
if(c) continue;
// Now, consider the logical size of the buffer file
// and the size of the actual file. If we are less
// than the former, but greater than the latter, simply
// fill the hole with zeroes and continue above.
piece = hole_top-offset;
if( offset<size && offset>=original->get_size() ) {
memset(data,0,piece);
offset += piece;
data += piece;
length -= piece;
bytes_read += piece;
continue;
}
// Otherwise, make a new chunk. Try to read a whole block
c = new CondorChunk(offset,FileTab->get_buffer_block_size());
piece = original->read(offset,c->data,c->size);
if(piece<0) {
delete c;
if(bytes_read==0) bytes_read=-1;
break;
} else if(piece==0) {
delete c;
break;
} else {
c->size = piece;
head = absorb( head, c );
}
}
trim();
return bytes_read;
}
/*
When writing, simply create a new chunk and add it to the list.
If the resulting list is larger than the required buffer size,
select a block to write to disk.
*/
int CondorFileBuffer::write(int offset, char *data, int length)
{
CondorChunk *c=0;
c = new CondorChunk(offset,length);
memcpy(c->data,data,length);
c->dirty = 1;
c->last_used = time++;
head = absorb( head, c );
trim();
if((offset+length)>get_size()) {
set_size(offset+length);
}
return length;
}
int CondorFileBuffer::fcntl( int cmd, int arg )
{
return original->fcntl(cmd,arg);
}
int CondorFileBuffer::ioctl( int cmd, int arg )
{
return original->ioctl(cmd,arg);
}
int CondorFileBuffer::ftruncate( size_t length )
{
flush(1);
size = length;
return original->ftruncate(length);
}
int CondorFileBuffer::fsync()
{
flush(0);
return original->fsync();
}
void CondorFileBuffer::checkpoint()
{
flush(0);
original->checkpoint();
}
void CondorFileBuffer::suspend()
{
flush(0);
original->suspend();
}
void CondorFileBuffer::resume( int count )
{
original->resume( count );
}
int CondorFileBuffer::is_readable()
{
return original->is_readable();
}
int CondorFileBuffer::is_writeable()
{
return original->is_writeable();
}
void CondorFileBuffer::set_size( size_t s )
{
size = s;
}
int CondorFileBuffer::get_size()
{
return size;
}
char * CondorFileBuffer::get_kind()
{
return "buffered file";
}
char * CondorFileBuffer::get_name()
{
return original->get_name();
}
int CondorFileBuffer::attach( int fd, char *name, int r, int w )
{
return -1;
}
int CondorFileBuffer::map_fd_hack()
{
return original->map_fd_hack();
}
int CondorFileBuffer::local_access_hack()
{
return original->local_access_hack();
}
/*
Trim this buffer down to size. As long as it is too big,
select the block that is least recently used, and write it out.
*/
void CondorFileBuffer::trim()
{
CondorChunk *best_chunk,*i;
int space_used;
while(1) {
space_used = 0;
best_chunk = head;
for( i=head; i; i=i->next ) {
if( i->last_used < best_chunk->last_used ) {
best_chunk = i;
}
space_used += i->size;
}
if( space_used <= FileTab->get_buffer_size() ) return;
evict( best_chunk );
}
}
void CondorFileBuffer::flush( int deallocate )
{
CondorChunk *c,*n;
for(c=head;c;c=n) {
clean(c);
n = c->next;
if(deallocate) {
delete c;
}
}
if(deallocate) head=0;
}
/*
Clean this chunk by writing it out to disk.
*/
void CondorFileBuffer::clean( CondorChunk *c )
{
if(c && c->dirty) {
int result = original->write(c->begin,c->data,c->size);
if(!result) _condor_error_retry("Unable to write buffered data to %s! (%s)",original->get_name(),strerror(errno));
c->dirty = 0;
}
}
/*
Evict this block by cleaning it, then removing it.
*/
void CondorFileBuffer::evict( CondorChunk *c )
{
CondorChunk *i;
clean(c);
if( c==head ) {
head = c->next;
delete c;
} else {
for( i=head; i; i=i->next ) {
if( i->next==c ) {
i->next = c->next;
delete c;
}
}
}
}
<|endoftext|> |
<commit_before>// @(#)root/gpad:$Id$
// Author: Rene Brun 01/07/96
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "Riostream.h"
#include "TROOT.h"
#include "TBox.h"
#include "TGroupButton.h"
#include "TVirtualX.h"
#include "TDialogCanvas.h"
#include "TCanvas.h"
#include "TText.h"
#include "TInterpreter.h"
#include "TTimer.h"
#include <string.h>
ClassImp(TGroupButton)
//______________________________________________________________________________
//
// A TGroupButton object is a specialized TButton used in a group of Buttons.
// When a button from a group of TGroupButtons is selected, all other buttons
// from the group with the same name are disabled.
//
// For examples of use of TGroupButton objects, see:
// TAttFillCanvas, TAttLineCanvas, TAttTextCanvas and TAttMarkerCanvas.
//______________________________________________________________________________
TGroupButton::TGroupButton(): TButton()
{
// GroupButton default constructor.
SetFraming();
}
//______________________________________________________________________________
TGroupButton::TGroupButton(const char *groupname, const char *title, const char *method, Double_t x1, Double_t y1,Double_t x2, Double_t y2)
:TButton(title,method,x1,y1,x2,y2)
{
// GroupButton normal constructor.
SetName((char*)groupname);
SetFraming();
}
//______________________________________________________________________________
TGroupButton::~TGroupButton()
{
// GroupButton default destructor.
}
//______________________________________________________________________________
void TGroupButton::DisplayColorTable(const char *action, Double_t x0, Double_t y0, Double_t wc, Double_t hc)
{
// Display Color Table in an attribute canvas.
TGroupButton *colorpad;
Int_t i, j;
Int_t color;
Double_t xlow, ylow, hs, ws;
// draw colortable buttons
hs = hc/5;
ws = wc/10;
char command[32];
for (i=0;i<10;i++) {
xlow = x0 + ws*i;
for (j=0;j<5;j++) {
ylow = y0 + hs*j;
color = 10*j + i + 1;
snprintf(command,32,"%s(%d)",action,10*j+i+1);
colorpad = new TGroupButton("Color","",command,xlow, ylow, xlow+0.9*ws, ylow+0.9*hs);
colorpad->SetFillColor(color);
colorpad->SetBorderSize(1);
if (i == 0 && j == 0) colorpad->SetBorderMode(-1);
colorpad->Draw();
}
}
}
//______________________________________________________________________________
void TGroupButton::ExecuteAction()
{
// Execute action of this button.
//
// If an object has been selected before executing the APPLY button
// in the control canvas, The member function and its parameters
// for this object is executed via the interpreter.
TVirtualPad *pad;
char line[128];
strlcpy(line,GetMethod(),128);
char *method = line;
if(!strlen(line)) return;
char *params = strchr(method,'(');
if (params) {
*params = 0;
params++;
char *end = strrchr(params,')');
if (end) *end = 0;
}
TDialogCanvas *canvas = (TDialogCanvas*)GetMother();
TObject *obj = canvas->GetRefObject();
if (!obj) return;
if (strcmp(method,"PIXELS")) {
obj->Execute(method,params);
} else {
TText *text = (TText*)GetListOfPrimitives()->First();
Int_t npixels = Int_t((YtoPixel(0) - YtoPixel(1))*text->GetTextSize());
Double_t dy;
pad = gROOT->GetSelectedPad();
if (!params) return;
Int_t nmax = (Int_t)(params-method);
if (obj->InheritsFrom("TPaveLabel")) {
TBox *pl = (TBox*)obj;
dy = pad->AbsPixeltoY(0) - pad->AbsPixeltoY(npixels);
snprintf(params,nmax,"%f",dy/(pl->GetY2() - pl->GetY1()));
obj->Execute("SetTextSize",params);
} else {
if (obj->InheritsFrom("TPave")) {
dy = pad->AbsPixeltoY(0) - pad->AbsPixeltoY(npixels);
snprintf(params,nmax,"%f",dy/(pad->GetY2() - pad->GetY1()));
obj->Execute("SetTextSize",params);
} else {
snprintf(params,nmax,"%d",npixels);
obj->Execute("SetTextSizePixels",params);
}
}
}
}
//______________________________________________________________________________
void TGroupButton::ExecuteEvent(Int_t event, Int_t px, Int_t py)
{
// Execute action corresponding to one event.
//
// This member function is called when a Button object is clicked.
if (fMother->IsEditable()) {
TPad::ExecuteEvent(event,px,py);
return;
}
TIter next(gPad->GetCanvas()->GetListOfPrimitives());
TObject *obj;
TGroupButton *button;
TPad *pad;
TDialogCanvas *canvas;
switch (event) {
case kButton1Down:
case kMouseMotion:
break;
case kButton1Motion:
break;
case kButton1Up:
//Clicked on APPLY button?
if (!strcasecmp(GetName(),"APPLY")) {
canvas = (TDialogCanvas*)GetMother();
if (!strcasecmp(GetTitle(),"CLOSE")) {
canvas->Close();
return;
}
pad = canvas->GetRefPad();
if (pad) pad->GetCanvas()->FeedbackMode(kFALSE);
canvas->Apply(GetTitle()); //just in case the apply button executes some code
if (pad) {
pad->Modified(kTRUE);
pad->Update();
}
break;
}
//Unset other buttons with same name
while ((obj = next())) {
if (obj == this) continue;
if (obj->InheritsFrom(TGroupButton::Class())) {
button = (TGroupButton*)obj;
if (!strcmp(button->GetName(),GetName())) {
if (button->GetBorderMode() < 0) {
button->SetBorderMode(1);
button->Modified();
}
}
}
}
//Set button on
SetBorderMode(-1);
Modified();
gPad->GetCanvas()->Modified();
gPad->Update();
break;
}
}
//______________________________________________________________________________
void TGroupButton::SavePrimitive(ostream &out, Option_t * /*= ""*/)
{
// Save primitive as a C++ statement(s) on output stream out
TPad *padsav = (TPad*)gPad;
char quote = '"';
if (gROOT->ClassSaved(TGroupButton::Class())) {
out<<" ";
} else {
out<<" TGroupButton *";
}
out<<"button = new TGroupButton("<<quote<<GetName()<<quote<<", "<<quote<<GetTitle()
<<quote<<","<<quote<<GetMethod()<<quote
<<","<<fXlowNDC
<<","<<fYlowNDC
<<","<<fXlowNDC+fWNDC
<<","<<fYlowNDC+fHNDC
<<");"<<endl;
SaveFillAttributes(out,"button",0,1001);
SaveLineAttributes(out,"button",1,1,1);
SaveTextAttributes(out,"button",22,0,1,62,.75);
if (GetBorderSize() != 2) {
out<<" button->SetBorderSize("<<GetBorderSize()<<");"<<endl;
}
if (GetBorderMode() != 1) {
out<<" button->SetBorderMode("<<GetBorderMode()<<");"<<endl;
}
out<<" button->Draw();"<<endl;
out<<" button->cd();"<<endl;
TIter next(GetListOfPrimitives());
TObject *obj = next(); //do not save first primitive
while ((obj = next()))
obj->SavePrimitive(out, (Option_t *)next.GetOption());
out<<" "<<padsav->GetName()<<"->cd();"<<endl;
padsav->cd();
}
<commit_msg>Fix Coverty report #33226<commit_after>// @(#)root/gpad:$Id$
// Author: Rene Brun 01/07/96
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "Riostream.h"
#include "TROOT.h"
#include "TBox.h"
#include "TGroupButton.h"
#include "TVirtualX.h"
#include "TDialogCanvas.h"
#include "TCanvas.h"
#include "TText.h"
#include "TInterpreter.h"
#include "TTimer.h"
#include <string.h>
ClassImp(TGroupButton)
//______________________________________________________________________________
//
// A TGroupButton object is a specialized TButton used in a group of Buttons.
// When a button from a group of TGroupButtons is selected, all other buttons
// from the group with the same name are disabled.
//
// For examples of use of TGroupButton objects, see:
// TAttFillCanvas, TAttLineCanvas, TAttTextCanvas and TAttMarkerCanvas.
//______________________________________________________________________________
TGroupButton::TGroupButton(): TButton()
{
// GroupButton default constructor.
SetFraming();
}
//______________________________________________________________________________
TGroupButton::TGroupButton(const char *groupname, const char *title, const char *method, Double_t x1, Double_t y1,Double_t x2, Double_t y2)
:TButton(title,method,x1,y1,x2,y2)
{
// GroupButton normal constructor.
SetName((char*)groupname);
SetFraming();
}
//______________________________________________________________________________
TGroupButton::~TGroupButton()
{
// GroupButton default destructor.
}
//______________________________________________________________________________
void TGroupButton::DisplayColorTable(const char *action, Double_t x0, Double_t y0, Double_t wc, Double_t hc)
{
// Display Color Table in an attribute canvas.
TGroupButton *colorpad;
Int_t i, j;
Int_t color;
Double_t xlow, ylow, hs, ws;
// draw colortable buttons
hs = hc/5;
ws = wc/10;
char command[32];
for (i=0;i<10;i++) {
xlow = x0 + ws*i;
for (j=0;j<5;j++) {
ylow = y0 + hs*j;
color = 10*j + i + 1;
snprintf(command,32,"%s(%d)",action,10*j+i+1);
colorpad = new TGroupButton("Color","",command,xlow, ylow, xlow+0.9*ws, ylow+0.9*hs);
colorpad->SetFillColor(color);
colorpad->SetBorderSize(1);
if (i == 0 && j == 0) colorpad->SetBorderMode(-1);
colorpad->Draw();
}
}
}
//______________________________________________________________________________
void TGroupButton::ExecuteAction()
{
// Execute action of this button.
//
// If an object has been selected before executing the APPLY button
// in the control canvas, The member function and its parameters
// for this object is executed via the interpreter.
TVirtualPad *pad;
char line[128];
strlcpy(line,GetMethod(),128);
char *method = line;
if(!strlen(line)) return;
char *params = strchr(method,'(');
if (params) {
*params = 0;
params++;
char *end = strrchr(params,')');
if (end) *end = 0;
}
TDialogCanvas *canvas = (TDialogCanvas*)GetMother();
TObject *obj = canvas->GetRefObject();
if (!obj) return;
if (strcmp(method,"PIXELS")) {
obj->Execute(method,params);
} else {
TText *text = (TText*)GetListOfPrimitives()->First();
Int_t npixels = Int_t((YtoPixel(0) - YtoPixel(1))*text->GetTextSize());
Double_t dy;
pad = gROOT->GetSelectedPad();
if (!params) return;
Int_t nmax = (Int_t)(params-method);
if (obj->InheritsFrom("TPaveLabel")) {
TBox *pl = (TBox*)obj;
dy = pad->AbsPixeltoY(0) - pad->AbsPixeltoY(npixels);
snprintf(params,nmax,"%f",dy/(pl->GetY2() - pl->GetY1()));
obj->Execute("SetTextSize",params);
} else {
if (obj->InheritsFrom("TPave")) {
dy = pad->AbsPixeltoY(0) - pad->AbsPixeltoY(npixels);
snprintf(params,nmax,"%f",dy/(pad->GetY2() - pad->GetY1()));
obj->Execute("SetTextSize",params);
} else {
snprintf(params,nmax,"%d",npixels);
obj->Execute("SetTextSizePixels",params);
}
}
}
}
//______________________________________________________________________________
void TGroupButton::ExecuteEvent(Int_t event, Int_t px, Int_t py)
{
// Execute action corresponding to one event.
//
// This member function is called when a Button object is clicked.
if (fMother->IsEditable()) {
TPad::ExecuteEvent(event,px,py);
return;
}
TCanvas *c = gPad->GetCanvas();
if (!c) return;
TIter next(c->GetListOfPrimitives());
TObject *obj;
TGroupButton *button;
TPad *pad;
TDialogCanvas *canvas;
switch (event) {
case kButton1Down:
case kMouseMotion:
break;
case kButton1Motion:
break;
case kButton1Up:
//Clicked on APPLY button?
if (!strcasecmp(GetName(),"APPLY")) {
canvas = (TDialogCanvas*)GetMother();
if (!strcasecmp(GetTitle(),"CLOSE")) {
canvas->Close();
return;
}
pad = canvas->GetRefPad();
if (pad) pad->GetCanvas()->FeedbackMode(kFALSE);
canvas->Apply(GetTitle()); //just in case the apply button executes some code
if (pad) {
pad->Modified(kTRUE);
pad->Update();
}
break;
}
//Unset other buttons with same name
while ((obj = next())) {
if (obj == this) continue;
if (obj->InheritsFrom(TGroupButton::Class())) {
button = (TGroupButton*)obj;
if (!strcmp(button->GetName(),GetName())) {
if (button->GetBorderMode() < 0) {
button->SetBorderMode(1);
button->Modified();
}
}
}
}
//Set button on
SetBorderMode(-1);
Modified();
gPad->GetCanvas()->Modified();
gPad->Update();
break;
}
}
//______________________________________________________________________________
void TGroupButton::SavePrimitive(ostream &out, Option_t * /*= ""*/)
{
// Save primitive as a C++ statement(s) on output stream out
TPad *padsav = (TPad*)gPad;
char quote = '"';
if (gROOT->ClassSaved(TGroupButton::Class())) {
out<<" ";
} else {
out<<" TGroupButton *";
}
out<<"button = new TGroupButton("<<quote<<GetName()<<quote<<", "<<quote<<GetTitle()
<<quote<<","<<quote<<GetMethod()<<quote
<<","<<fXlowNDC
<<","<<fYlowNDC
<<","<<fXlowNDC+fWNDC
<<","<<fYlowNDC+fHNDC
<<");"<<endl;
SaveFillAttributes(out,"button",0,1001);
SaveLineAttributes(out,"button",1,1,1);
SaveTextAttributes(out,"button",22,0,1,62,.75);
if (GetBorderSize() != 2) {
out<<" button->SetBorderSize("<<GetBorderSize()<<");"<<endl;
}
if (GetBorderMode() != 1) {
out<<" button->SetBorderMode("<<GetBorderMode()<<");"<<endl;
}
out<<" button->Draw();"<<endl;
out<<" button->cd();"<<endl;
TIter next(GetListOfPrimitives());
TObject *obj = next(); //do not save first primitive
while ((obj = next()))
obj->SavePrimitive(out, (Option_t *)next.GetOption());
out<<" "<<padsav->GetName()<<"->cd();"<<endl;
padsav->cd();
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: KWSys - Kitware System Library
Module: DynamicLoader.cxx
Copyright (c) Kitware, Inc., Insight Consortium. All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(DynamicLoader.hxx)
#include KWSYS_HEADER(Configure.hxx)
#ifdef __APPLE__
#if MAC_OS_X_VERSION_MIN_REQUIRED < 1030
#include <string.h> // for strlen
#endif //MAC_OS_X_VERSION_MIN_REQUIRED < 1030
#endif // __APPLE__
#ifdef __hpux
#include <errno.h>
#endif //__hpux
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
# include "DynamicLoader.hxx.in"
# include "Configure.hxx.in"
#endif
// This file is actually 3 different implementations.
// 1. HP machines which uses shl_load
// 2. Mac OS X 10.2.x and earlier which uses NSLinkModule
// 3. Windows which uses LoadLibrary
// 4. Most unix systems (including Mac OS X 10.3 and later) which use dlopen
// (default) Each part of the ifdef contains a complete implementation for
// the static methods of DynamicLoader.
namespace KWSYS_NAMESPACE
{
//----------------------------------------------------------------------------
DynamicLoader::DynamicLoader()
{
}
//----------------------------------------------------------------------------
DynamicLoader::~DynamicLoader()
{
}
}
// ---------------------------------------------------------------
// 1. Implementation for HPUX machines
#ifdef __hpux
#include <dl.h>
#define DYNAMICLOADER_DEFINED 1
namespace KWSYS_NAMESPACE
{
//----------------------------------------------------------------------------
DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const char* libname )
{
return shl_load(libname, BIND_DEFERRED | DYNAMIC_PATH, 0L);
}
//----------------------------------------------------------------------------
int DynamicLoader::CloseLibrary(DynamicLoader::LibraryHandle lib)
{
return !shl_unload(lib);
}
//----------------------------------------------------------------------------
DynamicLoader::SymbolPointer
DynamicLoader::GetSymbolAddress(DynamicLoader::LibraryHandle lib, const char* sym)
{
void* addr;
int status;
/* TYPE_PROCEDURE Look for a function or procedure. (This used to be default)
* TYPE_DATA Look for a symbol in the data segment (for example, variables).
* TYPE_UNDEFINED Look for any symbol.
*/
status = shl_findsym (&lib, sym, TYPE_UNDEFINED, &addr);
void* result = (status < 0) ? (void*)0 : addr;
// Hack to cast pointer-to-data to pointer-to-function.
return *reinterpret_cast<DynamicLoader::SymbolPointer*>(&result);
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibPrefix()
{
return "lib";
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibExtension()
{
return ".sl";
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LastError()
{
// TODO: Need implementation with errno/strerror
/* If successful, shl_findsym returns an integer (int) value zero. If
* shl_findsym cannot find sym, it returns -1 and sets errno to zero.
* If any other errors occur, shl_findsym returns -1 and sets errno to one
* of these values (defined in <errno.h>):
* ENOEXEC
* A format error was detected in the specified library.
* ENOSYM
* A symbol on which sym depends could not be found.
* EINVAL
* The specified handle is invalid.
*/
if( errno == ENOEXEC
|| errno == ENOSYM
|| errno == EINVAL )
{
return strerror(errno);
}
// else
return 0;
}
} // namespace KWSYS_NAMESPACE
#endif //__hpux
// ---------------------------------------------------------------
// 2. Implementation for Mac OS X 10.2.x and earlier
#ifdef __APPLE__
#if MAC_OS_X_VERSION_MIN_REQUIRED < 1030
#include <mach-o/dyld.h>
#define DYNAMICLOADER_DEFINED 1
namespace KWSYS_NAMESPACE
{
//----------------------------------------------------------------------------
DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const char* libname )
{
NSObjectFileImageReturnCode rc;
NSObjectFileImage image = 0;
rc = NSCreateObjectFileImageFromFile(libname, &image);
// rc == NSObjectFileImageInappropriateFile when trying to load a dylib file
if( rc != NSObjectFileImageSuccess )
{
return 0;
}
NSModule handle = NSLinkModule(image, libname,
NSLINKMODULE_OPTION_BINDNOW|NSLINKMODULE_OPTION_RETURN_ON_ERROR);
NSDestroyObjectFileImage(image);
return handle;
}
//----------------------------------------------------------------------------
int DynamicLoader::CloseLibrary( DynamicLoader::LibraryHandle lib)
{
// NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED
// With this option the memory for the module is not deallocated
// allowing pointers into the module to still be valid.
// You should use this option instead if your code experience some problems
// reported against Panther 10.3.9 (fixed in Tiger 10.4.2 and up)
bool success = NSUnLinkModule(lib, NSUNLINKMODULE_OPTION_NONE);
return success;
}
//----------------------------------------------------------------------------
DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
DynamicLoader::LibraryHandle lib, const char* sym)
{
void *result=0;
// Need to prepend symbols with '_' on Apple-gcc compilers
size_t len = strlen(sym);
char *rsym = new char[len + 1 + 1];
strcpy(rsym, "_");
strcat(rsym+1, sym);
NSSymbol symbol = NSLookupSymbolInModule(lib, rsym);
if(symbol)
{
result = NSAddressOfSymbol(symbol);
}
delete[] rsym;
// Hack to cast pointer-to-data to pointer-to-function.
return *reinterpret_cast<DynamicLoader::SymbolPointer*>(&result);
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibPrefix()
{
return "lib";
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibExtension()
{
// NSCreateObjectFileImageFromFile fail when dealing with dylib image
// it returns NSObjectFileImageInappropriateFile
//return ".dylib";
return ".so";
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LastError()
{
return 0;
}
} // namespace KWSYS_NAMESPACE
#endif //MAC_OS_X_VERSION_MIN_REQUIRED < 1030
#endif // __APPLE__
// ---------------------------------------------------------------
// 3. Implementation for Windows win32 code
#ifdef _WIN32
#include <windows.h>
#define DYNAMICLOADER_DEFINED 1
namespace KWSYS_NAMESPACE
{
//----------------------------------------------------------------------------
DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const char* libname)
{
DynamicLoader::LibraryHandle lh;
#ifdef UNICODE
wchar_t libn[MB_CUR_MAX];
mbstowcs(libn, libname, MB_CUR_MAX);
lh = LoadLibrary(libn);
#else
lh = LoadLibrary(libname);
#endif
return lh;
}
//----------------------------------------------------------------------------
int DynamicLoader::CloseLibrary(DynamicLoader::LibraryHandle lib)
{
return (int)FreeLibrary(lib);
}
//----------------------------------------------------------------------------
DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
DynamicLoader::LibraryHandle lib, const char* sym)
{
void *result;
#ifdef __BORLANDC__
// Need to prepend symbols with '_' on borland compilers
size_t len = strlen(sym);
char *rsym = new char[len + 1 + 1];
strcpy(rsym, "_");
strcat(rsym+1, sym);
#else
const char *rsym = sym;
#endif
#ifdef UNICODE
wchar_t wsym[MB_CUR_MAX];
mbstowcs(wsym, rsym, MB_CUR_MAX);
result = GetProcAddress(lib, wsym);
#else
result = (void*)GetProcAddress(lib, rsym);
#endif
#ifdef __BORLANDC__
delete[] rsym;
#endif
// Hack to cast pointer-to-data to pointer-to-function.
return *reinterpret_cast<DynamicLoader::SymbolPointer*>(&result);
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibPrefix()
{
#ifdef __MINGW32__
return "lib";
#else
return "";
#endif
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibExtension()
{
return ".dll";
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LastError()
{
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL
);
static char* str = 0;
delete [] str;
str = strcpy(new char[strlen((char*)lpMsgBuf)+1], (char*)lpMsgBuf);
// Free the buffer.
LocalFree( lpMsgBuf );
return str;
}
} // namespace KWSYS_NAMESPACE
#endif //_WIN32
// ---------------------------------------------------------------
// 4. Implementation for default UNIX machines.
// if nothing has been defined then use this
#ifndef DYNAMICLOADER_DEFINED
#define DYNAMICLOADER_DEFINED 1
// Setup for most unix machines
#include <dlfcn.h>
namespace KWSYS_NAMESPACE
{
//----------------------------------------------------------------------------
DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const char* libname )
{
return dlopen(libname, RTLD_LAZY);
}
//----------------------------------------------------------------------------
int DynamicLoader::CloseLibrary(DynamicLoader::LibraryHandle lib)
{
if (lib)
{
// The function dlclose() returns 0 on success, and non-zero on error.
return !dlclose(lib);
}
// else
return 0;
}
//----------------------------------------------------------------------------
DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
DynamicLoader::LibraryHandle lib, const char* sym)
{
void* result = dlsym(lib, sym);
// Hack to cast pointer-to-data to pointer-to-function.
return *reinterpret_cast<DynamicLoader::SymbolPointer*>(&result);
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibPrefix()
{
return "lib";
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibExtension()
{
#ifdef __CYGWIN__
return ".dll";
#else
return ".so";
#endif
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LastError()
{
return dlerror();
}
} // namespace KWSYS_NAMESPACE
#endif
<commit_msg>ENH: remove warning<commit_after>/*=========================================================================
Program: KWSys - Kitware System Library
Module: DynamicLoader.cxx
Copyright (c) Kitware, Inc., Insight Consortium. All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(DynamicLoader.hxx)
#include KWSYS_HEADER(Configure.hxx)
#ifdef __APPLE__
#if MAC_OS_X_VERSION_MIN_REQUIRED < 1030
#include <string.h> // for strlen
#endif //MAC_OS_X_VERSION_MIN_REQUIRED < 1030
#endif // __APPLE__
#ifdef __hpux
#include <errno.h>
#endif //__hpux
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
# include "DynamicLoader.hxx.in"
# include "Configure.hxx.in"
#endif
// This file is actually 3 different implementations.
// 1. HP machines which uses shl_load
// 2. Mac OS X 10.2.x and earlier which uses NSLinkModule
// 3. Windows which uses LoadLibrary
// 4. Most unix systems (including Mac OS X 10.3 and later) which use dlopen
// (default) Each part of the ifdef contains a complete implementation for
// the static methods of DynamicLoader.
namespace KWSYS_NAMESPACE
{
//----------------------------------------------------------------------------
DynamicLoader::DynamicLoader()
{
}
//----------------------------------------------------------------------------
DynamicLoader::~DynamicLoader()
{
}
}
// ---------------------------------------------------------------
// 1. Implementation for HPUX machines
#ifdef __hpux
#include <dl.h>
#define DYNAMICLOADER_DEFINED 1
namespace KWSYS_NAMESPACE
{
//----------------------------------------------------------------------------
DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const char* libname )
{
return shl_load(libname, BIND_DEFERRED | DYNAMIC_PATH, 0L);
}
//----------------------------------------------------------------------------
int DynamicLoader::CloseLibrary(DynamicLoader::LibraryHandle lib)
{
return !shl_unload(lib);
}
//----------------------------------------------------------------------------
DynamicLoader::SymbolPointer
DynamicLoader::GetSymbolAddress(DynamicLoader::LibraryHandle lib, const char* sym)
{
void* addr;
int status;
/* TYPE_PROCEDURE Look for a function or procedure. (This used to be default)
* TYPE_DATA Look for a symbol in the data segment (for example, variables).
* TYPE_UNDEFINED Look for any symbol.
*/
status = shl_findsym (&lib, sym, TYPE_UNDEFINED, &addr);
void* result = (status < 0) ? (void*)0 : addr;
// Hack to cast pointer-to-data to pointer-to-function.
return *reinterpret_cast<DynamicLoader::SymbolPointer*>(&result);
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibPrefix()
{
return "lib";
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibExtension()
{
return ".sl";
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LastError()
{
// TODO: Need implementation with errno/strerror
/* If successful, shl_findsym returns an integer (int) value zero. If
* shl_findsym cannot find sym, it returns -1 and sets errno to zero.
* If any other errors occur, shl_findsym returns -1 and sets errno to one
* of these values (defined in <errno.h>):
* ENOEXEC
* A format error was detected in the specified library.
* ENOSYM
* A symbol on which sym depends could not be found.
* EINVAL
* The specified handle is invalid.
*/
if( errno == ENOEXEC
|| errno == ENOSYM
|| errno == EINVAL )
{
return strerror(errno);
}
// else
return 0;
}
} // namespace KWSYS_NAMESPACE
#endif //__hpux
// ---------------------------------------------------------------
// 2. Implementation for Mac OS X 10.2.x and earlier
#ifdef __APPLE__
#if MAC_OS_X_VERSION_MIN_REQUIRED < 1030
#include <mach-o/dyld.h>
#define DYNAMICLOADER_DEFINED 1
namespace KWSYS_NAMESPACE
{
//----------------------------------------------------------------------------
DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const char* libname )
{
NSObjectFileImageReturnCode rc;
NSObjectFileImage image = 0;
rc = NSCreateObjectFileImageFromFile(libname, &image);
// rc == NSObjectFileImageInappropriateFile when trying to load a dylib file
if( rc != NSObjectFileImageSuccess )
{
return 0;
}
NSModule handle = NSLinkModule(image, libname,
NSLINKMODULE_OPTION_BINDNOW|NSLINKMODULE_OPTION_RETURN_ON_ERROR);
NSDestroyObjectFileImage(image);
return handle;
}
//----------------------------------------------------------------------------
int DynamicLoader::CloseLibrary( DynamicLoader::LibraryHandle lib)
{
// NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED
// With this option the memory for the module is not deallocated
// allowing pointers into the module to still be valid.
// You should use this option instead if your code experience some problems
// reported against Panther 10.3.9 (fixed in Tiger 10.4.2 and up)
bool success = NSUnLinkModule(lib, NSUNLINKMODULE_OPTION_NONE);
return success;
}
//----------------------------------------------------------------------------
DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
DynamicLoader::LibraryHandle lib, const char* sym)
{
void *result=0;
// Need to prepend symbols with '_' on Apple-gcc compilers
size_t len = strlen(sym);
char *rsym = new char[len + 1 + 1];
strcpy(rsym, "_");
strcat(rsym+1, sym);
NSSymbol symbol = NSLookupSymbolInModule(lib, rsym);
if(symbol)
{
result = NSAddressOfSymbol(symbol);
}
delete[] rsym;
// Hack to cast pointer-to-data to pointer-to-function.
return *reinterpret_cast<DynamicLoader::SymbolPointer*>(&result);
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibPrefix()
{
return "lib";
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibExtension()
{
// NSCreateObjectFileImageFromFile fail when dealing with dylib image
// it returns NSObjectFileImageInappropriateFile
//return ".dylib";
return ".so";
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LastError()
{
return 0;
}
} // namespace KWSYS_NAMESPACE
#endif //MAC_OS_X_VERSION_MIN_REQUIRED < 1030
#endif // __APPLE__
// ---------------------------------------------------------------
// 3. Implementation for Windows win32 code
#ifdef _WIN32
#include <windows.h>
#define DYNAMICLOADER_DEFINED 1
namespace KWSYS_NAMESPACE
{
//----------------------------------------------------------------------------
DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const char* libname)
{
DynamicLoader::LibraryHandle lh;
#ifdef UNICODE
wchar_t libn[MB_CUR_MAX];
mbstowcs(libn, libname, MB_CUR_MAX);
lh = LoadLibrary(libn);
#else
lh = LoadLibrary(libname);
#endif
return lh;
}
//----------------------------------------------------------------------------
int DynamicLoader::CloseLibrary(DynamicLoader::LibraryHandle lib)
{
return (int)FreeLibrary(lib);
}
//----------------------------------------------------------------------------
DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
DynamicLoader::LibraryHandle lib, const char* sym)
{
void *result;
#ifdef __BORLANDC__
// Need to prepend symbols with '_' on borland compilers
size_t len = strlen(sym);
char *rsym = new char[len + 1 + 1];
strcpy(rsym, "_");
strcat(rsym+1, sym);
#else
const char *rsym = sym;
#endif
#ifdef UNICODE
wchar_t wsym[MB_CUR_MAX];
mbstowcs(wsym, rsym, MB_CUR_MAX);
result = GetProcAddress(lib, wsym);
#else
result = (void*)GetProcAddress(lib, rsym);
#endif
#ifdef __BORLANDC__
delete[] rsym;
#endif
// Hack to cast pointer-to-data to pointer-to-function.
return *reinterpret_cast<DynamicLoader::SymbolPointer*>(&result);
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibPrefix()
{
#ifdef __MINGW32__
return "lib";
#else
return "";
#endif
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibExtension()
{
return ".dll";
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LastError()
{
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL
);
static char* str = 0;
delete [] str;
str = strcpy(new char[strlen((char*)lpMsgBuf)+1], (char*)lpMsgBuf);
// Free the buffer.
LocalFree( lpMsgBuf );
return str;
}
} // namespace KWSYS_NAMESPACE
#endif //_WIN32
// ---------------------------------------------------------------
// 4. Implementation for default UNIX machines.
// if nothing has been defined then use this
#ifndef DYNAMICLOADER_DEFINED
#define DYNAMICLOADER_DEFINED 1
// Setup for most unix machines
#include <dlfcn.h>
namespace KWSYS_NAMESPACE
{
//----------------------------------------------------------------------------
DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const char* libname )
{
return dlopen(libname, RTLD_LAZY);
}
//----------------------------------------------------------------------------
int DynamicLoader::CloseLibrary(DynamicLoader::LibraryHandle lib)
{
if (lib)
{
// The function dlclose() returns 0 on success, and non-zero on error.
return !dlclose(lib);
}
// else
return 0;
}
//----------------------------------------------------------------------------
DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
DynamicLoader::LibraryHandle lib, const char* sym)
{
// Hack to cast pointer-to-data to pointer-to-function.
union
{
void* pvoid;
DynamicLoader::SymbolPointer psym;
} result;
result.pvoid = dlsym(lib, sym);
return result.psym;
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibPrefix()
{
return "lib";
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LibExtension()
{
#ifdef __CYGWIN__
return ".dll";
#else
return ".so";
#endif
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LastError()
{
return dlerror();
}
} // namespace KWSYS_NAMESPACE
#endif
<|endoftext|> |
<commit_before>/*
* ProcessTests.cpp
*
* Copyright (C) 2017 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#ifndef _WIN32
#include <atomic>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/thread.hpp>
#include <core/SafeConvert.hpp>
#include <core/system/PosixProcess.hpp>
#include <core/system/PosixChildProcess.hpp>
#include <core/Thread.hpp>
#include <tests/TestThat.hpp>
namespace rstudio {
namespace core {
namespace system {
namespace tests {
void checkExitCode(int exitCode, int* outExitCode)
{
*outExitCode = exitCode;
}
void signalExit(int exitCode, int* outExitCode, boost::mutex* mutex, boost::condition_variable* signal)
{
*outExitCode = exitCode;
LOCK_MUTEX(*mutex)
{
signal->notify_all();
}
END_LOCK_MUTEX
}
void appendOutput(const std::string& output, std::string* pOutput)
{
pOutput->append(output);
}
struct IoServiceFixture
{
boost::asio::io_service ioService;
boost::asio::io_service::work work;
std::vector<boost::shared_ptr<boost::thread> > threads;
void runServiceThread()
{
ioService.run();
}
IoServiceFixture() :
ioService(), work(ioService)
{
for (int i = 0; i < 4; ++i)
{
boost::shared_ptr<boost::thread> pThread(
new boost::thread(boost::bind(&IoServiceFixture::runServiceThread, this)));
threads.push_back(pThread);
}
}
~IoServiceFixture()
{
ioService.stop();
for (const boost::shared_ptr<boost::thread>& thread : threads)
thread->join();
}
};
context("ProcessTests")
{
test_that("AsioProcessSupervisor can run program")
{
IoServiceFixture fixture;
// create new supervisor
AsioProcessSupervisor supervisor(fixture.ioService);
// create process options and callbacks
ProcessOptions options;
options.threadSafe = true;
ProcessCallbacks callbacks;
int exitCode = -1;
callbacks.onExit = boost::bind(&checkExitCode, _1, &exitCode);
// construct program arguments
std::vector<std::string> args;
args.push_back("Hello, world! This is a string to echo!");
// run program
supervisor.runProgram("/bin/echo", args, options, callbacks);
// wait for it to exit
bool success = supervisor.wait(boost::posix_time::seconds(5));
// verify process exited successfully
CHECK(success);
CHECK(exitCode == 0);
}
test_that("AsioProcessSupervisor returns correct output from stdout")
{
IoServiceFixture fixture;
// create new supervisor
AsioProcessSupervisor supervisor(fixture.ioService);
// create process options and callbacks
ProcessOptions options;
options.threadSafe = true;
ProcessCallbacks callbacks;
int exitCode = -1;
std::string output;
callbacks.onExit = boost::bind(&checkExitCode, _1, &exitCode);
callbacks.onStdout = boost::bind(&appendOutput, _2, &output);
// run command
std::string command = "bash -c \"python -c $'for i in range(10):\n print(i)'\"";
supervisor.runCommand(command, options, callbacks);
// wait for it to exit
bool success = supervisor.wait(boost::posix_time::seconds(5));
// verify process exited successfully and we got the expected output
std::string expectedOutput = "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n";
CHECK(success);
CHECK(exitCode == 0);
CHECK(output == expectedOutput);
}
/* test running child process as another user
* commented out due to users being different on every machine
test_that("AsioProcessSupervisor can run process as another user")
{
IoServiceFixture fixture;
// create new supervisor
AsioProcessSupervisor supervisor(fixture.ioService);
// create process options and callbacks
ProcessOptions options;
options.runAsUser = "jdoe1";
ProcessCallbacks callbacks;
int exitCode = -1;
std::string output;
callbacks.onExit = boost::bind(&checkExitCode, _1, &exitCode);
callbacks.onStdout = boost::bind(&appendOutput, _2, &output);
// run command
std::string command = "whoami";
supervisor.runCommand(command, options, callbacks);
// wait for it to exit
bool success = supervisor.wait(boost::posix_time::seconds(5));
// verify process exited successfully and we got the expected output
std::string expectedOutput = "jdoe1\n";
CHECK(success);
CHECK(exitCode == 0);
CHECK(output == expectedOutput);
}
*/
test_that("AsioProcessSupervisor returns correct error code for failure exit")
{
IoServiceFixture fixture;
// create new supervisor
AsioProcessSupervisor supervisor(fixture.ioService);
// create process options and callbacks
ProcessOptions options;
options.threadSafe = true;
ProcessCallbacks callbacks;
int exitCode = -1;
std::string output;
callbacks.onExit = boost::bind(&checkExitCode, _1, &exitCode);
// run command
std::string command = "this is not a valid command";
supervisor.runCommand(command, options, callbacks);
// wait for it to exit
bool success = supervisor.wait(boost::posix_time::seconds(5));
CHECK(success);
CHECK(exitCode == 127);
}
test_that("AsioAsyncChildProcess can write to std in")
{
IoServiceFixture fixture;
ProcessOptions options;
options.threadSafe = true;
options.threadSafe = true;
ProcessCallbacks callbacks;
int exitCode = -1;
std::string output;
boost::condition_variable signal;
boost::mutex mutex;
callbacks.onExit = boost::bind(&signalExit, _1, &exitCode, &mutex, &signal);
callbacks.onStdout = boost::bind(&appendOutput, _2, &output);
AsioAsyncChildProcess proc(fixture.ioService, "cat", options);
proc.run(callbacks);
proc.asyncWriteToStdin("Hello\n", false);
proc.asyncWriteToStdin("world!\n", true);
std::string expectedOutput = "Hello\nworld!\n";
boost::unique_lock<boost::mutex> lock(mutex);
bool timedOut = !signal.timed_wait<boost::posix_time::seconds>(lock, boost::posix_time::seconds(5));
CHECK(!timedOut);
CHECK(exitCode == 0);
CHECK(output == expectedOutput);
}
test_that("Can spawn multiple sync processes and they all return correct results")
{
// create new supervisor
ProcessSupervisor supervisor;
int exitCodes[10];
std::string outputs[10];
for (int i = 0; i < 10; ++i)
{
// construct program arguments
std::vector<std::string> args;
args.push_back("Hello, " + safe_convert::numberToString(i));
// create process options and callbacks
ProcessOptions options;
options.threadSafe = true;
ProcessCallbacks callbacks;
callbacks.onExit = boost::bind(&checkExitCode, _1, exitCodes + i);
callbacks.onStdout = boost::bind(&appendOutput, _2, outputs + i);
// run program
supervisor.runProgram("/bin/echo", args, options, callbacks);
}
// wait for processes to exit
bool success = supervisor.wait();
// verify correct exit statuses and outputs
for (int i = 0; i < 10; ++i)
{
CHECK(exitCodes[i] == 0);
CHECK(outputs[i] == "Hello, " + safe_convert::numberToString(i) + "\n");
}
}
test_that("Can spawn multiple async processes and they all return correct results")
{
IoServiceFixture fixture;
// create new supervisor
AsioProcessSupervisor supervisor(fixture.ioService);
const int numProcs = 1000;
int exitCodes[numProcs];
std::string outputs[numProcs];
std::atomic<int> numExited(0);
for (int i = 0; i < numProcs; ++i)
{
// set exit code to some initial bad value to ensure it is properly set when
// the process exits
exitCodes[i] = -1;
// construct program arguments
std::vector<std::string> args;
args.push_back("Hello, " + safe_convert::numberToString(i));
// create process options and callbacks
ProcessOptions options;
options.threadSafe = true;
ProcessCallbacks callbacks;
callbacks.onExit = [&exitCodes, &numExited, i](int exitCode) {
exitCodes[i] = exitCode;
numExited++;
};
callbacks.onStdout = boost::bind(&appendOutput, _2, outputs + i);
// run program
supervisor.runProgram("/bin/echo", args, options, callbacks);
}
// wait for processes to exit
bool success = supervisor.wait(boost::posix_time::seconds(10));
CHECK(success);
// check to make sure all processes really exited
CHECK(numExited == numProcs);
// verify correct exit statuses and outputs
for (int i = 0; i < numProcs; ++i)
{
CHECK(exitCodes[i] == 0);
CHECK(outputs[i] == "Hello, " + safe_convert::numberToString(i) + "\n");
}
}
}
} // end namespace tests
} // end namespace system
} // end namespace core
} // end namespace rstudio
#endif // !_WIN32
<commit_msg>Fixed asio process unit test issue found by Gary. Turns out on some systems fork is extremely slow, so the call to spawn 1,000 simultaneous process can take a long time on such systems. Bumped up the wait timer to something more reasonable, and made sure to set the amount of spawned processes to a proportional amount based on open files limit.<commit_after>/*
* ProcessTests.cpp
*
* Copyright (C) 2017 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#ifndef _WIN32
#include <atomic>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/thread.hpp>
#include <core/SafeConvert.hpp>
#include <core/system/PosixProcess.hpp>
#include <core/system/PosixChildProcess.hpp>
#include <core/system/PosixSystem.hpp>
#include <core/Thread.hpp>
#include <tests/TestThat.hpp>
namespace rstudio {
namespace core {
namespace system {
namespace tests {
void checkExitCode(int exitCode, int* outExitCode)
{
*outExitCode = exitCode;
}
void signalExit(int exitCode, int* outExitCode, boost::mutex* mutex, boost::condition_variable* signal)
{
*outExitCode = exitCode;
LOCK_MUTEX(*mutex)
{
signal->notify_all();
}
END_LOCK_MUTEX
}
void appendOutput(const std::string& output, std::string* pOutput)
{
pOutput->append(output);
}
struct IoServiceFixture
{
boost::asio::io_service ioService;
boost::asio::io_service::work work;
std::vector<boost::shared_ptr<boost::thread> > threads;
void runServiceThread()
{
ioService.run();
}
IoServiceFixture() :
ioService(), work(ioService)
{
for (int i = 0; i < 4; ++i)
{
boost::shared_ptr<boost::thread> pThread(
new boost::thread(boost::bind(&IoServiceFixture::runServiceThread, this)));
threads.push_back(pThread);
}
}
~IoServiceFixture()
{
ioService.stop();
for (const boost::shared_ptr<boost::thread>& thread : threads)
thread->join();
}
};
context("ProcessTests")
{
test_that("AsioProcessSupervisor can run program")
{
IoServiceFixture fixture;
// create new supervisor
AsioProcessSupervisor supervisor(fixture.ioService);
// create process options and callbacks
ProcessOptions options;
options.threadSafe = true;
ProcessCallbacks callbacks;
int exitCode = -1;
callbacks.onExit = boost::bind(&checkExitCode, _1, &exitCode);
// construct program arguments
std::vector<std::string> args;
args.push_back("Hello, world! This is a string to echo!");
// run program
supervisor.runProgram("/bin/echo", args, options, callbacks);
// wait for it to exit
bool success = supervisor.wait(boost::posix_time::seconds(5));
// verify process exited successfully
CHECK(success);
CHECK(exitCode == 0);
}
test_that("AsioProcessSupervisor returns correct output from stdout")
{
IoServiceFixture fixture;
// create new supervisor
AsioProcessSupervisor supervisor(fixture.ioService);
// create process options and callbacks
ProcessOptions options;
options.threadSafe = true;
ProcessCallbacks callbacks;
int exitCode = -1;
std::string output;
callbacks.onExit = boost::bind(&checkExitCode, _1, &exitCode);
callbacks.onStdout = boost::bind(&appendOutput, _2, &output);
// run command
std::string command = "bash -c \"python -c $'for i in range(10):\n print(i)'\"";
supervisor.runCommand(command, options, callbacks);
// wait for it to exit
bool success = supervisor.wait(boost::posix_time::seconds(5));
// verify process exited successfully and we got the expected output
std::string expectedOutput = "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n";
CHECK(success);
CHECK(exitCode == 0);
CHECK(output == expectedOutput);
}
/* test running child process as another user
* commented out due to users being different on every machine
test_that("AsioProcessSupervisor can run process as another user")
{
IoServiceFixture fixture;
// create new supervisor
AsioProcessSupervisor supervisor(fixture.ioService);
// create process options and callbacks
ProcessOptions options;
options.runAsUser = "jdoe1";
ProcessCallbacks callbacks;
int exitCode = -1;
std::string output;
callbacks.onExit = boost::bind(&checkExitCode, _1, &exitCode);
callbacks.onStdout = boost::bind(&appendOutput, _2, &output);
// run command
std::string command = "whoami";
supervisor.runCommand(command, options, callbacks);
// wait for it to exit
bool success = supervisor.wait(boost::posix_time::seconds(5));
// verify process exited successfully and we got the expected output
std::string expectedOutput = "jdoe1\n";
CHECK(success);
CHECK(exitCode == 0);
CHECK(output == expectedOutput);
}
*/
test_that("AsioProcessSupervisor returns correct error code for failure exit")
{
IoServiceFixture fixture;
// create new supervisor
AsioProcessSupervisor supervisor(fixture.ioService);
// create process options and callbacks
ProcessOptions options;
options.threadSafe = true;
ProcessCallbacks callbacks;
int exitCode = -1;
std::string output;
callbacks.onExit = boost::bind(&checkExitCode, _1, &exitCode);
// run command
std::string command = "this is not a valid command";
supervisor.runCommand(command, options, callbacks);
// wait for it to exit
bool success = supervisor.wait(boost::posix_time::seconds(5));
CHECK(success);
CHECK(exitCode == 127);
}
test_that("AsioAsyncChildProcess can write to std in")
{
IoServiceFixture fixture;
ProcessOptions options;
options.threadSafe = true;
options.threadSafe = true;
ProcessCallbacks callbacks;
int exitCode = -1;
std::string output;
boost::condition_variable signal;
boost::mutex mutex;
callbacks.onExit = boost::bind(&signalExit, _1, &exitCode, &mutex, &signal);
callbacks.onStdout = boost::bind(&appendOutput, _2, &output);
AsioAsyncChildProcess proc(fixture.ioService, "cat", options);
proc.run(callbacks);
proc.asyncWriteToStdin("Hello\n", false);
proc.asyncWriteToStdin("world!\n", true);
std::string expectedOutput = "Hello\nworld!\n";
boost::unique_lock<boost::mutex> lock(mutex);
bool timedOut = !signal.timed_wait<boost::posix_time::seconds>(lock, boost::posix_time::seconds(5));
CHECK(!timedOut);
CHECK(exitCode == 0);
CHECK(output == expectedOutput);
}
test_that("Can spawn multiple sync processes and they all return correct results")
{
// create new supervisor
ProcessSupervisor supervisor;
int exitCodes[10];
std::string outputs[10];
for (int i = 0; i < 10; ++i)
{
// construct program arguments
std::vector<std::string> args;
args.push_back("Hello, " + safe_convert::numberToString(i));
// create process options and callbacks
ProcessOptions options;
options.threadSafe = true;
ProcessCallbacks callbacks;
callbacks.onExit = boost::bind(&checkExitCode, _1, exitCodes + i);
callbacks.onStdout = boost::bind(&appendOutput, _2, outputs + i);
// run program
supervisor.runProgram("/bin/echo", args, options, callbacks);
}
// wait for processes to exit
bool success = supervisor.wait();
// verify correct exit statuses and outputs
for (int i = 0; i < 10; ++i)
{
CHECK(exitCodes[i] == 0);
CHECK(outputs[i] == "Hello, " + safe_convert::numberToString(i) + "\n");
}
}
test_that("Can spawn multiple async processes and they all return correct results")
{
IoServiceFixture fixture;
std::string asioType;
#if defined(BOOST_ASIO_HAS_IOCP)
asioType = "iocp" ;
#elif defined(BOOST_ASIO_HAS_EPOLL)
asioType = "epoll" ;
#elif defined(BOOST_ASIO_HAS_KQUEUE)
asioType = "kqueue" ;
#elif defined(BOOST_ASIO_HAS_DEV_POLL)
asioType = "/dev/poll" ;
#else
asioType = "select" ;
#endif
std::cout << "Using asio type: " << asioType << std::endl;
// determine open files limit
RLimitType soft, hard;
Error error = core::system::getResourceLimit(core::system::FilesLimit, &soft, &hard);
REQUIRE_FALSE(error);
// ensure we set the hard limit
error = core::system::setResourceLimit(core::system::FilesLimit, hard);
REQUIRE_FALSE(error);
// spawn amount of processes proportional to the hard limit
const int numProcs = ::fmin(hard / 6, 1000);
std::cout << "Spawning " << numProcs << " child procs" << std::endl;
// create new supervisor
AsioProcessSupervisor supervisor(fixture.ioService);
int exitCodes[numProcs];
std::string outputs[numProcs];
std::atomic<int> numExited(0);
int numError = 0;
Error lastError;
for (int i = 0; i < numProcs; ++i)
{
// set exit code to some initial bad value to ensure it is properly set when
// the process exits
exitCodes[i] = -1;
// construct program arguments
std::vector<std::string> args;
args.push_back("Hello, " + safe_convert::numberToString(i));
// create process options and callbacks
ProcessOptions options;
options.threadSafe = true;
ProcessCallbacks callbacks;
callbacks.onExit = [&exitCodes, &numExited, i](int exitCode) {
exitCodes[i] = exitCode;
numExited++;
};
callbacks.onStdout = boost::bind(&appendOutput, _2, outputs + i);
// run program
Error error = supervisor.runProgram("/bin/echo", args, options, callbacks);
if (error)
{
numError++;
lastError = error;
}
}
if (lastError)
std::cout << lastError.summary() << " " << lastError.location().asString() << std::endl;
CHECK(numError == 0);
// wait for processes to exit
bool success = supervisor.wait(boost::posix_time::seconds(60));
CHECK(success);
// check to make sure all processes really exited
CHECK(numExited == numProcs);
// verify correct exit statuses and outputs
for (int i = 0; i < numProcs; ++i)
{
CHECK(exitCodes[i] == 0);
CHECK(outputs[i] == "Hello, " + safe_convert::numberToString(i) + "\n");
}
}
}
} // end namespace tests
} // end namespace system
} // end namespace core
} // end namespace rstudio
#endif // !_WIN32
<|endoftext|> |
<commit_before>/* -*-c++-*- $Id: osgaudioocclude.cpp */
/**
* osgAudio - OpenSceneGraph Audio Library
* (C) Copyright 2009-2011 by Kenneth Mark Bryden
* (programming by Chris 'Xenon' Hanson, AlphaPixel, LLC xenon at alphapixel.com)
* based on a fork of:
* Osg AL - OpenSceneGraph Audio Library
* Copyright (C) 2004 VRlab, Ume University
*
* 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.
* Please see COPYING file for special static-link exemption to LGPL.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
#include <osg/DeleteHandler>
#include <osg/Notify>
#include <osg/MatrixTransform>
#include <osg/PositionAttitudeTransform>
#include <osg/Geometry>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osgUtil/Optimizer>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>
#include <osgGA/KeySwitchMatrixManipulator>
#include <osgViewer/ViewerEventHandlers>
#include <osgViewer/Viewer>
#include <osgAudio/SoundNode.h>
#include <osgAudio/SoundRoot.h>
#include <osgAudio/SoundManager.h>
#include <osgAudio/SoundState.h>
#include <osgAudio/OccludeCallback.h>
#include <osgAudio/Version.h>
osg::PositionAttitudeTransform *createSoundNode(const std::string& file, bool occlude, osg::Node *root, bool is_stream);
int main( int argc, char **argv )
{
osg::notify(osg::WARN) << "\n\n" << osgAudio::getLibraryName() << " demo" << std::endl;
osg::notify(osg::WARN) << "Version: " << osgAudio::getVersion() << "\n\n" << std::endl;
osg::notify(osg::WARN) << "Demonstrates occluders" << std::endl;
try {
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" demonstrates the use of the osgAudio toolkit for spatial sound.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
// initialize the viewer.
osgViewer::Viewer viewer(arguments);
osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;
keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
viewer.setCameraManipulator( keyswitchManipulator.get() );
// add the window size toggle handler
viewer.addEventHandler(new osgViewer::WindowSizeHandler);
// add the stats handler
viewer.addEventHandler(new osgViewer::StatsHandler);
// add the help handler
viewer.addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage()));
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
arguments.getApplicationUsage()->addKeyboardMouseBinding("RETURN", "Play a sound");
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
// initialize the SoundManager before loading any files
osgAudio::SoundManager::instance()->init(16);
osgAudio::SoundManager::instance()->getEnvironment()->setDistanceModel(osgAudio::InverseDistance);
osgAudio::SoundManager::instance()->getEnvironment()->setDopplerFactor(1);
osg::ref_ptr<osg::Group> rootnode = new osg::Group;
// load the nodes from the commandline arguments.
osg::Node* model = osgDB::readNodeFiles(arguments); //createModel();
if (!model)
{
osg::notify(osg::FATAL) << "Error loading models from commandline" << std::endl;
return 1;
}
osg::ref_ptr<osg::PositionAttitudeTransform> loaded_transform = new osg::PositionAttitudeTransform;
loaded_transform->addChild(model);
rootnode->addChild(loaded_transform.get());
// Create ONE (only one, otherwise the transformation of the listener and update for SoundManager will be
// called several times, which is not catastrophic, but unnecessary)
// SoundRoot that will make sure the listener is updated and
// to keep the internal state of the SoundManager updated
// This could also be done manually, this is just a handy way of doing it.
osg::ref_ptr<osgAudio::SoundRoot> sound_root = new osgAudio::SoundRoot;
sound_root->setCamera( viewer.getCamera() );
// The position in the scenegraph of this node is not important.
// Just as long as the cull traversal should be called after any changes to the SoundManager are made.
rootnode->addChild(sound_root.get());
bool occlude = true;
osg::ref_ptr<osg::PositionAttitudeTransform> sound_transform = createSoundNode("a.wav", occlude, rootnode.get(), false);
rootnode->addChild(sound_transform.get());
// run optimization over the scene graph
//osgUtil::Optimizer optimizer;
//optimizer.optimize(rootnode.get());
// set the scene to render
viewer.setSceneData(rootnode.get());
// create the windows and run the threads.
viewer.realize();
osg::Timer_t start = osg::Timer::instance()->tick();
float rate=10; // degrees per second
while( !viewer.done() )
{
osg::Timer_t now = osg::Timer::instance()->tick();
double dt = osg::Timer::instance()->delta_s(start, now);
double angle = rate*dt;
osg::Quat quat;
quat.makeRotate(osg::inDegrees(angle), osg::Vec3(0,0,1));
loaded_transform->setAttitude(quat);
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
}
catch (std::exception& e) {
osg::notify(osg::WARN) << "Caught: " << e.what() << std::endl;
}
// Very important to call this before end of main.
// Otherwise OpenAL will do all sorts of strange things after end of main
// in the destructor of soundmanager.
if (osg::Referenced::getDeleteHandler()) {
osg::Referenced::getDeleteHandler()->setNumFramesToRetainObjects(0);
osg::Referenced::getDeleteHandler()->flushAll();
}
osgAudio::SoundManager::instance()->shutdown();
return 0;
}
osg::PositionAttitudeTransform *createSoundNode(const std::string& file, bool occlude, osg::Node *root, bool is_stream)
{
// Create a sample, load a .wav file.
bool add_to_cache = false;
osg::ref_ptr<osgAudio::Stream> stream;
osg::ref_ptr<osgAudio::Sample> sample;
// Create a new soundstate, give it the name of the file we loaded.
osg::ref_ptr<osgAudio::SoundState> sound_state = new osgAudio::SoundState(file);
// Allocate a hardware soundsource to this soundstate (priority 10)
sound_state->allocateSource(10, false);
if (is_stream) {
stream = osgAudio::SoundManager::instance()->getStream(file.c_str(), add_to_cache);
osg::notify(osg::WARN) << "Loading stream: " << file << std::endl;
sound_state->setStream(stream.get());
}
else {
sample = osgAudio::SoundManager::instance()->getSample(file.c_str(), add_to_cache);
osg::notify(osg::WARN) << "Loading sample: " << file << std::endl;
sound_state->setSample(sample.get());
}
sound_state->setGain(1.0f);
sound_state->setReferenceDistance(10);
sound_state->setRolloffFactor(1);
sound_state->setPlay(true);
sound_state->setLooping(true);
// Add the soundstate to the sound manager, so we can find it later on if we want to
osgAudio::SoundManager::instance()->addSoundState(sound_state.get());
osgAudio::SoundNode *sound_node = new osgAudio::SoundNode;
sound_node->setSoundState(sound_state.get());
float radius = 0.5;
if (occlude) {
osgAudio::OccludeCallback *cb = new osgAudio::OccludeCallback(root);
cb->setNearThreshold(radius*1.1);
sound_node->setOccludeCallback(cb);
}
// Create a transformation node onto we will attach a soundnode
osg::PositionAttitudeTransform *sound_transform = new osg::PositionAttitudeTransform;
// Create a sphere so we can "see" the sound
osg::ref_ptr<osg::Geode> geode = new osg::Geode;
osg::TessellationHints* hints = new osg::TessellationHints;
hints->setDetailRatio(0.5f);
geode->addDrawable(new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(0.0f,0.0f,0.0f),radius),hints));
sound_transform->addChild(geode.get());
sound_transform->addChild(sound_node);
return sound_transform;
}
<commit_msg>update the occlude example to use the SoundUpdateCB instead of the deprecated SoundNode.<commit_after>/* -*-c++-*- $Id: osgaudioocclude.cpp */
/**
* osgAudio - OpenSceneGraph Audio Library
* (C) Copyright 2009-2011 by Kenneth Mark Bryden
* (programming by Chris 'Xenon' Hanson, AlphaPixel, LLC xenon at alphapixel.com)
* based on a fork of:
* Osg AL - OpenSceneGraph Audio Library
* Copyright (C) 2004 VRlab, Ume University
*
* 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.
* Please see COPYING file for special static-link exemption to LGPL.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
#include <osg/DeleteHandler>
#include <osg/Notify>
#include <osg/MatrixTransform>
#include <osg/PositionAttitudeTransform>
#include <osg/Geometry>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osgUtil/Optimizer>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>
#include <osgGA/KeySwitchMatrixManipulator>
#include <osgViewer/ViewerEventHandlers>
#include <osgViewer/Viewer>
#include <osgAudio/SoundNode.h>
#include <osgAudio/SoundRoot.h>
#include <osgAudio/SoundManager.h>
#include <osgAudio/SoundState.h>
#include <osgAudio/OccludeCallback.h>
#include <osgAudio/Version.h>
#include <osgAudio/SoundUpdateCB.h>
osg::PositionAttitudeTransform *createSound(const std::string& file, bool occlude, osg::Node *root, bool is_stream);
int main( int argc, char **argv )
{
osg::notify(osg::WARN) << "\n\n" << osgAudio::getLibraryName() << " demo" << std::endl;
osg::notify(osg::WARN) << "Version: " << osgAudio::getVersion() << "\n\n" << std::endl;
osg::notify(osg::WARN) << "Demonstrates occluders" << std::endl;
try {
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" demonstrates the use of the osgAudio toolkit for spatial sound.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
// initialize the viewer.
osgViewer::Viewer viewer(arguments);
osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;
keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
viewer.setCameraManipulator( keyswitchManipulator.get() );
// add the window size toggle handler
viewer.addEventHandler(new osgViewer::WindowSizeHandler);
// add the stats handler
viewer.addEventHandler(new osgViewer::StatsHandler);
// add the help handler
viewer.addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage()));
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
arguments.getApplicationUsage()->addKeyboardMouseBinding("RETURN", "Play a sound");
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
// initialize the SoundManager before loading any files
osgAudio::SoundManager::instance()->init(16);
osgAudio::SoundManager::instance()->getEnvironment()->setDistanceModel(osgAudio::InverseDistance);
osgAudio::SoundManager::instance()->getEnvironment()->setDopplerFactor(1);
osg::ref_ptr<osg::Group> rootnode = new osg::Group;
// load the nodes from the commandline arguments.
osg::Node* model = osgDB::readNodeFiles(arguments); //createModel();
if (!model)
{
osg::notify(osg::FATAL) << "Error loading models from commandline" << std::endl;
return 1;
}
osg::ref_ptr<osg::PositionAttitudeTransform> loaded_transform = new osg::PositionAttitudeTransform;
loaded_transform->addChild(model);
rootnode->addChild(loaded_transform.get());
// Create ONE (only one, otherwise the transformation of the listener and update for SoundManager will be
// called several times, which is not catastrophic, but unnecessary)
// SoundRoot that will make sure the listener is updated and
// to keep the internal state of the SoundManager updated
// This could also be done manually, this is just a handy way of doing it.
osg::ref_ptr<osgAudio::SoundRoot> sound_root = new osgAudio::SoundRoot;
sound_root->setCamera( viewer.getCamera() );
// The position in the scenegraph of this node is not important.
// Just as long as the cull traversal should be called after any changes to the SoundManager are made.
rootnode->addChild(sound_root.get());
bool occlude = true;
osg::ref_ptr<osg::PositionAttitudeTransform> sound_transform = createSound("a.wav", occlude, rootnode.get(), false);
rootnode->addChild(sound_transform.get());
// run optimization over the scene graph
//osgUtil::Optimizer optimizer;
//optimizer.optimize(rootnode.get());
// set the scene to render
viewer.setSceneData(rootnode.get());
// create the windows and run the threads.
viewer.realize();
osg::Timer_t start = osg::Timer::instance()->tick();
float rate=10; // degrees per second
while( !viewer.done() )
{
osg::Timer_t now = osg::Timer::instance()->tick();
double dt = osg::Timer::instance()->delta_s(start, now);
double angle = rate*dt;
osg::Quat quat;
quat.makeRotate(osg::inDegrees(angle), osg::Vec3(0,0,1));
loaded_transform->setAttitude(quat);
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
}
catch (std::exception& e) {
osg::notify(osg::WARN) << "Caught: " << e.what() << std::endl;
}
// Very important to call this before end of main.
// Otherwise OpenAL will do all sorts of strange things after end of main
// in the destructor of soundmanager.
if (osg::Referenced::getDeleteHandler()) {
osg::Referenced::getDeleteHandler()->setNumFramesToRetainObjects(0);
osg::Referenced::getDeleteHandler()->flushAll();
}
osgAudio::SoundManager::instance()->shutdown();
return 0;
}
osg::PositionAttitudeTransform *createSound(const std::string& file, bool occlude, osg::Node *root, bool is_stream)
{
// Create a sample, load a .wav file.
bool add_to_cache = false;
osg::ref_ptr<osgAudio::Stream> stream;
osg::ref_ptr<osgAudio::Sample> sample;
// Create a new soundstate, give it the name of the file we loaded.
osg::ref_ptr<osgAudio::SoundState> sound_state = new osgAudio::SoundState(file);
// Allocate a hardware soundsource to this soundstate (priority 10)
sound_state->allocateSource(10, false);
if (is_stream) {
stream = osgAudio::SoundManager::instance()->getStream(file.c_str(), add_to_cache);
osg::notify(osg::WARN) << "Loading stream: " << file << std::endl;
sound_state->setStream(stream.get());
}
else {
sample = osgAudio::SoundManager::instance()->getSample(file.c_str(), add_to_cache);
osg::notify(osg::WARN) << "Loading sample: " << file << std::endl;
sound_state->setSample(sample.get());
}
sound_state->setGain(1.0f);
sound_state->setReferenceDistance(10);
sound_state->setRolloffFactor(1);
sound_state->setPlay(true);
sound_state->setLooping(true);
// Add the soundstate to the sound manager, so we can find it later on if we want to
osgAudio::SoundManager::instance()->addSoundState(sound_state.get());
osg::ref_ptr< osgAudio::SoundUpdateCB > soundCB = new osgAudio::SoundUpdateCB;
soundCB->setSoundState( sound_state.get() );
float radius = 0.5;
if (occlude)
{
osgAudio::OccludeCallback* cb = new osgAudio::OccludeCallback(root);
cb->setNearThreshold(radius*1.1);
soundCB->setOccludeCallback( cb );
}
// Create a transformation node onto we will attach a soundnode
osg::PositionAttitudeTransform *sound_transform = new osg::PositionAttitudeTransform;
// Create a sphere so we can "see" the sound
osg::ref_ptr<osg::Geode> geode = new osg::Geode;
geode->setUpdateCallback( soundCB.get() );
osg::TessellationHints* hints = new osg::TessellationHints;
hints->setDetailRatio(0.5f);
geode->addDrawable(new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(0.0f,0.0f,0.0f),radius),hints));
sound_transform->addChild(geode.get());
return sound_transform;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/drivers/canbus/can_comm/protocol_data.h"
#include "gtest/gtest.h"
#include "modules/canbus/proto/chassis_detail.pb.h"
namespace apollo {
namespace drivers {
namespace canbus {
using ::apollo::canbus::ChassisDetail;
TEST(ProtocolDataTest, CheckSum) {
const uint8_t INPUT[] = {0x00, 0x12, 0x00, 0x13, 0x00, 0xF3, 0x00, 0x00};
const uint8_t result =
ProtocolData<apollo::canbus::ChassisDetail>::CalculateCheckSum(INPUT, 8);
EXPECT_EQ(0xE7, result);
}
} // namespace canbus
} // namespace drivers
} // namespace apollo
<commit_msg>Canbus: refactor the unit_test to check ProtocolData::BoundedValue()<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/drivers/canbus/can_comm/protocol_data.h"
#include "gtest/gtest.h"
#include "modules/canbus/proto/chassis_detail.pb.h"
namespace apollo {
namespace drivers {
namespace canbus {
using ::apollo::canbus::ChassisDetail;
TEST(ProtocolDataTest, CheckSum) {
const uint8_t INPUT[] = {0x00, 0x12, 0x00, 0x13, 0x00, 0xF3, 0x00, 0x00};
const uint8_t result =
ProtocolData<apollo::canbus::ChassisDetail>::CalculateCheckSum(INPUT, 8);
EXPECT_EQ(0xE7, result);
}
TEST(ProtocolDataTest, BoundedValue) {
const double_t input = 5.0;
const double_t min_bound = 0.0;
const double_t max_bound = M_PI;
const double_t result =
ProtocolData<apollo::canbus::ChassisDetail>::BoundedValue(
min_bound, max_bound, input);
EXPECT_EQ(M_PI, result);
}
} // namespace canbus
} // namespace drivers
} // namespace apollo
<|endoftext|> |
<commit_before>//
// This macro attaches to a PROOF session, possibly at the indicated URL.
// In the case non existing PROOF session is found and no URL is given, the macro
// tries to start a local PROOF session.
#include "Getline.h"
#include "TEnv.h"
#include "TProof.h"
#include "TString.h"
#include "TSystem.h"
Int_t getXrootdPid(Int_t port);
// By default we start a cluster on the local machine
const char *refloc = "proof://localhost:11093";
TProof *getProof(const char *url, Int_t nwrks, const char *dir, const char *opt = "ask")
{
TProof *p = 0;
TProof *pold = gProof;
// If an URL has specified get a session there
if (url && strlen(url) > 0 && strcmp(url, refloc)) {
p = TProof::Open(url);
if (p && p->IsValid()) {
// Done
return p;
} else {
Printf("getProof: could not get/start a valid session at %s - try local", url);
}
}
p = 0;
// Is there something valid running elsewhere?
if (pold && pold->IsValid()) {
if (url && strlen(url) > 0)
Printf("getProof: attaching to existing valid session at %s ", pold->GetMaster());
return pold;
}
// Is there something valid running elsewhere?
if (!dir || strlen(dir) <= 0 || gSystem->AccessPathName(dir, kWritePermission)) {
Printf("getProof: tutorial dir missing or not writable - cannot continue ");
return p;
}
#ifdef WIN32
// No support for local PROOF on Win32 (yet; the optimized local Proof will work there too)
Printf("getProof: local PROOF not yet supported on Windows, sorry!");
return p;
#else
// Local url (use a special port to try to not disturb running daemons)
Int_t lportx = 11094;
Int_t lportp = 11093;
url = (url && strlen(url) > 0) ? url : refloc;
TUrl u(url);
u.SetProtocol("proof");
u.SetPort(lportp);
TString lurl = u.GetUrl();
// Temp dir for tutorial daemons
TString tutdir = dir;
// Prepare to start the daemon
TString workarea = Form("%s/proof", tutdir.Data());
TString xpdcf(Form("%s/xpd.cf",tutdir.Data()));
TString xpdlog(Form("%s/xpd.log",tutdir.Data()));
TString xpdpid(Form("%s/xpd.pid",tutdir.Data()));
TString proofsessions(Form("%s/sessions",tutdir.Data()));
TString cmd;
Int_t rc = 0;
// Is there something listening already ?
Int_t pid = -1;
Bool_t restart = kTRUE;
gEnv->SetValue("XProof.FirstConnectMaxCnt",1);
Printf("getProof: checking for an existing daemon ...");
TProofMgr *mgr = TProof::Mgr(lurl);
if (mgr && mgr->IsValid()) {
restart = kFALSE;
pid = getXrootdPid(lportx);
Printf("getProof: daemon found listening on dedicated ports {%d,%d} (pid: %d)",
lportx, lportp, pid);
if (!strcmp(opt,"ask")) {
char *answer = Getline("getProof: would you like to restart it (N,Y)? [N] ");
if (answer && (answer[0] == 'Y' || answer[0] == 'y'))
restart = kTRUE;
}
if (!strcmp(opt,"force"))
// Always restart
restart = kTRUE;
// Cleanup, if required
if (restart) {
Printf("getProof: cleaning existing instance ...");
// Disconnect the manager
delete mgr;
// Cleanimg up existing daemon
cmd = Form("kill -9 %d", pid);
if ((rc = gSystem->Exec(cmd)) != 0)
Printf("getProof: problems stopping xrootd process %p (%d)", pid, rc);
// Remove the tutorial dir
cmd = Form("rm -fr %s/*", tutdir.Data());
gSystem->Exec(cmd);
}
}
if (restart) {
// Try to start something locally; make sure that evrything is there
char *xrootd = gSystem->Which(gSystem->Getenv("PATH"), "xrootd", kExecutePermission);
if (!xrootd) {
Printf("getProof: xrootd not found: please check the environment!");
return p;
}
// Try to start something locally; create the xrootd config file
FILE *fcf = fopen(xpdcf.Data(), "w");
if (!fcf) {
Printf("getProof: could not create config file for XPD (%s)", xpdcf.Data());
return p;
}
fprintf(fcf,"### Load the XrdProofd protocol on port %d\n", lportp);
fprintf(fcf,"xrd.protocol xproofd:%d libXrdProofd.so\n", lportp);
if (nwrks > 0) {
fprintf(fcf,"### Force number of local workers\n");
fprintf(fcf,"xpd.localwrks %d\n", nwrks);
}
fprintf(fcf,"### Root path for working dir\n");
fprintf(fcf,"xpd.workdir %s\n", workarea.Data());
fprintf(fcf,"### Limit the number of query results kept in the master sandbox\n");
fprintf(fcf,"xpd.putrc ProofServ.UserQuotas: maxquerykept=10\n");
fclose(fcf);
Printf("getProof: xrootd config file at %s", xpdcf.Data());
// Start xrootd in the background
Printf("getProof: xrootd log file at %s", xpdlog.Data());
cmd = Form("%s -c %s -b -l %s -n xpd-tutorial -p %d",
xrootd, xpdcf.Data(), xpdlog.Data(), lportx);
Printf("(NB: any error line from XrdClientSock::RecvRaw and XrdClientMessage::ReadRaw should be ignored)");
if ((rc = gSystem->Exec(cmd)) != 0) {
Printf("getProof: problems starting xrootd (%d)", rc);
return p;
}
delete[] xrootd;
// Wait a bit
Printf("getProof: waiting for xrootd to start ...");
gSystem->Sleep(2000);
pid = getXrootdPid(lportx);
Printf("getProof: xrootd pid: %d", pid);
// Save it in the PID file
FILE *fpid = fopen(xpdpid.Data(), "w");
if (!fpid) {
Printf("getProof: could not create pid file for XPD");
} else {
fprintf(fpid,"%d\n", pid);
fclose(fpid);
}
}
Printf("getProof: start / attach the PROOF session ...");
// Start / attach the session now
p = TProof::Open(lurl);
if (!p || !(p->IsValid())) {
Printf("getProof: starting local session failed");
if (p) delete p;
p = 0;
return p;
}
// Return the session
return p;
#endif
}
Int_t getXrootdPid(Int_t port)
{
// Get the pid of the started xrootd process
Int_t pid = -1;
#if defined(__sun)
const char *com = "-eo pid,comm";
#elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__APPLE__)
const char *com = "ax -w -w";
#else
const char *com = "-w -w -eo pid,command";
#endif
TString cmd = Form("ps %s | grep xrootd | grep \"\\-p %d\" | grep xpd-tutorial", com, port);
FILE *fp = gSystem->OpenPipe(cmd.Data(), "r");
if (fp) {
char line[2048], rest[2048];
while (fgets(line, sizeof(line), fp)) {
sscanf(line,"%d %s", &pid, rest);
break;
}
gSystem->ClosePipe(fp);
}
// Done
return pid;
}
<commit_msg>Notify the exact name of the xrootd log file (named xrootd instances internally add their name)<commit_after>//
// This macro attaches to a PROOF session, possibly at the indicated URL.
// In the case non existing PROOF session is found and no URL is given, the macro
// tries to start a local PROOF session.
#include "Getline.h"
#include "TEnv.h"
#include "TProof.h"
#include "TString.h"
#include "TSystem.h"
Int_t getXrootdPid(Int_t port);
// By default we start a cluster on the local machine
const char *refloc = "proof://localhost:11093";
TProof *getProof(const char *url, Int_t nwrks, const char *dir, const char *opt = "ask")
{
TProof *p = 0;
TProof *pold = gProof;
// If an URL has specified get a session there
if (url && strlen(url) > 0 && strcmp(url, refloc)) {
p = TProof::Open(url);
if (p && p->IsValid()) {
// Done
return p;
} else {
Printf("getProof: could not get/start a valid session at %s - try local", url);
}
}
p = 0;
// Is there something valid running elsewhere?
if (pold && pold->IsValid()) {
if (url && strlen(url) > 0)
Printf("getProof: attaching to existing valid session at %s ", pold->GetMaster());
return pold;
}
// Is there something valid running elsewhere?
if (!dir || strlen(dir) <= 0 || gSystem->AccessPathName(dir, kWritePermission)) {
Printf("getProof: tutorial dir missing or not writable - cannot continue ");
return p;
}
#ifdef WIN32
// No support for local PROOF on Win32 (yet; the optimized local Proof will work there too)
Printf("getProof: local PROOF not yet supported on Windows, sorry!");
return p;
#else
// Local url (use a special port to try to not disturb running daemons)
Int_t lportx = 11094;
Int_t lportp = 11093;
url = (url && strlen(url) > 0) ? url : refloc;
TUrl u(url);
u.SetProtocol("proof");
u.SetPort(lportp);
TString lurl = u.GetUrl();
// Temp dir for tutorial daemons
TString tutdir = dir;
// Prepare to start the daemon
TString workarea = Form("%s/proof", tutdir.Data());
TString xpdcf(Form("%s/xpd.cf",tutdir.Data()));
TString xpdlog(Form("%s/xpd.log",tutdir.Data()));
TString xpdlogprt(Form("%s/xpd-tutorial/xpd.log",tutdir.Data()));
TString xpdpid(Form("%s/xpd.pid",tutdir.Data()));
TString proofsessions(Form("%s/sessions",tutdir.Data()));
TString cmd;
Int_t rc = 0;
// Is there something listening already ?
Int_t pid = -1;
Bool_t restart = kTRUE;
gEnv->SetValue("XProof.FirstConnectMaxCnt",1);
Printf("getProof: checking for an existing daemon ...");
TProofMgr *mgr = TProof::Mgr(lurl);
if (mgr && mgr->IsValid()) {
restart = kFALSE;
pid = getXrootdPid(lportx);
Printf("getProof: daemon found listening on dedicated ports {%d,%d} (pid: %d)",
lportx, lportp, pid);
if (!strcmp(opt,"ask")) {
char *answer = Getline("getProof: would you like to restart it (N,Y)? [N] ");
if (answer && (answer[0] == 'Y' || answer[0] == 'y'))
restart = kTRUE;
}
if (!strcmp(opt,"force"))
// Always restart
restart = kTRUE;
// Cleanup, if required
if (restart) {
Printf("getProof: cleaning existing instance ...");
// Disconnect the manager
delete mgr;
// Cleanimg up existing daemon
cmd = Form("kill -9 %d", pid);
if ((rc = gSystem->Exec(cmd)) != 0)
Printf("getProof: problems stopping xrootd process %p (%d)", pid, rc);
// Remove the tutorial dir
cmd = Form("rm -fr %s/*", tutdir.Data());
gSystem->Exec(cmd);
}
}
if (restart) {
// Try to start something locally; make sure that evrything is there
char *xrootd = gSystem->Which(gSystem->Getenv("PATH"), "xrootd", kExecutePermission);
if (!xrootd) {
Printf("getProof: xrootd not found: please check the environment!");
return p;
}
// Try to start something locally; create the xrootd config file
FILE *fcf = fopen(xpdcf.Data(), "w");
if (!fcf) {
Printf("getProof: could not create config file for XPD (%s)", xpdcf.Data());
return p;
}
fprintf(fcf,"### Load the XrdProofd protocol on port %d\n", lportp);
fprintf(fcf,"xrd.protocol xproofd:%d libXrdProofd.so\n", lportp);
if (nwrks > 0) {
fprintf(fcf,"### Force number of local workers\n");
fprintf(fcf,"xpd.localwrks %d\n", nwrks);
}
fprintf(fcf,"### Root path for working dir\n");
fprintf(fcf,"xpd.workdir %s\n", workarea.Data());
fprintf(fcf,"### Limit the number of query results kept in the master sandbox\n");
fprintf(fcf,"xpd.putrc ProofServ.UserQuotas: maxquerykept=10\n");
fclose(fcf);
Printf("getProof: xrootd config file at %s", xpdcf.Data());
// Start xrootd in the background
Printf("getProof: xrootd log file at %s", xpdlogprt.Data());
cmd = Form("%s -c %s -b -l %s -n xpd-tutorial -p %d",
xrootd, xpdcf.Data(), xpdlog.Data(), lportx);
Printf("(NB: any error line from XrdClientSock::RecvRaw and XrdClientMessage::ReadRaw should be ignored)");
if ((rc = gSystem->Exec(cmd)) != 0) {
Printf("getProof: problems starting xrootd (%d)", rc);
return p;
}
delete[] xrootd;
// Wait a bit
Printf("getProof: waiting for xrootd to start ...");
gSystem->Sleep(2000);
pid = getXrootdPid(lportx);
Printf("getProof: xrootd pid: %d", pid);
// Save it in the PID file
FILE *fpid = fopen(xpdpid.Data(), "w");
if (!fpid) {
Printf("getProof: could not create pid file for XPD");
} else {
fprintf(fpid,"%d\n", pid);
fclose(fpid);
}
}
Printf("getProof: start / attach the PROOF session ...");
// Start / attach the session now
p = TProof::Open(lurl);
if (!p || !(p->IsValid())) {
Printf("getProof: starting local session failed");
if (p) delete p;
p = 0;
return p;
}
// Return the session
return p;
#endif
}
Int_t getXrootdPid(Int_t port)
{
// Get the pid of the started xrootd process
Int_t pid = -1;
#if defined(__sun)
const char *com = "-eo pid,comm";
#elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__APPLE__)
const char *com = "ax -w -w";
#else
const char *com = "-w -w -eo pid,command";
#endif
TString cmd = Form("ps %s | grep xrootd | grep \"\\-p %d\" | grep xpd-tutorial", com, port);
FILE *fp = gSystem->OpenPipe(cmd.Data(), "r");
if (fp) {
char line[2048], rest[2048];
while (fgets(line, sizeof(line), fp)) {
sscanf(line,"%d %s", &pid, rest);
break;
}
gSystem->ClosePipe(fp);
}
// Done
return pid;
}
<|endoftext|> |
<commit_before>//===- Local.cpp - Compute a local data structure graph for a function ----===//
//
// Compute the local version of the data structure graph for a function. The
// external interface to this file is the DSGraph constructor.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/DataStructure.h"
#include "llvm/iMemory.h"
#include "llvm/iTerminators.h"
#include "llvm/iPHINode.h"
#include "llvm/iOther.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Function.h"
#include "llvm/GlobalVariable.h"
#include "llvm/Support/InstVisitor.h"
#include "llvm/Target/TargetData.h"
#include "Support/Statistic.h"
// FIXME: This should eventually be a FunctionPass that is automatically
// aggregated into a Pass.
//
#include "llvm/Module.h"
using std::map;
using std::vector;
static RegisterAnalysis<LocalDataStructures>
X("datastructure", "Local Data Structure Analysis");
using namespace DataStructureAnalysis;
namespace DataStructureAnalysis {
// FIXME: Do something smarter with target data!
TargetData TD("temp-td");
unsigned PointerSize(TD.getPointerSize());
// isPointerType - Return true if this type is big enough to hold a pointer.
bool isPointerType(const Type *Ty) {
if (isa<PointerType>(Ty))
return true;
else if (Ty->isPrimitiveType() && Ty->isInteger())
return Ty->getPrimitiveSize() >= PointerSize;
return false;
}
}
namespace {
//===--------------------------------------------------------------------===//
// GraphBuilder Class
//===--------------------------------------------------------------------===//
//
/// This class is the builder class that constructs the local data structure
/// graph by performing a single pass over the function in question.
///
class GraphBuilder : InstVisitor<GraphBuilder> {
DSGraph &G;
vector<DSNode*> &Nodes;
DSNodeHandle &RetNode; // Node that gets returned...
map<Value*, DSNodeHandle> &ValueMap;
vector<vector<DSNodeHandle> > &FunctionCalls;
public:
GraphBuilder(DSGraph &g, vector<DSNode*> &nodes, DSNodeHandle &retNode,
map<Value*, DSNodeHandle> &vm,
vector<vector<DSNodeHandle> > &fc)
: G(g), Nodes(nodes), RetNode(retNode), ValueMap(vm), FunctionCalls(fc) {
// Create scalar nodes for all pointer arguments...
for (Function::aiterator I = G.getFunction().abegin(),
E = G.getFunction().aend(); I != E; ++I)
if (isPointerType(I->getType()))
getValueDest(*I);
visit(G.getFunction()); // Single pass over the function
// Not inlining, only eliminate trivially dead nodes.
G.removeTriviallyDeadNodes();
}
private:
// Visitor functions, used to handle each instruction type we encounter...
friend class InstVisitor<GraphBuilder>;
void visitMallocInst(MallocInst &MI) { handleAlloc(MI, DSNode::NewNode); }
void visitAllocaInst(AllocaInst &AI) { handleAlloc(AI, DSNode::AllocaNode);}
void handleAlloc(AllocationInst &AI, DSNode::NodeTy NT);
void visitPHINode(PHINode &PN);
void visitGetElementPtrInst(GetElementPtrInst &GEP);
void visitReturnInst(ReturnInst &RI);
void visitLoadInst(LoadInst &LI);
void visitStoreInst(StoreInst &SI);
void visitCallInst(CallInst &CI);
void visitSetCondInst(SetCondInst &SCI) {} // SetEQ & friends are ignored
void visitFreeInst(FreeInst &FI) {} // Ignore free instructions
void visitCastInst(CastInst &CI);
void visitInstruction(Instruction &I) {}
private:
// Helper functions used to implement the visitation functions...
/// createNode - Create a new DSNode, ensuring that it is properly added to
/// the graph.
///
DSNode *createNode(DSNode::NodeTy NodeType, const Type *Ty);
/// getValueNode - Return a DSNode that corresponds the the specified LLVM
/// value. This either returns the already existing node, or creates a new
/// one and adds it to the graph, if none exists.
///
DSNodeHandle getValueNode(Value &V);
/// getValueDest - Return the DSNode that the actual value points to. This
/// is basically the same thing as: getLink(getValueNode(V), 0)
///
DSNodeHandle &getValueDest(Value &V);
/// getGlobalNode - Just like getValueNode, except the global node itself is
/// returned, not a scalar node pointing to a global.
///
DSNodeHandle &getGlobalNode(GlobalValue &V);
/// getLink - This method is used to return the specified link in the
/// specified node if one exists. If a link does not already exist (it's
/// null), then we create a new node, link it, then return it. We must
/// specify the type of the Node field we are accessing so that we know what
/// type should be linked to if we need to create a new node.
///
DSNodeHandle &getLink(const DSNodeHandle &Node, unsigned Link,
const Type *FieldTy);
};
}
//===----------------------------------------------------------------------===//
// DSGraph constructor - Simply use the GraphBuilder to construct the local
// graph.
DSGraph::DSGraph(Function &F) : Func(&F) {
// Use the graph builder to construct the local version of the graph
GraphBuilder B(*this, Nodes, RetNode, ValueMap, FunctionCalls);
markIncompleteNodes();
}
//===----------------------------------------------------------------------===//
// Helper method implementations...
//
// createNode - Create a new DSNode, ensuring that it is properly added to the
// graph.
//
DSNode *GraphBuilder::createNode(DSNode::NodeTy NodeType, const Type *Ty) {
DSNode *N = new DSNode(NodeType, Ty);
Nodes.push_back(N);
return N;
}
// getGlobalNode - Just like getValueNode, except the global node itself is
// returned, not a scalar node pointing to a global.
//
DSNodeHandle &GraphBuilder::getGlobalNode(GlobalValue &V) {
DSNodeHandle &NH = ValueMap[&V];
if (NH.getNode()) return NH; // Already have a node? Just return it...
// Create a new global node for this global variable...
DSNode *G = createNode(DSNode::GlobalNode, V.getType()->getElementType());
G->addGlobal(&V);
// If this node has outgoing edges, make sure to recycle the same node for
// each use. For functions and other global variables, this is unneccesary,
// so avoid excessive merging by cloning these nodes on demand.
//
NH.setNode(G);
return NH;
}
// getValueNode - Return a DSNode that corresponds the the specified LLVM value.
// This either returns the already existing node, or creates a new one and adds
// it to the graph, if none exists.
//
DSNodeHandle GraphBuilder::getValueNode(Value &V) {
assert(isPointerType(V.getType()) && "Should only use pointer scalars!");
// Do not share the pointer value to globals... this would cause way too much
// false merging.
//
DSNodeHandle &NH = ValueMap[&V];
if (!isa<GlobalValue>(V) && NH.getNode())
return NH; // Already have a node? Just return it...
// Otherwise we need to create a new scalar node...
DSNode *N = createNode(DSNode::ScalarNode, V.getType());
// If this is a global value, create the global pointed to.
if (GlobalValue *GV = dyn_cast<GlobalValue>(&V)) {
N->addEdgeTo(0, getGlobalNode(*GV));
return DSNodeHandle(N, 0);
} else {
NH.setOffset(0);
NH.setNode(N);
}
return NH;
}
/// getValueDest - Return the DSNode that the actual value points to. This
/// is basically the same thing as: getLink(getValueNode(V), 0)
///
DSNodeHandle &GraphBuilder::getValueDest(Value &V) {
return getLink(getValueNode(V), 0, V.getType());
}
/// getLink - This method is used to return the specified link in the
/// specified node if one exists. If a link does not already exist (it's
/// null), then we create a new node, link it, then return it. We must
/// specify the type of the Node field we are accessing so that we know what
/// type should be linked to if we need to create a new node.
///
DSNodeHandle &GraphBuilder::getLink(const DSNodeHandle &node,
unsigned LinkNo, const Type *FieldTy) {
DSNodeHandle &Node = const_cast<DSNodeHandle&>(node);
DSNodeHandle *Link = Node.getLink(LinkNo);
if (Link) return *Link;
// If the link hasn't been created yet, make and return a new shadow node of
// the appropriate type for FieldTy...
//
// If we are indexing with a typed pointer, then the thing we are pointing
// to is of the pointed type. If we are pointing to it with an integer
// (because of cast to an integer), we represent it with a void type.
//
const Type *ReqTy;
if (const PointerType *Ptr = dyn_cast<PointerType>(FieldTy))
ReqTy = Ptr->getElementType();
else
ReqTy = Type::VoidTy;
DSNode *N = createNode(DSNode::ShadowNode, ReqTy);
Node.setLink(LinkNo, N);
return *Node.getLink(LinkNo);
}
//===----------------------------------------------------------------------===//
// Specific instruction type handler implementations...
//
/// Alloca & Malloc instruction implementation - Simply create a new memory
/// object, pointing the scalar to it.
///
void GraphBuilder::handleAlloc(AllocationInst &AI, DSNode::NodeTy NodeType) {
DSNode *New = createNode(NodeType, AI.getAllocatedType());
// Make the scalar point to the new node...
getValueNode(AI).addEdgeTo(New);
}
// PHINode - Make the scalar for the PHI node point to all of the things the
// incoming values point to... which effectively causes them to be merged.
//
void GraphBuilder::visitPHINode(PHINode &PN) {
if (!isPointerType(PN.getType())) return; // Only pointer PHIs
DSNodeHandle &ScalarDest = getValueDest(PN);
for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
if (!isa<ConstantPointerNull>(PN.getIncomingValue(i)))
ScalarDest.mergeWith(getValueDest(*PN.getIncomingValue(i)));
}
void GraphBuilder::visitGetElementPtrInst(GetElementPtrInst &GEP) {
DSNodeHandle Value = getValueDest(*GEP.getOperand(0));
unsigned Offset = 0;
const Type *CurTy = GEP.getOperand(0)->getType();
for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i)
if (GEP.getOperand(i)->getType() == Type::LongTy) {
if (GEP.getOperand(i) != Constant::getNullValue(Type::LongTy)) {
std::cerr << "Array indexing not handled yet!\n";
}
CurTy = cast<SequentialType>(CurTy)->getElementType();
} else if (GEP.getOperand(i)->getType() == Type::UByteTy) {
unsigned FieldNo = cast<ConstantUInt>(GEP.getOperand(i))->getValue();
const StructType *STy = cast<StructType>(CurTy);
Offset += TD.getStructLayout(STy)->MemberOffsets[FieldNo];
CurTy = STy->getContainedType(FieldNo);
}
// Add in the offset calculated...
Value.setOffset(Value.getOffset()+Offset);
// Value is now the pointer we want to GEP to be...
getValueNode(GEP).addEdgeTo(Value);
}
void GraphBuilder::visitLoadInst(LoadInst &LI) {
DSNodeHandle &Ptr = getValueDest(*LI.getOperand(0));
if (isPointerType(LI.getType()))
getValueNode(LI).addEdgeTo(getLink(Ptr, 0, LI.getType()));
}
void GraphBuilder::visitStoreInst(StoreInst &SI) {
DSNodeHandle &Dest = getValueDest(*SI.getOperand(1));
// Avoid adding edges from null, or processing non-"pointer" stores
if (isPointerType(SI.getOperand(0)->getType()) &&
!isa<ConstantPointerNull>(SI.getOperand(0))) {
Dest.addEdgeTo(getValueDest(*SI.getOperand(0)));
}
}
void GraphBuilder::visitReturnInst(ReturnInst &RI) {
if (RI.getNumOperands() && isPointerType(RI.getOperand(0)->getType()) &&
!isa<ConstantPointerNull>(RI.getOperand(0))) {
DSNodeHandle &Value = getValueDest(*RI.getOperand(0));
Value.mergeWith(RetNode);
RetNode = Value;
}
}
void GraphBuilder::visitCallInst(CallInst &CI) {
// Add a new function call entry...
FunctionCalls.push_back(vector<DSNodeHandle>());
vector<DSNodeHandle> &Args = FunctionCalls.back();
// Set up the return value...
if (isPointerType(CI.getType()))
Args.push_back(getLink(getValueNode(CI), 0, CI.getType()));
else
Args.push_back(DSNodeHandle());
unsigned Start = 0;
// Special case for a direct call, avoid creating spurious scalar node...
if (GlobalValue *GV = dyn_cast<GlobalValue>(CI.getOperand(0))) {
Args.push_back(getGlobalNode(*GV));
Start = 1;
}
// Pass the arguments in...
for (unsigned i = Start, e = CI.getNumOperands(); i != e; ++i)
if (isPointerType(CI.getOperand(i)->getType()))
Args.push_back(getLink(getValueNode(*CI.getOperand(i)), 0,
CI.getOperand(i)->getType()));
}
/// Handle casts...
void GraphBuilder::visitCastInst(CastInst &CI) {
if (isPointerType(CI.getType()) && isPointerType(CI.getOperand(0)->getType()))
getValueNode(CI).addEdgeTo(getLink(getValueNode(*CI.getOperand(0)), 0,
CI.getOperand(0)->getType()));
}
//===----------------------------------------------------------------------===//
// LocalDataStructures Implementation
//===----------------------------------------------------------------------===//
// releaseMemory - If the pass pipeline is done with this pass, we can release
// our memory... here...
//
void LocalDataStructures::releaseMemory() {
for (std::map<const Function*, DSGraph*>::iterator I = DSInfo.begin(),
E = DSInfo.end(); I != E; ++I)
delete I->second;
// Empty map so next time memory is released, data structures are not
// re-deleted.
DSInfo.clear();
}
bool LocalDataStructures::run(Module &M) {
// Calculate all of the graphs...
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
if (!I->isExternal())
DSInfo.insert(std::make_pair(I, new DSGraph(*I)));
return false;
}
<commit_msg><commit_after>//===- Local.cpp - Compute a local data structure graph for a function ----===//
//
// Compute the local version of the data structure graph for a function. The
// external interface to this file is the DSGraph constructor.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/DataStructure.h"
#include "llvm/iMemory.h"
#include "llvm/iTerminators.h"
#include "llvm/iPHINode.h"
#include "llvm/iOther.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Function.h"
#include "llvm/GlobalVariable.h"
#include "llvm/Support/InstVisitor.h"
#include "llvm/Target/TargetData.h"
#include "Support/Statistic.h"
// FIXME: This should eventually be a FunctionPass that is automatically
// aggregated into a Pass.
//
#include "llvm/Module.h"
using std::map;
using std::vector;
static RegisterAnalysis<LocalDataStructures>
X("datastructure", "Local Data Structure Analysis");
using namespace DataStructureAnalysis;
namespace DataStructureAnalysis {
// FIXME: Do something smarter with target data!
TargetData TD("temp-td");
unsigned PointerSize(TD.getPointerSize());
// isPointerType - Return true if this type is big enough to hold a pointer.
bool isPointerType(const Type *Ty) {
if (isa<PointerType>(Ty))
return true;
else if (Ty->isPrimitiveType() && Ty->isInteger())
return Ty->getPrimitiveSize() >= PointerSize;
return false;
}
}
namespace {
//===--------------------------------------------------------------------===//
// GraphBuilder Class
//===--------------------------------------------------------------------===//
//
/// This class is the builder class that constructs the local data structure
/// graph by performing a single pass over the function in question.
///
class GraphBuilder : InstVisitor<GraphBuilder> {
DSGraph &G;
vector<DSNode*> &Nodes;
DSNodeHandle &RetNode; // Node that gets returned...
map<Value*, DSNodeHandle> &ValueMap;
vector<vector<DSNodeHandle> > &FunctionCalls;
public:
GraphBuilder(DSGraph &g, vector<DSNode*> &nodes, DSNodeHandle &retNode,
map<Value*, DSNodeHandle> &vm,
vector<vector<DSNodeHandle> > &fc)
: G(g), Nodes(nodes), RetNode(retNode), ValueMap(vm), FunctionCalls(fc) {
// Create scalar nodes for all pointer arguments...
for (Function::aiterator I = G.getFunction().abegin(),
E = G.getFunction().aend(); I != E; ++I)
if (isPointerType(I->getType()))
getValueDest(*I);
visit(G.getFunction()); // Single pass over the function
// Not inlining, only eliminate trivially dead nodes.
G.removeTriviallyDeadNodes();
}
private:
// Visitor functions, used to handle each instruction type we encounter...
friend class InstVisitor<GraphBuilder>;
void visitMallocInst(MallocInst &MI) { handleAlloc(MI, DSNode::NewNode); }
void visitAllocaInst(AllocaInst &AI) { handleAlloc(AI, DSNode::AllocaNode);}
void handleAlloc(AllocationInst &AI, DSNode::NodeTy NT);
void visitPHINode(PHINode &PN);
void visitGetElementPtrInst(GetElementPtrInst &GEP);
void visitReturnInst(ReturnInst &RI);
void visitLoadInst(LoadInst &LI);
void visitStoreInst(StoreInst &SI);
void visitCallInst(CallInst &CI);
void visitSetCondInst(SetCondInst &SCI) {} // SetEQ & friends are ignored
void visitFreeInst(FreeInst &FI) {} // Ignore free instructions
void visitCastInst(CastInst &CI);
void visitInstruction(Instruction &I) {}
private:
// Helper functions used to implement the visitation functions...
/// createNode - Create a new DSNode, ensuring that it is properly added to
/// the graph.
///
DSNode *createNode(DSNode::NodeTy NodeType, const Type *Ty);
/// getValueNode - Return a DSNode that corresponds the the specified LLVM
/// value. This either returns the already existing node, or creates a new
/// one and adds it to the graph, if none exists.
///
DSNodeHandle getValueNode(Value &V);
/// getValueDest - Return the DSNode that the actual value points to. This
/// is basically the same thing as: getLink(getValueNode(V), 0)
///
DSNodeHandle &getValueDest(Value &V);
/// getGlobalNode - Just like getValueNode, except the global node itself is
/// returned, not a scalar node pointing to a global.
///
DSNodeHandle &getGlobalNode(GlobalValue &V);
/// getLink - This method is used to return the specified link in the
/// specified node if one exists. If a link does not already exist (it's
/// null), then we create a new node, link it, then return it. We must
/// specify the type of the Node field we are accessing so that we know what
/// type should be linked to if we need to create a new node.
///
DSNodeHandle &getLink(const DSNodeHandle &Node, unsigned Link,
const Type *FieldTy);
};
}
//===----------------------------------------------------------------------===//
// DSGraph constructor - Simply use the GraphBuilder to construct the local
// graph.
DSGraph::DSGraph(Function &F) : Func(&F) {
// Use the graph builder to construct the local version of the graph
GraphBuilder B(*this, Nodes, RetNode, ValueMap, FunctionCalls);
markIncompleteNodes();
}
//===----------------------------------------------------------------------===//
// Helper method implementations...
//
// createNode - Create a new DSNode, ensuring that it is properly added to the
// graph.
//
DSNode *GraphBuilder::createNode(DSNode::NodeTy NodeType, const Type *Ty) {
DSNode *N = new DSNode(NodeType, Ty);
Nodes.push_back(N);
return N;
}
// getGlobalNode - Just like getValueNode, except the global node itself is
// returned, not a scalar node pointing to a global.
//
DSNodeHandle &GraphBuilder::getGlobalNode(GlobalValue &V) {
DSNodeHandle &NH = ValueMap[&V];
if (NH.getNode()) return NH; // Already have a node? Just return it...
// Create a new global node for this global variable...
DSNode *G = createNode(DSNode::GlobalNode, V.getType()->getElementType());
G->addGlobal(&V);
// If this node has outgoing edges, make sure to recycle the same node for
// each use. For functions and other global variables, this is unneccesary,
// so avoid excessive merging by cloning these nodes on demand.
//
NH.setNode(G);
return NH;
}
// getValueNode - Return a DSNode that corresponds the the specified LLVM value.
// This either returns the already existing node, or creates a new one and adds
// it to the graph, if none exists.
//
DSNodeHandle GraphBuilder::getValueNode(Value &V) {
assert(isPointerType(V.getType()) && "Should only use pointer scalars!");
// Do not share the pointer value to globals... this would cause way too much
// false merging.
//
DSNodeHandle &NH = ValueMap[&V];
if (!isa<GlobalValue>(V) && NH.getNode())
return NH; // Already have a node? Just return it...
// Otherwise we need to create a new scalar node...
DSNode *N = createNode(DSNode::ScalarNode, V.getType());
// If this is a global value, create the global pointed to.
if (GlobalValue *GV = dyn_cast<GlobalValue>(&V)) {
N->addEdgeTo(0, getGlobalNode(*GV));
return DSNodeHandle(N, 0);
} else {
NH.setOffset(0);
NH.setNode(N);
}
return NH;
}
/// getValueDest - Return the DSNode that the actual value points to. This
/// is basically the same thing as: getLink(getValueNode(V), 0)
///
DSNodeHandle &GraphBuilder::getValueDest(Value &V) {
return getLink(getValueNode(V), 0, V.getType());
}
/// getLink - This method is used to return the specified link in the
/// specified node if one exists. If a link does not already exist (it's
/// null), then we create a new node, link it, then return it. We must
/// specify the type of the Node field we are accessing so that we know what
/// type should be linked to if we need to create a new node.
///
DSNodeHandle &GraphBuilder::getLink(const DSNodeHandle &node,
unsigned LinkNo, const Type *FieldTy) {
DSNodeHandle &Node = const_cast<DSNodeHandle&>(node);
DSNodeHandle *Link = Node.getLink(LinkNo);
if (Link) return *Link;
// If the link hasn't been created yet, make and return a new shadow node of
// the appropriate type for FieldTy...
//
// If we are indexing with a typed pointer, then the thing we are pointing
// to is of the pointed type. If we are pointing to it with an integer
// (because of cast to an integer), we represent it with a void type.
//
const Type *ReqTy;
if (const PointerType *Ptr = dyn_cast<PointerType>(FieldTy))
ReqTy = Ptr->getElementType();
else
ReqTy = Type::VoidTy;
DSNode *N = createNode(DSNode::ShadowNode, ReqTy);
Node.setLink(LinkNo, N);
return *Node.getLink(LinkNo);
}
//===----------------------------------------------------------------------===//
// Specific instruction type handler implementations...
//
/// Alloca & Malloc instruction implementation - Simply create a new memory
/// object, pointing the scalar to it.
///
void GraphBuilder::handleAlloc(AllocationInst &AI, DSNode::NodeTy NodeType) {
DSNode *New = createNode(NodeType, AI.getAllocatedType());
// Make the scalar point to the new node...
getValueNode(AI).addEdgeTo(New);
}
// PHINode - Make the scalar for the PHI node point to all of the things the
// incoming values point to... which effectively causes them to be merged.
//
void GraphBuilder::visitPHINode(PHINode &PN) {
if (!isPointerType(PN.getType())) return; // Only pointer PHIs
DSNodeHandle &ScalarDest = getValueDest(PN);
for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
if (!isa<ConstantPointerNull>(PN.getIncomingValue(i)))
ScalarDest.mergeWith(getValueDest(*PN.getIncomingValue(i)));
}
void GraphBuilder::visitGetElementPtrInst(GetElementPtrInst &GEP) {
DSNodeHandle Value = getValueDest(*GEP.getOperand(0));
unsigned Offset = 0;
const Type *CurTy = GEP.getOperand(0)->getType();
for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i)
if (GEP.getOperand(i)->getType() == Type::LongTy) {
// Get the type indexing into...
const SequentialType *STy = cast<SequentialType>(CurTy);
CurTy = STy->getElementType();
if (ConstantSInt *CS = dyn_cast<ConstantSInt>(GEP.getOperand(i))) {
if (isa<PointerType>(STy))
std::cerr << "Pointer indexing not handled yet!\n";
else
Offset += CS->getValue()*TD.getTypeSize(CurTy);
} else {
// Variable index into a node. We must merge all of the elements of the
// sequential type here.
if (isa<PointerType>(STy))
std::cerr << "Pointer indexing not handled yet!\n";
else {
const ArrayType *ATy = cast<ArrayType>(STy);
unsigned ElSize = TD.getTypeSize(CurTy);
DSNode *N = Value.getNode();
assert(N && "Value must have a node!");
unsigned RawOffset = Offset+Value.getOffset();
// Loop over all of the elements of the array, merging them into the
// zero'th element.
for (unsigned i = 1, e = ATy->getNumElements(); i != e; ++i)
// Merge all of the byte components of this array element
for (unsigned j = 0; j != ElSize; ++j)
N->mergeIndexes(RawOffset+j, RawOffset+i*ElSize+j);
}
}
} else if (GEP.getOperand(i)->getType() == Type::UByteTy) {
unsigned FieldNo = cast<ConstantUInt>(GEP.getOperand(i))->getValue();
const StructType *STy = cast<StructType>(CurTy);
Offset += TD.getStructLayout(STy)->MemberOffsets[FieldNo];
CurTy = STy->getContainedType(FieldNo);
}
// Add in the offset calculated...
Value.setOffset(Value.getOffset()+Offset);
// Value is now the pointer we want to GEP to be...
getValueNode(GEP).addEdgeTo(Value);
}
void GraphBuilder::visitLoadInst(LoadInst &LI) {
DSNodeHandle &Ptr = getValueDest(*LI.getOperand(0));
if (isPointerType(LI.getType()))
getValueNode(LI).addEdgeTo(getLink(Ptr, 0, LI.getType()));
}
void GraphBuilder::visitStoreInst(StoreInst &SI) {
DSNodeHandle &Dest = getValueDest(*SI.getOperand(1));
// Avoid adding edges from null, or processing non-"pointer" stores
if (isPointerType(SI.getOperand(0)->getType()) &&
!isa<ConstantPointerNull>(SI.getOperand(0))) {
Dest.addEdgeTo(getValueDest(*SI.getOperand(0)));
}
}
void GraphBuilder::visitReturnInst(ReturnInst &RI) {
if (RI.getNumOperands() && isPointerType(RI.getOperand(0)->getType()) &&
!isa<ConstantPointerNull>(RI.getOperand(0))) {
DSNodeHandle &Value = getValueDest(*RI.getOperand(0));
Value.mergeWith(RetNode);
RetNode = Value;
}
}
void GraphBuilder::visitCallInst(CallInst &CI) {
// Add a new function call entry...
FunctionCalls.push_back(vector<DSNodeHandle>());
vector<DSNodeHandle> &Args = FunctionCalls.back();
// Set up the return value...
if (isPointerType(CI.getType()))
Args.push_back(getLink(getValueNode(CI), 0, CI.getType()));
else
Args.push_back(DSNodeHandle());
unsigned Start = 0;
// Special case for a direct call, avoid creating spurious scalar node...
if (GlobalValue *GV = dyn_cast<GlobalValue>(CI.getOperand(0))) {
Args.push_back(getGlobalNode(*GV));
Start = 1;
}
// Pass the arguments in...
for (unsigned i = Start, e = CI.getNumOperands(); i != e; ++i)
if (isPointerType(CI.getOperand(i)->getType()))
Args.push_back(getLink(getValueNode(*CI.getOperand(i)), 0,
CI.getOperand(i)->getType()));
}
/// Handle casts...
void GraphBuilder::visitCastInst(CastInst &CI) {
if (isPointerType(CI.getType()) && isPointerType(CI.getOperand(0)->getType()))
getValueNode(CI).addEdgeTo(getLink(getValueNode(*CI.getOperand(0)), 0,
CI.getOperand(0)->getType()));
}
//===----------------------------------------------------------------------===//
// LocalDataStructures Implementation
//===----------------------------------------------------------------------===//
// releaseMemory - If the pass pipeline is done with this pass, we can release
// our memory... here...
//
void LocalDataStructures::releaseMemory() {
for (std::map<const Function*, DSGraph*>::iterator I = DSInfo.begin(),
E = DSInfo.end(); I != E; ++I)
delete I->second;
// Empty map so next time memory is released, data structures are not
// re-deleted.
DSInfo.clear();
}
bool LocalDataStructures::run(Module &M) {
// Calculate all of the graphs...
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
if (!I->isExternal())
DSInfo.insert(std::make_pair(I, new DSGraph(*I)));
return false;
}
<|endoftext|> |
<commit_before>//
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
//
// bench.cpp : spdlog benchmarks
//
#include <atomic>
#include <cstdlib> // EXIT_FAILURE
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include "spdlog/spdlog.h"
#include "spdlog/async_logger.h"
#include "spdlog/sinks/file_sinks.h"
#include "spdlog/sinks/null_sink.h"
#include "utils.h"
using namespace std;
using namespace std::chrono;
using namespace spdlog;
using namespace spdlog::sinks;
using namespace utils;
void bench(int howmany, std::shared_ptr<spdlog::logger> log);
void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count);
int main(int argc, char* argv[])
{
int queue_size = 1048576;
int howmany = 1000000;
int threads = 10;
bool auto_flush = false;
int file_size = 30 * 1024 * 1024;
int rotating_files = 5;
try
{
if(argc > 1)
howmany = atoi(argv[1]);
if (argc > 2)
threads = atoi(argv[2]);
if (argc > 3)
queue_size = atoi(argv[3]);
cout << "*******************************************************************************\n";
cout << "Single thread, " << format(howmany) << " iterations, auto flush=" << auto_flush << endl;
cout << "*******************************************************************************\n";
auto rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_st", file_size, rotating_files, auto_flush);
bench(howmany, rotating_st);
auto daily_st = spdlog::daily_logger_st("daily_st", "logs/daily_st", auto_flush);
bench(howmany, daily_st);
bench(howmany, spdlog::create<null_sink_st>("null_st"));
cout << "\n*******************************************************************************\n";
cout << threads << " threads sharing same logger, " << format(howmany) << " iterations, auto_flush=" << auto_flush << endl;
cout << "*******************************************************************************\n";
auto rotating_mt = spdlog::rotating_logger_mt("rotating_mt", "logs/rotating_mt", file_size, rotating_files, auto_flush);
bench_mt(howmany, rotating_mt, threads);
auto daily_mt = spdlog::daily_logger_mt("daily_mt", "logs/daily_mt", auto_flush);
bench_mt(howmany, daily_mt, threads);
bench(howmany, spdlog::create<null_sink_st>("null_mt"));
cout << "\n*******************************************************************************\n";
cout << "async logging.. " << threads << " threads sharing same logger, " << format(howmany) << " iterations, auto_flush=" << auto_flush << endl;
cout << "*******************************************************************************\n";
spdlog::set_async_mode(queue_size);
for(int i = 0; i < 3; ++i)
{
auto as = spdlog::daily_logger_st("as", "logs/daily_async", auto_flush);
bench_mt(howmany, as, threads);
spdlog::drop("as");
}
}
catch (std::exception &ex)
{
std::cerr << "Error: " << ex.what() << std::endl;
perror("Last error");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
void bench(int howmany, std::shared_ptr<spdlog::logger> log)
{
cout << log->name() << "...\t\t" << flush;
auto start = system_clock::now();
for (auto i = 0; i < howmany; ++i)
{
log->info("Hello logger: msg number {}", i);
}
auto delta = system_clock::now() - start;
auto delta_d = duration_cast<duration<double>> (delta).count();
cout << format(int(howmany / delta_d)) << "/sec" << endl;
}
void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count)
{
cout << log->name() << "...\t\t" << flush;
std::atomic<int > msg_counter {0};
vector<thread> threads;
auto start = system_clock::now();
for (int t = 0; t < thread_count; ++t)
{
threads.push_back(std::thread([&]()
{
for(;;)
{
int counter = ++msg_counter;
if (counter > howmany) break;
log->info("Hello logger: msg number {}", counter);
}
}));
}
for(auto &t:threads)
{
t.join();
};
auto delta = system_clock::now() - start;
auto delta_d = duration_cast<duration<double>> (delta).count();
cout << format(int(howmany / delta_d)) << "/sec" << endl;
}
<commit_msg>fixed bench compilation<commit_after>//
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
//
// bench.cpp : spdlog benchmarks
//
#include <atomic>
#include <cstdlib> // EXIT_FAILURE
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include "spdlog/spdlog.h"
#include "spdlog/async_logger.h"
#include "spdlog/sinks/file_sinks.h"
#include "spdlog/sinks/null_sink.h"
#include "utils.h"
using namespace std;
using namespace std::chrono;
using namespace spdlog;
using namespace spdlog::sinks;
using namespace utils;
void bench(int howmany, std::shared_ptr<spdlog::logger> log);
void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count);
int main(int argc, char* argv[])
{
int queue_size = 1048576;
int howmany = 1000000;
int threads = 10;
int file_size = 30 * 1024 * 1024;
int rotating_files = 5;
try
{
if(argc > 1)
howmany = atoi(argv[1]);
if (argc > 2)
threads = atoi(argv[2]);
if (argc > 3)
queue_size = atoi(argv[3]);
cout << "*******************************************************************************\n";
cout << "Single thread, " << format(howmany) << " iterations" << endl;
cout << "*******************************************************************************\n";
auto rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_st", file_size, rotating_files);
bench(howmany, rotating_st);
auto daily_st = spdlog::daily_logger_st("daily_st", "logs/daily_st");
bench(howmany, daily_st);
bench(howmany, spdlog::create<null_sink_st>("null_st"));
cout << "\n*******************************************************************************\n";
cout << threads << " threads sharing same logger, " << format(howmany) << " iterations" << endl;
cout << "*******************************************************************************\n";
auto rotating_mt = spdlog::rotating_logger_mt("rotating_mt", "logs/rotating_mt", file_size, rotating_files);
bench_mt(howmany, rotating_mt, threads);
auto daily_mt = spdlog::daily_logger_mt("daily_mt", "logs/daily_mt");
bench_mt(howmany, daily_mt, threads);
bench(howmany, spdlog::create<null_sink_st>("null_mt"));
cout << "\n*******************************************************************************\n";
cout << "async logging.. " << threads << " threads sharing same logger, " << format(howmany) << " iterations " << endl;
cout << "*******************************************************************************\n";
spdlog::set_async_mode(queue_size);
for(int i = 0; i < 3; ++i)
{
auto as = spdlog::daily_logger_st("as", "logs/daily_async");
bench_mt(howmany, as, threads);
spdlog::drop("as");
}
}
catch (std::exception &ex)
{
std::cerr << "Error: " << ex.what() << std::endl;
perror("Last error");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
void bench(int howmany, std::shared_ptr<spdlog::logger> log)
{
cout << log->name() << "...\t\t" << flush;
auto start = system_clock::now();
for (auto i = 0; i < howmany; ++i)
{
log->info("Hello logger: msg number {}", i);
}
auto delta = system_clock::now() - start;
auto delta_d = duration_cast<duration<double>> (delta).count();
cout << format(int(howmany / delta_d)) << "/sec" << endl;
}
void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count)
{
cout << log->name() << "...\t\t" << flush;
std::atomic<int > msg_counter {0};
vector<thread> threads;
auto start = system_clock::now();
for (int t = 0; t < thread_count; ++t)
{
threads.push_back(std::thread([&]()
{
for(;;)
{
int counter = ++msg_counter;
if (counter > howmany) break;
log->info("Hello logger: msg number {}", counter);
}
}));
}
for(auto &t:threads)
{
t.join();
};
auto delta = system_clock::now() - start;
auto delta_d = duration_cast<duration<double>> (delta).count();
cout << format(int(howmany / delta_d)) << "/sec" << endl;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "vtrc-server/vtrc-application.h"
#include "vtrc-server/vtrc-listener-tcp.h"
#include "vtrc-server/vtrc-listener-local.h"
#include "vtrc-common/vtrc-connection-iface.h"
#include "vtrc-common/vtrc-pool-pair.h"
#include "vtrc-common/vtrc-rpc-service-wrapper.h"
#include "protocol/hello.pb.h" /// hello protocol
#include "boost/lexical_cast.hpp"
using namespace vtrc;
namespace {
class hello_service_impl: public howto::hello_service {
common::connection_iface *cl_;
void send_hello(::google::protobuf::RpcController* controller,
const ::howto::request_message* request,
::howto::response_message* response,
::google::protobuf::Closure* done) /*override*/
{
std::ostringstream oss;
oss << "Hello " << request->name( )
<< " from hello_service_impl::send_hello!\n"
<< "Your client name is '"
<< cl_->name( ) << "'.\nHave a nice day.";
response->set_hello( oss.str( ) );
done->Run( );
}
public:
hello_service_impl( common::connection_iface *cl )
:cl_(cl)
{ }
static std::string const &service_name( )
{
return howto::hello_service::descriptor( )->full_name( );
}
};
class hello_application: public server::application {
typedef vtrc::shared_ptr<common::rpc_service_wrapper> wrapper_sptr;
public:
hello_application( vtrc::common::pool_pair &pp )
:vtrc::server::application(pp)
{ }
wrapper_sptr get_service_by_name( common::connection_iface* connection,
const std::string &service_name )
{
if( service_name == hello_service_impl::service_name( ) ) {
hello_service_impl *new_impl = new hello_service_impl(connection);
return vtrc::make_shared<common::rpc_service_wrapper>( new_impl );
}
return wrapper_sptr( );
}
};
}
int main( int argc, const char **argv )
{
common::pool_pair pp( 1, 1 );
hello_application app( pp );
const char *address = "127.0.0.1";
unsigned short port = 56560;
if( argc > 2 ) {
address = argv[1];
port = boost::lexical_cast<unsigned short>( argv[2] );
} else if( argc > 1 ) {
port = boost::lexical_cast<unsigned short>( argv[1] );
}
try {
vtrc::shared_ptr<server::listener>
tcp( server::listeners::tcp::create( app, address, port ) );
tcp->start( );
} catch( const std::exception &ex ) {
std::cerr << "Hello, world failed: " << ex.what( ) << "\n";
}
pp.join_all( );
/// make valgrind happy.
google::protobuf::ShutdownProtobufLibrary( );
return 0;
}
<commit_msg>proto<commit_after>#include <iostream>
#include "vtrc-server/vtrc-application.h"
#include "vtrc-server/vtrc-listener-tcp.h"
#include "vtrc-server/vtrc-listener-local.h"
#include "vtrc-common/vtrc-connection-iface.h"
#include "vtrc-common/vtrc-pool-pair.h"
#include "vtrc-common/vtrc-rpc-service-wrapper.h"
#include "protocol/hello.pb.h" /// hello protocol
#include "boost/lexical_cast.hpp"
using namespace vtrc;
namespace {
class hello_service_impl: public howto::hello_service {
common::connection_iface *cl_;
void send_hello(::google::protobuf::RpcController* controller,
const ::howto::request_message* request,
::howto::response_message* response,
::google::protobuf::Closure* done) /*override*/
{
std::ostringstream oss;
oss << "Hello " << request->name( )
<< " from hello_service_impl::send_hello!\n"
<< "Your transport name is '"
<< cl_->name( ) << "'.\nHave a nice day.";
response->set_hello( oss.str( ) );
done->Run( );
}
public:
hello_service_impl( common::connection_iface *cl )
:cl_(cl)
{ }
static std::string const &service_name( )
{
return howto::hello_service::descriptor( )->full_name( );
}
};
class hello_application: public server::application {
typedef vtrc::shared_ptr<common::rpc_service_wrapper> wrapper_sptr;
public:
hello_application( vtrc::common::pool_pair &pp )
:vtrc::server::application(pp)
{ }
wrapper_sptr get_service_by_name( common::connection_iface* connection,
const std::string &service_name )
{
if( service_name == hello_service_impl::service_name( ) ) {
hello_service_impl *new_impl = new hello_service_impl(connection);
return vtrc::make_shared<common::rpc_service_wrapper>( new_impl );
}
return wrapper_sptr( );
}
};
}
int main( int argc, const char **argv )
{
common::pool_pair pp( 1, 1 );
hello_application app( pp );
const char *address = "127.0.0.1";
unsigned short port = 56560;
if( argc > 2 ) {
address = argv[1];
port = boost::lexical_cast<unsigned short>( argv[2] );
} else if( argc > 1 ) {
port = boost::lexical_cast<unsigned short>( argv[1] );
}
try {
vtrc::shared_ptr<server::listener>
tcp( server::listeners::tcp::create( app, address, port ) );
tcp->start( );
} catch( const std::exception &ex ) {
std::cerr << "Hello, world failed: " << ex.what( ) << "\n";
}
pp.join_all( );
/// make valgrind happy.
google::protobuf::ShutdownProtobufLibrary( );
return 0;
}
<|endoftext|> |
<commit_before>#include <Ancona/Framework/Config/Config.hpp>
#include <Ancona/Framework/Serializing/Serializing.hpp>
using namespace ild;
MapSerializer::MapSerializer(
std::string key,
ScreenSystemsContainer & systems,
std::shared_ptr<RequestList> request,
bool loading,
bool snapshotSave) :
_key(key),
_request(request),
_loadingContext(new SerializingContext(systems)),
_profile(systems.profile()),
_loading(loading),
_snapshotSave(snapshotSave)
{
Assert(_profile != -1, "A profile must be specified for the map");
}
bool MapSerializer::ContinueLoading()
{
switch (_state)
{
case LoadingMetaData:
LoadMetaData();
break;
case LoadingMapFile:
LoadMapFile();
break;
case LoadingAssets:
LoadAssets();
break;
case LoadingEntities:
LoadEntities();
break;
case SerializingComponents:
SerializeComponents();
break;
case DoneSerializing:
SaveMapFiles();
return false;
}
return true;
}
void MapSerializer::LoadMetaData()
{
for (auto it : _loadingContext->systems())
{
if (_loading)
{
it.second->OnLoad();
}
}
_state = SerializerState::LoadingMapFile;
}
void MapSerializer::LoadMapFile()
{
auto saveStream = FileOperations::GetInputFileStream(Config::GetOption("SaveData"));
Json::Reader reader;
reader.parse(*saveStream, _saveRoot);
_saveProfileRoot = _saveRoot["profiles"][_profile];
_mapName = _saveProfileRoot["screen-maps"][_key].asString();
Assert(_mapName != "", "Cannot have a null map");
std::string mapFileName = "maps/" + _mapName + ".map";
auto mapStream = FileOperations::GetInputFileStream(mapFileName);
reader.parse(*mapStream, _mapRoot);
if (_loading)
{
for (Json::Value & assetJson : _mapRoot["assets"])
{
auto type = assetJson["type"].asString();
auto key = assetJson["key"].asString();
if (!_request->Contains(type, key))
{
_request->Add(type, key);
}
}
_request->Start();
}
_state = SerializerState::LoadingAssets;
}
void MapSerializer::LoadAssets()
{
if (!_loading)
{
_state = SerializerState::LoadingEntities;
return;
}
if (ResourceLibrary::DoneLoading(*_request))
{
_state = SerializerState::LoadingEntities;
}
}
void MapSerializer::LoadEntities()
{
if (!_loading)
{
_state = SerializerState::SerializingComponents;
return;
}
for (Json::Value & curEntity : _mapRoot["entities"])
{
_loadingContext->systems().systemManager().CreateEntity(curEntity.asString());
}
SerializeEntitySystemSaveables();
_state = SerializerState::SerializingComponents;
}
void MapSerializer::SerializeEntitySystemSaveables()
{
Archive entitySaveablesArc(_mapRoot, *_loadingContext.get(), _loading);
_loadingContext->systems().systemManager().Serialize(entitySaveablesArc);
}
void MapSerializer::SerializeComponents()
{
Archive mapArc(_mapRoot["systems"], *_loadingContext.get(), _loading, _snapshotSave);
Archive saveArc(_saveProfileRoot["systems"], *_loadingContext.get(), _loading, true);
for (auto systemNamePair : _loadingContext->systems().systemManager().keyedSystems())
{
SerializeSpecifiedSystem(systemNamePair, mapArc);
SerializeSpecifiedSystem(systemNamePair, saveArc);
}
if (_loading)
{
_loadingContext->systems().systemManager().FetchWaitingDependencies();
}
_mapRoot["systems"] = mapArc.CurrentBranch();
_saveRoot["systems"] = saveArc.CurrentBranch();
_state = SerializerState::DoneSerializing;
}
void MapSerializer::SerializeSpecifiedSystem(
std::pair<std::string, AbstractSystem *> systemNamePair,
Archive & currentArc)
{
if (currentArc.HasProperty(systemNamePair.first))
{
currentArc.EnterProperty(systemNamePair.first);
_loadingContext->systems().GetSystem<AbstractSystem>(systemNamePair.first)->Serialize(currentArc);
currentArc.ExitProperty();
}
}
void MapSerializer::SaveMapFiles()
{
if (_loading)
{
return;
}
auto saveStream = FileOperations::GetOutputFileStream(Config::GetOption("SaveData"));
_saveRoot["profiles"][_profile] = _saveProfileRoot;
(*saveStream) << _saveRoot;
auto mapStream = FileOperations::GetOutputFileStream("maps/" + _mapName + ".map");
(*mapStream) << _mapRoot;
}
<commit_msg>Remove obsolete saving code.<commit_after>#include <Ancona/Framework/Config/Config.hpp>
#include <Ancona/Framework/Serializing/Serializing.hpp>
using namespace ild;
MapSerializer::MapSerializer(
std::string key,
ScreenSystemsContainer & systems,
std::shared_ptr<RequestList> request,
bool loading,
bool snapshotSave) :
_key(key),
_request(request),
_loadingContext(new SerializingContext(systems)),
_profile(systems.profile()),
_loading(loading),
_snapshotSave(snapshotSave)
{
Assert(_profile != -1, "A profile must be specified for the map");
}
bool MapSerializer::ContinueLoading()
{
switch (_state)
{
case LoadingMetaData:
LoadMetaData();
break;
case LoadingMapFile:
LoadMapFile();
break;
case LoadingAssets:
LoadAssets();
break;
case LoadingEntities:
LoadEntities();
break;
case SerializingComponents:
SerializeComponents();
break;
case DoneSerializing:
SaveMapFiles();
return false;
}
return true;
}
void MapSerializer::LoadMetaData()
{
for (auto it : _loadingContext->systems())
{
if (_loading)
{
it.second->OnLoad();
}
}
_state = SerializerState::LoadingMapFile;
}
void MapSerializer::LoadMapFile()
{
auto saveStream = FileOperations::GetInputFileStream(Config::GetOption("SaveData"));
Json::Reader reader;
reader.parse(*saveStream, _saveRoot);
_saveProfileRoot = _saveRoot["profiles"][_profile];
_mapName = _saveProfileRoot["screen-maps"][_key].asString();
Assert(_mapName != "", "Cannot have a null map");
std::string mapFileName = "maps/" + _mapName + ".map";
auto mapStream = FileOperations::GetInputFileStream(mapFileName);
reader.parse(*mapStream, _mapRoot);
if (_loading)
{
for (Json::Value & assetJson : _mapRoot["assets"])
{
auto type = assetJson["type"].asString();
auto key = assetJson["key"].asString();
if (!_request->Contains(type, key))
{
_request->Add(type, key);
}
}
_request->Start();
}
_state = SerializerState::LoadingAssets;
}
void MapSerializer::LoadAssets()
{
if (!_loading)
{
_state = SerializerState::LoadingEntities;
return;
}
if (ResourceLibrary::DoneLoading(*_request))
{
_state = SerializerState::LoadingEntities;
}
}
void MapSerializer::LoadEntities()
{
if (!_loading)
{
_state = SerializerState::SerializingComponents;
return;
}
for (Json::Value & curEntity : _mapRoot["entities"])
{
_loadingContext->systems().systemManager().CreateEntity(curEntity.asString());
}
SerializeEntitySystemSaveables();
_state = SerializerState::SerializingComponents;
}
void MapSerializer::SerializeEntitySystemSaveables()
{
Archive entitySaveablesArc(_mapRoot, *_loadingContext.get(), _loading);
_loadingContext->systems().systemManager().Serialize(entitySaveablesArc);
}
void MapSerializer::SerializeComponents()
{
Archive mapArc(_mapRoot["systems"], *_loadingContext.get(), _loading, _snapshotSave);
Archive saveArc(_saveProfileRoot["systems"], *_loadingContext.get(), _loading, true);
for (auto systemNamePair : _loadingContext->systems().systemManager().keyedSystems())
{
SerializeSpecifiedSystem(systemNamePair, mapArc);
SerializeSpecifiedSystem(systemNamePair, saveArc);
}
if (_loading)
{
_loadingContext->systems().systemManager().FetchWaitingDependencies();
}
_mapRoot["systems"] = mapArc.CurrentBranch();
_saveRoot["systems"] = saveArc.CurrentBranch();
_state = SerializerState::DoneSerializing;
}
void MapSerializer::SerializeSpecifiedSystem(
std::pair<std::string, AbstractSystem *> systemNamePair,
Archive & currentArc)
{
if (currentArc.HasProperty(systemNamePair.first))
{
currentArc.EnterProperty(systemNamePair.first);
_loadingContext->systems().GetSystem<AbstractSystem>(systemNamePair.first)->Serialize(currentArc);
currentArc.ExitProperty();
}
}
void MapSerializer::SaveMapFiles()
{
// TODO Implement Snapshot Save
}
<|endoftext|> |
<commit_before>#include <stan/math/prim.hpp>
#include <gtest/gtest.h>
#include <boost/random/mersenne_twister.hpp>
#include <boost/math/special_functions/digamma.hpp>
#include <boost/math/distributions.hpp>
TEST(ProbDistributionsWishartCholesky, wishart_symmetry) {
using Eigen::Dynamic;
using Eigen::Matrix;
using Eigen::MatrixXd;
using stan::math::wishart_cholesky_lpdf;
MatrixXd Sigma(4, 4);
MatrixXd Y(4, 4);
Y << 7.988168, -9.555605, -14.47483, 4.395895, -9.555605, 44.750570,
49.215769, -15.454186, -14.474830, 49.215769, 60.08987, -20.48108,
4.395895, -15.454186, -20.48108, 7.885833;
Sigma << 2.9983662, 0.2898776, -2.650523, 0.1055911, 0.2898776, 11.4803610,
7.1579931, -3.1129955, -2.650523, 7.1579931, 11.676181, -3.586685,
0.1055911, -3.1129955, -3.586685, 1.4482736;
unsigned int dof = 5;
MatrixXd L_Y = Y.llt().matrixL();
MatrixXd L_S = Sigma.llt().matrixL();
EXPECT_NO_THROW(wishart_cholesky_lpdf(L_Y, dof, L_S));
}
TEST(ProbDistributionsWishartCholesky, wishart_pos_def) {
using Eigen::Dynamic;
using Eigen::Matrix;
using Eigen::MatrixXd;
using stan::math::wishart_cholesky_lpdf;
MatrixXd Sigma(2, 2);
MatrixXd Sigma_non_pos_def(2, 2);
MatrixXd Y(2, 2);
MatrixXd Y_non_pos_def(2, 2);
Sigma << 1, 0, 0, 1;
Sigma_non_pos_def << -1, 0, 0, 1;
Y << 1, 0, 0, 1;
Y_non_pos_def << -1, 0, 0, 1;
unsigned int dof = 5;
EXPECT_NO_THROW(wishart_cholesky_lpdf(Y, dof, Sigma));
EXPECT_THROW(wishart_cholesky_lpdf(Y_non_pos_def, dof, Sigma),
std::domain_error);
EXPECT_THROW(wishart_cholesky_lpdf(Y, dof, Sigma_non_pos_def),
std::domain_error);
}
TEST(ProbDistributionsWishartCholesky, 0x0) {
using Eigen::Dynamic;
using Eigen::MatrixXd;
MatrixXd Sigma(0, 0);
MatrixXd Y(0, 0);
unsigned int dof = 3;
EXPECT_THROW(stan::math::wishart_cholesky_lpdf(Y, dof, Sigma),
std::domain_error);
unsigned int dof0 = 0;
EXPECT_THROW(stan::math::wishart_cholesky_lpdf(Y, dof0, Sigma),
std::domain_error);
}
TEST(ProbDistributionsWishartCholesky, dof_0) {
using Eigen::Dynamic;
using Eigen::MatrixXd;
MatrixXd Sigma(2, 2);
Sigma << 1.848220, 1.899623, 1.899623, 12.751941;
MatrixXd Y(2, 2);
Y << 2.011108, -11.206611, -11.206611, 112.94139;
MatrixXd L_Y = Y.llt().matrixL();
MatrixXd L_S = Sigma.llt().matrixL();
unsigned int dof = std::numeric_limits<double>::quiet_NaN();
EXPECT_THROW(stan::math::wishart_cholesky_lpdf(L_Y, dof, L_S),
std::domain_error);
}
TEST(ProbDistributionsWishartCholesky, 1x1) {
using Eigen::Dynamic;
using Eigen::MatrixXd;
MatrixXd Sigma(1, 1);
Sigma << 1;
MatrixXd Y(1, 1);
Y << 2.011108;
double dof = 0.1;
EXPECT_NO_THROW(stan::math::wishart_cholesky_lpdf(Y, dof, Sigma));
}
TEST(ProbDistributionsWishartCholesky, 2x2) {
using Eigen::Dynamic;
using Eigen::MatrixXd;
MatrixXd Sigma(2, 2);
Sigma << 1.848220, 1.899623, 1.899623, 12.751941;
MatrixXd Y(2, 2);
Y << 2.011108, -11.206611, -11.206611, 112.94139;
MatrixXd L_Y = Y.llt().matrixL();
MatrixXd L_S = Sigma.llt().matrixL();
unsigned int dof = 3;
// log absolute determinant of the change of variables from Y -> LL'
// see Theorem 2.1.9 in Muirhead, Aspects of Multivariate Statistical Theory
double log_jac = 2 * stan::math::LOG_TWO;
for (int i = 0; i < 2; i++) {
log_jac += (2 - i) * log(L_Y(i, i));
}
// computed with MCMCpack in R
double lp = -13.9596117200 + log_jac;
EXPECT_NEAR(lp, stan::math::wishart_cholesky_lpdf(L_Y, dof, L_S), 1e-9);
}
TEST(ProbDistributionsWishartCholesky, 4x4) {
using Eigen::Dynamic;
using Eigen::MatrixXd;
MatrixXd Y(4, 4);
Y << 7.988168, -9.555605, -14.47483, 4.395895, -9.555605, 44.750570, 49.21577,
-18.454186, -14.474830, 49.21577, 60.08987, -21.48108, 4.395895,
-18.454186, -21.48108, 7.885833;
MatrixXd Sigma(4, 4);
Sigma << 2.9983662, 0.2898776, -2.650523, 0.1055911, 0.2898776, 11.4803610,
7.1579931, -3.1129955, -2.650523, 7.1579931, 11.676181, -3.5866852,
0.1055911, -3.1129955, -3.5866852, 1.4482736;
MatrixXd L_Y = Y.llt().matrixL();
MatrixXd L_S = Sigma.llt().matrixL();
unsigned int dof = 4;
double log_jac = 4 * stan::math::LOG_TWO;
unsigned int n = 4;
for (int i = 0; i < n; i++) {
log_jac += (n - i) * log(L_Y(i, i));
}
double log_p = -20.9420668184 + log_jac;
EXPECT_NEAR(log_p, stan::math::wishart_cholesky_lpdf(L_Y, dof, L_S), 1e-9);
dof = 5;
log_p = -22.6084823429 + log_jac;
EXPECT_NEAR(log_p, stan::math::wishart_cholesky_lpdf(L_Y, dof, L_S), 1e-9);
}
TEST(ProbDistributionsWishartCholesky, 2x2Propto) {
using Eigen::Dynamic;
using Eigen::MatrixXd;
MatrixXd Sigma(2, 2);
Sigma << 1.848220, 1.899623, 1.899623, 12.751941;
MatrixXd Y(2, 2);
Y << 2.011108, -11.206611, -11.206611, 112.94139;
MatrixXd L_Y = Y.llt().matrixL();
MatrixXd L_S = Sigma.llt().matrixL();
unsigned int dof = 3;
EXPECT_FLOAT_EQ(0.0, stan::math::wishart_cholesky_lpdf<true>(L_Y, dof, L_S));
}
TEST(ProbDistributionsWishartCholesky, 4x4Propto) {
using Eigen::Dynamic;
using Eigen::MatrixXd;
MatrixXd Y(4, 4);
Y << 7.988168, -9.555605, -14.47483, 4.395895, -9.555605, 44.750570,
49.215769, -18.454186, -14.474830, 49.215769, 60.08987, -21.48108,
4.395895, -18.454186, -21.48108, 7.885833;
MatrixXd Sigma(4, 4);
Sigma << 2.9983662, 0.2898776, -2.650523, 0.1055911, 0.2898776, 11.4803610,
7.1579931, -3.1129955, -2.650523, 7.1579931, 11.676181, -3.5866852,
0.1055911, -3.1129955, -3.5866852, 1.4482736;
MatrixXd L_Y = Y.llt().matrixL();
MatrixXd L_S = Sigma.llt().matrixL();
double dof = 4;
EXPECT_FLOAT_EQ(0, stan::math::wishart_cholesky_lpdf<true>(L_Y, dof, L_S));
dof = 5;
EXPECT_FLOAT_EQ(0, stan::math::wishart_cholesky_lpdf<true>(L_Y, dof, L_S));
}
TEST(ProbDistributionsWishartCholesky, error) {
using Eigen::Dynamic;
using Eigen::MatrixXd;
using stan::math::wishart_cholesky_lpdf;
double nu;
nu = 1;
EXPECT_NO_THROW(wishart_cholesky_lpdf(MatrixXd::Identity(1, 1), nu,
MatrixXd::Identity(1, 1)));
nu = 5;
MatrixXd Sigma(2, 1);
EXPECT_THROW(wishart_cholesky_lpdf(MatrixXd::Identity(1, 1), nu, Sigma),
std::invalid_argument);
nu = 5;
MatrixXd Y(2, 1);
EXPECT_THROW(wishart_cholesky_lpdf(Y, nu, MatrixXd::Identity(2, 2)),
std::invalid_argument);
nu = 5;
EXPECT_THROW(wishart_cholesky_lpdf(MatrixXd::Identity(3, 3), nu,
MatrixXd::Identity(2, 2)),
std::invalid_argument);
nu = 3;
EXPECT_NO_THROW(wishart_cholesky_lpdf(MatrixXd::Identity(3, 3), nu,
MatrixXd::Identity(3, 3)));
nu = 2;
EXPECT_THROW(wishart_cholesky_lpdf(MatrixXd::Identity(3, 3), nu,
MatrixXd::Identity(3, 3)),
std::domain_error);
}
<commit_msg>Fix test failure due to undefined behaviour<commit_after>#include <stan/math/prim.hpp>
#include <gtest/gtest.h>
#include <boost/random/mersenne_twister.hpp>
#include <boost/math/special_functions/digamma.hpp>
#include <boost/math/distributions.hpp>
TEST(ProbDistributionsWishartCholesky, wishart_symmetry) {
using Eigen::Dynamic;
using Eigen::Matrix;
using Eigen::MatrixXd;
using stan::math::wishart_cholesky_lpdf;
MatrixXd Sigma(4, 4);
MatrixXd Y(4, 4);
Y << 7.988168, -9.555605, -14.47483, 4.395895, -9.555605, 44.750570,
49.215769, -15.454186, -14.474830, 49.215769, 60.08987, -20.48108,
4.395895, -15.454186, -20.48108, 7.885833;
Sigma << 2.9983662, 0.2898776, -2.650523, 0.1055911, 0.2898776, 11.4803610,
7.1579931, -3.1129955, -2.650523, 7.1579931, 11.676181, -3.586685,
0.1055911, -3.1129955, -3.586685, 1.4482736;
unsigned int dof = 5;
MatrixXd L_Y = Y.llt().matrixL();
MatrixXd L_S = Sigma.llt().matrixL();
EXPECT_NO_THROW(wishart_cholesky_lpdf(L_Y, dof, L_S));
}
TEST(ProbDistributionsWishartCholesky, wishart_pos_def) {
using Eigen::Dynamic;
using Eigen::Matrix;
using Eigen::MatrixXd;
using stan::math::wishart_cholesky_lpdf;
MatrixXd Sigma(2, 2);
MatrixXd Sigma_non_pos_def(2, 2);
MatrixXd Y(2, 2);
MatrixXd Y_non_pos_def(2, 2);
Sigma << 1, 0, 0, 1;
Sigma_non_pos_def << -1, 0, 0, 1;
Y << 1, 0, 0, 1;
Y_non_pos_def << -1, 0, 0, 1;
unsigned int dof = 5;
EXPECT_NO_THROW(wishart_cholesky_lpdf(Y, dof, Sigma));
EXPECT_THROW(wishart_cholesky_lpdf(Y_non_pos_def, dof, Sigma),
std::domain_error);
EXPECT_THROW(wishart_cholesky_lpdf(Y, dof, Sigma_non_pos_def),
std::domain_error);
}
TEST(ProbDistributionsWishartCholesky, 0x0) {
using Eigen::Dynamic;
using Eigen::MatrixXd;
MatrixXd Sigma(0, 0);
MatrixXd Y(0, 0);
unsigned int dof = 3;
EXPECT_THROW(stan::math::wishart_cholesky_lpdf(Y, dof, Sigma),
std::domain_error);
unsigned int dof0 = 0;
EXPECT_THROW(stan::math::wishart_cholesky_lpdf(Y, dof0, Sigma),
std::domain_error);
}
TEST(ProbDistributionsWishartCholesky, dof_0) {
using Eigen::Dynamic;
using Eigen::MatrixXd;
MatrixXd Sigma(2, 2);
Sigma << 1.848220, 1.899623, 1.899623, 12.751941;
MatrixXd Y(2, 2);
Y << 2.011108, -11.206611, -11.206611, 112.94139;
MatrixXd L_Y = Y.llt().matrixL();
MatrixXd L_S = Sigma.llt().matrixL();
unsigned int dof = 0;
EXPECT_THROW(stan::math::wishart_cholesky_lpdf(L_Y, dof, L_S),
std::domain_error);
}
TEST(ProbDistributionsWishartCholesky, 1x1) {
using Eigen::Dynamic;
using Eigen::MatrixXd;
MatrixXd Sigma(1, 1);
Sigma << 1;
MatrixXd Y(1, 1);
Y << 2.011108;
double dof = 0.1;
EXPECT_NO_THROW(stan::math::wishart_cholesky_lpdf(Y, dof, Sigma));
}
TEST(ProbDistributionsWishartCholesky, 2x2) {
using Eigen::Dynamic;
using Eigen::MatrixXd;
MatrixXd Sigma(2, 2);
Sigma << 1.848220, 1.899623, 1.899623, 12.751941;
MatrixXd Y(2, 2);
Y << 2.011108, -11.206611, -11.206611, 112.94139;
MatrixXd L_Y = Y.llt().matrixL();
MatrixXd L_S = Sigma.llt().matrixL();
unsigned int dof = 3;
// log absolute determinant of the change of variables from Y -> LL'
// see Theorem 2.1.9 in Muirhead, Aspects of Multivariate Statistical Theory
double log_jac = 2 * stan::math::LOG_TWO;
for (int i = 0; i < 2; i++) {
log_jac += (2 - i) * log(L_Y(i, i));
}
// computed with MCMCpack in R
double lp = -13.9596117200 + log_jac;
EXPECT_NEAR(lp, stan::math::wishart_cholesky_lpdf(L_Y, dof, L_S), 1e-9);
}
TEST(ProbDistributionsWishartCholesky, 4x4) {
using Eigen::Dynamic;
using Eigen::MatrixXd;
MatrixXd Y(4, 4);
Y << 7.988168, -9.555605, -14.47483, 4.395895, -9.555605, 44.750570, 49.21577,
-18.454186, -14.474830, 49.21577, 60.08987, -21.48108, 4.395895,
-18.454186, -21.48108, 7.885833;
MatrixXd Sigma(4, 4);
Sigma << 2.9983662, 0.2898776, -2.650523, 0.1055911, 0.2898776, 11.4803610,
7.1579931, -3.1129955, -2.650523, 7.1579931, 11.676181, -3.5866852,
0.1055911, -3.1129955, -3.5866852, 1.4482736;
MatrixXd L_Y = Y.llt().matrixL();
MatrixXd L_S = Sigma.llt().matrixL();
unsigned int dof = 4;
double log_jac = 4 * stan::math::LOG_TWO;
unsigned int n = 4;
for (int i = 0; i < n; i++) {
log_jac += (n - i) * log(L_Y(i, i));
}
double log_p = -20.9420668184 + log_jac;
EXPECT_NEAR(log_p, stan::math::wishart_cholesky_lpdf(L_Y, dof, L_S), 1e-9);
dof = 5;
log_p = -22.6084823429 + log_jac;
EXPECT_NEAR(log_p, stan::math::wishart_cholesky_lpdf(L_Y, dof, L_S), 1e-9);
}
TEST(ProbDistributionsWishartCholesky, 2x2Propto) {
using Eigen::Dynamic;
using Eigen::MatrixXd;
MatrixXd Sigma(2, 2);
Sigma << 1.848220, 1.899623, 1.899623, 12.751941;
MatrixXd Y(2, 2);
Y << 2.011108, -11.206611, -11.206611, 112.94139;
MatrixXd L_Y = Y.llt().matrixL();
MatrixXd L_S = Sigma.llt().matrixL();
unsigned int dof = 3;
EXPECT_FLOAT_EQ(0.0, stan::math::wishart_cholesky_lpdf<true>(L_Y, dof, L_S));
}
TEST(ProbDistributionsWishartCholesky, 4x4Propto) {
using Eigen::Dynamic;
using Eigen::MatrixXd;
MatrixXd Y(4, 4);
Y << 7.988168, -9.555605, -14.47483, 4.395895, -9.555605, 44.750570,
49.215769, -18.454186, -14.474830, 49.215769, 60.08987, -21.48108,
4.395895, -18.454186, -21.48108, 7.885833;
MatrixXd Sigma(4, 4);
Sigma << 2.9983662, 0.2898776, -2.650523, 0.1055911, 0.2898776, 11.4803610,
7.1579931, -3.1129955, -2.650523, 7.1579931, 11.676181, -3.5866852,
0.1055911, -3.1129955, -3.5866852, 1.4482736;
MatrixXd L_Y = Y.llt().matrixL();
MatrixXd L_S = Sigma.llt().matrixL();
double dof = 4;
EXPECT_FLOAT_EQ(0, stan::math::wishart_cholesky_lpdf<true>(L_Y, dof, L_S));
dof = 5;
EXPECT_FLOAT_EQ(0, stan::math::wishart_cholesky_lpdf<true>(L_Y, dof, L_S));
}
TEST(ProbDistributionsWishartCholesky, error) {
using Eigen::Dynamic;
using Eigen::MatrixXd;
using stan::math::wishart_cholesky_lpdf;
double nu;
nu = 1;
EXPECT_NO_THROW(wishart_cholesky_lpdf(MatrixXd::Identity(1, 1), nu,
MatrixXd::Identity(1, 1)));
nu = 5;
MatrixXd Sigma(2, 1);
EXPECT_THROW(wishart_cholesky_lpdf(MatrixXd::Identity(1, 1), nu, Sigma),
std::invalid_argument);
nu = 5;
MatrixXd Y(2, 1);
EXPECT_THROW(wishart_cholesky_lpdf(Y, nu, MatrixXd::Identity(2, 2)),
std::invalid_argument);
nu = 5;
EXPECT_THROW(wishart_cholesky_lpdf(MatrixXd::Identity(3, 3), nu,
MatrixXd::Identity(2, 2)),
std::invalid_argument);
nu = 3;
EXPECT_NO_THROW(wishart_cholesky_lpdf(MatrixXd::Identity(3, 3), nu,
MatrixXd::Identity(3, 3)));
nu = 2;
EXPECT_THROW(wishart_cholesky_lpdf(MatrixXd::Identity(3, 3), nu,
MatrixXd::Identity(3, 3)),
std::domain_error);
}
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Manasij Mukherjee <[email protected]>
// author: Vassil Vassilev <[email protected]>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Path.h"
#include "clang/Sema/Sema.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/AST/AST.h"
#include "clang/AST/ASTContext.h" // for operator new[](unsigned long, ASTCtx..)
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Frontend/CompilerInstance.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/AutoloadCallback.h"
#include "cling/Interpreter/Transaction.h"
namespace {
static const char annoTag[] = "$clingAutoload$";
static const size_t lenAnnoTag = sizeof(annoTag) - 1;
}
using namespace clang;
namespace cling {
void AutoloadCallback::report(clang::SourceLocation l, llvm::StringRef name,
llvm::StringRef header) {
Sema& sema= m_Interpreter->getSema();
unsigned id
= sema.getDiagnostics().getCustomDiagID (DiagnosticsEngine::Level::Warning,
"Note: '%0' can be found in %1");
/* unsigned idn //TODO: To be enabled after we have a way to get the full path
= sema.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Level::Note,
"Type : %0 , Full Path: %1")*/;
if (header.startswith(llvm::StringRef(annoTag, lenAnnoTag)))
sema.Diags.Report(l, id) << name << header.drop_front(lenAnnoTag);
}
bool AutoloadCallback::LookupObject (TagDecl *t) {
if (m_ShowSuggestions && t->hasAttr<AnnotateAttr>())
report(t->getLocation(),t->getNameAsString(),t->getAttr<AnnotateAttr>()->getAnnotation());
return false;
}
class AutoloadingVisitor: public RecursiveASTVisitor<AutoloadingVisitor> {
private:
///\brief Flag determining the visitor's actions. If true, register autoload
/// entries, i.e. remember the connection between filename and the declaration
/// that needs to be updated on #include of the filename.
/// If false, react on an #include by adjusting the forward decls, e.g. by
/// removing the default tremplate arguments (that will now be provided by
/// the definition read from the include) and by removing enum declarations
/// that would otherwise be duplicates.
bool m_IsStoringState;
AutoloadCallback::FwdDeclsMap* m_Map;
clang::Preprocessor* m_PP;
const clang::FileEntry* m_PrevFE;
std::string m_PrevFileName;
private:
void InsertIntoAutoloadingState (Decl* decl, llvm::StringRef annotation) {
assert(!annotation.empty() && "Empty annotation!");
if (!annotation.startswith(llvm::StringRef(annoTag, lenAnnoTag))) {
// not an autoload annotation.
return;
}
assert(m_PP);
const FileEntry* FE = 0;
SourceLocation fileNameLoc;
bool isAngled = false;
const DirectoryLookup* LookupFrom = 0;
const DirectoryLookup* CurDir = 0;
llvm::StringRef FileName = annotation.drop_front(lenAnnoTag);
if (FileName.equals(m_PrevFileName))
FE = m_PrevFE;
else {
FE = m_PP->LookupFile(fileNameLoc, FileName, isAngled,
LookupFrom, CurDir, /*SearchPath*/0,
/*RelativePath*/ 0, /*suggestedModule*/0,
/*SkipCache*/ false, /*OpenFile*/ false,
/*CacheFail*/ true);
m_PrevFE = FE;
m_PrevFileName = FileName;
}
assert(FE && "Must have a valid FileEntry");
if (FE) {
auto& Vec = (*m_Map)[FE];
Vec.push_back(decl);
}
}
public:
AutoloadingVisitor():
m_IsStoringState(false), m_Map(0), m_PP(0), m_PrevFE(0) {}
void RemoveDefaultArgsOf(Decl* D) {
//D = D->getMostRecentDecl();
TraverseDecl(D);
//while ((D = D->getPreviousDecl()))
// TraverseDecl(D);
}
void TrackDefaultArgStateOf(Decl* D, AutoloadCallback::FwdDeclsMap& map,
Preprocessor& PP) {
m_IsStoringState = true;
m_Map = ↦
m_PP = &PP;
TraverseDecl(D);
m_PP = 0;
m_Map = 0;
m_IsStoringState = false;
}
bool shouldVisitTemplateInstantiations() { return true; }
bool VisitDecl(Decl* D) {
if (!m_IsStoringState)
return true;
if (!D->hasAttr<AnnotateAttr>())
return true;
AnnotateAttr* attr = D->getAttr<AnnotateAttr>();
if (!attr)
return true;
switch (D->getKind()) {
default:
InsertIntoAutoloadingState(D, attr->getAnnotation());
break;
case Decl::Enum:
// EnumDecls have extra information 2 chars after the filename used
// for extra fixups.
EnumDecl* ED = cast<EnumDecl>(D);
if (ED->isFixed()) {
StringRef str = ED->getAttr<AnnotateAttr>()->getAnnotation();
char ch = str.back();
// str.drop_back(2);
ED->getAttr<AnnotateAttr>()->setAnnotation(ED->getASTContext(), str);
struct EnumDeclDerived: public EnumDecl {
static void setFixed(EnumDecl* ED, bool value = true) {
((EnumDeclDerived*)ED)->IsFixed = value;
}
};
if (ch != '1')
EnumDeclDerived::setFixed(ED, false);
}
InsertIntoAutoloadingState(D, attr->getAnnotation().drop_back(2));
break;
}
return true;
}
bool VisitCXXRecordDecl(CXXRecordDecl* D) {
if (!D->hasAttr<AnnotateAttr>())
return true;
VisitDecl(D);
if (ClassTemplateDecl* TmplD = D->getDescribedClassTemplate())
return VisitTemplateDecl(TmplD);
return true;
}
bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl* D) {
VisitDecl(D);
if (m_IsStoringState)
return true;
if (D->hasDefaultArgument())
D->removeDefaultArgument();
return true;
}
bool VisitTemplateDecl(TemplateDecl* D) {
if (D->getTemplatedDecl() &&
!D->getTemplatedDecl()->hasAttr<AnnotateAttr>())
return true;
VisitDecl(D);
// If we have a definition we might be about to re-#include the
// same header containing definition that was #included previously,
// i.e. we might have multiple fwd decls for the same template.
// DO NOT remove the defaults here; the definition needs to keep it.
// (ROOT-7037)
if (ClassTemplateDecl* CTD = dyn_cast<ClassTemplateDecl>(D))
if (CXXRecordDecl* TemplatedD = CTD->getTemplatedDecl())
if (TemplatedD->getDefinition())
return true;
for(auto P: D->getTemplateParameters()->asArray())
TraverseDecl(P);
return true;
}
bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl* D) {
VisitDecl(D);
if (m_IsStoringState)
return true;
if (D->hasDefaultArgument())
D->removeDefaultArgument();
return true;
}
bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl* D) {
VisitDecl(D);
if (m_IsStoringState)
return true;
if (D->hasDefaultArgument())
D->removeDefaultArgument();
return true;
}
bool VisitParmVarDecl(ParmVarDecl* D) {
VisitDecl(D);
if (m_IsStoringState)
return true;
if (D->hasDefaultArg())
D->setDefaultArg(nullptr);
return true;
}
};
void AutoloadCallback::InclusionDirective(clang::SourceLocation HashLoc,
const clang::Token &IncludeTok,
llvm::StringRef FileName,
bool IsAngled,
clang::CharSourceRange FilenameRange,
const clang::FileEntry *File,
llvm::StringRef SearchPath,
llvm::StringRef RelativePath,
const clang::Module *Imported) {
// If File is 0 this means that the #included file doesn't exist.
if (!File)
return;
auto found = m_Map.find(File);
if (found == m_Map.end())
return; // nothing to do, file not referred in any annotation
AutoloadingVisitor defaultArgsCleaner;
for (auto D : found->second) {
defaultArgsCleaner.RemoveDefaultArgsOf(D);
}
// Don't need to keep track of cleaned up decls from file.
m_Map.erase(found);
}
AutoloadCallback::~AutoloadCallback() {
}
void AutoloadCallback::TransactionCommitted(const Transaction &T) {
if (T.decls_begin() == T.decls_end())
return;
if (T.decls_begin()->m_DGR.isNull())
return;
if (const NamedDecl* ND = dyn_cast<NamedDecl>(*T.decls_begin()->m_DGR.begin()))
if (ND->getIdentifier() && ND->getName().equals("__Cling_Autoloading_Map")) {
AutoloadingVisitor defaultArgsStateCollector;
Preprocessor& PP = m_Interpreter->getCI()->getPreprocessor();
for (Transaction::const_iterator I = T.decls_begin(), E = T.decls_end();
I != E; ++I) {
Transaction::DelayCallInfo DCI = *I;
// if (DCI.m_Call != Transaction::kCCIHandleTopLevelDecl)
// continue;
if (DCI.m_DGR.isNull())
continue;
if (const NamedDecl* ND = dyn_cast<NamedDecl>(*T.decls_begin()->m_DGR.begin()))
if (ND->getIdentifier()
&& ND->getName().equals("__Cling_Autoloading_Map")) {
for (Transaction::const_iterator I = T.decls_begin(),
E = T.decls_end(); I != E; ++I) {
Transaction::DelayCallInfo DCI = *I;
for (DeclGroupRef::iterator J = DCI.m_DGR.begin(),
JE = DCI.m_DGR.end(); J != JE; ++J) {
defaultArgsStateCollector.TrackDefaultArgStateOf(*J, m_Map, PP);
}
}
}
}
}
}
} //end namespace cling
<commit_msg>Follow interface change.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Manasij Mukherjee <[email protected]>
// author: Vassil Vassilev <[email protected]>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Path.h"
#include "clang/Sema/Sema.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/AST/AST.h"
#include "clang/AST/ASTContext.h" // for operator new[](unsigned long, ASTCtx..)
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Frontend/CompilerInstance.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/AutoloadCallback.h"
#include "cling/Interpreter/Transaction.h"
namespace {
static const char annoTag[] = "$clingAutoload$";
static const size_t lenAnnoTag = sizeof(annoTag) - 1;
}
using namespace clang;
namespace cling {
void AutoloadCallback::report(clang::SourceLocation l, llvm::StringRef name,
llvm::StringRef header) {
Sema& sema= m_Interpreter->getSema();
unsigned id
= sema.getDiagnostics().getCustomDiagID (DiagnosticsEngine::Level::Warning,
"Note: '%0' can be found in %1");
/* unsigned idn //TODO: To be enabled after we have a way to get the full path
= sema.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Level::Note,
"Type : %0 , Full Path: %1")*/;
if (header.startswith(llvm::StringRef(annoTag, lenAnnoTag)))
sema.Diags.Report(l, id) << name << header.drop_front(lenAnnoTag);
}
bool AutoloadCallback::LookupObject (TagDecl *t) {
if (m_ShowSuggestions && t->hasAttr<AnnotateAttr>())
report(t->getLocation(),t->getNameAsString(),t->getAttr<AnnotateAttr>()->getAnnotation());
return false;
}
class AutoloadingVisitor: public RecursiveASTVisitor<AutoloadingVisitor> {
private:
///\brief Flag determining the visitor's actions. If true, register autoload
/// entries, i.e. remember the connection between filename and the declaration
/// that needs to be updated on #include of the filename.
/// If false, react on an #include by adjusting the forward decls, e.g. by
/// removing the default tremplate arguments (that will now be provided by
/// the definition read from the include) and by removing enum declarations
/// that would otherwise be duplicates.
bool m_IsStoringState;
AutoloadCallback::FwdDeclsMap* m_Map;
clang::Preprocessor* m_PP;
const clang::FileEntry* m_PrevFE;
std::string m_PrevFileName;
private:
void InsertIntoAutoloadingState (Decl* decl, llvm::StringRef annotation) {
assert(!annotation.empty() && "Empty annotation!");
if (!annotation.startswith(llvm::StringRef(annoTag, lenAnnoTag))) {
// not an autoload annotation.
return;
}
assert(m_PP);
const FileEntry* FE = 0;
SourceLocation fileNameLoc;
bool isAngled = false;
const DirectoryLookup* FromDir = 0;
const FileEntry* FromFile = 0;
const DirectoryLookup* CurDir = 0;
llvm::StringRef FileName = annotation.drop_front(lenAnnoTag);
if (FileName.equals(m_PrevFileName))
FE = m_PrevFE;
else {
FE = m_PP->LookupFile(fileNameLoc, FileName, isAngled,
FromDir, FromFile, CurDir, /*SearchPath*/0,
/*RelativePath*/ 0, /*suggestedModule*/0,
/*SkipCache*/ false, /*OpenFile*/ false,
/*CacheFail*/ true);
m_PrevFE = FE;
m_PrevFileName = FileName;
}
assert(FE && "Must have a valid FileEntry");
if (FE) {
auto& Vec = (*m_Map)[FE];
Vec.push_back(decl);
}
}
public:
AutoloadingVisitor():
m_IsStoringState(false), m_Map(0), m_PP(0), m_PrevFE(0) {}
void RemoveDefaultArgsOf(Decl* D) {
//D = D->getMostRecentDecl();
TraverseDecl(D);
//while ((D = D->getPreviousDecl()))
// TraverseDecl(D);
}
void TrackDefaultArgStateOf(Decl* D, AutoloadCallback::FwdDeclsMap& map,
Preprocessor& PP) {
m_IsStoringState = true;
m_Map = ↦
m_PP = &PP;
TraverseDecl(D);
m_PP = 0;
m_Map = 0;
m_IsStoringState = false;
}
bool shouldVisitTemplateInstantiations() { return true; }
bool VisitDecl(Decl* D) {
if (!m_IsStoringState)
return true;
if (!D->hasAttr<AnnotateAttr>())
return true;
AnnotateAttr* attr = D->getAttr<AnnotateAttr>();
if (!attr)
return true;
switch (D->getKind()) {
default:
InsertIntoAutoloadingState(D, attr->getAnnotation());
break;
case Decl::Enum:
// EnumDecls have extra information 2 chars after the filename used
// for extra fixups.
EnumDecl* ED = cast<EnumDecl>(D);
if (ED->isFixed()) {
StringRef str = ED->getAttr<AnnotateAttr>()->getAnnotation();
char ch = str.back();
// str.drop_back(2);
ED->getAttr<AnnotateAttr>()->setAnnotation(ED->getASTContext(), str);
struct EnumDeclDerived: public EnumDecl {
static void setFixed(EnumDecl* ED, bool value = true) {
((EnumDeclDerived*)ED)->IsFixed = value;
}
};
if (ch != '1')
EnumDeclDerived::setFixed(ED, false);
}
InsertIntoAutoloadingState(D, attr->getAnnotation().drop_back(2));
break;
}
return true;
}
bool VisitCXXRecordDecl(CXXRecordDecl* D) {
if (!D->hasAttr<AnnotateAttr>())
return true;
VisitDecl(D);
if (ClassTemplateDecl* TmplD = D->getDescribedClassTemplate())
return VisitTemplateDecl(TmplD);
return true;
}
bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl* D) {
VisitDecl(D);
if (m_IsStoringState)
return true;
if (D->hasDefaultArgument())
D->removeDefaultArgument();
return true;
}
bool VisitTemplateDecl(TemplateDecl* D) {
if (D->getTemplatedDecl() &&
!D->getTemplatedDecl()->hasAttr<AnnotateAttr>())
return true;
VisitDecl(D);
// If we have a definition we might be about to re-#include the
// same header containing definition that was #included previously,
// i.e. we might have multiple fwd decls for the same template.
// DO NOT remove the defaults here; the definition needs to keep it.
// (ROOT-7037)
if (ClassTemplateDecl* CTD = dyn_cast<ClassTemplateDecl>(D))
if (CXXRecordDecl* TemplatedD = CTD->getTemplatedDecl())
if (TemplatedD->getDefinition())
return true;
for(auto P: D->getTemplateParameters()->asArray())
TraverseDecl(P);
return true;
}
bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl* D) {
VisitDecl(D);
if (m_IsStoringState)
return true;
if (D->hasDefaultArgument())
D->removeDefaultArgument();
return true;
}
bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl* D) {
VisitDecl(D);
if (m_IsStoringState)
return true;
if (D->hasDefaultArgument())
D->removeDefaultArgument();
return true;
}
bool VisitParmVarDecl(ParmVarDecl* D) {
VisitDecl(D);
if (m_IsStoringState)
return true;
if (D->hasDefaultArg())
D->setDefaultArg(nullptr);
return true;
}
};
void AutoloadCallback::InclusionDirective(clang::SourceLocation HashLoc,
const clang::Token &IncludeTok,
llvm::StringRef FileName,
bool IsAngled,
clang::CharSourceRange FilenameRange,
const clang::FileEntry *File,
llvm::StringRef SearchPath,
llvm::StringRef RelativePath,
const clang::Module *Imported) {
// If File is 0 this means that the #included file doesn't exist.
if (!File)
return;
auto found = m_Map.find(File);
if (found == m_Map.end())
return; // nothing to do, file not referred in any annotation
AutoloadingVisitor defaultArgsCleaner;
for (auto D : found->second) {
defaultArgsCleaner.RemoveDefaultArgsOf(D);
}
// Don't need to keep track of cleaned up decls from file.
m_Map.erase(found);
}
AutoloadCallback::~AutoloadCallback() {
}
void AutoloadCallback::TransactionCommitted(const Transaction &T) {
if (T.decls_begin() == T.decls_end())
return;
if (T.decls_begin()->m_DGR.isNull())
return;
if (const NamedDecl* ND = dyn_cast<NamedDecl>(*T.decls_begin()->m_DGR.begin()))
if (ND->getIdentifier() && ND->getName().equals("__Cling_Autoloading_Map")) {
AutoloadingVisitor defaultArgsStateCollector;
Preprocessor& PP = m_Interpreter->getCI()->getPreprocessor();
for (Transaction::const_iterator I = T.decls_begin(), E = T.decls_end();
I != E; ++I) {
Transaction::DelayCallInfo DCI = *I;
// if (DCI.m_Call != Transaction::kCCIHandleTopLevelDecl)
// continue;
if (DCI.m_DGR.isNull())
continue;
if (const NamedDecl* ND = dyn_cast<NamedDecl>(*T.decls_begin()->m_DGR.begin()))
if (ND->getIdentifier()
&& ND->getName().equals("__Cling_Autoloading_Map")) {
for (Transaction::const_iterator I = T.decls_begin(),
E = T.decls_end(); I != E; ++I) {
Transaction::DelayCallInfo DCI = *I;
for (DeclGroupRef::iterator J = DCI.m_DGR.begin(),
JE = DCI.m_DGR.end(); J != JE; ++J) {
defaultArgsStateCollector.TrackDefaultArgStateOf(*J, m_Map, PP);
}
}
}
}
}
}
} //end namespace cling
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_comphelper.hxx"
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XTypeProvider.hpp>
#include <cppuhelper/weakagg.hxx>
#include <cppuhelper/interfacecontainer.hxx>
#include <comphelper/propertysethelper.hxx>
#include <osl/mutex.hxx>
#include <comphelper/genericpropertyset.hxx>
#include <comphelper/propertysetinfo.hxx>
#include <comphelper/stl_types.hxx>
#include <osl/mutex.hxx>
#include <rtl/uuid.h>
///////////////////////////////////////////////////////////////////////
using namespace ::rtl;
using namespace ::osl;
using namespace ::cppu;
using namespace ::comphelper;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
DECLARE_STL_USTRINGACCESS_MAP( Any, GenericAnyMapImpl );
namespace comphelper
{
struct IMPL_GenericPropertySet_MutexContainer
{
Mutex maMutex ;
} ;
class GenericPropertySet : public OWeakAggObject,
public XServiceInfo,
public XTypeProvider,
public PropertySetHelper,
private IMPL_GenericPropertySet_MutexContainer
{
private:
GenericAnyMapImpl maAnyMap;
::cppu::OMultiTypeInterfaceContainerHelperVar< ::rtl::OUString,UStringHash,UStringEqual> m_aListener;
protected:
virtual void _setPropertyValues( const PropertyMapEntry** ppEntries, const Any* pValues ) throw( UnknownPropertyException, PropertyVetoException, IllegalArgumentException, WrappedTargetException );
virtual void _getPropertyValues( const PropertyMapEntry** ppEntries, Any* pValue ) throw( UnknownPropertyException, WrappedTargetException );
public:
GenericPropertySet( PropertySetInfo* pInfo ) throw();
virtual ~GenericPropertySet() throw();
// XInterface
virtual Any SAL_CALL queryAggregation( const Type & rType ) throw( RuntimeException);
virtual Any SAL_CALL queryInterface( const Type & rType ) throw( RuntimeException);
virtual void SAL_CALL acquire() throw();
virtual void SAL_CALL release() throw();
// XTypeProvider
virtual Sequence< Type > SAL_CALL getTypes( ) throw( RuntimeException);
virtual Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw( RuntimeException);
// XServiceInfo
virtual rtl::OUString SAL_CALL getImplementationName() throw( RuntimeException );
virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& ServiceName ) throw( RuntimeException );
virtual Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames() throw( RuntimeException );
// XPropertySet
virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
};
}
///////////////////////////////////////////////////////////////////////
GenericPropertySet::GenericPropertySet( PropertySetInfo* pInfo ) throw()
: PropertySetHelper( pInfo )
,m_aListener(maMutex)
{
}
GenericPropertySet::~GenericPropertySet() throw()
{
}
void SAL_CALL GenericPropertySet::addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const Reference< XPropertyChangeListener >& xListener ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
Reference < XPropertySetInfo > xInfo = getPropertySetInfo( );
if ( xInfo.is() )
{
if ( !aPropertyName.getLength() )
{
Sequence< Property> aSeq = xInfo->getProperties();
const Property* pIter = aSeq.getConstArray();
const Property* pEnd = pIter + aSeq.getLength();
for( ; pIter != pEnd ; ++pIter)
{
m_aListener.addInterface(pIter->Name,xListener);
}
}
else if ( xInfo->hasPropertyByName(aPropertyName) )
m_aListener.addInterface(aPropertyName,xListener);
else
throw UnknownPropertyException( aPropertyName, *this );
}
}
void SAL_CALL GenericPropertySet::removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const Reference< XPropertyChangeListener >& xListener ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
ResettableMutexGuard aGuard( maMutex );
Reference < XPropertySetInfo > xInfo = getPropertySetInfo( );
aGuard.clear();
if ( xInfo.is() )
{
if ( !aPropertyName.getLength() )
{
Sequence< Property> aSeq = xInfo->getProperties();
const Property* pIter = aSeq.getConstArray();
const Property* pEnd = pIter + aSeq.getLength();
for( ; pIter != pEnd ; ++pIter)
{
m_aListener.removeInterface(pIter->Name,xListener);
}
}
else if ( xInfo->hasPropertyByName(aPropertyName) )
m_aListener.removeInterface(aPropertyName,xListener);
else
throw UnknownPropertyException( aPropertyName, *this );
}
}
void GenericPropertySet::_setPropertyValues( const PropertyMapEntry** ppEntries, const Any* pValues )
throw(UnknownPropertyException, PropertyVetoException, IllegalArgumentException, WrappedTargetException )
{
ResettableMutexGuard aGuard( maMutex );
while( *ppEntries )
{
const OUString aPropertyName( (*ppEntries)->mpName, (*ppEntries)->mnNameLen, RTL_TEXTENCODING_ASCII_US );
OInterfaceContainerHelper * pHelper = m_aListener.getContainer(aPropertyName);
maAnyMap[ aPropertyName ] = *pValues;
if ( pHelper )
{
PropertyChangeEvent aEvt;
aEvt.PropertyName = aPropertyName;
aEvt.NewValue = *pValues;
aGuard.clear();
pHelper->notifyEach( &XPropertyChangeListener::propertyChange, aEvt );
aGuard.reset();
}
ppEntries++;
pValues++;
}
}
void GenericPropertySet::_getPropertyValues( const comphelper::PropertyMapEntry** ppEntries, Any* pValue )
throw( UnknownPropertyException, WrappedTargetException )
{
MutexGuard aGuard( maMutex );
while( *ppEntries )
{
const OUString aPropertyName( (*ppEntries)->mpName, (*ppEntries)->mnNameLen, RTL_TEXTENCODING_ASCII_US );
*pValue = maAnyMap[ aPropertyName ];
ppEntries++;
pValue++;
}
}
// XInterface
Any SAL_CALL GenericPropertySet::queryInterface( const Type & rType )
throw( RuntimeException )
{
return OWeakAggObject::queryInterface( rType );
}
Any SAL_CALL GenericPropertySet::queryAggregation( const Type & rType )
throw(RuntimeException)
{
Any aAny;
if( rType == ::getCppuType((const Reference< XServiceInfo >*)0) )
aAny <<= Reference< XServiceInfo >(this);
else if( rType == ::getCppuType((const Reference< XTypeProvider >*)0) )
aAny <<= Reference< XTypeProvider >(this);
else if( rType == ::getCppuType((const Reference< XPropertySet >*)0) )
aAny <<= Reference< XPropertySet >(this);
else if( rType == ::getCppuType((const Reference< XMultiPropertySet >*)0) )
aAny <<= Reference< XMultiPropertySet >(this);
else
aAny <<= OWeakAggObject::queryAggregation( rType );
return aAny;
}
void SAL_CALL GenericPropertySet::acquire() throw()
{
OWeakAggObject::acquire();
}
void SAL_CALL GenericPropertySet::release() throw()
{
OWeakAggObject::release();
}
uno::Sequence< uno::Type > SAL_CALL GenericPropertySet::getTypes()
throw (uno::RuntimeException)
{
uno::Sequence< uno::Type > aTypes( 5 );
uno::Type* pTypes = aTypes.getArray();
*pTypes++ = ::getCppuType((const uno::Reference< XAggregation>*)0);
*pTypes++ = ::getCppuType((const uno::Reference< XServiceInfo>*)0);
*pTypes++ = ::getCppuType((const uno::Reference< XTypeProvider>*)0);
*pTypes++ = ::getCppuType((const uno::Reference< XPropertySet>*)0);
*pTypes++ = ::getCppuType((const uno::Reference< XMultiPropertySet>*)0);
return aTypes;
}
uno::Sequence< sal_Int8 > SAL_CALL GenericPropertySet::getImplementationId()
throw (uno::RuntimeException)
{
MutexGuard aGuard( maMutex );
static uno::Sequence< sal_Int8 > aId;
if( aId.getLength() == 0 )
{
aId.realloc( 16 );
rtl_createUuid( (sal_uInt8 *)aId.getArray(), 0, sal_True );
}
return aId;
}
// XServiceInfo
sal_Bool SAL_CALL GenericPropertySet::supportsService( const OUString& ServiceName ) throw(RuntimeException)
{
Sequence< OUString > aSNL( getSupportedServiceNames() );
const OUString * pArray = aSNL.getConstArray();
for( sal_Int32 i = 0; i < aSNL.getLength(); ++i )
if( pArray[i] == ServiceName )
return sal_True;
return sal_False;
}
OUString SAL_CALL GenericPropertySet::getImplementationName() throw( RuntimeException )
{
return OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.comphelper.GenericPropertySet") );
}
Sequence< OUString > SAL_CALL GenericPropertySet::getSupportedServiceNames( )
throw( RuntimeException )
{
Sequence< OUString > aSNS( 1 );
aSNS.getArray()[0] = OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.beans.XPropertySet" ));
return aSNS;
}
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > comphelper::GenericPropertySet_CreateInstance( comphelper::PropertySetInfo* pInfo )
{
return (XPropertySet*)new GenericPropertySet( pInfo );
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>use standard template here<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_comphelper.hxx"
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XTypeProvider.hpp>
#include <cppuhelper/weakagg.hxx>
#include <cppuhelper/interfacecontainer.hxx>
#include <comphelper/propertysethelper.hxx>
#include <osl/mutex.hxx>
#include <comphelper/genericpropertyset.hxx>
#include <comphelper/propertysetinfo.hxx>
#include <comphelper/stl_types.hxx>
#include <comphelper/servicehelper.hxx>
#include <osl/mutex.hxx>
#include <rtl/uuid.h>
///////////////////////////////////////////////////////////////////////
using namespace ::rtl;
using namespace ::osl;
using namespace ::cppu;
using namespace ::comphelper;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
DECLARE_STL_USTRINGACCESS_MAP( Any, GenericAnyMapImpl );
namespace comphelper
{
struct IMPL_GenericPropertySet_MutexContainer
{
Mutex maMutex ;
} ;
class GenericPropertySet : public OWeakAggObject,
public XServiceInfo,
public XTypeProvider,
public PropertySetHelper,
private IMPL_GenericPropertySet_MutexContainer
{
private:
GenericAnyMapImpl maAnyMap;
::cppu::OMultiTypeInterfaceContainerHelperVar< ::rtl::OUString,UStringHash,UStringEqual> m_aListener;
protected:
virtual void _setPropertyValues( const PropertyMapEntry** ppEntries, const Any* pValues ) throw( UnknownPropertyException, PropertyVetoException, IllegalArgumentException, WrappedTargetException );
virtual void _getPropertyValues( const PropertyMapEntry** ppEntries, Any* pValue ) throw( UnknownPropertyException, WrappedTargetException );
public:
GenericPropertySet( PropertySetInfo* pInfo ) throw();
virtual ~GenericPropertySet() throw();
// XInterface
virtual Any SAL_CALL queryAggregation( const Type & rType ) throw( RuntimeException);
virtual Any SAL_CALL queryInterface( const Type & rType ) throw( RuntimeException);
virtual void SAL_CALL acquire() throw();
virtual void SAL_CALL release() throw();
// XTypeProvider
virtual Sequence< Type > SAL_CALL getTypes( ) throw( RuntimeException);
virtual Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw( RuntimeException);
// XServiceInfo
virtual rtl::OUString SAL_CALL getImplementationName() throw( RuntimeException );
virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& ServiceName ) throw( RuntimeException );
virtual Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames() throw( RuntimeException );
// XPropertySet
virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
};
}
///////////////////////////////////////////////////////////////////////
GenericPropertySet::GenericPropertySet( PropertySetInfo* pInfo ) throw()
: PropertySetHelper( pInfo )
,m_aListener(maMutex)
{
}
GenericPropertySet::~GenericPropertySet() throw()
{
}
void SAL_CALL GenericPropertySet::addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const Reference< XPropertyChangeListener >& xListener ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
Reference < XPropertySetInfo > xInfo = getPropertySetInfo( );
if ( xInfo.is() )
{
if ( !aPropertyName.getLength() )
{
Sequence< Property> aSeq = xInfo->getProperties();
const Property* pIter = aSeq.getConstArray();
const Property* pEnd = pIter + aSeq.getLength();
for( ; pIter != pEnd ; ++pIter)
{
m_aListener.addInterface(pIter->Name,xListener);
}
}
else if ( xInfo->hasPropertyByName(aPropertyName) )
m_aListener.addInterface(aPropertyName,xListener);
else
throw UnknownPropertyException( aPropertyName, *this );
}
}
void SAL_CALL GenericPropertySet::removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const Reference< XPropertyChangeListener >& xListener ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
ResettableMutexGuard aGuard( maMutex );
Reference < XPropertySetInfo > xInfo = getPropertySetInfo( );
aGuard.clear();
if ( xInfo.is() )
{
if ( !aPropertyName.getLength() )
{
Sequence< Property> aSeq = xInfo->getProperties();
const Property* pIter = aSeq.getConstArray();
const Property* pEnd = pIter + aSeq.getLength();
for( ; pIter != pEnd ; ++pIter)
{
m_aListener.removeInterface(pIter->Name,xListener);
}
}
else if ( xInfo->hasPropertyByName(aPropertyName) )
m_aListener.removeInterface(aPropertyName,xListener);
else
throw UnknownPropertyException( aPropertyName, *this );
}
}
void GenericPropertySet::_setPropertyValues( const PropertyMapEntry** ppEntries, const Any* pValues )
throw(UnknownPropertyException, PropertyVetoException, IllegalArgumentException, WrappedTargetException )
{
ResettableMutexGuard aGuard( maMutex );
while( *ppEntries )
{
const OUString aPropertyName( (*ppEntries)->mpName, (*ppEntries)->mnNameLen, RTL_TEXTENCODING_ASCII_US );
OInterfaceContainerHelper * pHelper = m_aListener.getContainer(aPropertyName);
maAnyMap[ aPropertyName ] = *pValues;
if ( pHelper )
{
PropertyChangeEvent aEvt;
aEvt.PropertyName = aPropertyName;
aEvt.NewValue = *pValues;
aGuard.clear();
pHelper->notifyEach( &XPropertyChangeListener::propertyChange, aEvt );
aGuard.reset();
}
ppEntries++;
pValues++;
}
}
void GenericPropertySet::_getPropertyValues( const comphelper::PropertyMapEntry** ppEntries, Any* pValue )
throw( UnknownPropertyException, WrappedTargetException )
{
MutexGuard aGuard( maMutex );
while( *ppEntries )
{
const OUString aPropertyName( (*ppEntries)->mpName, (*ppEntries)->mnNameLen, RTL_TEXTENCODING_ASCII_US );
*pValue = maAnyMap[ aPropertyName ];
ppEntries++;
pValue++;
}
}
// XInterface
Any SAL_CALL GenericPropertySet::queryInterface( const Type & rType )
throw( RuntimeException )
{
return OWeakAggObject::queryInterface( rType );
}
Any SAL_CALL GenericPropertySet::queryAggregation( const Type & rType )
throw(RuntimeException)
{
Any aAny;
if( rType == ::getCppuType((const Reference< XServiceInfo >*)0) )
aAny <<= Reference< XServiceInfo >(this);
else if( rType == ::getCppuType((const Reference< XTypeProvider >*)0) )
aAny <<= Reference< XTypeProvider >(this);
else if( rType == ::getCppuType((const Reference< XPropertySet >*)0) )
aAny <<= Reference< XPropertySet >(this);
else if( rType == ::getCppuType((const Reference< XMultiPropertySet >*)0) )
aAny <<= Reference< XMultiPropertySet >(this);
else
aAny <<= OWeakAggObject::queryAggregation( rType );
return aAny;
}
void SAL_CALL GenericPropertySet::acquire() throw()
{
OWeakAggObject::acquire();
}
void SAL_CALL GenericPropertySet::release() throw()
{
OWeakAggObject::release();
}
uno::Sequence< uno::Type > SAL_CALL GenericPropertySet::getTypes()
throw (uno::RuntimeException)
{
uno::Sequence< uno::Type > aTypes( 5 );
uno::Type* pTypes = aTypes.getArray();
*pTypes++ = ::getCppuType((const uno::Reference< XAggregation>*)0);
*pTypes++ = ::getCppuType((const uno::Reference< XServiceInfo>*)0);
*pTypes++ = ::getCppuType((const uno::Reference< XTypeProvider>*)0);
*pTypes++ = ::getCppuType((const uno::Reference< XPropertySet>*)0);
*pTypes++ = ::getCppuType((const uno::Reference< XMultiPropertySet>*)0);
return aTypes;
}
namespace
{
class theGenericPropertySetImplmentationId : public rtl::Static< UnoTunnelIdInit, theGenericPropertySetImplmentationId > {};
}
uno::Sequence< sal_Int8 > SAL_CALL GenericPropertySet::getImplementationId()
throw (uno::RuntimeException)
{
return theGenericPropertySetImplmentationId::get().getSeq();
}
// XServiceInfo
sal_Bool SAL_CALL GenericPropertySet::supportsService( const OUString& ServiceName ) throw(RuntimeException)
{
Sequence< OUString > aSNL( getSupportedServiceNames() );
const OUString * pArray = aSNL.getConstArray();
for( sal_Int32 i = 0; i < aSNL.getLength(); ++i )
if( pArray[i] == ServiceName )
return sal_True;
return sal_False;
}
OUString SAL_CALL GenericPropertySet::getImplementationName() throw( RuntimeException )
{
return OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.comphelper.GenericPropertySet") );
}
Sequence< OUString > SAL_CALL GenericPropertySet::getSupportedServiceNames( )
throw( RuntimeException )
{
Sequence< OUString > aSNS( 1 );
aSNS.getArray()[0] = OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.beans.XPropertySet" ));
return aSNS;
}
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > comphelper::GenericPropertySet_CreateInstance( comphelper::PropertySetInfo* pInfo )
{
return (XPropertySet*)new GenericPropertySet( pInfo );
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>//===- ValueMapper.cpp - Interface shared by lib/Transforms/Utils ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the MapValue function, which is shared by various parts of
// the lib/Transforms/Utils library.
//
//===----------------------------------------------------------------------===//
#include "ValueMapper.h"
#include "llvm/Type.h"
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/Metadata.h"
#include "llvm/ADT/SmallVector.h"
using namespace llvm;
Value *llvm::MapValue(const Value *V, ValueToValueMapTy &VM) {
Value *&VMSlot = VM[V];
if (VMSlot) return VMSlot; // Does it exist in the map yet?
// NOTE: VMSlot can be invalidated by any reference to VM, which can grow the
// DenseMap. This includes any recursive calls to MapValue.
// Global values and non-function-local metadata do not need to be seeded into
// the VM if they are using the identity mapping.
if (isa<GlobalValue>(V) || isa<InlineAsm>(V) || isa<MDString>(V) ||
(isa<MDNode>(V) && !cast<MDNode>(V)->isFunctionLocal()))
return VMSlot = const_cast<Value*>(V);
if (const MDNode *MD = dyn_cast<MDNode>(V)) {
SmallVector<Value*, 4> Elts;
for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
Elts.push_back(MD->getOperand(i) ? MapValue(MD->getOperand(i), VM) : 0);
return VM[V] = MDNode::get(V->getContext(), Elts.data(), Elts.size());
}
Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
if (C == 0) return 0;
if (isa<ConstantInt>(C) || isa<ConstantFP>(C) ||
isa<ConstantPointerNull>(C) || isa<ConstantAggregateZero>(C) ||
isa<UndefValue>(C))
return VMSlot = C; // Primitive constants map directly
if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) {
for (User::op_iterator b = CA->op_begin(), i = b, e = CA->op_end();
i != e; ++i) {
Value *MV = MapValue(*i, VM);
if (MV != *i) {
// This array must contain a reference to a global, make a new array
// and return it.
//
std::vector<Constant*> Values;
Values.reserve(CA->getNumOperands());
for (User::op_iterator j = b; j != i; ++j)
Values.push_back(cast<Constant>(*j));
Values.push_back(cast<Constant>(MV));
for (++i; i != e; ++i)
Values.push_back(cast<Constant>(MapValue(*i, VM)));
return VM[V] = ConstantArray::get(CA->getType(), Values);
}
}
return VM[V] = C;
}
if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
for (User::op_iterator b = CS->op_begin(), i = b, e = CS->op_end();
i != e; ++i) {
Value *MV = MapValue(*i, VM);
if (MV != *i) {
// This struct must contain a reference to a global, make a new struct
// and return it.
//
std::vector<Constant*> Values;
Values.reserve(CS->getNumOperands());
for (User::op_iterator j = b; j != i; ++j)
Values.push_back(cast<Constant>(*j));
Values.push_back(cast<Constant>(MV));
for (++i; i != e; ++i)
Values.push_back(cast<Constant>(MapValue(*i, VM)));
return VM[V] = ConstantStruct::get(CS->getType(), Values);
}
}
return VM[V] = C;
}
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
std::vector<Constant*> Ops;
for (User::op_iterator i = CE->op_begin(), e = CE->op_end(); i != e; ++i)
Ops.push_back(cast<Constant>(MapValue(*i, VM)));
return VM[V] = CE->getWithOperands(Ops);
}
if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
for (User::op_iterator b = CV->op_begin(), i = b, e = CV->op_end();
i != e; ++i) {
Value *MV = MapValue(*i, VM);
if (MV != *i) {
// This vector value must contain a reference to a global, make a new
// vector constant and return it.
//
std::vector<Constant*> Values;
Values.reserve(CV->getNumOperands());
for (User::op_iterator j = b; j != i; ++j)
Values.push_back(cast<Constant>(*j));
Values.push_back(cast<Constant>(MV));
for (++i; i != e; ++i)
Values.push_back(cast<Constant>(MapValue(*i, VM)));
return VM[V] = ConstantVector::get(Values);
}
}
return VM[V] = C;
}
BlockAddress *BA = cast<BlockAddress>(C);
Function *F = cast<Function>(MapValue(BA->getFunction(), VM));
BasicBlock *BB = cast_or_null<BasicBlock>(MapValue(BA->getBasicBlock(),VM));
return VM[V] = BlockAddress::get(F, BB ? BB : BA->getBasicBlock());
}
/// RemapInstruction - Convert the instruction operands from referencing the
/// current values into those specified by VMap.
///
void llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &VMap) {
for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) {
Value *V = MapValue(*op, VMap);
assert(V && "Referenced value not in value map!");
*op = V;
}
}
<commit_msg>Whether function-local or not, a MDNode may reference a Function in which case it needs to be mapped to refer to the function in the new module, not the old one. Fixes PR7700.<commit_after>//===- ValueMapper.cpp - Interface shared by lib/Transforms/Utils ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the MapValue function, which is shared by various parts of
// the lib/Transforms/Utils library.
//
//===----------------------------------------------------------------------===//
#include "ValueMapper.h"
#include "llvm/Type.h"
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/Metadata.h"
#include "llvm/ADT/SmallVector.h"
using namespace llvm;
Value *llvm::MapValue(const Value *V, ValueToValueMapTy &VM) {
Value *&VMSlot = VM[V];
if (VMSlot) return VMSlot; // Does it exist in the map yet?
// NOTE: VMSlot can be invalidated by any reference to VM, which can grow the
// DenseMap. This includes any recursive calls to MapValue.
// Global values do not need to be seeded into the VM if they are using
// the identity mapping.
if (isa<GlobalValue>(V) || isa<InlineAsm>(V) || isa<MDString>(V))
return VMSlot = const_cast<Value*>(V);
if (const MDNode *MD = dyn_cast<MDNode>(V)) {
SmallVector<Value*, 4> Elts;
for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
Elts.push_back(MD->getOperand(i) ? MapValue(MD->getOperand(i), VM) : 0);
return VM[V] = MDNode::get(V->getContext(), Elts.data(), Elts.size());
}
Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
if (C == 0) return 0;
if (isa<ConstantInt>(C) || isa<ConstantFP>(C) ||
isa<ConstantPointerNull>(C) || isa<ConstantAggregateZero>(C) ||
isa<UndefValue>(C))
return VMSlot = C; // Primitive constants map directly
if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) {
for (User::op_iterator b = CA->op_begin(), i = b, e = CA->op_end();
i != e; ++i) {
Value *MV = MapValue(*i, VM);
if (MV != *i) {
// This array must contain a reference to a global, make a new array
// and return it.
//
std::vector<Constant*> Values;
Values.reserve(CA->getNumOperands());
for (User::op_iterator j = b; j != i; ++j)
Values.push_back(cast<Constant>(*j));
Values.push_back(cast<Constant>(MV));
for (++i; i != e; ++i)
Values.push_back(cast<Constant>(MapValue(*i, VM)));
return VM[V] = ConstantArray::get(CA->getType(), Values);
}
}
return VM[V] = C;
}
if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
for (User::op_iterator b = CS->op_begin(), i = b, e = CS->op_end();
i != e; ++i) {
Value *MV = MapValue(*i, VM);
if (MV != *i) {
// This struct must contain a reference to a global, make a new struct
// and return it.
//
std::vector<Constant*> Values;
Values.reserve(CS->getNumOperands());
for (User::op_iterator j = b; j != i; ++j)
Values.push_back(cast<Constant>(*j));
Values.push_back(cast<Constant>(MV));
for (++i; i != e; ++i)
Values.push_back(cast<Constant>(MapValue(*i, VM)));
return VM[V] = ConstantStruct::get(CS->getType(), Values);
}
}
return VM[V] = C;
}
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
std::vector<Constant*> Ops;
for (User::op_iterator i = CE->op_begin(), e = CE->op_end(); i != e; ++i)
Ops.push_back(cast<Constant>(MapValue(*i, VM)));
return VM[V] = CE->getWithOperands(Ops);
}
if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
for (User::op_iterator b = CV->op_begin(), i = b, e = CV->op_end();
i != e; ++i) {
Value *MV = MapValue(*i, VM);
if (MV != *i) {
// This vector value must contain a reference to a global, make a new
// vector constant and return it.
//
std::vector<Constant*> Values;
Values.reserve(CV->getNumOperands());
for (User::op_iterator j = b; j != i; ++j)
Values.push_back(cast<Constant>(*j));
Values.push_back(cast<Constant>(MV));
for (++i; i != e; ++i)
Values.push_back(cast<Constant>(MapValue(*i, VM)));
return VM[V] = ConstantVector::get(Values);
}
}
return VM[V] = C;
}
BlockAddress *BA = cast<BlockAddress>(C);
Function *F = cast<Function>(MapValue(BA->getFunction(), VM));
BasicBlock *BB = cast_or_null<BasicBlock>(MapValue(BA->getBasicBlock(),VM));
return VM[V] = BlockAddress::get(F, BB ? BB : BA->getBasicBlock());
}
/// RemapInstruction - Convert the instruction operands from referencing the
/// current values into those specified by VMap.
///
void llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &VMap) {
for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) {
Value *V = MapValue(*op, VMap);
assert(V && "Referenced value not in value map!");
*op = V;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef WIN32
# include <windows.h>
# include <string.h>
# include <strsafe.h>
#endif
#include <vector>
#include <zorba/config.h>
#include "xqdb_client.h"
#include "process_listener.h"
using namespace zorba;
using namespace zorba::debugger;
std::auto_ptr<XqdbClient> theClient;
void
onExitProcess(ExitCode aExitCode) {
std::cout << "Terminating debugger client." << std::endl;
exit(aExitCode);
}
int
startZorba(std::string& aExec, std::vector<std::string>& aArgs, std::auto_ptr<ProcessListener>& aProcessListener)
{
#ifdef WIN32
// **************************
// start a process on Windows
DWORD iReturnVal = 0;
std::wstring lExec;
std::wstring lArgs;
lExec.assign(aExec.begin(), aExec.end());
// the executable must be the first in the list of arguments
lArgs.append(L"\"");
lArgs.append(lExec);
lArgs.append(L"\"");
for (std::vector<std::string>::size_type j = 0; j < aArgs.size(); j++) {
std::string lArg(aArgs.at(j));
std::wstring lArgW;
lArgW.assign(lArg.begin(), lArg.end());
lArgs.append(L" ");
lArgs.append(lArgW);
}
// CreateProcessW can modify Parameters thus we allocate needed memory
wchar_t * pwszParam = new wchar_t[lArgs.size() + 1];
if (pwszParam == 0) {
return 1;
}
const wchar_t* pchrTemp = lArgs.c_str();
wcscpy_s(pwszParam, lArgs.size() + 1, pchrTemp);
// CreateProcess API initialization
STARTUPINFOW siStartupInfo;
PROCESS_INFORMATION piProcessInfo;
memset(&siStartupInfo, 0, sizeof(siStartupInfo));
memset(&piProcessInfo, 0, sizeof(piProcessInfo));
siStartupInfo.cb = sizeof(siStartupInfo);
BOOL lResult = CreateProcessW(
const_cast<LPCWSTR>(lExec.c_str()),
pwszParam, 0, 0, false,
CREATE_DEFAULT_ERROR_MODE, 0, 0,
&siStartupInfo, &piProcessInfo);
if (lResult) {
// Watch the process
aProcessListener.reset(new ProcessListener(piProcessInfo.dwProcessId, &onExitProcess));
}
else {
// CreateProcess failed
iReturnVal = GetLastError();
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
iReturnVal,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL);
// Display the error message and exit the process
lpDisplayBuf = (LPVOID)LocalAlloc(
LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf) + 40) * sizeof(TCHAR));
StringCchPrintf(
(LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("Error (%d) when starting zorba: %s"),
iReturnVal,
lpMsgBuf);
std::wstring lErrorW((wchar_t*)lpDisplayBuf);
std::string lError;
lError.assign(lErrorW.begin(), lErrorW.end());
std::cout << lError << std::endl;
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
}
// Free memory
delete[]pwszParam;
pwszParam = 0;
// Release handles
CloseHandle(piProcessInfo.hProcess);
CloseHandle(piProcessInfo.hThread);
return iReturnVal;
#else
// ************************
// start a process on Linux
pid_t pID = fork();
if (pID == 0) {
// Code only executed by child process
std::stringstream lCommand;
lCommand << aExec;
for (std::vector<std::string>::size_type j = 0; j < aArgs.size(); j++) {
lCommand << " " << aArgs.at(j);
}
int lRes = system(lCommand.str().c_str());
exit(lRes);
}
else {
// Code only executed by parent process
if (pID < 0) {
std::cerr << "Failed to fork Zorba" << std::endl;
return pID;
}
// Watch the process
aProcessListener.reset(new ProcessListener(pID, &onExitProcess));
return 0;
}
#endif
}
void printUsage(std::string& aProgram)
{
std::cerr << "Usage:" << std::endl
<< " " << aProgram << " <zorba_arguments>" << std::endl
<< " this will start a debugger command line and a zorba process with the given arguments" << std::endl;
}
bool
processArguments(
int argc,
char* argv[],
std::string& aProgram,
bool& aStandalone,
std::string& aZorba,
unsigned int& aPort,
std::vector<std::string>& aZorbaArgs)
{
aPort = 28028;
// find the path to Zorba and this executable name
aProgram = argv[0];
#ifdef WIN32
char lSep = '\\';
#else
char lSep = '/';
#endif
std::string::size_type lPos = aProgram.find_last_of(lSep);
std::stringstream lZs;
if (lPos == aProgram.npos) {
lZs << "." << lSep;
} else {
lZs << aProgram.substr(0, lPos + 1);
aProgram = aProgram.substr(lPos + 1);
}
lZs << "zorba";
#ifdef WIN32
lZs << ".exe";
#endif
aZorba = lZs.str();
bool lHasFileArg = false;
bool lHasQueryArg = false;
bool lHasQueryVal = false;
// find if the user asked for help or specified a specific port
for (int i = 1; i < argc; i++) {
std::string lArg = argv[i];
if (lArg == "-h" || lArg == "--help") {
return false;
}
else if (lArg == "-p" || lArg == "--debug-port") {
// if there is one more argument
if (i < argc - 1) {
// get the port value
int lPort;
std::stringstream lStream(argv[i + 1]);
lStream >> lPort;
if (!lStream.fail()) {
aPort = lPort;
}
}
}
else if (lArg == "-f") {
lHasFileArg = true;
}
else if (lArg == "-q") {
lHasQueryArg = true;
if (++i < argc) {
lHasQueryVal = true;
}
}
}
if (!lHasFileArg || !lHasQueryArg || !lHasQueryVal) {
std::cout << "Not enough arguments to start Zorba." << std::endl;
std::cout << "Running the standalone XQuery debugger client on port: " << aPort << std::endl;
return true;
}
// zorba will need the -d flag
aZorbaArgs.push_back("-d");
// gather all arguments (excepting the program name)
for (int i = 1; i < argc; i++) {
aZorbaArgs.push_back(argv[i]);
}
aStandalone = false;
return true;
}
#ifdef WIN32
BOOL WINAPI
ctrlC_Handler(DWORD aCtrlType)
{
if (CTRL_C_EVENT == aCtrlType) {
return true;
}
return false;
}
#else
void
ctrlC_Handler(int lParam)
{
//exit(1);
}
#endif
#ifndef _WIN32_WCE
int
main(int argc, char* argv[])
#else
int
_tmain(int argc, _TCHAR* argv[])
#endif
{
#ifdef WIN32
SetConsoleCtrlHandler(ctrlC_Handler, TRUE);
#else
signal(SIGINT, ctrlC_Handler);
#endif
// **************************************************************************
// processing arguments
std::string lProgram, lZorbaExec;
unsigned int lPort = 28028;
std::vector<std::string> lZorbaArgs;
bool lStandalone = true;
if (!processArguments(argc, argv, lProgram, lStandalone, lZorbaExec, lPort, lZorbaArgs)) {
printUsage(lProgram);
return 1;
}
#ifndef NDEBUG
// **************************************************************************
// debug reporting
if (!lStandalone) {
std::cout << "Communication port: " << lPort << std::endl;
std::cout << "Zorba executable: " << lZorbaExec << std::endl;
std::cout << "Zorba arguments: ";
for (std::vector<std::string>::size_type j = 0; j < lZorbaArgs.size(); j++) {
std::cout << lZorbaArgs.at(j) << " ";
}
std::cout << std::endl;
}
#endif
try {
// **************************************************************************
// start a zorba
// This is a process listener used to watch the Zorba process termination.
std::auto_ptr<ProcessListener> lProcessListener;
if (!lStandalone) {
int lResult = startZorba(lZorbaExec, lZorbaArgs, lProcessListener);
if (lResult) {
return lResult;
}
} else {
std::cout << "Listening for an incomming Zorba connection on port " << lPort << "..." << std::endl;
}
// **************************************************************************
// start the debugger command line
theClient.reset(new XqdbClient(lPort));
theClient->start();
} catch (...) {
return -1;
}
return 0;
}
<commit_msg>clean XqdbClient termination also on Linux; I don't know why the exit function does not trigger a cleanup of the autoptr on Linux; this works on Windows where no explicit release&delete is necessary<commit_after>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef WIN32
# include <windows.h>
# include <string.h>
# include <strsafe.h>
#endif
#include <vector>
#include <zorba/config.h>
#include "xqdb_client.h"
#include "process_listener.h"
using namespace zorba;
using namespace zorba::debugger;
std::auto_ptr<XqdbClient> theClient;
void
onExitProcess(ExitCode aExitCode) {
std::cout << std::endl << "Terminating debugger client." << std::endl;
XqdbClient* lClient = theClient.release();
if (lClient) {
delete lClient;
}
exit(aExitCode);
}
int
startZorba(std::string& aExec, std::vector<std::string>& aArgs, std::auto_ptr<ProcessListener>& aProcessListener)
{
#ifdef WIN32
// **************************
// start a process on Windows
DWORD iReturnVal = 0;
std::wstring lExec;
std::wstring lArgs;
lExec.assign(aExec.begin(), aExec.end());
// the executable must be the first in the list of arguments
lArgs.append(L"\"");
lArgs.append(lExec);
lArgs.append(L"\"");
for (std::vector<std::string>::size_type j = 0; j < aArgs.size(); j++) {
std::string lArg(aArgs.at(j));
std::wstring lArgW;
lArgW.assign(lArg.begin(), lArg.end());
lArgs.append(L" ");
lArgs.append(lArgW);
}
// CreateProcessW can modify Parameters thus we allocate needed memory
wchar_t * pwszParam = new wchar_t[lArgs.size() + 1];
if (pwszParam == 0) {
return 1;
}
const wchar_t* pchrTemp = lArgs.c_str();
wcscpy_s(pwszParam, lArgs.size() + 1, pchrTemp);
// CreateProcess API initialization
STARTUPINFOW siStartupInfo;
PROCESS_INFORMATION piProcessInfo;
memset(&siStartupInfo, 0, sizeof(siStartupInfo));
memset(&piProcessInfo, 0, sizeof(piProcessInfo));
siStartupInfo.cb = sizeof(siStartupInfo);
BOOL lResult = CreateProcessW(
const_cast<LPCWSTR>(lExec.c_str()),
pwszParam, 0, 0, false,
CREATE_DEFAULT_ERROR_MODE, 0, 0,
&siStartupInfo, &piProcessInfo);
if (lResult) {
// Watch the process
aProcessListener.reset(new ProcessListener(piProcessInfo.dwProcessId, &onExitProcess));
}
else {
// CreateProcess failed
iReturnVal = GetLastError();
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
iReturnVal,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL);
// Display the error message and exit the process
lpDisplayBuf = (LPVOID)LocalAlloc(
LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf) + 40) * sizeof(TCHAR));
StringCchPrintf(
(LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("Error (%d) when starting zorba: %s"),
iReturnVal,
lpMsgBuf);
std::wstring lErrorW((wchar_t*)lpDisplayBuf);
std::string lError;
lError.assign(lErrorW.begin(), lErrorW.end());
std::cout << lError << std::endl;
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
}
// Free memory
delete[]pwszParam;
pwszParam = 0;
// Release handles
CloseHandle(piProcessInfo.hProcess);
CloseHandle(piProcessInfo.hThread);
return iReturnVal;
#else
// ************************
// start a process on Linux
pid_t pID = fork();
if (pID == 0) {
// Code only executed by child process
std::stringstream lCommand;
lCommand << aExec;
for (std::vector<std::string>::size_type j = 0; j < aArgs.size(); j++) {
lCommand << " " << aArgs.at(j);
}
int lRes = system(lCommand.str().c_str());
exit(lRes);
}
else {
// Code only executed by parent process
if (pID < 0) {
std::cerr << "Failed to fork Zorba" << std::endl;
return pID;
}
// Watch the process
aProcessListener.reset(new ProcessListener(pID, &onExitProcess));
return 0;
}
#endif
}
void printUsage(std::string& aProgram)
{
std::cerr << "Usage:" << std::endl
<< " " << aProgram << " <zorba_arguments>" << std::endl
<< " this will start a debugger command line and a zorba process with the given arguments" << std::endl;
}
bool
processArguments(
int argc,
char* argv[],
std::string& aProgram,
bool& aStandalone,
std::string& aZorba,
unsigned int& aPort,
std::vector<std::string>& aZorbaArgs)
{
aPort = 28028;
// find the path to Zorba and this executable name
aProgram = argv[0];
#ifdef WIN32
char lSep = '\\';
#else
char lSep = '/';
#endif
std::string::size_type lPos = aProgram.find_last_of(lSep);
std::stringstream lZs;
if (lPos == aProgram.npos) {
lZs << "." << lSep;
} else {
lZs << aProgram.substr(0, lPos + 1);
aProgram = aProgram.substr(lPos + 1);
}
lZs << "zorba";
#ifdef WIN32
lZs << ".exe";
#endif
aZorba = lZs.str();
bool lHasFileArg = false;
bool lHasQueryArg = false;
bool lHasQueryVal = false;
// find if the user asked for help or specified a specific port
for (int i = 1; i < argc; i++) {
std::string lArg = argv[i];
if (lArg == "-h" || lArg == "--help") {
return false;
}
else if (lArg == "-p" || lArg == "--debug-port") {
// if there is one more argument
if (i < argc - 1) {
// get the port value
int lPort;
std::stringstream lStream(argv[i + 1]);
lStream >> lPort;
if (!lStream.fail()) {
aPort = lPort;
}
}
}
else if (lArg == "-f") {
lHasFileArg = true;
}
else if (lArg == "-q") {
lHasQueryArg = true;
if (++i < argc) {
lHasQueryVal = true;
}
}
}
if (!lHasFileArg || !lHasQueryArg || !lHasQueryVal) {
std::cout << "Not enough arguments to start Zorba." << std::endl;
std::cout << "Running the standalone XQuery debugger client on port: " << aPort << std::endl;
return true;
}
// zorba will need the -d flag
aZorbaArgs.push_back("-d");
// gather all arguments (excepting the program name)
for (int i = 1; i < argc; i++) {
aZorbaArgs.push_back(argv[i]);
}
aStandalone = false;
return true;
}
#ifdef WIN32
BOOL WINAPI
ctrlC_Handler(DWORD aCtrlType)
{
if (CTRL_C_EVENT == aCtrlType) {
return true;
}
return false;
}
#else
void
ctrlC_Handler(int lParam)
{
//exit(1);
}
#endif
#ifndef _WIN32_WCE
int
main(int argc, char* argv[])
#else
int
_tmain(int argc, _TCHAR* argv[])
#endif
{
#ifdef WIN32
SetConsoleCtrlHandler(ctrlC_Handler, TRUE);
#else
signal(SIGINT, ctrlC_Handler);
#endif
// **************************************************************************
// processing arguments
std::string lProgram, lZorbaExec;
unsigned int lPort = 28028;
std::vector<std::string> lZorbaArgs;
bool lStandalone = true;
if (!processArguments(argc, argv, lProgram, lStandalone, lZorbaExec, lPort, lZorbaArgs)) {
printUsage(lProgram);
return 1;
}
#ifndef NDEBUG
// **************************************************************************
// debug reporting
if (!lStandalone) {
std::cout << "Communication port: " << lPort << std::endl;
std::cout << "Zorba executable: " << lZorbaExec << std::endl;
std::cout << "Zorba arguments: ";
for (std::vector<std::string>::size_type j = 0; j < lZorbaArgs.size(); j++) {
std::cout << lZorbaArgs.at(j) << " ";
}
std::cout << std::endl;
}
#endif
try {
// **************************************************************************
// start a zorba
// This is a process listener used to watch the Zorba process termination.
std::auto_ptr<ProcessListener> lProcessListener;
if (!lStandalone) {
int lResult = startZorba(lZorbaExec, lZorbaArgs, lProcessListener);
if (lResult) {
return lResult;
}
} else {
std::cout << "Listening for an incomming Zorba connection on port " << lPort << "..." << std::endl;
}
// **************************************************************************
// start the debugger command line
theClient.reset(new XqdbClient(lPort));
theClient->start();
} catch (...) {
return -1;
}
return 0;
}
<|endoftext|> |
<commit_before>// -*-c++-*-
#include <osgProducer/Viewer>
#include <osgDB/ReadFile>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/StateSet>
#include <osg/Material>
#include <osg/Texture2D>
#include <osg/TextureRectangle>
#include <osg/TexMat>
#include <osg/CullFace>
#include <osg/ImageStream>
#include <osgGA/TrackballManipulator>
osg::ImageStream* s_imageStream = 0;
class PostSwapFinishCallback : public Producer::Camera::Callback
{
public:
PostSwapFinishCallback() {}
virtual void operator()(const Producer::Camera& camera)
{
// osg::Timer_t start_tick = osg::Timer::instance()->tick();
osgProducer::OsgSceneHandler* sh = const_cast<osgProducer::OsgSceneHandler*>(dynamic_cast<const osgProducer::OsgSceneHandler*>(camera.getSceneHandler()));
if (s_imageStream && s_imageStream->getPixelBufferObject()) s_imageStream->getPixelBufferObject()->compileBuffer(*(sh->getSceneView()->getState()));
// glFinish();
//osg::notify(osg::NOTICE)<<"callback after PBO "<<osg::Timer::instance()->delta_m(start_tick,osg::Timer::instance()->tick())<<"ms"<<std::endl;
}
};
class MovieEventHandler : public osgGA::GUIEventHandler
{
public:
MovieEventHandler() {}
void set(osg::Node* node);
virtual void accept(osgGA::GUIEventHandlerVisitor& v) { v.visit(*this); }
virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&);
virtual void getUsage(osg::ApplicationUsage& usage) const;
typedef std::vector< osg::ref_ptr<osg::ImageStream> > ImageStreamList;
protected:
virtual ~MovieEventHandler() {}
class FindImageStreamsVisitor : public osg::NodeVisitor
{
public:
FindImageStreamsVisitor(ImageStreamList& imageStreamList):
_imageStreamList(imageStreamList) {}
virtual void apply(osg::Geode& geode)
{
apply(geode.getStateSet());
for(unsigned int i=0;i<geode.getNumDrawables();++i)
{
apply(geode.getDrawable(i)->getStateSet());
}
traverse(geode);
}
virtual void apply(osg::Node& node)
{
apply(node.getStateSet());
traverse(node);
}
inline void apply(osg::StateSet* stateset)
{
if (!stateset) return;
osg::StateAttribute* attr = stateset->getTextureAttribute(0,osg::StateAttribute::TEXTURE);
if (attr)
{
osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(attr);
if (texture2D) apply(dynamic_cast<osg::ImageStream*>(texture2D->getImage()));
osg::TextureRectangle* textureRec = dynamic_cast<osg::TextureRectangle*>(attr);
if (textureRec) apply(dynamic_cast<osg::ImageStream*>(textureRec->getImage()));
}
}
inline void apply(osg::ImageStream* imagestream)
{
if (imagestream)
{
_imageStreamList.push_back(imagestream);
s_imageStream = imagestream;
}
}
ImageStreamList& _imageStreamList;
};
ImageStreamList _imageStreamList;
};
void MovieEventHandler::set(osg::Node* node)
{
_imageStreamList.clear();
if (node)
{
FindImageStreamsVisitor fisv(_imageStreamList);
node->accept(fisv);
}
}
bool MovieEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
{
switch(ea.getEventType())
{
case(osgGA::GUIEventAdapter::KEYDOWN):
{
if (ea.getKey()=='s')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Play"<<std::endl;
(*itr)->play();
}
return true;
}
else if (ea.getKey()=='p')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Pause"<<std::endl;
(*itr)->pause();
}
return true;
}
else if (ea.getKey()=='r')
{
return true;
}
else if (ea.getKey()=='l')
{
return true;
}
return false;
}
default:
return false;
}
}
void MovieEventHandler::getUsage(osg::ApplicationUsage& usage) const
{
usage.addKeyboardMouseBinding("p","Pause movie");
usage.addKeyboardMouseBinding("s","Play movie");
usage.addKeyboardMouseBinding("r","Start movie");
usage.addKeyboardMouseBinding("l","Toggle looping of movie");
}
osg::Geometry* createTexturedQuadGeometry(const osg::Vec3& pos,float width,float height, osg::Image* image)
{
bool useTextureRectangle = true;
if (useTextureRectangle)
{
osg::Geometry* pictureQuad = osg::createTexturedQuadGeometry(pos,
osg::Vec3(width,0.0f,0.0f),
osg::Vec3(0.0f,0.0f,height),
image->s(),image->t());
pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
new osg::TextureRectangle(image),
osg::StateAttribute::ON);
return pictureQuad;
}
else
{
osg::Geometry* pictureQuad = osg::createTexturedQuadGeometry(pos,
osg::Vec3(width,0.0f,0.0f),
osg::Vec3(0.0f,0.0f,height),
1.0f,1.0f);
pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
new osg::Texture2D(image),
osg::StateAttribute::ON);
return pictureQuad;
}
}
int main(int argc, char** argv)
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// register the handler to add keyboard and mosue handling.
MovieEventHandler* meh = new MovieEventHandler();
viewer.getEventHandlerList().push_front(meh);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
osg::Geode* geode = new osg::Geode;
osg::Vec3 pos(0.0f,0.0f,0.0f);
for(int i=1;i<arguments.argc();++i)
{
if (arguments.isString(i))
{
osg::Image* image = osgDB::readImageFile(arguments[i]);
geode->addDrawable(createTexturedQuadGeometry(pos,image->s(),image->t(),image));
geode->getOrCreateStateSet()->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
}
}
// pass the model to the MovieEventHandler so it can pick out ImageStream's to manipulate.
meh->set(geode);
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
if (arguments.argc()<=1)
{
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
}
// set up a post swap callback to flush deleted GL objects and compile new GL objects
for(unsigned int cameraNum=0;cameraNum<viewer.getNumberOfCameras();++cameraNum)
{
Producer::Camera* camera=viewer.getCamera(cameraNum);
camera->addPostSwapCallback(new PostSwapFinishCallback());
}
// set the scene to render
viewer.setSceneData(geode);
// create the windows and run the threads.
viewer.realize();
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
}
<commit_msg>Added vertical offset to multiple movies instances<commit_after>// -*-c++-*-
#include <osgProducer/Viewer>
#include <osgDB/ReadFile>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/StateSet>
#include <osg/Material>
#include <osg/Texture2D>
#include <osg/TextureRectangle>
#include <osg/TexMat>
#include <osg/CullFace>
#include <osg/ImageStream>
#include <osgGA/TrackballManipulator>
osg::ImageStream* s_imageStream = 0;
class PostSwapFinishCallback : public Producer::Camera::Callback
{
public:
PostSwapFinishCallback() {}
virtual void operator()(const Producer::Camera& camera)
{
// osg::Timer_t start_tick = osg::Timer::instance()->tick();
osgProducer::OsgSceneHandler* sh = const_cast<osgProducer::OsgSceneHandler*>(dynamic_cast<const osgProducer::OsgSceneHandler*>(camera.getSceneHandler()));
if (s_imageStream && s_imageStream->getPixelBufferObject()) s_imageStream->getPixelBufferObject()->compileBuffer(*(sh->getSceneView()->getState()));
// glFinish();
//osg::notify(osg::NOTICE)<<"callback after PBO "<<osg::Timer::instance()->delta_m(start_tick,osg::Timer::instance()->tick())<<"ms"<<std::endl;
}
};
class MovieEventHandler : public osgGA::GUIEventHandler
{
public:
MovieEventHandler() {}
void set(osg::Node* node);
virtual void accept(osgGA::GUIEventHandlerVisitor& v) { v.visit(*this); }
virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&);
virtual void getUsage(osg::ApplicationUsage& usage) const;
typedef std::vector< osg::ref_ptr<osg::ImageStream> > ImageStreamList;
protected:
virtual ~MovieEventHandler() {}
class FindImageStreamsVisitor : public osg::NodeVisitor
{
public:
FindImageStreamsVisitor(ImageStreamList& imageStreamList):
_imageStreamList(imageStreamList) {}
virtual void apply(osg::Geode& geode)
{
apply(geode.getStateSet());
for(unsigned int i=0;i<geode.getNumDrawables();++i)
{
apply(geode.getDrawable(i)->getStateSet());
}
traverse(geode);
}
virtual void apply(osg::Node& node)
{
apply(node.getStateSet());
traverse(node);
}
inline void apply(osg::StateSet* stateset)
{
if (!stateset) return;
osg::StateAttribute* attr = stateset->getTextureAttribute(0,osg::StateAttribute::TEXTURE);
if (attr)
{
osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(attr);
if (texture2D) apply(dynamic_cast<osg::ImageStream*>(texture2D->getImage()));
osg::TextureRectangle* textureRec = dynamic_cast<osg::TextureRectangle*>(attr);
if (textureRec) apply(dynamic_cast<osg::ImageStream*>(textureRec->getImage()));
}
}
inline void apply(osg::ImageStream* imagestream)
{
if (imagestream)
{
_imageStreamList.push_back(imagestream);
s_imageStream = imagestream;
}
}
ImageStreamList& _imageStreamList;
};
ImageStreamList _imageStreamList;
};
void MovieEventHandler::set(osg::Node* node)
{
_imageStreamList.clear();
if (node)
{
FindImageStreamsVisitor fisv(_imageStreamList);
node->accept(fisv);
}
}
bool MovieEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
{
switch(ea.getEventType())
{
case(osgGA::GUIEventAdapter::KEYDOWN):
{
if (ea.getKey()=='s')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Play"<<std::endl;
(*itr)->play();
}
return true;
}
else if (ea.getKey()=='p')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Pause"<<std::endl;
(*itr)->pause();
}
return true;
}
else if (ea.getKey()=='r')
{
return true;
}
else if (ea.getKey()=='l')
{
return true;
}
return false;
}
default:
return false;
}
}
void MovieEventHandler::getUsage(osg::ApplicationUsage& usage) const
{
usage.addKeyboardMouseBinding("p","Pause movie");
usage.addKeyboardMouseBinding("s","Play movie");
usage.addKeyboardMouseBinding("r","Start movie");
usage.addKeyboardMouseBinding("l","Toggle looping of movie");
}
osg::Geometry* createTexturedQuadGeometry(const osg::Vec3& pos,float width,float height, osg::Image* image)
{
bool useTextureRectangle = true;
if (useTextureRectangle)
{
osg::Geometry* pictureQuad = osg::createTexturedQuadGeometry(pos,
osg::Vec3(width,0.0f,0.0f),
osg::Vec3(0.0f,0.0f,height),
image->s(),image->t());
pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
new osg::TextureRectangle(image),
osg::StateAttribute::ON);
return pictureQuad;
}
else
{
osg::Geometry* pictureQuad = osg::createTexturedQuadGeometry(pos,
osg::Vec3(width,0.0f,0.0f),
osg::Vec3(0.0f,0.0f,height),
1.0f,1.0f);
pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
new osg::Texture2D(image),
osg::StateAttribute::ON);
return pictureQuad;
}
}
int main(int argc, char** argv)
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// register the handler to add keyboard and mosue handling.
MovieEventHandler* meh = new MovieEventHandler();
viewer.getEventHandlerList().push_front(meh);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
osg::Geode* geode = new osg::Geode;
osg::Vec3 pos(0.0f,0.0f,0.0f);
for(int i=1;i<arguments.argc();++i)
{
if (arguments.isString(i))
{
osg::Image* image = osgDB::readImageFile(arguments[i]);
geode->addDrawable(createTexturedQuadGeometry(pos,image->s(),image->t(),image));
geode->getOrCreateStateSet()->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
pos.z() += image->t()*1.5f;
}
}
// pass the model to the MovieEventHandler so it can pick out ImageStream's to manipulate.
meh->set(geode);
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
if (arguments.argc()<=1)
{
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
}
// set up a post swap callback to flush deleted GL objects and compile new GL objects
for(unsigned int cameraNum=0;cameraNum<viewer.getNumberOfCameras();++cameraNum)
{
Producer::Camera* camera=viewer.getCamera(cameraNum);
camera->addPostSwapCallback(new PostSwapFinishCallback());
}
// set the scene to render
viewer.setSceneData(geode);
// create the windows and run the threads.
viewer.realize();
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
}
<|endoftext|> |
<commit_before>/*
* SDL Hello World example for Gui-chan
*/
// Include all necessary headers.
#include <iostream>
#include <guichan.hpp>
#include <guichan/sdl.hpp>
#include <SDL/SDL.h>
/*
* Common stuff we need
*/
bool running = true;
/*
*SDL Stuff we need
*/
SDL_Surface* screen;
SDL_Event event;
/*
* Gui-chan SDL stuff we need
*/
gcn::SDLInput* input; // Input driver
gcn::SDLGraphics* graphics; // Graphics driver
/*
* Gui-chan stuff we need
*/
gcn::ImageLoader* imageLoader; // For loading images
gcn::Gui* gui; // A Gui object
gcn::Container* top; // A top container
gcn::ImageFont* font; // A font
gcn::Label* label; // And a label for the Hello World text
/**
* Initializes the Hello World
*/
void init()
{
/*
* Here we initialize SDL as we would do with any SDL application.
*/
SDL_Init(SDL_INIT_VIDEO);
screen = SDL_SetVideoMode(640, 480, 32, SDL_HWSURFACE);
// We want unicode
SDL_EnableUNICODE(1);
// We want to enable key repeat
SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
/*
* Now it's time for Gui-chan SDL stuff
*/
gcn::ImageLoader* imageLoader = new gcn::SDLImageLoader();
// The ImageLoader in use is static and must be set to be
// able to load images
gcn::Image::setImageLoader(imageLoader);
graphics = new gcn::SDLGraphics();
// Set the target for the graphics object to be the screen.
// In other words, we will draw to the screen.
// Note, any surface will do, it doesn't have to be the screen.
graphics->setTarget(screen);
input = new gcn::SDLInput();
/*
* Last but not least it's time to initialize and create the gui
* with Gui-chan stuff.
*/
top = new gcn::Container();
// Set the dimension of the top container to match the screen.
top->setDimension(gcn::Rectangle(0, 0, 640, 480));
gui = new gcn::Gui();
// Set gui to use the SDLGraphics object.
gui->setGraphics(graphics);
// Set gui to use the SDLInput object
gui->setInput(input);
// Set the top container
gui->setTop(top);
// Load the image font.
font = new gcn::ImageFont("fixedfont.bmp", " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
// The global font is static and must be set.
gcn::Widget::setGlobalFont(font);
// Create a label with test hello world
label = new gcn::Label("Hello World");
// Set the labels position
label->setPosition(280, 220);
// Add the label to the top container
top->add(label);
}
/**
* Halts the application
*/
void halt()
{
/*
* Destroy Gui-chan stuff
*/
delete label;
delete font;
delete top;
delete gui;
/*
* Destroy Gui-chan SDL stuff
*/
delete input;
delete graphics;
delete imageLoader;
/*
* Destroy SDL stuff
*/
SDL_FreeSurface(screen);
SDL_Quit();
}
/**
* Checks input. On escape halt the application.
*/
void checkInput()
{
/*
* Poll SDL events
*/
while(SDL_PollEvent(&event))
{
if (event.type == SDL_KEYDOWN)
{
if (event.key.keysym.sym == SDLK_ESCAPE)
{
running = false;
}
if (event.key.keysym.sym == SDLK_f)
{
if (event.key.keysym.mod & KMOD_CTRL)
{
// Works with X11 only
SDL_WM_ToggleFullScreen(screen);
}
}
}
else if(event.type == SDL_QUIT)
{
running = false;
}
/*
* Now that we are done polling and using SDL events we pass
* the leftovers to the SDLInput object to later be handled by
* the Gui. (This example doesn't require us to do this 'cause a
* label doesn't use input. But will do it anyway to show how to
* set up an SDL application with Gui-chan.)
*/
input->pushInput(event);
}
}
/**
* Runs the application
*/
void run()
{
while(running)
{
// Poll input
checkInput();
// Let the gui perform it's logic (like handle input)
gui->logic();
// Draw the gui
gui->draw();
// Update the screen
SDL_Flip(screen);
}
}
int main(int argc, char **argv)
{
try
{
init();
run();
halt();
}
/*
* Catch all Gui-chan exceptions
*/
catch (gcn::Exception e)
{
std::cout << e.getMessage() << std::endl;
}
/*
* Catch all Std exceptions
*/
catch (std::exception e)
{
std::cout << "Std exception: " << e.what() << std::endl;
}
/*
* Catch all Unknown exceptions
*/
catch (...)
{
std::cout << "Unknown exception" << std::endl;
}
return 0;
}
<commit_msg>Added a comment finalman found more appropriate (he always always has to complain about something...)<commit_after>/*
* SDL Hello World example for Gui-chan
*/
// Include all necessary headers.
#include <iostream>
#include <guichan.hpp>
#include <guichan/sdl.hpp>
#include <SDL/SDL.h>
/*
* Common stuff we need
*/
bool running = true;
/*
*SDL Stuff we need
*/
SDL_Surface* screen;
SDL_Event event;
/*
* Gui-chan SDL stuff we need
*/
gcn::SDLInput* input; // Input driver
gcn::SDLGraphics* graphics; // Graphics driver
/*
* Gui-chan stuff we need
*/
gcn::ImageLoader* imageLoader; // For loading images
gcn::Gui* gui; // A Gui object - binds it all together
gcn::Container* top; // A top container
gcn::ImageFont* font; // A font
gcn::Label* label; // And a label for the Hello World text
/**
* Initializes the Hello World
*/
void init()
{
/*
* Here we initialize SDL as we would do with any SDL application.
*/
SDL_Init(SDL_INIT_VIDEO);
screen = SDL_SetVideoMode(640, 480, 32, SDL_HWSURFACE);
// We want unicode
SDL_EnableUNICODE(1);
// We want to enable key repeat
SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
/*
* Now it's time for Gui-chan SDL stuff
*/
gcn::ImageLoader* imageLoader = new gcn::SDLImageLoader();
// The ImageLoader in use is static and must be set to be
// able to load images
gcn::Image::setImageLoader(imageLoader);
graphics = new gcn::SDLGraphics();
// Set the target for the graphics object to be the screen.
// In other words, we will draw to the screen.
// Note, any surface will do, it doesn't have to be the screen.
graphics->setTarget(screen);
input = new gcn::SDLInput();
/*
* Last but not least it's time to initialize and create the gui
* with Gui-chan stuff.
*/
top = new gcn::Container();
// Set the dimension of the top container to match the screen.
top->setDimension(gcn::Rectangle(0, 0, 640, 480));
gui = new gcn::Gui();
// Set gui to use the SDLGraphics object.
gui->setGraphics(graphics);
// Set gui to use the SDLInput object
gui->setInput(input);
// Set the top container
gui->setTop(top);
// Load the image font.
font = new gcn::ImageFont("fixedfont.bmp", " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
// The global font is static and must be set.
gcn::Widget::setGlobalFont(font);
// Create a label with test hello world
label = new gcn::Label("Hello World");
// Set the labels position
label->setPosition(280, 220);
// Add the label to the top container
top->add(label);
}
/**
* Halts the application
*/
void halt()
{
/*
* Destroy Gui-chan stuff
*/
delete label;
delete font;
delete top;
delete gui;
/*
* Destroy Gui-chan SDL stuff
*/
delete input;
delete graphics;
delete imageLoader;
/*
* Destroy SDL stuff
*/
SDL_FreeSurface(screen);
SDL_Quit();
}
/**
* Checks input. On escape halt the application.
*/
void checkInput()
{
/*
* Poll SDL events
*/
while(SDL_PollEvent(&event))
{
if (event.type == SDL_KEYDOWN)
{
if (event.key.keysym.sym == SDLK_ESCAPE)
{
running = false;
}
if (event.key.keysym.sym == SDLK_f)
{
if (event.key.keysym.mod & KMOD_CTRL)
{
// Works with X11 only
SDL_WM_ToggleFullScreen(screen);
}
}
}
else if(event.type == SDL_QUIT)
{
running = false;
}
/*
* Now that we are done polling and using SDL events we pass
* the leftovers to the SDLInput object to later be handled by
* the Gui. (This example doesn't require us to do this 'cause a
* label doesn't use input. But will do it anyway to show how to
* set up an SDL application with Gui-chan.)
*/
input->pushInput(event);
}
}
/**
* Runs the application
*/
void run()
{
while(running)
{
// Poll input
checkInput();
// Let the gui perform it's logic (like handle input)
gui->logic();
// Draw the gui
gui->draw();
// Update the screen
SDL_Flip(screen);
}
}
int main(int argc, char **argv)
{
try
{
init();
run();
halt();
}
/*
* Catch all Gui-chan exceptions
*/
catch (gcn::Exception e)
{
std::cout << e.getMessage() << std::endl;
}
/*
* Catch all Std exceptions
*/
catch (std::exception e)
{
std::cout << "Std exception: " << e.what() << std::endl;
}
/*
* Catch all Unknown exceptions
*/
catch (...)
{
std::cout << "Unknown exception" << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>#include "catch.hpp"
#include "util.h"
#include <grammar_registry.h>
using namespace shl;
using namespace std;
class TestSource : public GrammarSource {
public:
TestSource();
virtual const std::string load_data(const std::string& grammar_name) const;
virtual const std::vector<std::string> list_grammars() const;
private:
string ruby;
string html;
};
TestSource::TestSource() {
ruby = load_string("fixture/ruby.json");
html = load_string("fixture/hello.json");
}
const std::string TestSource::load_data(const std::string& grammar_name) const {
if ( grammar_name == "text.html.basic" ) return html;
if ( grammar_name == "source.ruby" ) return ruby;
return "";
}
const std::vector<std::string> TestSource::list_grammars() const {
vector<string> list = {"text.html.basic", "source.ruby"};
return list;
}
TEST_CASE("GrammarRegistry Test") {
SECTION("can load all grammar presented by the GrammarSource") {
shared_ptr<GrammarSource> source(new TestSource());
GrammarRegistry registry(source);
REQUIRE( registry.contain_grammar("text.html.basic") );
REQUIRE( registry.contain_grammar("source.ruby") );
}
}
<commit_msg>fix a test bug<commit_after>#include "catch.hpp"
#include "util.h"
#include <grammar_registry.h>
using namespace shl;
using namespace std;
class TestSource : public GrammarSource {
public:
TestSource();
virtual const std::string load_data(const std::string& grammar_name) const;
virtual const std::vector<std::string> list_grammars() const;
private:
string ruby;
string html;
};
TestSource::TestSource() {
ruby = load_string("fixture/ruby.json");
html = load_string("fixture/html.json");
}
const std::string TestSource::load_data(const std::string& grammar_name) const {
if ( grammar_name == "text.html.basic" ) return html;
if ( grammar_name == "source.ruby" ) return ruby;
return "";
}
const std::vector<std::string> TestSource::list_grammars() const {
vector<string> list = {"text.html.basic", "source.ruby"};
return list;
}
TEST_CASE("GrammarRegistry Test") {
SECTION("can load all grammar presented by the GrammarSource") {
shared_ptr<GrammarSource> source(new TestSource());
GrammarRegistry registry(source);
REQUIRE( registry.contain_grammar("text.html.basic") );
REQUIRE( registry.contain_grammar("source.ruby") );
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <cmath>
#include "glow.h"
using namespace std;
void display(unsigned long t, unsigned int dt, glow *gl);
void idle(glow *gl);
void timeout(unsigned int id, glow *gl);
void resize(unsigned int wW, unsigned int wH, unsigned int rW, unsigned int rH, glow *gl);
void onMouseDown(unsigned short button, int x, int y, glow *gl);
void onMouseUp(unsigned short button, int x, int y, glow *gl);
void onMouseMove(int x, int y, glow *gl);
void onScrollWheel(int dx, int dy, int x, int y, glow *gl);
void onKeyDown(unsigned short key, int x, int y, glow *gl);
void onKeyUp(unsigned short key, int x, int y, glow *gl);
unsigned int fontTex[2];
int main (int argc, char **argv) {
if (strcmp(argv[0], "./text/text") != 0 && strcmp(argv[0], ".\\text\\text\\Debug\\text.exe") != 0) {
printf(" program designed to be run from \'examples\' directory.\n");
printf(" please cd to '<glow_dir>/examples' and run ./text/text\n");
exit(1);
}
glow *gl = new glow();
//gl->initialize(GLOW_OPENGL_CORE, 3, 2, GLOW_HIDPI_WINDOW);
gl->initialize(GLOW_OPENGL_LEGACY, 0, 0, GLOW_BASE_WINDOW);
gl->createWindow("TEST", GLOW_CENTER_HORIZONTAL, GLOW_CENTER_VERTICAL, 800, 640);
gl->mouseDownListener(onMouseDown);
gl->mouseUpListener(onMouseUp);
gl->mouseMoveListener(onMouseMove);
gl->scrollWheelListener(onScrollWheel);
gl->keyDownListener(onKeyDown);
gl->keyUpListener(onKeyUp);
gl->renderFunction(display);
gl->idleFunction(idle);
gl->resizeFunction(resize);
unsigned int t1 = gl->setTimeout(timeout, 5000);
unsigned int t2 = gl->setTimeout(timeout, 1000);
unsigned int t3 = gl->setTimeout(timeout, 2000);
gl->cancelTimeout(t2);
string version, shadingVersion;
gl->getGLVersions(&version, &shadingVersion);
printf("Using OpenGL: %s, GLSL: %s\n", version.c_str(), shadingVersion.c_str());
string test1 = "的 uni";
string test2 = "\xe7\x9a\x84 code \U00007684"; // \U unicode not working for Windows
printf("%s %s\n", test1.c_str(), test2.c_str());
GLOW_FontFace *face;
unsigned char *textPx1, *textPx2;
unsigned int textW1, textH1, textW2, textH2;
unsigned char col[] = {255, 126, 0};
//gl->createFontFace("./fonts/Arial.ttf", 96, &face);
//gl->createFontFace("./fonts/AGaramondPro.otf", 96, &face);
gl->createFontFace("./fonts/simsun.ttc", 96, &face);
gl->renderStringToTexture(face, test1, true, &textW1, &textH1, &textPx1);
gl->renderStringToTexture(face, test2, col, true, &textW2, &textH2, &textPx2);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glGenTextures(2, fontTex);
glBindTexture(GL_TEXTURE_2D, fontTex[0]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, textW1, textH1, 0, GL_ALPHA, GL_UNSIGNED_BYTE, textPx1);
glBindTexture(GL_TEXTURE_2D, fontTex[1]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, textW2, textH2, 0, GL_RGBA, GL_UNSIGNED_BYTE, textPx2);
glBindTexture(GL_TEXTURE_2D, 0);
printf("Text texture sizes: %dx%d, %dx%d\n", textW1, textH1, textW2, textH2);
gl->runLoop();
return 0;
}
void display(unsigned long t, unsigned int dt, glow *gl) {
//printf("render: t=%.3f, dt=%.3f\n", (float)t/1000.0, (float)dt/1000.0);
float c = (float)(abs((int)(t % 4000) - 2000)) / 2000.0f;
glClearColor(c, c, c, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBindTexture(GL_TEXTURE_2D, fontTex[0]);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f); glVertex2f(-1.00f, -0.19f);
glTexCoord2f(1.0f, 0.0f); glVertex2f(-0.25f, -0.19f);
glTexCoord2f(1.0f, 1.0f); glVertex2f(-0.25f, 0.19f);
glTexCoord2f(0.0f, 1.0f); glVertex2f(-1.00f, 0.19f);
glEnd();
glBindTexture(GL_TEXTURE_2D, fontTex[1]);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f); glVertex2f(-0.25f, -0.19f);
glTexCoord2f(1.0f, 0.0f); glVertex2f( 1.00f, -0.19f);
glTexCoord2f(1.0f, 1.0f); glVertex2f( 1.00f, 0.19f);
glTexCoord2f(0.0f, 1.0f); glVertex2f(-0.25f, 0.19f);
glEnd();
glBindTexture(GL_TEXTURE_2D, 0);
gl->swapBuffers();
}
void idle(glow *gl) {
gl->requestRenderFrame();
}
void timeout(unsigned int id, glow *gl) {
printf("timeout: %u\n", id);
gl->requestRenderFrame();
}
void resize(unsigned int wW, unsigned int wH, unsigned int rW, unsigned int rH, glow *gl) {
printf("window size: %ux%u (%ux%u)\n", wW, wH, rW, rH);
glViewport(0, 0, rW, rH);
gl->requestRenderFrame();
}
void onMouseDown(unsigned short button, int x, int y, glow *gl) {
switch (button) {
case GLOW_MOUSE_BUTTON_LEFT:
printf("mousedown: left (%d, %d)\n", x, y);
break;
case GLOW_MOUSE_BUTTON_RIGHT:
printf("mousedown: right (%d, %d)\n", x, y);
gl->setWindowTitle("TEXT: right click");
gl->setWindowGeometry(720, 450, 400, 300);
break;
}
}
void onMouseUp(unsigned short button, int x, int y, glow *gl) {
switch (button) {
case GLOW_MOUSE_BUTTON_LEFT:
printf("mouseup: left (%d, %d)\n", x, y);
break;
case GLOW_MOUSE_BUTTON_RIGHT:
printf("mouseup: right (%d, %d)\n", x, y);
break;
}
}
void onMouseMove(int x, int y, glow *gl) {
//printf("mousemove: (%d, %d)\n", x, y);
}
void onScrollWheel(int dx, int dy, int x, int y, glow *gl) {
printf("scroll wheel: %d %d (%d, %d)\n", dx, dy, x, y);
}
void onKeyDown(unsigned short key, int x, int y, glow *gl) {
printf("keydown: %u [%c] (%d, %d)\n", key, (unsigned char)key, x, y);
if (key == 'F') gl->enableFullscreen();
if (key == 27) gl->disableFullscreen();
}
void onKeyUp(unsigned short key, int x, int y, glow *gl) {
printf("keyup: %u [%c] (%d, %d)\n", key, (unsigned char)key, x, y);
}
<commit_msg>text example command line x,y<commit_after>#include <iostream>
#include <cmath>
#include "glow.h"
using namespace std;
void display(unsigned long t, unsigned int dt, glow *gl);
void idle(glow *gl);
void timeout(unsigned int id, glow *gl);
void resize(unsigned int wW, unsigned int wH, unsigned int rW, unsigned int rH, glow *gl);
void onMouseDown(unsigned short button, int x, int y, glow *gl);
void onMouseUp(unsigned short button, int x, int y, glow *gl);
void onMouseMove(int x, int y, glow *gl);
void onScrollWheel(int dx, int dy, int x, int y, glow *gl);
void onKeyDown(unsigned short key, int x, int y, glow *gl);
void onKeyUp(unsigned short key, int x, int y, glow *gl);
unsigned int fontTex[2];
int main (int argc, char **argv) {
if (strcmp(argv[0], "./text/text") != 0 && strcmp(argv[0], ".\\text\\text\\Debug\\text.exe") != 0) {
printf(" program designed to be run from \'examples\' directory.\n");
printf(" please cd to '<glow_dir>/examples' and run ./text/text\n");
exit(1);
}
glow *gl = new glow();
int winX = GLOW_CENTER_HORIZONTAL;
int winY = GLOW_CENTER_VERTICAL;
if (argc >= 2)
winX = atoi(argv[1]);
if (argc >= 3)
winY = atoi(argv[2]);
//gl->initialize(GLOW_OPENGL_CORE, 3, 2, GLOW_HIDPI_WINDOW);
gl->initialize(GLOW_OPENGL_LEGACY, 0, 0, GLOW_BASE_WINDOW);
gl->createWindow("TEST", winX, winY, 800, 640);
gl->mouseDownListener(onMouseDown);
gl->mouseUpListener(onMouseUp);
gl->mouseMoveListener(onMouseMove);
gl->scrollWheelListener(onScrollWheel);
gl->keyDownListener(onKeyDown);
gl->keyUpListener(onKeyUp);
gl->renderFunction(display);
gl->idleFunction(idle);
gl->resizeFunction(resize);
unsigned int t1 = gl->setTimeout(timeout, 5000);
unsigned int t2 = gl->setTimeout(timeout, 1000);
unsigned int t3 = gl->setTimeout(timeout, 2000);
gl->cancelTimeout(t2);
string version, shadingVersion;
gl->getGLVersions(&version, &shadingVersion);
printf("Using OpenGL: %s, GLSL: %s\n", version.c_str(), shadingVersion.c_str());
string test1 = "的 uni";
string test2 = "\xe7\x9a\x84 code \U00007684"; // \U unicode not working for Windows
printf("%s %s\n", test1.c_str(), test2.c_str());
GLOW_FontFace *face;
unsigned char *textPx1, *textPx2;
unsigned int textW1, textH1, textW2, textH2;
unsigned char col[] = {255, 126, 0};
//gl->createFontFace("./fonts/Arial.ttf", 96, &face);
//gl->createFontFace("./fonts/AGaramondPro.otf", 96, &face);
gl->createFontFace("./fonts/simsun.ttc", 96, &face);
gl->renderStringToTexture(face, test1, true, &textW1, &textH1, &textPx1);
gl->renderStringToTexture(face, test2, col, true, &textW2, &textH2, &textPx2);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glGenTextures(2, fontTex);
glBindTexture(GL_TEXTURE_2D, fontTex[0]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, textW1, textH1, 0, GL_ALPHA, GL_UNSIGNED_BYTE, textPx1);
glBindTexture(GL_TEXTURE_2D, fontTex[1]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, textW2, textH2, 0, GL_RGBA, GL_UNSIGNED_BYTE, textPx2);
glBindTexture(GL_TEXTURE_2D, 0);
printf("Text texture sizes: %dx%d, %dx%d\n", textW1, textH1, textW2, textH2);
gl->runLoop();
return 0;
}
void display(unsigned long t, unsigned int dt, glow *gl) {
//printf("render: t=%.3f, dt=%.3f\n", (float)t/1000.0, (float)dt/1000.0);
float c = (float)(abs((int)(t % 4000) - 2000)) / 2000.0f;
glClearColor(c, c, c, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBindTexture(GL_TEXTURE_2D, fontTex[0]);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f); glVertex2f(-1.00f, -0.19f);
glTexCoord2f(1.0f, 0.0f); glVertex2f(-0.25f, -0.19f);
glTexCoord2f(1.0f, 1.0f); glVertex2f(-0.25f, 0.19f);
glTexCoord2f(0.0f, 1.0f); glVertex2f(-1.00f, 0.19f);
glEnd();
glBindTexture(GL_TEXTURE_2D, fontTex[1]);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f); glVertex2f(-0.25f, -0.19f);
glTexCoord2f(1.0f, 0.0f); glVertex2f( 1.00f, -0.19f);
glTexCoord2f(1.0f, 1.0f); glVertex2f( 1.00f, 0.19f);
glTexCoord2f(0.0f, 1.0f); glVertex2f(-0.25f, 0.19f);
glEnd();
glBindTexture(GL_TEXTURE_2D, 0);
gl->swapBuffers();
}
void idle(glow *gl) {
gl->requestRenderFrame();
}
void timeout(unsigned int id, glow *gl) {
printf("timeout: %u\n", id);
gl->requestRenderFrame();
}
void resize(unsigned int wW, unsigned int wH, unsigned int rW, unsigned int rH, glow *gl) {
printf("window size: %ux%u (%ux%u)\n", wW, wH, rW, rH);
glViewport(0, 0, rW, rH);
gl->requestRenderFrame();
}
void onMouseDown(unsigned short button, int x, int y, glow *gl) {
switch (button) {
case GLOW_MOUSE_BUTTON_LEFT:
printf("mousedown: left (%d, %d)\n", x, y);
break;
case GLOW_MOUSE_BUTTON_RIGHT:
printf("mousedown: right (%d, %d)\n", x, y);
gl->setWindowTitle("TEXT: right click");
gl->setWindowGeometry(720, 450, 400, 300);
break;
}
}
void onMouseUp(unsigned short button, int x, int y, glow *gl) {
switch (button) {
case GLOW_MOUSE_BUTTON_LEFT:
printf("mouseup: left (%d, %d)\n", x, y);
break;
case GLOW_MOUSE_BUTTON_RIGHT:
printf("mouseup: right (%d, %d)\n", x, y);
break;
}
}
void onMouseMove(int x, int y, glow *gl) {
//printf("mousemove: (%d, %d)\n", x, y);
}
void onScrollWheel(int dx, int dy, int x, int y, glow *gl) {
printf("scroll wheel: %d %d (%d, %d)\n", dx, dy, x, y);
}
void onKeyDown(unsigned short key, int x, int y, glow *gl) {
printf("keydown: %u [%c] (%d, %d)\n", key, (unsigned char)key, x, y);
if (key == 'F') gl->enableFullscreen();
if (key == 27) gl->disableFullscreen();
}
void onKeyUp(unsigned short key, int x, int y, glow *gl) {
printf("keyup: %u [%c] (%d, %d)\n", key, (unsigned char)key, x, y);
}
<|endoftext|> |
<commit_before>#include "board.h"
#include <aery32/all.h>
using namespace aery;
#define TWI_MASK ((1 << 29) | (1 << 30))
int main(void)
{
bool twi_slave_found = false;
uint8_t twi_slave_address = 0;
uint8_t read_data = 0;
init_board(); /* Setup LED pin and CPU clock to 66 MHz */
gpio_init_pins(porta, TWI_MASK, GPIO_FUNCTION_A);
twi_init_master();
/* All done, turn the LED on */
gpio_set_pin_high(LED);
/* Scan for the first device on the twi-bus */
for (; twi_slave_address <= 0x7f; twi_slave_address++) {
twi_select_slave(twi_slave_address);
if (twi_write_byte(0x00) == 0)
break;
}
if (twi_slave_found) {
/* You may omit the register if not needed */
twi_write_byte(
0x90 /* data */,
0x80 /* register */
);
read_data = twi_read_byte(0x80 /* register */);
}
for(;;) {
/* Put your application code here */
}
return 0;
}
<commit_msg>Fix twi example<commit_after>#include "board.h"
#include <aery32/all.h>
using namespace aery;
#define TWI_MASK ((1 << 29) | (1 << 30))
int main(void)
{
bool twi_slave_found = false;
uint8_t twi_slave_address = 0;
uint8_t read_data = 0;
init_board(); /* Setup LED pin and CPU clock to 66 MHz */
gpio_init_pins(porta, TWI_MASK, GPIO_FUNCTION_A);
twi_init_master();
/* All done, turn the LED on */
gpio_set_pin_high(LED);
/* Scan for the first device on the twi-bus */
for (; twi_slave_address <= 0x7f; twi_slave_address++) {
twi_select_slave(twi_slave_address);
if (twi_write_byte(0x00) == 0) {
twi_slave_found = true;
break;
}
}
if (twi_slave_found) {
/* You may omit the register if not needed */
twi_write_byte(
0x90 /* data */,
0x80 /* register */
);
read_data = twi_read_byte(0x80 /* register */);
}
for(;;) {
/* Put your application code here */
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/base/tcp_client_socket.h"
#include "base/memory_debug.h"
#include "base/string_util.h"
#include "base/sys_info.h"
#include "base/trace_event.h"
#include "net/base/net_errors.h"
#include "net/base/winsock_init.h"
namespace net {
//-----------------------------------------------------------------------------
static int MapWinsockError(DWORD err) {
// There are numerous Winsock error codes, but these are the ones we thus far
// find interesting.
switch (err) {
case WSAENETDOWN:
return ERR_INTERNET_DISCONNECTED;
case WSAETIMEDOUT:
return ERR_TIMED_OUT;
case WSAECONNRESET:
case WSAENETRESET: // Related to keep-alive
return ERR_CONNECTION_RESET;
case WSAECONNABORTED:
return ERR_CONNECTION_ABORTED;
case WSAECONNREFUSED:
return ERR_CONNECTION_REFUSED;
case WSAEDISCON:
// Returned by WSARecv or WSARecvFrom for message-oriented sockets (where
// a return value of zero means a zero-byte message) to indicate graceful
// connection shutdown. We should not ever see this error code for TCP
// sockets, which are byte stream oriented.
NOTREACHED();
return ERR_CONNECTION_CLOSED;
case WSAEHOSTUNREACH:
case WSAENETUNREACH:
return ERR_ADDRESS_UNREACHABLE;
case WSAEADDRNOTAVAIL:
return ERR_ADDRESS_INVALID;
case WSA_IO_INCOMPLETE:
return ERR_UNEXPECTED;
case ERROR_SUCCESS:
return OK;
default:
LOG(WARNING) << "Unknown error " << err << " mapped to net::ERR_FAILED";
return ERR_FAILED;
}
}
//-----------------------------------------------------------------------------
TCPClientSocket::TCPClientSocket(const AddressList& addresses)
: socket_(INVALID_SOCKET),
addresses_(addresses),
current_ai_(addresses_.head()),
wait_state_(NOT_WAITING),
callback_(NULL) {
memset(&overlapped_, 0, sizeof(overlapped_));
EnsureWinsockInit();
}
TCPClientSocket::~TCPClientSocket() {
Disconnect();
}
int TCPClientSocket::Connect(CompletionCallback* callback) {
// If already connected, then just return OK.
if (socket_ != INVALID_SOCKET)
return OK;
TRACE_EVENT_BEGIN("socket.connect", this, "");
const struct addrinfo* ai = current_ai_;
DCHECK(ai);
int rv = CreateSocket(ai);
if (rv != OK)
return rv;
// WSACreateEvent creates a manual-reset event object.
overlapped_.hEvent = WSACreateEvent();
// WSAEventSelect sets the socket to non-blocking mode as a side effect.
// Our connect() and recv() calls require that the socket be non-blocking.
WSAEventSelect(socket_, overlapped_.hEvent, FD_CONNECT);
if (!connect(socket_, ai->ai_addr, static_cast<int>(ai->ai_addrlen))) {
// Connected without waiting!
WaitForAndResetEvent();
TRACE_EVENT_END("socket.connect", this, "");
return OK;
}
DWORD err = WSAGetLastError();
if (err != WSAEWOULDBLOCK) {
LOG(ERROR) << "connect failed: " << err;
return MapWinsockError(err);
}
watcher_.StartWatching(overlapped_.hEvent, this);
wait_state_ = WAITING_CONNECT;
callback_ = callback;
return ERR_IO_PENDING;
}
int TCPClientSocket::ReconnectIgnoringLastError(CompletionCallback* callback) {
// No ignorable errors!
return ERR_UNEXPECTED;
}
void TCPClientSocket::Disconnect() {
if (socket_ == INVALID_SOCKET)
return;
TRACE_EVENT_INSTANT("socket.disconnect", this, "");
// Make sure the message loop is not watching this object anymore.
watcher_.StopWatching();
// Cancel any pending IO and wait for it to be aborted.
if (wait_state_ == WAITING_READ || wait_state_ == WAITING_WRITE) {
CancelIo(reinterpret_cast<HANDLE>(socket_));
WaitForSingleObject(overlapped_.hEvent, INFINITE);
wait_state_ = NOT_WAITING;
}
// In most socket implementations, closing a socket results in a graceful
// connection shutdown, but in Winsock we have to call shutdown explicitly.
// See the MSDN page "Graceful Shutdown, Linger Options, and Socket Closure"
// at http://msdn.microsoft.com/en-us/library/ms738547.aspx
shutdown(socket_, SD_SEND);
closesocket(socket_);
socket_ = INVALID_SOCKET;
WSACloseEvent(overlapped_.hEvent);
memset(&overlapped_, 0, sizeof(overlapped_));
// Reset for next time.
current_ai_ = addresses_.head();
}
bool TCPClientSocket::IsConnected() const {
if (socket_ == INVALID_SOCKET || wait_state_ == WAITING_CONNECT)
return false;
// Check if connection is alive.
char c;
int rv = recv(socket_, &c, 1, MSG_PEEK);
if (rv == 0)
return false;
if (rv == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK)
return false;
return true;
}
bool TCPClientSocket::IsConnectedAndIdle() const {
if (socket_ == INVALID_SOCKET || wait_state_ == WAITING_CONNECT)
return false;
// Check if connection is alive and we haven't received any data
// unexpectedly.
char c;
int rv = recv(socket_, &c, 1, MSG_PEEK);
if (rv >= 0)
return false;
if (WSAGetLastError() != WSAEWOULDBLOCK)
return false;
return true;
}
int TCPClientSocket::Read(char* buf,
int buf_len,
CompletionCallback* callback) {
DCHECK(socket_ != INVALID_SOCKET);
DCHECK(wait_state_ == NOT_WAITING);
DCHECK(!callback_);
buffer_.len = buf_len;
buffer_.buf = buf;
TRACE_EVENT_BEGIN("socket.read", this, "");
// TODO(wtc): Remove the CHECK after enough testing.
CHECK(WaitForSingleObject(overlapped_.hEvent, 0) == WAIT_TIMEOUT);
DWORD num, flags = 0;
int rv = WSARecv(socket_, &buffer_, 1, &num, &flags, &overlapped_, NULL);
if (rv == 0) {
WaitForAndResetEvent();
TRACE_EVENT_END("socket.read", this, StringPrintf("%d bytes", num));
// Because of how WSARecv fills memory when used asynchronously, Purify
// isn't able to detect that it's been initialized, so it scans for 0xcd
// in the buffer and reports UMRs (uninitialized memory reads) for those
// individual bytes. We override that in PURIFY builds to avoid the false
// error reports.
// See bug 5297.
base::MemoryDebug::MarkAsInitialized(buffer_.buf, num);
return static_cast<int>(num);
}
int err = WSAGetLastError();
if (err == WSA_IO_PENDING) {
watcher_.StartWatching(overlapped_.hEvent, this);
wait_state_ = WAITING_READ;
callback_ = callback;
return ERR_IO_PENDING;
}
return MapWinsockError(err);
}
int TCPClientSocket::Write(const char* buf,
int buf_len,
CompletionCallback* callback) {
DCHECK(socket_ != INVALID_SOCKET);
DCHECK(wait_state_ == NOT_WAITING);
DCHECK(!callback_);
buffer_.len = buf_len;
buffer_.buf = const_cast<char*>(buf);
TRACE_EVENT_BEGIN("socket.write", this, "");
// TODO(wtc): Remove the CHECK after enough testing.
CHECK(WaitForSingleObject(overlapped_.hEvent, 0) == WAIT_TIMEOUT);
DWORD num;
int rv = WSASend(socket_, &buffer_, 1, &num, 0, &overlapped_, NULL);
if (rv == 0) {
WaitForAndResetEvent();
TRACE_EVENT_END("socket.write", this, StringPrintf("%d bytes", num));
return static_cast<int>(num);
}
int err = WSAGetLastError();
if (err == WSA_IO_PENDING) {
watcher_.StartWatching(overlapped_.hEvent, this);
wait_state_ = WAITING_WRITE;
callback_ = callback;
return ERR_IO_PENDING;
}
return MapWinsockError(err);
}
int TCPClientSocket::CreateSocket(const struct addrinfo* ai) {
socket_ = WSASocket(ai->ai_family, ai->ai_socktype, ai->ai_protocol, NULL, 0,
WSA_FLAG_OVERLAPPED);
if (socket_ == INVALID_SOCKET) {
DWORD err = WSAGetLastError();
LOG(ERROR) << "WSASocket failed: " << err;
return MapWinsockError(err);
}
// Increase the socket buffer sizes from the default sizes for WinXP. In
// performance testing, there is substantial benefit by increasing from 8KB
// to 64KB.
// See also:
// http://support.microsoft.com/kb/823764/EN-US
// On Vista, if we manually set these sizes, Vista turns off its receive
// window auto-tuning feature.
// http://blogs.msdn.com/wndp/archive/2006/05/05/Winhec-blog-tcpip-2.aspx
// Since Vista's auto-tune is better than any static value we can could set,
// only change these on pre-vista machines.
int32 major_version, minor_version, fix_version;
base::SysInfo::OperatingSystemVersionNumbers(&major_version, &minor_version,
&fix_version);
if (major_version < 6) {
const int kSocketBufferSize = 64 * 1024;
int rv = setsockopt(socket_, SOL_SOCKET, SO_SNDBUF,
reinterpret_cast<const char*>(&kSocketBufferSize),
sizeof(kSocketBufferSize));
DCHECK(!rv) << "Could not set socket send buffer size";
rv = setsockopt(socket_, SOL_SOCKET, SO_RCVBUF,
reinterpret_cast<const char*>(&kSocketBufferSize),
sizeof(kSocketBufferSize));
DCHECK(!rv) << "Could not set socket receive buffer size";
}
// Disable Nagle.
// The Nagle implementation on windows is governed by RFC 896. The idea
// behind Nagle is to reduce small packets on the network. When Nagle is
// enabled, if a partial packet has been sent, the TCP stack will disallow
// further *partial* packets until an ACK has been received from the other
// side. Good applications should always strive to send as much data as
// possible and avoid partial-packet sends. However, in most real world
// applications, there are edge cases where this does not happen, and two
// partil packets may be sent back to back. For a browser, it is NEVER
// a benefit to delay for an RTT before the second packet is sent.
//
// As a practical example in Chromium today, consider the case of a small
// POST. I have verified this:
// Client writes 649 bytes of header (partial packet #1)
// Client writes 50 bytes of POST data (partial packet #2)
// In the above example, with Nagle, a RTT delay is inserted between these
// two sends due to nagle. RTTs can easily be 100ms or more. The best
// fix is to make sure that for POSTing data, we write as much data as
// possible and minimize partial packets. We will fix that. But disabling
// Nagle also ensure we don't run into this delay in other edge cases.
// See also:
// http://technet.microsoft.com/en-us/library/bb726981.aspx
const BOOL kDisableNagle = TRUE;
int rv = setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY,
reinterpret_cast<const char*>(&kDisableNagle), sizeof(kDisableNagle));
DCHECK(!rv) << "Could not disable nagle";
return OK;
}
void TCPClientSocket::DoCallback(int rv) {
DCHECK(rv != ERR_IO_PENDING);
DCHECK(callback_);
// since Run may result in Read being called, clear callback_ up front.
CompletionCallback* c = callback_;
callback_ = NULL;
c->Run(rv);
}
void TCPClientSocket::DidCompleteConnect() {
int result;
TRACE_EVENT_END("socket.connect", this, "");
wait_state_ = NOT_WAITING;
WSANETWORKEVENTS events;
int rv = WSAEnumNetworkEvents(socket_, overlapped_.hEvent, &events);
if (rv == SOCKET_ERROR) {
NOTREACHED();
result = MapWinsockError(WSAGetLastError());
} else if (events.lNetworkEvents & FD_CONNECT) {
wait_state_ = NOT_WAITING;
DWORD error_code = static_cast<DWORD>(events.iErrorCode[FD_CONNECT_BIT]);
if (current_ai_->ai_next && (
error_code == WSAEADDRNOTAVAIL ||
error_code == WSAEAFNOSUPPORT ||
error_code == WSAECONNREFUSED ||
error_code == WSAENETUNREACH ||
error_code == WSAEHOSTUNREACH ||
error_code == WSAETIMEDOUT)) {
// Try using the next address.
const struct addrinfo* next = current_ai_->ai_next;
Disconnect();
current_ai_ = next;
result = Connect(callback_);
} else {
result = MapWinsockError(error_code);
}
} else {
NOTREACHED();
result = ERR_UNEXPECTED;
}
if (result != ERR_IO_PENDING)
DoCallback(result);
}
void TCPClientSocket::DidCompleteIO() {
DWORD num_bytes, flags;
BOOL ok = WSAGetOverlappedResult(
socket_, &overlapped_, &num_bytes, FALSE, &flags);
WSAResetEvent(overlapped_.hEvent);
if (wait_state_ == WAITING_READ) {
TRACE_EVENT_END("socket.read", this, StringPrintf("%d bytes", num_bytes));
} else {
TRACE_EVENT_END("socket.write", this, StringPrintf("%d bytes", num_bytes));
}
wait_state_ = NOT_WAITING;
DoCallback(ok ? num_bytes : MapWinsockError(WSAGetLastError()));
}
void TCPClientSocket::OnObjectSignaled(HANDLE object) {
DCHECK(object == overlapped_.hEvent);
switch (wait_state_) {
case WAITING_CONNECT:
DidCompleteConnect();
break;
case WAITING_READ:
case WAITING_WRITE:
DidCompleteIO();
break;
default:
NOTREACHED();
break;
}
}
void TCPClientSocket::WaitForAndResetEvent() {
// TODO(wtc): Remove the CHECKs after enough testing.
DWORD wait_rv = WaitForSingleObject(overlapped_.hEvent, INFINITE);
CHECK(wait_rv == WAIT_OBJECT_0);
BOOL ok = WSAResetEvent(overlapped_.hEvent);
CHECK(ok);
}
} // namespace net
<commit_msg>Ensures that writes are at least one byte, matching the libevent version. As discussed in http://codereview.chromium.org/55014 .<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/base/tcp_client_socket.h"
#include "base/memory_debug.h"
#include "base/string_util.h"
#include "base/sys_info.h"
#include "base/trace_event.h"
#include "net/base/net_errors.h"
#include "net/base/winsock_init.h"
namespace net {
//-----------------------------------------------------------------------------
static int MapWinsockError(DWORD err) {
// There are numerous Winsock error codes, but these are the ones we thus far
// find interesting.
switch (err) {
case WSAENETDOWN:
return ERR_INTERNET_DISCONNECTED;
case WSAETIMEDOUT:
return ERR_TIMED_OUT;
case WSAECONNRESET:
case WSAENETRESET: // Related to keep-alive
return ERR_CONNECTION_RESET;
case WSAECONNABORTED:
return ERR_CONNECTION_ABORTED;
case WSAECONNREFUSED:
return ERR_CONNECTION_REFUSED;
case WSAEDISCON:
// Returned by WSARecv or WSARecvFrom for message-oriented sockets (where
// a return value of zero means a zero-byte message) to indicate graceful
// connection shutdown. We should not ever see this error code for TCP
// sockets, which are byte stream oriented.
NOTREACHED();
return ERR_CONNECTION_CLOSED;
case WSAEHOSTUNREACH:
case WSAENETUNREACH:
return ERR_ADDRESS_UNREACHABLE;
case WSAEADDRNOTAVAIL:
return ERR_ADDRESS_INVALID;
case WSA_IO_INCOMPLETE:
return ERR_UNEXPECTED;
case ERROR_SUCCESS:
return OK;
default:
LOG(WARNING) << "Unknown error " << err << " mapped to net::ERR_FAILED";
return ERR_FAILED;
}
}
//-----------------------------------------------------------------------------
TCPClientSocket::TCPClientSocket(const AddressList& addresses)
: socket_(INVALID_SOCKET),
addresses_(addresses),
current_ai_(addresses_.head()),
wait_state_(NOT_WAITING),
callback_(NULL) {
memset(&overlapped_, 0, sizeof(overlapped_));
EnsureWinsockInit();
}
TCPClientSocket::~TCPClientSocket() {
Disconnect();
}
int TCPClientSocket::Connect(CompletionCallback* callback) {
// If already connected, then just return OK.
if (socket_ != INVALID_SOCKET)
return OK;
TRACE_EVENT_BEGIN("socket.connect", this, "");
const struct addrinfo* ai = current_ai_;
DCHECK(ai);
int rv = CreateSocket(ai);
if (rv != OK)
return rv;
// WSACreateEvent creates a manual-reset event object.
overlapped_.hEvent = WSACreateEvent();
// WSAEventSelect sets the socket to non-blocking mode as a side effect.
// Our connect() and recv() calls require that the socket be non-blocking.
WSAEventSelect(socket_, overlapped_.hEvent, FD_CONNECT);
if (!connect(socket_, ai->ai_addr, static_cast<int>(ai->ai_addrlen))) {
// Connected without waiting!
WaitForAndResetEvent();
TRACE_EVENT_END("socket.connect", this, "");
return OK;
}
DWORD err = WSAGetLastError();
if (err != WSAEWOULDBLOCK) {
LOG(ERROR) << "connect failed: " << err;
return MapWinsockError(err);
}
watcher_.StartWatching(overlapped_.hEvent, this);
wait_state_ = WAITING_CONNECT;
callback_ = callback;
return ERR_IO_PENDING;
}
int TCPClientSocket::ReconnectIgnoringLastError(CompletionCallback* callback) {
// No ignorable errors!
return ERR_UNEXPECTED;
}
void TCPClientSocket::Disconnect() {
if (socket_ == INVALID_SOCKET)
return;
TRACE_EVENT_INSTANT("socket.disconnect", this, "");
// Make sure the message loop is not watching this object anymore.
watcher_.StopWatching();
// Cancel any pending IO and wait for it to be aborted.
if (wait_state_ == WAITING_READ || wait_state_ == WAITING_WRITE) {
CancelIo(reinterpret_cast<HANDLE>(socket_));
WaitForSingleObject(overlapped_.hEvent, INFINITE);
wait_state_ = NOT_WAITING;
}
// In most socket implementations, closing a socket results in a graceful
// connection shutdown, but in Winsock we have to call shutdown explicitly.
// See the MSDN page "Graceful Shutdown, Linger Options, and Socket Closure"
// at http://msdn.microsoft.com/en-us/library/ms738547.aspx
shutdown(socket_, SD_SEND);
closesocket(socket_);
socket_ = INVALID_SOCKET;
WSACloseEvent(overlapped_.hEvent);
memset(&overlapped_, 0, sizeof(overlapped_));
// Reset for next time.
current_ai_ = addresses_.head();
}
bool TCPClientSocket::IsConnected() const {
if (socket_ == INVALID_SOCKET || wait_state_ == WAITING_CONNECT)
return false;
// Check if connection is alive.
char c;
int rv = recv(socket_, &c, 1, MSG_PEEK);
if (rv == 0)
return false;
if (rv == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK)
return false;
return true;
}
bool TCPClientSocket::IsConnectedAndIdle() const {
if (socket_ == INVALID_SOCKET || wait_state_ == WAITING_CONNECT)
return false;
// Check if connection is alive and we haven't received any data
// unexpectedly.
char c;
int rv = recv(socket_, &c, 1, MSG_PEEK);
if (rv >= 0)
return false;
if (WSAGetLastError() != WSAEWOULDBLOCK)
return false;
return true;
}
int TCPClientSocket::Read(char* buf,
int buf_len,
CompletionCallback* callback) {
DCHECK(socket_ != INVALID_SOCKET);
DCHECK(wait_state_ == NOT_WAITING);
DCHECK(!callback_);
buffer_.len = buf_len;
buffer_.buf = buf;
TRACE_EVENT_BEGIN("socket.read", this, "");
// TODO(wtc): Remove the CHECK after enough testing.
CHECK(WaitForSingleObject(overlapped_.hEvent, 0) == WAIT_TIMEOUT);
DWORD num, flags = 0;
int rv = WSARecv(socket_, &buffer_, 1, &num, &flags, &overlapped_, NULL);
if (rv == 0) {
WaitForAndResetEvent();
TRACE_EVENT_END("socket.read", this, StringPrintf("%d bytes", num));
// Because of how WSARecv fills memory when used asynchronously, Purify
// isn't able to detect that it's been initialized, so it scans for 0xcd
// in the buffer and reports UMRs (uninitialized memory reads) for those
// individual bytes. We override that in PURIFY builds to avoid the false
// error reports.
// See bug 5297.
base::MemoryDebug::MarkAsInitialized(buffer_.buf, num);
return static_cast<int>(num);
}
int err = WSAGetLastError();
if (err == WSA_IO_PENDING) {
watcher_.StartWatching(overlapped_.hEvent, this);
wait_state_ = WAITING_READ;
callback_ = callback;
return ERR_IO_PENDING;
}
return MapWinsockError(err);
}
int TCPClientSocket::Write(const char* buf,
int buf_len,
CompletionCallback* callback) {
DCHECK(socket_ != INVALID_SOCKET);
DCHECK(wait_state_ == NOT_WAITING);
DCHECK(!callback_);
DCHECK(buf_len > 0);
buffer_.len = buf_len;
buffer_.buf = const_cast<char*>(buf);
TRACE_EVENT_BEGIN("socket.write", this, "");
// TODO(wtc): Remove the CHECK after enough testing.
CHECK(WaitForSingleObject(overlapped_.hEvent, 0) == WAIT_TIMEOUT);
DWORD num;
int rv = WSASend(socket_, &buffer_, 1, &num, 0, &overlapped_, NULL);
if (rv == 0) {
WaitForAndResetEvent();
TRACE_EVENT_END("socket.write", this, StringPrintf("%d bytes", num));
return static_cast<int>(num);
}
int err = WSAGetLastError();
if (err == WSA_IO_PENDING) {
watcher_.StartWatching(overlapped_.hEvent, this);
wait_state_ = WAITING_WRITE;
callback_ = callback;
return ERR_IO_PENDING;
}
return MapWinsockError(err);
}
int TCPClientSocket::CreateSocket(const struct addrinfo* ai) {
socket_ = WSASocket(ai->ai_family, ai->ai_socktype, ai->ai_protocol, NULL, 0,
WSA_FLAG_OVERLAPPED);
if (socket_ == INVALID_SOCKET) {
DWORD err = WSAGetLastError();
LOG(ERROR) << "WSASocket failed: " << err;
return MapWinsockError(err);
}
// Increase the socket buffer sizes from the default sizes for WinXP. In
// performance testing, there is substantial benefit by increasing from 8KB
// to 64KB.
// See also:
// http://support.microsoft.com/kb/823764/EN-US
// On Vista, if we manually set these sizes, Vista turns off its receive
// window auto-tuning feature.
// http://blogs.msdn.com/wndp/archive/2006/05/05/Winhec-blog-tcpip-2.aspx
// Since Vista's auto-tune is better than any static value we can could set,
// only change these on pre-vista machines.
int32 major_version, minor_version, fix_version;
base::SysInfo::OperatingSystemVersionNumbers(&major_version, &minor_version,
&fix_version);
if (major_version < 6) {
const int kSocketBufferSize = 64 * 1024;
int rv = setsockopt(socket_, SOL_SOCKET, SO_SNDBUF,
reinterpret_cast<const char*>(&kSocketBufferSize),
sizeof(kSocketBufferSize));
DCHECK(!rv) << "Could not set socket send buffer size";
rv = setsockopt(socket_, SOL_SOCKET, SO_RCVBUF,
reinterpret_cast<const char*>(&kSocketBufferSize),
sizeof(kSocketBufferSize));
DCHECK(!rv) << "Could not set socket receive buffer size";
}
// Disable Nagle.
// The Nagle implementation on windows is governed by RFC 896. The idea
// behind Nagle is to reduce small packets on the network. When Nagle is
// enabled, if a partial packet has been sent, the TCP stack will disallow
// further *partial* packets until an ACK has been received from the other
// side. Good applications should always strive to send as much data as
// possible and avoid partial-packet sends. However, in most real world
// applications, there are edge cases where this does not happen, and two
// partil packets may be sent back to back. For a browser, it is NEVER
// a benefit to delay for an RTT before the second packet is sent.
//
// As a practical example in Chromium today, consider the case of a small
// POST. I have verified this:
// Client writes 649 bytes of header (partial packet #1)
// Client writes 50 bytes of POST data (partial packet #2)
// In the above example, with Nagle, a RTT delay is inserted between these
// two sends due to nagle. RTTs can easily be 100ms or more. The best
// fix is to make sure that for POSTing data, we write as much data as
// possible and minimize partial packets. We will fix that. But disabling
// Nagle also ensure we don't run into this delay in other edge cases.
// See also:
// http://technet.microsoft.com/en-us/library/bb726981.aspx
const BOOL kDisableNagle = TRUE;
int rv = setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY,
reinterpret_cast<const char*>(&kDisableNagle), sizeof(kDisableNagle));
DCHECK(!rv) << "Could not disable nagle";
return OK;
}
void TCPClientSocket::DoCallback(int rv) {
DCHECK(rv != ERR_IO_PENDING);
DCHECK(callback_);
// since Run may result in Read being called, clear callback_ up front.
CompletionCallback* c = callback_;
callback_ = NULL;
c->Run(rv);
}
void TCPClientSocket::DidCompleteConnect() {
int result;
TRACE_EVENT_END("socket.connect", this, "");
wait_state_ = NOT_WAITING;
WSANETWORKEVENTS events;
int rv = WSAEnumNetworkEvents(socket_, overlapped_.hEvent, &events);
if (rv == SOCKET_ERROR) {
NOTREACHED();
result = MapWinsockError(WSAGetLastError());
} else if (events.lNetworkEvents & FD_CONNECT) {
wait_state_ = NOT_WAITING;
DWORD error_code = static_cast<DWORD>(events.iErrorCode[FD_CONNECT_BIT]);
if (current_ai_->ai_next && (
error_code == WSAEADDRNOTAVAIL ||
error_code == WSAEAFNOSUPPORT ||
error_code == WSAECONNREFUSED ||
error_code == WSAENETUNREACH ||
error_code == WSAEHOSTUNREACH ||
error_code == WSAETIMEDOUT)) {
// Try using the next address.
const struct addrinfo* next = current_ai_->ai_next;
Disconnect();
current_ai_ = next;
result = Connect(callback_);
} else {
result = MapWinsockError(error_code);
}
} else {
NOTREACHED();
result = ERR_UNEXPECTED;
}
if (result != ERR_IO_PENDING)
DoCallback(result);
}
void TCPClientSocket::DidCompleteIO() {
DWORD num_bytes, flags;
BOOL ok = WSAGetOverlappedResult(
socket_, &overlapped_, &num_bytes, FALSE, &flags);
WSAResetEvent(overlapped_.hEvent);
if (wait_state_ == WAITING_READ) {
TRACE_EVENT_END("socket.read", this, StringPrintf("%d bytes", num_bytes));
} else {
TRACE_EVENT_END("socket.write", this, StringPrintf("%d bytes", num_bytes));
}
wait_state_ = NOT_WAITING;
DoCallback(ok ? num_bytes : MapWinsockError(WSAGetLastError()));
}
void TCPClientSocket::OnObjectSignaled(HANDLE object) {
DCHECK(object == overlapped_.hEvent);
switch (wait_state_) {
case WAITING_CONNECT:
DidCompleteConnect();
break;
case WAITING_READ:
case WAITING_WRITE:
DidCompleteIO();
break;
default:
NOTREACHED();
break;
}
}
void TCPClientSocket::WaitForAndResetEvent() {
// TODO(wtc): Remove the CHECKs after enough testing.
DWORD wait_rv = WaitForSingleObject(overlapped_.hEvent, INFINITE);
CHECK(wait_rv == WAIT_OBJECT_0);
BOOL ok = WSAResetEvent(overlapped_.hEvent);
CHECK(ok);
}
} // namespace net
<|endoftext|> |
<commit_before>// ------------------------------------------------------------------
// pion-net: a C++ framework for building lightweight HTTP interfaces
// ------------------------------------------------------------------
// Copyright (C) 2007-2008 Atomic Labs, Inc. (http://www.atomiclabs.com)
//
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
//
#ifndef __PION_PIONUSER_HEADER__
#define __PION_PIONUSER_HEADER__
#include <map>
#include <string>
#include <cstring>
#include <boost/shared_ptr.hpp>
#include <boost/noncopyable.hpp>
#include <boost/thread/mutex.hpp>
#ifdef PION_HAVE_SSL
#include <openssl/sha.h>
#endif
namespace pion { // begin namespace pion
namespace net { // begin namespace net (Pion Network Library)
///
/// PionUser: base class to store user credentials
///
class PionUser :
private boost::noncopyable
{
public:
/// construct a new PionUser object
PionUser(std::string const &username, std::string const &password) :
m_username(username)
{
setPassword(password);
}
/// virtual destructor
virtual ~PionUser() {}
/// returns user name as a string
std::string const & getUsername() const { return m_username; }
/**
* matches password credential for given user
*
* @param password password credentials
*/
virtual bool matchPassword(const std::string& password) const {
#ifdef PION_HAVE_SSL
unsigned char sha1_hash[SHA_DIGEST_LENGTH];
SHA1(reinterpret_cast<const unsigned char *>(password.data()), password.size(), sha1_hash);
return (memcmp(sha1_hash, m_password_hash, SHA_DIGEST_LENGTH) == 0);
#else
return m_password == password;
#endif
}
/// sets password credentials for given user
virtual void setPassword(const std::string& password) {
#ifdef PION_HAVE_SSL
SHA1((const unsigned char *)password.data(), password.size(), m_password_hash);
#else
m_password = password;
#endif
}
protected:
/// username string
const std::string m_username;
#ifdef PION_HAVE_SSL
/// SHA1 hash of the password
unsigned char m_password_hash[SHA_DIGEST_LENGTH];
#else
/// password string (actual contents depends on implementation)
std::string m_password;
#endif
};
/// data type for a PionUser pointer
typedef boost::shared_ptr<PionUser> PionUserPtr;
///
/// PionUserManager base class for PionUser container/manager
///
class PionUserManager :
private boost::noncopyable
{
public:
/// construct a new PionUserManager object
PionUserManager(void) {}
/// virtual destructor
virtual ~PionUserManager() {}
/**
* used to add a new user
*
* @return false if user with such a name already exists
*/
virtual bool addUser(const std::string &username, const std::string &password) {
boost::mutex::scoped_lock lock(m_mutex);
UserMap::iterator i = m_users.find(username);
if (i!=m_users.end())
return false;
PionUserPtr user(new PionUser(username,password));
m_users.insert(std::make_pair(username, user));
return true;
}
/**
* update password for given user
*
* @return false if user with such a name doesn't exist
*/
virtual bool updateUser(const std::string &username, const std::string &password) {
boost::mutex::scoped_lock lock(m_mutex);
UserMap::iterator i = m_users.find(username);
if (i==m_users.end())
return false;
i->second->setPassword(password);
return true;
}
/**
* used to remove given user
*
* @return false if no user with such username
*/
virtual bool removeUser(const std::string &username) {
boost::mutex::scoped_lock lock(m_mutex);
UserMap::iterator i = m_users.find(username);
if (i==m_users.end())
return false;
m_users.erase(i);
return true;
}
/**
* Used to locate user object by username
*/
virtual PionUserPtr getUser(const std::string &username) {
boost::mutex::scoped_lock lock(m_mutex);
UserMap::const_iterator i = m_users.find(username);
if (i==m_users.end())
return PionUserPtr();
else
return i->second;
}
/**
* Used to locate user object by username and password
*/
virtual PionUserPtr getUser(const std::string& username, const std::string& password) {
boost::mutex::scoped_lock lock(m_mutex);
UserMap::const_iterator i = m_users.find(username);
if (i==m_users.end() || !i->second->matchPassword(password))
return PionUserPtr();
else
return i->second;
}
protected:
/// data type for a map of usernames to user objects
typedef std::map<std::string, PionUserPtr> UserMap;
/// mutex used to protect access to the user list
mutable boost::mutex m_mutex;
/// user records container
UserMap m_users;
};
/// data type for a PionUserManager pointer
typedef boost::shared_ptr<PionUserManager> PionUserManagerPtr;
} // end namespace net
} // end namespace pion
#endif
<commit_msg>Added some more support to the PionUser and PionUserManager classes for handling encrypted passwords<commit_after>// ------------------------------------------------------------------
// pion-net: a C++ framework for building lightweight HTTP interfaces
// ------------------------------------------------------------------
// Copyright (C) 2007-2008 Atomic Labs, Inc. (http://www.atomiclabs.com)
//
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
//
#ifndef __PION_PIONUSER_HEADER__
#define __PION_PIONUSER_HEADER__
#include <map>
#include <string>
#include <cstring>
#include <boost/shared_ptr.hpp>
#include <boost/noncopyable.hpp>
#include <boost/thread/mutex.hpp>
#include <pion/PionConfig.hpp>
#include <pion/PionException.hpp>
#ifdef PION_HAVE_SSL
#include <openssl/sha.h>
#endif
namespace pion { // begin namespace pion
namespace net { // begin namespace net (Pion Network Library)
///
/// PionUser: base class to store user credentials
///
class PionUser :
private boost::noncopyable
{
public:
/// exception thrown if a bad password hash is given to setPasswordHash()
class BadPasswordHash : public std::exception {
public:
virtual const char* what() const throw() {
return "Invalid password hash provided";
}
};
/// construct a new PionUser object
PionUser(std::string const &username) :
m_username(username)
{}
/// construct a new PionUser object
PionUser(std::string const &username, std::string const &password) :
m_username(username)
{
setPassword(password);
}
/// virtual destructor
virtual ~PionUser() {}
/// returns user name as a string
std::string const & getUsername() const { return m_username; }
/// returns password for the user (encrypted if SSL is enabled)
std::string const & getPassword() const { return m_password; }
/**
* matches password credential for given user
*
* @param password password credentials
*/
virtual bool matchPassword(const std::string& password) const {
#ifdef PION_HAVE_SSL
unsigned char sha1_hash[SHA_DIGEST_LENGTH];
SHA1(reinterpret_cast<const unsigned char *>(password.data()), password.size(), sha1_hash);
return (memcmp(sha1_hash, m_password_hash, SHA_DIGEST_LENGTH) == 0);
#else
return m_password == password;
#endif
}
/// sets password credentials for given user
virtual void setPassword(const std::string& password) {
#ifdef PION_HAVE_SSL
// store encrypted hash value
SHA1((const unsigned char *)password.data(), password.size(), m_password_hash);
m_password_hash[SHA_DIGEST_LENGTH] = '\0';
// update password string (convert binary to hex)
m_password.clear();
char buf[3];
buf[2] = '\0';
for (unsigned int n = 0; n < SHA_DIGEST_LENGTH; ++n) {
sprintf(buf, "%2X", static_cast<unsigned int>(m_password_hash[n]));
m_password += buf;
}
#else
m_password = password;
#endif
}
#ifdef PION_HAVE_SSL
/// sets encrypted password credentials for given user
virtual void setPasswordHash(const std::string& password_hash) {
// update password string representation
if (password_hash.size() != SHA_DIGEST_LENGTH*2)
throw BadPasswordHash();
m_password = password_hash;
// convert string from hex to binary value
char buf[3];
buf[2] = '\0';
unsigned int hash_pos = 0;
std::string::iterator str_it = m_password.begin();
while (str_it != m_password.end()) {
buf[0] = *str_it;
++str_it;
buf[1] = *str_it;
++str_it;
m_password_hash[hash_pos++] = strtoul(buf, 0, 16);
}
}
#endif
protected:
/// username string
const std::string m_username;
/// password string (actual contents depends on implementation)
std::string m_password;
#ifdef PION_HAVE_SSL
/// SHA1 hash of the password
unsigned char m_password_hash[SHA_DIGEST_LENGTH];
#endif
};
/// data type for a PionUser pointer
typedef boost::shared_ptr<PionUser> PionUserPtr;
///
/// PionUserManager base class for PionUser container/manager
///
class PionUserManager :
private boost::noncopyable
{
public:
/// construct a new PionUserManager object
PionUserManager(void) {}
/// virtual destructor
virtual ~PionUserManager() {}
/**
* used to add a new user with plaintext password
*
* @param username name or identifier of the user to add
* @param password plaintext password of the user to add
*
* @return false if user with such a name already exists
*/
virtual bool addUser(const std::string &username,
const std::string &password)
{
boost::mutex::scoped_lock lock(m_mutex);
UserMap::iterator i = m_users.find(username);
if (i!=m_users.end())
return false;
PionUserPtr user(new PionUser(username, password));
m_users.insert(std::make_pair(username, user));
return true;
}
/**
* update password for given user
*
* @param username name or identifier of the user to update
* @param password plaintext password of the user to update
*
* @return false if user with such a name doesn't exist
*/
virtual bool updateUser(const std::string &username,
const std::string &password)
{
boost::mutex::scoped_lock lock(m_mutex);
UserMap::iterator i = m_users.find(username);
if (i==m_users.end())
return false;
i->second->setPassword(password);
return true;
}
#ifdef PION_HAVE_SSL
/**
* used to add a new user with encrypted password
*
* @param username name or identifier of the user to add
* @param password_hash encrypted password of the user to add
*
* @return false if user with such a name already exists
*/
virtual bool addUserHash(const std::string &username,
const std::string &password_hash)
{
boost::mutex::scoped_lock lock(m_mutex);
UserMap::iterator i = m_users.find(username);
if (i!=m_users.end())
return false;
PionUserPtr user(new PionUser(username));
user->setPasswordHash(password_hash);
m_users.insert(std::make_pair(username, user));
return true;
}
/**
* update password for given user with encrypted password
*
* @param username name or identifier of the user to update
* @param password_hash encrypted password of the user to update
*
* @return false if user with such a name doesn't exist
*/
virtual bool updateUserHash(const std::string &username,
const std::string &password_hash)
{
boost::mutex::scoped_lock lock(m_mutex);
UserMap::iterator i = m_users.find(username);
if (i==m_users.end())
return false;
i->second->setPasswordHash(password_hash);
return true;
}
#endif
/**
* used to remove given user
*
* @return false if no user with such username
*/
virtual bool removeUser(const std::string &username) {
boost::mutex::scoped_lock lock(m_mutex);
UserMap::iterator i = m_users.find(username);
if (i==m_users.end())
return false;
m_users.erase(i);
return true;
}
/**
* Used to locate user object by username
*/
virtual PionUserPtr getUser(const std::string &username) {
boost::mutex::scoped_lock lock(m_mutex);
UserMap::const_iterator i = m_users.find(username);
if (i==m_users.end())
return PionUserPtr();
else
return i->second;
}
/**
* Used to locate user object by username and password
*/
virtual PionUserPtr getUser(const std::string& username, const std::string& password) {
boost::mutex::scoped_lock lock(m_mutex);
UserMap::const_iterator i = m_users.find(username);
if (i==m_users.end() || !i->second->matchPassword(password))
return PionUserPtr();
else
return i->second;
}
protected:
/// data type for a map of usernames to user objects
typedef std::map<std::string, PionUserPtr> UserMap;
/// mutex used to protect access to the user list
mutable boost::mutex m_mutex;
/// user records container
UserMap m_users;
};
/// data type for a PionUserManager pointer
typedef boost::shared_ptr<PionUserManager> PionUserManagerPtr;
} // end namespace net
} // end namespace pion
#endif
<|endoftext|> |
<commit_before>/* Copyright 2019 Benjamin Worpitz, Matthias Werner
*
* This file is part of Alpaka.
*
* 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/.
*/
#pragma once
namespace alpaka
{
//-----------------------------------------------------------------------------
//! The test specifics.
namespace test
{
template<
typename TIdx>
struct CreateVecWithIdx
{
//#############################################################################
//! 1D: (16)
//! 2D: (16, 14)
//! 3D: (16, 14, 12)
//! 4D: (16, 14, 12, 10)
template<
std::size_t Tidx>
struct ForExtentBuf
{
//-----------------------------------------------------------------------------
ALPAKA_FN_HOST_ACC static auto create()
{
return static_cast<TIdx>(16u - (Tidx*2u));
}
};
//#############################################################################
//! 1D: (11)
//! 2D: (11, 8)
//! 3D: (11, 8, 5)
//! 4D: (11, 8, 5, 2)
template<
std::size_t Tidx>
struct ForExtentSubView
{
//-----------------------------------------------------------------------------
ALPAKA_FN_HOST_ACC static auto create()
{
return static_cast<TIdx>(11u - (Tidx*3u));
}
};
//#############################################################################
//! 1D: (2)
//! 2D: (2, 3)
//! 3D: (2, 3, 4)
//! 4D: (2, 3, 4, 5)
template<
std::size_t Tidx>
struct ForOffset
{
//-----------------------------------------------------------------------------
ALPAKA_FN_HOST_ACC static auto create()
{
return static_cast<TIdx>(2u + Tidx);
}
};
};
}
}
<commit_msg>Reduce test buffer sizes to fix tests with small Idx types<commit_after>/* Copyright 2019 Benjamin Worpitz, Matthias Werner
*
* This file is part of Alpaka.
*
* 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/.
*/
#pragma once
namespace alpaka
{
//-----------------------------------------------------------------------------
//! The test specifics.
namespace test
{
template<
typename TIdx>
struct CreateVecWithIdx
{
//#############################################################################
//! 1D: (11)
//! 2D: (11, 10)
//! 3D: (11, 10, 9)
//! 4D: (11, 10, 9, 8)
template<
std::size_t Tidx>
struct ForExtentBuf
{
//-----------------------------------------------------------------------------
ALPAKA_FN_HOST_ACC static auto create()
{
return static_cast<TIdx>(11u - Tidx);
}
};
//#############################################################################
//! 1D: (8)
//! 2D: (8, 6)
//! 3D: (8, 6, 4)
//! 4D: (8, 6, 4, 2)
template<
std::size_t Tidx>
struct ForExtentSubView
{
//-----------------------------------------------------------------------------
ALPAKA_FN_HOST_ACC static auto create()
{
return static_cast<TIdx>(8u - (Tidx * 2u));
}
};
//#############################################################################
//! 1D: (2)
//! 2D: (2, 3)
//! 3D: (2, 3, 4)
//! 4D: (2, 3, 4, 5)
template<
std::size_t Tidx>
struct ForOffset
{
//-----------------------------------------------------------------------------
ALPAKA_FN_HOST_ACC static auto create()
{
return static_cast<TIdx>(2u + Tidx);
}
};
};
}
}
<|endoftext|> |
<commit_before>#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/objdetect/objdetect.hpp"
#include <opencv2/opencv.hpp>
#include <iostream>
#include <stdio.h>
#include "imagedetect.hpp"
#include "videoin_c920.hpp"
#include "track.hpp"
using namespace std;
using namespace cv;
void writeImage(const Mat &frame, const vector<Rect> &rects, size_t index, const char *path, int frameCounter);
int main( int argc, const char** argv )
{
string windowName = "Capture - Face detection";
string capPath;
VideoIn *cap;
const size_t detectMax = 10;
const string frameOpt = "--frame=";
double frameStart = 0.0;
const string captureAllOpt = "--all";
// Flags for various UI features
bool pause = false; // pause playback?
bool captureAll = false; // capture all found targets to image files?
bool tracking = true; // display tracking info?
bool printFrames = false; // print frame number?
enum GPU_MODE
{
GPU_MODE_UNINITIALIZED,
GPU_MODE_CPU,
GPU_MODE_GPU
};
GPU_MODE gpuModeCurrent = GPU_MODE_UNINITIALIZED;
GPU_MODE gpuModeNext = GPU_MODE_CPU;
if (gpu::getCudaEnabledDeviceCount() > 0)
gpuModeNext = GPU_MODE_GPU;
if (argc < 2)
{
// No arguments? Open default camera
// and hope for the best
cap = new VideoIn(0);
capPath = "negative/2-11";
windowName = "Camera 0";
}
else
{
// Read through command line args, extract
// cmd line parameters and input filename
int fileArgc;
for (fileArgc = 1; fileArgc < argc; fileArgc++)
{
if (frameOpt.compare(0, frameOpt.length(), argv[fileArgc], frameOpt.length()) == 0)
frameStart = (double)atoi(argv[fileArgc] + frameOpt.length());
else if (captureAllOpt.compare(0, captureAllOpt.length(), argv[fileArgc], captureAllOpt.length()) == 0)
captureAll = true;
else
break;
}
// Digit? Open camera
if (isdigit(*argv[fileArgc]) && !strstr(argv[fileArgc],".jpg"))
{
cap = new VideoIn(*argv[fileArgc] - '0');
capPath = "negative/2-11_" + (*argv[fileArgc] - '0');
stringstream ss;
ss << "Camera ";
ss << *argv[fileArgc] - '0';
windowName = ss.str();
}
else
{
// Open file name - will handle images or videos
cap = new VideoIn(argv[fileArgc]);
if (cap->VideoCap())
{
cap->VideoCap()->set(CV_CAP_PROP_POS_FRAMES, frameStart);
cap->frameCounter(frameStart);
}
capPath = "negative/" + string(argv[fileArgc]).substr(string(argv[fileArgc]).rfind('/')+1);
windowName = argv[fileArgc];
}
}
Mat frame;
vector <Mat> images;
string detectWindowName = "Detection Parameters";
namedWindow(detectWindowName);
createTrackbar ("Scale", detectWindowName, &scale, 50, NULL);
createTrackbar ("Neighbors", detectWindowName, &neighbors, 50, NULL);
createTrackbar ("Max Detect", detectWindowName, &maxDetectSize, 1000, NULL);
const char *cascadeName = "../cascade_training/classifier_bin_6/cascade_oldformat_49.xml";
// Use GPU code if hardware is detected, otherwise
// fall back to CPU code
BaseCascadeDetect *detectCascade = NULL;;
if (!cap->getNextFrame(false, frame))
{
cerr << "Can not read frame from input" << endl;
return 0;
}
// Minimum size of a bin at ~30 feet distance
// TODO : Verify this once camera is calibrated
minDetectSize = frame.cols * 0.04;
// Create list of tracked objects
TrackedObjectList binTrackingList(24.0, frame.cols);
#define frameTicksLength (sizeof(frameTicks) / sizeof(frameTicks[0]))
double frameTicks[20];
int64 startTick;
int64 endTick;
size_t frameTicksIndex = 0;
// Read the video stream
while(cap->getNextFrame(pause, frame))
{
startTick = getTickCount();
//TODO : grab angle delta from robot
// Adjust the position of all of the detected objects
// to account for movement of the robot between frames
double deltaAngle = 0.0;
binTrackingList.adjustAngle(deltaAngle);
if ((gpuModeCurrent == GPU_MODE_UNINITIALIZED) || (gpuModeCurrent != gpuModeNext))
{
if (detectCascade)
delete detectCascade;
if (gpuModeNext == GPU_MODE_GPU)
detectCascade = new GPU_CascadeDetect(cascadeName);
else
detectCascade = new CPU_CascadeDetect(cascadeName);
gpuModeCurrent = gpuModeNext;
// Load the cascades
if( !detectCascade->loaded() )
{
cerr << "--(!)Error loading " << cascadeName << endl;
return -1;
}
}
// Apply the classifier to the frame
vector<Rect> detectRects;
vector<unsigned> detectDirections;
detectCascade->cascadeDetect(frame, detectRects, detectDirections);
images.clear();
// Filter out images using threshold values -
// since bins are green this could be used as a second pass
// to get rid of false positives which aren't green enough
vector <Rect> filteredRects;
for( size_t i = 0; i < min(detectRects.size(), detectMax); i++ )
{
for (size_t j = 0; j < detectRects.size(); j++) {
if (i != j) {
Rect intersection = detectRects[i] & detectRects[j];
if (intersection.width * intersection.height > 0)
if (abs((detectRects[i].width * detectRects[i].height) - (detectRects[j].width * detectRects[j].height)) < 2000)
if (intersection.width / intersection.height < 5 && intersection.width / intersection.height > 0) {
Rect lowestYVal;
int indexHighest;
if(detectRects[i].y < detectRects[j].y) {
lowestYVal = detectRects[i]; //higher rectangle
indexHighest = j;
}
else {
lowestYVal = detectRects[j]; //higher rectangle
indexHighest = i;
}
if(intersection.y > lowestYVal.y) {
//cout << "found intersection" << endl;
rectangle(frame, detectRects[indexHighest], Scalar(0,255,255), 3);
detectRects.erase(detectRects.begin()+indexHighest);
detectDirections.erase(detectDirections.begin()+indexHighest);
}
}
}
}
// Mark detected rectangle on image
Scalar rectColor;
switch (detectDirections[i])
{
case 1:
rectColor = Scalar(0,0,255);
break;
case 2:
rectColor = Scalar(0,255,0);
break;
case 4:
rectColor = Scalar(255,0,0);
break;
case 8:
rectColor = Scalar(255,255,0);
break;
default:
rectColor = Scalar(255,0,255);
break;
}
rectangle( frame, detectRects[i], rectColor, 3);
// Label each outlined image with a digit. Top-level code allows
// users to save these small images by hitting the key they're labeled with
// This should be a quick way to grab lots of falsly detected images
// which need to be added to the negative list for the next
// pass of classifier training.
stringstream label;
label << i;
putText(frame, label.str(), Point(detectRects[i].x+10, detectRects[i].y+30),
FONT_HERSHEY_PLAIN, 2.0, Scalar(0, 0, 255));
// Process this detected rectangle - either update the nearest
// object or add it as a new one
binTrackingList.processDetect(detectRects[i]);
}
// Print detect status of live objects
binTrackingList.print();
if (tracking)
{
// Grab info from detected objects, print it ou
vector<TrackedObjectDisplay> displayList;
binTrackingList.getDisplay(displayList);
for (size_t i = 0; i < displayList.size(); i++)
{
if (displayList[i].ratio < 0.15)
continue;
// Color moves from red to green (via brown, yuck)
// as the detected ratio goes up
Scalar rectColor(0, 255 * displayList[i].ratio, 255 * (1.0 - displayList[i].ratio));
// Highlight detected target
rectangle(frame, displayList[i].rect, rectColor, 3);
// Write detect ID, distance and angle data
putText(frame, displayList[i].id, Point(displayList[i].rect.x+25, displayList[i].rect.y+30), FONT_HERSHEY_PLAIN, 2.0, rectColor);
stringstream distLabel;
distLabel << "D=";
distLabel << displayList[i].distance;
putText(frame, distLabel.str(), Point(displayList[i].rect.x+10, displayList[i].rect.y+50), FONT_HERSHEY_PLAIN, 1.5, rectColor);
stringstream angleLabel;
angleLabel << "A=";
angleLabel << displayList[i].angle;
putText(frame, angleLabel.str(), Point(displayList[i].rect.x+10, displayList[i].rect.y+70), FONT_HERSHEY_PLAIN, 1.5, rectColor);
}
}
// Don't update to next frame if paused to prevent
// objects missing from this frame to be aged out
if (!pause)
binTrackingList.nextFrame();
if (printFrames && cap->VideoCap())
{
int frames = cap->VideoCap()->get(CV_CAP_PROP_FRAME_COUNT);
stringstream ss;
ss << cap->frameCounter();
ss << '/';
ss << frames;
putText(frame, ss.str(), Point(frame.cols - 15 * ss.str().length(), 20), FONT_HERSHEY_PLAIN, 1.5, Scalar(0,0,255));
}
if (frameTicksIndex >= frameTicksLength)
{
double sum = 0;
for (size_t i = 0; i < frameTicksLength; i++)
sum += frameTicks[i];
sum /= frameTicksLength;
stringstream ss;
ss.precision(3);
ss << 1.0/sum;
ss << " FPS";
putText(frame, ss.str(), Point(frame.cols - 15 * ss.str().length(), 50), FONT_HERSHEY_PLAIN, 1.5, Scalar(0,0,255));
}
// Put an A on the screen if capture-all is enabled so
// users can keep track of that toggle's mode
if (captureAll)
putText(frame, "A", Point(25,25), FONT_HERSHEY_PLAIN, 2.5, Scalar(0, 255, 255));
//-- Show what you got
imshow( windowName, frame );
// Process user IO
char c = waitKey(5);
if( c == 'c' ) { break; } // exit
else if( c == 'q' ) { break; } // exit
else if( c == 27 ) { break; } // exit
else if( c == ' ') { pause = !pause; }
else if( c == 'f') // advance to next frame
{
cap->getNextFrame(false, frame);
}
else if (c == 'A') // toggle capture-all
{
captureAll = !captureAll;
}
else if (c == 't') // toggle tracking info display
{
tracking = !tracking;
}
else if (c == 'a') // save all detected images
{
Mat frameCopy;
cap->getNextFrame(true, frameCopy);
for (size_t index = 0; index < detectRects.size(); index++)
writeImage(frameCopy, detectRects, index, capPath.c_str(), cap->frameCounter());
}
else if (c == 'p') // print frame number to screen
{
cout << cap->frameCounter() << endl;
}
else if (c == 'P')
{
printFrames = !printFrames;
}
else if (c == 'G') // toggle CPU/GPU mode
{
if (gpuModeNext == GPU_MODE_GPU)
gpuModeNext = GPU_MODE_CPU;
else
gpuModeNext = GPU_MODE_GPU;
}
else if (isdigit(c)) // save a single detected image
{
Mat frameCopy;
cap->getNextFrame(true, frameCopy);
writeImage(frameCopy, detectRects, c - '0', capPath.c_str(), cap->frameCounter());
}
if (captureAll && detectRects.size())
{
Mat frameCopy;
cap->getNextFrame(true, frameCopy);
for (size_t index = 0; index < detectRects.size(); index++)
writeImage(frameCopy, detectRects, index, capPath.c_str(), cap->frameCounter());
}
endTick = getTickCount();
frameTicks[frameTicksIndex++ % frameTicksLength] = (double)(endTick - startTick) / getTickFrequency();
}
return 0;
}
void writeImage(const Mat &frame, const vector<Rect> &rects, size_t index, const char *path, int frameCounter)
{
if (index < rects.size())
{
Mat image = frame(rects[index]);
// Create filename, save image
stringstream fn;
fn << path;
fn << "_";
fn << frameCounter;
fn << "_";
fn << index;
imwrite(fn.str().substr(fn.str().rfind('\\')+1) + ".png", image);
// Save grayscale equalized version
Mat frameGray;
cvtColor( image, frameGray, CV_BGR2GRAY );
equalizeHist( frameGray, frameGray );
imwrite(fn.str().substr(fn.str().rfind('\\')+1) + "_g.png", frameGray);
// Save 20x20 version of the same image
Mat smallImg;
resize(image, smallImg, Size(20,20));
imwrite(fn.str().substr(fn.str().rfind('\\')+1) + "_s.png", smallImg);
// Save grayscale equalized version of small image
cvtColor( smallImg, frameGray, CV_BGR2GRAY );
equalizeHist( frameGray, frameGray );
imwrite(fn.str().substr(fn.str().rfind('\\')+1) + "_g_s.png", frameGray);
}
}
<commit_msg>Add batch mode - no GUI. Use for benchmarking or for bulk extracting false positives (use --all on the command line to default to save-all)<commit_after>#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/objdetect/objdetect.hpp"
#include <opencv2/opencv.hpp>
#include <iostream>
#include <stdio.h>
#include "imagedetect.hpp"
#include "videoin_c920.hpp"
#include "track.hpp"
using namespace std;
using namespace cv;
void writeImage(const Mat &frame, const vector<Rect> &rects, size_t index, const char *path, int frameCounter);
int main( int argc, const char** argv )
{
string windowName = "Capture - Face detection";
string capPath;
VideoIn *cap;
const size_t detectMax = 10;
const string frameOpt = "--frame=";
double frameStart = 0.0;
const string captureAllOpt = "--all";
const string batchModeOpt = "--batch";
// Flags for various UI features
bool pause = false; // pause playback?
bool captureAll = false; // capture all found targets to image files?
bool tracking = true; // display tracking info?
bool printFrames = false; // print frame number?
bool batchMode = false; // non-interactive mode - no display, run through
// as quickly as possible. Combine with --all
enum GPU_MODE
{
GPU_MODE_UNINITIALIZED,
GPU_MODE_CPU,
GPU_MODE_GPU
};
GPU_MODE gpuModeCurrent = GPU_MODE_UNINITIALIZED;
GPU_MODE gpuModeNext = GPU_MODE_CPU;
if (gpu::getCudaEnabledDeviceCount() > 0)
gpuModeNext = GPU_MODE_GPU;
if (argc < 2)
{
// No arguments? Open default camera
// and hope for the best
cap = new VideoIn(0);
capPath = "negative/2-11";
windowName = "Camera 0";
}
else
{
// Read through command line args, extract
// cmd line parameters and input filename
int fileArgc;
for (fileArgc = 1; fileArgc < argc; fileArgc++)
{
if (frameOpt.compare(0, frameOpt.length(), argv[fileArgc], frameOpt.length()) == 0)
frameStart = (double)atoi(argv[fileArgc] + frameOpt.length());
else if (captureAllOpt.compare(0, captureAllOpt.length(), argv[fileArgc], captureAllOpt.length()) == 0)
captureAll = true;
else if (batchModeOpt.compare(0, batchModeOpt.length(), argv[fileArgc], batchModeOpt.length()) == 0)
batchMode = true;
else
break;
}
// Digit? Open camera
if (isdigit(*argv[fileArgc]) && !strstr(argv[fileArgc],".jpg"))
{
cap = new VideoIn(*argv[fileArgc] - '0');
capPath = "negative/2-11_" + (*argv[fileArgc] - '0');
stringstream ss;
ss << "Camera ";
ss << *argv[fileArgc] - '0';
windowName = ss.str();
}
else
{
// Open file name - will handle images or videos
cap = new VideoIn(argv[fileArgc]);
if (cap->VideoCap())
{
cap->VideoCap()->set(CV_CAP_PROP_POS_FRAMES, frameStart);
cap->frameCounter(frameStart);
}
capPath = "negative/" + string(argv[fileArgc]).substr(string(argv[fileArgc]).rfind('/')+1);
windowName = argv[fileArgc];
}
}
Mat frame;
vector <Mat> images;
if (!batchMode)
{
string detectWindowName = "Detection Parameters";
namedWindow(detectWindowName);
createTrackbar ("Scale", detectWindowName, &scale, 50, NULL);
createTrackbar ("Neighbors", detectWindowName, &neighbors, 50, NULL);
createTrackbar ("Max Detect", detectWindowName, &maxDetectSize, 1000, NULL);
}
const char *cascadeName = "../cascade_training/classifier_bin_6/cascade_oldformat_51.xml";
// Use GPU code if hardware is detected, otherwise
// fall back to CPU code
BaseCascadeDetect *detectCascade = NULL;;
if (!cap->getNextFrame(false, frame))
{
cerr << "Can not read frame from input" << endl;
return 0;
}
// Minimum size of a bin at ~30 feet distance
// TODO : Verify this once camera is calibrated
minDetectSize = frame.cols * 0.04;
// Create list of tracked objects
TrackedObjectList binTrackingList(24.0, frame.cols);
#define frameTicksLength (sizeof(frameTicks) / sizeof(frameTicks[0]))
double frameTicks[20];
int64 startTick;
int64 endTick;
size_t frameTicksIndex = 0;
// Read the video stream
while(cap->getNextFrame(pause, frame))
{
startTick = getTickCount();
//TODO : grab angle delta from robot
// Adjust the position of all of the detected objects
// to account for movement of the robot between frames
double deltaAngle = 0.0;
binTrackingList.adjustAngle(deltaAngle);
if ((gpuModeCurrent == GPU_MODE_UNINITIALIZED) || (gpuModeCurrent != gpuModeNext))
{
if (detectCascade)
delete detectCascade;
if (gpuModeNext == GPU_MODE_GPU)
detectCascade = new GPU_CascadeDetect(cascadeName);
else
detectCascade = new CPU_CascadeDetect(cascadeName);
gpuModeCurrent = gpuModeNext;
// Load the cascades
if( !detectCascade->loaded() )
{
cerr << "--(!)Error loading " << cascadeName << endl;
return -1;
}
}
// Apply the classifier to the frame
vector<Rect> detectRects;
vector<unsigned> detectDirections;
detectCascade->cascadeDetect(frame, detectRects, detectDirections);
images.clear();
// Filter out images using threshold values -
// since bins are green this could be used as a second pass
// to get rid of false positives which aren't green enough
vector <Rect> filteredRects;
for( size_t i = 0; i < min(detectRects.size(), detectMax); i++ )
{
for (size_t j = 0; j < detectRects.size(); j++) {
if (i != j) {
Rect intersection = detectRects[i] & detectRects[j];
if (intersection.width * intersection.height > 0)
if (abs((detectRects[i].width * detectRects[i].height) - (detectRects[j].width * detectRects[j].height)) < 2000)
if (intersection.width / intersection.height < 5 && intersection.width / intersection.height > 0) {
Rect lowestYVal;
int indexHighest;
if(detectRects[i].y < detectRects[j].y) {
lowestYVal = detectRects[i]; //higher rectangle
indexHighest = j;
}
else {
lowestYVal = detectRects[j]; //higher rectangle
indexHighest = i;
}
if(intersection.y > lowestYVal.y) {
//cout << "found intersection" << endl;
if (!batchMode)
rectangle(frame, detectRects[indexHighest], Scalar(0,255,255), 3);
detectRects.erase(detectRects.begin()+indexHighest);
detectDirections.erase(detectDirections.begin()+indexHighest);
}
}
}
}
// Mark detected rectangle on image
Scalar rectColor;
switch (detectDirections[i])
{
case 1:
rectColor = Scalar(0,0,255);
break;
case 2:
rectColor = Scalar(0,255,0);
break;
case 4:
rectColor = Scalar(255,0,0);
break;
case 8:
rectColor = Scalar(255,255,0);
break;
default:
rectColor = Scalar(255,0,255);
break;
}
if (!batchMode)
rectangle( frame, detectRects[i], rectColor, 3);
// Label each outlined image with a digit. Top-level code allows
// users to save these small images by hitting the key they're labeled with
// This should be a quick way to grab lots of falsly detected images
// which need to be added to the negative list for the next
// pass of classifier training.
if (!batchMode)
{
stringstream label;
label << i;
putText(frame, label.str(), Point(detectRects[i].x+10, detectRects[i].y+30),
FONT_HERSHEY_PLAIN, 2.0, Scalar(0, 0, 255));
// Process this detected rectangle - either update the nearest
// object or add it as a new one
binTrackingList.processDetect(detectRects[i]);
}
}
// Print detect status of live objects
binTrackingList.print();
if (tracking)
{
// Grab info from detected objects, print it ou
vector<TrackedObjectDisplay> displayList;
binTrackingList.getDisplay(displayList);
for (size_t i = 0; i < displayList.size(); i++)
{
if (displayList[i].ratio < 0.15)
continue;
if (!batchMode)
{
// Color moves from red to green (via brown, yuck)
// as the detected ratio goes up
Scalar rectColor(0, 255 * displayList[i].ratio, 255 * (1.0 - displayList[i].ratio));
// Highlight detected target
rectangle(frame, displayList[i].rect, rectColor, 3);
// Write detect ID, distance and angle data
putText(frame, displayList[i].id, Point(displayList[i].rect.x+25, displayList[i].rect.y+30), FONT_HERSHEY_PLAIN, 2.0, rectColor);
stringstream distLabel;
distLabel << "D=";
distLabel << displayList[i].distance;
putText(frame, distLabel.str(), Point(displayList[i].rect.x+10, displayList[i].rect.y+50), FONT_HERSHEY_PLAIN, 1.5, rectColor);
stringstream angleLabel;
angleLabel << "A=";
angleLabel << displayList[i].angle;
putText(frame, angleLabel.str(), Point(displayList[i].rect.x+10, displayList[i].rect.y+70), FONT_HERSHEY_PLAIN, 1.5, rectColor);
}
}
}
// Don't update to next frame if paused to prevent
// objects missing from this frame to be aged out
if (!pause)
binTrackingList.nextFrame();
if (!batchMode && printFrames && cap->VideoCap())
{
stringstream ss;
ss << cap->frameCounter();
ss << '/';
ss << cap->VideoCap()->get(CV_CAP_PROP_FRAME_COUNT);
putText(frame, ss.str(), Point(frame.cols - 15 * ss.str().length(), 20), FONT_HERSHEY_PLAIN, 1.5, Scalar(0,0,255));
}
if (frameTicksIndex >= frameTicksLength)
{
// Display if GUI is up or print every frameTicksLength frames
if (!batchMode || ((frameTicksIndex % frameTicksLength) == 0))
{
double sum = 0;
for (size_t i = 0; i < frameTicksLength; i++)
sum += frameTicks[i];
sum /= frameTicksLength;
stringstream ss;
if (batchMode)
{
ss << cap->frameCounter();
ss << '/';
ss << cap->VideoCap()->get(CV_CAP_PROP_FRAME_COUNT);
ss << " : ";
}
ss.precision(3);
ss << 1.0/sum;
ss << " FPS";
if (!batchMode)
putText(frame, ss.str(), Point(frame.cols - 15 * ss.str().length(), 50), FONT_HERSHEY_PLAIN, 1.5, Scalar(0,0,255));
else
cout << ss.str() << endl;
}
}
// Put an A on the screen if capture-all is enabled so
// users can keep track of that toggle's mode
if (!batchMode && captureAll)
putText(frame, "A", Point(25,25), FONT_HERSHEY_PLAIN, 2.5, Scalar(0, 255, 255));
if (!batchMode)
{
//-- Show what you got
imshow( windowName, frame );
// Process user IO
char c = waitKey(5);
if( c == 'c' ) { break; } // exit
else if( c == 'q' ) { break; } // exit
else if( c == 27 ) { break; } // exit
else if( c == ' ') { pause = !pause; }
else if( c == 'f') // advance to next frame
{
cap->getNextFrame(false, frame);
}
else if (c == 'A') // toggle capture-all
{
captureAll = !captureAll;
}
else if (c == 't') // toggle tracking info display
{
tracking = !tracking;
}
else if (c == 'a') // save all detected images
{
Mat frameCopy;
cap->getNextFrame(true, frameCopy);
for (size_t index = 0; index < detectRects.size(); index++)
writeImage(frameCopy, detectRects, index, capPath.c_str(), cap->frameCounter());
}
else if (c == 'p') // print frame number to screen
{
cout << cap->frameCounter() << endl;
}
else if (c == 'P')
{
printFrames = !printFrames;
}
else if (c == 'G') // toggle CPU/GPU mode
{
if (gpuModeNext == GPU_MODE_GPU)
gpuModeNext = GPU_MODE_CPU;
else
gpuModeNext = GPU_MODE_GPU;
}
else if (isdigit(c)) // save a single detected image
{
Mat frameCopy;
cap->getNextFrame(true, frameCopy);
writeImage(frameCopy, detectRects, c - '0', capPath.c_str(), cap->frameCounter());
}
}
if (captureAll && detectRects.size())
{
Mat frameCopy;
cap->getNextFrame(true, frameCopy);
for (size_t index = 0; index < detectRects.size(); index++)
writeImage(frameCopy, detectRects, index, capPath.c_str(), cap->frameCounter());
}
endTick = getTickCount();
frameTicks[frameTicksIndex++ % frameTicksLength] = (double)(endTick - startTick) / getTickFrequency();
}
return 0;
}
void writeImage(const Mat &frame, const vector<Rect> &rects, size_t index, const char *path, int frameCounter)
{
if (index < rects.size())
{
Mat image = frame(rects[index]);
// Create filename, save image
stringstream fn;
fn << path;
fn << "_";
fn << frameCounter;
fn << "_";
fn << index;
imwrite(fn.str().substr(fn.str().rfind('\\')+1) + ".png", image);
// Save grayscale equalized version
Mat frameGray;
cvtColor( image, frameGray, CV_BGR2GRAY );
equalizeHist( frameGray, frameGray );
imwrite(fn.str().substr(fn.str().rfind('\\')+1) + "_g.png", frameGray);
// Save 20x20 version of the same image
Mat smallImg;
resize(image, smallImg, Size(20,20));
imwrite(fn.str().substr(fn.str().rfind('\\')+1) + "_s.png", smallImg);
// Save grayscale equalized version of small image
cvtColor( smallImg, frameGray, CV_BGR2GRAY );
equalizeHist( frameGray, frameGray );
imwrite(fn.str().substr(fn.str().rfind('\\')+1) + "_g_s.png", frameGray);
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include "Limonp/ArgvContext.hpp"
#include "MPSegment.hpp"
#include "HMMSegment.hpp"
#include "MixSegment.hpp"
using namespace CppJieba;
void cut(const ISegment * seg, const char * const filePath)
{
ifstream ifile(filePath);
vector<string> res;
string line;
while(getline(ifile, line))
{
if(!line.empty())
{
res.clear();
if(!seg->cut(line, res))
{
LogError("seg cut failed.");
}
else
{
print(join(res.begin(), res.end(), "/"));
}
}
}
}
int main(int argc, char ** argv)
{
if(argc < 2)
{
cout<<"usage: \n\t"<<argv[0]<<" [options] <filename>\n"
<<"options:\n"
<<"\t--algorithm\tSupported methods are [cutDAG, cutHMM, cutMix] for now. \n\t\t\tIf not specified, the default is cutMix\n"
<<"\t--dictpath\tsee example\n"
<<"\t--modelpath\tsee example\n"
<<"example:\n"
<<"\t"<<argv[0]<<" testlines.utf8 --dictpath dicts/jieba.dict.utf8\n"
<<"\t"<<argv[0]<<" testlines.utf8 --modelpath dicts/hmm_model.utf8 --algorithm cutHMM\n"
<<"\t"<<argv[0]<<" testlines.utf8 --dictpath dicts/jieba.dict.utf8 --modelpath dicts/hmm_model.utf8 --algorithm cutMix\n"
<<endl;
return EXIT_FAILURE;
}
ArgvContext arg(argc, argv);
string dictPath = arg["--dictpath"];
string modelPath = arg["--modelpath"];
string algorithm = arg["--algorithm"];
if("cutHMM" == algorithm)
{
HMMSegment seg;
if(!seg.init(modelPath.c_str()))
{
cout<<"seg init failed."<<endl;
return EXIT_FAILURE;
}
cut(&seg, arg[1].c_str());
seg.dispose();
}
else if("cutDAG" == algorithm)
{
MPSegment seg;
if(!seg.init(dictPath.c_str()))
{
cout<<"seg init failed."<<endl;
return false;
}
cut(&seg, arg[1].c_str());
seg.dispose();
}
else
{
MixSegment seg;
if(!seg.init(dictPath.c_str(), modelPath.c_str()))
{
cout<<"seg init failed."<<endl;
return EXIT_FAILURE;
}
cut(&seg, arg[1].c_str());
seg.dispose();
}
return EXIT_SUCCESS;
}
<commit_msg>modify segment.cpp for example<commit_after>#include <iostream>
#include <fstream>
#include "Limonp/ArgvContext.hpp"
#include "MPSegment.hpp"
#include "HMMSegment.hpp"
#include "MixSegment.hpp"
using namespace CppJieba;
void cut(const ISegment * seg, const char * const filePath)
{
ifstream ifile(filePath);
vector<string> res;
string line;
while(getline(ifile, line))
{
if(!line.empty())
{
res.clear();
if(!seg->cut(line, res))
{
LogError("seg cut failed.");
}
else
{
print(join(res.begin(), res.end(), "/"));
}
}
}
}
int main(int argc, char ** argv)
{
if(argc < 2)
{
cout<<"usage: \n\t"<<argv[0]<<" [options] <filename>\n"
<<"options:\n"
<<"\t--algorithm\tSupported methods are [cutDAG, cutHMM, cutMix] for now. \n\t\t\tIf not specified, the default is cutMix\n"
<<"\t--dictpath\tsee example\n"
<<"\t--modelpath\tsee example\n"
<<"example:\n"
<<"\t"<<argv[0]<<" ../test/testlines.utf8 --dictpath ../dicts/jieba.dict.utf8 --algorithm cutDAG\n"
<<"\t"<<argv[0]<<" ../test/testlines.utf8 --modelpath ../dicts/hmm_model.utf8 --algorithm cutHMM\n"
<<"\t"<<argv[0]<<" ../test/testlines.utf8 --dictpath ../dicts/jieba.dict.utf8 --modelpath dicts/hmm_model.utf8 --algorithm cutMix\n"
<<endl;
return EXIT_FAILURE;
}
ArgvContext arg(argc, argv);
string dictPath = arg["--dictpath"];
string modelPath = arg["--modelpath"];
string algorithm = arg["--algorithm"];
if("cutHMM" == algorithm)
{
HMMSegment seg;
if(!seg.init(modelPath.c_str()))
{
cout<<"seg init failed."<<endl;
return EXIT_FAILURE;
}
cut(&seg, arg[1].c_str());
seg.dispose();
}
else if("cutDAG" == algorithm)
{
MPSegment seg;
if(!seg.init(dictPath.c_str()))
{
cout<<"seg init failed."<<endl;
return false;
}
cut(&seg, arg[1].c_str());
seg.dispose();
}
else
{
MixSegment seg;
if(!seg.init(dictPath.c_str(), modelPath.c_str()))
{
cout<<"seg init failed."<<endl;
return EXIT_FAILURE;
}
cut(&seg, arg[1].c_str());
seg.dispose();
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "V4LCameraSettingsManager.h"
extern "C"
{
#include <linux/videodev2.h>
#include <linux/uvcvideo.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <linux/usb/video.h>
}
#define LOG "[CameraHandler:" << __LINE__ << ", Camera: " << cameraName << "] "
V4LCameraSettingsManager::V4LCameraSettingsManager()
: error_count(0)
{
}
int V4LCameraSettingsManager::getSingleCameraParameterRaw(int cameraFd, const std::string& cameraName, int parameterID)
{
struct v4l2_queryctrl queryctrl;
queryctrl.id = parameterID;
if (int errCode = ioctl(cameraFd, VIDIOC_QUERYCTRL, &queryctrl) < 0)
{
std::cerr << LOG << "VIDIOC_QUERYCTRL failed: " << strerror(errCode) << std::endl;
return -1;
}
if (queryctrl.flags & V4L2_CTRL_FLAG_DISABLED)
{
std::cerr << LOG << "not getting camera parameter since it is not available" << std::endl;
return -1; // not available
}
if (queryctrl.type != V4L2_CTRL_TYPE_BOOLEAN && queryctrl.type != V4L2_CTRL_TYPE_INTEGER && queryctrl.type != V4L2_CTRL_TYPE_MENU)
{
std::cerr << LOG << "not getting camera parameter since it is not supported" << std::endl;
return -1; // not supported
}
struct v4l2_control control_g;
control_g.id = parameterID;
// max 20 trials
int errorOccured = xioctl(cameraFd, VIDIOC_G_CTRL, &control_g);
if (hasIOError(cameraName, errorOccured, errno, false))
{
return -1;
}
else
{
return control_g.value;
}
}
bool V4LCameraSettingsManager::setSingleCameraParameterRaw(int cameraFd, const std::string& cameraName, int parameterID, const std::string& parameterName, int value)
{
if (parameterID < 0)
{
return false;
}
struct v4l2_queryctrl queryctrl;
memset(&queryctrl, 0, sizeof(queryctrl));
queryctrl.id = parameterID;
if (int errCode = xioctl(cameraFd, VIDIOC_QUERYCTRL, &queryctrl) < 0)
{
std::cerr << LOG << "VIDIOC_QUERYCTRL for parameter " << parameterName << " failed with code " << errCode << " " << strerror(errCode) << std::endl;
return false;
}
if (queryctrl.flags & V4L2_CTRL_FLAG_DISABLED)
{
std::cerr << LOG << "V4L2_CTRL_FLAG_DISABLED failed" << std::endl;
return false; // not available
}
if (queryctrl.type != V4L2_CTRL_TYPE_BOOLEAN && queryctrl.type != V4L2_CTRL_TYPE_INTEGER && queryctrl.type != V4L2_CTRL_TYPE_MENU)
{
std::cerr << LOG << "V4L2_CTRL_FLAG_DISABLED failed" << std::endl;
return false; // not supported
}
// clip value
if (value < queryctrl.minimum)
{
std::cout << LOG << "Clipping control value " << parameterName << " from " << value << " to " << queryctrl.minimum << std::endl;
value = queryctrl.minimum;
}
if (value > queryctrl.maximum)
{
std::cout << LOG << "Clipping control value " << parameterName << " from " << value << " to " << queryctrl.maximum << std::endl;
value = queryctrl.maximum;
}
struct v4l2_control control_s;
control_s.id = parameterID;
control_s.value = value;
std::cout << LOG << "Setting control value " << parameterName << " to " << value << std::endl;
int error = xioctl(cameraFd, VIDIOC_S_CTRL, &control_s);
return !hasIOError(cameraName, error, errno, false);
}
bool V4LCameraSettingsManager::setRawIfChanged(int cameraFd, const std::string& cameraName, int parameterID,
const std::string& parameterName, int value, int &bufferedValue, bool force)
{
if ((force || bufferedValue != value) &&
setSingleCameraParameterRaw(cameraFd, cameraName, parameterID, parameterName, value))
{
bufferedValue = value;
return true;
}
return false;
}
// https://01.org/linuxgraphics/gfx-docs/drm/media/uapi/v4l/capture.c.html
int V4LCameraSettingsManager::xioctl(int fd, int request, void *arg) const
{
int r;
// TODO: possibly endless loop?
do
{
r = ioctl(fd, request, arg);
} while (-1 == r && EINTR == errno); // repeat if the call was interrupted
return r;
}
int32_t V4LCameraSettingsManager::getSingleCameraParameterUVC(int cameraFd, const std::string& cameraName,
uint8_t parameterSelector, const std::string& parameterName, uint16_t parameterDataSize)
{
struct uvc_xu_control_query queryctrl;
memset(&queryctrl, 0, sizeof(queryctrl));
// HACK: currently only maximum of 4-bytes is supported
assert(parameterDataSize <= sizeof(int32_t));
int32_t value;
queryctrl.unit = 3;
queryctrl.query = UVC_GET_CUR;
queryctrl.selector = parameterSelector;
queryctrl.size = parameterDataSize;
queryctrl.data = reinterpret_cast<uint8_t*>(&value);
int error = xioctl(cameraFd, UVCIOC_CTRL_QUERY, &queryctrl);
if (hasIOError(cameraName, error, errno, false, "get " + parameterName)) {
return -1;
} else {
return value;
}
}
bool V4LCameraSettingsManager::setSingleCameraParameterUVC(int cameraFd, const std::string& cameraName,
uint8_t parameterSelector, const std::string& parameterName, uint16_t data_size, int32_t value)
{
struct uvc_xu_control_query queryctrl;
queryctrl.unit = 3;
queryctrl.query = UVC_SET_CUR;
queryctrl.selector = parameterSelector;
queryctrl.size = data_size;
queryctrl.data = reinterpret_cast<uint8_t*>(&value);
int error = xioctl(cameraFd, UVCIOC_CTRL_QUERY, &queryctrl);
return !hasIOError(cameraName, error, errno, false, "set " + parameterName);
}
/*
// https://linuxtv.org/downloads/v4l-dvb-apis/v4l-drivers/uvcvideo.html
// https://elixir.bootlin.com/linux/latest/source/include/uapi/linux/uvcvideo.h#L61
struct uvc_xu_control_query {
__u8 unit; // Extension unit ID
__u8 selector; // Control selector
__u8 query; // Request code to send to the device (Video Class-Specific Request Code, defined in linux/usb/video.h A.8.)
__u16 size; // Control data size (in bytes)
__u8 __user *data; // Control value
};
*/
/*
int V4LCameraSettingsManager::querySingleCameraParameterUVC(int cameraFd, uint8_t query, uint8_t selector, void* data, uint16_t size)
{
struct uvc_xu_control_query query;
queryctrl.unit = 3;
queryctrl.selector = selector;
queryctrl.query = query;
queryctrl.size = size;
queryctrl.data = static_cast<uint8_t*>(data);
return xioctl(cameraFd, UVCIOC_CTRL_QUERY, &queryctrl);
}
*/
bool V4LCameraSettingsManager::hasIOError(const std::string& cameraName, int errOccured, int errNo, bool exitByIOError, const std::string& paramName) const
{
if (errOccured < 0 && errNo != EAGAIN)
{
std::cout << LOG << paramName << " failed with errno " << errNo << " (" << strerror(errNo) << ") >> exiting" << std::endl;
if (exitByIOError)
{
assert(errOccured >= 0);
}
return true;
}
return false;
}<commit_msg>output for setSingleCameraParameterUVC and getSingleCameraParameterUVC<commit_after>#include "V4LCameraSettingsManager.h"
extern "C"
{
#include <linux/videodev2.h>
#include <linux/uvcvideo.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <linux/usb/video.h>
}
#define LOG "[CameraHandler:" << __LINE__ << ", Camera: " << cameraName << "] "
V4LCameraSettingsManager::V4LCameraSettingsManager()
: error_count(0)
{
}
int V4LCameraSettingsManager::getSingleCameraParameterRaw(int cameraFd, const std::string& cameraName, int parameterID)
{
struct v4l2_queryctrl queryctrl;
queryctrl.id = parameterID;
if (int errCode = ioctl(cameraFd, VIDIOC_QUERYCTRL, &queryctrl) < 0)
{
std::cerr << LOG << "VIDIOC_QUERYCTRL failed: " << strerror(errCode) << std::endl;
return -1;
}
if (queryctrl.flags & V4L2_CTRL_FLAG_DISABLED)
{
std::cerr << LOG << "not getting camera parameter since it is not available" << std::endl;
return -1; // not available
}
if (queryctrl.type != V4L2_CTRL_TYPE_BOOLEAN && queryctrl.type != V4L2_CTRL_TYPE_INTEGER && queryctrl.type != V4L2_CTRL_TYPE_MENU)
{
std::cerr << LOG << "not getting camera parameter since it is not supported" << std::endl;
return -1; // not supported
}
struct v4l2_control control_g;
control_g.id = parameterID;
// max 20 trials
int errorOccured = xioctl(cameraFd, VIDIOC_G_CTRL, &control_g);
if (hasIOError(cameraName, errorOccured, errno, false))
{
return -1;
}
else
{
return control_g.value;
}
}
bool V4LCameraSettingsManager::setSingleCameraParameterRaw(int cameraFd, const std::string& cameraName, int parameterID, const std::string& parameterName, int value)
{
if (parameterID < 0)
{
return false;
}
struct v4l2_queryctrl queryctrl;
memset(&queryctrl, 0, sizeof(queryctrl));
queryctrl.id = parameterID;
if (int errCode = xioctl(cameraFd, VIDIOC_QUERYCTRL, &queryctrl) < 0)
{
std::cerr << LOG << "VIDIOC_QUERYCTRL for parameter " << parameterName << " failed with code " << errCode << " " << strerror(errCode) << std::endl;
return false;
}
if (queryctrl.flags & V4L2_CTRL_FLAG_DISABLED)
{
std::cerr << LOG << "V4L2_CTRL_FLAG_DISABLED failed" << std::endl;
return false; // not available
}
if (queryctrl.type != V4L2_CTRL_TYPE_BOOLEAN && queryctrl.type != V4L2_CTRL_TYPE_INTEGER && queryctrl.type != V4L2_CTRL_TYPE_MENU)
{
std::cerr << LOG << "V4L2_CTRL_FLAG_DISABLED failed" << std::endl;
return false; // not supported
}
// clip value
if (value < queryctrl.minimum)
{
std::cout << LOG << "Clipping control value " << parameterName << " from " << value << " to " << queryctrl.minimum << std::endl;
value = queryctrl.minimum;
}
if (value > queryctrl.maximum)
{
std::cout << LOG << "Clipping control value " << parameterName << " from " << value << " to " << queryctrl.maximum << std::endl;
value = queryctrl.maximum;
}
struct v4l2_control control_s;
control_s.id = parameterID;
control_s.value = value;
std::cout << LOG << "Setting control value " << parameterName << " to " << value << std::endl;
int error = xioctl(cameraFd, VIDIOC_S_CTRL, &control_s);
return !hasIOError(cameraName, error, errno, false);
}
bool V4LCameraSettingsManager::setRawIfChanged(int cameraFd, const std::string& cameraName, int parameterID,
const std::string& parameterName, int value, int &bufferedValue, bool force)
{
if ((force || bufferedValue != value) &&
setSingleCameraParameterRaw(cameraFd, cameraName, parameterID, parameterName, value))
{
bufferedValue = value;
return true;
}
return false;
}
// https://01.org/linuxgraphics/gfx-docs/drm/media/uapi/v4l/capture.c.html
int V4LCameraSettingsManager::xioctl(int fd, int request, void *arg) const
{
int r;
// TODO: possibly endless loop?
do
{
r = ioctl(fd, request, arg);
} while (-1 == r && EINTR == errno); // repeat if the call was interrupted
return r;
}
int32_t V4LCameraSettingsManager::getSingleCameraParameterUVC(int cameraFd, const std::string& cameraName,
uint8_t parameterSelector, const std::string& parameterName, uint16_t parameterDataSize)
{
struct uvc_xu_control_query queryctrl;
memset(&queryctrl, 0, sizeof(queryctrl));
// HACK: currently only maximum of 4-bytes is supported
assert(parameterDataSize <= sizeof(int32_t));
int32_t value;
queryctrl.unit = 3;
queryctrl.query = UVC_GET_CUR;
queryctrl.selector = parameterSelector;
queryctrl.size = parameterDataSize;
queryctrl.data = reinterpret_cast<uint8_t*>(&value);
int error = xioctl(cameraFd, UVCIOC_CTRL_QUERY, &queryctrl);
std::cout << cameraName << ": " << parameterName << " = " << ((uint16_t)value) << std::endl;
if (hasIOError(cameraName, error, errno, false, "get " + parameterName)) {
return -1;
} else {
return value;
}
}
bool V4LCameraSettingsManager::setSingleCameraParameterUVC(int cameraFd, const std::string& cameraName,
uint8_t parameterSelector, const std::string& parameterName, uint16_t data_size, int32_t value)
{
struct uvc_xu_control_query queryctrl;
queryctrl.unit = 3;
queryctrl.query = UVC_SET_CUR;
queryctrl.selector = parameterSelector;
queryctrl.size = data_size;
queryctrl.data = reinterpret_cast<uint8_t*>(&value);
std::cout << LOG << "Setting control value " << parameterName << " to " << value << std::endl;
int error = xioctl(cameraFd, UVCIOC_CTRL_QUERY, &queryctrl);
return !hasIOError(cameraName, error, errno, false, "set " + parameterName);
}
/*
// https://linuxtv.org/downloads/v4l-dvb-apis/v4l-drivers/uvcvideo.html
// https://elixir.bootlin.com/linux/latest/source/include/uapi/linux/uvcvideo.h#L61
struct uvc_xu_control_query {
__u8 unit; // Extension unit ID
__u8 selector; // Control selector
__u8 query; // Request code to send to the device (Video Class-Specific Request Code, defined in linux/usb/video.h A.8.)
__u16 size; // Control data size (in bytes)
__u8 __user *data; // Control value
};
*/
/*
int V4LCameraSettingsManager::querySingleCameraParameterUVC(int cameraFd, uint8_t query, uint8_t selector, void* data, uint16_t size)
{
struct uvc_xu_control_query query;
queryctrl.unit = 3;
queryctrl.selector = selector;
queryctrl.query = query;
queryctrl.size = size;
queryctrl.data = static_cast<uint8_t*>(data);
return xioctl(cameraFd, UVCIOC_CTRL_QUERY, &queryctrl);
}
*/
bool V4LCameraSettingsManager::hasIOError(const std::string& cameraName, int errOccured, int errNo, bool exitByIOError, const std::string& paramName) const
{
if (errOccured < 0 && errNo != EAGAIN)
{
std::cout << LOG << paramName << " failed with errno " << errNo << " (" << strerror(errNo) << ") >> exiting" << std::endl;
if (exitByIOError)
{
assert(errOccured >= 0);
}
return true;
}
return false;
}<|endoftext|> |
<commit_before>#include <chrono>
#include <iostream>
void if_else_benchmark() {
std::cout << "If Else Bench\n";
int array[] = {1, 3, 5, 7, 9, 11, 13, 17, 18};
for (auto x : array) {
if (x == 1) {
std::cout << "The number is 1: " << x << "\n";
} else if (x == 3) {
std::cout << "The number is 3: " << x << "\n";
} else if (x == 5) {
std::cout << "The number is 5: " << x << "\n";
} else if (x == 7) {
std::cout << "The number is 7: " << x << "\n";
} else if (x == 9) {
std::cout << "The number is 9: " << x << "\n";
} else if (x == 11) {
std::cout << "The number is 11: " << x << "\n";
} else if (x == 13) {
std::cout << "The number is 13: " << x << "\n";
} else if (x == 17) {
std::cout << "The number is 17: " << x << "\n";
} else {
std::cout << "The number is 18: " << x << "\n";
}
}
}
void switch_benchmark() {
std::cout << "Switch Bench\n";
int array[] = {1, 3, 5, 7, 9, 11, 13, 17, 18};
for (auto x : array) {
switch (x) {
case 1: {
std::cout << "The number is 1: " << x << "\n";
} break;
case 3: {
std::cout << "The number is 3: " << x << "\n";
} break;
case 5: {
std::cout << "The number is 5: " << x << "\n";
} break;
case 7: {
std::cout << "The number is 7: " << x << "\n";
} break;
case 9: {
std::cout << "The number is 9: " << x << "\n";
} break;
case 11: {
std::cout << "The number is 11: " << x << "\n";
} break;
case 13: {
std::cout << "The number is 13: " << x << "\n";
} break;
case 17: {
std::cout << "The number is 17: " << x << "\n";
} break;
default: {
std::cout << "The number is 18: " << x << "\n";
}
}
}
}
void clock_time(std::chrono::steady_clock::time_point start, std::chrono::steady_clock::time_point end) {
std::chrono::duration<double> elapsed_seconds = end - start;
std::cout << "elapsed time: " << elapsed_seconds.count() << "s\n";
std::cout << "elapsed time: "
<< std::chrono::duration_cast<std::chrono::nanoseconds>(elapsed_seconds).count()
<< "ns\n";
}
int main(int argc, char const* argv[]) {
auto switch_start = std::chrono::steady_clock::now();
switch_benchmark();
auto switch_end = std::chrono::steady_clock::now();
clock_time(switch_start, switch_end);
auto if_else_start = std::chrono::steady_clock::now();
if_else_benchmark();
auto if_else_end = std::chrono::steady_clock::now();
clock_time(if_else_start, if_else_end);
return 0;
}
<commit_msg>Update switch_bench.cpp<commit_after>#include <chrono>
#include <iostream>
void if_else_benchmark() {
std::cout << "If Else Bench\n";
int array[] = {1, 3, 5, 7, 9, 11, 13, 17, 18};
for (auto x : array) {
if (x == 1) {
std::cout << "The number is 1: " << x << "\n";
} else if (x == 3) {
std::cout << "The number is 3: " << x << "\n";
} else if (x == 5) {
std::cout << "The number is 5: " << x << "\n";
} else if (x == 7) {
std::cout << "The number is 7: " << x << "\n";
} else if (x == 9) {
std::cout << "The number is 9: " << x << "\n";
} else if (x == 11) {
std::cout << "The number is 11: " << x << "\n";
} else if (x == 13) {
std::cout << "The number is 13: " << x << "\n";
} else if (x == 17) {
std::cout << "The number is 17: " << x << "\n";
} else {
std::cout << "The number is 18: " << x << "\n";
}
}
}
void switch_benchmark() {
std::cout << "Switch Bench\n";
int array[] = {1, 3, 5, 7, 9, 11, 13, 17, 18};
for (auto x : array) {
switch (x) {
case 1: {
std::cout << "The number is 1: " << x << "\n";
} break;
case 3: {
std::cout << "The number is 3: " << x << "\n";
} break;
case 5: {
std::cout << "The number is 5: " << x << "\n";
} break;
case 7: {
std::cout << "The number is 7: " << x << "\n";
} break;
case 9: {
std::cout << "The number is 9: " << x << "\n";
} break;
case 11: {
std::cout << "The number is 11: " << x << "\n";
} break;
case 13: {
std::cout << "The number is 13: " << x << "\n";
} break;
case 17: {
std::cout << "The number is 17: " << x << "\n";
} break;
default: {
std::cout << "The number is 18: " << x << "\n";
}
}
}
}
void clock_time(std::chrono::steady_clock::time_point start,
std::chrono::steady_clock::time_point end) {
std::chrono::duration<double> elapsed_seconds = end - start;
std::cout << "elapsed time: " << elapsed_seconds.count() << "s\n";
std::cout << "elapsed time: "
<< std::chrono::duration_cast<std::chrono::nanoseconds>(elapsed_seconds).count()
<< "ns\n";
}
int main(int argc, char const* argv[]) {
auto switch_start = std::chrono::steady_clock::now();
switch_benchmark();
auto switch_end = std::chrono::steady_clock::now();
clock_time(switch_start, switch_end);
auto if_else_start = std::chrono::steady_clock::now();
if_else_benchmark();
auto if_else_end = std::chrono::steady_clock::now();
clock_time(if_else_start, if_else_end);
return 0;
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <osmesa.h>
#include <conio.h> // For kbhit, getch, textmode (console access)
#include <dpmi.h> // For __dpmi_int (mouse access)
#include <go32.h> // For _dos_ds (VRAM access)
#include <sys/movedata.h> // For movedata (VRAM access)
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <GL/glu.h> // GLU = OpenGL utility library
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <cstdio>
#include <assert.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <string.h>
#include <memory>
#include <iostream>
#include <map>
#include <array>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include "NativeBitmap.h"
#include "SoundClip.h"
#include "SoundUtils.h"
#include "SoundListener.h"
#include "SoundEmitter.h"
#include "IFileLoaderDelegate.h"
#include "Vec2i.h"
#include "NativeBitmap.h"
#include "IMapElement.h"
#include "CTeam.h"
#include "CActor.h"
#include "CGameDelegate.h"
#include "CMap.h"
#include "IRenderer.h"
#include "NoudarDungeonSnapshot.h"
#include "GameNativeAPI.h"
#include "WindowOperations.h"
#include "Common.h"
#include "LoadPNG.h"
namespace PC {
const unsigned W = 320, H = 200, mode = 0x10F; // resolution & BIOS mode#
unsigned ImageBuffer[W*H];
unsigned reverseBuffer[W*H];
int selector;
void Init() // Initialize graphics
{
__dpmi_regs regs = { };
regs.x.ax = 0x4F02;
regs.x.bx = 0x4000 | mode;
__dpmi_int(0x10, ®s);
// Map the video memory into memory
__dpmi_meminfo meminfo;
meminfo.address = 0xC0000000ul; // DOSBox's S3 video memory
meminfo.size = PC::W * PC::H * 4;
__dpmi_physical_address_mapping(&meminfo);
__dpmi_lock_linear_region(&meminfo);
selector = __dpmi_allocate_ldt_descriptors(1);
__dpmi_set_segment_base_address(selector, meminfo.address);
__dpmi_set_segment_limit(selector, ((meminfo.size+4095)&~4095)-1);
}
void Render() // Update the displayed screen
{
int fullSize = 320 * 200;
for ( int y = 100; y < 200; ++y ) {
std::copy(ImageBuffer + (320/4) + (320*(y-1)), ImageBuffer - (320/4) + (320*(y)), reverseBuffer + (20) + ( fullSize ) - (320 * 2 * (y-100) ) ) ;
std::copy(ImageBuffer + (320/4) + (320*(y-1)), ImageBuffer - (320/4) + (320*(y)), reverseBuffer + (20) + ( fullSize ) + 320 - (320 * 2 * (y-100) ) ) ;
}
movedata( _my_ds(), (long)(&reverseBuffer) + (320/4), selector, 0, -(320/4 ) + sizeof(reverseBuffer) );
}
void Close() // End graphics
{
textmode(C80); // Set textmode again.
}
}
const int winWidth = 320, winHeight = 200;
bool done = false;
bool isActive = false;
std::vector <std::shared_ptr<odb::NativeBitmap>> loadTextures() {
std::vector<std::shared_ptr<odb::NativeBitmap>> toReturn;
toReturn.push_back( loadPNG( "res/grass.ppm") );
toReturn.push_back( loadPNG( "res/stonef1.ppm") );
toReturn.push_back( loadPNG( "res/bricks.ppm") );
toReturn.push_back( loadPNG( "res/arch.ppm") );
toReturn.push_back( loadPNG( "res/bars.ppm") );
toReturn.push_back( loadPNG( "res/begin.ppm") );
toReturn.push_back( loadPNG( "res/exit.ppm") );
toReturn.push_back( loadPNG( "res/bricks2.ppm") );
toReturn.push_back( loadPNG( "res/bricks3.ppm") );
toReturn.push_back( loadPNG( "res/foe0.ppm") );
toReturn.push_back( loadPNG( "res/foe1.ppm") );
toReturn.push_back( loadPNG( "res/foe2.ppm") );
toReturn.push_back( loadPNG( "res/foe3.ppm") );
toReturn.push_back( loadPNG( "res/foe4.ppm") );
toReturn.push_back( loadPNG( "res/foe5.ppm") );
toReturn.push_back( loadPNG( "res/crusad0.ppm") );
toReturn.push_back( loadPNG( "res/crusad1.ppm") );
toReturn.push_back( loadPNG( "res/crusad2.ppm") );
toReturn.push_back( loadPNG( "res/shadow.ppm") );
toReturn.push_back( loadPNG( "res/ceilin.ppm") );
toReturn.push_back( loadPNG( "res/ceigdr.ppm") );
toReturn.push_back( loadPNG( "res/ceigbgn.ppm") );
toReturn.push_back( loadPNG( "res/ceilend.ppm") );
toReturn.push_back( loadPNG( "res/splat0.ppm") );
toReturn.push_back( loadPNG( "res/splat1.ppm") );
toReturn.push_back( loadPNG( "res/splat2.ppm") );
toReturn.push_back( loadPNG( "res/ceilbar.ppm") );
toReturn.push_back( loadPNG( "res/clouds.ppm"));
toReturn.push_back( loadPNG( "res/stngrsf.ppm"));
toReturn.push_back( loadPNG( "res/grsstnf.ppm"));
toReturn.push_back( loadPNG( "res/stngrsn.ppm"));
toReturn.push_back( loadPNG( "res/grsstnn.ppm"));
toReturn.push_back( loadPNG( "res/cross.ppm"));
return toReturn;
}
void initWindow() {
auto textures = loadTextures();
OSMesaContext om = OSMesaCreateContext(OSMESA_RGBA, NULL);
OSMesaMakeCurrent(om, PC::ImageBuffer, GL_UNSIGNED_BYTE, PC::W, PC::H);
PC::Init();
auto gVertexShader = "";
auto gFragmentShader = "";
setupGraphics(winWidth, winHeight, gVertexShader, gFragmentShader, textures);
auto soundListener = std::make_shared<odb::SoundListener>();
std::vector<std::shared_ptr<odb::SoundEmitter>> sounds;
std::string filenames[] {
"res/grasssteps.wav",
"res/stepsstones.wav",
"res/bgnoise.wav",
"res/monsterdamage.wav",
"res/monsterdead.wav",
"res/playerdamage.wav",
"res/playerdead.wav",
"res/swing.wav"
};
for ( auto filename : filenames ) {
FILE *file = fopen( filename.c_str(), "r");
auto soundClip = odb::makeSoundClipFrom( file );
sounds.push_back( std::make_shared<odb::SoundEmitter>(soundClip) );
}
setSoundEmitters( sounds, soundListener );
}
void tick() {
//if I want at least 10fps, I need my rendering and updates to take no more than 100ms, combined
gameLoopTick( 250 );
renderFrame( 250 );
PC::Render();
}
void setMainLoop() {
while ( !done ) {
while(kbhit())
switch(getch()) {
case 27: done = true; break;
case 'w':
moveUp();
break;
case 's':
moveDown();
break;
case 'd':
moveRight();
break;
case 'a':
moveLeft();
break;
case 'e':
rotateCameraRight();
break;
case 'q':
rotateCameraLeft();
break;
}
tick();
}
}
void destroyWindow() {
shutdown();
}
<commit_msg>Add graphics switching to text and scalling to fullscreen<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <osmesa.h>
#include <conio.h> // For kbhit, getch, textmode (console access)
#include <dpmi.h> // For __dpmi_int (mouse access)
#include <go32.h> // For _dos_ds (VRAM access)
#include <sys/movedata.h> // For movedata (VRAM access)
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <GL/glu.h> // GLU = OpenGL utility library
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <cstdio>
#include <assert.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <string.h>
#include <memory>
#include <iostream>
#include <map>
#include <array>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <pc.h>
#include "NativeBitmap.h"
#include "SoundClip.h"
#include "SoundUtils.h"
#include "SoundListener.h"
#include "SoundEmitter.h"
#include "IFileLoaderDelegate.h"
#include "Vec2i.h"
#include "NativeBitmap.h"
#include "IMapElement.h"
#include "CTeam.h"
#include "CActor.h"
#include "CGameDelegate.h"
#include "CMap.h"
#include "IRenderer.h"
#include "NoudarDungeonSnapshot.h"
#include "GameNativeAPI.h"
#include "WindowOperations.h"
#include "Common.h"
#include "LoadPNG.h"
bool inGraphics = true;
namespace PC {
const unsigned W = 320, H = 200, mode = 0x10F; // resolution & BIOS mode#
unsigned ImageBuffer[W*H];
unsigned reverseBuffer[W*H];
int selector;
void Init() // Initialize graphics
{
__dpmi_regs regs = { };
regs.x.ax = 0x4F02;
regs.x.bx = 0x4000 | mode;
__dpmi_int(0x10, ®s);
// Map the video memory into memory
__dpmi_meminfo meminfo;
meminfo.address = 0xC0000000ul; // DOSBox's S3 video memory
meminfo.size = PC::W * PC::H * 4;
__dpmi_physical_address_mapping(&meminfo);
__dpmi_lock_linear_region(&meminfo);
selector = __dpmi_allocate_ldt_descriptors(1);
__dpmi_set_segment_base_address(selector, meminfo.address);
__dpmi_set_segment_limit(selector, ((meminfo.size+4095)&~4095)-1);
}
void Render() // Update the displayed screen
{
int fullSize = 320 * 200;
for ( int y = 100; y < 200; ++y ) {
for ( int x = 80; x < 240; ++x ) {
auto origin = ImageBuffer[ (320 * y ) + x];
reverseBuffer[ 160 + ( (200 - (2 * ( (y - 100)) )) * 320 ) + (( 2 * x) ) + 20 ] = origin;
reverseBuffer[ 160 + ( (199 - (2 * ( (y - 100)) )) * 320 ) + (( 2 * x) ) + 19 ] = origin;
reverseBuffer[ 160 + ( (200 - (2 * ( (y - 100)) )) * 320 ) + (( 2 * x) ) + 19 ] = origin;
reverseBuffer[ 160 + ( (199 - (2 * ( (y - 100)) )) * 320 ) + (( 2 * x) ) + 20 ] = origin;
}
}
movedata( _my_ds(), (long)(&reverseBuffer) + (320/4), selector, 0, -(320/4 ) + sizeof(reverseBuffer) );
}
void Close() // End graphics
{
textmode(C80); // Set textmode again.
}
}
void setGraphics() {
inGraphics = true;
PC::Init();
}
void setTextMode() {
inGraphics = false;
__dpmi_regs r;
r.x.ax = 3;
__dpmi_int(0x10, &r);
}
const int winWidth = 320, winHeight = 200;
bool done = false;
bool isActive = false;
std::vector <std::shared_ptr<odb::NativeBitmap>> loadTextures() {
std::vector<std::shared_ptr<odb::NativeBitmap>> toReturn;
toReturn.push_back( loadPNG( "res/grass.ppm") );
toReturn.push_back( loadPNG( "res/stonef1.ppm") );
toReturn.push_back( loadPNG( "res/bricks.ppm") );
toReturn.push_back( loadPNG( "res/arch.ppm") );
toReturn.push_back( loadPNG( "res/bars.ppm") );
toReturn.push_back( loadPNG( "res/begin.ppm") );
toReturn.push_back( loadPNG( "res/exit.ppm") );
toReturn.push_back( loadPNG( "res/bricks2.ppm") );
toReturn.push_back( loadPNG( "res/bricks3.ppm") );
toReturn.push_back( loadPNG( "res/foe0.ppm") );
toReturn.push_back( loadPNG( "res/foe1.ppm") );
toReturn.push_back( loadPNG( "res/foe2.ppm") );
toReturn.push_back( loadPNG( "res/foe3.ppm") );
toReturn.push_back( loadPNG( "res/foe4.ppm") );
toReturn.push_back( loadPNG( "res/foe5.ppm") );
toReturn.push_back( loadPNG( "res/crusad0.ppm") );
toReturn.push_back( loadPNG( "res/crusad1.ppm") );
toReturn.push_back( loadPNG( "res/crusad2.ppm") );
toReturn.push_back( loadPNG( "res/shadow.ppm") );
toReturn.push_back( loadPNG( "res/ceilin.ppm") );
toReturn.push_back( loadPNG( "res/ceigdr.ppm") );
toReturn.push_back( loadPNG( "res/ceigbgn.ppm") );
toReturn.push_back( loadPNG( "res/ceilend.ppm") );
toReturn.push_back( loadPNG( "res/splat0.ppm") );
toReturn.push_back( loadPNG( "res/splat1.ppm") );
toReturn.push_back( loadPNG( "res/splat2.ppm") );
toReturn.push_back( loadPNG( "res/ceilbar.ppm") );
toReturn.push_back( loadPNG( "res/clouds.ppm"));
toReturn.push_back( loadPNG( "res/stngrsf.ppm"));
toReturn.push_back( loadPNG( "res/grsstnf.ppm"));
toReturn.push_back( loadPNG( "res/stngrsn.ppm"));
toReturn.push_back( loadPNG( "res/grsstnn.ppm"));
toReturn.push_back( loadPNG( "res/cross.ppm"));
return toReturn;
}
void initWindow() {
auto textures = loadTextures();
OSMesaContext om = OSMesaCreateContext(OSMESA_RGBA, NULL);
OSMesaMakeCurrent(om, PC::ImageBuffer, GL_UNSIGNED_BYTE, PC::W, PC::H);
PC::Init();
auto gVertexShader = "";
auto gFragmentShader = "";
setupGraphics(winWidth, winHeight, gVertexShader, gFragmentShader, textures);
auto soundListener = std::make_shared<odb::SoundListener>();
std::vector<std::shared_ptr<odb::SoundEmitter>> sounds;
std::string filenames[] {
"res/grasssteps.wav",
"res/stepsstones.wav",
"res/bgnoise.wav",
"res/monsterdamage.wav",
"res/monsterdead.wav",
"res/playerdamage.wav",
"res/playerdead.wav",
"res/swing.wav"
};
for ( auto filename : filenames ) {
FILE *file = fopen( filename.c_str(), "r");
auto soundClip = odb::makeSoundClipFrom( file );
sounds.push_back( std::make_shared<odb::SoundEmitter>(soundClip) );
}
setSoundEmitters( sounds, soundListener );
}
void tick() {
//if I want at least 10fps, I need my rendering and updates to take no more than 100ms, combined
if ( inGraphics ) {
gameLoopTick( 250 );
renderFrame( 250 );
PC::Render();
}
}
void setMainLoop() {
while ( !done ) {
while(kbhit())
switch(getch()) {
case 27: done = true; break;
case '1':
setGraphics();
break;
case '2':
setTextMode();
break;
case 'w':
moveUp();
break;
case 's':
moveDown();
break;
case 'd':
moveRight();
break;
case 'a':
moveLeft();
break;
case 'e':
rotateCameraRight();
break;
case 'q':
rotateCameraLeft();
break;
}
tick();
}
}
void destroyWindow() {
shutdown();
}
<|endoftext|> |
<commit_before>//@author A0097630B
#include "stdafx.h"
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include "task_field.h"
#include "edit_query.h"
using You::NLP::EDIT_QUERY;
namespace You {
namespace NLP {
namespace {
/// The format for displaying an EDIT_QUERY.
const boost::wformat STRING_FORMAT(L"Edit task #%1% (%2%)");
/// The format for displaying a field change.
const boost::wformat CHANGE_FIELD_FORMAT(L"%1% => %2%");
/// Converts the attachment actions to a string.
std::vector<std::wstring> getAttachmentActionsAsString(
const std::vector<EDIT_QUERY::ATTACHMENT_ACTION>& q) {
std::vector<std::wstring> result;
std::transform(begin(q), end(q), std::back_inserter(result),
[](const EDIT_QUERY::ATTACHMENT_ACTION& a) {
return boost::lexical_cast<std::wstring>(a);
});
return result;
}
/// Converts the changed fields to a string.
std::vector<std::wstring> getChangedFieldsAsString(const EDIT_QUERY& q) {
using You::NLP::TaskField;
std::vector<std::wstring> fields;
if (q.description) {
fields.emplace_back(
(boost::wformat(CHANGE_FIELD_FORMAT) %
TaskField::DESCRIPTION %
q.description.get()).str());
}
if (q.priority) {
fields.emplace_back(
(boost::wformat(CHANGE_FIELD_FORMAT) %
TaskField::PRIORITY %
q.priority.get()).str());
}
if (q.start) {
fields.emplace_back(
(boost::wformat(CHANGE_FIELD_FORMAT) %
TaskField::START %
q.start.get()).str());
}
if (q.deadline) {
fields.emplace_back(
(boost::wformat(CHANGE_FIELD_FORMAT) %
TaskField::DEADLINE %
q.deadline.get()).str());
}
if (q.complete) {
fields.emplace_back(
(boost::wformat(CHANGE_FIELD_FORMAT) %
TaskField::COMPLETE %
q.complete.get()).str());
}
if (q.childTask) {
fields.emplace_back(
(boost::wformat(CHANGE_FIELD_FORMAT) %
TaskField::SUBTASKS %
q.childTask.get()).str());
}
if (q.dependingTask) {
fields.emplace_back(
(boost::wformat(CHANGE_FIELD_FORMAT) %
TaskField::DEPENDENTS %
q.dependingTask.get()).str());
}
if (!q.attachments.empty()) {
fields.emplace_back(
(boost::wformat(CHANGE_FIELD_FORMAT) %
TaskField::ATTACHMENTS %
boost::algorithm::join(getAttachmentActionsAsString(q.attachments),
L", ")).str());
}
return fields;
}
} // namespace
std::wostream& operator<<(std::wostream& s, const EDIT_QUERY& q) {
return s << boost::wformat(STRING_FORMAT) % q.taskID %
boost::algorithm::join(getChangedFieldsAsString(q), L", ");
}
std::wostream& operator<<(std::wostream& s,
const EDIT_QUERY::ATTACHMENT_ACTION& a) {
return s <<
(a.add ? L"add" : L"remove") << L' ' <<
a.path;
}
bool EDIT_QUERY::operator==(const EDIT_QUERY& rhs) const {
if (taskID != rhs.taskID) {
return false;
}
return description == rhs.description &&
priority == rhs.priority &&
deadline == rhs.deadline &&
complete == rhs.complete &&
childTask == rhs.childTask &&
dependingTask == rhs.dependingTask &&
attachments.size() == rhs.attachments.size() &&
std::equal(
begin(attachments),
end(attachments),
begin(rhs.attachments));
}
bool EDIT_QUERY::ATTACHMENT_ACTION::operator==(
const ATTACHMENT_ACTION& rhs) const {
return add == rhs.add &&
path == rhs.path;
}
std::wstring ToString(const EDIT_QUERY& q) {
return boost::lexical_cast<std::wstring>(q);
}
} // namespace NLP
} // namespace You
<commit_msg>Fix broken comparison.<commit_after>//@author A0097630B
#include "stdafx.h"
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include "task_field.h"
#include "edit_query.h"
using You::NLP::EDIT_QUERY;
namespace You {
namespace NLP {
namespace {
/// The format for displaying an EDIT_QUERY.
const boost::wformat STRING_FORMAT(L"Edit task #%1% (%2%)");
/// The format for displaying a field change.
const boost::wformat CHANGE_FIELD_FORMAT(L"%1% => %2%");
/// Converts the attachment actions to a string.
std::vector<std::wstring> getAttachmentActionsAsString(
const std::vector<EDIT_QUERY::ATTACHMENT_ACTION>& q) {
std::vector<std::wstring> result;
std::transform(begin(q), end(q), std::back_inserter(result),
[](const EDIT_QUERY::ATTACHMENT_ACTION& a) {
return boost::lexical_cast<std::wstring>(a);
});
return result;
}
/// Converts the changed fields to a string.
std::vector<std::wstring> getChangedFieldsAsString(const EDIT_QUERY& q) {
using You::NLP::TaskField;
std::vector<std::wstring> fields;
if (q.description) {
fields.emplace_back(
(boost::wformat(CHANGE_FIELD_FORMAT) %
TaskField::DESCRIPTION %
q.description.get()).str());
}
if (q.priority) {
fields.emplace_back(
(boost::wformat(CHANGE_FIELD_FORMAT) %
TaskField::PRIORITY %
q.priority.get()).str());
}
if (q.start) {
fields.emplace_back(
(boost::wformat(CHANGE_FIELD_FORMAT) %
TaskField::START %
q.start.get()).str());
}
if (q.deadline) {
fields.emplace_back(
(boost::wformat(CHANGE_FIELD_FORMAT) %
TaskField::DEADLINE %
q.deadline.get()).str());
}
if (q.complete) {
fields.emplace_back(
(boost::wformat(CHANGE_FIELD_FORMAT) %
TaskField::COMPLETE %
q.complete.get()).str());
}
if (q.childTask) {
fields.emplace_back(
(boost::wformat(CHANGE_FIELD_FORMAT) %
TaskField::SUBTASKS %
q.childTask.get()).str());
}
if (q.dependingTask) {
fields.emplace_back(
(boost::wformat(CHANGE_FIELD_FORMAT) %
TaskField::DEPENDENTS %
q.dependingTask.get()).str());
}
if (!q.attachments.empty()) {
fields.emplace_back(
(boost::wformat(CHANGE_FIELD_FORMAT) %
TaskField::ATTACHMENTS %
boost::algorithm::join(getAttachmentActionsAsString(q.attachments),
L", ")).str());
}
return fields;
}
} // namespace
std::wostream& operator<<(std::wostream& s, const EDIT_QUERY& q) {
return s << boost::wformat(STRING_FORMAT) % q.taskID %
boost::algorithm::join(getChangedFieldsAsString(q), L", ");
}
std::wostream& operator<<(std::wostream& s,
const EDIT_QUERY::ATTACHMENT_ACTION& a) {
return s <<
(a.add ? L"add" : L"remove") << L' ' <<
a.path;
}
bool EDIT_QUERY::operator==(const EDIT_QUERY& rhs) const {
if (taskID != rhs.taskID) {
return false;
}
return description == rhs.description &&
priority == rhs.priority &&
start == rhs.start &&
deadline == rhs.deadline &&
complete == rhs.complete &&
childTask == rhs.childTask &&
dependingTask == rhs.dependingTask &&
attachments.size() == rhs.attachments.size() &&
std::equal(
begin(attachments),
end(attachments),
begin(rhs.attachments));
}
bool EDIT_QUERY::ATTACHMENT_ACTION::operator==(
const ATTACHMENT_ACTION& rhs) const {
return add == rhs.add &&
path == rhs.path;
}
std::wstring ToString(const EDIT_QUERY& q) {
return boost::lexical_cast<std::wstring>(q);
}
} // namespace NLP
} // namespace You
<|endoftext|> |
<commit_before>#include "utility.h"
/**
* @brief Gets time used in logs
* @return string representation of current date
* Format: [7.3.2016 21:54:59:382]
*/
std::string getTime(void)
{
timeval now;
gettimeofday(&now, 0);
tm *curr_time = localtime(&now.tv_sec);
std::ostringstream buff;
buff << "(" << curr_time->tm_mday << "." << curr_time->tm_mon+1 << "." << (curr_time->tm_year+1900) << " ";
if(curr_time->tm_hour<10){buff << "0";}
buff << curr_time->tm_hour << ":";
if(curr_time->tm_min<10){buff << "0";}
buff << curr_time->tm_min << ":";
if(curr_time->tm_sec<10){buff << "0";}
buff << curr_time->tm_sec << ":" << now.tv_usec/1000 << ")";
return buff.str();
}
/**
* @brief Gets filename from current date
* @details Log file filename encodes current date in format: yymmdd
* @return date encoded in string according to format
*/
std::string getFileNameByDate()
{
timeval now;
gettimeofday(&now, 0);
tm *curr_time = localtime(&now.tv_sec);
std::ostringstream buff;
buff << (curr_time->tm_year+1900);
if ( curr_time->tm_mon+1 < 10) { buff << "0";}
buff << curr_time->tm_mon+1;
if ( curr_time->tm_mday < 10) { buff << "0";}
buff << curr_time->tm_mday;
return buff.str();
}<commit_msg>Unified_logger: date is now in ISO 8601 format<commit_after>#include "utility.h"
/**
* @brief Gets time used in logs
* @return string representation of current date
* Format: [7.3.2016 21:54:59:382]
*/
std::string getTime(void)
{
timeval now;
gettimeofday(&now, 0);
tm *curr_time = localtime(&now.tv_sec);
std::ostringstream buff;
//buff << "(" << curr_time->tm_mday << "." << curr_time->tm_mon+1 << "." << (curr_time->tm_year+1900) << " ";
buff << "(" << (curr_time->tm_year+1900) << "-";
if(curr_time->tm_mon+1<10){buff << "0";}
buff << curr_time->tm_mon+1 << "-";
if(curr_time->tm_mday+1<10){buff << "0";}
buff << curr_time->tm_mday << " ";
if(curr_time->tm_hour<10){buff << "0";}
buff << curr_time->tm_hour << ":";
if(curr_time->tm_min<10){buff << "0";}
buff << curr_time->tm_min << ":";
if(curr_time->tm_sec<10){buff << "0";}
buff << curr_time->tm_sec << ":" << now.tv_usec/1000 << ")";
return buff.str();
}
/**
* @brief Gets filename from current date
* @details Log file filename encodes current date in format: yymmdd
* @return date encoded in string according to format
*/
std::string getFileNameByDate()
{
timeval now;
gettimeofday(&now, 0);
tm *curr_time = localtime(&now.tv_sec);
std::ostringstream buff;
buff << (curr_time->tm_year+1900);
if ( curr_time->tm_mon+1 < 10) { buff << "0";}
buff << curr_time->tm_mon+1;
if ( curr_time->tm_mday < 10) { buff << "0";}
buff << curr_time->tm_mday;
return buff.str();
}<|endoftext|> |
<commit_before>#include "io/synth.h"
#include "ts/ts.h"
#include "core/exception.h"
#include <opencv2/highgui.hpp>
using namespace std;
class SynthBarsTest : public testing::Test
{
protected:
virtual void SetUp()
{
to_ = SynthBars();
}
SynthBars to_; ///< test object
};
TEST_F(SynthBarsTest, Reset)
{
EXPECT_THROW(to_.Reset(3, 3, 0), ExceptionValueError);
for(int i=1; i<6; i++) {
to_.Reset(3, 3, i);
float angle = 0.f;
float delta = static_cast<float>(180.f/i);
for(int j=0; j<100; j++) {
EXPECT_FLOAT_EQ(to_.IndexToDeg(j), static_cast<float>(angle));
angle += delta;
if(angle >= 180.f) { angle = 0.f; }
}
}
}
TEST_F(SynthBarsTest, IndexToDegrees)
{
float angle = 0.f;
float delta = static_cast<float>(180.f/6.f);
for(int i=0; i<70; i++) {
EXPECT_FLOAT_EQ(to_.IndexToDeg(i), static_cast<float>(angle));
angle += delta;
if(angle >= 180.f) { angle = 0.f; }
}
EXPECT_NE(to_.IndexToDeg(0), to_.IndexToDeg(1)) << "No variation.";
EXPECT_NE(to_.IndexToDeg(0), to_.IndexToDeg(5)) << "No variation.";
EXPECT_FLOAT_EQ(to_.IndexToDeg(0), to_.IndexToDeg(6)) << "0 should equal 180";
}
TEST_F(SynthBarsTest, Next)
{
const int N=50;
const int ROWS=100;
const int COLS=100;
const int NB_VARIATIONS=6;
to_.Reset(ROWS, COLS, NB_VARIATIONS);
for(int i=0; i<N; i++) {
cv::Mat img, label;
to_.Next(img, label);
EXPECT_MAT_DIMS_EQ(img, cv::Mat1b(ROWS, COLS));
EXPECT_MAT_TYPE(img, CV_8U);
EXPECT_EQ(img.at<uchar>(ROWS/2, COLS/2), static_cast<uchar>(255));
EXPECT_MAT_DIMS_EQ(label, cv::Mat1f(1, 1));
EXPECT_MAT_TYPE(label, CV_32F);
EXPECT_IN_LCLOSED_ROPEN(label.at<float>(0), 0.f, 180.f);
}
}
/**
* @brief test that bar orientations are unifromly distributed
*/
TEST_F(SynthBarsTest, Uniform)
{
const int N=4e3;
const int ROWS=3;
const int COLS=3;
const int NB_VARIATIONS=4;
to_.Reset(ROWS, COLS, NB_VARIATIONS);
cv::Mat1f counts = cv::Mat1f::zeros(1, NB_VARIATIONS);
for(int i=0; i<N; i++) {
cv::Mat img, label;
to_.Next(img, label);
float angle = label.at<float>(0);
EXPECT_IN_LCLOSED_ROPEN(angle, 0, 180);
int bin = static_cast<int>(angle/180.f*NB_VARIATIONS);
EXPECT_LT(bin, NB_VARIATIONS);
counts(bin)++;
}
EXPECT_FLOAT_EQ(cv::sum(counts)(0), N);
cv::Mat1f hist_normalized = counts/static_cast<float>(N);
// check histogram is near uniform
cv::Mat m, s;
cv::meanStdDev(hist_normalized, m, s);
EXPECT_MAT_NEAR(m, cv::Mat1d(1, 1, 1.f/static_cast<double>(NB_VARIATIONS)), 1e-5);
EXPECT_MAT_NEAR(s, cv::Mat1d::zeros(1, 1), 1e-2);
}
/**
* @brief Spot-check bar lines
*/
TEST_F(SynthBarsTest, BarLines)
{
const int SIZE=28;
const int NB_VARIATIONS=4;
const float DELTA=180.f/NB_VARIATIONS;
cv::Mat1b variations_covered = cv::Mat1b::zeros(1, NB_VARIATIONS);
cv::Mat1b covered_enough = cv::Mat1b::ones(1, NB_VARIATIONS);
to_.Reset(SIZE, SIZE, NB_VARIATIONS);
const uchar ON=static_cast<uchar>(255);
const uchar OFF=static_cast<uchar>(0);
int i=0;
int MAX_ITERATIONS=50;
while(cv::countNonZero(covered_enough) > 0 && i < MAX_ITERATIONS) {
cv::Mat img, label;
to_.Next(img, label);
float angle = label.at<float>(0);
if(angle == 0.f) {
// horizontal line
for(int i=0; i<SIZE; i++) {
EXPECT_EQ(img.at<uchar>(SIZE/2, i), ON) << "No horizontal line.";
}
EXPECT_MAT_EQ(img.rowRange(0, 4), cv::Mat1b(4, SIZE, OFF));
EXPECT_MAT_EQ(img.rowRange(SIZE-4, SIZE), cv::Mat1b(4, SIZE, OFF));
}
else if(angle == 45.f) {
EXPECT_EQ(img.at<uchar>(0, 0), OFF) << "diagonal not /";
EXPECT_EQ(img.at<uchar>(SIZE-1, 0), ON) << "diagonal not /";
EXPECT_EQ(img.at<uchar>(0, SIZE-1), ON) << "diagonal not /";
EXPECT_EQ(img.at<uchar>(SIZE-1, SIZE-1), OFF) << "diagonal not /";
}
else if(angle == 90.f) {
// vertical line
for(int i=0; i<SIZE; i++) {
EXPECT_EQ(img.at<uchar>(i, SIZE/2), ON) << "No vertical line.";
}
EXPECT_MAT_EQ(img.colRange(0, 4), cv::Mat1b(SIZE, 4, OFF));
EXPECT_MAT_EQ(img.colRange(SIZE-4, SIZE), cv::Mat1b(SIZE, 4, OFF));
}
else if(angle == 135.f) {
EXPECT_EQ(img.at<uchar>(0, 0), ON) << "diagonal not \\";
EXPECT_EQ(img.at<uchar>(SIZE-1, 0), OFF) << "diagonal not \\";
EXPECT_EQ(img.at<uchar>(0, SIZE-1), OFF) << "diagonal not \\";
EXPECT_EQ(img.at<uchar>(SIZE-1, SIZE-1), ON) << "diagonal not \\";
}
EXPECT_EQ(img.at<uchar>(SIZE/2, SIZE/2), ON) << "not centered";
int bin = static_cast<int>(angle/DELTA);
variations_covered(bin)++;
cv::compare(variations_covered,
cv::Mat1b(1, NB_VARIATIONS, static_cast<uchar>(5)),
covered_enough, cv::CMP_LT);
}
EXPECT_FALSE(cv::countNonZero(covered_enough) > 0 && i < MAX_ITERATIONS)
<< "Insufficient coverage of orientation variations" << variations_covered;
}
TEST_F(SynthBarsTest, DISABLED_Display)
{
to_.Reset(100, 100, 6);
for(int i=0; i<10; i++) {
cv::Mat img, label;
to_.Next(img, label);
cv::imshow(FullTestName(test_info_), img);
cv::waitKey();
}
}
<commit_msg>test bar draw method<commit_after>#include "io/synth.h"
#include "ts/ts.h"
#include "core/exception.h"
#include <opencv2/highgui.hpp>
using namespace std;
class SynthBarsTest : public testing::Test
{
protected:
virtual void SetUp()
{
to_ = SynthBars();
}
SynthBars to_; ///< test object
};
TEST_F(SynthBarsTest, Reset)
{
EXPECT_THROW(to_.Reset(3, 3, 0), ExceptionValueError);
for(int i=1; i<6; i++) {
to_.Reset(3, 3, i);
float angle = 0.f;
float delta = static_cast<float>(180.f/i);
for(int j=0; j<100; j++) {
EXPECT_FLOAT_EQ(to_.IndexToDeg(j), static_cast<float>(angle));
angle += delta;
if(angle >= 180.f) { angle = 0.f; }
}
}
}
TEST_F(SynthBarsTest, IndexToDegrees)
{
float angle = 0.f;
float delta = static_cast<float>(180.f/6.f);
for(int i=0; i<70; i++) {
EXPECT_FLOAT_EQ(to_.IndexToDeg(i), static_cast<float>(angle));
angle += delta;
if(angle >= 180.f) { angle = 0.f; }
}
EXPECT_NE(to_.IndexToDeg(0), to_.IndexToDeg(1)) << "No variation.";
EXPECT_NE(to_.IndexToDeg(0), to_.IndexToDeg(5)) << "No variation.";
EXPECT_FLOAT_EQ(to_.IndexToDeg(0), to_.IndexToDeg(6)) << "0 should equal 180";
}
TEST_F(SynthBarsTest, Next)
{
const int N=50;
const int ROWS=100;
const int COLS=100;
const int NB_VARIATIONS=6;
to_.Reset(ROWS, COLS, NB_VARIATIONS);
for(int i=0; i<N; i++) {
cv::Mat img, label;
to_.Next(img, label);
EXPECT_MAT_DIMS_EQ(img, cv::Mat1b(ROWS, COLS));
EXPECT_MAT_TYPE(img, CV_8U);
EXPECT_EQ(img.at<uchar>(ROWS/2, COLS/2), static_cast<uchar>(255));
EXPECT_MAT_DIMS_EQ(label, cv::Mat1f(1, 1));
EXPECT_MAT_TYPE(label, CV_32F);
EXPECT_IN_LCLOSED_ROPEN(label.at<float>(0), 0.f, 180.f);
}
}
/**
* @brief test that bar orientations are unifromly distributed
*/
TEST_F(SynthBarsTest, Uniform)
{
const int N=4e3;
const int ROWS=3;
const int COLS=3;
const int NB_VARIATIONS=4;
to_.Reset(ROWS, COLS, NB_VARIATIONS);
cv::Mat1f counts = cv::Mat1f::zeros(1, NB_VARIATIONS);
for(int i=0; i<N; i++) {
cv::Mat img, label;
to_.Next(img, label);
float angle = label.at<float>(0);
EXPECT_IN_LCLOSED_ROPEN(angle, 0, 180);
int bin = static_cast<int>(angle/180.f*NB_VARIATIONS);
EXPECT_LT(bin, NB_VARIATIONS);
counts(bin)++;
}
EXPECT_FLOAT_EQ(cv::sum(counts)(0), N);
cv::Mat1f hist_normalized = counts/static_cast<float>(N);
// check histogram is near uniform
cv::Mat m, s;
cv::meanStdDev(hist_normalized, m, s);
EXPECT_MAT_NEAR(m, cv::Mat1d(1, 1, 1.f/static_cast<double>(NB_VARIATIONS)), 1e-5);
EXPECT_MAT_NEAR(s, cv::Mat1d::zeros(1, 1), 1e-2);
}
/**
* @brief Spot-check bar lines
*/
TEST_F(SynthBarsTest, BarLines)
{
const int SIZE=28;
const int NB_VARIATIONS=4;
const float DELTA=180.f/NB_VARIATIONS;
cv::Mat1b variations_covered = cv::Mat1b::zeros(1, NB_VARIATIONS);
cv::Mat1b covered_enough = cv::Mat1b::ones(1, NB_VARIATIONS);
to_.Reset(SIZE, SIZE, NB_VARIATIONS);
const uchar ON=static_cast<uchar>(255);
const uchar OFF=static_cast<uchar>(0);
int i=0;
int MAX_ITERATIONS=50;
while(cv::countNonZero(covered_enough) > 0 && i < MAX_ITERATIONS) {
cv::Mat img, label;
to_.Next(img, label);
float angle = label.at<float>(0);
if(angle == 0.f) {
// horizontal line
for(int i=0; i<SIZE; i++) {
EXPECT_EQ(img.at<uchar>(SIZE/2, i), ON) << "No horizontal line.";
}
EXPECT_MAT_EQ(img.rowRange(0, 4), cv::Mat1b(4, SIZE, OFF));
EXPECT_MAT_EQ(img.rowRange(SIZE-4, SIZE), cv::Mat1b(4, SIZE, OFF));
}
else if(angle == 45.f) {
EXPECT_EQ(img.at<uchar>(0, 0), OFF) << "diagonal not /";
EXPECT_EQ(img.at<uchar>(SIZE-1, 0), ON) << "diagonal not /";
EXPECT_EQ(img.at<uchar>(0, SIZE-1), ON) << "diagonal not /";
EXPECT_EQ(img.at<uchar>(SIZE-1, SIZE-1), OFF) << "diagonal not /";
}
else if(angle == 90.f) {
// vertical line
for(int i=0; i<SIZE; i++) {
EXPECT_EQ(img.at<uchar>(i, SIZE/2), ON) << "No vertical line.";
}
EXPECT_MAT_EQ(img.colRange(0, 4), cv::Mat1b(SIZE, 4, OFF));
EXPECT_MAT_EQ(img.colRange(SIZE-4, SIZE), cv::Mat1b(SIZE, 4, OFF));
}
else if(angle == 135.f) {
EXPECT_EQ(img.at<uchar>(0, 0), ON) << "diagonal not \\";
EXPECT_EQ(img.at<uchar>(SIZE-1, 0), OFF) << "diagonal not \\";
EXPECT_EQ(img.at<uchar>(0, SIZE-1), OFF) << "diagonal not \\";
EXPECT_EQ(img.at<uchar>(SIZE-1, SIZE-1), ON) << "diagonal not \\";
}
EXPECT_EQ(img.at<uchar>(SIZE/2, SIZE/2), ON) << "not centered";
int bin = static_cast<int>(angle/DELTA);
variations_covered(bin)++;
cv::compare(variations_covered,
cv::Mat1b(1, NB_VARIATIONS, static_cast<uchar>(5)),
covered_enough, cv::CMP_LT);
}
EXPECT_FALSE(cv::countNonZero(covered_enough) > 0 && i < MAX_ITERATIONS)
<< "Insufficient coverage of orientation variations" << variations_covered;
}
TEST_F(SynthBarsTest, Draw)
{
const int SIZE=28;
const int NB_VARIATIONS=4;
const float DELTA=180.f/NB_VARIATIONS;
to_.Reset(SIZE, SIZE, NB_VARIATIONS);
const uchar ON=static_cast<uchar>(255);
const uchar OFF=static_cast<uchar>(0);
for(float angle=0.f; angle<=360.f; angle+=DELTA) {
cv::Mat1f img;
to_.Draw(angle, img);
if(angle == 0.f) {
// horizontal line
for(int i=0; i<SIZE; i++) {
EXPECT_EQ(img.at<uchar>(SIZE/2, i), ON) << "No horizontal line.";
}
EXPECT_MAT_EQ(img.rowRange(0, 4), cv::Mat1b(4, SIZE, OFF));
EXPECT_MAT_EQ(img.rowRange(SIZE-4, SIZE), cv::Mat1b(4, SIZE, OFF));
}
else if(angle == 45.f) {
EXPECT_EQ(img.at<uchar>(0, 0), OFF) << "diagonal not /";
EXPECT_EQ(img.at<uchar>(SIZE-1, 0), ON) << "diagonal not /";
EXPECT_EQ(img.at<uchar>(0, SIZE-1), ON) << "diagonal not /";
EXPECT_EQ(img.at<uchar>(SIZE-1, SIZE-1), OFF) << "diagonal not /";
}
else if(angle == 90.f) {
// vertical line
for(int i=0; i<SIZE; i++) {
EXPECT_EQ(img.at<uchar>(i, SIZE/2), ON) << "No vertical line.";
}
EXPECT_MAT_EQ(img.colRange(0, 4), cv::Mat1b(SIZE, 4, OFF));
EXPECT_MAT_EQ(img.colRange(SIZE-4, SIZE), cv::Mat1b(SIZE, 4, OFF));
}
else if(angle == 135.f) {
EXPECT_EQ(img.at<uchar>(0, 0), ON) << "diagonal not \\";
EXPECT_EQ(img.at<uchar>(SIZE-1, 0), OFF) << "diagonal not \\";
EXPECT_EQ(img.at<uchar>(0, SIZE-1), OFF) << "diagonal not \\";
EXPECT_EQ(img.at<uchar>(SIZE-1, SIZE-1), ON) << "diagonal not \\";
}
EXPECT_EQ(img.at<uchar>(SIZE/2, SIZE/2), ON) << "not centered";
}
}
TEST_F(SynthBarsTest, DISABLED_Display)
{
to_.Reset(100, 100, 6);
for(int i=0; i<10; i++) {
cv::Mat img, label;
to_.Next(img, label);
cv::imshow(FullTestName(test_info_), img);
cv::waitKey();
}
}
<|endoftext|> |
<commit_before><?hh // strict
/**
* This file is part of hhpack\process package.
*
* (c) Noritaka Horio <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace HHPack\Process;
use RuntimeException;
async function exec(
string $command,
ExecOptions $options = new ExecOptions()
) : Awaitable<ProcessResult>
{
$builder = new ProcessBuilder($command, $options);
using ($cp = $builder->start()) {
return await $cp->wait();
}
}
async function execFile(
string $file,
?Traversable<mixed> $args = [],
ExecOptions $options = new ExecOptions()
) : Awaitable<ProcessResult>
{
if (is_file($file) === false) {
throw new RuntimeException(sprintf('%s is not a file', $file));
}
$arguments = ImmSet::fromItems($args)->map(($value) ==> {
return trim((string) $value);
})->toArray();
$command = sprintf('hhvm %s %s', trim($file), implode(' ', $arguments));
return await exec($command, $options);
}
<<__ReturnDisposable>>
function fork(
string $script,
?Traversable<mixed> $args = [],
ProcessOptions $options = new ProcessOptions()
) : ChildProcess
{
$arguments = ImmSet::fromItems($args)->map(($value) ==> {
return trim((string) $value);
})->toArray();
$command = sprintf('hhvm %s %s', trim($script), implode(' ', $arguments));
$builder = new ProcessBuilder($command, $options);
return $builder->start();
}
<<__ReturnDisposable>>
function spawn(
string $command,
?Traversable<mixed> $args = [],
ProcessOptions $options = new ProcessOptions()
) : ChildProcess
{
$arguments = ImmSet::fromItems($args)->map(($value) ==> {
return trim((string) $value);
})->toArray();
$command = sprintf('%s %s', trim($command), implode(' ', $arguments));
$builder = new ProcessBuilder($command, $options);
return $builder->start();
}
<commit_msg>fix indent<commit_after><?hh // strict
/**
* This file is part of hhpack\process package.
*
* (c) Noritaka Horio <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace HHPack\Process;
use RuntimeException;
async function exec(
string $command,
ExecOptions $options = new ExecOptions()
) : Awaitable<ProcessResult>
{
$builder = new ProcessBuilder($command, $options);
using ($cp = $builder->start()) {
return await $cp->wait();
}
}
async function execFile(
string $file,
?Traversable<mixed> $args = [],
ExecOptions $options = new ExecOptions()
) : Awaitable<ProcessResult>
{
if (is_file($file) === false) {
throw new RuntimeException(sprintf('%s is not a file', $file));
}
$arguments = ImmSet::fromItems($args)->map(($value) ==> {
return trim((string) $value);
})->toArray();
$command = sprintf('hhvm %s %s', trim($file), implode(' ', $arguments));
return await exec($command, $options);
}
<<__ReturnDisposable>>
function fork(
string $script,
?Traversable<mixed> $args = [],
ProcessOptions $options = new ProcessOptions()
) : ChildProcess
{
$arguments = ImmSet::fromItems($args)->map(($value) ==> {
return trim((string) $value);
})->toArray();
$command = sprintf('hhvm %s %s', trim($script), implode(' ', $arguments));
$builder = new ProcessBuilder($command, $options);
return $builder->start();
}
<<__ReturnDisposable>>
function spawn(
string $command,
?Traversable<mixed> $args = [],
ProcessOptions $options = new ProcessOptions()
) : ChildProcess
{
$arguments = ImmSet::fromItems($args)->map(($value) ==> {
return trim((string) $value);
})->toArray();
$command = sprintf('%s %s', trim($command), implode(' ', $arguments));
$builder = new ProcessBuilder($command, $options);
return $builder->start();
}
<|endoftext|> |
<commit_before>/*
* Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)
*
* 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 <votca/kmc/vssmgroup.h>
#include <vector>
#include <map>
#include <iostream>
#include <votca/tools/vec.h>
#include <votca/tools/database.h>
#include <votca/tools/statement.h>
#include <votca/tools/application.h>
#include <votca/tools/tokenizer.h>
using namespace std;
using namespace votca::kmc;
struct link_t;
class node_t : public VSSMGroup<link_t> {
public:
node_t(int id)
: _id(id), _occ(0) {}
double _occ;
int _id;
void onExecute() {
_occ+=WaitingTime();
VSSMGroup<link_t>::onExecute();
}
};
node_t *current;
vec r(0,0,0);
struct link_t {
link_t(node_t *dest, double rate, vec r)
: _dest(dest), _rate(rate), _r(r) {}
double Rate() {
return _rate;
}
void onExecute() {
r+=_r;
current = _dest;
}
double _rate;
node_t *_dest;
vec _r;
};
class KMCApplication
: public Application
{
public:
virtual string ProgramName() { return "kmc_test"; }
virtual void HelpText(std::ostream &out) { };
void Initialize();
bool EvaluateOptions();
void Run(void);
protected:
void LoadGraph(void);
void RunKMC(void);
void WriteOcc(void);
map<int , node_t *> _nodes_lookup;
vector<node_t *> _nodes;
map<int , node_t *> _injection_lookup;
vector<node_t *> _injection;
string _injection_name;
double _runtime;
double _dt;
};
void KMCApplication::Initialize()
{
AddProgramOptions("KMC Options")
("graph,g", boost::program_options::value<string>(), "file which contains graph")
("time,t", boost::program_options::value<double>(), "time to run")
("seed,s", boost::program_options::value<int>(), "seed for kmc")
("dt", boost::program_options::value<double>()->default_value(1e-4), "output frequency during run")
("injection,i", boost::program_options::value<string>()->default_value("*"), "name pattern for conjugated segments as injection points");
}
bool KMCApplication::EvaluateOptions()
{
CheckRequired("graph");
CheckRequired("seed");
CheckRequired("time");
_runtime = OptionsMap()["time"].as<double>();
_dt = OptionsMap()["dt"].as<double>();
_injection_name=OptionsMap()["injection"].as<string>();
//cout <<_injection_name<<endl;
//_injection_name=OptionsMap()["i"].as<string>();
return true;
}
void KMCApplication::Run(void)
{
srand(OptionsMap()["seed"].as<int>());
Random::init(rand(), rand(), rand(), rand());
LoadGraph();
RunKMC();
}
void KMCApplication::LoadGraph() {
Database db;
db.Open(OptionsMap()["graph"].as<string > ());
Statement *stmt = db.Prepare("SELECT _id,name FROM conjsegs;");
while (stmt->Step() != SQLITE_DONE) {
int id = stmt->Column<int>(0);
string name = stmt->Column<string>(1);
node_t *n =new node_t(id);
_nodes.push_back(n);
_nodes_lookup[id] = _nodes.back();
if (wildcmp(_injection_name.c_str(), name.c_str())) {
_injection.push_back(n);
_injection_lookup[id] = _injection.back();
}
}
//delete stmt;
cout << "Nodes: " << _nodes.size() << endl;
cout << "Injection Points: " << _injection.size() << endl;
delete stmt;
int links = 0;
stmt = db.Prepare("SELECT conjseg1, conjseg2, rate12, rate21, r_x, r_y, r_z FROM pairs;");
while (stmt->Step() != SQLITE_DONE) {
node_t *n1 = _nodes_lookup[stmt->Column<int>(0)];
node_t *n2 = _nodes_lookup[stmt->Column<int>(1)];
double rate12 = stmt->Column<double>(2);
double rate21 = stmt->Column<double>(3);
vec r = vec(stmt->Column<double>(4), stmt->Column<double>(5), stmt->Column<double>(6));
n1->AddEvent(new link_t(n2, rate12, r));
n2->AddEvent(new link_t(n1, rate21, -r));
links += 2;
}
delete stmt;
cout << "Links: " << links << endl;
}
void KMCApplication::RunKMC(void)
{
double t = 0;
current=_injection[Random::rand_uniform_int(_injection.size())];
cout <<"starting simulation at node: "<<current->_id-1<<endl;
double next_output = _dt;
int i=0;
while(t<_runtime) {
t+=current->WaitingTime();
current->onExecute();
if(t > next_output) {
next_output = t + _dt;
cout << t << ": " << r << endl;
}
}
_runtime = t;
WriteOcc();
cout << std::scientific << "\nKMC run finished\nAverage velocity (m/s): " << r/t*1e-9 << endl;
}
void KMCApplication::WriteOcc()
{
Database db;
db.Open(OptionsMap()["graph"].as<string>());
db.Exec("BEGIN;");
Statement *stmt = db.Prepare("UPDATE conjsegs SET occ = ? WHERE _id = ?;");
for(int i=0; i<_nodes.size(); ++i) {
stmt->Reset();
stmt->Bind(1, _nodes[i]->_occ/_runtime);
stmt->Bind(2, _nodes[i]->_id);
stmt->Step();
}
db.Exec("END;");
delete stmt;
}
int main(int argc, char **argv)
{
KMCApplication app;
return app.Exec(argc, argv);
}
<commit_msg>changed to kmc_run<commit_after>/*
* Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)
*
* 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 <votca/kmc/vssmgroup.h>
#include <vector>
#include <map>
#include <iostream>
#include <votca/tools/vec.h>
#include <votca/tools/database.h>
#include <votca/tools/statement.h>
#include <votca/tools/application.h>
#include <votca/tools/tokenizer.h>
using namespace std;
using namespace votca::kmc;
struct link_t;
class node_t : public VSSMGroup<link_t> {
public:
node_t(int id)
: _id(id), _occ(0) {}
double _occ;
int _id;
void onExecute() {
_occ+=WaitingTime();
VSSMGroup<link_t>::onExecute();
}
};
node_t *current;
vec r(0,0,0);
struct link_t {
link_t(node_t *dest, double rate, vec r)
: _dest(dest), _rate(rate), _r(r) {}
double Rate() {
return _rate;
}
void onExecute() {
r+=_r;
current = _dest;
}
double _rate;
node_t *_dest;
vec _r;
};
class KMCApplication
: public Application
{
public:
virtual string ProgramName() { return "kmc_run"; }
virtual void HelpText(std::ostream &out) { };
void Initialize();
bool EvaluateOptions();
void Run(void);
protected:
void LoadGraph(void);
void RunKMC(void);
void WriteOcc(void);
map<int , node_t *> _nodes_lookup;
vector<node_t *> _nodes;
map<int , node_t *> _injection_lookup;
vector<node_t *> _injection;
string _injection_name;
double _runtime;
double _dt;
};
void KMCApplication::Initialize()
{
AddProgramOptions("KMC Options")
("graph,g", boost::program_options::value<string>(), "file which contains graph")
("time,t", boost::program_options::value<double>(), "time to run")
("seed,s", boost::program_options::value<int>(), "seed for kmc")
("dt", boost::program_options::value<double>()->default_value(1e-4), "output frequency during run")
("injection,i", boost::program_options::value<string>()->default_value("*"), "name pattern for conjugated segments as injection points");
}
bool KMCApplication::EvaluateOptions()
{
CheckRequired("graph");
CheckRequired("seed");
CheckRequired("time");
_runtime = OptionsMap()["time"].as<double>();
_dt = OptionsMap()["dt"].as<double>();
_injection_name=OptionsMap()["injection"].as<string>();
//cout <<_injection_name<<endl;
//_injection_name=OptionsMap()["i"].as<string>();
return true;
}
void KMCApplication::Run(void)
{
srand(OptionsMap()["seed"].as<int>());
Random::init(rand(), rand(), rand(), rand());
LoadGraph();
RunKMC();
}
void KMCApplication::LoadGraph() {
Database db;
db.Open(OptionsMap()["graph"].as<string > ());
Statement *stmt = db.Prepare("SELECT _id,name FROM conjsegs;");
while (stmt->Step() != SQLITE_DONE) {
int id = stmt->Column<int>(0);
string name = stmt->Column<string>(1);
node_t *n =new node_t(id);
_nodes.push_back(n);
_nodes_lookup[id] = _nodes.back();
if (wildcmp(_injection_name.c_str(), name.c_str())) {
_injection.push_back(n);
_injection_lookup[id] = _injection.back();
}
}
//delete stmt;
cout << "Nodes: " << _nodes.size() << endl;
cout << "Injection Points: " << _injection.size() << endl;
delete stmt;
int links = 0;
stmt = db.Prepare("SELECT conjseg1, conjseg2, rate12, rate21, r_x, r_y, r_z FROM pairs;");
while (stmt->Step() != SQLITE_DONE) {
node_t *n1 = _nodes_lookup[stmt->Column<int>(0)];
node_t *n2 = _nodes_lookup[stmt->Column<int>(1)];
double rate12 = stmt->Column<double>(2);
double rate21 = stmt->Column<double>(3);
vec r = vec(stmt->Column<double>(4), stmt->Column<double>(5), stmt->Column<double>(6));
n1->AddEvent(new link_t(n2, rate12, r));
n2->AddEvent(new link_t(n1, rate21, -r));
links += 2;
}
delete stmt;
cout << "Links: " << links << endl;
}
void KMCApplication::RunKMC(void)
{
double t = 0;
current=_injection[Random::rand_uniform_int(_injection.size())];
cout <<"starting simulation at node: "<<current->_id-1<<endl;
double next_output = _dt;
int i=0;
while(t<_runtime) {
t+=current->WaitingTime();
current->onExecute();
if(t > next_output) {
next_output = t + _dt;
cout << t << ": " << r << endl;
}
}
_runtime = t;
WriteOcc();
cout << std::scientific << "\nKMC run finished\nAverage velocity (m/s): " << r/t*1e-9 << endl;
}
void KMCApplication::WriteOcc()
{
Database db;
db.Open(OptionsMap()["graph"].as<string>());
db.Exec("BEGIN;");
Statement *stmt = db.Prepare("UPDATE conjsegs SET occ = ? WHERE _id = ?;");
for(int i=0; i<_nodes.size(); ++i) {
stmt->Reset();
stmt->Bind(1, _nodes[i]->_occ/_runtime);
stmt->Bind(2, _nodes[i]->_id);
stmt->Step();
}
db.Exec("END;");
delete stmt;
}
int main(int argc, char **argv)
{
KMCApplication app;
return app.Exec(argc, argv);
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.