text
stringlengths
54
60.6k
<commit_before>#ifndef _TREEVIEW_TVREAD_HXX_ #define _TREEVIEW_TVREAD_HXX_ #ifndef INCLUDED_STL_VECTOR #include <vector> #define INCLUDED_STL_VECTOR #endif #ifndef _RTL_REF_HXX_ #include <rtl/ref.hxx> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _UCBHELPER_MACROS_HXX #include <ucbhelper/macros.hxx> #endif #ifndef _COM_SUN_STAR_UNO_TYPE_HXX_ #include <com/sun/star/uno/Type.hxx> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_ #include <com/sun/star/uno/XInterface.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_ #include <com/sun/star/lang/XTypeProvider.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XHIERARCHICALNAMEACCESS_HPP_ #include <com/sun/star/container/XHierarchicalNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XCHANGESNOTIFIER_HPP_ #include <com/sun/star/util/XChangesNotifier.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif namespace treeview { class ConfigData { public: #define PRODUCTNAME 0 #define PRODUCTVERSION 1 #define VENDORNAME 2 #define VENDORVERSION 3 #define VENDORSHORT 4 #define MAX_MODULE_COUNT 16 ConfigData(); int m_vAdd[5]; rtl::OUString m_vReplacement[5]; rtl::OUString prodName,prodVersion,vendName,vendVersion,vendShort; sal_uInt64 filelen[MAX_MODULE_COUNT]; rtl::OUString fileurl[MAX_MODULE_COUNT]; rtl::OUString locale,system; rtl::OUString appendix; void SAL_CALL replaceName( rtl::OUString& oustring ) const; }; class TVDom; class TVChildTarget; class TVBase : public cppu::OWeakObject, public com::sun::star::lang::XTypeProvider, public com::sun::star::container::XNameAccess, public com::sun::star::container::XHierarchicalNameAccess, public com::sun::star::util::XChangesNotifier, public com::sun::star::lang::XComponent { friend class TVChildTarget; public: virtual ~TVBase() { } // XInterface virtual com::sun::star::uno::Any SAL_CALL queryInterface( const com::sun::star::uno::Type& aType ) throw( com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire( void ) throw(); virtual void SAL_CALL release( void ) throw(); // XTypeProvider XTYPEPROVIDER_DECL() // XNameAccess virtual com::sun::star::uno::Type SAL_CALL getElementType( ) throw( com::sun::star::uno::RuntimeException ) { return getCppuVoidType(); } virtual sal_Bool SAL_CALL hasElements() throw( com::sun::star::uno::RuntimeException ) { return true; } // XChangesNotifier virtual void SAL_CALL addChangesListener( const com::sun::star::uno::Reference< com::sun::star::util::XChangesListener >& aListener ) throw( com::sun::star::uno::RuntimeException ) { // read only } virtual void SAL_CALL removeChangesListener( const com::sun::star::uno::Reference< com::sun::star::util::XChangesListener >& aListener ) throw( com::sun::star::uno::RuntimeException ) { // read only } // XComponent virtual void SAL_CALL dispose( ) throw( com::sun::star::uno::RuntimeException ) { } virtual void SAL_CALL addEventListener( const com::sun::star::uno::Reference< com::sun::star::lang::XEventListener >& xListener ) throw( com::sun::star::uno::RuntimeException ) { } virtual void SAL_CALL removeEventListener( const com::sun::star::uno::Reference< com::sun::star::lang::XEventListener >& aListener ) throw( com::sun::star::uno::RuntimeException ) { } // Abstract functions // XNameAccess virtual com::sun::star::uno::Any SAL_CALL getByName( const rtl::OUString& aName ) throw( com::sun::star::container::NoSuchElementException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException) = 0; virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getElementNames( ) throw( com::sun::star::uno::RuntimeException ) = 0; virtual sal_Bool SAL_CALL hasByName( const rtl::OUString& aName ) throw( com::sun::star::uno::RuntimeException ) = 0; // XHierarchicalNameAccess virtual com::sun::star::uno::Any SAL_CALL getByHierarchicalName( const rtl::OUString& aName ) throw( com::sun::star::container::NoSuchElementException, com::sun::star::uno::RuntimeException ) = 0; virtual sal_Bool SAL_CALL hasByHierarchicalName( const rtl::OUString& aName ) throw( com::sun::star::uno::RuntimeException ) = 0; }; // end class TVBase class TVRead : public TVBase { friend class TVChildTarget; public: TVRead(); TVRead( const ConfigData& configData,TVDom* tvDom = 0 ); ~TVRead(); // XNameAccess virtual com::sun::star::uno::Any SAL_CALL getByName( const rtl::OUString& aName ) throw( com::sun::star::container::NoSuchElementException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getElementNames( ) throw( com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL hasByName( const rtl::OUString& aName ) throw( com::sun::star::uno::RuntimeException ); // XHierarchicalNameAccess virtual com::sun::star::uno::Any SAL_CALL getByHierarchicalName( const rtl::OUString& aName ) throw( com::sun::star::container::NoSuchElementException, com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL hasByHierarchicalName( const rtl::OUString& aName ) throw( com::sun::star::uno::RuntimeException ); private: rtl::OUString Title; rtl::OUString TargetURL; rtl::Reference< TVChildTarget > Children; }; // end class TVRead class TVChildTarget : public TVBase { public: TVChildTarget( const ConfigData& configData,TVDom* tvDom ); TVChildTarget( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& xMSF ); ~TVChildTarget(); virtual com::sun::star::uno::Any SAL_CALL getByName( const rtl::OUString& aName ) throw( com::sun::star::container::NoSuchElementException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getElementNames( ) throw( com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL hasByName( const rtl::OUString& aName ) throw( com::sun::star::uno::RuntimeException ); // XHierarchicalNameAccess virtual com::sun::star::uno::Any SAL_CALL getByHierarchicalName( const rtl::OUString& aName ) throw( com::sun::star::container::NoSuchElementException, com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL hasByHierarchicalName( const rtl::OUString& aName ) throw( com::sun::star::uno::RuntimeException ); private: std::vector< rtl::Reference< TVRead > > Elements; ConfigData init( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& xMSF ); ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getConfiguration( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xMSgr ) const; ::com::sun::star::uno::Reference< ::com::sun::star::container::XHierarchicalNameAccess > getHierAccess( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& sProvider, const char* file ) const; ::rtl::OUString getKey( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XHierarchicalNameAccess >& xHierAccess, const char* key ) const; sal_Bool getBooleanKey( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XHierarchicalNameAccess >& xHierAccess, const char* key) const; void subst( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xMSgr, rtl::OUString& instpath ) const; }; // end class TVChildTarget } #endif <commit_msg>INTEGRATION: CWS warnings01 (1.10.166); FILE MERGED 2006/01/25 20:43:33 sb 1.10.166.2: RESYNC: (1.10-1.11); FILE MERGED 2005/12/15 16:36:48 ab 1.10.166.1: #i53898# Removed warnings for unxlngi6/unxlngi6.pro<commit_after>#ifndef _TREEVIEW_TVREAD_HXX_ #define _TREEVIEW_TVREAD_HXX_ #ifndef INCLUDED_STL_VECTOR #include <vector> #define INCLUDED_STL_VECTOR #endif #ifndef _RTL_REF_HXX_ #include <rtl/ref.hxx> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _UCBHELPER_MACROS_HXX #include <ucbhelper/macros.hxx> #endif #ifndef _COM_SUN_STAR_UNO_TYPE_HXX_ #include <com/sun/star/uno/Type.hxx> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_ #include <com/sun/star/uno/XInterface.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_ #include <com/sun/star/lang/XTypeProvider.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XHIERARCHICALNAMEACCESS_HPP_ #include <com/sun/star/container/XHierarchicalNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XCHANGESNOTIFIER_HPP_ #include <com/sun/star/util/XChangesNotifier.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif namespace treeview { class ConfigData { public: #define PRODUCTNAME 0 #define PRODUCTVERSION 1 #define VENDORNAME 2 #define VENDORVERSION 3 #define VENDORSHORT 4 #define MAX_MODULE_COUNT 16 ConfigData(); int m_vAdd[5]; rtl::OUString m_vReplacement[5]; rtl::OUString prodName,prodVersion,vendName,vendVersion,vendShort; sal_uInt64 filelen[MAX_MODULE_COUNT]; rtl::OUString fileurl[MAX_MODULE_COUNT]; rtl::OUString locale,system; rtl::OUString appendix; void SAL_CALL replaceName( rtl::OUString& oustring ) const; }; class TVDom; class TVChildTarget; class TVBase : public cppu::OWeakObject, public com::sun::star::lang::XTypeProvider, public com::sun::star::container::XNameAccess, public com::sun::star::container::XHierarchicalNameAccess, public com::sun::star::util::XChangesNotifier, public com::sun::star::lang::XComponent { friend class TVChildTarget; public: virtual ~TVBase() { } // XInterface virtual com::sun::star::uno::Any SAL_CALL queryInterface( const com::sun::star::uno::Type& aType ) throw( com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire( void ) throw(); virtual void SAL_CALL release( void ) throw(); // XTypeProvider XTYPEPROVIDER_DECL() // XNameAccess virtual com::sun::star::uno::Type SAL_CALL getElementType( ) throw( com::sun::star::uno::RuntimeException ) { return getCppuVoidType(); } virtual sal_Bool SAL_CALL hasElements() throw( com::sun::star::uno::RuntimeException ) { return true; } // XChangesNotifier virtual void SAL_CALL addChangesListener( const com::sun::star::uno::Reference< com::sun::star::util::XChangesListener >& aListener ) throw( com::sun::star::uno::RuntimeException ) { // read only (void)aListener; } virtual void SAL_CALL removeChangesListener( const com::sun::star::uno::Reference< com::sun::star::util::XChangesListener >& aListener ) throw( com::sun::star::uno::RuntimeException ) { // read only (void)aListener; } // XComponent virtual void SAL_CALL dispose( ) throw( com::sun::star::uno::RuntimeException ) { } virtual void SAL_CALL addEventListener( const com::sun::star::uno::Reference< com::sun::star::lang::XEventListener >& xListener ) throw( com::sun::star::uno::RuntimeException ) { (void)xListener; } virtual void SAL_CALL removeEventListener( const com::sun::star::uno::Reference< com::sun::star::lang::XEventListener >& aListener ) throw( com::sun::star::uno::RuntimeException ) { (void)aListener; } // Abstract functions // XNameAccess virtual com::sun::star::uno::Any SAL_CALL getByName( const rtl::OUString& aName ) throw( com::sun::star::container::NoSuchElementException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException) = 0; virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getElementNames( ) throw( com::sun::star::uno::RuntimeException ) = 0; virtual sal_Bool SAL_CALL hasByName( const rtl::OUString& aName ) throw( com::sun::star::uno::RuntimeException ) = 0; // XHierarchicalNameAccess virtual com::sun::star::uno::Any SAL_CALL getByHierarchicalName( const rtl::OUString& aName ) throw( com::sun::star::container::NoSuchElementException, com::sun::star::uno::RuntimeException ) = 0; virtual sal_Bool SAL_CALL hasByHierarchicalName( const rtl::OUString& aName ) throw( com::sun::star::uno::RuntimeException ) = 0; }; // end class TVBase class TVRead : public TVBase { friend class TVChildTarget; public: TVRead(); TVRead( const ConfigData& configData,TVDom* tvDom = 0 ); ~TVRead(); // XNameAccess virtual com::sun::star::uno::Any SAL_CALL getByName( const rtl::OUString& aName ) throw( com::sun::star::container::NoSuchElementException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getElementNames( ) throw( com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL hasByName( const rtl::OUString& aName ) throw( com::sun::star::uno::RuntimeException ); // XHierarchicalNameAccess virtual com::sun::star::uno::Any SAL_CALL getByHierarchicalName( const rtl::OUString& aName ) throw( com::sun::star::container::NoSuchElementException, com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL hasByHierarchicalName( const rtl::OUString& aName ) throw( com::sun::star::uno::RuntimeException ); private: rtl::OUString Title; rtl::OUString TargetURL; rtl::Reference< TVChildTarget > Children; }; // end class TVRead class TVChildTarget : public TVBase { public: TVChildTarget( const ConfigData& configData,TVDom* tvDom ); TVChildTarget( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& xMSF ); ~TVChildTarget(); virtual com::sun::star::uno::Any SAL_CALL getByName( const rtl::OUString& aName ) throw( com::sun::star::container::NoSuchElementException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getElementNames( ) throw( com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL hasByName( const rtl::OUString& aName ) throw( com::sun::star::uno::RuntimeException ); // XHierarchicalNameAccess virtual com::sun::star::uno::Any SAL_CALL getByHierarchicalName( const rtl::OUString& aName ) throw( com::sun::star::container::NoSuchElementException, com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL hasByHierarchicalName( const rtl::OUString& aName ) throw( com::sun::star::uno::RuntimeException ); private: std::vector< rtl::Reference< TVRead > > Elements; ConfigData init( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& xMSF ); ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getConfiguration( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xMSgr ) const; ::com::sun::star::uno::Reference< ::com::sun::star::container::XHierarchicalNameAccess > getHierAccess( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& sProvider, const char* file ) const; ::rtl::OUString getKey( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XHierarchicalNameAccess >& xHierAccess, const char* key ) const; sal_Bool getBooleanKey( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XHierarchicalNameAccess >& xHierAccess, const char* key) const; void subst( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xMSgr, rtl::OUString& instpath ) const; }; // end class TVChildTarget } #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ImageStyle.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: obo $ $Date: 2006-09-17 10:43:47 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" #ifndef _XMLOFF_IMAGESTYLE_HXX #include "ImageStyle.hxx" #endif #ifndef _COM_SUN_STAR_AWT_XBITMAP_HPP_ #include <com/sun/star/awt/XBitmap.hpp> #endif #ifndef _XMLOFF_ATTRLIST_HXX #include"attrlist.hxx" #endif #ifndef _XMLOFF_NMSPMAP_HXX #include "nmspmap.hxx" #endif #ifndef _XMLOFF_XMLUCONV_HXX #include"xmluconv.hxx" #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include"xmlnmspe.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include "xmltoken.hxx" #endif #ifndef _XMLOFF_XMLEXP_HXX #include "xmlexp.hxx" #endif #ifndef _XMLOFF_XMLIMP_HXX #include "xmlimp.hxx" #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _RTL_USTRING_ #include <rtl/ustring.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _XMLOFF_XMLTKMAP_HXX #include "xmltkmap.hxx" #endif using namespace ::com::sun::star; using namespace ::rtl; using namespace ::xmloff::token; enum SvXMLTokenMapAttrs { XML_TOK_IMAGE_NAME, XML_TOK_IMAGE_DISPLAY_NAME, XML_TOK_IMAGE_URL, XML_TOK_IMAGE_TYPE, XML_TOK_IMAGE_SHOW, XML_TOK_IMAGE_ACTUATE, /* XML_TOK_IMAGE_SIZEW, XML_TOK_IMAGE_SIZEH,*/ XML_TOK_TABSTOP_END=XML_TOK_UNKNOWN }; static __FAR_DATA SvXMLTokenMapEntry aHatchAttrTokenMap[] = { { XML_NAMESPACE_DRAW, XML_NAME, XML_TOK_IMAGE_NAME }, { XML_NAMESPACE_DRAW, XML_DISPLAY_NAME, XML_TOK_IMAGE_DISPLAY_NAME }, { XML_NAMESPACE_XLINK, XML_HREF, XML_TOK_IMAGE_URL }, { XML_NAMESPACE_XLINK, XML_TYPE, XML_TOK_IMAGE_TYPE }, { XML_NAMESPACE_XLINK, XML_SHOW, XML_TOK_IMAGE_SHOW }, { XML_NAMESPACE_XLINK, XML_ACTUATE, XML_TOK_IMAGE_ACTUATE }, /*{ XML_NAMESPACE_XLINK, XML_HREF, XML_TOK_IMAGE_URL }, { XML_NAMESPACE_XLINK, XML_HREF, XML_TOK_IMAGE_URL },*/ XML_TOKEN_MAP_END }; XMLImageStyle::XMLImageStyle() { } XMLImageStyle::~XMLImageStyle() { } #ifndef SVX_LIGHT sal_Bool XMLImageStyle::exportXML( const OUString& rStrName, const ::com::sun::star::uno::Any& rValue, SvXMLExport& rExport ) { return ImpExportXML( rStrName, rValue, rExport ); } sal_Bool XMLImageStyle::ImpExportXML( const OUString& rStrName, const uno::Any& rValue, SvXMLExport& rExport ) { sal_Bool bRet = sal_False; OUString sImageURL; if( rStrName.getLength() ) { if( rValue >>= sImageURL ) { OUString aStrValue; OUStringBuffer aOut; // Name sal_Bool bEncoded = sal_False; rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_NAME, rExport.EncodeStyleName( rStrName, &bEncoded ) ); if( bEncoded ) rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_DISPLAY_NAME, rStrName ); // uri const OUString aStr( rExport.AddEmbeddedGraphicObject( sImageURL ) ); if( aStr.getLength() ) { rExport.AddAttribute( XML_NAMESPACE_XLINK, XML_HREF, aStr ); rExport.AddAttribute( XML_NAMESPACE_XLINK, XML_TYPE, XML_SIMPLE ); rExport.AddAttribute( XML_NAMESPACE_XLINK, XML_SHOW, XML_EMBED ); rExport.AddAttribute( XML_NAMESPACE_XLINK, XML_ACTUATE, XML_ONLOAD ); } /* // size awt::Size aSize = xBitmap->getSize(); rUnitConverter.convertNumber( aOut, aSize.Width ); aStrValue = aOut.makeStringAndClear(); AddAttribute( XML_NAMESPACE_SVG, XML_WIDTH, aStrValue ); rUnitConverter.convertNumber( aOut, aSize.Height ); aStrValue = aOut.makeStringAndClear(); AddAttribute( XML_NAMESPACE_SVG, XML_HEIGHT, aStrValue ); */ // Do Write SvXMLElementExport aElem( rExport, XML_NAMESPACE_DRAW, XML_FILL_IMAGE, sal_True, sal_True ); if( sImageURL.getLength() ) { // optional office:binary-data rExport.AddEmbeddedGraphicObjectAsBase64( sImageURL ); } } } return bRet; } #endif // #ifndef SVX_LIGHT sal_Bool XMLImageStyle::importXML( const uno::Reference< xml::sax::XAttributeList >& xAttrList, uno::Any& rValue, OUString& rStrName, SvXMLImport& rImport ) { return ImpImportXML( xAttrList, rValue, rStrName, rImport ); } sal_Bool XMLImageStyle::ImpImportXML( const uno::Reference< xml::sax::XAttributeList >& xAttrList, uno::Any& rValue, OUString& rStrName, SvXMLImport& rImport ) { sal_Bool bRet = sal_False; sal_Bool bHasHRef = sal_False; sal_Bool bHasName = sal_False; OUString aStrURL; OUString aDisplayName; SvXMLTokenMap aTokenMap( aHatchAttrTokenMap ); sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for( sal_Int16 i=0; i < nAttrCount; i++ ) { const OUString& rFullAttrName = xAttrList->getNameByIndex( i ); OUString aStrAttrName; sal_uInt16 nPrefix = rImport.GetNamespaceMap().GetKeyByAttrName( rFullAttrName, &aStrAttrName ); const OUString& rStrValue = xAttrList->getValueByIndex( i ); switch( aTokenMap.Get( nPrefix, aStrAttrName ) ) { case XML_TOK_IMAGE_NAME: { rStrName = rStrValue; bHasName = sal_True; } break; case XML_TOK_IMAGE_DISPLAY_NAME: { aDisplayName = rStrValue; } break; case XML_TOK_IMAGE_URL: { aStrURL = rImport.ResolveGraphicObjectURL( rStrValue, sal_False ); bHasHRef = sal_True; } break; case XML_TOK_IMAGE_TYPE: // ignore break; case XML_TOK_IMAGE_SHOW: // ignore break; case XML_TOK_IMAGE_ACTUATE: // ignore break; default: DBG_WARNING( "Unknown token at import fill bitmap style" ) ; } } rValue <<= aStrURL; if( aDisplayName.getLength() ) { rImport.AddStyleDisplayName( XML_STYLE_FAMILY_SD_FILL_IMAGE_ID, rStrName, aDisplayName ); rStrName = aDisplayName; } bRet = bHasName && bHasHRef; return bRet; } <commit_msg>INTEGRATION: CWS vgbugs07 (1.12.124); FILE MERGED 2007/06/04 13:23:28 vg 1.12.124.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ImageStyle.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: hr $ $Date: 2007-06-27 15:24:59 $ * * 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_xmloff.hxx" #ifndef _XMLOFF_IMAGESTYLE_HXX #include "ImageStyle.hxx" #endif #ifndef _COM_SUN_STAR_AWT_XBITMAP_HPP_ #include <com/sun/star/awt/XBitmap.hpp> #endif #ifndef _XMLOFF_ATTRLIST_HXX #include <xmloff/attrlist.hxx> #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef _XMLOFF_XMLUCONV_HXX #include <xmloff/xmluconv.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include"xmlnmspe.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_XMLEXP_HXX #include <xmloff/xmlexp.hxx> #endif #ifndef _XMLOFF_XMLIMP_HXX #include <xmloff/xmlimp.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _RTL_USTRING_ #include <rtl/ustring.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _XMLOFF_XMLTKMAP_HXX #include <xmloff/xmltkmap.hxx> #endif using namespace ::com::sun::star; using namespace ::rtl; using namespace ::xmloff::token; enum SvXMLTokenMapAttrs { XML_TOK_IMAGE_NAME, XML_TOK_IMAGE_DISPLAY_NAME, XML_TOK_IMAGE_URL, XML_TOK_IMAGE_TYPE, XML_TOK_IMAGE_SHOW, XML_TOK_IMAGE_ACTUATE, /* XML_TOK_IMAGE_SIZEW, XML_TOK_IMAGE_SIZEH,*/ XML_TOK_TABSTOP_END=XML_TOK_UNKNOWN }; static __FAR_DATA SvXMLTokenMapEntry aHatchAttrTokenMap[] = { { XML_NAMESPACE_DRAW, XML_NAME, XML_TOK_IMAGE_NAME }, { XML_NAMESPACE_DRAW, XML_DISPLAY_NAME, XML_TOK_IMAGE_DISPLAY_NAME }, { XML_NAMESPACE_XLINK, XML_HREF, XML_TOK_IMAGE_URL }, { XML_NAMESPACE_XLINK, XML_TYPE, XML_TOK_IMAGE_TYPE }, { XML_NAMESPACE_XLINK, XML_SHOW, XML_TOK_IMAGE_SHOW }, { XML_NAMESPACE_XLINK, XML_ACTUATE, XML_TOK_IMAGE_ACTUATE }, /*{ XML_NAMESPACE_XLINK, XML_HREF, XML_TOK_IMAGE_URL }, { XML_NAMESPACE_XLINK, XML_HREF, XML_TOK_IMAGE_URL },*/ XML_TOKEN_MAP_END }; XMLImageStyle::XMLImageStyle() { } XMLImageStyle::~XMLImageStyle() { } #ifndef SVX_LIGHT sal_Bool XMLImageStyle::exportXML( const OUString& rStrName, const ::com::sun::star::uno::Any& rValue, SvXMLExport& rExport ) { return ImpExportXML( rStrName, rValue, rExport ); } sal_Bool XMLImageStyle::ImpExportXML( const OUString& rStrName, const uno::Any& rValue, SvXMLExport& rExport ) { sal_Bool bRet = sal_False; OUString sImageURL; if( rStrName.getLength() ) { if( rValue >>= sImageURL ) { OUString aStrValue; OUStringBuffer aOut; // Name sal_Bool bEncoded = sal_False; rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_NAME, rExport.EncodeStyleName( rStrName, &bEncoded ) ); if( bEncoded ) rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_DISPLAY_NAME, rStrName ); // uri const OUString aStr( rExport.AddEmbeddedGraphicObject( sImageURL ) ); if( aStr.getLength() ) { rExport.AddAttribute( XML_NAMESPACE_XLINK, XML_HREF, aStr ); rExport.AddAttribute( XML_NAMESPACE_XLINK, XML_TYPE, XML_SIMPLE ); rExport.AddAttribute( XML_NAMESPACE_XLINK, XML_SHOW, XML_EMBED ); rExport.AddAttribute( XML_NAMESPACE_XLINK, XML_ACTUATE, XML_ONLOAD ); } /* // size awt::Size aSize = xBitmap->getSize(); rUnitConverter.convertNumber( aOut, aSize.Width ); aStrValue = aOut.makeStringAndClear(); AddAttribute( XML_NAMESPACE_SVG, XML_WIDTH, aStrValue ); rUnitConverter.convertNumber( aOut, aSize.Height ); aStrValue = aOut.makeStringAndClear(); AddAttribute( XML_NAMESPACE_SVG, XML_HEIGHT, aStrValue ); */ // Do Write SvXMLElementExport aElem( rExport, XML_NAMESPACE_DRAW, XML_FILL_IMAGE, sal_True, sal_True ); if( sImageURL.getLength() ) { // optional office:binary-data rExport.AddEmbeddedGraphicObjectAsBase64( sImageURL ); } } } return bRet; } #endif // #ifndef SVX_LIGHT sal_Bool XMLImageStyle::importXML( const uno::Reference< xml::sax::XAttributeList >& xAttrList, uno::Any& rValue, OUString& rStrName, SvXMLImport& rImport ) { return ImpImportXML( xAttrList, rValue, rStrName, rImport ); } sal_Bool XMLImageStyle::ImpImportXML( const uno::Reference< xml::sax::XAttributeList >& xAttrList, uno::Any& rValue, OUString& rStrName, SvXMLImport& rImport ) { sal_Bool bRet = sal_False; sal_Bool bHasHRef = sal_False; sal_Bool bHasName = sal_False; OUString aStrURL; OUString aDisplayName; SvXMLTokenMap aTokenMap( aHatchAttrTokenMap ); sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for( sal_Int16 i=0; i < nAttrCount; i++ ) { const OUString& rFullAttrName = xAttrList->getNameByIndex( i ); OUString aStrAttrName; sal_uInt16 nPrefix = rImport.GetNamespaceMap().GetKeyByAttrName( rFullAttrName, &aStrAttrName ); const OUString& rStrValue = xAttrList->getValueByIndex( i ); switch( aTokenMap.Get( nPrefix, aStrAttrName ) ) { case XML_TOK_IMAGE_NAME: { rStrName = rStrValue; bHasName = sal_True; } break; case XML_TOK_IMAGE_DISPLAY_NAME: { aDisplayName = rStrValue; } break; case XML_TOK_IMAGE_URL: { aStrURL = rImport.ResolveGraphicObjectURL( rStrValue, sal_False ); bHasHRef = sal_True; } break; case XML_TOK_IMAGE_TYPE: // ignore break; case XML_TOK_IMAGE_SHOW: // ignore break; case XML_TOK_IMAGE_ACTUATE: // ignore break; default: DBG_WARNING( "Unknown token at import fill bitmap style" ) ; } } rValue <<= aStrURL; if( aDisplayName.getLength() ) { rImport.AddStyleDisplayName( XML_STYLE_FAMILY_SD_FILL_IMAGE_ID, rStrName, aDisplayName ); rStrName = aDisplayName; } bRet = bHasName && bHasHRef; return bRet; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ImageStyle.cxx,v $ * * $Revision: 1.14 $ * * last change: $Author: rt $ $Date: 2008-03-12 10:42:50 $ * * 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_xmloff.hxx" #ifndef _XMLOFF_IMAGESTYLE_HXX #include "ImageStyle.hxx" #endif #ifndef _COM_SUN_STAR_AWT_XBITMAP_HPP_ #include <com/sun/star/awt/XBitmap.hpp> #endif #ifndef _XMLOFF_ATTRLIST_HXX #include <xmloff/attrlist.hxx> #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef _XMLOFF_XMLUCONV_HXX #include <xmloff/xmluconv.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include"xmlnmspe.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_XMLEXP_HXX #include <xmloff/xmlexp.hxx> #endif #ifndef _XMLOFF_XMLIMP_HXX #include <xmloff/xmlimp.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _RTL_USTRING_ #include <rtl/ustring.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _XMLOFF_XMLTKMAP_HXX #include <xmloff/xmltkmap.hxx> #endif using namespace ::com::sun::star; using ::rtl::OUString; using ::rtl::OUStringBuffer; using namespace ::xmloff::token; enum SvXMLTokenMapAttrs { XML_TOK_IMAGE_NAME, XML_TOK_IMAGE_DISPLAY_NAME, XML_TOK_IMAGE_URL, XML_TOK_IMAGE_TYPE, XML_TOK_IMAGE_SHOW, XML_TOK_IMAGE_ACTUATE, /* XML_TOK_IMAGE_SIZEW, XML_TOK_IMAGE_SIZEH,*/ XML_TOK_TABSTOP_END=XML_TOK_UNKNOWN }; static __FAR_DATA SvXMLTokenMapEntry aHatchAttrTokenMap[] = { { XML_NAMESPACE_DRAW, XML_NAME, XML_TOK_IMAGE_NAME }, { XML_NAMESPACE_DRAW, XML_DISPLAY_NAME, XML_TOK_IMAGE_DISPLAY_NAME }, { XML_NAMESPACE_XLINK, XML_HREF, XML_TOK_IMAGE_URL }, { XML_NAMESPACE_XLINK, XML_TYPE, XML_TOK_IMAGE_TYPE }, { XML_NAMESPACE_XLINK, XML_SHOW, XML_TOK_IMAGE_SHOW }, { XML_NAMESPACE_XLINK, XML_ACTUATE, XML_TOK_IMAGE_ACTUATE }, /*{ XML_NAMESPACE_XLINK, XML_HREF, XML_TOK_IMAGE_URL }, { XML_NAMESPACE_XLINK, XML_HREF, XML_TOK_IMAGE_URL },*/ XML_TOKEN_MAP_END }; XMLImageStyle::XMLImageStyle() { } XMLImageStyle::~XMLImageStyle() { } #ifndef SVX_LIGHT sal_Bool XMLImageStyle::exportXML( const OUString& rStrName, const ::com::sun::star::uno::Any& rValue, SvXMLExport& rExport ) { return ImpExportXML( rStrName, rValue, rExport ); } sal_Bool XMLImageStyle::ImpExportXML( const OUString& rStrName, const uno::Any& rValue, SvXMLExport& rExport ) { sal_Bool bRet = sal_False; OUString sImageURL; if( rStrName.getLength() ) { if( rValue >>= sImageURL ) { OUString aStrValue; OUStringBuffer aOut; // Name sal_Bool bEncoded = sal_False; rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_NAME, rExport.EncodeStyleName( rStrName, &bEncoded ) ); if( bEncoded ) rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_DISPLAY_NAME, rStrName ); // uri const OUString aStr( rExport.AddEmbeddedGraphicObject( sImageURL ) ); if( aStr.getLength() ) { rExport.AddAttribute( XML_NAMESPACE_XLINK, XML_HREF, aStr ); rExport.AddAttribute( XML_NAMESPACE_XLINK, XML_TYPE, XML_SIMPLE ); rExport.AddAttribute( XML_NAMESPACE_XLINK, XML_SHOW, XML_EMBED ); rExport.AddAttribute( XML_NAMESPACE_XLINK, XML_ACTUATE, XML_ONLOAD ); } /* // size awt::Size aSize = xBitmap->getSize(); rUnitConverter.convertNumber( aOut, aSize.Width ); aStrValue = aOut.makeStringAndClear(); AddAttribute( XML_NAMESPACE_SVG, XML_WIDTH, aStrValue ); rUnitConverter.convertNumber( aOut, aSize.Height ); aStrValue = aOut.makeStringAndClear(); AddAttribute( XML_NAMESPACE_SVG, XML_HEIGHT, aStrValue ); */ // Do Write SvXMLElementExport aElem( rExport, XML_NAMESPACE_DRAW, XML_FILL_IMAGE, sal_True, sal_True ); if( sImageURL.getLength() ) { // optional office:binary-data rExport.AddEmbeddedGraphicObjectAsBase64( sImageURL ); } } } return bRet; } #endif // #ifndef SVX_LIGHT sal_Bool XMLImageStyle::importXML( const uno::Reference< xml::sax::XAttributeList >& xAttrList, uno::Any& rValue, OUString& rStrName, SvXMLImport& rImport ) { return ImpImportXML( xAttrList, rValue, rStrName, rImport ); } sal_Bool XMLImageStyle::ImpImportXML( const uno::Reference< xml::sax::XAttributeList >& xAttrList, uno::Any& rValue, OUString& rStrName, SvXMLImport& rImport ) { sal_Bool bRet = sal_False; sal_Bool bHasHRef = sal_False; sal_Bool bHasName = sal_False; OUString aStrURL; OUString aDisplayName; SvXMLTokenMap aTokenMap( aHatchAttrTokenMap ); sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for( sal_Int16 i=0; i < nAttrCount; i++ ) { const OUString& rFullAttrName = xAttrList->getNameByIndex( i ); OUString aStrAttrName; sal_uInt16 nPrefix = rImport.GetNamespaceMap().GetKeyByAttrName( rFullAttrName, &aStrAttrName ); const OUString& rStrValue = xAttrList->getValueByIndex( i ); switch( aTokenMap.Get( nPrefix, aStrAttrName ) ) { case XML_TOK_IMAGE_NAME: { rStrName = rStrValue; bHasName = sal_True; } break; case XML_TOK_IMAGE_DISPLAY_NAME: { aDisplayName = rStrValue; } break; case XML_TOK_IMAGE_URL: { aStrURL = rImport.ResolveGraphicObjectURL( rStrValue, sal_False ); bHasHRef = sal_True; } break; case XML_TOK_IMAGE_TYPE: // ignore break; case XML_TOK_IMAGE_SHOW: // ignore break; case XML_TOK_IMAGE_ACTUATE: // ignore break; default: DBG_WARNING( "Unknown token at import fill bitmap style" ) ; } } rValue <<= aStrURL; if( aDisplayName.getLength() ) { rImport.AddStyleDisplayName( XML_STYLE_FAMILY_SD_FILL_IMAGE_ID, rStrName, aDisplayName ); rStrName = aDisplayName; } bRet = bHasName && bHasHRef; return bRet; } <commit_msg>INTEGRATION: CWS changefileheader (1.14.18); FILE MERGED 2008/04/01 16:09:51 thb 1.14.18.3: #i85898# Stripping all external header guards 2008/04/01 13:04:56 thb 1.14.18.2: #i85898# Stripping all external header guards 2008/03/31 16:28:18 rt 1.14.18.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: ImageStyle.cxx,v $ * $Revision: 1.15 $ * * 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_xmloff.hxx" #include "ImageStyle.hxx" #include <com/sun/star/awt/XBitmap.hpp> #include <xmloff/attrlist.hxx> #include <xmloff/nmspmap.hxx> #include <xmloff/xmluconv.hxx> #include"xmlnmspe.hxx" #include <xmloff/xmltoken.hxx> #include <xmloff/xmlexp.hxx> #include <xmloff/xmlimp.hxx> #include <rtl/ustrbuf.hxx> #include <rtl/ustring.hxx> #include <tools/debug.hxx> #include <xmloff/xmltkmap.hxx> using namespace ::com::sun::star; using ::rtl::OUString; using ::rtl::OUStringBuffer; using namespace ::xmloff::token; enum SvXMLTokenMapAttrs { XML_TOK_IMAGE_NAME, XML_TOK_IMAGE_DISPLAY_NAME, XML_TOK_IMAGE_URL, XML_TOK_IMAGE_TYPE, XML_TOK_IMAGE_SHOW, XML_TOK_IMAGE_ACTUATE, /* XML_TOK_IMAGE_SIZEW, XML_TOK_IMAGE_SIZEH,*/ XML_TOK_TABSTOP_END=XML_TOK_UNKNOWN }; static __FAR_DATA SvXMLTokenMapEntry aHatchAttrTokenMap[] = { { XML_NAMESPACE_DRAW, XML_NAME, XML_TOK_IMAGE_NAME }, { XML_NAMESPACE_DRAW, XML_DISPLAY_NAME, XML_TOK_IMAGE_DISPLAY_NAME }, { XML_NAMESPACE_XLINK, XML_HREF, XML_TOK_IMAGE_URL }, { XML_NAMESPACE_XLINK, XML_TYPE, XML_TOK_IMAGE_TYPE }, { XML_NAMESPACE_XLINK, XML_SHOW, XML_TOK_IMAGE_SHOW }, { XML_NAMESPACE_XLINK, XML_ACTUATE, XML_TOK_IMAGE_ACTUATE }, /*{ XML_NAMESPACE_XLINK, XML_HREF, XML_TOK_IMAGE_URL }, { XML_NAMESPACE_XLINK, XML_HREF, XML_TOK_IMAGE_URL },*/ XML_TOKEN_MAP_END }; XMLImageStyle::XMLImageStyle() { } XMLImageStyle::~XMLImageStyle() { } #ifndef SVX_LIGHT sal_Bool XMLImageStyle::exportXML( const OUString& rStrName, const ::com::sun::star::uno::Any& rValue, SvXMLExport& rExport ) { return ImpExportXML( rStrName, rValue, rExport ); } sal_Bool XMLImageStyle::ImpExportXML( const OUString& rStrName, const uno::Any& rValue, SvXMLExport& rExport ) { sal_Bool bRet = sal_False; OUString sImageURL; if( rStrName.getLength() ) { if( rValue >>= sImageURL ) { OUString aStrValue; OUStringBuffer aOut; // Name sal_Bool bEncoded = sal_False; rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_NAME, rExport.EncodeStyleName( rStrName, &bEncoded ) ); if( bEncoded ) rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_DISPLAY_NAME, rStrName ); // uri const OUString aStr( rExport.AddEmbeddedGraphicObject( sImageURL ) ); if( aStr.getLength() ) { rExport.AddAttribute( XML_NAMESPACE_XLINK, XML_HREF, aStr ); rExport.AddAttribute( XML_NAMESPACE_XLINK, XML_TYPE, XML_SIMPLE ); rExport.AddAttribute( XML_NAMESPACE_XLINK, XML_SHOW, XML_EMBED ); rExport.AddAttribute( XML_NAMESPACE_XLINK, XML_ACTUATE, XML_ONLOAD ); } /* // size awt::Size aSize = xBitmap->getSize(); rUnitConverter.convertNumber( aOut, aSize.Width ); aStrValue = aOut.makeStringAndClear(); AddAttribute( XML_NAMESPACE_SVG, XML_WIDTH, aStrValue ); rUnitConverter.convertNumber( aOut, aSize.Height ); aStrValue = aOut.makeStringAndClear(); AddAttribute( XML_NAMESPACE_SVG, XML_HEIGHT, aStrValue ); */ // Do Write SvXMLElementExport aElem( rExport, XML_NAMESPACE_DRAW, XML_FILL_IMAGE, sal_True, sal_True ); if( sImageURL.getLength() ) { // optional office:binary-data rExport.AddEmbeddedGraphicObjectAsBase64( sImageURL ); } } } return bRet; } #endif // #ifndef SVX_LIGHT sal_Bool XMLImageStyle::importXML( const uno::Reference< xml::sax::XAttributeList >& xAttrList, uno::Any& rValue, OUString& rStrName, SvXMLImport& rImport ) { return ImpImportXML( xAttrList, rValue, rStrName, rImport ); } sal_Bool XMLImageStyle::ImpImportXML( const uno::Reference< xml::sax::XAttributeList >& xAttrList, uno::Any& rValue, OUString& rStrName, SvXMLImport& rImport ) { sal_Bool bRet = sal_False; sal_Bool bHasHRef = sal_False; sal_Bool bHasName = sal_False; OUString aStrURL; OUString aDisplayName; SvXMLTokenMap aTokenMap( aHatchAttrTokenMap ); sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for( sal_Int16 i=0; i < nAttrCount; i++ ) { const OUString& rFullAttrName = xAttrList->getNameByIndex( i ); OUString aStrAttrName; sal_uInt16 nPrefix = rImport.GetNamespaceMap().GetKeyByAttrName( rFullAttrName, &aStrAttrName ); const OUString& rStrValue = xAttrList->getValueByIndex( i ); switch( aTokenMap.Get( nPrefix, aStrAttrName ) ) { case XML_TOK_IMAGE_NAME: { rStrName = rStrValue; bHasName = sal_True; } break; case XML_TOK_IMAGE_DISPLAY_NAME: { aDisplayName = rStrValue; } break; case XML_TOK_IMAGE_URL: { aStrURL = rImport.ResolveGraphicObjectURL( rStrValue, sal_False ); bHasHRef = sal_True; } break; case XML_TOK_IMAGE_TYPE: // ignore break; case XML_TOK_IMAGE_SHOW: // ignore break; case XML_TOK_IMAGE_ACTUATE: // ignore break; default: DBG_WARNING( "Unknown token at import fill bitmap style" ) ; } } rValue <<= aStrURL; if( aDisplayName.getLength() ) { rImport.AddStyleDisplayName( XML_STYLE_FAMILY_SD_FILL_IMAGE_ID, rStrName, aDisplayName ); rStrName = aDisplayName; } bRet = bHasName && bHasHRef; return bRet; } <|endoftext|>
<commit_before>#include <clang-c/Index.h> #include <fstream> #include <string> class String { CXString m_str; public: String(CXString str) : m_str(str) {} ~String() { clang_disposeString(m_str); } operator const char*() { return clang_getCString(m_str); } }; std::string &operator+=(std::string &str, unsigned int i) { static char buf[15] = { '\0' }; char *ptr = &buf[13]; do { *ptr-- = (i % 10) + '0'; i = i/10; } while (i > 0); return str += (ptr + 1); } std::ofstream sql_output; CXChildVisitResult mainVisitor(CXCursor cursor, CXCursor parent, void *data); int main(int argc, char **argv) { CXIndex idx = clang_createIndex(0, 0); CXTranslationUnit contents = clang_parseTranslationUnit(idx, NULL, argv, argc, NULL, 0, CXTranslationUnit_None); // We are going to output to file.sql CXString ifile = clang_getTranslationUnitSpelling(contents); std::string ofile(clang_getCString(ifile)); ofile += ".sql"; sql_output.open(ofile.c_str()); clang_disposeString(ifile); CXCursor mainCursor = clang_getTranslationUnitCursor(contents); clang_visitChildren(mainCursor, mainVisitor, NULL); // Clean everything up! sql_output.close(); clang_disposeTranslationUnit(contents); clang_disposeIndex(idx); return 0; } bool wantLocation(CXSourceLocation loc) { CXFile file; clang_getSpellingLocation(loc, &file, NULL, NULL, NULL); String locStr(clang_getFileName(file)); if ((const char *)locStr == NULL) return false; std::string cxxstr((const char*)locStr); if (cxxstr[0] != '/') // Relative -> probably in srcdir return true; return cxxstr.find("/src/OpenSkyscraper") == 0; } std::string sanitizeString(std::string &str) { std::string result(str); size_t iter = -1; while ((iter = result.find('\'', iter + 1)) != std::string::npos) { result.replace(iter, 1, "''"); } return result; } std::string cursorLocation(CXCursor cursor) { CXSourceLocation sourceLoc = clang_getCursorLocation(cursor); CXFile file; unsigned int line, column; clang_getSpellingLocation(sourceLoc, &file, &line, &column, NULL); String filestring(clang_getFileName(file)); std::string fstr; if (filestring == NULL) fstr += "(null)"; else fstr += filestring; std::string result = sanitizeString(fstr); result += ":"; result += line; result += ":"; result += column; return result; } std::string getFQName(CXType type); std::string getFQName(CXCursor cursor); #ifdef BUILD_FQ_SELF static CXChildVisitResult fqbld(CXCursor child, CXCursor parent, void *param) { std::string &build = *(std::string*)param; CXCursorKind kind = clang_getCursorKind(child); if (kind != CXCursor_ParmDecl) return CXChildVisit_Break; CXType type = clang_getCursorType(child); build += getFQName(type); build += ", "; return CXChildVisit_Continue; } #endif std::string getFQName(CXCursor cursor) { CXCursor parent = clang_getCursorSemanticParent(cursor); if (clang_equalCursors(parent, clang_getNullCursor())) return std::string(); std::string base = getFQName(parent); if (!base.empty()) base += "::"; #ifdef BUILD_FQ_SELF String component(clang_getCursorSpelling(cursor)); if ((const char *)component != NULL) base += component; CXCursorKind kind = clang_getCursorKind(cursor); if (kind == CXCursor_FunctionDecl || kind == CXCursor_CXXMethod || kind == CXCursor_Constructor || kind == CXCursor_Destructor || kind == CXCursor_ConversionFunction) { // This is a method base += "("; clang_visitChildren(cursor, fqbld, &base); if (*(base.end() - 1) == '(') base += ")"; else base.replace(base.end() - 2, base.end(), ")"); } #else String component(clang_getCursorDisplayName(cursor)); if ((const char *)component != NULL) base += component; #endif return base; } #ifdef BUILD_FQ_SELF const char *primitiveTypes[] = { "void", "bool", "char", "unsigned char", "char16_t", "char32_t", "unsigned short", "unsigned int", "unsigned long", "unsigned long long", "__uint128_t", "char", "signed char", "wchar_t", "int", "long", "long long", "__int128_t", "float", "double", "long double", "std::nullptr_t", NULL, NULL, NULL, NULL, NULL}; std::string getFQName(CXType type) { // Normalize types in case of namespace aliasing or other weird stuff // Just don't undo typedefs if (type.kind != CXType_Typedef) type = clang_getCanonicalType(type); std::string typeStr; if (type.kind >= CXType_FirstBuiltin && type.kind <= CXType_LastBuiltin) { if (clang_isConstQualifiedType(type)) typeStr += "const "; if (clang_isVolatileQualifiedType(type)) typeStr += "volatile "; typeStr += primitiveTypes[type.kind - CXType_FirstBuiltin]; return typeStr; } switch (type.kind) { case CXType_Pointer: typeStr += getFQName(clang_getPointeeType(type)); typeStr += "*"; if (clang_isConstQualifiedType(type)) typeStr += " const"; if (clang_isVolatileQualifiedType(type)) typeStr += " volatile"; break; case CXType_LValueReference: // references don't do cv-qualified typeStr += getFQName(clang_getPointeeType(type)); typeStr += "&"; break; case CXType_RValueReference: // references don't do cv-qualified typeStr += getFQName(clang_getPointeeType(type)); typeStr += "&&"; break; case CXType_Record: case CXType_Enum: case CXType_Typedef: if (clang_isConstQualifiedType(type)) typeStr += "const "; if (clang_isVolatileQualifiedType(type)) typeStr += "volatile "; return getFQName(clang_getTypeDeclaration(type)); default: { String kindStr(clang_getTypeKindSpelling(type.kind)); printf("Kind of type: %s\n", (const char *)kindStr); } } return typeStr; } #endif void processCompoundType(CXCursor cursor, CXCursorKind kind) { const char *kindName; if (kind == CXCursor_StructDecl) kindName = "struct"; else if (kind == CXCursor_UnionDecl) kindName = "union"; else if (kind == CXCursor_ClassDecl) kindName = "class"; else if (kind == CXCursor_EnumDecl) kindName = "enum"; else if (kind == CXCursor_ClassTemplate) kindName = "class"; // Curse you libclang else kindName = "___UNKNOWN___"; // XXX: Need to support namespaces sql_output << "INSERT INTO types ('tname', 'tloc', 'tkind') VALUES ('" << getFQName(cursor) << "', '" << cursorLocation(cursor) << "', '" << kindName << "');" << std::endl; } void processFunctionType(CXCursor cursor, CXCursorKind kind) { CXCursor container = clang_getCursorSemanticParent(cursor); CXCursorKind parentKind = clang_getCursorKind(container); bool isContained = (parentKind != CXCursor_Namespace && parentKind != CXCursor_TranslationUnit && parentKind != CXCursor_UnexposedDecl); // Anonymous namespace ? sql_output << "INSERT INTO members ("; if (isContained) sql_output << "'mtname', 'mtdecl', "; sql_output << "'mname', 'mshortname', 'mdecl') VALUES ('"; if (isContained) sql_output << getFQName(container) << "', '" << cursorLocation(container) << "', '"; String shortname(clang_getCursorSpelling(cursor)); sql_output << getFQName(cursor) << "', '" << (shortname) << "', '" << cursorLocation(cursor) << "');" << std::endl; } void processVariableType(CXCursor cursor, CXCursorKind kind) { // Is this an included method or not? CXCursor container = clang_getCursorSemanticParent(cursor); CXCursorKind parentKind = clang_getCursorKind(container); bool isContained = (parentKind != CXCursor_Namespace && parentKind != CXCursor_TranslationUnit && parentKind != CXCursor_UnexposedDecl); // Anonymous namespace ? String name(clang_getCursorSpelling(cursor)); sql_output << "INSERT INTO members ("; if (isContained) sql_output << "'mtname', 'mtdecl', "; sql_output << "'mname', 'mdecl') VALUES ('"; if (isContained) sql_output << getFQName(container) << "', '" << cursorLocation(container) << "', '"; sql_output << (name) << "', '" << cursorLocation(cursor) << "');" << std::endl; } void processTypedef(CXCursor cursor) { // Are we a straightup typedef? CXType type = clang_getCanonicalType(clang_getCursorType(cursor)); bool simple = (type.kind == CXType_Record || (type.kind >= CXType_FirstBuiltin && type.kind <= CXType_LastBuiltin)); CXCursor typeRef = clang_getTypeDeclaration(type); sql_output << "INSERT INTO types ('tname', 'tloc', 'ttypedefname'," " 'ttypedefloc', 'tkind') VALUES ('" << getFQName(cursor) << "', '" << cursorLocation(cursor) << "', '" << (simple ? getFQName(typeRef) : "") << "', '" << (simple ? cursorLocation(typeRef) : "") << "');" << std::endl; } CXChildVisitResult mainVisitor(CXCursor cursor, CXCursor parent, void *data) { CXCursorKind kind = clang_getCursorKind(cursor); // Step 1: Do we care about this location? CXSourceLocation sourceLoc = clang_getCursorLocation(cursor); if (!wantLocation(sourceLoc)) return CXChildVisit_Continue; // Dispatch the code to the main processors if (!clang_isDeclaration(kind)) return CXChildVisit_Continue; switch (kind) { case CXCursor_StructDecl: case CXCursor_UnionDecl: case CXCursor_ClassDecl: case CXCursor_EnumDecl: case CXCursor_ClassTemplate: processCompoundType(cursor, kind); return CXChildVisit_Recurse; case CXCursor_FunctionDecl: case CXCursor_CXXMethod: case CXCursor_Constructor: case CXCursor_Destructor: case CXCursor_ConversionFunction: case CXCursor_FunctionTemplate: processFunctionType(cursor, kind); return CXChildVisit_Recurse; case CXCursor_FieldDecl: case CXCursor_EnumConstantDecl: case CXCursor_VarDecl: case CXCursor_ParmDecl: processVariableType(cursor, kind); return CXChildVisit_Recurse; case CXCursor_TypedefDecl: processTypedef(cursor); return CXChildVisit_Recurse; case CXCursor_UnexposedDecl: case CXCursor_TemplateTypeParameter: case CXCursor_Namespace: case CXCursor_UsingDeclaration: case CXCursor_UsingDirective: return CXChildVisit_Recurse; default: { String kindSpell(clang_getCursorKindSpelling(kind)); fprintf(stderr, "Unknown kind: %s at %s\n", (const char *)kindSpell, cursorLocation(cursor).c_str()); } } return CXChildVisit_Recurse; } <commit_msg>Add implementation hierarchy.<commit_after>#include <clang-c/Index.h> #include <fstream> #include <string> class String { CXString m_str; public: String(CXString str) : m_str(str) {} ~String() { clang_disposeString(m_str); } operator const char*() { return clang_getCString(m_str); } }; std::string &operator+=(std::string &str, unsigned int i) { static char buf[15] = { '\0' }; char *ptr = &buf[13]; do { *ptr-- = (i % 10) + '0'; i = i/10; } while (i > 0); return str += (ptr + 1); } std::ofstream sql_output; CXChildVisitResult mainVisitor(CXCursor cursor, CXCursor parent, void *data); int main(int argc, char **argv) { CXIndex idx = clang_createIndex(0, 0); CXTranslationUnit contents = clang_parseTranslationUnit(idx, NULL, argv, argc, NULL, 0, CXTranslationUnit_None); // We are going to output to file.sql CXString ifile = clang_getTranslationUnitSpelling(contents); std::string ofile(clang_getCString(ifile)); ofile += ".sql"; sql_output.open(ofile.c_str()); clang_disposeString(ifile); CXCursor mainCursor = clang_getTranslationUnitCursor(contents); clang_visitChildren(mainCursor, mainVisitor, NULL); // Clean everything up! sql_output.close(); clang_disposeTranslationUnit(contents); clang_disposeIndex(idx); return 0; } bool wantLocation(CXSourceLocation loc) { CXFile file; clang_getSpellingLocation(loc, &file, NULL, NULL, NULL); String locStr(clang_getFileName(file)); if ((const char *)locStr == NULL) return false; std::string cxxstr((const char*)locStr); if (cxxstr[0] != '/') // Relative -> probably in srcdir return true; return cxxstr.find("/src/OpenSkyscraper") == 0; } std::string sanitizeString(std::string &str) { std::string result(str); size_t iter = -1; while ((iter = result.find('\'', iter + 1)) != std::string::npos) { result.replace(iter, 1, "''"); } return result; } std::string cursorLocation(CXCursor cursor) { CXSourceLocation sourceLoc = clang_getCursorLocation(cursor); CXFile file; unsigned int line, column; clang_getSpellingLocation(sourceLoc, &file, &line, &column, NULL); String filestring(clang_getFileName(file)); std::string fstr; if (filestring == NULL) fstr += "(null)"; else fstr += filestring; std::string result = sanitizeString(fstr); result += ":"; result += line; result += ":"; result += column; return result; } std::string getFQName(CXType type); std::string getFQName(CXCursor cursor); #ifdef BUILD_FQ_SELF static CXChildVisitResult fqbld(CXCursor child, CXCursor parent, void *param) { std::string &build = *(std::string*)param; CXCursorKind kind = clang_getCursorKind(child); if (kind != CXCursor_ParmDecl) return CXChildVisit_Break; CXType type = clang_getCursorType(child); build += getFQName(type); build += ", "; return CXChildVisit_Continue; } #endif std::string getFQName(CXCursor cursor) { CXCursor parent = clang_getCursorSemanticParent(cursor); if (clang_equalCursors(parent, clang_getNullCursor())) return std::string(); std::string base = getFQName(parent); if (!base.empty()) base += "::"; #ifdef BUILD_FQ_SELF String component(clang_getCursorSpelling(cursor)); if ((const char *)component != NULL) base += component; CXCursorKind kind = clang_getCursorKind(cursor); if (kind == CXCursor_FunctionDecl || kind == CXCursor_CXXMethod || kind == CXCursor_Constructor || kind == CXCursor_Destructor || kind == CXCursor_ConversionFunction) { // This is a method base += "("; clang_visitChildren(cursor, fqbld, &base); if (*(base.end() - 1) == '(') base += ")"; else base.replace(base.end() - 2, base.end(), ")"); } #else String component(clang_getCursorDisplayName(cursor)); if ((const char *)component != NULL) base += component; #endif return base; } #ifdef BUILD_FQ_SELF const char *primitiveTypes[] = { "void", "bool", "char", "unsigned char", "char16_t", "char32_t", "unsigned short", "unsigned int", "unsigned long", "unsigned long long", "__uint128_t", "char", "signed char", "wchar_t", "int", "long", "long long", "__int128_t", "float", "double", "long double", "std::nullptr_t", NULL, NULL, NULL, NULL, NULL}; std::string getFQName(CXType type) { // Normalize types in case of namespace aliasing or other weird stuff // Just don't undo typedefs if (type.kind != CXType_Typedef) type = clang_getCanonicalType(type); std::string typeStr; if (type.kind >= CXType_FirstBuiltin && type.kind <= CXType_LastBuiltin) { if (clang_isConstQualifiedType(type)) typeStr += "const "; if (clang_isVolatileQualifiedType(type)) typeStr += "volatile "; typeStr += primitiveTypes[type.kind - CXType_FirstBuiltin]; return typeStr; } switch (type.kind) { case CXType_Pointer: typeStr += getFQName(clang_getPointeeType(type)); typeStr += "*"; if (clang_isConstQualifiedType(type)) typeStr += " const"; if (clang_isVolatileQualifiedType(type)) typeStr += " volatile"; break; case CXType_LValueReference: // references don't do cv-qualified typeStr += getFQName(clang_getPointeeType(type)); typeStr += "&"; break; case CXType_RValueReference: // references don't do cv-qualified typeStr += getFQName(clang_getPointeeType(type)); typeStr += "&&"; break; case CXType_Record: case CXType_Enum: case CXType_Typedef: if (clang_isConstQualifiedType(type)) typeStr += "const "; if (clang_isVolatileQualifiedType(type)) typeStr += "volatile "; return getFQName(clang_getTypeDeclaration(type)); default: { String kindStr(clang_getTypeKindSpelling(type.kind)); printf("Kind of type: %s\n", (const char *)kindStr); } } return typeStr; } #endif void processCompoundType(CXCursor cursor, CXCursorKind kind) { const char *kindName; if (kind == CXCursor_StructDecl) kindName = "struct"; else if (kind == CXCursor_UnionDecl) kindName = "union"; else if (kind == CXCursor_ClassDecl) kindName = "class"; else if (kind == CXCursor_EnumDecl) kindName = "enum"; else if (kind == CXCursor_ClassTemplate) kindName = "class"; // Curse you libclang else kindName = "___UNKNOWN___"; // XXX: Need to support namespaces sql_output << "INSERT INTO types ('tname', 'tloc', 'tkind') VALUES ('" << getFQName(cursor) << "', '" << cursorLocation(cursor) << "', '" << kindName << "');" << std::endl; } void processFunctionType(CXCursor cursor, CXCursorKind kind) { CXCursor container = clang_getCursorSemanticParent(cursor); CXCursorKind parentKind = clang_getCursorKind(container); bool isContained = (parentKind != CXCursor_Namespace && parentKind != CXCursor_TranslationUnit && parentKind != CXCursor_UnexposedDecl); // Anonymous namespace ? sql_output << "INSERT INTO members ("; if (isContained) sql_output << "'mtname', 'mtdecl', "; sql_output << "'mname', 'mshortname', 'mdecl') VALUES ('"; if (isContained) sql_output << getFQName(container) << "', '" << cursorLocation(container) << "', '"; String shortname(clang_getCursorSpelling(cursor)); sql_output << getFQName(cursor) << "', '" << (shortname) << "', '" << cursorLocation(cursor) << "');" << std::endl; } void processVariableType(CXCursor cursor, CXCursorKind kind) { // Is this an included method or not? CXCursor container = clang_getCursorSemanticParent(cursor); CXCursorKind parentKind = clang_getCursorKind(container); bool isContained = (parentKind != CXCursor_Namespace && parentKind != CXCursor_TranslationUnit && parentKind != CXCursor_UnexposedDecl); // Anonymous namespace ? String name(clang_getCursorSpelling(cursor)); sql_output << "INSERT INTO members ("; if (isContained) sql_output << "'mtname', 'mtdecl', "; sql_output << "'mname', 'mdecl') VALUES ('"; if (isContained) sql_output << getFQName(container) << "', '" << cursorLocation(container) << "', '"; sql_output << (name) << "', '" << cursorLocation(cursor) << "');" << std::endl; } void processTypedef(CXCursor cursor) { // Are we a straightup typedef? CXType type = clang_getCanonicalType(clang_getCursorType(cursor)); bool simple = (type.kind == CXType_Record || (type.kind >= CXType_FirstBuiltin && type.kind <= CXType_LastBuiltin)); CXCursor typeRef = clang_getTypeDeclaration(type); sql_output << "INSERT INTO types ('tname', 'tloc', 'ttypedefname'," " 'ttypedefloc', 'tkind') VALUES ('" << getFQName(cursor) << "', '" << cursorLocation(cursor) << "', '" << (simple ? getFQName(typeRef) : "") << "', '" << (simple ? cursorLocation(typeRef) : "") << "');" << std::endl; } void processInheritance(CXCursor base, CXCursor clazz, bool direct = 1) { sql_output << "INSERT INTO impl('tbname', 'tloc', 'tcname', 'tcloc', " "'direct') VALUES ('" << getFQName(clazz) << "', '" << cursorLocation(clazz) << "', '" << getFQName(base) << "', '" << cursorLocation(base) << "', " << (direct ? "1" : "0") << ");" << std::endl; } CXChildVisitResult mainVisitor(CXCursor cursor, CXCursor parent, void *data) { CXCursorKind kind = clang_getCursorKind(cursor); // Step 1: Do we care about this location? CXSourceLocation sourceLoc = clang_getCursorLocation(cursor); if (!wantLocation(sourceLoc)) return CXChildVisit_Continue; // Dispatch the code to the main processors if (!clang_isDeclaration(kind) && kind != CXCursor_CXXBaseSpecifier) return CXChildVisit_Continue; switch (kind) { case CXCursor_StructDecl: case CXCursor_UnionDecl: case CXCursor_ClassDecl: case CXCursor_EnumDecl: case CXCursor_ClassTemplate: processCompoundType(cursor, kind); return CXChildVisit_Recurse; case CXCursor_FunctionDecl: case CXCursor_CXXMethod: case CXCursor_Constructor: case CXCursor_Destructor: case CXCursor_ConversionFunction: case CXCursor_FunctionTemplate: processFunctionType(cursor, kind); return CXChildVisit_Recurse; case CXCursor_FieldDecl: case CXCursor_EnumConstantDecl: case CXCursor_VarDecl: case CXCursor_ParmDecl: processVariableType(cursor, kind); return CXChildVisit_Recurse; case CXCursor_TypedefDecl: processTypedef(cursor); return CXChildVisit_Recurse; case CXCursor_CXXBaseSpecifier: processInheritance(cursor, parent); return CXChildVisit_Recurse; case CXCursor_UnexposedDecl: case CXCursor_TemplateTypeParameter: case CXCursor_Namespace: case CXCursor_UsingDeclaration: case CXCursor_UsingDirective: return CXChildVisit_Recurse; default: { String kindSpell(clang_getCursorKindSpelling(kind)); fprintf(stderr, "Unknown kind: %s at %s\n", (const char *)kindSpell, cursorLocation(cursor).c_str()); } } return CXChildVisit_Recurse; } <|endoftext|>
<commit_before>// Simple byte-aligned rANS encoder/decoder - public domain - Fabian 'ryg' Giesen 2014 // // Not intended to be "industrial strength"; just meant to illustrate the general // idea. #ifndef RANS_BYTE_HEADER #define RANS_BYTE_HEADER #include <stdint.h> #ifdef assert #define RansAssert assert #else #define RansAssert(x) #endif // READ ME FIRST: // // This is designed like a typical arithmetic coder API, but there's three // twists you absolutely should be aware of before you start hacking: // // 1. You need to encode data in *reverse* - last symbol first. rANS works // like a stack: last in, first out. // 2. Likewise, the encoder outputs bytes *in reverse* - that is, you give // it a pointer to the *end* of your buffer (exclusive), and it will // slowly move towards the beginning as more bytes are emitted. // 3. Unlike basically any other entropy coder implementation you might // have used, you can interleave data from multiple independent rANS // encoders into the same bytestream without any extra signaling; // you can also just write some bytes by yourself in the middle if // you want to. This is in addition to the usual arithmetic encoder // property of being able to switch models on the fly. Writing raw // bytes can be useful when you have some data that you know is // incompressible, and is cheaper than going through the rANS encode // function. Using multiple rANS coders on the same byte stream wastes // a few bytes compared to using just one, but execution of two // independent encoders can happen in parallel on superscalar and // Out-of-Order CPUs, so this can be *much* faster in tight decoding // loops. // // This is why all the rANS functions take the write pointer as an // argument instead of just storing it in some context struct. // -------------------------------------------------------------------------- // L ('l' in the paper) is the lower bound of our normalization interval. // Between this and our byte-aligned emission, we use 31 (not 32!) bits. // This is done intentionally because exact reciprocals for 31-bit uints // fit in 32-bit uints: this permits some optimizations during encoding. #define RANS_BYTE_L (1u << 23) // lower bound of our normalization interval // State for a rANS encoder. Yep, that's all there is to it. typedef uint32_t RansState; // Initialize a rANS encoder. static inline void RansEncInit(RansState* r) { *r = RANS_BYTE_L; } // Renormalize the encoder. Internal function. static inline RansState RansEncRenorm(RansState x, uint8_t** pptr, uint32_t freq, uint32_t scale_bits) { uint32_t x_max = ((RANS_BYTE_L >> scale_bits) << 8) * freq; // this turns into a shift. if (x >= x_max) { uint8_t* ptr = *pptr; do { *--ptr = (uint8_t) (x & 0xff); x >>= 8; } while (x >= x_max); *pptr = ptr; } return x; } // Encodes a single symbol with range start "start" and frequency "freq". // All frequencies are assumed to sum to "1 << scale_bits", and the // resulting bytes get written to ptr (which is updated). // // NOTE: With rANS, you need to encode symbols in *reverse order*, i.e. from // beginning to end! Likewise, the output bytestream is written *backwards*: // ptr starts pointing at the end of the output buffer and keeps decrementing. static inline void RansEncPut(RansState* r, uint8_t** pptr, uint32_t start, uint32_t freq, uint32_t scale_bits) { // renormalize RansState x = RansEncRenorm(*r, pptr, freq, scale_bits); // x = C(s,x) *r = ((x / freq) << scale_bits) + (x % freq) + start; } // Flushes the rANS encoder. static inline void RansEncFlush(RansState* r, uint8_t** pptr) { uint32_t x = *r; uint8_t* ptr = *pptr; ptr -= 4; ptr[0] = (uint8_t) (x >> 0); ptr[1] = (uint8_t) (x >> 8); ptr[2] = (uint8_t) (x >> 16); ptr[3] = (uint8_t) (x >> 24); *pptr = ptr; } // Initializes a rANS decoder. // Unlike the encoder, the decoder works forwards as you'd expect. static inline void RansDecInit(RansState* r, uint8_t** pptr) { uint32_t x; uint8_t* ptr = *pptr; x = ptr[0] << 0; x |= ptr[1] << 8; x |= ptr[2] << 16; x |= ptr[3] << 24; ptr += 4; *pptr = ptr; *r = x; } // Returns the current cumulative frequency (map it to a symbol yourself!) static inline uint32_t RansDecGet(RansState* r, uint32_t scale_bits) { return *r & ((1u << scale_bits) - 1); } // Advances in the bit stream by "popping" a single symbol with range start // "start" and frequency "freq". All frequencies are assumed to sum to "1 << scale_bits", // and the resulting bytes get written to ptr (which is updated). static inline void RansDecAdvance(RansState* r, uint8_t** pptr, uint32_t start, uint32_t freq, uint32_t scale_bits) { uint32_t mask = (1u << scale_bits) - 1; // s, x = D(x) uint32_t x = *r; x = freq * (x >> scale_bits) + (x & mask) - start; // renormalize if (x < RANS_BYTE_L) { uint8_t* ptr = *pptr; do x = (x << 8) | *ptr++; while (x < RANS_BYTE_L); *pptr = ptr; } *r = x; } // -------------------------------------------------------------------------- // That's all you need for a full encoder; below here are some utility // functions with extra convenience or optimizations. // Encoder symbol description // This (admittedly odd) selection of parameters was chosen to make // RansEncPutSymbol as cheap as possible. typedef struct { uint32_t x_max; // (Exclusive) upper bound of pre-normalization interval uint32_t rcp_freq; // Fixed-point reciprocal frequency uint32_t bias; // Bias uint16_t cmpl_freq; // Complement of frequency: (1 << scale_bits) - freq uint16_t rcp_shift; // Reciprocal shift } RansEncSymbol; // Decoder symbols are straightforward. typedef struct { uint16_t start; // Start of range. uint16_t freq; // Symbol frequency. } RansDecSymbol; // Initializes an encoder symbol to start "start" and frequency "freq" static inline void RansEncSymbolInit(RansEncSymbol* s, uint32_t start, uint32_t freq, uint32_t scale_bits) { RansAssert(scale_bits <= 16); RansAssert(start <= (1u << scale_bits)); RansAssert(freq <= (1u << scale_bits) - start); // Say M := 1 << scale_bits. // // The original encoder does: // x_new = (x/freq)*M + start + (x%freq) // // The fast encoder does (schematically): // q = mul_hi(x, rcp_freq) >> rcp_shift (division) // r = x - q*freq (remainder) // x_new = q*M + bias + r (new x) // plugging in r into x_new yields: // x_new = bias + x + q*(M - freq) // =: bias + x + q*cmpl_freq (*) // // and we can just precompute cmpl_freq. Now we just need to // set up our parameters such that the original encoder and // the fast encoder agree. s->x_max = ((RANS_BYTE_L >> scale_bits) << 8) * freq; s->cmpl_freq = (uint16_t) ((1 << scale_bits) - freq); if (freq < 2) { // freq=0 symbols are never valid to encode, so it doesn't matter what // we set our values to. // // freq=1 is tricky, since the reciprocal of 1 is 1; unfortunately, // our fixed-point reciprocal approximation can only multiply by values // smaller than 1. // // So we use the "next best thing": rcp_freq=0xffffffff, rcp_shift=0. // This gives: // q = mul_hi(x, rcp_freq) >> rcp_shift // = mul_hi(x, (1<<32) - 1)) >> 0 // = floor(x - x/(2^32)) // = x - 1 if 1 <= x < 2^32 // and we know that x>0 (x=0 is never in a valid normalization interval). // // So we now need to choose the other parameters such that // x_new = x*M + start // plug it in: // x*M + start (desired result) // = bias + x + q*cmpl_freq (*) // = bias + x + (x - 1)*(M - 1) (plug in q=x-1, cmpl_freq) // = bias + 1 + (x - 1)*M // = x*M + (bias + 1 - M) // // so we have start = bias + 1 - M, or equivalently // bias = start + M - 1. s->rcp_freq = ~0u; s->rcp_shift = 0; s->bias = start + (1 << scale_bits) - 1; } else { // Alverson, "Integer Division using reciprocals" // shift=ceil(log2(freq)) uint32_t shift = 0; while (freq > (1u << shift)) shift++; s->rcp_freq = (uint32_t) (((1ull << (shift + 31)) + freq-1) / freq); s->rcp_shift = shift - 1; // With these values, 'q' is the correct quotient, so we // have bias=start. s->bias = start; } } // Initialize a decoder symbol to start "start" and frequency "freq" static inline void RansDecSymbolInit(RansDecSymbol* s, uint32_t start, uint32_t freq) { RansAssert(start <= (1 << 16)); RansAssert(freq <= (1 << 16) - start); s->start = (uint16_t) start; s->freq = (uint16_t) freq; } // Encodes a given symbol. This is faster than straight RansEnc since we can do // multiplications instead of a divide. // // See RansEncSymbolInit for a description of how this works. static inline void RansEncPutSymbol(RansState* r, uint8_t** pptr, RansEncSymbol const* sym) { RansAssert(sym->x_max != 0); // can't encode symbol with freq=0 // renormalize uint32_t x = *r; uint32_t x_max = sym->x_max; if (x >= x_max) { uint8_t* ptr = *pptr; do { *--ptr = (uint8_t) (x & 0xff); x >>= 8; } while (x >= x_max); *pptr = ptr; } // x = C(s,x) // NOTE: written this way so we get a 32-bit "multiply high" when // available. If you're on a 64-bit platform with cheap multiplies // (e.g. x64), just bake the +32 into rcp_shift. uint32_t q = (uint32_t) (((uint64_t)x * sym->rcp_freq) >> 32) >> sym->rcp_shift; *r = x + sym->bias + q * sym->cmpl_freq; } // Equivalent to RansDecAdvance that takes a symbol. static inline void RansDecAdvanceSymbol(RansState* r, uint8_t** pptr, RansDecSymbol const* sym, uint32_t scale_bits) { RansDecAdvance(r, pptr, sym->start, sym->freq, scale_bits); } // Advances in the bit stream by "popping" a single symbol with range start // "start" and frequency "freq". All frequencies are assumed to sum to "1 << scale_bits". // No renormalization or output happens. static inline void RansDecAdvanceStep(RansState* r, uint32_t start, uint32_t freq, uint32_t scale_bits) { uint32_t mask = (1u << scale_bits) - 1; // s, x = D(x) uint32_t x = *r; *r = freq * (x >> scale_bits) + (x & mask) - start; } // Equivalent to RansDecAdvanceStep that takes a symbol. static inline void RansDecAdvanceSymbolStep(RansState* r, RansDecSymbol const* sym, uint32_t scale_bits) { RansDecAdvanceStep(r, sym->start, sym->freq, scale_bits); } // Renormalize. static inline void RansDecRenorm(RansState* r, uint8_t** pptr) { // renormalize uint32_t x = *r; if (x < RANS_BYTE_L) { uint8_t* ptr = *pptr; do x = (x << 8) | *ptr++; while (x < RANS_BYTE_L); *pptr = ptr; } *r = x; } #endif // RANS_BYTE_HEADER<commit_msg>Delete rans_byte.hpp<commit_after><|endoftext|>
<commit_before>#include <chrono> #include <iostream> #include <limits> #include <string> #include "CLI/CLI.hpp" #include "cereal/archives/binary.hpp" #include "doc_lens.hpp" #include "inverted_index.hpp" #include "term_feature.hpp" int main(int argc, char **argv) { size_t done = 0; size_t freq = 0; double tfidf_max = 0.0; double bm25_max = 0.0; double pr_max = 0.0; double be_max = 0.0; double dfr_max = 0.0; double dph_max = 0.0; double lm_max = -std::numeric_limits<double>::max(); std::string inverted_index_file; std::string doc_lens_file; std::string output_file; CLI::App app{"Unigram feature generation."}; app.add_option("-i,--inverted-index", inverted_index_file, "Inverted index filename") ->required(); app.add_option("-d,--doc-lens", doc_lens_file, "Document lens filename")->required(); app.add_option("-o,--out-file", output_file, "Output filename")->required(); CLI11_PARSE(app, argc, argv); using clock = std::chrono::high_resolution_clock; InvertedIndex inv_idx; DocLens doc_lens; { auto start = clock::now(); // load inv_idx std::ifstream ifs_inv(inverted_index_file); cereal::BinaryInputArchive iarchive_inv(ifs_inv); iarchive_inv(inv_idx); auto stop = clock::now(); auto load_time = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start); std::cerr << "Loaded " << inverted_index_file << " in " << load_time.count() << " ms" << std::endl; } { auto start = clock::now(); // load doc_lens std::ifstream ifs_len(doc_lens_file); cereal::BinaryInputArchive iarchive_len(ifs_len); iarchive_len(doc_lens); auto stop = clock::now(); auto load_time = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start); std::cerr << "Loaded " << doc_lens_file << " in " << load_time.count() << " ms" << std::endl; } std::ofstream outfile(output_file, std::ofstream::app); outfile << std::fixed << std::setprecision(6); size_t clen = std::accumulate(doc_lens.begin(), doc_lens.end(), 0); size_t ndocs = doc_lens.size(); double avg_dlen = (double)clen / ndocs; std::cout << "Avg Document Length: " << avg_dlen << std::endl; std::cout << "N. docs: " << ndocs << std::endl; std::cout << "Collection Length " << clen << std::endl; for (auto &&pl : inv_idx) { feature_t feature; feature.term = pl.term; feature.cf = pl.totalCount; feature.cdf = pl.size(); auto list = pl.list(); /* Min count is set to 4 or IQR computation goes boom. */ if (pl.size() >= 4) { feature.geo_mean = compute_geo_mean(list.second); compute_tfidf_stats(feature, doc_lens, list, ndocs, tfidf_max); compute_bm25_stats(feature, doc_lens, list, ndocs, avg_dlen, bm25_max); compute_lm_stats(feature, doc_lens, list, clen, pl.totalCount, lm_max); compute_prob_stats(feature, doc_lens, list, pr_max); compute_be_stats(feature, doc_lens, list, ndocs, avg_dlen, pl.totalCount, be_max); compute_dph_stats(feature, doc_lens, list, ndocs, avg_dlen, pl.totalCount, dph_max); compute_dfr_stats(feature, doc_lens, list, ndocs, avg_dlen, pl.totalCount, dfr_max); outfile << feature; freq++; } done++; } std::cout << "Inv Lists Processed = " << done << std::endl; std::cout << "Inv Lists > 4 = " << freq << std::endl; std::cout << "TFIDF Max Score = " << tfidf_max << std::endl; std::cout << "BM25 Max Score = " << bm25_max << std::endl; std::cout << "LM Max Score = " << lm_max << std::endl; std::cout << "PR Max Score = " << pr_max << std::endl; std::cout << "BE Max Score = " << be_max << std::endl; std::cout << "DPH Max Score = " << dph_max << std::endl; std::cout << "DFR Max Score = " << dfr_max << std::endl; return 0; } <commit_msg>Fix possible overflow<commit_after>#include <chrono> #include <iostream> #include <limits> #include <string> #include "CLI/CLI.hpp" #include "cereal/archives/binary.hpp" #include "doc_lens.hpp" #include "inverted_index.hpp" #include "term_feature.hpp" int main(int argc, char **argv) { size_t done = 0; size_t freq = 0; double tfidf_max = 0.0; double bm25_max = 0.0; double pr_max = 0.0; double be_max = 0.0; double dfr_max = 0.0; double dph_max = 0.0; double lm_max = -std::numeric_limits<double>::max(); std::string inverted_index_file; std::string doc_lens_file; std::string output_file; CLI::App app{"Unigram feature generation."}; app.add_option("-i,--inverted-index", inverted_index_file, "Inverted index filename") ->required(); app.add_option("-d,--doc-lens", doc_lens_file, "Document lens filename")->required(); app.add_option("-o,--out-file", output_file, "Output filename")->required(); CLI11_PARSE(app, argc, argv); using clock = std::chrono::high_resolution_clock; InvertedIndex inv_idx; DocLens doc_lens; { auto start = clock::now(); // load inv_idx std::ifstream ifs_inv(inverted_index_file); cereal::BinaryInputArchive iarchive_inv(ifs_inv); iarchive_inv(inv_idx); auto stop = clock::now(); auto load_time = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start); std::cerr << "Loaded " << inverted_index_file << " in " << load_time.count() << " ms" << std::endl; } { auto start = clock::now(); // load doc_lens std::ifstream ifs_len(doc_lens_file); cereal::BinaryInputArchive iarchive_len(ifs_len); iarchive_len(doc_lens); auto stop = clock::now(); auto load_time = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start); std::cerr << "Loaded " << doc_lens_file << " in " << load_time.count() << " ms" << std::endl; } std::ofstream outfile(output_file, std::ofstream::app); outfile << std::fixed << std::setprecision(6); size_t clen = std::accumulate(doc_lens.begin(), doc_lens.end(), size_t(0)); size_t ndocs = doc_lens.size(); double avg_dlen = (double)clen / ndocs; std::cout << "Avg Document Length: " << avg_dlen << std::endl; std::cout << "N. docs: " << ndocs << std::endl; std::cout << "Collection Length " << clen << std::endl; for (auto &&pl : inv_idx) { feature_t feature; feature.term = pl.term; feature.cf = pl.totalCount; feature.cdf = pl.size(); auto list = pl.list(); /* Min count is set to 4 or IQR computation goes boom. */ if (pl.size() >= 4) { feature.geo_mean = compute_geo_mean(list.second); compute_tfidf_stats(feature, doc_lens, list, ndocs, tfidf_max); compute_bm25_stats(feature, doc_lens, list, ndocs, avg_dlen, bm25_max); compute_lm_stats(feature, doc_lens, list, clen, pl.totalCount, lm_max); compute_prob_stats(feature, doc_lens, list, pr_max); compute_be_stats(feature, doc_lens, list, ndocs, avg_dlen, pl.totalCount, be_max); compute_dph_stats(feature, doc_lens, list, ndocs, avg_dlen, pl.totalCount, dph_max); compute_dfr_stats(feature, doc_lens, list, ndocs, avg_dlen, pl.totalCount, dfr_max); outfile << feature; freq++; } if(done % 10000 == 0) { std::cout << "Processed " << done << " terms." << std::endl; } done++; } std::cout << "Inv Lists Processed = " << done << std::endl; std::cout << "Inv Lists > 4 = " << freq << std::endl; std::cout << "TFIDF Max Score = " << tfidf_max << std::endl; std::cout << "BM25 Max Score = " << bm25_max << std::endl; std::cout << "LM Max Score = " << lm_max << std::endl; std::cout << "PR Max Score = " << pr_max << std::endl; std::cout << "BE Max Score = " << be_max << std::endl; std::cout << "DPH Max Score = " << dph_max << std::endl; std::cout << "DFR Max Score = " << dfr_max << std::endl; return 0; } <|endoftext|>
<commit_before>// festus/algebraic-path-test.cc // // 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. // // Copyright 2016 Google, Inc. // Author: mjansche@google.com (Martin Jansche) // // \file // Unit test for algebraic path computation. #include "festus/algebraic-path.h" #include <cmath> #include <fst/compat.h> #include <fst/fstlib.h> #include <gtest/gtest.h> #include "festus/arc.h" #include "festus/float-weight-star.h" #include "festus/max-times-semiring.h" #include "festus/modular-int-semiring.h" #include "festus/quaternion-semiring.h" #include "festus/real-weight.h" #include "festus/value-weight-static.h" DEFINE_double(delta, fst::kDelta, "Convergence threshold for ShortestDistance"); DEFINE_bool(modular_int, false, "Try to compute ShortestDistance in modular int semiring"); DEFINE_bool(quaternion, false, "Try to compute ShortestDistance in quaternion semiring"); namespace { TEST(AlgebraicPathTest, Log) { typedef fst::LogArc Arc; typedef Arc::Weight Weight; // Internal implementation detail: typedef typename festus::internal::SemiringFor<Weight> SemiringForWeight; EXPECT_EQ(0, SemiringForWeight::IsSpecialized()); const auto &semiring = SemiringForWeight::Instance(); EXPECT_EQ(semiring.Zero(), Weight::Zero().Value()); constexpr float q = 1.0f / 32768.0f; fst::VectorFst<Arc> fst; auto s = fst.AddState(); fst.SetStart(s); fst.AddArc(s, Arc(0, 0, -std::log1p(-q), s)); fst.SetFinal(s, -std::log(q)); const auto total_value = festus::SumTotalValue(fst, &semiring); EXPECT_NEAR(0, total_value, 1e-9); const Weight total_weight = festus::SumTotalWeight(fst); EXPECT_TRUE(ApproxEqual(Weight::One(), total_weight)); VLOG(0) << "sum total = " << total_weight; VLOG(0) << "shortest distance computation will be slow and imprecise:"; VLOG(0) << "shortest distance = " << fst::ShortestDistance(fst, FLAGS_delta); } TEST(AlgebraicPathTest, LimitedMaxTimes) { // Note that this semiring is not k-closed. typedef festus::LimitedMaxTimesSemiring<int8, 3, 2> SemiringType; typedef festus::ValueWeightStatic<SemiringType> Weight; typedef festus::ValueArcTpl<Weight> Arc; // Internal implementation detail: typedef typename festus::internal::SemiringFor<Weight> SemiringForWeight; EXPECT_EQ(1, SemiringForWeight::IsSpecialized()); const auto &semiring = SemiringForWeight::Instance(); EXPECT_EQ(semiring.Zero(), Weight::Zero().Value()); fst::VectorFst<Arc> fst; auto s = fst.AddState(); fst.SetStart(s); fst.AddArc(s, Arc(0, 0, Weight::From(1), s)); fst.SetFinal(s, Weight::From(1)); const auto total_value = festus::SumTotalValue(fst, &semiring); EXPECT_EQ(2, total_value); const Weight total_weight = festus::SumTotalWeight(fst); EXPECT_EQ(Weight::From(2), total_weight); VLOG(0) << "sum total = " << total_weight; VLOG(0) << "shortest distance computation will be fast and wrong:"; VLOG(0) << "shortest distance = " << fst::ShortestDistance(fst, FLAGS_delta); } TEST(AlgebraicPathTest, IntegersMod13) { // Note that this semiring is not k-closed. typedef festus::IntegersMod<13> SemiringType; typedef festus::ValueWeightStatic<SemiringType> Weight; typedef festus::ValueArcTpl<Weight> Arc; // Internal implementation detail: typedef typename festus::internal::SemiringFor<Weight> SemiringForWeight; EXPECT_EQ(1, SemiringForWeight::IsSpecialized()); const auto &semiring = SemiringForWeight::Instance(); EXPECT_EQ(semiring.Zero(), Weight::Zero().Value()); fst::VectorFst<Arc> fst; auto s = fst.AddState(); fst.SetStart(s); fst.AddArc(s, Arc(0, 0, Weight::From(3), s)); fst.SetFinal(s, Weight::From(11)); const auto total_value = festus::SumTotalValue(fst, &semiring); EXPECT_EQ(1, total_value); const Weight total_weight = festus::SumTotalWeight(fst); EXPECT_EQ(Weight::One(), total_weight); VLOG(0) << "sum total = " << total_weight; if (FLAGS_modular_int) { VLOG(0) << "shortest distance computation will not terminate:"; VLOG(0) << "shortest distance = " << fst::ShortestDistance(fst, FLAGS_delta); } } TEST(AlgebraicPathTest, Quaternion) { // Note that this semiring is not k-closed. typedef festus::QuaternionWeightTpl<festus::RealSemiring<float>> Weight; typedef festus::ValueArcTpl<Weight> Arc; // Internal implementation detail: typedef typename festus::internal::SemiringFor<Weight> SemiringForWeight; EXPECT_EQ(1, SemiringForWeight::IsSpecialized()); const auto &semiring = SemiringForWeight::Instance(); EXPECT_EQ(semiring.Zero(), Weight::Zero().Value()); const Weight p = Weight::From(-0.5f, 0.5f, 0.5f, 0.5f); const Weight q = Minus(Weight::One(), p); fst::VectorFst<Arc> fst; auto s = fst.AddState(); fst.SetStart(s); fst.AddArc(s, Arc(0, 0, p, s)); fst.SetFinal(s, q); const auto total_value = festus::SumTotalValue(fst, &semiring); EXPECT_NEAR(1, total_value[0], 1e-7); EXPECT_NEAR(0, total_value[1], 1e-7); EXPECT_NEAR(0, total_value[2], 1e-7); EXPECT_NEAR(0, total_value[3], 1e-7); const Weight total_weight = festus::SumTotalWeight(fst); EXPECT_TRUE(ApproxEqual(Weight::One(), total_weight, 1e-7)); VLOG(0) << "sum total = " << total_weight; if (FLAGS_quaternion) { VLOG(0) << "shortest distance computation will not terminate:"; VLOG(0) << "shortest distance = " << fst::ShortestDistance(fst, FLAGS_delta); } } } // namespace int main(int argc, char *argv[]) { testing::InitGoogleTest(&argc, argv); SET_FLAGS(argv[0], &argc, &argv, true); return RUN_ALL_TESTS(); } <commit_msg>Factor out common function.<commit_after>// festus/algebraic-path-test.cc // // 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. // // Copyright 2016 Google, Inc. // Author: mjansche@google.com (Martin Jansche) // // \file // Unit test for algebraic path computation. #include "festus/algebraic-path.h" #include <cmath> #include <fst/compat.h> #include <fst/fstlib.h> #include <gtest/gtest.h> #include "festus/arc.h" #include "festus/float-weight-star.h" #include "festus/max-times-semiring.h" #include "festus/modular-int-semiring.h" #include "festus/quaternion-semiring.h" #include "festus/real-weight.h" #include "festus/value-weight-static.h" DEFINE_double(delta, fst::kDelta, "Convergence threshold for ShortestDistance"); DEFINE_bool(modular_int, false, "Try to compute ShortestDistance in modular int semiring"); DEFINE_bool(quaternion, false, "Try to compute ShortestDistance in quaternion semiring"); namespace { template <class Arc> void TestOneStateLoop( typename Arc::Weight loop_weight, typename Arc::Weight final_weight, typename Arc::Weight expected_sum_total, float comparison_delta, int power_series_terms, bool use_shortest_distance, const char *msg) { typedef typename Arc::Weight Weight; // One-state FST with a loop at its only (initial and final) state. fst::VectorFst<Arc> fst; const auto state = fst.AddState(); fst.SetStart(state); fst.AddArc(state, Arc(0, 0, loop_weight, state)); fst.SetFinal(state, final_weight); const Weight sum_total = festus::SumTotalWeight(fst); EXPECT_TRUE(ApproxEqual(sum_total, expected_sum_total, comparison_delta)); VLOG(0) << "sum total = " << sum_total << " ~= " << expected_sum_total; if (power_series_terms) { Weight power = Weight::One(); Weight series = Weight::One(); VLOG(0) << "\\sum_{n=0}^0 loop_weight^n = " << series; VLOG(0) << " sum x final = " << Times(series, final_weight); for (int n = 1; n <= power_series_terms; ++n) { power = Times(power, loop_weight); series = Plus(series, power); VLOG(0) << "\\sum_{n=0}^" << n << " loop_weight^n = " << series; VLOG(0) << " sum x final = " << Times(series, final_weight); } } if (use_shortest_distance) { VLOG(0) << msg; VLOG(0) << "shortest distance = " << fst::ShortestDistance(fst, FLAGS_delta); } } TEST(AlgebraicPathTest, Log) { typedef fst::LogArc Arc; typedef Arc::Weight Weight; constexpr float q = 1.0f / 32768.0f; TestOneStateLoop<Arc>( Weight(-std::log1p(-q)), Weight(-std::log(q)), Weight::One(), 1e-9, 9, true, "shortest distance computation will be slow and imprecise"); // Internal implementation detail: EXPECT_EQ(0, festus::internal::SemiringFor<Weight>::IsSpecialized()); } TEST(AlgebraicPathTest, LimitedMaxTimes) { // Note that this semiring is not k-closed. typedef festus::LimitedMaxTimesSemiring<int8, 3, 2> SemiringType; typedef festus::ValueWeightStatic<SemiringType> Weight; typedef festus::ValueArcTpl<Weight> Arc; TestOneStateLoop<Arc>( Weight::From(1), Weight::From(1), Weight::From(2), 1e-30, 3, true, "shortest distance computation will be fast and different"); // Internal implementation detail: EXPECT_EQ(1, festus::internal::SemiringFor<Weight>::IsSpecialized()); } TEST(AlgebraicPathTest, IntegersMod13) { // Note that this semiring is not k-closed. typedef festus::IntegersMod<13> SemiringType; typedef festus::ValueWeightStatic<SemiringType> Weight; typedef festus::ValueArcTpl<Weight> Arc; TestOneStateLoop<Arc>( Weight::From(3), Weight::From(11), Weight::One(), 1e-30, 5, FLAGS_modular_int, "shortest distance computation will not terminate"); // Internal implementation detail: EXPECT_EQ(1, festus::internal::SemiringFor<Weight>::IsSpecialized()); } TEST(AlgebraicPathTest, Quaternion) { // Note that this semiring is not k-closed. typedef festus::QuaternionWeightTpl<festus::RealSemiring<float>> Weight; typedef festus::ValueArcTpl<Weight> Arc; const Weight p = Weight::From(-0.5f, 0.5f, 0.5f, 0.5f); const Weight q = Minus(Weight::One(), p); TestOneStateLoop<Arc>( p, q, Weight::One(), 1e-9, 5, FLAGS_quaternion, "shortest distance computation will not terminate"); // Internal implementation detail: EXPECT_EQ(1, festus::internal::SemiringFor<Weight>::IsSpecialized()); } } // namespace int main(int argc, char *argv[]) { testing::InitGoogleTest(&argc, argv); SET_FLAGS(argv[0], &argc, &argv, true); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include "FastTimer.hpp" #include <sys/time.h> #include <stdio.h> #include <QEvent> #include <QApplication> FastTimer::FastTimer(QObject* parent): QThread(parent), _us(0), _running(false) { pthread_mutex_init(&_mutex, 0); pthread_cond_init(&_cond, 0); } FastTimer::~FastTimer() { if (_running) { stop(); // The event loop may not be running any more pthread_mutex_lock(&_mutex); pthread_cond_signal(&_cond); pthread_mutex_unlock(&_mutex); // terminate(); //FIXME - What if the delay is really long? wait(); } } void FastTimer::start(int ms) { _us = ms * 1000; if (!_running) { _running = true; QThread::start(); } } void FastTimer::stop() { _running = false; } void FastTimer::run() { struct timeval start; gettimeofday(&start, 0); pthread_mutex_lock(&_mutex); while (_running) { struct timeval t; gettimeofday(&t, 0); useconds_t us = (t.tv_sec - start.tv_sec) * 1000000 + t.tv_usec - start.tv_usec; start = t; if (_us > us) { usleep(_us); } QApplication::instance()->postEvent(this, new QEvent(QEvent::User)); pthread_cond_wait(&_cond, &_mutex); } pthread_mutex_unlock(&_mutex); } bool FastTimer::event(QEvent* e) { if (e->type() == QEvent::User) { timeout(); pthread_mutex_lock(&_mutex); pthread_cond_signal(&_cond); pthread_mutex_unlock(&_mutex); e->accept(); return true; } else { return QObject::event(e); } } <commit_msg>Fixed elapsed time calculation in FastTimer<commit_after>#include "FastTimer.hpp" #include <sys/time.h> #include <stdio.h> #include <QEvent> #include <QApplication> FastTimer::FastTimer(QObject* parent): QThread(parent), _us(0), _running(false) { pthread_mutex_init(&_mutex, 0); pthread_cond_init(&_cond, 0); } FastTimer::~FastTimer() { if (_running) { stop(); // The event loop may not be running any more pthread_mutex_lock(&_mutex); pthread_cond_signal(&_cond); pthread_mutex_unlock(&_mutex); // terminate(); //FIXME - What if the delay is really long? wait(); } } void FastTimer::start(int ms) { _us = ms * 1000; if (!_running) { _running = true; QThread::start(); } } void FastTimer::stop() { _running = false; } void FastTimer::run() { struct timeval start; gettimeofday(&start, 0); pthread_mutex_lock(&_mutex); while (_running) { struct timeval t; gettimeofday(&t, 0); useconds_t us = (t.tv_sec - start.tv_sec) * 1000000 + t.tv_usec - start.tv_usec; start = t; if (_us > us) { usleep(_us-us); gettimeofday(&start, 0); } QApplication::instance()->postEvent(this, new QEvent(QEvent::User)); pthread_cond_wait(&_cond, &_mutex); } pthread_mutex_unlock(&_mutex); } bool FastTimer::event(QEvent* e) { if (e->type() == QEvent::User) { timeout(); pthread_mutex_lock(&_mutex); pthread_cond_signal(&_cond); pthread_mutex_unlock(&_mutex); e->accept(); return true; } else { return QObject::event(e); } } <|endoftext|>
<commit_before><commit_msg>small improvement to fz logging<commit_after><|endoftext|>
<commit_before>#include <ir/Zambezi/AttrScoreInvertedIndex.hpp> #include <ir/Zambezi/Utils.hpp> #include <glog/logging.h> NS_IZENELIB_IR_BEGIN namespace Zambezi { AttrScoreInvertedIndex::AttrScoreInvertedIndex( uint32_t maxPoolSize, uint32_t numberOfPools, bool reverse) : buffer_(DEFAULT_VOCAB_SIZE) , pool_(maxPoolSize, numberOfPools, reverse) , dictionary_(DEFAULT_VOCAB_SIZE) , pointers_(DEFAULT_VOCAB_SIZE, 0) { } AttrScoreInvertedIndex::~AttrScoreInvertedIndex() { } void AttrScoreInvertedIndex::save(std::ostream& ostr) const { std::streamoff offset = ostr.tellp(); buffer_.save(ostr); LOG(INFO) << "Saving: buffer maps size " << ostr.tellp() - offset; offset = ostr.tellp(); pool_.save(ostr); LOG(INFO) << "Saving: segment pools size " << ostr.tellp() - offset; offset = ostr.tellp(); dictionary_.save(ostr); LOG(INFO) << "Saving: dictionary size " << ostr.tellp() - offset; offset = ostr.tellp(); pointers_.save(ostr); LOG(INFO) << "Saving: head pointers size " << ostr.tellp() - offset; } void AttrScoreInvertedIndex::load(std::istream& istr) { std::streamoff offset = istr.tellg(); buffer_.load(istr); LOG(INFO) << "Loading: buffer maps size " << istr.tellg() - offset; offset = istr.tellg(); pool_.load(istr); LOG(INFO) << "Loading: segment pool size " << istr.tellg() - offset; offset = istr.tellg(); dictionary_.load(istr); LOG(INFO) << "Loading: dictionary size " << istr.tellg() - offset; offset = istr.tellg(); pointers_.load(istr); LOG(INFO) << "Loading: head pointers size " << istr.tellg() - offset; } bool AttrScoreInvertedIndex::hasValidPostingsList(uint32_t termid) const { return pointers_.getHeadPointer(termid) != UNDEFINED_POINTER; } void AttrScoreInvertedIndex::insertDoc( uint32_t docid, const std::vector<std::string>& term_list, const std::vector<uint32_t>& score_list) { for (uint32_t i = 0; i < term_list.size(); ++i) { uint32_t id = dictionary_.insertTerm(term_list[i]); pointers_.cf_.increment(id); std::vector<uint32_t>& docBuffer = buffer_.getDocidList(id); std::vector<uint32_t>& scoreBuffer = buffer_.getScoreList(id); if (pointers_.getDf(id) < DF_CUTOFF) { if (docBuffer.capacity() == 0) { docBuffer.reserve(DF_CUTOFF); scoreBuffer.reserve(DF_CUTOFF); } docBuffer.push_back(docid); scoreBuffer.push_back(score_list[i]); pointers_.df_.increment(id); continue; } if (docBuffer.capacity() < BLOCK_SIZE) { docBuffer.reserve(BLOCK_SIZE); scoreBuffer.reserve(BLOCK_SIZE); } docBuffer.push_back(docid); scoreBuffer.push_back(score_list[i]); pointers_.df_.increment(id); if (docBuffer.size() == docBuffer.capacity()) { uint32_t nb = docBuffer.size() / BLOCK_SIZE; size_t pointer = buffer_.tailPointer_[id]; for (uint32_t j = 0; j < nb; ++j) { pointer = pool_.compressAndAppend( codec_, &docBuffer[j * BLOCK_SIZE], &scoreBuffer[j * BLOCK_SIZE], BLOCK_SIZE, pointer); if (pool_.isReverse() || pointers_.getHeadPointer(id) == UNDEFINED_POINTER) { pointers_.setHeadPointer(id, pointer); } } buffer_.tailPointer_[id] = pointer; docBuffer.clear(); scoreBuffer.clear(); if (docBuffer.capacity() < MAX_BLOCK_SIZE) { uint32_t newLen = docBuffer.capacity() * EXPANSION_RATE; docBuffer.reserve(newLen); scoreBuffer.reserve(newLen); } } } } void AttrScoreInvertedIndex::flush() { uint32_t term = UNDEFINED_OFFSET; while ((term = buffer_.nextIndex(term, DF_CUTOFF)) != UNDEFINED_OFFSET) { std::vector<uint32_t>& docBuffer = buffer_.docid_[term]; std::vector<uint32_t>& scoreBuffer = buffer_.score_[term]; uint32_t pos = docBuffer.size(); size_t pointer = buffer_.tailPointer_[term]; uint32_t nb = pos / BLOCK_SIZE; uint32_t res = pos % BLOCK_SIZE; for (uint32_t i = 0; i < nb; ++i) { pointer = pool_.compressAndAppend( codec_, &docBuffer[i * BLOCK_SIZE], &scoreBuffer[i * BLOCK_SIZE], BLOCK_SIZE, pointer); if (pool_.isReverse() || pointers_.getHeadPointer(term) == UNDEFINED_POINTER) { pointers_.setHeadPointer(term, pointer); } } if (res > 0) { pointer = pool_.compressAndAppend( codec_, &docBuffer[nb * BLOCK_SIZE], &scoreBuffer[nb * BLOCK_SIZE], res, pointer); if (pool_.isReverse() || pointers_.getHeadPointer(term) == UNDEFINED_POINTER) { pointers_.setHeadPointer(term, pointer); } } buffer_.tailPointer_[term] = pointer; docBuffer.clear(); scoreBuffer.clear(); } } uint32_t AttrScoreInvertedIndex::totalDocNum() const { return pointers_.getTotalDocs(); } void AttrScoreInvertedIndex::retrieval( Algorithm algorithm, const std::vector<std::string>& term_list, uint32_t hits, std::vector<uint32_t>& docid_list, std::vector<uint32_t>& score_list) const { std::vector<std::pair<uint32_t, size_t> > queries; uint32_t minimumDf = 0xFFFFFFFF; for (uint32_t i = 0; i < term_list.size(); ++i) { uint32_t termid = dictionary_.getTermId(term_list[i]); if (termid != INVALID_ID) { size_t pointer = pointers_.getHeadPointer(termid); if (pointer != UNDEFINED_POINTER) { queries.push_back(std::make_pair(pointers_.getDf(termid), pointer)); minimumDf = std::min(queries.back().first, minimumDf); } } } if (queries.empty()) return; if (algorithm == SVS) { std::sort(queries.begin(), queries.end()); } std::vector<size_t> qHeadPointers(queries.size()); for (uint32_t i = 0; i < queries.size(); ++i) { qHeadPointers[i] = queries[i].second; } if (algorithm == SVS) { pool_.intersectSvS(qHeadPointers, minimumDf, hits, docid_list, score_list); } } void AttrScoreInvertedIndex::retrievalAndFiltering( Algorithm algorithm, const std::vector<std::string>& term_list, const boost::function<bool(uint32_t)>& filter, uint32_t hits, std::vector<uint32_t>& docid_list, std::vector<uint32_t>& score_list) const { std::vector<std::pair<uint32_t, size_t> > queries; uint32_t minimumDf = 0xFFFFFFFF; for (uint32_t i = 0; i < term_list.size(); ++i) { uint32_t termid = dictionary_.getTermId(term_list[i]); if (termid != INVALID_ID) { size_t pointer = pointers_.getHeadPointer(termid); if (pointer != UNDEFINED_POINTER) { queries.push_back(std::make_pair(pointers_.getDf(termid), pointer)); minimumDf = std::min(queries.back().first, minimumDf); } } } if (queries.empty()) return; if (algorithm == SVS) { std::sort(queries.begin(), queries.end()); } std::vector<size_t> qHeadPointers(queries.size()); for (uint32_t i = 0; i < queries.size(); ++i) { qHeadPointers[i] = queries[i].second; } if (algorithm == SVS) { pool_.intersectSvS(qHeadPointers, filter, minimumDf, hits, docid_list, score_list); } } } NS_IZENELIB_IR_END <commit_msg>fix buffer capacity<commit_after>#include <ir/Zambezi/AttrScoreInvertedIndex.hpp> #include <ir/Zambezi/Utils.hpp> #include <glog/logging.h> NS_IZENELIB_IR_BEGIN namespace Zambezi { AttrScoreInvertedIndex::AttrScoreInvertedIndex( uint32_t maxPoolSize, uint32_t numberOfPools, bool reverse) : buffer_(DEFAULT_VOCAB_SIZE) , pool_(maxPoolSize, numberOfPools, reverse) , dictionary_(DEFAULT_VOCAB_SIZE) , pointers_(DEFAULT_VOCAB_SIZE, 0) { } AttrScoreInvertedIndex::~AttrScoreInvertedIndex() { } void AttrScoreInvertedIndex::save(std::ostream& ostr) const { std::streamoff offset = ostr.tellp(); buffer_.save(ostr); LOG(INFO) << "Saving: buffer maps size " << ostr.tellp() - offset; offset = ostr.tellp(); pool_.save(ostr); LOG(INFO) << "Saving: segment pools size " << ostr.tellp() - offset; offset = ostr.tellp(); dictionary_.save(ostr); LOG(INFO) << "Saving: dictionary size " << ostr.tellp() - offset; offset = ostr.tellp(); pointers_.save(ostr); LOG(INFO) << "Saving: head pointers size " << ostr.tellp() - offset; } void AttrScoreInvertedIndex::load(std::istream& istr) { std::streamoff offset = istr.tellg(); buffer_.load(istr); LOG(INFO) << "Loading: buffer maps size " << istr.tellg() - offset; offset = istr.tellg(); pool_.load(istr); LOG(INFO) << "Loading: segment pool size " << istr.tellg() - offset; offset = istr.tellg(); dictionary_.load(istr); LOG(INFO) << "Loading: dictionary size " << istr.tellg() - offset; offset = istr.tellg(); pointers_.load(istr); LOG(INFO) << "Loading: head pointers size " << istr.tellg() - offset; } bool AttrScoreInvertedIndex::hasValidPostingsList(uint32_t termid) const { return pointers_.getHeadPointer(termid) != UNDEFINED_POINTER; } void AttrScoreInvertedIndex::insertDoc( uint32_t docid, const std::vector<std::string>& term_list, const std::vector<uint32_t>& score_list) { for (uint32_t i = 0; i < term_list.size(); ++i) { uint32_t id = dictionary_.insertTerm(term_list[i]); pointers_.cf_.increment(id); pointers_.df_.increment(id); std::vector<uint32_t>& docBuffer = buffer_.getDocidList(id); std::vector<uint32_t>& scoreBuffer = buffer_.getScoreList(id); if (pointers_.getDf(id) < DF_CUTOFF) { if (docBuffer.capacity() == 0) { docBuffer.reserve(DF_CUTOFF); scoreBuffer.reserve(DF_CUTOFF); } docBuffer.push_back(docid); scoreBuffer.push_back(score_list[i]); continue; } if (docBuffer.capacity() < BLOCK_SIZE) { docBuffer.reserve(BLOCK_SIZE); scoreBuffer.reserve(BLOCK_SIZE); } docBuffer.push_back(docid); scoreBuffer.push_back(score_list[i]); if (docBuffer.size() == docBuffer.capacity()) { uint32_t nb = docBuffer.size() / BLOCK_SIZE; size_t pointer = buffer_.tailPointer_[id]; for (uint32_t j = 0; j < nb; ++j) { pointer = pool_.compressAndAppend( codec_, &docBuffer[j * BLOCK_SIZE], &scoreBuffer[j * BLOCK_SIZE], BLOCK_SIZE, pointer); if (pool_.isReverse() || pointers_.getHeadPointer(id) == UNDEFINED_POINTER) { pointers_.setHeadPointer(id, pointer); } } buffer_.tailPointer_[id] = pointer; docBuffer.clear(); scoreBuffer.clear(); if (docBuffer.capacity() < MAX_BLOCK_SIZE) { uint32_t newLen = docBuffer.capacity() * EXPANSION_RATE; docBuffer.reserve(newLen); scoreBuffer.reserve(newLen); } } } } void AttrScoreInvertedIndex::flush() { uint32_t term = UNDEFINED_OFFSET; while ((term = buffer_.nextIndex(term, DF_CUTOFF)) != UNDEFINED_OFFSET) { std::vector<uint32_t>& docBuffer = buffer_.docid_[term]; std::vector<uint32_t>& scoreBuffer = buffer_.score_[term]; uint32_t pos = docBuffer.size(); size_t pointer = buffer_.tailPointer_[term]; uint32_t nb = pos / BLOCK_SIZE; uint32_t res = pos % BLOCK_SIZE; for (uint32_t i = 0; i < nb; ++i) { pointer = pool_.compressAndAppend( codec_, &docBuffer[i * BLOCK_SIZE], &scoreBuffer[i * BLOCK_SIZE], BLOCK_SIZE, pointer); if (pool_.isReverse() || pointers_.getHeadPointer(term) == UNDEFINED_POINTER) { pointers_.setHeadPointer(term, pointer); } } if (res > 0) { pointer = pool_.compressAndAppend( codec_, &docBuffer[nb * BLOCK_SIZE], &scoreBuffer[nb * BLOCK_SIZE], res, pointer); if (pool_.isReverse() || pointers_.getHeadPointer(term) == UNDEFINED_POINTER) { pointers_.setHeadPointer(term, pointer); } } buffer_.tailPointer_[term] = pointer; docBuffer.clear(); scoreBuffer.clear(); } } uint32_t AttrScoreInvertedIndex::totalDocNum() const { return pointers_.getTotalDocs(); } void AttrScoreInvertedIndex::retrieval( Algorithm algorithm, const std::vector<std::string>& term_list, uint32_t hits, std::vector<uint32_t>& docid_list, std::vector<uint32_t>& score_list) const { std::vector<std::pair<uint32_t, size_t> > queries; uint32_t minimumDf = 0xFFFFFFFF; for (uint32_t i = 0; i < term_list.size(); ++i) { uint32_t termid = dictionary_.getTermId(term_list[i]); if (termid != INVALID_ID) { size_t pointer = pointers_.getHeadPointer(termid); if (pointer != UNDEFINED_POINTER) { queries.push_back(std::make_pair(pointers_.getDf(termid), pointer)); minimumDf = std::min(queries.back().first, minimumDf); } } } if (queries.empty()) return; if (algorithm == SVS) { std::sort(queries.begin(), queries.end()); } std::vector<size_t> qHeadPointers(queries.size()); for (uint32_t i = 0; i < queries.size(); ++i) { qHeadPointers[i] = queries[i].second; } if (algorithm == SVS) { pool_.intersectSvS(qHeadPointers, minimumDf, hits, docid_list, score_list); } } void AttrScoreInvertedIndex::retrievalAndFiltering( Algorithm algorithm, const std::vector<std::string>& term_list, const boost::function<bool(uint32_t)>& filter, uint32_t hits, std::vector<uint32_t>& docid_list, std::vector<uint32_t>& score_list) const { std::vector<std::pair<uint32_t, size_t> > queries; uint32_t minimumDf = 0xFFFFFFFF; for (uint32_t i = 0; i < term_list.size(); ++i) { uint32_t termid = dictionary_.getTermId(term_list[i]); if (termid != INVALID_ID) { size_t pointer = pointers_.getHeadPointer(termid); if (pointer != UNDEFINED_POINTER) { queries.push_back(std::make_pair(pointers_.getDf(termid), pointer)); minimumDf = std::min(queries.back().first, minimumDf); } } } if (queries.empty()) return; if (algorithm == SVS) { std::sort(queries.begin(), queries.end()); } std::vector<size_t> qHeadPointers(queries.size()); for (uint32_t i = 0; i < queries.size(); ++i) { qHeadPointers[i] = queries[i].second; } if (algorithm == SVS) { pool_.intersectSvS(qHeadPointers, filter, minimumDf, hits, docid_list, score_list); } } } NS_IZENELIB_IR_END <|endoftext|>
<commit_before>/* * * Copyright (C) 2020 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "source/loader/driver_discovery.h" #include "source/inc/ze_util.h" #include <iostream> #include <sstream> #include <string> namespace loader { static const char *knownDriverNames[] = { MAKE_LIBRARY_NAME("ze_intel_gpu", "1"), }; std::vector<DriverLibraryPath> discoverEnabledDrivers() { std::vector<DriverLibraryPath> enabledDrivers; const char *altDrivers = nullptr; // ZE_ENABLE_ALT_DRIVERS is for development/debug only altDrivers = getenv("ZE_ENABLE_ALT_DRIVERS"); if (altDrivers == nullptr) { for (auto path : knownDriverNames) { enabledDrivers.emplace_back(path); } } else { std::stringstream ss(altDrivers); while (ss.good()) { std::string substr; getline(ss, substr, ','); enabledDrivers.emplace_back(substr); } } return enabledDrivers; } } // namespace loader <commit_msg>Add Intel VPU driver to known driver list<commit_after>/* * * Copyright (C) 2020 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "source/loader/driver_discovery.h" #include "source/inc/ze_util.h" #include <iostream> #include <sstream> #include <string> namespace loader { static const char *knownDriverNames[] = { MAKE_LIBRARY_NAME("ze_intel_gpu", "1"), MAKE_LIBRARY_NAME("ze_intel_vpu", "1"), }; std::vector<DriverLibraryPath> discoverEnabledDrivers() { std::vector<DriverLibraryPath> enabledDrivers; const char *altDrivers = nullptr; // ZE_ENABLE_ALT_DRIVERS is for development/debug only altDrivers = getenv("ZE_ENABLE_ALT_DRIVERS"); if (altDrivers == nullptr) { for (auto path : knownDriverNames) { enabledDrivers.emplace_back(path); } } else { std::stringstream ss(altDrivers); while (ss.good()) { std::string substr; getline(ss, substr, ','); enabledDrivers.emplace_back(substr); } } return enabledDrivers; } } // namespace loader <|endoftext|>
<commit_before>/* Copyright © 2001-2019, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Stay tuned using twitter @navitia channel `#navitia` on riot https://riot.im/app/#/room/#navitia:matrix.org https://groups.google.com/d/forum/navitia www.navitia.io */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE position_test #include <boost/test/unit_test.hpp> #include "ed/build_helper.h" #include "position/position_api.h" #include "type/pb_converter.h" #include "utils/logger.h" #include "type/pt_data.h" #include "tests/utils_test.h" using namespace navitia; using boost::posix_time::time_period; struct logger_initialized { logger_initialized() { navitia::init_logger(); } }; BOOST_GLOBAL_FIXTURE(logger_initialized); namespace { class positionTestFixture { public: ed::builder b; const type::Data& data; positionTestFixture() : b("20210913"), data(*b.data) { b.vj_with_network("network:R", "line:A", "1111111", "", true, "")("stop_area:stop1", "10:00"_t, "10:00"_t)( "stop_area:stop2", "11:00"_t, "11:00"_t); b.vj_with_network("network:R", "line:S", "1111111", "", true, "")("stop_area:stop5", "14:00"_t, "14:00"_t)( "stop_area:stop6", "15:00"_t, "15:00"_t); b.vj_with_network("network:K", "line:KA", "1111111", "", true, "KA")( "stop_area:stop_k_0", "14:00"_t, "14:00"_t)("stop_area:stop_k_1", "15:00"_t, "15:00"_t)( "stop_area:stop_k_2", "16:00"_t, "16:00"_t); b.vj_with_network("network:K", "line:KA", "1111111", "", true, "KB")( "stop_area:stop_k_0", "15:00"_t, "15:00"_t)("stop_area:stop_k_1", "16:00"_t, "16:00"_t); auto& vj = data.pt_data->vehicle_journeys_map.at("vehicle_journey:line:S:1"); data.pt_data->codes.add(vj, "source", "network:R-line:S"); vj = data.pt_data->vehicle_journeys_map.at("vehicle_journey:line:A:0"); data.pt_data->codes.add(vj, "source", "network:R-line:A"); b.make(); } }; BOOST_FIXTURE_TEST_CASE(test_one_vehicle_position_by_network, positionTestFixture) { const ptime current_datetime = "20210913T095500"_dt; const ptime since = current_datetime; const ptime until = current_datetime + boost::posix_time::minutes(10); navitia::PbCreator pb_creator; pb_creator.init(&data, current_datetime, null_time_period); navitia::position::vehicle_positions(pb_creator, R"#(network.uri="network:R")#", 10, 0, 0, {}, since, until); pbnavitia::Response resp = pb_creator.get_response(); BOOST_REQUIRE_EQUAL(resp.vehicle_positions().size(), 1); auto vehicle_position = resp.vehicle_positions(0); BOOST_REQUIRE_EQUAL(vehicle_position.line().uri(), "line:A"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().uri(), "vehicle_journey:line:A:0"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).type(), "source"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).value(), "network:R-line:A"); } BOOST_FIXTURE_TEST_CASE(test_many_vehicle_position_by_network, positionTestFixture) { const ptime current_datetime = "20210913T100000"_dt; const ptime since = current_datetime; const ptime until = current_datetime + boost::posix_time::minutes(4 * 60); navitia::PbCreator pb_creator; pb_creator.init(&data, current_datetime, null_time_period); navitia::position::vehicle_positions(pb_creator, R"#(network.uri="network:R")#", 10, 0, 0, {}, since, until); pbnavitia::Response resp = pb_creator.get_response(); BOOST_REQUIRE_EQUAL(resp.vehicle_positions().size(), 2); auto vehicle_position = resp.vehicle_positions(0); BOOST_REQUIRE_EQUAL(vehicle_position.line().uri(), "line:A"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().uri(), "vehicle_journey:line:A:0"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).type(), "source"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).value(), "network:R-line:A"); vehicle_position = resp.vehicle_positions(1); BOOST_REQUIRE_EQUAL(vehicle_position.line().uri(), "line:S"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().uri(), "vehicle_journey:line:S:1"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).type(), "source"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).value(), "network:R-line:S"); } BOOST_FIXTURE_TEST_CASE(test_vehicle_position_by_network_and_line, positionTestFixture) { const ptime current_datetime = "20210913T100000"_dt; const ptime since = current_datetime; const ptime until = current_datetime + boost::posix_time::minutes(4 * 60); navitia::PbCreator pb_creator; pb_creator.init(&data, current_datetime, null_time_period); navitia::position::vehicle_positions(pb_creator, R"#(network.uri="network:R" and line.uri="line:A")#", 10, 0, 0, {}, since, until); pbnavitia::Response resp = pb_creator.get_response(); BOOST_REQUIRE_EQUAL(resp.vehicle_positions().size(), 1); auto vehicle_position = resp.vehicle_positions(0); BOOST_REQUIRE_EQUAL(vehicle_position.line().uri(), "line:A"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().uri(), "vehicle_journey:line:A:0"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).type(), "source"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).value(), "network:R-line:A"); } BOOST_FIXTURE_TEST_CASE(test_vehicle_position_by_network_and_stop_area, positionTestFixture) { const ptime current_datetime = "20210913T100000"_dt; const ptime since = current_datetime; const ptime until = current_datetime + boost::posix_time::minutes(4 * 60); navitia::PbCreator pb_creator; pb_creator.init(&data, current_datetime, null_time_period); navitia::position::vehicle_positions(pb_creator, R"#(network.uri="network:R" and stop_area.uri="stop_area:stop1")#", 10, 0, 0, {}, since, until); pbnavitia::Response resp = pb_creator.get_response(); BOOST_REQUIRE_EQUAL(resp.vehicle_positions().size(), 1); auto vehicle_position = resp.vehicle_positions(0); BOOST_REQUIRE_EQUAL(vehicle_position.line().uri(), "line:A"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().uri(), "vehicle_journey:line:A:0"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).type(), "source"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).value(), "network:R-line:A"); } BOOST_FIXTURE_TEST_CASE(test_one_vehicle_position_by_network_many_position_by_line, positionTestFixture) { const ptime current_datetime = "20210913T131000"_dt; const ptime since = current_datetime; const ptime until = current_datetime + boost::posix_time::hours(2); navitia::PbCreator pb_creator; pb_creator.init(&data, current_datetime, null_time_period); navitia::position::vehicle_positions(pb_creator, R"#(network.uri="network:K")#", 10, 0, 0, {}, since, until); pbnavitia::Response resp = pb_creator.get_response(); BOOST_REQUIRE_EQUAL(resp.vehicle_positions().size(), 1); auto vehicle_position = resp.vehicle_positions(0); BOOST_REQUIRE_EQUAL(vehicle_position.line().uri(), "line:KA"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions().size(), 2); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().uri(), "vehicle_journey:KB"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes().size(), 0); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(1).vehicle_journey().uri(), "vehicle_journey:KA"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(1).vehicle_journey().codes().size(), 0); } } // namespace <commit_msg>correction<commit_after>/* Copyright © 2001-2019, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Stay tuned using twitter @navitia channel `#navitia` on riot https://riot.im/app/#/room/#navitia:matrix.org https://groups.google.com/d/forum/navitia www.navitia.io */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE position_test #include <boost/test/unit_test.hpp> #include "ed/build_helper.h" #include "position/position_api.h" #include "type/pb_converter.h" #include "utils/logger.h" #include "type/pt_data.h" #include "tests/utils_test.h" using namespace navitia; using boost::posix_time::time_period; struct logger_initialized { logger_initialized() { navitia::init_logger(); } }; BOOST_GLOBAL_FIXTURE(logger_initialized); namespace { class positionTestFixture { public: ed::builder b; const type::Data& data; positionTestFixture() : b("20210913"), data(*b.data) { b.vj_with_network("network:R", "line:A", "1111111", "", true, "")("stop_area:stop1", "10:00"_t, "10:00"_t)( "stop_area:stop2", "11:00"_t, "11:00"_t); b.vj_with_network("network:R", "line:S", "1111111", "", true, "")("stop_area:stop5", "14:00"_t, "14:00"_t)( "stop_area:stop6", "15:00"_t, "15:00"_t); b.vj_with_network("network:K", "line:KA", "1111111", "", true, "KA")( "stop_area:stop_k_0", "14:00"_t, "14:00"_t)("stop_area:stop_k_1", "15:00"_t, "15:00"_t)( "stop_area:stop_k_2", "16:00"_t, "16:00"_t); b.vj_with_network("network:K", "line:KA", "1111111", "", true, "KB")( "stop_area:stop_k_0", "15:00"_t, "15:00"_t)("stop_area:stop_k_1", "16:00"_t, "16:00"_t); auto& vj = data.pt_data->vehicle_journeys_map.at("vehicle_journey:line:S:1"); data.pt_data->codes.add(vj, "source", "network:R-line:S"); vj = data.pt_data->vehicle_journeys_map.at("vehicle_journey:line:A:0"); data.pt_data->codes.add(vj, "source", "network:R-line:A"); b.make(); } }; BOOST_FIXTURE_TEST_CASE(test_one_vehicle_position_by_network, positionTestFixture) { const ptime current_datetime = "20210913T095500"_dt; const ptime since = current_datetime; const ptime until = current_datetime + boost::posix_time::minutes(10); navitia::PbCreator pb_creator; pb_creator.init(&data, current_datetime, null_time_period); navitia::position::vehicle_positions(pb_creator, "(network.uri=\"network:R\"", 10, 0, 0, {}, since, until); pbnavitia::Response resp = pb_creator.get_response(); BOOST_REQUIRE_EQUAL(resp.vehicle_positions().size(), 1); auto vehicle_position = resp.vehicle_positions(0); BOOST_REQUIRE_EQUAL(vehicle_position.line().uri(), "line:A"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().uri(), "vehicle_journey:line:A:0"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).type(), "source"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).value(), "network:R-line:A"); } BOOST_FIXTURE_TEST_CASE(test_many_vehicle_position_by_network, positionTestFixture) { const ptime current_datetime = "20210913T100000"_dt; const ptime since = current_datetime; const ptime until = current_datetime + boost::posix_time::minutes(4 * 60); navitia::PbCreator pb_creator; pb_creator.init(&data, current_datetime, null_time_period); navitia::position::vehicle_positions(pb_creator, "network.uri=\"network:R\"", 10, 0, 0, {}, since, until); pbnavitia::Response resp = pb_creator.get_response(); BOOST_REQUIRE_EQUAL(resp.vehicle_positions().size(), 2); auto vehicle_position = resp.vehicle_positions(0); BOOST_REQUIRE_EQUAL(vehicle_position.line().uri(), "line:A"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().uri(), "vehicle_journey:line:A:0"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).type(), "source"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).value(), "network:R-line:A"); vehicle_position = resp.vehicle_positions(1); BOOST_REQUIRE_EQUAL(vehicle_position.line().uri(), "line:S"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().uri(), "vehicle_journey:line:S:1"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).type(), "source"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).value(), "network:R-line:S"); } BOOST_FIXTURE_TEST_CASE(test_vehicle_position_by_network_and_line, positionTestFixture) { const ptime current_datetime = "20210913T100000"_dt; const ptime since = current_datetime; const ptime until = current_datetime + boost::posix_time::minutes(4 * 60); navitia::PbCreator pb_creator; pb_creator.init(&data, current_datetime, null_time_period); navitia::position::vehicle_positions(pb_creator, "network.uri=\"network:R\" and line.uri=\"line:A\"", 10, 0, 0, {}, since, until); pbnavitia::Response resp = pb_creator.get_response(); BOOST_REQUIRE_EQUAL(resp.vehicle_positions().size(), 1); auto vehicle_position = resp.vehicle_positions(0); BOOST_REQUIRE_EQUAL(vehicle_position.line().uri(), "line:A"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().uri(), "vehicle_journey:line:A:0"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).type(), "source"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).value(), "network:R-line:A"); } BOOST_FIXTURE_TEST_CASE(test_vehicle_position_by_network_and_stop_area, positionTestFixture) { const ptime current_datetime = "20210913T100000"_dt; const ptime since = current_datetime; const ptime until = current_datetime + boost::posix_time::minutes(4 * 60); navitia::PbCreator pb_creator; pb_creator.init(&data, current_datetime, null_time_period); navitia::position::vehicle_positions(pb_creator, "network.uri=\"network:R\" and stop_area.uri=\"stop_area:stop1\"", 10, 0, 0, {}, since, until); pbnavitia::Response resp = pb_creator.get_response(); BOOST_REQUIRE_EQUAL(resp.vehicle_positions().size(), 1); auto vehicle_position = resp.vehicle_positions(0); BOOST_REQUIRE_EQUAL(vehicle_position.line().uri(), "line:A"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().uri(), "vehicle_journey:line:A:0"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).type(), "source"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).value(), "network:R-line:A"); } BOOST_FIXTURE_TEST_CASE(test_one_vehicle_position_by_network_many_position_by_line, positionTestFixture) { const ptime current_datetime = "20210913T131000"_dt; const ptime since = current_datetime; const ptime until = current_datetime + boost::posix_time::hours(2); navitia::PbCreator pb_creator; pb_creator.init(&data, current_datetime, null_time_period); navitia::position::vehicle_positions(pb_creator, "network.uri=\"network:K\"", 10, 0, 0, {}, since, until); pbnavitia::Response resp = pb_creator.get_response(); BOOST_REQUIRE_EQUAL(resp.vehicle_positions().size(), 1); auto vehicle_position = resp.vehicle_positions(0); BOOST_REQUIRE_EQUAL(vehicle_position.line().uri(), "line:KA"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions().size(), 2); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().uri(), "vehicle_journey:KB"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes().size(), 0); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(1).vehicle_journey().uri(), "vehicle_journey:KA"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(1).vehicle_journey().codes().size(), 0); } } // namespace <|endoftext|>
<commit_before>#include "Game.h" Game::Game() : board(10, 10, 2), renderer(), gameState(IN_GAME) { } int Game::init() { // Handle renderer setup if(renderer.init() != 0) { renderer.quit(); return 1; } return 0; } // Returns a bool indicating if the game should continue (true) or terminate (false) bool Game::handle_input(SDL_Event &event) { // Close window if(event.type == SDL_QUIT) { return false; } // Presses any key if(event.type == SDL_KEYDOWN) { switch(inputHandler.handle_key(event)) { case InputHandler::Action::QUIT: return false; } } // Click the mouse if(event.type == SDL_MOUSEBUTTONDOWN) { std::tuple<int, int> row_and_col = inputHandler.row_col_from_click_coordinates( board.get_height(), board.get_width(), renderer.get_window_dimensions(), event ); board.select_tile(std::get<0>(row_and_col), std::get<1>(row_and_col)); } return true; } int Game::main_loop() { bool running = true; SDL_Event event; while(running) { while(SDL_PollEvent(&event)) { running = handle_input(event); } renderer.render(board); } return 0; } <commit_msg>Add missing refactor from last commit<commit_after>#include "Game.h" Game::Game() : board(10, 10, 2), renderer(), gameState(IN_GAME) { } int Game::init() { // Handle renderer setup if(renderer.init() != 0) { renderer.quit(); return 1; } return 0; } // Returns a bool indicating if the game should continue (true) or terminate (false) bool Game::handle_input(SDL_Event &event) { // Close window if(event.type == SDL_QUIT) { return false; } // Presses any key if(event.type == SDL_KEYDOWN) { switch(inputHandler.handle_key(event)) { case InputHandler::Action::QUIT: return false; } } // Click the mouse if(event.type == SDL_MOUSEBUTTONDOWN) { std::tuple<int, int> row_and_col = inputHandler.row_col_from_click_coordinates( board.get_height(), board.get_width(), renderer.get_window_dimensions(), event ); board.select_tile(std::get<0>(row_and_col), std::get<1>(row_and_col)); } return true; } int Game::main_loop() { bool running = true; SDL_Event event; while(running) { while(SDL_PollEvent(&event)) { running = handle_input(event); } renderer.render_in_game(board); } return 0; } <|endoftext|>
<commit_before>/* Copyright © 2001-2019, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Stay tuned using twitter @navitia channel `#navitia` on riot https://riot.im/app/#/room/#navitia:matrix.org https://groups.google.com/d/forum/navitia www.navitia.io */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE position_test #include <boost/test/unit_test.hpp> #include "ed/build_helper.h" #include "position/position_api.h" #include "type/pb_converter.h" #include "utils/logger.h" #include "type/pt_data.h" #include "tests/utils_test.h" using namespace navitia; using boost::posix_time::time_period; struct logger_initialized { logger_initialized() { navitia::init_logger(); } }; BOOST_GLOBAL_FIXTURE(logger_initialized); namespace { class positionTestFixture { public: ed::builder b; const type::Data& data; positionTestFixture() : b("20210913"), data(*b.data) { b.vj_with_network("network:R", "line:A", "1111111", "", true, "")("stop_area:stop1", "10:00"_t, "10:00"_t)( "stop_area:stop2", "11:00"_t, "11:00"_t); b.vj_with_network("network:R", "line:S", "1111111", "", true, "")("stop_area:stop5", "14:00"_t, "14:00"_t)( "stop_area:stop6", "15:00"_t, "15:00"_t); auto& vj = data.pt_data->vehicle_journeys_map.at("vehicle_journey:line:S:1"); data.pt_data->codes.add(vj, "source", "network:R-line:S"); vj = data.pt_data->vehicle_journeys_map.at("vehicle_journey:line:A:0"); data.pt_data->codes.add(vj, "source", "network:R-line:A"); b.make(); } }; BOOST_FIXTURE_TEST_CASE(test_one_vehicle_position_by_network, positionTestFixture) { const ptime current_datetime = "20210913T095500"_dt; const ptime since = current_datetime; const ptime until = current_datetime + boost::posix_time::minutes(10); navitia::PbCreator pb_creator; pb_creator.init(&data, current_datetime, null_time_period); navitia::position::vehicle_positions(pb_creator, "network.uri=\"network:R\"", 10, 0, 0, {}, since, until); pbnavitia::Response resp = pb_creator.get_response(); BOOST_REQUIRE_EQUAL(resp.vehicle_positions().size(), 1); auto vehicle_position = resp.vehicle_positions(0); BOOST_REQUIRE_EQUAL(vehicle_position.line().uri(), "line:A"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().uri(), "vehicle_journey:line:A:0"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).type(), "source"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).value(), "network:R-line:A"); } BOOST_FIXTURE_TEST_CASE(test_many_vehicle_position_by_network, positionTestFixture) { const ptime current_datetime = "20210913T100000"_dt; const ptime since = current_datetime; const ptime until = current_datetime + boost::posix_time::minutes(4 * 60); navitia::PbCreator pb_creator; pb_creator.init(&data, current_datetime, null_time_period); navitia::position::vehicle_positions(pb_creator, "network.uri=\"network:R\"", 10, 0, 0, {}, since, until); pbnavitia::Response resp = pb_creator.get_response(); BOOST_REQUIRE_EQUAL(resp.vehicle_positions().size(), 2); auto vehicle_position = resp.vehicle_positions(0); BOOST_REQUIRE_EQUAL(vehicle_position.line().uri(), "line:A"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().uri(), "vehicle_journey:line:A:0"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).type(), "source"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).value(), "network:R-line:A"); vehicle_position = resp.vehicle_positions(1); BOOST_REQUIRE_EQUAL(vehicle_position.line().uri(), "line:S"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().uri(), "vehicle_journey:line:S:1"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).type(), "source"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).value(), "network:R-line:S"); } BOOST_FIXTURE_TEST_CASE(test_vehicle_position_by_network_and_line, positionTestFixture) { const ptime current_datetime = "20210913T100000"_dt; const ptime since = current_datetime; const ptime until = current_datetime + boost::posix_time::minutes(4 * 60); navitia::PbCreator pb_creator; pb_creator.init(&data, current_datetime, null_time_period); navitia::position::vehicle_positions(pb_creator, "network.uri=\"network:R\" and line.uri=\"line:A\"", 10, 0, 0, {}, since, until); pbnavitia::Response resp = pb_creator.get_response(); BOOST_REQUIRE_EQUAL(resp.vehicle_positions().size(), 1); auto vehicle_position = resp.vehicle_positions(0); BOOST_REQUIRE_EQUAL(vehicle_position.line().uri(), "line:A"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().uri(), "vehicle_journey:line:A:0"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).type(), "source"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).value(), "network:R-line:A"); } BOOST_FIXTURE_TEST_CASE(test_vehicle_position_by_network_and_stop_area, positionTestFixture) { const ptime current_datetime = "20210913T100000"_dt; const ptime since = current_datetime; const ptime until = current_datetime + boost::posix_time::minutes(4 * 60); navitia::PbCreator pb_creator; pb_creator.init(&data, current_datetime, null_time_period); navitia::position::vehicle_positions(pb_creator, "network.uri=\"network:R\" and stop_area.uri=\"stop_area:stop1\"", 10, 0, 0, {}, since, until); pbnavitia::Response resp = pb_creator.get_response(); BOOST_REQUIRE_EQUAL(resp.vehicle_positions().size(), 1); auto vehicle_position = resp.vehicle_positions(0); BOOST_REQUIRE_EQUAL(vehicle_position.line().uri(), "line:A"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().uri(), "vehicle_journey:line:A:0"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).type(), "source"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).value(), "network:R-line:A"); } } // namespace <commit_msg>corrections<commit_after>/* Copyright © 2001-2019, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Stay tuned using twitter @navitia channel `#navitia` on riot https://riot.im/app/#/room/#navitia:matrix.org https://groups.google.com/d/forum/navitia www.navitia.io */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE position_test #include <boost/test/unit_test.hpp> #include "ed/build_helper.h" #include "position/position_api.h" #include "type/pb_converter.h" #include "utils/logger.h" #include "type/pt_data.h" #include "tests/utils_test.h" using namespace navitia; using boost::posix_time::time_period; struct logger_initialized { logger_initialized() { navitia::init_logger(); } }; BOOST_GLOBAL_FIXTURE(logger_initialized); namespace { class positionTestFixture { public: ed::builder b; const type::Data& data; positionTestFixture() : b("20210913"), data(*b.data) { b.vj_with_network("network:R", "line:A", "1111111", "", true, "")("stop_area:stop1", "10:00"_t, "10:00"_t)( "stop_area:stop2", "11:00"_t, "11:00"_t); b.vj_with_network("network:R", "line:S", "1111111", "", true, "")("stop_area:stop5", "14:00"_t, "14:00"_t)( "stop_area:stop6", "15:00"_t, "15:00"_t); b.vj_with_network("network:K", "line:KA", "1111111", "", true, "KA")( "stop_area:stop_k_0", "14:00"_t, "14:00"_t)("stop_area:stop_k_1", "15:00"_t, "15:00"_t)( "stop_area:stop_k_2", "16:00"_t, "16:00"_t); b.vj_with_network("network:K", "line:KA", "1111111", "", true, "KB")( "stop_area:stop_k_0", "15:00"_t, "15:00"_t)("stop_area:stop_k_1", "16:00"_t, "16:00"_t); auto& vj = data.pt_data->vehicle_journeys_map.at("vehicle_journey:line:S:1"); data.pt_data->codes.add(vj, "source", "network:R-line:S"); vj = data.pt_data->vehicle_journeys_map.at("vehicle_journey:line:A:0"); data.pt_data->codes.add(vj, "source", "network:R-line:A"); b.make(); } }; BOOST_FIXTURE_TEST_CASE(test_one_vehicle_position_by_network, positionTestFixture) { const ptime current_datetime = "20210913T095500"_dt; const ptime since = current_datetime; const ptime until = current_datetime + boost::posix_time::minutes(10); navitia::PbCreator pb_creator; pb_creator.init(&data, current_datetime, null_time_period); navitia::position::vehicle_positions(pb_creator, R"(network.uri="network:R")", 10, 0, 0, {}, since, until); pbnavitia::Response resp = pb_creator.get_response(); BOOST_REQUIRE_EQUAL(resp.vehicle_positions().size(), 1); auto vehicle_position = resp.vehicle_positions(0); BOOST_REQUIRE_EQUAL(vehicle_position.line().uri(), "line:A"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().uri(), "vehicle_journey:line:A:0"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).type(), "source"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).value(), "network:R-line:A"); } BOOST_FIXTURE_TEST_CASE(test_many_vehicle_position_by_network, positionTestFixture) { const ptime current_datetime = "20210913T100000"_dt; const ptime since = current_datetime; const ptime until = current_datetime + boost::posix_time::minutes(4 * 60); navitia::PbCreator pb_creator; pb_creator.init(&data, current_datetime, null_time_period); navitia::position::vehicle_positions(pb_creator, R"(network.uri="network:R")", 10, 0, 0, {}, since, until); pbnavitia::Response resp = pb_creator.get_response(); BOOST_REQUIRE_EQUAL(resp.vehicle_positions().size(), 2); auto vehicle_position = resp.vehicle_positions(0); BOOST_REQUIRE_EQUAL(vehicle_position.line().uri(), "line:A"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().uri(), "vehicle_journey:line:A:0"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).type(), "source"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).value(), "network:R-line:A"); vehicle_position = resp.vehicle_positions(1); BOOST_REQUIRE_EQUAL(vehicle_position.line().uri(), "line:S"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().uri(), "vehicle_journey:line:S:1"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).type(), "source"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).value(), "network:R-line:S"); } BOOST_FIXTURE_TEST_CASE(test_vehicle_position_by_network_and_line, positionTestFixture) { const ptime current_datetime = "20210913T100000"_dt; const ptime since = current_datetime; const ptime until = current_datetime + boost::posix_time::minutes(4 * 60); navitia::PbCreator pb_creator; pb_creator.init(&data, current_datetime, null_time_period); navitia::position::vehicle_positions(pb_creator, R"(network.uri="network:R" and line.uri="line:A")", 10, 0, 0, {}, since, until); pbnavitia::Response resp = pb_creator.get_response(); BOOST_REQUIRE_EQUAL(resp.vehicle_positions().size(), 1); auto vehicle_position = resp.vehicle_positions(0); BOOST_REQUIRE_EQUAL(vehicle_position.line().uri(), "line:A"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().uri(), "vehicle_journey:line:A:0"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).type(), "source"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).value(), "network:R-line:A"); } BOOST_FIXTURE_TEST_CASE(test_vehicle_position_by_network_and_stop_area, positionTestFixture) { const ptime current_datetime = "20210913T100000"_dt; const ptime since = current_datetime; const ptime until = current_datetime + boost::posix_time::minutes(4 * 60); navitia::PbCreator pb_creator; pb_creator.init(&data, current_datetime, null_time_period); navitia::position::vehicle_positions(pb_creator, R"(network.uri="network:R" and stop_area.uri="stop_area:stop1")", 10, 0, 0, {}, since, until); pbnavitia::Response resp = pb_creator.get_response(); BOOST_REQUIRE_EQUAL(resp.vehicle_positions().size(), 1); auto vehicle_position = resp.vehicle_positions(0); BOOST_REQUIRE_EQUAL(vehicle_position.line().uri(), "line:A"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().uri(), "vehicle_journey:line:A:0"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes().size(), 1); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).type(), "source"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes(0).value(), "network:R-line:A"); } BOOST_FIXTURE_TEST_CASE(test_one_vehicle_position_by_network_many_position_by_line, positionTestFixture) { const ptime current_datetime = "20210913T131000"_dt; const ptime since = current_datetime; const ptime until = current_datetime + boost::posix_time::hours(2); navitia::PbCreator pb_creator; pb_creator.init(&data, current_datetime, null_time_period); navitia::position::vehicle_positions(pb_creator, R"(network.uri="network:K")", 10, 0, 0, {}, since, until); pbnavitia::Response resp = pb_creator.get_response(); BOOST_REQUIRE_EQUAL(resp.vehicle_positions().size(), 1); auto vehicle_position = resp.vehicle_positions(0); BOOST_REQUIRE_EQUAL(vehicle_position.line().uri(), "line:KA"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions().size(), 2); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().uri(), "vehicle_journey:KB"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(0).vehicle_journey().codes().size(), 0); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(1).vehicle_journey().uri(), "vehicle_journey:KA"); BOOST_REQUIRE_EQUAL(vehicle_position.vehicle_journey_positions(1).vehicle_journey().codes().size(), 0); } } // namespace <|endoftext|>
<commit_before>#include "Game.hpp" #include <Arduino.h> namespace { constexpr uint32_t MsPerUpdate = 200; } // namespace namespace arduino_pong { void Game::run() { while(true) { uint32_t start = millis(); gameField_.update(); gameField_.render(renderer_); int32_t delayValue = start + MsPerUpdate - millis(); Serial.println(delayValue); delay(delayValue < 0 ? 0 : delayValue); } } } // namespace arduino_pong <commit_msg>Speed up the game a bit<commit_after>#include "Game.hpp" #include <Arduino.h> namespace { constexpr uint32_t MsPerUpdate = 30; } // namespace namespace arduino_pong { void Game::run() { while(true) { uint32_t start = millis(); gameField_.update(); gameField_.render(renderer_); int32_t delayValue = start + MsPerUpdate - millis(); #ifdef ARDUINO_PONG_DEBUG Serial.println(delayValue); #endif delay(delayValue < 0 ? 0 : delayValue); } } } // namespace arduino_pong <|endoftext|>
<commit_before>/** * \file * \brief MutexControlBlock class implementation * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2014-11-07 */ #include "distortos/scheduler/MutexControlBlock.hpp" #include "distortos/scheduler/getScheduler.hpp" #include "distortos/scheduler/Scheduler.hpp" #include <cerrno> namespace distortos { namespace scheduler { /*---------------------------------------------------------------------------------------------------------------------+ | public functions +---------------------------------------------------------------------------------------------------------------------*/ MutexControlBlock::MutexControlBlock(const Protocol protocol, const uint8_t priorityCeiling) : blockedList_{getScheduler().getThreadControlBlockListAllocator(), ThreadControlBlock::State::BlockedOnMutex}, list_{}, iterator_{}, owner_{}, protocol_{protocol}, priorityCeiling_{priorityCeiling} { } void MutexControlBlock::block() { if (protocol_ == Protocol::PriorityInheritance) priorityInheritanceBeforeBlock(); getScheduler().block(blockedList_); } int MutexControlBlock::blockUntil(const TickClock::time_point timePoint) { if (protocol_ == Protocol::PriorityInheritance) priorityInheritanceBeforeBlock(); const auto ret = getScheduler().blockUntil(blockedList_, timePoint); // waiting for mutex timed-out and mutex is still locked? if (protocol_ == Protocol::PriorityInheritance && ret == ETIMEDOUT && owner_ != nullptr) owner_->updateBoostedPriority(); return ret; } uint8_t MutexControlBlock::getBoostedPriority() const { if (protocol_ == Protocol::PriorityInheritance) { if (blockedList_.empty() == true) return 0; return blockedList_.begin()->get().getEffectivePriority(); } if (protocol_ == Protocol::PriorityProtect) return priorityCeiling_; return 0; } void MutexControlBlock::lock() { auto& scheduler = scheduler::getScheduler(); owner_ = &scheduler.getCurrentThreadControlBlock(); if (protocol_ == Protocol::None) return; scheduler.getMutexControlBlockListAllocatorPool().feed(link_); list_ = &owner_->getOwnedProtocolMutexControlBlocksList(); list_->emplace_front(*this); iterator_ = list_->begin(); if (protocol_ == Protocol::PriorityProtect) owner_->updateBoostedPriority(); } void MutexControlBlock::unlockOrTransferLock() { auto& oldOwner = *owner_; if (blockedList_.empty() == false) transferLock(); else unlock(); if (protocol_ == Protocol::None) return; oldOwner.updateBoostedPriority(); if (owner_ == nullptr) return; owner_->updateBoostedPriority(); } /*---------------------------------------------------------------------------------------------------------------------+ | private functions +---------------------------------------------------------------------------------------------------------------------*/ void MutexControlBlock::priorityInheritanceBeforeBlock() const { // calling thread is not yet on the blocked list, that's why it's effective priority is given explicitly owner_->updateBoostedPriority(getScheduler().getCurrentThreadControlBlock().getEffectivePriority()); } void MutexControlBlock::transferLock() { owner_ = &blockedList_.begin()->get(); // pass ownership to the unblocked thread scheduler::getScheduler().unblock(blockedList_.begin()); if (list_ == nullptr) return; auto& oldList = *list_; list_ = &owner_->getOwnedProtocolMutexControlBlocksList(); list_->splice(list_->begin(), oldList, iterator_); } void MutexControlBlock::unlock() { owner_ = nullptr; if (list_ == nullptr) return; list_->erase(iterator_); list_ = nullptr; } } // namespace scheduler } // namespace distortos <commit_msg>MutexControlBlock: clear pointer to blocking priority inheritance mutex in MutexControlBlock::blockUntil() after the calling thread is unlocked (for whatever reason)<commit_after>/** * \file * \brief MutexControlBlock class implementation * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2014-11-07 */ #include "distortos/scheduler/MutexControlBlock.hpp" #include "distortos/scheduler/getScheduler.hpp" #include "distortos/scheduler/Scheduler.hpp" #include <cerrno> namespace distortos { namespace scheduler { /*---------------------------------------------------------------------------------------------------------------------+ | public functions +---------------------------------------------------------------------------------------------------------------------*/ MutexControlBlock::MutexControlBlock(const Protocol protocol, const uint8_t priorityCeiling) : blockedList_{getScheduler().getThreadControlBlockListAllocator(), ThreadControlBlock::State::BlockedOnMutex}, list_{}, iterator_{}, owner_{}, protocol_{protocol}, priorityCeiling_{priorityCeiling} { } void MutexControlBlock::block() { if (protocol_ == Protocol::PriorityInheritance) priorityInheritanceBeforeBlock(); getScheduler().block(blockedList_); } int MutexControlBlock::blockUntil(const TickClock::time_point timePoint) { if (protocol_ == Protocol::PriorityInheritance) priorityInheritanceBeforeBlock(); auto& scheduler = getScheduler(); const auto ret = scheduler.blockUntil(blockedList_, timePoint); if (protocol_ == Protocol::PriorityInheritance) { // waiting for mutex timed-out and mutex is still locked? if (ret == ETIMEDOUT && owner_ != nullptr) owner_->updateBoostedPriority(); scheduler.getCurrentThreadControlBlock().setPriorityInheritanceMutexControlBlock(nullptr); } return ret; } uint8_t MutexControlBlock::getBoostedPriority() const { if (protocol_ == Protocol::PriorityInheritance) { if (blockedList_.empty() == true) return 0; return blockedList_.begin()->get().getEffectivePriority(); } if (protocol_ == Protocol::PriorityProtect) return priorityCeiling_; return 0; } void MutexControlBlock::lock() { auto& scheduler = scheduler::getScheduler(); owner_ = &scheduler.getCurrentThreadControlBlock(); if (protocol_ == Protocol::None) return; scheduler.getMutexControlBlockListAllocatorPool().feed(link_); list_ = &owner_->getOwnedProtocolMutexControlBlocksList(); list_->emplace_front(*this); iterator_ = list_->begin(); if (protocol_ == Protocol::PriorityProtect) owner_->updateBoostedPriority(); } void MutexControlBlock::unlockOrTransferLock() { auto& oldOwner = *owner_; if (blockedList_.empty() == false) transferLock(); else unlock(); if (protocol_ == Protocol::None) return; oldOwner.updateBoostedPriority(); if (owner_ == nullptr) return; owner_->updateBoostedPriority(); } /*---------------------------------------------------------------------------------------------------------------------+ | private functions +---------------------------------------------------------------------------------------------------------------------*/ void MutexControlBlock::priorityInheritanceBeforeBlock() const { // calling thread is not yet on the blocked list, that's why it's effective priority is given explicitly owner_->updateBoostedPriority(getScheduler().getCurrentThreadControlBlock().getEffectivePriority()); } void MutexControlBlock::transferLock() { owner_ = &blockedList_.begin()->get(); // pass ownership to the unblocked thread scheduler::getScheduler().unblock(blockedList_.begin()); if (list_ == nullptr) return; auto& oldList = *list_; list_ = &owner_->getOwnedProtocolMutexControlBlocksList(); list_->splice(list_->begin(), oldList, iterator_); } void MutexControlBlock::unlock() { owner_ = nullptr; if (list_ == nullptr) return; list_->erase(iterator_); list_ = nullptr; } } // namespace scheduler } // namespace distortos <|endoftext|>
<commit_before>#include <Game.hpp> #include <iostream> Game::Game(sf::RenderWindow* window): m_window(*window), m_gameState(GAME_STATE::MAIN_MENU), m_level(Level(*window)), m_blackBar(sf::RectangleShape(sf::Vector2f(window->getSize().x, 36))){ m_view.reset(sf::FloatRect(0, 0, 500, 500)); m_window.setFramerateLimit(60); m_window.setView(m_view); if(!m_uiFont.loadFromFile("../resources/font/uiFont.ttf")){ std::cout << "Erro ao carregar a fonte" << std::endl; } m_hero.initHero(HERO_CLASS::THIEF); m_hero.setPosition(1.3*TILE_SIZE, 1.3*TILE_SIZE); // botões do menu inicial auto playButtonId = TextureManager::addTexture("../resources/sprites/buttons/btn_start.png"); m_buttons[0].setTexture(TextureManager::getTexture(playButtonId)); m_buttons[0].centerHorizontal(m_window.getSize().x, 250); loadUI(); m_level.generate(); } void Game::run(){ float currentTime = m_gameClock.restart().asSeconds(); while(m_window.isOpen()){ sf::Event event; while(m_window.pollEvent(event)){ if(event.type == sf::Event::Closed) m_window.close(); if(event.type == sf::Event::MouseButtonPressed) mouseClick(); } float newTime = m_gameClock.getElapsedTime().asSeconds(); float timeDelta = std::max(0.f, newTime - currentTime); currentTime = newTime; update(timeDelta); draw(timeDelta); } } void Game::update(float delta){ sf::Vector2i zero(0, 0); sf::Vector2i healthSize(240*m_hero.getHP()/m_hero.getMaxHP(), 16); sf::Vector2i manaSize(240*100/100, 16); if(m_gameState == GAME_STATE::GAME_RUN && m_hero.getHP() == 0) m_gameState = GAME_STATE::GAME_END; switch(m_gameState){ case GAME_STATE::MAIN_MENU: break; case GAME_STATE::GAME_RUN: m_healthBar.setTextureRect(sf::IntRect(zero, healthSize)); m_manaBar.setTextureRect(sf::IntRect(zero, manaSize)); m_attackValue.setString(std::to_string(m_hero.getBuffDmg())); m_speedValue.setString(std::to_string(m_hero.getMovSpd())); m_hero.update(m_level, delta); m_view.setCenter(m_hero.getCenterPosition()); m_window.setView(m_view); updateUI(m_view); break; case GAME_STATE::GAME_END: break; } } void Game::draw(float delta){ m_window.clear(sf::Color::Black); switch(m_gameState){ case GAME_STATE::MAIN_MENU: m_buttons[0].draw(m_window); break; case GAME_STATE::GAME_RUN: // renderiza o mapa m_level.draw(m_window); m_hero.draw(m_window, delta); // renderiza a ui drawUI(); break; case GAME_STATE::GAME_END: // código do fim de jogo break; } m_window.display(); } void Game::loadUI(){ // barra preta m_blackBar.setPosition(0, m_window.getSize().y - 36); m_blackBar.setFillColor(sf::Color::Black); // carrega as texturas das barras e altera os sprites // texturas auto barOutlineId = TextureManager::addTexture("../resources/sprites/ui/outline_bar.png"); auto healthBarId = TextureManager::addTexture("../resources/sprites/ui/health_bar.png"); auto manaBarId = TextureManager::addTexture("../resources/sprites/ui/mana_bar.png"); // sprites // barra de vida m_healthBarOutline.setTexture(TextureManager::getTexture(barOutlineId)); m_healthBarOutline.setPosition(10, 10); m_healthBar.setTexture(TextureManager::getTexture(healthBarId)); m_healthBar.setPosition(10, 10); // barra de mana m_manaBarOutline.setTexture(TextureManager::getTexture(barOutlineId)); m_manaBarOutline.setPosition(10, 36); m_manaBar.setTexture(TextureManager::getTexture(manaBarId)); m_manaBar.setPosition(10, 36); // status // texturas auto attackStatId = TextureManager::addTexture("../resources/sprites/ui/attack_stat.png"); auto defenseStatId = TextureManager::addTexture("../resources/sprites/ui/defense_stat.png"); auto speedStatId = TextureManager::addTexture("../resources/sprites/ui/speed_stat.png"); auto luckStatId = TextureManager::addTexture("../resources/sprites/ui/luck_stat.png"); // sprites m_attackStat.setTexture(TextureManager::getTexture(attackStatId)); m_attackStat.setPosition(10, m_window.getSize().y - 26); m_defenseStat.setTexture(TextureManager::getTexture(defenseStatId)); m_defenseStat.setPosition(148, m_window.getSize().y - 26); m_speedStat.setTexture(TextureManager::getTexture(speedStatId)); m_speedStat.setPosition(296, m_window.getSize().y - 26); m_luckStat.setTexture(TextureManager::getTexture(luckStatId)); m_luckStat.setPosition(444, m_window.getSize().y - 26); // texto m_attackValue.setFont(m_uiFont); m_attackValue.setString("3.5"); m_attackValue.setCharacterSize(22); m_attackValue.setFillColor(sf::Color::White); m_attackValue.setPosition(31, m_window.getSize().y - 33); m_defenseValue.setFont(m_uiFont); m_defenseValue.setString("4.5"); m_defenseValue.setCharacterSize(22); m_defenseValue.setFillColor(sf::Color::White); m_defenseValue.setPosition(169, m_window.getSize().y - 33); m_speedValue.setFont(m_uiFont); m_speedValue.setString("6.5"); m_speedValue.setCharacterSize(22); m_speedValue.setFillColor(sf::Color::White); m_speedValue.setPosition(317, m_window.getSize().y - 33); m_luckValue.setFont(m_uiFont); m_luckValue.setString("0.0"); m_luckValue.setCharacterSize(22); m_luckValue.setFillColor(sf::Color::White); m_luckValue.setPosition(465, m_window.getSize().y - 33); } void Game::updateUI(sf::View view){ auto viewTranslation = view.getCenter() - view.getSize()/2.f; auto left = viewTranslation.x; auto top = viewTranslation.y; auto down = view.getSize().y + top; // Barras no topo m_healthBarOutline.setPosition(left + 10, top + 10); m_healthBar.setPosition(left + 10, top + 10); m_manaBarOutline.setPosition(left + 10, top + 36); m_manaBar.setPosition(left + 10, top + 36); // Status no fundo m_blackBar.setPosition(left, down - 36); m_attackStat.setPosition(left + 10, down - 26); m_attackValue.setPosition(left + 31, down - 33); m_defenseStat.setPosition(left + 148, down - 26); m_defenseValue.setPosition(left + 169, down - 33); m_speedStat.setPosition(left + 296, down - 26); m_speedValue.setPosition(left + 317, down - 33); m_luckStat.setPosition(left + 444, down - 26); m_luckValue.setPosition(left + 465, down - 33); } void Game::drawUI(){ // barra preta m_window.draw(m_blackBar); // barras // vida m_window.draw(m_healthBarOutline); m_window.draw(m_healthBar); // mana m_window.draw(m_manaBarOutline); m_window.draw(m_manaBar); // Status m_window.draw(m_attackStat); m_window.draw(m_defenseStat); m_window.draw(m_speedStat); m_window.draw(m_luckStat); m_window.draw(m_attackValue); m_window.draw(m_defenseValue); m_window.draw(m_speedValue); m_window.draw(m_luckValue); } void Game::mouseClick(){ if(sf::Mouse::isButtonPressed(sf::Mouse::Button::Left)) if(m_buttons[0].isPressed(sf::Mouse::getPosition(m_window))) m_gameState = GAME_STATE::GAME_RUN; } <commit_msg>Personagens são selecionados aleatoriamente.<commit_after>#include <Game.hpp> #include <iostream> Game::Game(sf::RenderWindow* window): m_window(*window), m_gameState(GAME_STATE::MAIN_MENU), m_level(Level(*window)), m_blackBar(sf::RectangleShape(sf::Vector2f(window->getSize().x, 36))){ m_view.reset(sf::FloatRect(0, 0, 500, 500)); m_window.setFramerateLimit(60); m_window.setView(m_view); if(!m_uiFont.loadFromFile("../resources/font/uiFont.ttf")){ std::cout << "Erro ao carregar a fonte" << std::endl; } auto classHero = static_cast<HERO_CLASS>(rand()%static_cast<int>(HERO_CLASS::COUNT)); m_hero.initHero(classHero); m_hero.setPosition(1.3*TILE_SIZE, 1.3*TILE_SIZE); // botões do menu inicial auto playButtonId = TextureManager::addTexture("../resources/sprites/buttons/btn_start.png"); m_buttons[0].setTexture(TextureManager::getTexture(playButtonId)); m_buttons[0].centerHorizontal(m_window.getSize().x, 250); loadUI(); m_level.generate(); } void Game::run(){ float currentTime = m_gameClock.restart().asSeconds(); while(m_window.isOpen()){ sf::Event event; while(m_window.pollEvent(event)){ if(event.type == sf::Event::Closed) m_window.close(); if(event.type == sf::Event::MouseButtonPressed) mouseClick(); } float newTime = m_gameClock.getElapsedTime().asSeconds(); float timeDelta = std::max(0.f, newTime - currentTime); currentTime = newTime; update(timeDelta); draw(timeDelta); } } void Game::update(float delta){ sf::Vector2i zero(0, 0); sf::Vector2i healthSize(240*m_hero.getHP()/m_hero.getMaxHP(), 16); sf::Vector2i manaSize(240*100/100, 16); if(m_gameState == GAME_STATE::GAME_RUN && m_hero.getHP() == 0) m_gameState = GAME_STATE::GAME_END; switch(m_gameState){ case GAME_STATE::MAIN_MENU: break; case GAME_STATE::GAME_RUN: m_healthBar.setTextureRect(sf::IntRect(zero, healthSize)); m_manaBar.setTextureRect(sf::IntRect(zero, manaSize)); m_attackValue.setString(std::to_string(m_hero.getBuffDmg())); m_speedValue.setString(std::to_string(m_hero.getMovSpd())); m_hero.update(m_level, delta); m_view.setCenter(m_hero.getCenterPosition()); m_window.setView(m_view); updateUI(m_view); break; case GAME_STATE::GAME_END: break; } } void Game::draw(float delta){ m_window.clear(sf::Color::Black); switch(m_gameState){ case GAME_STATE::MAIN_MENU: m_buttons[0].draw(m_window); break; case GAME_STATE::GAME_RUN: // renderiza o mapa m_level.draw(m_window); m_hero.draw(m_window, delta); // renderiza a ui drawUI(); break; case GAME_STATE::GAME_END: // código do fim de jogo break; } m_window.display(); } void Game::loadUI(){ // barra preta m_blackBar.setPosition(0, m_window.getSize().y - 36); m_blackBar.setFillColor(sf::Color::Black); // carrega as texturas das barras e altera os sprites // texturas auto barOutlineId = TextureManager::addTexture("../resources/sprites/ui/outline_bar.png"); auto healthBarId = TextureManager::addTexture("../resources/sprites/ui/health_bar.png"); auto manaBarId = TextureManager::addTexture("../resources/sprites/ui/mana_bar.png"); // sprites // barra de vida m_healthBarOutline.setTexture(TextureManager::getTexture(barOutlineId)); m_healthBarOutline.setPosition(10, 10); m_healthBar.setTexture(TextureManager::getTexture(healthBarId)); m_healthBar.setPosition(10, 10); // barra de mana m_manaBarOutline.setTexture(TextureManager::getTexture(barOutlineId)); m_manaBarOutline.setPosition(10, 36); m_manaBar.setTexture(TextureManager::getTexture(manaBarId)); m_manaBar.setPosition(10, 36); // status // texturas auto attackStatId = TextureManager::addTexture("../resources/sprites/ui/attack_stat.png"); auto defenseStatId = TextureManager::addTexture("../resources/sprites/ui/defense_stat.png"); auto speedStatId = TextureManager::addTexture("../resources/sprites/ui/speed_stat.png"); auto luckStatId = TextureManager::addTexture("../resources/sprites/ui/luck_stat.png"); // sprites m_attackStat.setTexture(TextureManager::getTexture(attackStatId)); m_attackStat.setPosition(10, m_window.getSize().y - 26); m_defenseStat.setTexture(TextureManager::getTexture(defenseStatId)); m_defenseStat.setPosition(148, m_window.getSize().y - 26); m_speedStat.setTexture(TextureManager::getTexture(speedStatId)); m_speedStat.setPosition(296, m_window.getSize().y - 26); m_luckStat.setTexture(TextureManager::getTexture(luckStatId)); m_luckStat.setPosition(444, m_window.getSize().y - 26); // texto m_attackValue.setFont(m_uiFont); m_attackValue.setString("3.5"); m_attackValue.setCharacterSize(22); m_attackValue.setFillColor(sf::Color::White); m_attackValue.setPosition(31, m_window.getSize().y - 33); m_defenseValue.setFont(m_uiFont); m_defenseValue.setString("4.5"); m_defenseValue.setCharacterSize(22); m_defenseValue.setFillColor(sf::Color::White); m_defenseValue.setPosition(169, m_window.getSize().y - 33); m_speedValue.setFont(m_uiFont); m_speedValue.setString("6.5"); m_speedValue.setCharacterSize(22); m_speedValue.setFillColor(sf::Color::White); m_speedValue.setPosition(317, m_window.getSize().y - 33); m_luckValue.setFont(m_uiFont); m_luckValue.setString("0.0"); m_luckValue.setCharacterSize(22); m_luckValue.setFillColor(sf::Color::White); m_luckValue.setPosition(465, m_window.getSize().y - 33); } void Game::updateUI(sf::View view){ auto viewTranslation = view.getCenter() - view.getSize()/2.f; auto left = viewTranslation.x; auto top = viewTranslation.y; auto down = view.getSize().y + top; // Barras no topo m_healthBarOutline.setPosition(left + 10, top + 10); m_healthBar.setPosition(left + 10, top + 10); m_manaBarOutline.setPosition(left + 10, top + 36); m_manaBar.setPosition(left + 10, top + 36); // Status no fundo m_blackBar.setPosition(left, down - 36); m_attackStat.setPosition(left + 10, down - 26); m_attackValue.setPosition(left + 31, down - 33); m_defenseStat.setPosition(left + 148, down - 26); m_defenseValue.setPosition(left + 169, down - 33); m_speedStat.setPosition(left + 296, down - 26); m_speedValue.setPosition(left + 317, down - 33); m_luckStat.setPosition(left + 444, down - 26); m_luckValue.setPosition(left + 465, down - 33); } void Game::drawUI(){ // barra preta m_window.draw(m_blackBar); // barras // vida m_window.draw(m_healthBarOutline); m_window.draw(m_healthBar); // mana m_window.draw(m_manaBarOutline); m_window.draw(m_manaBar); // Status m_window.draw(m_attackStat); m_window.draw(m_defenseStat); m_window.draw(m_speedStat); m_window.draw(m_luckStat); m_window.draw(m_attackValue); m_window.draw(m_defenseValue); m_window.draw(m_speedValue); m_window.draw(m_luckValue); } void Game::mouseClick(){ if(sf::Mouse::isButtonPressed(sf::Mouse::Button::Left)) if(m_buttons[0].isPressed(sf::Mouse::getPosition(m_window))) m_gameState = GAME_STATE::GAME_RUN; } <|endoftext|>
<commit_before>//- Standard Library - #include <iostream> #include <fstream> #include <algorithm> #include <cstring> //- Beach Judge - #include <BeachJudge/Base.h> #include <BeachJudge/Page.h> #include <BeachJudge/Session.h> #include <BeachJudge/HTTP.h> #include <BeachJudge/Team.h> using namespace std; const char *wwwPrefix = "../www/"; namespace beachjudge { void HTTP::OpenHeader_OK(stringstream &stream) { stream << "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-type: text/html\r\n"; } void HTTP::OpenHeader_NotFound(std::stringstream &stream) { stream << "HTTP/1.1 404 Not Found\r\nConnection: close\r\nContent-type: text/html\r\n"; } void HTTP::SetSessionCookie(std::stringstream &stream, std::string target, std::string value) { stream << "Set-Cookie: " << target << "=" << value << "\r\n"; } void HTTP::LoadImage(stringstream &stream, string file) { ifstream inFile(file.c_str(), ios::binary); stream << "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-type: */*\r\n"; string img; while(!inFile.eof()) { char c; inFile.get(c); img.push_back(c); } unsigned long size = img.size(); stream << "Content-Length: " << size << "\r\n\r\n"; for(unsigned long a = 0; a < size; a++) stream << img[a]; inFile.close(); } void HTTP::CloseHeader(stringstream &stream) { stream << "\r\n"; } void HTTP::HandleRequest(Socket *client, std::string &request) { unsigned short port = 0; unsigned long addr = 0; client->GetPeerIP4Info(&addr, &port); unsigned char ip[4], *ipPtr = (unsigned char *)&addr; for(unsigned char a = 0; a < 4; a++) { ip[a] = *ipPtr & 0xFF; ipPtr++; } Session *session = Session::Lookup(addr); stringstream stream(request); string method; stream >> method; // print("[%d: %d %d] Receiving Msg: %d.%d.%d.%d:%d\r\n", getRunTimeMS(), session, session->GetID(), (unsigned short)ip[0], (unsigned short)ip[1], (unsigned short)ip[2], (unsigned short)ip[3], port); cout << request << endl; if(!method.compare("GET")) { string arguments; stream >> arguments; string in; while(stream >> in) { if(!in.compare("Cookie:")) { string cookie; while(getline(stream, cookie, '=')) { string value; stream >> value; if(!value.empty()) if(*value.rbegin() == ';') value = value.substr(0, value.size() - 1); if(!cookie.compare(" BEACHJUDGESESSID")) { print("Beach Judge Sess ID: %s\r\n", value.c_str()); } } break; } } stringstream argStream(arguments); string arg, filePath(wwwPrefix); bool e404 = false; stringstream webPageStream; getline(argStream, arg, '/'); if(getline(argStream, arg, '/')) { if(!arg.compare("logout")) if(session) { delete session; session = 0; } string testPath = filePath; testPath.append(arg); if(fileExists(testPath.c_str())) filePath = testPath; else { testPath.append(".html"); if(fileExists(testPath.c_str())) filePath = testPath; else { filePath.append("404.html"); e404 = true; } } } else filePath.append("index.html"); unsigned short per = filePath.find_last_of('.'); string type; if(per != string::npos) type = filePath.substr(per + 1); bool img = false; if(type.length()) { transform(type.begin(), type.end(), type.begin(), ::tolower); if(!type.compare("jpg") || !type.compare("jpeg") || !type.compare("png") || !type.compare("bmp")) img = true; } if(img) { LoadImage(webPageStream, filePath); string response = webPageStream.str(); client->Write((char *)response.c_str(), response.length()); } else { if(e404) OpenHeader_NotFound(webPageStream); else OpenHeader_OK(webPageStream); if(session) { char idBuff[8]; memset(idBuff, 0, 8); #ifdef _WIN32 _itoa_s(session->GetID(), idBuff, 8, 10); #else sprintf(idBuff, "%d", session->GetID()); #endif SetSessionCookie(webPageStream, "BEACHJUDGESESSID", string(idBuff)); } else SetSessionCookie(webPageStream, "BEACHJUDGESESSID", "deleted; expires=Thu, 01 Jan 1970 00:00:00 GMT"); CloseHeader(webPageStream); Page *index = Page::Create(filePath); index->AddToStream(webPageStream, client, session); string webPage = webPageStream.str(); client->Write((char *)webPage.c_str(), webPage.length()); } } else if(!method.compare("POST")) { string arguments; stream >> arguments; map<string, string> argMap; string in; while(stream >> in) { if(!in.compare("Cookie:")) { string cookie; while(getline(stream, cookie, '=')) { string value; stream >> value; if(!value.empty()) if(*value.rbegin() == ';') value = value.substr(0, value.size() - 1); if(!cookie.compare(" BEACHJUDGESESSID")) { print("Beach Judge Sess ID: %s\r\n", value.c_str()); } if(stream.peek() == '\r') break; } getline(stream, cookie); getline(stream, cookie); string postArgs; stream >> postArgs; string arg; stringstream argStream(postArgs); while(getline(argStream, arg, '=')) { string val; getline(argStream, val, '&'); argMap[arg] = val; } break; } else if(in.find("team=") == 0) { string postArgs = in; string arg; stringstream argStream(postArgs); while(getline(argStream, arg, '=')) { string val; getline(argStream, val, '&'); argMap[arg] = val; } } } if(argMap.count("passwd")) if(argMap.count("team")) { Team *team = Team::LookupByName(argMap["team"]); if(team) if(team->TestPassword(argMap["passwd"])) session = Session::Create(addr, port, team); } stringstream argStream(arguments); string arg, filePath(wwwPrefix); bool e404 = false; stringstream webPageStream; getline(argStream, arg, '/'); if(getline(argStream, arg, '/')) { if(!arg.compare("logout")) if(session) { delete session; session = 0; } string testPath = filePath; testPath.append(arg); if(fileExists(testPath.c_str())) filePath = testPath; else { testPath.append(".html"); if(fileExists(testPath.c_str())) filePath = testPath; else { filePath.append("404.html"); e404 = true; } } } else filePath.append("index.html"); unsigned short per = filePath.find_last_of('.'); string type; if(per != string::npos) type = filePath.substr(per + 1); bool img = false; if(type.length()) { transform(type.begin(), type.end(), type.begin(), ::tolower); if(!type.compare("jpg") || !type.compare("jpeg") || !type.compare("png") || !type.compare("bmp")) img = true; } if(img) { LoadImage(webPageStream, filePath); string response = webPageStream.str(); client->Write((char *)response.c_str(), response.length()); } else { if(e404) OpenHeader_NotFound(webPageStream); else OpenHeader_OK(webPageStream); if(session) { char idBuff[8]; memset(idBuff, 0, 8); #ifdef _WIN32 _itoa_s(session->GetID(), idBuff, 8, 10); #else sprintf(idBuff, "%d", session->GetID()); #endif SetSessionCookie(webPageStream, "BEACHJUDGESESSID", string(idBuff)); } else SetSessionCookie(webPageStream, "BEACHJUDGESESSID", "deleted; expires=Thu, 01 Jan 1970 00:00:00 GMT"); CloseHeader(webPageStream); Page *index = Page::Create(filePath); index->AddToStream(webPageStream, client, session); string webPage = webPageStream.str(); client->Write((char *)webPage.c_str(), webPage.length()); } } } } <commit_msg>Changed the file request parser to allow for sub-folders<commit_after>//- Standard Library - #include <iostream> #include <fstream> #include <algorithm> #include <cstring> //- Beach Judge - #include <BeachJudge/Base.h> #include <BeachJudge/Page.h> #include <BeachJudge/Session.h> #include <BeachJudge/HTTP.h> #include <BeachJudge/Team.h> using namespace std; const char *wwwPrefix = "../www/"; namespace beachjudge { void HTTP::OpenHeader_OK(stringstream &stream) { stream << "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-type: text/html\r\n"; } void HTTP::OpenHeader_NotFound(std::stringstream &stream) { stream << "HTTP/1.1 404 Not Found\r\nConnection: close\r\nContent-type: text/html\r\n"; } void HTTP::SetSessionCookie(std::stringstream &stream, std::string target, std::string value) { stream << "Set-Cookie: " << target << "=" << value << "\r\n"; } void HTTP::LoadImage(stringstream &stream, string file) { ifstream inFile(file.c_str(), ios::binary); stream << "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-type: */*\r\n"; string img; while(!inFile.eof()) { char c; inFile.get(c); img.push_back(c); } unsigned long size = img.size(); stream << "Content-Length: " << size << "\r\n\r\n"; for(unsigned long a = 0; a < size; a++) stream << img[a]; inFile.close(); } void HTTP::CloseHeader(stringstream &stream) { stream << "\r\n"; } void HTTP::HandleRequest(Socket *client, std::string &request) { unsigned short port = 0; unsigned long addr = 0; client->GetPeerIP4Info(&addr, &port); unsigned char ip[4], *ipPtr = (unsigned char *)&addr; for(unsigned char a = 0; a < 4; a++) { ip[a] = *ipPtr & 0xFF; ipPtr++; } Session *session = Session::Lookup(addr); stringstream stream(request); string method; stream >> method; // print("[%d: %d %d] Receiving Msg: %d.%d.%d.%d:%d\r\n", getRunTimeMS(), session, session->GetID(), (unsigned short)ip[0], (unsigned short)ip[1], (unsigned short)ip[2], (unsigned short)ip[3], port); cout << request << endl; if(!method.compare("GET")) { string arguments; stream >> arguments; string in; while(stream >> in) { if(!in.compare("Cookie:")) { string cookie; while(getline(stream, cookie, '=')) { string value; stream >> value; if(!value.empty()) if(*value.rbegin() == ';') value = value.substr(0, value.size() - 1); if(!cookie.compare(" BEACHJUDGESESSID")) { print("Beach Judge Sess ID: %s\r\n", value.c_str()); } } break; } } stringstream argStream(arguments); string filePath(wwwPrefix); bool e404 = false; stringstream webPageStream; string fileReq = arguments.substr(0, arguments.find_first_of('?')); fileReq = fileReq.substr(0, fileReq.find_first_of('#')); if(fileReq.length() == 1) filePath.append("index.html"); else { if(!fileReq.compare("logout")) if(session) { delete session; session = 0; } string testPath = filePath; testPath.append(fileReq); if(fileExists(testPath.c_str())) filePath = testPath; else { testPath.append(".html"); if(fileExists(testPath.c_str())) filePath = testPath; else { filePath.append("404.html"); e404 = true; } } } unsigned short per = filePath.find_last_of('.'); string type; if(per != string::npos) type = filePath.substr(per + 1); bool img = false; if(type.length()) { transform(type.begin(), type.end(), type.begin(), ::tolower); if(!type.compare("jpg") || !type.compare("jpeg") || !type.compare("png") || !type.compare("bmp")) img = true; } if(img) { LoadImage(webPageStream, filePath); string response = webPageStream.str(); client->Write((char *)response.c_str(), response.length()); } else { if(e404) OpenHeader_NotFound(webPageStream); else OpenHeader_OK(webPageStream); if(session) { char idBuff[8]; memset(idBuff, 0, 8); #ifdef _WIN32 _itoa_s(session->GetID(), idBuff, 8, 10); #else sprintf(idBuff, "%d", session->GetID()); #endif SetSessionCookie(webPageStream, "BEACHJUDGESESSID", string(idBuff)); } else SetSessionCookie(webPageStream, "BEACHJUDGESESSID", "deleted; expires=Thu, 01 Jan 1970 00:00:00 GMT"); CloseHeader(webPageStream); Page *index = Page::Create(filePath); index->AddToStream(webPageStream, client, session); string webPage = webPageStream.str(); client->Write((char *)webPage.c_str(), webPage.length()); } } else if(!method.compare("POST")) { string arguments; stream >> arguments; map<string, string> argMap; string in; while(stream >> in) { if(!in.compare("Cookie:")) { string cookie; while(getline(stream, cookie, '=')) { string value; stream >> value; if(!value.empty()) if(*value.rbegin() == ';') value = value.substr(0, value.size() - 1); if(!cookie.compare(" BEACHJUDGESESSID")) { print("Beach Judge Sess ID: %s\r\n", value.c_str()); } if(stream.peek() == '\r') break; } getline(stream, cookie); getline(stream, cookie); string postArgs; stream >> postArgs; string arg; stringstream argStream(postArgs); while(getline(argStream, arg, '=')) { string val; getline(argStream, val, '&'); argMap[arg] = val; } break; } else if(in.find("team=") == 0) { string postArgs = in; string arg; stringstream argStream(postArgs); while(getline(argStream, arg, '=')) { string val; getline(argStream, val, '&'); argMap[arg] = val; } } } if(argMap.count("passwd")) if(argMap.count("team")) { Team *team = Team::LookupByName(argMap["team"]); if(team) if(team->TestPassword(argMap["passwd"])) session = Session::Create(addr, port, team); } stringstream argStream(arguments); string filePath(wwwPrefix); bool e404 = false; stringstream webPageStream; string fileReq = arguments.substr(0, arguments.find_first_of('?')); fileReq = fileReq.substr(0, fileReq.find_first_of('#')); if(fileReq.length() == 1) filePath.append("index.html"); else { if(!fileReq.compare("logout")) if(session) { delete session; session = 0; } string testPath = filePath; testPath.append(fileReq); if(fileExists(testPath.c_str())) filePath = testPath; else { testPath.append(".html"); if(fileExists(testPath.c_str())) filePath = testPath; else { filePath.append("404.html"); e404 = true; } } } unsigned short per = filePath.find_last_of('.'); string type; if(per != string::npos) type = filePath.substr(per + 1); bool img = false; if(type.length()) { transform(type.begin(), type.end(), type.begin(), ::tolower); if(!type.compare("jpg") || !type.compare("jpeg") || !type.compare("png") || !type.compare("bmp")) img = true; } if(img) { LoadImage(webPageStream, filePath); string response = webPageStream.str(); client->Write((char *)response.c_str(), response.length()); } else { if(e404) OpenHeader_NotFound(webPageStream); else OpenHeader_OK(webPageStream); if(session) { char idBuff[8]; memset(idBuff, 0, 8); #ifdef _WIN32 _itoa_s(session->GetID(), idBuff, 8, 10); #else sprintf(idBuff, "%d", session->GetID()); #endif SetSessionCookie(webPageStream, "BEACHJUDGESESSID", string(idBuff)); } else SetSessionCookie(webPageStream, "BEACHJUDGESESSID", "deleted; expires=Thu, 01 Jan 1970 00:00:00 GMT"); CloseHeader(webPageStream); Page *index = Page::Create(filePath); index->AddToStream(webPageStream, client, session); string webPage = webPageStream.str(); client->Write((char *)webPage.c_str(), webPage.length()); } } } } <|endoftext|>
<commit_before>#include "Http.hpp" #include "Logger.hpp" #include "misc.hpp" #include "version.hpp" #include <boost/asio/system_timer.hpp> #include <boost/beast/version.hpp> Http::Http(std::string token) : m_SslContext(asio::ssl::context::tlsv12_client), m_Token(token), m_NetworkThreadRunning(true), m_NetworkThread(std::bind(&Http::NetworkThreadFunc, this)) { } Http::~Http() { m_NetworkThreadRunning = false; m_NetworkThread.join(); // drain requests queue QueueEntry *entry; while (m_Queue.pop(entry)) delete entry; } void Http::NetworkThreadFunc() { std::unordered_map<std::string, TimePoint_t> path_ratelimit; unsigned int retry_counter = 0; unsigned int const MaxRetries = 3; bool skip_entry = false; if (!Connect()) return; while (m_NetworkThreadRunning) { TimePoint_t current_time = std::chrono::steady_clock::now(); std::list<QueueEntry*> skipped_entries; QueueEntry *entry; while (m_Queue.pop(entry)) { // check if we're rate-limited auto pr_it = path_ratelimit.find(entry->Request->target().to_string()); if (pr_it != path_ratelimit.end()) { // rate-limit for this path exists // are we still within the rate-limit timepoint? if (current_time < pr_it->second) { // yes, ignore this request for now skipped_entries.push_back(entry); continue; } // no, delete rate-limit and go on path_ratelimit.erase(pr_it); Logger::Get()->Log(LogLevel::DEBUG, "rate-limit on path '{}' lifted", entry->Request->target().to_string()); } boost::system::error_code error_code; Response_t response; Streambuf_t sb; retry_counter = 0; skip_entry = false; do { bool do_reconnect = false; beast::http::write(*m_SslStream, *entry->Request, error_code); if (error_code) { Logger::Get()->Log(LogLevel::ERROR, "Error while sending HTTP {} request to '{}': {}", entry->Request->method_string().to_string(), entry->Request->target().to_string(), error_code.message()); do_reconnect = true; } else { beast::http::read(*m_SslStream, sb, response, error_code); if (error_code) { Logger::Get()->Log(LogLevel::ERROR, "Error while retrieving HTTP {} response from '{}': {}", entry->Request->method_string().to_string(), entry->Request->target().to_string(), error_code.message()); do_reconnect = true; } } if (do_reconnect) { if (retry_counter++ >= MaxRetries || !ReconnectRetry()) { // we failed to reconnect, discard this request Logger::Get()->Log(LogLevel::WARNING, "Failed to send request, discarding"); skip_entry = true; break; // break out of do-while loop } } } while (error_code); if (skip_entry) continue; // continue queue loop auto it_r = response.find("X-RateLimit-Remaining"); if (it_r != response.end()) { if (it_r->value().compare("0") == 0) { // we're now officially rate-limited // the next call to this path will fail std::string limited_url = entry->Request->target().to_string(); auto lit = path_ratelimit.find(limited_url); if (lit != path_ratelimit.end()) { Logger::Get()->Log(LogLevel::ERROR, "Error while processing rate-limit: already rate-limited path '{}'", limited_url); // skip this request, we'll re-add it to the queue to retry later skipped_entries.push_back(entry); continue; } it_r = response.find("X-RateLimit-Reset"); if (it_r != response.end()) { std::chrono::seconds timepoint_now = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()); Logger::Get()->Log(LogLevel::DEBUG, "rate-limiting path {} until {} (current time: {})", limited_url, it_r->value().to_string(), timepoint_now.count()); string const &reset_time_str = it_r->value().to_string(); long long reset_time_secs = 0; ConvertStrToData(reset_time_str, reset_time_secs); TimePoint_t reset_time = std::chrono::steady_clock::now() + std::chrono::seconds(reset_time_secs - timepoint_now.count() + 1); // add a buffer of 1 second path_ratelimit.insert({ limited_url, reset_time }); } } } if (entry->Callback) entry->Callback(sb, response); delete entry; entry = nullptr; } // add skipped entries back to queue for (auto e : skipped_entries) m_Queue.push(e); std::this_thread::sleep_for(std::chrono::milliseconds(50)); } Disconnect(); } bool Http::Connect() { Logger::Get()->Log(LogLevel::DEBUG, "Http::Connect"); m_SslStream.reset(new SslStream_t(m_IoService, m_SslContext)); const char *API_HOST = "discord.com"; // Set SNI Hostname (many hosts need this to handshake successfully) if (!SSL_set_tlsext_host_name(m_SslStream->native_handle(), API_HOST)) { beast::error_code ec{ static_cast<int>(::ERR_get_error()), asio::error::get_ssl_category() }; Logger::Get()->Log(LogLevel::ERROR, "Can't set SNI hostname for Discord API URL: {} ({})", ec.message(), ec.value()); return false; } // connect to REST API asio::ip::tcp::resolver r{ m_IoService }; boost::system::error_code error; auto target = r.resolve(API_HOST, "443", error); if (error) { Logger::Get()->Log(LogLevel::ERROR, "Can't resolve Discord API URL: {} ({})", error.message(), error.value()); return false; } beast::get_lowest_layer(*m_SslStream).expires_after(std::chrono::seconds(30)); beast::get_lowest_layer(*m_SslStream).connect(target, error); if (error) { Logger::Get()->Log(LogLevel::ERROR, "Can't connect to Discord API: {} ({})", error.message(), error.value()); return false; } // SSL handshake m_SslStream->handshake(asio::ssl::stream_base::client, error); if (error) { Logger::Get()->Log(LogLevel::ERROR, "Can't establish secured connection to Discord API: {} ({})", error.message(), error.value()); return false; } return true; } void Http::Disconnect() { Logger::Get()->Log(LogLevel::DEBUG, "Http::Disconnect"); boost::system::error_code error; m_SslStream->shutdown(error); if (error && error != boost::asio::error::eof && error != boost::asio::ssl::error::stream_truncated) { Logger::Get()->Log(LogLevel::WARNING, "Error while shutting down SSL on HTTP connection: {} ({})", error.message(), error.value()); } } bool Http::ReconnectRetry() { Logger::Get()->Log(LogLevel::DEBUG, "Http::ReconnectRetry"); unsigned int reconnect_counter = 0; do { Logger::Get()->Log(LogLevel::INFO, "trying reconnect #{}...", reconnect_counter + 1); Disconnect(); if (Connect()) { Logger::Get()->Log(LogLevel::INFO, "reconnect succeeded, resending request"); return true; } else { unsigned int seconds_to_wait = static_cast<unsigned int>(std::pow(2U, reconnect_counter)); Logger::Get()->Log(LogLevel::WARNING, "reconnect failed, waiting {} seconds...", seconds_to_wait); std::this_thread::sleep_for(std::chrono::seconds(seconds_to_wait)); } } while (++reconnect_counter < 3); Logger::Get()->Log(LogLevel::ERROR, "Could not reconnect to Discord"); return false; } Http::SharedRequest_t Http::PrepareRequest(beast::http::verb const method, std::string const &url, std::string const &content) { Logger::Get()->Log(LogLevel::DEBUG, "Http::PrepareRequest"); auto req = std::make_shared<Request_t>(); req->method(method); req->target("/api/v6" + url); req->version(11); req->insert(beast::http::field::connection, "keep-alive"); req->insert(beast::http::field::host, "discord.com"); req->insert(beast::http::field::user_agent, "samp-discord-connector (" BOOST_BEAST_VERSION_STRING ")"); if (!content.empty()) req->insert(beast::http::field::content_type, "application/json"); req->insert(beast::http::field::authorization, "Bot " + m_Token); req->body() = content; req->prepare_payload(); return req; } void Http::SendRequest(beast::http::verb const method, std::string const &url, std::string const &content, ResponseCallback_t &&callback) { Logger::Get()->Log(LogLevel::DEBUG, "Http::SendRequest"); SharedRequest_t req = PrepareRequest(method, url, content); if (callback == nullptr && Logger::Get()->IsLogLevel(LogLevel::DEBUG)) { callback = CreateResponseCallback([=](Response r) { Logger::Get()->Log(LogLevel::DEBUG, "{:s} {:s} [{:s}] --> {:d} {:s}: {:s}", beast::http::to_string(method).to_string(), url, content, r.status, r.reason, r.body); }); } m_Queue.push(new QueueEntry(req, std::move(callback))); } Http::ResponseCallback_t Http::CreateResponseCallback(ResponseCb_t &&callback) { if (callback == nullptr) return nullptr; return [callback](Streambuf_t &sb, Response_t &resp) { callback({ resp.result_int(), resp.reason().to_string(), beast::buffers_to_string(resp.body().data()), beast::buffers_to_string(sb.data()) }); }; } void Http::Get(std::string const &url, ResponseCb_t &&callback) { Logger::Get()->Log(LogLevel::DEBUG, "Http::Get"); SendRequest(beast::http::verb::get, url, "", CreateResponseCallback(std::move(callback))); } void Http::Post(std::string const &url, std::string const &content, ResponseCb_t &&callback /*= nullptr*/) { Logger::Get()->Log(LogLevel::DEBUG, "Http::Post"); SendRequest(beast::http::verb::post, url, content, CreateResponseCallback(std::move(callback))); } void Http::Delete(std::string const &url) { Logger::Get()->Log(LogLevel::DEBUG, "Http::Delete"); SendRequest(beast::http::verb::delete_, url, "", nullptr); } void Http::Put(std::string const &url) { Logger::Get()->Log(LogLevel::DEBUG, "Http::Put"); SendRequest(beast::http::verb::put, url, "", nullptr); } void Http::Patch(std::string const &url, std::string const &content) { Logger::Get()->Log(LogLevel::DEBUG, "Http::Patch"); SendRequest(beast::http::verb::patch, url, content, nullptr); } <commit_msg>Made ratelimit use MS precision rather than seconds, improves reaction rate limit, but still isn't perfect.<commit_after>#include "Http.hpp" #include "Logger.hpp" #include "misc.hpp" #include "version.hpp" #include <boost/asio/system_timer.hpp> #include <boost/beast/version.hpp> Http::Http(std::string token) : m_SslContext(asio::ssl::context::tlsv12_client), m_Token(token), m_NetworkThreadRunning(true), m_NetworkThread(std::bind(&Http::NetworkThreadFunc, this)) { } Http::~Http() { m_NetworkThreadRunning = false; m_NetworkThread.join(); // drain requests queue QueueEntry *entry; while (m_Queue.pop(entry)) delete entry; } void Http::NetworkThreadFunc() { std::unordered_map<std::string, TimePoint_t> path_ratelimit; unsigned int retry_counter = 0; unsigned int const MaxRetries = 3; bool skip_entry = false; if (!Connect()) return; while (m_NetworkThreadRunning) { TimePoint_t current_time = std::chrono::steady_clock::now(); std::list<QueueEntry*> skipped_entries; QueueEntry *entry; while (m_Queue.pop(entry)) { // check if we're rate-limited auto pr_it = path_ratelimit.find(entry->Request->target().to_string()); if (pr_it != path_ratelimit.end()) { // rate-limit for this path exists // are we still within the rate-limit timepoint? if (current_time < pr_it->second) { // yes, ignore this request for now skipped_entries.push_back(entry); continue; } // no, delete rate-limit and go on path_ratelimit.erase(pr_it); Logger::Get()->Log(LogLevel::DEBUG, "rate-limit on path '{}' lifted", entry->Request->target().to_string()); } boost::system::error_code error_code; Response_t response; Streambuf_t sb; retry_counter = 0; skip_entry = false; do { bool do_reconnect = false; beast::http::write(*m_SslStream, *entry->Request, error_code); if (error_code) { Logger::Get()->Log(LogLevel::ERROR, "Error while sending HTTP {} request to '{}': {}", entry->Request->method_string().to_string(), entry->Request->target().to_string(), error_code.message()); do_reconnect = true; } else { beast::http::read(*m_SslStream, sb, response, error_code); if (error_code) { Logger::Get()->Log(LogLevel::ERROR, "Error while retrieving HTTP {} response from '{}': {}", entry->Request->method_string().to_string(), entry->Request->target().to_string(), error_code.message()); do_reconnect = true; } } if (do_reconnect) { if (retry_counter++ >= MaxRetries || !ReconnectRetry()) { // we failed to reconnect, discard this request Logger::Get()->Log(LogLevel::WARNING, "Failed to send request, discarding"); skip_entry = true; break; // break out of do-while loop } } } while (error_code); if (skip_entry) continue; // continue queue loop auto it_r = response.find("X-RateLimit-Remaining"); if (it_r != response.end()) { if (it_r->value().compare("0") == 0) { // we're now officially rate-limited // the next call to this path will fail std::string limited_url = entry->Request->target().to_string(); auto lit = path_ratelimit.find(limited_url); if (lit != path_ratelimit.end()) { Logger::Get()->Log(LogLevel::ERROR, "Error while processing rate-limit: already rate-limited path '{}'", limited_url); // skip this request, we'll re-add it to the queue to retry later skipped_entries.push_back(entry); continue; } it_r = response.find("X-RateLimit-Reset"); if (it_r != response.end()) { string const& reset_time_str = it_r->value().to_string(); long long reset_time_secs = 0; ConvertStrToData(reset_time_str, reset_time_secs); std::chrono::milliseconds milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::seconds(reset_time_secs)); // we have milliseconds too. if (reset_time_str.find(".") != std::string::npos) { const std::string msstr = reset_time_str.substr(reset_time_str.find(".")); long ms; ConvertStrToData(msstr, ms); milliseconds += std::chrono::milliseconds(ms); } std::chrono::milliseconds timepoint_now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()); Logger::Get()->Log(LogLevel::DEBUG, "rate-limiting path {} until {} (current time: {})", limited_url, it_r->value().to_string(), timepoint_now.count()); TimePoint_t reset_time = std::chrono::steady_clock::now() + std::chrono::milliseconds(milliseconds.count() - timepoint_now.count() + 1000); // add a buffer of 1 second path_ratelimit.insert({ limited_url, reset_time }); } } } if (entry->Callback) entry->Callback(sb, response); delete entry; entry = nullptr; } // add skipped entries back to queue for (auto e : skipped_entries) m_Queue.push(e); std::this_thread::sleep_for(std::chrono::milliseconds(50)); } Disconnect(); } bool Http::Connect() { Logger::Get()->Log(LogLevel::DEBUG, "Http::Connect"); m_SslStream.reset(new SslStream_t(m_IoService, m_SslContext)); const char *API_HOST = "discord.com"; // Set SNI Hostname (many hosts need this to handshake successfully) if (!SSL_set_tlsext_host_name(m_SslStream->native_handle(), API_HOST)) { beast::error_code ec{ static_cast<int>(::ERR_get_error()), asio::error::get_ssl_category() }; Logger::Get()->Log(LogLevel::ERROR, "Can't set SNI hostname for Discord API URL: {} ({})", ec.message(), ec.value()); return false; } // connect to REST API asio::ip::tcp::resolver r{ m_IoService }; boost::system::error_code error; auto target = r.resolve(API_HOST, "443", error); if (error) { Logger::Get()->Log(LogLevel::ERROR, "Can't resolve Discord API URL: {} ({})", error.message(), error.value()); return false; } beast::get_lowest_layer(*m_SslStream).expires_after(std::chrono::seconds(30)); beast::get_lowest_layer(*m_SslStream).connect(target, error); if (error) { Logger::Get()->Log(LogLevel::ERROR, "Can't connect to Discord API: {} ({})", error.message(), error.value()); return false; } // SSL handshake m_SslStream->handshake(asio::ssl::stream_base::client, error); if (error) { Logger::Get()->Log(LogLevel::ERROR, "Can't establish secured connection to Discord API: {} ({})", error.message(), error.value()); return false; } return true; } void Http::Disconnect() { Logger::Get()->Log(LogLevel::DEBUG, "Http::Disconnect"); boost::system::error_code error; m_SslStream->shutdown(error); if (error && error != boost::asio::error::eof && error != boost::asio::ssl::error::stream_truncated) { Logger::Get()->Log(LogLevel::WARNING, "Error while shutting down SSL on HTTP connection: {} ({})", error.message(), error.value()); } } bool Http::ReconnectRetry() { Logger::Get()->Log(LogLevel::DEBUG, "Http::ReconnectRetry"); unsigned int reconnect_counter = 0; do { Logger::Get()->Log(LogLevel::INFO, "trying reconnect #{}...", reconnect_counter + 1); Disconnect(); if (Connect()) { Logger::Get()->Log(LogLevel::INFO, "reconnect succeeded, resending request"); return true; } else { unsigned int seconds_to_wait = static_cast<unsigned int>(std::pow(2U, reconnect_counter)); Logger::Get()->Log(LogLevel::WARNING, "reconnect failed, waiting {} seconds...", seconds_to_wait); std::this_thread::sleep_for(std::chrono::seconds(seconds_to_wait)); } } while (++reconnect_counter < 3); Logger::Get()->Log(LogLevel::ERROR, "Could not reconnect to Discord"); return false; } Http::SharedRequest_t Http::PrepareRequest(beast::http::verb const method, std::string const &url, std::string const &content) { Logger::Get()->Log(LogLevel::DEBUG, "Http::PrepareRequest"); auto req = std::make_shared<Request_t>(); req->method(method); req->target("/api/v8" + url); req->version(11); req->insert(beast::http::field::connection, "keep-alive"); req->insert(beast::http::field::host, "discord.com"); req->insert(beast::http::field::user_agent, "samp-discord-connector (" BOOST_BEAST_VERSION_STRING ")"); if (!content.empty()) req->insert(beast::http::field::content_type, "application/json"); req->insert(beast::http::field::authorization, "Bot " + m_Token); req->body() = content; req->prepare_payload(); return req; } void Http::SendRequest(beast::http::verb const method, std::string const &url, std::string const &content, ResponseCallback_t &&callback) { Logger::Get()->Log(LogLevel::DEBUG, "Http::SendRequest"); SharedRequest_t req = PrepareRequest(method, url, content); if (callback == nullptr && Logger::Get()->IsLogLevel(LogLevel::DEBUG)) { callback = CreateResponseCallback([=](Response r) { Logger::Get()->Log(LogLevel::DEBUG, "{:s} {:s} [{:s}] --> {:d} {:s}: {:s}", beast::http::to_string(method).to_string(), url, content, r.status, r.reason, r.body); }); } m_Queue.push(new QueueEntry(req, std::move(callback))); } Http::ResponseCallback_t Http::CreateResponseCallback(ResponseCb_t &&callback) { if (callback == nullptr) return nullptr; return [callback](Streambuf_t &sb, Response_t &resp) { callback({ resp.result_int(), resp.reason().to_string(), beast::buffers_to_string(resp.body().data()), beast::buffers_to_string(sb.data()) }); }; } void Http::Get(std::string const &url, ResponseCb_t &&callback) { Logger::Get()->Log(LogLevel::DEBUG, "Http::Get"); SendRequest(beast::http::verb::get, url, "", CreateResponseCallback(std::move(callback))); } void Http::Post(std::string const &url, std::string const &content, ResponseCb_t &&callback /*= nullptr*/) { Logger::Get()->Log(LogLevel::DEBUG, "Http::Post"); SendRequest(beast::http::verb::post, url, content, CreateResponseCallback(std::move(callback))); } void Http::Delete(std::string const &url) { Logger::Get()->Log(LogLevel::DEBUG, "Http::Delete"); SendRequest(beast::http::verb::delete_, url, "", nullptr); } void Http::Put(std::string const &url) { Logger::Get()->Log(LogLevel::DEBUG, "Http::Put"); SendRequest(beast::http::verb::put, url, "", nullptr); } void Http::Patch(std::string const &url, std::string const &content) { Logger::Get()->Log(LogLevel::DEBUG, "Http::Patch"); SendRequest(beast::http::verb::patch, url, content, nullptr); } <|endoftext|>
<commit_before>#ifndef __SNOW__AUTORELEASE_HH__ #define __SNOW__AUTORELEASE_HH__ #include "config.hh" #ifndef __has_feature #define __has_feature(F) 0 #endif #if __has_feature(objc_arc) #define AUTORELEASE_PUSH() do { @autoreleasepool { #define AUTORELEASE_POP() } } while (0) #elif S_PLATFORM_APPLE && !__has_feature(objc_arc) #define AUTORELEASE_PUSH() do { void *OBJC_ARPOOL___ = ::snow::autorelease_push() #define AUTORELEASE_POP() ::snow::autorelease_pop(OBJC_ARPOOL___); } while (0) #else #define AUTORELEASE_PUSH() do { #define AUTORELEASE_POP() } while (0) #endif namespace snow { S_EXPORT void *autorelease_push(); S_EXPORT void autorelease_pop(void *pool); } // namespace snow #endif /* end __SNOW__AUTORELEASE_HH__ include guard */ <commit_msg>Add note about scope and such for AUTORELEASE_PUSH/POP<commit_after>#ifndef __SNOW__AUTORELEASE_HH__ #define __SNOW__AUTORELEASE_HH__ #include "config.hh" #ifndef __has_feature #define __has_feature(F) 0 #endif /* AUTORELEASE_PUSH and AUTORELEASE_POP work on more or less the same idea as Obj-C's @autoreleasepool { ... } blocks. So, they must remain in the same scope, variables declared between them will cease to exist outside of them, and so on. Basically, treat them as though they're { ... } blocks, because they are. */ #if __has_feature(objc_arc) #define AUTORELEASE_PUSH() do { @autoreleasepool { #define AUTORELEASE_POP() } } while (0) #elif S_PLATFORM_APPLE && !__has_feature(objc_arc) #define AUTORELEASE_PUSH() do { void *OBJC_ARPOOL___ = ::snow::autorelease_push() #define AUTORELEASE_POP() ::snow::autorelease_pop(OBJC_ARPOOL___); } while (0) #else #define AUTORELEASE_PUSH() do { #define AUTORELEASE_POP() } while (0) #endif namespace snow { S_EXPORT void *autorelease_push(); S_EXPORT void autorelease_pop(void *pool); } // namespace snow #endif /* end __SNOW__AUTORELEASE_HH__ include guard */ <|endoftext|>
<commit_before>#include "stdafx.h" #include "Audio.h" #include "Configuration.h" const WAVEFORMATEX Audio::wfx = { WAVE_FORMAT_PCM, // wFormatTag 1, // nChannels AU_SAMPLING_RATE, // nSamplesPerSec AU_SAMPLING_RATE * 2, // nAvgBytesPerSec 1 * 2, // nBlockAlign 16, // wBitsPerSample 0 // cbSize }; Audio::Audio() { num_waves_ = 0; wave_out_prepared_ = false; ReleaseAll(); } Audio::~Audio() { ReleaseAll(); } DWORD WINAPI Audio::ThreadFunc(LPVOID lpParameter) { Audio *audio = (Audio *)lpParameter; float *float_data = new float[AU_AUDIO_BUFFER_SIZE]; while (audio->num_waves_ > 0 && audio->wave_out_prepared_) { // Try to unprepare header if (waveOutUnprepareHeader(audio->hWaveOut, &(audio->header[audio->nextPlayBlock]), sizeof(WAVEHDR)) != WAVERR_STILLPLAYING) { int block = audio->nextPlayBlock; audio->RenderSamples(float_data, AU_AUDIO_BUFFER_SIZE); for (int i = 0; i < AU_AUDIO_BUFFER_SIZE; i++) { int sample = (int)(float_data[i] * 32768); if (sample > 32767) sample = 32767; if (sample < -32768) sample = -32768; audio->myMuzikBlock[block][i] = sample; } waveOutPrepareHeader(audio->hWaveOut, &(audio->header[block]), sizeof(WAVEHDR)); waveOutWrite(audio->hWaveOut, &(audio->header[block]), sizeof(WAVEHDR)); audio->nextPlayBlock++; if (audio->nextPlayBlock >= AU_NUM_PLAY_BLOCKS) audio->nextPlayBlock = 0; } else { Sleep(1); } } // This will not work, but who cares? delete[] float_data; return 0; } int Audio::Init(char * error_string) { ReleaseAll(); // Go throught the waves directory and load all audio files. HANDLE hFind = INVALID_HANDLE_VALUE; WIN32_FIND_DATA ffd; // Go to first file in textures directory char *dirname = AU_DIRECTORY AU_WAVE_WILDCARD; hFind = FindFirstFile(AU_DIRECTORY AU_WAVE_WILDCARD, &ffd); if (hFind == INVALID_HANDLE_VALUE) { sprintf_s(error_string, MAX_ERROR_LENGTH, "IO Error\nThere are no wave files in " AU_DIRECTORY); return -1; } // Load all the textures in the directory do { // Note that the number of textures is increased automatically int ret_val = LoadWave(ffd.cFileName, error_string); if (ret_val) return ret_val; } while (FindNextFile(hFind, &ffd)); // Initialize audio device // open audio device waveOutOpen(&hWaveOut, WAVE_MAPPER, &wfx, 0, 0, CALLBACK_NULL); // open audio device if (waveOutOpen(&hWaveOut, WAVE_MAPPER, &wfx, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR) { sprintf_s(error_string, MAX_ERROR_LENGTH, "unable to open WAVE_MAPPER device"); return -1; } wave_out_prepared_ = true; // prepare and play music block for (int i = 0; i < AU_NUM_PLAY_BLOCKS; i++) { header[i].lpData = (char *)myMuzikBlock[i]; header[i].dwBufferLength = AU_AUDIO_BUFFER_SIZE * 2; waveOutPrepareHeader(hWaveOut, &(header[i]), sizeof(WAVEHDR)); waveOutWrite(hWaveOut, &(header[i]), sizeof(WAVEHDR)); } CreateThread(NULL, 0, ThreadFunc, this, 0, 0); return 0; } int Audio::PlaySound(const char *name, int channel, bool loop, float fade_in, char *error_string) { if (channel < 0 || channel >= AU_NUM_CHANNELS) { sprintf_s(error_string, MAX_ERROR_LENGTH, "Channel %d not supported", channel); return -1; } // Find the ID of the name int audio_id = -1; for (int i = 0; i < num_waves_; i++) { if (strcmp(name, wave_name_[i]) == 0) audio_id = i; } if (audio_id < 0) { sprintf_s(error_string, MAX_ERROR_LENGTH, "Wave file '%s' not found.", name); return -1; } channel_wave_id_[channel] = audio_id; channel_position_[channel] = 0; channel_loop_[channel] = loop; channel_fade_out_[channel] = -1.0f; if (fade_in < 0.0f) { channel_volume_[channel] = 1.0f; channel_fade_in_[channel] = -1.0f; } else { channel_volume_[channel] = 0.0f; channel_fade_in_[channel] = fade_in; } return 0; } int Audio::StopSound(int channel, float fade_out, char *error_string) { if (channel < 0 || channel >= AU_NUM_CHANNELS) { sprintf_s(error_string, MAX_ERROR_LENGTH, "Channel %d not supported", channel); return -1; } channel_fade_in_[channel] = -1.0f; if (fade_out < 0.0f) { channel_volume_[channel] = expf(AU_FADE_IN_START_DB / 6.0f * logf(2.0f)); } else { channel_fade_out_[channel] = fade_out; } return 0; } int Audio::LoadWave(const char * filename, char * error_string) { char combined_name[AU_MAX_FILENAME_LENGTH + 1]; sprintf_s(combined_name, AU_MAX_FILENAME_LENGTH, AU_DIRECTORY "%s", filename); if (num_waves_ >= AU_MAX_NUM_WAVES) { sprintf_s(error_string, MAX_ERROR_LENGTH, "Too many wave files."); return -1; } FILE *fid; if (fopen_s(&fid, combined_name, "rb")) { sprintf_s(error_string, MAX_ERROR_LENGTH, "Could not find wave '%s'", filename); return -1; } // Load header (best guess) int header[11]; if (fread(header, sizeof(int), 11, fid) < 10) { fclose(fid); sprintf_s(error_string, MAX_ERROR_LENGTH, "Invalid wave file '%s'", filename); return -1; } // Stupid header checking if (header[4] != 16) { sprintf_s(error_string, MAX_ERROR_LENGTH, "%s: Not 16-bit audio", filename); return -1; } if (header[6] != AU_SAMPLING_RATE) { sprintf_s(error_string, MAX_ERROR_LENGTH, "%s: Sampling rate is not 48000 Hz", filename); return -1; } bool stereo = false; if (header[7] != 2 * AU_SAMPLING_RATE) { // This is how I know it is stereo... if (header[7] == 4 * AU_SAMPLING_RATE) { stereo = true; } else { sprintf_s(error_string, MAX_ERROR_LENGTH, "%s: Unknown format", filename); return -1; } } // TODO: Number of channels [I could just take the left one for stereo... int num_samples = header[10] / 2; wave_length_[num_waves_] = num_samples; if (stereo) wave_length_[num_waves_] = num_samples / 2; if (wave_length_[num_waves_] > AU_MAX_AUDIO_LENGTH) { sprintf_s(error_string, MAX_ERROR_LENGTH, "%s: Too many samples: %d", filename, wave_length_[num_waves_]); return -1; } short *short_buffer = new short[num_samples]; if (fread(short_buffer, sizeof(short), num_samples, fid) != num_samples) { delete[] short_buffer; sprintf_s(error_string, MAX_ERROR_LENGTH, "%s: Could not load samples for some reason...", filename); return -1; } wave_data_[num_waves_] = new float[wave_length_[num_waves_]]; for (int i = 0; i < wave_length_[num_waves_]; i++) { if (stereo) wave_data_[num_waves_][i] = (float)(short_buffer[i * 2]) / 32768.0f; else wave_data_[num_waves_][i] = (float)(short_buffer[i]) / 32768.0f; } strcpy_s(wave_name_[num_waves_], AU_MAX_FILENAME_LENGTH, filename); num_waves_++; delete[] short_buffer; fclose(fid); return 0; } void Audio::RenderSamples(float *mix, int num_samples) { // Clear the mix so that the following calls can just add for (int sample = 0; sample < num_samples; sample++) { mix[sample] = 0.0f; } for (int channel = 0; channel < AU_NUM_CHANNELS; channel++) { int wave_id = channel_wave_id_[channel]; if (wave_id >= 0) { int position = channel_position_[channel]; int length = wave_length_[wave_id]; bool loop = channel_loop_[channel]; float volume = channel_volume_[channel]; float fade_in = channel_fade_in_[channel]; float fade_out = channel_fade_out_[channel]; float fade_multiply = 1.0f; const float *wave = wave_data_[wave_id]; if (fade_in >= 0.0f) { // fade_in of 6 equals fade_multiply of 2.0f fade_multiply = expf(fade_in / 6.0f / AU_SAMPLING_RATE * logf(2.0f)); } // Fade out has higher priority if (fade_out >= 0.0f) { // fade_out of 6 equals fade_multiply of 2.0f fade_multiply = expf(-fade_out / 6.0f / AU_SAMPLING_RATE * logf(2.0f)); } for (int sample = 0; sample < num_samples; sample++) { position++; if (position >= length) { position = 0; if (!loop) { volume = 0.0f; fade_in = -1.0f; fade_out = -1.0f; } } volume *= fade_multiply; if (volume > 1.0f) volume = 1.0f; if (volume < 1e-10f) volume = 0.0f; // Avoid denormal floats mix[sample] += volume * wave[position]; } // Write back modified channel data channel_position_[channel] = position; channel_volume_[channel] = volume; } } } void Audio::ReleaseAll(void) { int num = num_waves_; num_waves_ = 0; for (int i = 0; i < AU_NUM_CHANNELS; i++) { channel_wave_id_[i] = -1; } // Assume that playing stops after a while Sleep(200); for (int i = 0; i < num_waves_; i++) { delete[] wave_data_[i]; } if (wave_out_prepared_) { waveOutClose(hWaveOut); } } <commit_msg>Fixed fade-in bug<commit_after>#include "stdafx.h" #include "Audio.h" #include "Configuration.h" const WAVEFORMATEX Audio::wfx = { WAVE_FORMAT_PCM, // wFormatTag 1, // nChannels AU_SAMPLING_RATE, // nSamplesPerSec AU_SAMPLING_RATE * 2, // nAvgBytesPerSec 1 * 2, // nBlockAlign 16, // wBitsPerSample 0 // cbSize }; Audio::Audio() { num_waves_ = 0; wave_out_prepared_ = false; ReleaseAll(); } Audio::~Audio() { ReleaseAll(); } DWORD WINAPI Audio::ThreadFunc(LPVOID lpParameter) { Audio *audio = (Audio *)lpParameter; float *float_data = new float[AU_AUDIO_BUFFER_SIZE]; while (audio->num_waves_ > 0 && audio->wave_out_prepared_) { // Try to unprepare header if (waveOutUnprepareHeader(audio->hWaveOut, &(audio->header[audio->nextPlayBlock]), sizeof(WAVEHDR)) != WAVERR_STILLPLAYING) { int block = audio->nextPlayBlock; audio->RenderSamples(float_data, AU_AUDIO_BUFFER_SIZE); for (int i = 0; i < AU_AUDIO_BUFFER_SIZE; i++) { int sample = (int)(float_data[i] * 32768); if (sample > 32767) sample = 32767; if (sample < -32768) sample = -32768; audio->myMuzikBlock[block][i] = sample; } waveOutPrepareHeader(audio->hWaveOut, &(audio->header[block]), sizeof(WAVEHDR)); waveOutWrite(audio->hWaveOut, &(audio->header[block]), sizeof(WAVEHDR)); audio->nextPlayBlock++; if (audio->nextPlayBlock >= AU_NUM_PLAY_BLOCKS) audio->nextPlayBlock = 0; } else { Sleep(1); } } // This will not work, but who cares? delete[] float_data; return 0; } int Audio::Init(char * error_string) { ReleaseAll(); // Go throught the waves directory and load all audio files. HANDLE hFind = INVALID_HANDLE_VALUE; WIN32_FIND_DATA ffd; // Go to first file in textures directory char *dirname = AU_DIRECTORY AU_WAVE_WILDCARD; hFind = FindFirstFile(AU_DIRECTORY AU_WAVE_WILDCARD, &ffd); if (hFind == INVALID_HANDLE_VALUE) { sprintf_s(error_string, MAX_ERROR_LENGTH, "IO Error\nThere are no wave files in " AU_DIRECTORY); return -1; } // Load all the textures in the directory do { // Note that the number of textures is increased automatically int ret_val = LoadWave(ffd.cFileName, error_string); if (ret_val) return ret_val; } while (FindNextFile(hFind, &ffd)); // Initialize audio device // open audio device waveOutOpen(&hWaveOut, WAVE_MAPPER, &wfx, 0, 0, CALLBACK_NULL); // open audio device if (waveOutOpen(&hWaveOut, WAVE_MAPPER, &wfx, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR) { sprintf_s(error_string, MAX_ERROR_LENGTH, "unable to open WAVE_MAPPER device"); return -1; } wave_out_prepared_ = true; // prepare and play music block for (int i = 0; i < AU_NUM_PLAY_BLOCKS; i++) { header[i].lpData = (char *)myMuzikBlock[i]; header[i].dwBufferLength = AU_AUDIO_BUFFER_SIZE * 2; waveOutPrepareHeader(hWaveOut, &(header[i]), sizeof(WAVEHDR)); waveOutWrite(hWaveOut, &(header[i]), sizeof(WAVEHDR)); } CreateThread(NULL, 0, ThreadFunc, this, 0, 0); return 0; } int Audio::PlaySound(const char *name, int channel, bool loop, float fade_in, char *error_string) { if (channel < 0 || channel >= AU_NUM_CHANNELS) { sprintf_s(error_string, MAX_ERROR_LENGTH, "Channel %d not supported", channel); return -1; } // Find the ID of the name int audio_id = -1; for (int i = 0; i < num_waves_; i++) { if (strcmp(name, wave_name_[i]) == 0) audio_id = i; } if (audio_id < 0) { sprintf_s(error_string, MAX_ERROR_LENGTH, "Wave file '%s' not found.", name); return -1; } channel_wave_id_[channel] = audio_id; channel_position_[channel] = 0; channel_loop_[channel] = loop; channel_fade_out_[channel] = -1.0f; if (fade_in < 0.0f) { channel_volume_[channel] = 1.0f; channel_fade_in_[channel] = -1.0f; } else { // start sound with -70dB channel_volume_[channel] = expf(-70.0f / 6.0f * logf(2.0f)); channel_fade_in_[channel] = fade_in; } return 0; } int Audio::StopSound(int channel, float fade_out, char *error_string) { if (channel < 0 || channel >= AU_NUM_CHANNELS) { sprintf_s(error_string, MAX_ERROR_LENGTH, "Channel %d not supported", channel); return -1; } channel_fade_in_[channel] = -1.0f; if (fade_out < 0.0f) { channel_volume_[channel] = expf(AU_FADE_IN_START_DB / 6.0f * logf(2.0f)); } else { channel_fade_out_[channel] = fade_out; } return 0; } int Audio::LoadWave(const char * filename, char * error_string) { char combined_name[AU_MAX_FILENAME_LENGTH + 1]; sprintf_s(combined_name, AU_MAX_FILENAME_LENGTH, AU_DIRECTORY "%s", filename); if (num_waves_ >= AU_MAX_NUM_WAVES) { sprintf_s(error_string, MAX_ERROR_LENGTH, "Too many wave files."); return -1; } FILE *fid; if (fopen_s(&fid, combined_name, "rb")) { sprintf_s(error_string, MAX_ERROR_LENGTH, "Could not find wave '%s'", filename); return -1; } // Load header (best guess) int header[11]; if (fread(header, sizeof(int), 11, fid) < 10) { fclose(fid); sprintf_s(error_string, MAX_ERROR_LENGTH, "Invalid wave file '%s'", filename); return -1; } // Stupid header checking if (header[4] != 16) { sprintf_s(error_string, MAX_ERROR_LENGTH, "%s: Not 16-bit audio", filename); return -1; } if (header[6] != AU_SAMPLING_RATE) { sprintf_s(error_string, MAX_ERROR_LENGTH, "%s: Sampling rate is not 48000 Hz", filename); return -1; } bool stereo = false; if (header[7] != 2 * AU_SAMPLING_RATE) { // This is how I know it is stereo... if (header[7] == 4 * AU_SAMPLING_RATE) { stereo = true; } else { sprintf_s(error_string, MAX_ERROR_LENGTH, "%s: Unknown format", filename); return -1; } } // TODO: Number of channels [I could just take the left one for stereo... int num_samples = header[10] / 2; wave_length_[num_waves_] = num_samples; if (stereo) wave_length_[num_waves_] = num_samples / 2; if (wave_length_[num_waves_] > AU_MAX_AUDIO_LENGTH) { sprintf_s(error_string, MAX_ERROR_LENGTH, "%s: Too many samples: %d", filename, wave_length_[num_waves_]); return -1; } short *short_buffer = new short[num_samples]; if (fread(short_buffer, sizeof(short), num_samples, fid) != num_samples) { delete[] short_buffer; sprintf_s(error_string, MAX_ERROR_LENGTH, "%s: Could not load samples for some reason...", filename); return -1; } wave_data_[num_waves_] = new float[wave_length_[num_waves_]]; for (int i = 0; i < wave_length_[num_waves_]; i++) { if (stereo) wave_data_[num_waves_][i] = (float)(short_buffer[i * 2]) / 32768.0f; else wave_data_[num_waves_][i] = (float)(short_buffer[i]) / 32768.0f; } strcpy_s(wave_name_[num_waves_], AU_MAX_FILENAME_LENGTH, filename); num_waves_++; delete[] short_buffer; fclose(fid); return 0; } void Audio::RenderSamples(float *mix, int num_samples) { // Clear the mix so that the following calls can just add for (int sample = 0; sample < num_samples; sample++) { mix[sample] = 0.0f; } for (int channel = 0; channel < AU_NUM_CHANNELS; channel++) { int wave_id = channel_wave_id_[channel]; if (wave_id >= 0) { int position = channel_position_[channel]; int length = wave_length_[wave_id]; bool loop = channel_loop_[channel]; float volume = channel_volume_[channel]; float fade_in = channel_fade_in_[channel]; float fade_out = channel_fade_out_[channel]; float fade_multiply = 1.0f; const float *wave = wave_data_[wave_id]; if (fade_in >= 0.0f) { // fade_in of 6 equals fade_multiply of 2.0f fade_multiply = expf(fade_in / 6.0f / AU_SAMPLING_RATE * logf(2.0f)); } // Fade out has higher priority if (fade_out >= 0.0f) { // fade_out of 6 equals fade_multiply of 2.0f fade_multiply = expf(-fade_out / 6.0f / AU_SAMPLING_RATE * logf(2.0f)); } for (int sample = 0; sample < num_samples; sample++) { position++; if (position >= length) { position = 0; if (!loop) { volume = 0.0f; fade_in = -1.0f; fade_out = -1.0f; } } volume *= fade_multiply; if (volume > 1.0f) volume = 1.0f; if (volume < 1e-10f) volume = 0.0f; // Avoid denormal floats mix[sample] += volume * wave[position]; } // Write back modified channel data channel_position_[channel] = position; channel_volume_[channel] = volume; } } } void Audio::ReleaseAll(void) { int num = num_waves_; num_waves_ = 0; for (int i = 0; i < AU_NUM_CHANNELS; i++) { channel_wave_id_[i] = -1; } // Assume that playing stops after a while Sleep(200); for (int i = 0; i < num_waves_; i++) { delete[] wave_data_[i]; } if (wave_out_prepared_) { waveOutClose(hWaveOut); } } <|endoftext|>
<commit_before><commit_msg>Updated xjob.cc includes and namespace.<commit_after><|endoftext|>
<commit_before>#include "Core/Logger.hpp" #include "Core/MessageQueue.hpp" #include "Services/Display.hpp" #include "Services/HttpServerAsync.hpp" #include "Services/WiFiManager.hpp" #include "Services/WebSocketsServerAsync.hpp" #include "Json/SerializationService.hpp" #include "Json/StatusResultSerializer.hpp" #include "Json/ListSerializer.hpp" #include "Json/NetworkSerializer.hpp" #include "Json/SettingsSerializer.hpp" #include "Json/ConnectionSerializer.hpp" #include "Json/SerializationContextFactory.hpp" #include "Json/RequestSerializer.hpp" #include "Json/ResponseSerializer.hpp" #include "Json/NotificationSerializer.hpp" #include "Json/ObjectResultSerializer.hpp" #include <FS.h> #include <Adafruit_NeoPixel.h> using namespace Core; using namespace Json; using namespace Services; std::list<std::shared_ptr<ILoopedService>> loopedServices; void setup(void){ Logger::initialize(); SPIFFS.begin(); // Creating services Logger::message("Creating the message queue..."); auto messageQueue(std::make_shared<MessageQueue>()); Logger::message("Creating the display.."); auto display(std::make_shared<Display>(messageQueue)); Logger::message("Creating the wifi manager..."); auto wifiManager(std::make_shared<WiFiManager>(messageQueue)); Logger::message("Creating the context factory..."); auto contextFactory( std::make_shared<SerializationContextFactory>()); Logger::message("Creating the serialization service..."); auto serializationService( std::make_shared<SerializationService>(contextFactory)); Logger::message("Creating the creating HTTP server..."); auto httpServerAsync( std::make_shared<HttpServerAsync>(80, wifiManager)); Logger::message("Creating creating Web Sockets server..."); auto webSocketsServerAsync( std::make_shared<WebSocketsServerAsync>(81, messageQueue, serializationService)); httpServerAsync->server->addHandler(webSocketsServerAsync->server.get()); // Registering serializers Logger::message("Registering serializers..."); serializationService->addSerializer( std::make_shared<StatusResultSerializer>()); serializationService->addSerializer( std::make_shared<ListSerializer>()); serializationService->addSerializer( std::make_shared<NetworkSerializer>()); serializationService->addSerializer( std::make_shared<SettingsSerializer>()); serializationService->addSerializer( std::make_shared<ConnectionSerializer>()); serializationService->addSerializer( std::make_shared<RequestSerializer>()); serializationService->addSerializer( std::make_shared<ResponseSerializer>()); serializationService->addSerializer( std::make_shared<NotificationSerializer>()); serializationService->addSerializer( std::make_shared<ObjectResultSerializer>()); Logger::message("Starting wifi manager..."); wifiManager->start(); Logger::message("Starting http server..."); httpServerAsync->start(); Logger::message("Starting websocket server server..."); webSocketsServerAsync->start(); // Adding servers to the loop Logger::message("Adding services to the loop..."); loopedServices.push_back(display); loopedServices.push_back(messageQueue); loopedServices.push_back(httpServerAsync); loopedServices.push_back(wifiManager); loopedServices.push_back(webSocketsServerAsync); Logger::message("Initialization finished."); } void loop(void){ for(auto service : loopedServices) { service->loop(); } } <commit_msg>Adding heap metric.<commit_after>#include "Core/Logger.hpp" #include "Core/MessageQueue.hpp" #include "Services/Display.hpp" #include "Services/HttpServerAsync.hpp" #include "Services/WiFiManager.hpp" #include "Services/WebSocketsServerAsync.hpp" #include "Json/SerializationService.hpp" #include "Json/StatusResultSerializer.hpp" #include "Json/ListSerializer.hpp" #include "Json/NetworkSerializer.hpp" #include "Json/SettingsSerializer.hpp" #include "Json/ConnectionSerializer.hpp" #include "Json/SerializationContextFactory.hpp" #include "Json/RequestSerializer.hpp" #include "Json/ResponseSerializer.hpp" #include "Json/NotificationSerializer.hpp" #include "Json/ObjectResultSerializer.hpp" #include <FS.h> #include <Adafruit_NeoPixel.h> using namespace Core; using namespace Json; using namespace Services; std::list<std::shared_ptr<ILoopedService>> loopedServices; void setup(void){ Logger::initialize(); SPIFFS.begin(); // Creating services Logger::message("Creating the message queue..."); auto messageQueue(std::make_shared<MessageQueue>()); Logger::message("Creating the display.."); auto display(std::make_shared<Display>(messageQueue)); Logger::message("Creating the wifi manager..."); auto wifiManager(std::make_shared<WiFiManager>(messageQueue)); Logger::message("Creating the context factory..."); auto contextFactory( std::make_shared<SerializationContextFactory>()); Logger::message("Creating the serialization service..."); auto serializationService( std::make_shared<SerializationService>(contextFactory)); Logger::message("Creating the creating HTTP server..."); auto httpServerAsync( std::make_shared<HttpServerAsync>(80, wifiManager)); Logger::message("Creating creating Web Sockets server..."); auto webSocketsServerAsync( std::make_shared<WebSocketsServerAsync>(81, messageQueue, serializationService)); httpServerAsync->server->addHandler(webSocketsServerAsync->server.get()); // Registering serializers Logger::message("Registering serializers..."); serializationService->addSerializer( std::make_shared<StatusResultSerializer>()); serializationService->addSerializer( std::make_shared<ListSerializer>()); serializationService->addSerializer( std::make_shared<NetworkSerializer>()); serializationService->addSerializer( std::make_shared<SettingsSerializer>()); serializationService->addSerializer( std::make_shared<ConnectionSerializer>()); serializationService->addSerializer( std::make_shared<RequestSerializer>()); serializationService->addSerializer( std::make_shared<ResponseSerializer>()); serializationService->addSerializer( std::make_shared<NotificationSerializer>()); serializationService->addSerializer( std::make_shared<ObjectResultSerializer>()); Logger::message("Starting wifi manager..."); wifiManager->start(); Logger::message("Starting http server..."); httpServerAsync->start(); Logger::message("Starting websocket server server..."); webSocketsServerAsync->start(); // Adding servers to the loop Logger::message("Adding services to the loop..."); loopedServices.push_back(display); loopedServices.push_back(messageQueue); loopedServices.push_back(httpServerAsync); loopedServices.push_back(wifiManager); loopedServices.push_back(webSocketsServerAsync); Logger::message("Initialization finished, free heap size " + String(ESP.getFreeHeap()) + " bytes."); } void loop(void){ for(auto service : loopedServices) { service->loop(); } } <|endoftext|>
<commit_before>/* * Main.cpp * * Created on: Jul 13, 2014 * Author: Pimenta */ #include "metallicar.hpp" class FirstScene : public metallicar::engine::GameScene { protected: void update() { if (metallicar::engine::Game::quitRequested()) { metallicar::engine::Game::quit(); } } void render() { } void wakeup(void* args) { } }; int main(int argc, char* argv[]) { metallicar::engine::Game::init(); metallicar::engine::Game::run(new FirstScene()); return 0; } <commit_msg>Update Main.cpp<commit_after>/* * Main.cpp * * Created on: Jul 13, 2014 * Author: Pimenta */ #include "metallicar.hpp" using namespace metallicar::engine; class FirstScene : public GameScene { protected: void update() { if (Game::quitRequested()) { Game::quit(); } } void render() { } void wakeup(void* args) { } }; int main(int argc, char* argv[]) { Game::init(); Game::run(new FirstScene()); return 0; } <|endoftext|>
<commit_before>// The MIT License (MIT) // // Copyright (c) 2016 Mustafa Serdar Sanli // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include <cstdlib> #include <fstream> #include <iostream> #include <iterator> #include <string> #include <vector> #include "CodeGenerator.hpp" #include "Parser.hpp" #include "Tokenizer.hpp" #include "src/CommandLineFlags.hpp" using namespace std; int main(int argc, char* argv[]) { gengetopt_args_info args; if (cmdline_parser (argc, argv, &args) != 0) { exit(1); } ifstream iSource(args.in_arg); if (!iSource.is_open()) { // TODO untested cerr << "Unable to open file " << args.in_arg << "\n"; return 1; } string input{istreambuf_iterator<char>(iSource), istreambuf_iterator<char>()}; ParsedFile f = Parse(Tokenize(input)); ofstream oHeader(args.out_arg); GenerateHeaderForFile(oHeader, f); return 0; } <commit_msg>Improve I/O error handling<commit_after>// The MIT License (MIT) // // Copyright (c) 2016 Mustafa Serdar Sanli // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include <cstdlib> #include <fstream> #include <iostream> #include <iterator> #include <string> #include <vector> #include "CodeGenerator.hpp" #include "Parser.hpp" #include "Tokenizer.hpp" #include "src/CommandLineFlags.hpp" using namespace std; int main(int argc, char* argv[]) { gengetopt_args_info args; if (cmdline_parser (argc, argv, &args) != 0) { exit(1); } ifstream iSource(args.in_arg); if (!iSource.is_open()) { cerr << "Unable to open input file " << args.in_arg << "\n"; return 1; } string input{istreambuf_iterator<char>(iSource), istreambuf_iterator<char>()}; if (iSource.bad()) { cerr << "Read error on file " << args.in_arg << "\n"; return 1; } ParsedFile f = Parse(Tokenize(input)); ofstream oHeader(args.out_arg); if (!oHeader.is_open()) { cerr << "Unable to open output file " << args.out_arg << "\n"; return 1; } GenerateHeaderForFile(oHeader, f); oHeader.flush(); if (oHeader.bad()) { cerr << "Write error on file " << args.out_arg << "\n"; return 1; } return 0; } <|endoftext|>
<commit_before>#include "OSPGlutViewer.h" using std::cout; using std::endl; using std::string; using std::lock_guard; using std::mutex; using namespace ospcommon; // Static local helper functions ////////////////////////////////////////////// // helper function to write the rendered image as PPM file static void writePPM(const string &fileName, const int sizeX, const int sizeY, const uint32_t *pixel) { FILE *file = fopen(fileName.c_str(), "wb"); fprintf(file, "P6\n%i %i\n255\n", sizeX, sizeY); unsigned char *out = (unsigned char *)alloca(3*sizeX); for (int y = 0; y < sizeY; y++) { const unsigned char *in = (const unsigned char *)&pixel[(sizeY-1-y)*sizeX]; for (int x = 0; x < sizeX; x++) { out[3*x + 0] = in[4*x + 0]; out[3*x + 1] = in[4*x + 1]; out[3*x + 2] = in[4*x + 2]; } fwrite(out, 3*sizeX, sizeof(char), file); } fprintf(file, "\n"); fclose(file); } // MSGViewer definitions ////////////////////////////////////////////////////// namespace ospray { OSPGlutViewer::OSPGlutViewer(const box3f &worldBounds, cpp::Model model, cpp::Renderer renderer, cpp::Camera camera) : Glut3DWidget(Glut3DWidget::FRAMEBUFFER_NONE), m_model(model), m_fb(nullptr), m_renderer(renderer), m_camera(camera), m_queuedRenderer(nullptr), m_alwaysRedraw(true), m_accumID(-1), m_fullScreen(false) { setWorldBounds(worldBounds); m_renderer.set("world", m_model); m_renderer.set("model", m_model); m_renderer.set("camera", m_camera); m_renderer.commit(); #if 0 cout << "#ospDebugViewer: set world bounds " << worldBounds << ", motion speed " << motionSpeed << endl; #endif m_resetAccum = false; } void OSPGlutViewer::setRenderer(OSPRenderer renderer) { lock_guard<mutex> lock{m_rendererMutex}; m_queuedRenderer = renderer; } void OSPGlutViewer::resetAccumulation() { m_resetAccum = true; } void OSPGlutViewer::toggleFullscreen() { m_fullScreen = !m_fullScreen; if(m_fullScreen) { glutFullScreen(); } else { glutPositionWindow(0,10); } } void OSPGlutViewer::resetView() { viewPort = m_viewPort; } void OSPGlutViewer::printViewport() { printf("-vp %f %f %f -vu %f %f %f -vi %f %f %f\n", viewPort.from.x, viewPort.from.y, viewPort.from.z, viewPort.up.x, viewPort.up.y, viewPort.up.z, viewPort.at.x, viewPort.at.y, viewPort.at.z); fflush(stdout); } void OSPGlutViewer::saveScreenshot(const std::string &basename) { const uint32_t *p = (uint32_t*)m_fb.map(OSP_FB_COLOR); writePPM(basename + ".ppm", m_windowSize.x, m_windowSize.y, p); cout << "#ospDebugViewer: saved current frame to '" << basename << ".ppm'" << endl; } void OSPGlutViewer::reshape(const vec2i &newSize) { Glut3DWidget::reshape(newSize); m_windowSize = newSize; m_fb = cpp::FrameBuffer(osp::vec2i{newSize.x, newSize.y}, OSP_FB_SRGBA, OSP_FB_COLOR | OSP_FB_DEPTH | OSP_FB_ACCUM); m_fb.clear(OSP_FB_ACCUM); m_camera.set("aspect", viewPort.aspect); m_camera.commit(); viewPort.modified = true; forceRedraw(); } void OSPGlutViewer::keypress(char key, const vec2i &where) { switch (key) { case 'R': m_alwaysRedraw = !m_alwaysRedraw; forceRedraw(); break; case '!': saveScreenshot("ospdebugviewer"); break; case 'X': if (viewPort.up == vec3f(1,0,0) || viewPort.up == vec3f(-1.f,0,0)) { viewPort.up = - viewPort.up; } else { viewPort.up = vec3f(1,0,0); } viewPort.modified = true; forceRedraw(); break; case 'Y': if (viewPort.up == vec3f(0,1,0) || viewPort.up == vec3f(0,-1.f,0)) { viewPort.up = - viewPort.up; } else { viewPort.up = vec3f(0,1,0); } viewPort.modified = true; forceRedraw(); break; case 'Z': if (viewPort.up == vec3f(0,0,1) || viewPort.up == vec3f(0,0,-1.f)) { viewPort.up = - viewPort.up; } else { viewPort.up = vec3f(0,0,1); } viewPort.modified = true; forceRedraw(); break; case 'f': toggleFullscreen(); break; case 'r': resetView(); break; case 'p': printViewport(); break; default: Glut3DWidget::keypress(key,where); } } void OSPGlutViewer::mouseButton(int32_t whichButton, bool released, const vec2i &pos) { Glut3DWidget::mouseButton(whichButton, released, pos); if((currButtonState == (1<<GLUT_LEFT_BUTTON)) && (glutGetModifiers() & GLUT_ACTIVE_SHIFT) && (manipulator == inspectCenterManipulator)) { vec2f normpos = vec2f(pos.x / (float)windowSize.x, 1.0f - pos.y / (float)windowSize.y); OSPPickResult pick; ospPick(&pick, m_renderer.handle(), osp::vec2f{normpos.x, normpos.y}); if(pick.hit) { viewPort.at = ospcommon::vec3f{pick.position.x, pick.position.y, pick.position.z}; viewPort.modified = true; computeFrame(); forceRedraw(); } } } void OSPGlutViewer::display() { if (!m_fb.handle() || !m_renderer.handle()) return; static int frameID = 0; //{ // note that the order of 'start' and 'end' here is // (intentionally) reversed: due to our asynchrounous rendering // you cannot place start() and end() _around_ the renderframe // call (which in itself will not do a lot other than triggering // work), but the average time between the two calls is roughly the // frame rate (including display overhead, of course) if (frameID > 0) m_fps.doneRender(); // NOTE: consume a new renderer if one has been queued by another thread switchRenderers(); if (m_resetAccum) { m_fb.clear(OSP_FB_ACCUM); m_resetAccum = false; } m_fps.startRender(); //} ++frameID; if (viewPort.modified) { static bool once = true; if(once) { m_viewPort = viewPort; once = false; } Assert2(m_camera.handle(),"ospray camera is null"); m_camera.set("pos", viewPort.from); auto dir = viewPort.at - viewPort.from; m_camera.set("dir", dir); m_camera.set("up", viewPort.up); m_camera.set("aspect", viewPort.aspect); m_camera.commit(); viewPort.modified = false; m_accumID=0; m_fb.clear(OSP_FB_ACCUM); } m_renderer.renderFrame(m_fb, OSP_FB_COLOR | OSP_FB_ACCUM); ++m_accumID; // set the glut3d widget's frame buffer to the opsray frame buffer, // then display ucharFB = (uint32_t *)m_fb.map(OSP_FB_COLOR); frameBufferMode = Glut3DWidget::FRAMEBUFFER_UCHAR; Glut3DWidget::display(); m_fb.unmap(ucharFB); // that pointer is no longer valid, so set it to null ucharFB = nullptr; std::string title("OSPRay Debug Viewer"); if (m_alwaysRedraw) { title += " (" + std::to_string((long double)m_fps.getFPS()) + " fps)"; setTitle(title); forceRedraw(); } else { setTitle(title); } } void OSPGlutViewer::switchRenderers() { lock_guard<mutex> lock{m_rendererMutex}; if (m_queuedRenderer.handle()) { m_renderer = m_queuedRenderer; m_queuedRenderer = nullptr; m_fb.clear(OSP_FB_ACCUM); } } }// namepace ospray <commit_msg>fix missed rename ospDebugViewer --> ospGlutViewer<commit_after>#include "OSPGlutViewer.h" using std::cout; using std::endl; using std::string; using std::lock_guard; using std::mutex; using namespace ospcommon; // Static local helper functions ////////////////////////////////////////////// // helper function to write the rendered image as PPM file static void writePPM(const string &fileName, const int sizeX, const int sizeY, const uint32_t *pixel) { FILE *file = fopen(fileName.c_str(), "wb"); fprintf(file, "P6\n%i %i\n255\n", sizeX, sizeY); unsigned char *out = (unsigned char *)alloca(3*sizeX); for (int y = 0; y < sizeY; y++) { const unsigned char *in = (const unsigned char *)&pixel[(sizeY-1-y)*sizeX]; for (int x = 0; x < sizeX; x++) { out[3*x + 0] = in[4*x + 0]; out[3*x + 1] = in[4*x + 1]; out[3*x + 2] = in[4*x + 2]; } fwrite(out, 3*sizeX, sizeof(char), file); } fprintf(file, "\n"); fclose(file); } // MSGViewer definitions ////////////////////////////////////////////////////// namespace ospray { OSPGlutViewer::OSPGlutViewer(const box3f &worldBounds, cpp::Model model, cpp::Renderer renderer, cpp::Camera camera) : Glut3DWidget(Glut3DWidget::FRAMEBUFFER_NONE), m_model(model), m_fb(nullptr), m_renderer(renderer), m_camera(camera), m_queuedRenderer(nullptr), m_alwaysRedraw(true), m_accumID(-1), m_fullScreen(false) { setWorldBounds(worldBounds); m_renderer.set("world", m_model); m_renderer.set("model", m_model); m_renderer.set("camera", m_camera); m_renderer.commit(); #if 0 cout << "#ospGlutViewer: set world bounds " << worldBounds << ", motion speed " << motionSpeed << endl; #endif m_resetAccum = false; } void OSPGlutViewer::setRenderer(OSPRenderer renderer) { lock_guard<mutex> lock{m_rendererMutex}; m_queuedRenderer = renderer; } void OSPGlutViewer::resetAccumulation() { m_resetAccum = true; } void OSPGlutViewer::toggleFullscreen() { m_fullScreen = !m_fullScreen; if(m_fullScreen) { glutFullScreen(); } else { glutPositionWindow(0,10); } } void OSPGlutViewer::resetView() { viewPort = m_viewPort; } void OSPGlutViewer::printViewport() { printf("-vp %f %f %f -vu %f %f %f -vi %f %f %f\n", viewPort.from.x, viewPort.from.y, viewPort.from.z, viewPort.up.x, viewPort.up.y, viewPort.up.z, viewPort.at.x, viewPort.at.y, viewPort.at.z); fflush(stdout); } void OSPGlutViewer::saveScreenshot(const std::string &basename) { const uint32_t *p = (uint32_t*)m_fb.map(OSP_FB_COLOR); writePPM(basename + ".ppm", m_windowSize.x, m_windowSize.y, p); cout << "#ospGlutViewer: saved current frame to '" << basename << ".ppm'" << endl; } void OSPGlutViewer::reshape(const vec2i &newSize) { Glut3DWidget::reshape(newSize); m_windowSize = newSize; m_fb = cpp::FrameBuffer(osp::vec2i{newSize.x, newSize.y}, OSP_FB_SRGBA, OSP_FB_COLOR | OSP_FB_DEPTH | OSP_FB_ACCUM); m_fb.clear(OSP_FB_ACCUM); m_camera.set("aspect", viewPort.aspect); m_camera.commit(); viewPort.modified = true; forceRedraw(); } void OSPGlutViewer::keypress(char key, const vec2i &where) { switch (key) { case 'R': m_alwaysRedraw = !m_alwaysRedraw; forceRedraw(); break; case '!': saveScreenshot("ospdebugviewer"); break; case 'X': if (viewPort.up == vec3f(1,0,0) || viewPort.up == vec3f(-1.f,0,0)) { viewPort.up = - viewPort.up; } else { viewPort.up = vec3f(1,0,0); } viewPort.modified = true; forceRedraw(); break; case 'Y': if (viewPort.up == vec3f(0,1,0) || viewPort.up == vec3f(0,-1.f,0)) { viewPort.up = - viewPort.up; } else { viewPort.up = vec3f(0,1,0); } viewPort.modified = true; forceRedraw(); break; case 'Z': if (viewPort.up == vec3f(0,0,1) || viewPort.up == vec3f(0,0,-1.f)) { viewPort.up = - viewPort.up; } else { viewPort.up = vec3f(0,0,1); } viewPort.modified = true; forceRedraw(); break; case 'f': toggleFullscreen(); break; case 'r': resetView(); break; case 'p': printViewport(); break; default: Glut3DWidget::keypress(key,where); } } void OSPGlutViewer::mouseButton(int32_t whichButton, bool released, const vec2i &pos) { Glut3DWidget::mouseButton(whichButton, released, pos); if((currButtonState == (1<<GLUT_LEFT_BUTTON)) && (glutGetModifiers() & GLUT_ACTIVE_SHIFT) && (manipulator == inspectCenterManipulator)) { vec2f normpos = vec2f(pos.x / (float)windowSize.x, 1.0f - pos.y / (float)windowSize.y); OSPPickResult pick; ospPick(&pick, m_renderer.handle(), osp::vec2f{normpos.x, normpos.y}); if(pick.hit) { viewPort.at = ospcommon::vec3f{pick.position.x, pick.position.y, pick.position.z}; viewPort.modified = true; computeFrame(); forceRedraw(); } } } void OSPGlutViewer::display() { if (!m_fb.handle() || !m_renderer.handle()) return; static int frameID = 0; //{ // note that the order of 'start' and 'end' here is // (intentionally) reversed: due to our asynchrounous rendering // you cannot place start() and end() _around_ the renderframe // call (which in itself will not do a lot other than triggering // work), but the average time between the two calls is roughly the // frame rate (including display overhead, of course) if (frameID > 0) m_fps.doneRender(); // NOTE: consume a new renderer if one has been queued by another thread switchRenderers(); if (m_resetAccum) { m_fb.clear(OSP_FB_ACCUM); m_resetAccum = false; } m_fps.startRender(); //} ++frameID; if (viewPort.modified) { static bool once = true; if(once) { m_viewPort = viewPort; once = false; } Assert2(m_camera.handle(),"ospray camera is null"); m_camera.set("pos", viewPort.from); auto dir = viewPort.at - viewPort.from; m_camera.set("dir", dir); m_camera.set("up", viewPort.up); m_camera.set("aspect", viewPort.aspect); m_camera.commit(); viewPort.modified = false; m_accumID=0; m_fb.clear(OSP_FB_ACCUM); } m_renderer.renderFrame(m_fb, OSP_FB_COLOR | OSP_FB_ACCUM); ++m_accumID; // set the glut3d widget's frame buffer to the opsray frame buffer, // then display ucharFB = (uint32_t *)m_fb.map(OSP_FB_COLOR); frameBufferMode = Glut3DWidget::FRAMEBUFFER_UCHAR; Glut3DWidget::display(); m_fb.unmap(ucharFB); // that pointer is no longer valid, so set it to null ucharFB = nullptr; std::string title("OSPRay GLUT Viewer"); if (m_alwaysRedraw) { title += " (" + std::to_string((long double)m_fps.getFPS()) + " fps)"; setTitle(title); forceRedraw(); } else { setTitle(title); } } void OSPGlutViewer::switchRenderers() { lock_guard<mutex> lock{m_rendererMutex}; if (m_queuedRenderer.handle()) { m_renderer = m_queuedRenderer; m_queuedRenderer = nullptr; m_fb.clear(OSP_FB_ACCUM); } } }// namepace ospray <|endoftext|>
<commit_before><commit_msg>Fixes for notify callback.<commit_after><|endoftext|>
<commit_before>/******************************************************************************* Module: FGFCS.cpp Author: Jon Berndt Date started: 12/12/98 Purpose: Model the flight controls Called by: FDMExec ------------- Copyright (C) 1999 Jon S. Berndt (jsb@hal-pc.org) ------------- 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 -------------------------------------------------------------------------------- This class models the flight controls for a specific airplane HISTORY -------------------------------------------------------------------------------- 12/12/98 JSB Created ******************************************************************************** INCLUDES *******************************************************************************/ #include "FGFCS.h" #include "FGState.h" #include "FGFDMExec.h" #include "FGAtmosphere.h" #include "FGAircraft.h" #include "FGTranslation.h" #include "FGRotation.h" #include "FGPosition.h" #include "FGAuxiliary.h" #include "FGOutput.h" #include "filtersjb/FGFilter.h" #include "filtersjb/FGDeadBand.h" #include "filtersjb/FGGain.h" #include "filtersjb/FGGradient.h" #include "filtersjb/FGSwitch.h" #include "filtersjb/FGSummer.h" #include "filtersjb/FGFlaps.h" /******************************************************************************* ************************************ CODE ************************************** *******************************************************************************/ FGFCS::FGFCS(FGFDMExec* fdmex) : FGModel(fdmex) { Name = "FGFCS"; for (int i=0; i < MAX_ENGINES; i++) { ThrottleCmd[i] = 0.0; ThrottlePos[i] = 0.0; } DaCmd = DeCmd = DrCmd = DfCmd = DsbCmd = DspCmd = 0.0; DaPos = DePos = DrPos = DfPos = DsbPos = DspPos = 0.0; } /******************************************************************************/ FGFCS::~FGFCS(void) {} /******************************************************************************/ bool FGFCS::Run(void) { if (!FGModel::Run()) { for (unsigned int i=0; i<Components.size(); i++) Components[i]->Run(); } else {} return false; } /******************************************************************************/ void FGFCS::SetThrottleCmd(int engineNum, float setting) { if (engineNum < 0) { for (int ctr=0;ctr<Aircraft->GetNumEngines();ctr++) ThrottleCmd[ctr] = setting; } else { ThrottleCmd[engineNum] = setting; } } /******************************************************************************/ void FGFCS::SetThrottlePos(int engineNum, float setting) { if (engineNum < 0) { for (int ctr=0;ctr<=Aircraft->GetNumEngines();ctr++) ThrottlePos[ctr] = ThrottleCmd[ctr]; } else { ThrottlePos[engineNum] = setting; } } /******************************************************************************/ bool FGFCS::LoadFCS(FGConfigFile* AC_cfg) { string token; FCSName = AC_cfg->GetValue("NAME"); cout << " Control System Name: " << FCSName << endl; AC_cfg->GetNextConfigLine(); while ((token = AC_cfg->GetValue()) != "/FLIGHT_CONTROL") { if (token == "COMPONENT") { token = AC_cfg->GetValue("TYPE"); cout << " Loading Component \"" << AC_cfg->GetValue("NAME") << "\" of type: " << token << endl; if ((token == "LAG_FILTER") || (token == "RECT_LAG_FILTER") || (token == "LEAD_LAG_FILTER") || (token == "SECOND_ORDER_FILTER") || (token == "WASHOUT_FILTER") || (token == "INTEGRATOR") ) { Components.push_back(new FGFilter(this, AC_cfg)); } else if ((token == "PURE_GAIN") || (token == "SCHEDULED_GAIN") || (token == "AEROSURFACE_SCALE") ) { Components.push_back(new FGGain(this, AC_cfg)); } else if (token == "SUMMER") { Components.push_back(new FGSummer(this, AC_cfg)); } else if (token == "DEADBAND") { Components.push_back(new FGDeadBand(this, AC_cfg)); } else if (token == "GRADIENT") { Components.push_back(new FGGradient(this, AC_cfg)); } else if (token == "SWITCH") { Components.push_back(new FGSwitch(this, AC_cfg)); } else if (token == "FLAPS") { Components.push_back(new FGFlaps(this, AC_cfg)); } AC_cfg->GetNextConfigLine(); } } return true; } /******************************************************************************/ float FGFCS::GetComponentOutput(int idx) { return Components[idx]->GetOutput(); } /******************************************************************************/ string FGFCS::GetComponentName(int idx) { return Components[idx]->GetName(); } #pragma warn .8030 <commit_msg>Added loop to Run that copies ThrottleCmd to ThrottlePos<commit_after>/******************************************************************************* Module: FGFCS.cpp Author: Jon Berndt Date started: 12/12/98 Purpose: Model the flight controls Called by: FDMExec ------------- Copyright (C) 1999 Jon S. Berndt (jsb@hal-pc.org) ------------- 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 -------------------------------------------------------------------------------- This class models the flight controls for a specific airplane HISTORY -------------------------------------------------------------------------------- 12/12/98 JSB Created ******************************************************************************** INCLUDES *******************************************************************************/ #include "FGFCS.h" #include "FGState.h" #include "FGFDMExec.h" #include "FGAtmosphere.h" #include "FGAircraft.h" #include "FGTranslation.h" #include "FGRotation.h" #include "FGPosition.h" #include "FGAuxiliary.h" #include "FGOutput.h" #include "filtersjb/FGFilter.h" #include "filtersjb/FGDeadBand.h" #include "filtersjb/FGGain.h" #include "filtersjb/FGGradient.h" #include "filtersjb/FGSwitch.h" #include "filtersjb/FGSummer.h" #include "filtersjb/FGFlaps.h" /******************************************************************************* ************************************ CODE ************************************** *******************************************************************************/ FGFCS::FGFCS(FGFDMExec* fdmex) : FGModel(fdmex) { Name = "FGFCS"; for (int i=0; i < MAX_ENGINES; i++) { ThrottleCmd[i] = 0.0; ThrottlePos[i] = 0.0; } DaCmd = DeCmd = DrCmd = DfCmd = DsbCmd = DspCmd = 0.0; DaPos = DePos = DrPos = DfPos = DsbPos = DspPos = 0.0; } /******************************************************************************/ FGFCS::~FGFCS(void) {} /******************************************************************************/ bool FGFCS::Run(void) { if (!FGModel::Run()) { for (unsigned int i=0; i<Aircraft->GetNumEngines(); i++) ThrottlePos[i]=ThrottleCmd[i]; for (unsigned int i=0; i<Components.size(); i++) Components[i]->Run(); } else {} return false; } /******************************************************************************/ void FGFCS::SetThrottleCmd(int engineNum, float setting) { if (engineNum < 0) { for (int ctr=0;ctr<Aircraft->GetNumEngines();ctr++) ThrottleCmd[ctr] = setting; } else { ThrottleCmd[engineNum] = setting; } } /******************************************************************************/ void FGFCS::SetThrottlePos(int engineNum, float setting) { if (engineNum < 0) { for (int ctr=0;ctr<=Aircraft->GetNumEngines();ctr++) ThrottlePos[ctr] = ThrottleCmd[ctr]; } else { ThrottlePos[engineNum] = setting; } } /******************************************************************************/ bool FGFCS::LoadFCS(FGConfigFile* AC_cfg) { string token; FCSName = AC_cfg->GetValue("NAME"); cout << " Control System Name: " << FCSName << endl; AC_cfg->GetNextConfigLine(); while ((token = AC_cfg->GetValue()) != "/FLIGHT_CONTROL") { if (token == "COMPONENT") { token = AC_cfg->GetValue("TYPE"); cout << " Loading Component \"" << AC_cfg->GetValue("NAME") << "\" of type: " << token << endl; if ((token == "LAG_FILTER") || (token == "RECT_LAG_FILTER") || (token == "LEAD_LAG_FILTER") || (token == "SECOND_ORDER_FILTER") || (token == "WASHOUT_FILTER") || (token == "INTEGRATOR") ) { Components.push_back(new FGFilter(this, AC_cfg)); } else if ((token == "PURE_GAIN") || (token == "SCHEDULED_GAIN") || (token == "AEROSURFACE_SCALE") ) { Components.push_back(new FGGain(this, AC_cfg)); } else if (token == "SUMMER") { Components.push_back(new FGSummer(this, AC_cfg)); } else if (token == "DEADBAND") { Components.push_back(new FGDeadBand(this, AC_cfg)); } else if (token == "GRADIENT") { Components.push_back(new FGGradient(this, AC_cfg)); } else if (token == "SWITCH") { Components.push_back(new FGSwitch(this, AC_cfg)); } else if (token == "FLAPS") { Components.push_back(new FGFlaps(this, AC_cfg)); } AC_cfg->GetNextConfigLine(); } } return true; } /******************************************************************************/ float FGFCS::GetComponentOutput(int idx) { return Components[idx]->GetOutput(); } /******************************************************************************/ string FGFCS::GetComponentName(int idx) { return Components[idx]->GetName(); } #pragma warn .8030 <|endoftext|>
<commit_before>#ifndef __FRAME_HPP__ #define __FRAME_HPP__ #include "include/global.hpp" #include <string> #include <vector> #define MAX_PAYLOAD_LENGTH 0x7FFFFFFFFFFFFFFF; #define PAYLOAD_SIZE_DEFAULT 125; #define PAYLOAD_SIZE_EXTRA_WORD 126; #define PAYLOAD_SIZE_EXTRA_QWORD 127; typedef unsigned int FrameMask; namespace ws { struct Frame { static const byte FinalBit = 0x80; static const byte ReservedBit1 = 0x40; // Compress Extension static const byte ReservedBit2 = 0x20; static const byte ReservedBit3 = 0x10; static const byte TypeMask = 0x0F; static const byte MaskBit = 0x80; static const byte PayloadLengthMask = 0x7F; static const int FrameMinSize = 2; static const int MaskKeySize = 4; static const int PayloadSizeDefault = 125; static const int PayloadSizeExtraWord = 126; static const int PayloadSizeExtraQWord = 127; // RFC 6455 OpCodes enum Type { CONTINIUATION = 0x0, TEXT = 0x1, BINARY = 0x2, // Reserved for further non-control Frames (RFC 6455) NCF1 = 0x3, NCF2 = 0x4, NCF3 = 0x5, NCF4 = 0x6, NCF5 = 0x7, CLOSE = 0x8, PING = 0x9, PONG = 0xA, // Reserved for further control frames (RFC 6455) CF1 = 0xB, CF2 = 0xC, CF3 = 0xD, INCOMPLETE = 0xE, // Reserved for further control frames (RFC 6455) CF4 = 0xF, }; enum ParseResult { OK, Incomplete, Error }; bool final : 1; bool rsv1 : 1; bool rsv2 : 1; bool rsv3 : 1; Type opcode : 4; bool masked : 1; unsigned short length : 7; unsigned short extended : 16; char *payload; bool IsControl(); bool IsNonControl(); bool IsReserved(); bool Extended(); static ParseResult Parse(char *data, size_t length, Frame &target, const char *end, std::string reason); Frame(); Frame(Type opcode, bool final, bool masked, const char *payload, size_t length); void MakeData(std::vector<char> &data); }; } #endif<commit_msg>Removed extra definitions.<commit_after>#ifndef __FRAME_HPP__ #define __FRAME_HPP__ #include "include/global.hpp" #include <string> #include <vector> #define MAX_PAYLOAD_LENGTH 0x7FFFFFFFFFFFFFFF; typedef unsigned int FrameMask; namespace ws { struct Frame { static const byte FinalBit = 0x80; static const byte ReservedBit1 = 0x40; // Compress Extension static const byte ReservedBit2 = 0x20; static const byte ReservedBit3 = 0x10; static const byte TypeMask = 0x0F; static const byte MaskBit = 0x80; static const byte PayloadLengthMask = 0x7F; static const int FrameMinSize = 2; static const int MaskKeySize = 4; static const int PayloadSizeDefault = 125; static const int PayloadSizeExtraWord = 126; static const int PayloadSizeExtraQWord = 127; // RFC 6455 OpCodes enum Type { CONTINIUATION = 0x0, TEXT = 0x1, BINARY = 0x2, // Reserved for further non-control Frames (RFC 6455) NCF1 = 0x3, NCF2 = 0x4, NCF3 = 0x5, NCF4 = 0x6, NCF5 = 0x7, CLOSE = 0x8, PING = 0x9, PONG = 0xA, // Reserved for further control frames (RFC 6455) CF1 = 0xB, CF2 = 0xC, CF3 = 0xD, INCOMPLETE = 0xE, // Reserved for further control frames (RFC 6455) CF4 = 0xF, }; enum ParseResult { OK, Incomplete, Error }; bool final : 1; bool rsv1 : 1; bool rsv2 : 1; bool rsv3 : 1; Type opcode : 4; bool masked : 1; unsigned short length : 7; unsigned short extended : 16; char *payload; bool IsControl(); bool IsNonControl(); bool IsReserved(); bool Extended(); static ParseResult Parse(char *data, size_t length, Frame &target, const char *end, std::string reason); Frame(); Frame(Type opcode, bool final, bool masked, const char *payload, size_t length); void MakeData(std::vector<char> &data); }; } #endif<|endoftext|>
<commit_before><commit_msg>mds: path_traverse cleanup<commit_after><|endoftext|>
<commit_before>/* Ping.cpp - Implementation of the pinger component Copyright 2006 Jens Georg Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** @file */ #include <winsock2.h> #ifndef IP_TTL # include <ws2tcpip.h> #endif #include <windows.h> #include <process.h> #include <iphlpapi.h> #include <errno.h> #include <string> #include <iostream> #include "IcmpPacket.h" #include "IpPacket.h" #include "PingException.h" #include "Ping.h" CPing::CPing( const HWND hMessageWindow, const char* c_pszHost, const bool c_bResolveAddress, const unsigned int c_uTimeout, const unsigned int c_uSleep, const unsigned int c_uUnreachableThreshold, const unsigned int c_lBufferSize, const unsigned int c_uTtl) throw(CPingException): m_ulInetAddr(0L), m_pszHost(NULL), m_uBufferSize(c_lBufferSize), m_uTtl(c_uTtl), m_uUnreachableThreshold(c_uUnreachableThreshold), m_uTimeout(c_uTimeout), m_hMessageWindow(hMessageWindow), m_bDownSignalled(false), m_uFailedPings(0), m_uSleep(c_uSleep), m_uSequenceNumber(0), m_sd(INVALID_SOCKET) { struct hostent* pHostInfo = NULL; // try to convert the host address into a inet address m_ulInetAddr = inet_addr(c_pszHost); if (INADDR_NONE == m_ulInetAddr) { // we assume this is a hostname, not an ip pHostInfo = gethostbyname(c_pszHost); if (NULL == pHostInfo) { throw CPingException("Could not resolve hostname"); } else { m_pszHost = new char[strlen(c_pszHost) + 1]; memset(m_pszHost, 0, strlen(c_pszHost) + 1); memcpy(m_pszHost, c_pszHost, strlen(c_pszHost)); memcpy(&(m_saDest.sin_addr), pHostInfo->h_addr, pHostInfo->h_length); m_saDest.sin_family = pHostInfo->h_addrtype; } } else { // fill inet address for destination m_saDest.sin_addr.s_addr = m_ulInetAddr; m_saDest.sin_family = AF_INET; if (c_bResolveAddress) { pHostInfo = gethostbyaddr((char *)&m_ulInetAddr, 4, AF_INET); if (NULL != pHostInfo) { m_pszHost = new char[strlen(pHostInfo->h_name) + 1]; memset(m_pszHost, 0, strlen(pHostInfo->h_name) + 1); memcpy(m_pszHost, pHostInfo->h_name, strlen(pHostInfo->h_name)); } else { m_pszHost = new char[strlen(c_pszHost) + 1]; memset(m_pszHost, 0, strlen(c_pszHost) + 1); memcpy(m_pszHost, c_pszHost, strlen(c_pszHost)); } } else { m_pszHost = new char[strlen(c_pszHost) + 1]; memset(m_pszHost, 0, strlen(c_pszHost) + 1); memcpy(m_pszHost, c_pszHost, strlen(c_pszHost)); } } createSocket(); m_hEvent = CreateEvent(NULL, TRUE, FALSE, "PingCancel event"); m_pReplyBuffer = new char[IpPacket::MAX_PACKET_SIZE]; memset(m_pReplyBuffer, 0, IpPacket::MAX_PACKET_SIZE); } void CPing::start() { // todo: check for successful thread creation m_hThread = (HANDLE)_beginthreadex(NULL, 0, CPing::threadFunc, this, 0, &m_uThreadId); if (0 == m_hThread) { // failed to create thread // check what exactly failed switch (errno) { case EAGAIN: // too many threads OutputDebugString("Could not spawn ping thread. To many open threads"); // throw exception break; case EINVAL: OutputDebugString("Could not spawn ping thread. Invalid argument or stack size"); break; default: break; } } } void CPing::stop() { // todo: mutex for m_hEvent SetEvent(m_hEvent); } unsigned int __stdcall CPing::threadFunc(void *pParam) { CPing *pInstance = reinterpret_cast<CPing *>(pParam); if (isValidInstance(pInstance)) { pInstance->pingThread(); } return 0; } bool CPing::isValidInstance(const CPing* pInstance) { return true; } CPing::~CPing() { if (m_sd != INVALID_SOCKET) { closesocket(m_sd); m_sd = INVALID_SOCKET; } long lResult; // wait for ping thread to end lResult = WaitForSingleObject(m_hThread, INFINITE); switch (lResult) { case WAIT_OBJECT_0: // all fine break; case WAIT_FAILED: OutputDebugString("Waiting for ping thread to finish failed."); break; } CloseHandle(m_hEvent); delete [] m_pReplyBuffer; // free host name if (m_pszHost != NULL) { delete [] m_pszHost; m_pszHost = NULL; } } void CPing::createSocket() throw(CPingException) { int nResult = 0; // create raw socket m_sd = WSASocket(AF_INET, SOCK_RAW, IPPROTO_ICMP, 0,0,0); if (INVALID_SOCKET == m_sd) { char buf[255] = {0}; sprintf(buf, "%ld", GetLastError()); OutputDebugString(buf); throw CPingException("Could not create raw socket. Are you Administrator?"); } // set TTL of socket nResult = setsockopt(m_sd, IPPROTO_IP, IP_TTL, (const char *)&m_uTtl, sizeof(m_uTtl)); if (SOCKET_ERROR == nResult) { throw CPingException(std::string("Could not set TTL of socket.")); } } void CPing::pingThread() { long lResult; bool bLeave = false; // have a first checkup of the host if (!ping()) { fireDown(); m_bDownSignalled = true; } while (!bLeave) { lResult = WaitForSingleObject(m_hEvent, m_uSleep); switch (lResult) { case WAIT_TIMEOUT: // Check if host is reachable if (ping()) { OutputDebugString("Up\r\n"); if (m_bDownSignalled) { fireUp(); m_bDownSignalled = false; } m_uFailedPings = 0; } else { OutputDebugString("Down\r\n"); m_uFailedPings++; if (m_uFailedPings > m_uUnreachableThreshold && !m_bDownSignalled) { fireDown(); m_bDownSignalled = true; } } break; default: bLeave = true; } } ResetEvent(m_hEvent); m_uSequenceNumber = 0; } bool CPing::ping() { int nResult = SOCKET_ERROR; TIMEVAL tvTimeout = {0}; fd_set fds = {0}; tvTimeout.tv_usec = m_uTimeout * 1000; FD_ZERO(&fds); FD_SET(m_sd, &fds); sockaddr_in sa; //ip_header* pIpHeader; IcmpPacket* response = NULL; IpPacket* responsePacket = NULL; // copy dest address, routers overwrite it on DEST_UNREACHABLE memcpy(&sa, &m_saDest, sizeof(m_saDest)); IcmpPacket packet(GetCurrentProcessId(), ++m_uSequenceNumber, m_uBufferSize); nResult = sendto(m_sd, packet.rawData(), packet.getSize(), 0, (const sockaddr *)&m_saDest, sizeof(m_saDest)); if (SOCKET_ERROR == nResult) { nResult = WSAGetLastError(); return false; } do { nResult = select(1, &fds, NULL, NULL, &tvTimeout); OutputDebugString("After select\r\n"); if (nResult != 1) { return false; } int size = sizeof(m_saDest); nResult = recvfrom(m_sd, (char *)m_pReplyBuffer, IpPacket::MAX_PACKET_SIZE, 0, (sockaddr *)&sa, &size); OutputDebugString("After recvfrom\r\n"); if (SOCKET_ERROR == nResult) { nResult = WSAGetLastError(); return false; } if (responsePacket != NULL) { delete responsePacket; } responsePacket = new IpPacket(m_pReplyBuffer, nResult); //pIpHeader = (ip_header *) m_pReplyBuffer; if (response != NULL) { delete response; } //response = new IcmpPacket((m_pReplyBuffer + pIpHeader->h_len * 4), pIpHeader->total_length - (pIpHeader->h_len * 4)); response = new IcmpPacket(responsePacket->getPayload(), responsePacket->getPayloadSize()); // check sequence number } while (response->getSequenceNumber() != m_uSequenceNumber); // check length if (response->getType() != IcmpPacket::ICMP_TYPE_ECHO_REPLY) { delete response; OutputDebugString("Answer is not ECHO_REPLY"); return false; } if (response->getId() != GetCurrentProcessId()) { delete response; OutputDebugString("Answer is not for us"); return false; } delete response; return true; } void CPing::fireUp() { ::PostMessage(m_hMessageWindow, CPing::PING_HOST_UP, (LPARAM)this, 0); } void CPing::fireDown() { ::PostMessage(m_hMessageWindow, CPing::PING_HOST_DOWN, (LPARAM)this, 0); } <commit_msg>remove regular debug outputs<commit_after>/* Ping.cpp - Implementation of the pinger component Copyright 2006 Jens Georg Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** @file */ #include <winsock2.h> #ifndef IP_TTL # include <ws2tcpip.h> #endif #include <windows.h> #include <process.h> #include <iphlpapi.h> #include <errno.h> #include <string> #include <iostream> #include "IcmpPacket.h" #include "IpPacket.h" #include "PingException.h" #include "Ping.h" CPing::CPing( const HWND hMessageWindow, const char* c_pszHost, const bool c_bResolveAddress, const unsigned int c_uTimeout, const unsigned int c_uSleep, const unsigned int c_uUnreachableThreshold, const unsigned int c_lBufferSize, const unsigned int c_uTtl) throw(CPingException): m_ulInetAddr(0L), m_pszHost(NULL), m_uBufferSize(c_lBufferSize), m_uTtl(c_uTtl), m_uUnreachableThreshold(c_uUnreachableThreshold), m_uTimeout(c_uTimeout), m_hMessageWindow(hMessageWindow), m_bDownSignalled(false), m_uFailedPings(0), m_uSleep(c_uSleep), m_uSequenceNumber(0), m_sd(INVALID_SOCKET) { struct hostent* pHostInfo = NULL; // try to convert the host address into a inet address m_ulInetAddr = inet_addr(c_pszHost); if (INADDR_NONE == m_ulInetAddr) { // we assume this is a hostname, not an ip pHostInfo = gethostbyname(c_pszHost); if (NULL == pHostInfo) { throw CPingException("Could not resolve hostname"); } else { m_pszHost = new char[strlen(c_pszHost) + 1]; memset(m_pszHost, 0, strlen(c_pszHost) + 1); memcpy(m_pszHost, c_pszHost, strlen(c_pszHost)); memcpy(&(m_saDest.sin_addr), pHostInfo->h_addr, pHostInfo->h_length); m_saDest.sin_family = pHostInfo->h_addrtype; } } else { // fill inet address for destination m_saDest.sin_addr.s_addr = m_ulInetAddr; m_saDest.sin_family = AF_INET; if (c_bResolveAddress) { pHostInfo = gethostbyaddr((char *)&m_ulInetAddr, 4, AF_INET); if (NULL != pHostInfo) { m_pszHost = new char[strlen(pHostInfo->h_name) + 1]; memset(m_pszHost, 0, strlen(pHostInfo->h_name) + 1); memcpy(m_pszHost, pHostInfo->h_name, strlen(pHostInfo->h_name)); } else { m_pszHost = new char[strlen(c_pszHost) + 1]; memset(m_pszHost, 0, strlen(c_pszHost) + 1); memcpy(m_pszHost, c_pszHost, strlen(c_pszHost)); } } else { m_pszHost = new char[strlen(c_pszHost) + 1]; memset(m_pszHost, 0, strlen(c_pszHost) + 1); memcpy(m_pszHost, c_pszHost, strlen(c_pszHost)); } } createSocket(); m_hEvent = CreateEvent(NULL, TRUE, FALSE, "PingCancel event"); m_pReplyBuffer = new char[IpPacket::MAX_PACKET_SIZE]; memset(m_pReplyBuffer, 0, IpPacket::MAX_PACKET_SIZE); } void CPing::start() { // todo: check for successful thread creation m_hThread = (HANDLE)_beginthreadex(NULL, 0, CPing::threadFunc, this, 0, &m_uThreadId); if (0 == m_hThread) { // failed to create thread // check what exactly failed switch (errno) { case EAGAIN: // too many threads OutputDebugString("Could not spawn ping thread. To many open threads"); // throw exception break; case EINVAL: OutputDebugString("Could not spawn ping thread. Invalid argument or stack size"); break; default: break; } } } void CPing::stop() { // todo: mutex for m_hEvent SetEvent(m_hEvent); } unsigned int __stdcall CPing::threadFunc(void *pParam) { CPing *pInstance = reinterpret_cast<CPing *>(pParam); if (isValidInstance(pInstance)) { pInstance->pingThread(); } return 0; } bool CPing::isValidInstance(const CPing* pInstance) { return true; } CPing::~CPing() { if (m_sd != INVALID_SOCKET) { closesocket(m_sd); m_sd = INVALID_SOCKET; } long lResult; // wait for ping thread to end lResult = WaitForSingleObject(m_hThread, INFINITE); switch (lResult) { case WAIT_OBJECT_0: // all fine break; case WAIT_FAILED: OutputDebugString("Waiting for ping thread to finish failed."); break; } CloseHandle(m_hEvent); delete [] m_pReplyBuffer; // free host name if (m_pszHost != NULL) { delete [] m_pszHost; m_pszHost = NULL; } } void CPing::createSocket() throw(CPingException) { int nResult = 0; // create raw socket m_sd = WSASocket(AF_INET, SOCK_RAW, IPPROTO_ICMP, 0,0,0); if (INVALID_SOCKET == m_sd) { char buf[255] = {0}; sprintf(buf, "%ld", GetLastError()); OutputDebugString(buf); throw CPingException("Could not create raw socket. Are you Administrator?"); } // set TTL of socket nResult = setsockopt(m_sd, IPPROTO_IP, IP_TTL, (const char *)&m_uTtl, sizeof(m_uTtl)); if (SOCKET_ERROR == nResult) { throw CPingException(std::string("Could not set TTL of socket.")); } } void CPing::pingThread() { long lResult; bool bLeave = false; // have a first checkup of the host if (!ping()) { fireDown(); m_bDownSignalled = true; } while (!bLeave) { lResult = WaitForSingleObject(m_hEvent, m_uSleep); switch (lResult) { case WAIT_TIMEOUT: // Check if host is reachable if (ping()) { //OutputDebugString("Up\r\n"); if (m_bDownSignalled) { fireUp(); m_bDownSignalled = false; } m_uFailedPings = 0; } else { //OutputDebugString("Down\r\n"); m_uFailedPings++; if (m_uFailedPings > m_uUnreachableThreshold && !m_bDownSignalled) { fireDown(); m_bDownSignalled = true; } } break; default: bLeave = true; } } ResetEvent(m_hEvent); m_uSequenceNumber = 0; } bool CPing::ping() { int nResult = SOCKET_ERROR; TIMEVAL tvTimeout = {0}; fd_set fds = {0}; tvTimeout.tv_usec = m_uTimeout * 1000; FD_ZERO(&fds); FD_SET(m_sd, &fds); sockaddr_in sa; //ip_header* pIpHeader; IcmpPacket* response = NULL; IpPacket* responsePacket = NULL; // copy dest address, routers overwrite it on DEST_UNREACHABLE memcpy(&sa, &m_saDest, sizeof(m_saDest)); IcmpPacket packet(GetCurrentProcessId(), ++m_uSequenceNumber, m_uBufferSize); nResult = sendto(m_sd, packet.rawData(), packet.getSize(), 0, (const sockaddr *)&m_saDest, sizeof(m_saDest)); if (SOCKET_ERROR == nResult) { nResult = WSAGetLastError(); return false; } do { nResult = select(1, &fds, NULL, NULL, &tvTimeout); if (nResult != 1) { char buf[255] = {0}; sprintf(buf, "Select failed with error: %d", nResult); OutputDebugString(buf); return false; } int size = sizeof(m_saDest); nResult = recvfrom(m_sd, (char *)m_pReplyBuffer, IpPacket::MAX_PACKET_SIZE, 0, (sockaddr *)&sa, &size); //OutputDebugString("After recvfrom\r\n"); if (SOCKET_ERROR == nResult) { nResult = WSAGetLastError(); return false; } if (responsePacket != NULL) { delete responsePacket; } responsePacket = new IpPacket(m_pReplyBuffer, nResult); if (response != NULL) { delete response; } response = new IcmpPacket(responsePacket->getPayload(), responsePacket->getPayloadSize()); // check sequence number } while (response->getSequenceNumber() != m_uSequenceNumber); // check length if (response->getType() != IcmpPacket::ICMP_TYPE_ECHO_REPLY) { delete response; OutputDebugString("Answer is not ECHO_REPLY"); return false; } if (response->getId() != GetCurrentProcessId()) { delete response; OutputDebugString("Answer is not for us"); return false; } delete response; return true; } void CPing::fireUp() { ::PostMessage(m_hMessageWindow, CPing::PING_HOST_UP, (LPARAM)this, 0); } void CPing::fireDown() { ::PostMessage(m_hMessageWindow, CPing::PING_HOST_DOWN, (LPARAM)this, 0); } <|endoftext|>
<commit_before> #include "Globals.h" class MockChest; typedef cItemCallback<MockChest> cChestCallback; AString ItemToFullString(const cItem & a_Item) { return ""; } class cEntity { public: const Vector3d & GetPosition (void) const { return m_pos;} double GetWidth (void) const { return 0; } double GetHeight (void) const { return 0; } static const Vector3d m_pos; }; const Vector3d cEntity::m_pos = Vector3d(0,0,0); class cItem { public: cItem(BLOCKTYPE val) {} }; void cBlockInfo::Initialize(cBlockInfoArray & a_Info) {} cBlockInfo::~cBlockInfo () {} #include "Blocks/ChunkInterface.h" bool cChunkInterface::ForEachChunkInRect(int a_MinChunkX, int a_MaxChunkX, int a_MinChunkZ, int a_MaxChunkZ, cChunkDataCallback & a_Callback) { return false; } bool cChunkInterface::WriteBlockArea(cBlockArea & a_Area, int a_MinBlockX, int a_MinBlockY, int a_MinBlockZ, int a_DataTypes) { return false; } #include "Simulator/Simulator.inc" #include "Simulator/IncrementalRedstoneSimulator.inc" class MockWorld; class MockHandler { public: static eBlockFace MetadataToDirection(NIBBLETYPE a_MetaData) { return BLOCK_FACE_NONE; } static eBlockFace MetaDataToDirection(NIBBLETYPE a_MetaData) { return BLOCK_FACE_NONE; } static eBlockFace BlockMetaDataToBlockFace(NIBBLETYPE a_MetaData) { return BLOCK_FACE_NONE; } static NIBBLETYPE IsOpen(cChunkInterface & a_ChunkInterface, int a_BlockX, int a_BlockY, int a_BlockZ) { return 0; } static void ExtendPiston(int a_BlockX, int a_BlockY, int a_BlockZ, MockWorld * a_World) {} static void RetractPiston(int a_BlockX, int a_BlockY, int a_BlockZ, MockWorld * a_World) {} static void SetOpen(cChunkInterface & a_ChunkInterface, int a_BlockX, int a_BlockY, int a_BlockZ, bool a_Open) {} }; template<unsigned char val> class MockHandlerFetcher { public: typedef MockHandler type; }; class MockWorld { public: bool IsChunkLighted(int a_ChunkX, int a_ChunkZ) { return false; } bool ForEachEntityInChunk(int a_ChunkX, int a_ChunkZ, cEntityCallback & a_Callback) { return false; } void QueueLightChunk(int a_ChunkX, int a_ChunkZ, cChunkCoordCallback * a_Callback = NULL) {} NIBBLETYPE GetBlockSkyLight (int a_BlockX, int a_BlockY, int a_BlockZ) { return 0; } cPlayer * FindClosestPlayer(const Vector3d & a_Pos, float a_SightLimit, bool a_CheckLineOfSight = true) { return NULL; } void WakeUpSimulators(int a_BlockX, int a_BlockY, int a_BlockZ) {} void SpawnPrimedTNT(double a_X, double a_Y, double a_Z, int a_FuseTimeInSec = 80, double a_InitialVelocityCoeff = 1) {} bool SetTrapdoorOpen(int a_BlockX, int a_BlockY, int a_BlockZ, bool a_Open) {return false; } cChunkMap * GetChunkMap (void) { return NULL; } }; class MockChunk { public: cRedstoneSimulatorChunkData * GetRedstoneSimulatorData() { return NULL; } bool IsRedstoneDirty() { return true; } void SetIsRedstoneDirty(bool a_Param) {} void GetBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta) {} void SetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, bool a_SendToClients = true) {} void SetBlock( const Vector3i & a_RelBlockPos, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) {} int GetPosX(void) const { return 0; } int GetPosZ(void) const { return 0; } MockChunk * GetRelNeighborChunkAdjustCoords(int & a_RelX, int & a_RelZ) const { return NULL; } BLOCKTYPE GetBlock(int a_RelX, int a_RelY, int a_RelZ) const { return 0; } BLOCKTYPE GetBlock(const Vector3i & a_RelCoords) const { return 0; } NIBBLETYPE GetMeta(int a_RelX, int a_RelY, int a_RelZ) const { return 0; } void SetMeta(int a_RelX, int a_RelY, int a_RelZ, NIBBLETYPE a_Meta) {} bool UnboundedRelGetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta) const { return false; } bool UnboundedRelGetBlockType(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType) const { return false; } MockChunk * GetNeighborChunk(int a_BlockX, int a_BlockZ) { return NULL; } MockChunk * GetRelNeighborChunk(int a_RelX, int a_RelZ) { return NULL; } bool IsValid(void) const { return false; } NIBBLETYPE GetTimeAlteredLight(NIBBLETYPE a_Skylight) const { return 0; } void BroadcastSoundParticleEffect(int a_EffectID, int a_SrcX, int a_SrcY, int a_SrcZ, int a_Data, const cClientHandle * a_Exclude = NULL) {} void BroadcastSoundEffect (const AString & a_SoundName, double a_X, double a_Y, double a_Z, float a_Volume, float a_Pitch, const cClientHandle * a_Exclude = NULL) {} bool DoWithRedstonePoweredEntityAt(int a_BlockX, int a_BlockY, int a_BlockZ, cRedstonePoweredCallback & a_Callback) { return false; } template <class T> bool DoWithChestAt(int a_BlockX, int a_BlockY, int a_BlockZ, T & a_Callback) { return false; } }; class MockChest { public: BLOCKTYPE GetBlockType(void) const { return 0; } int GetNumberOfPlayers(void) const { return 0; } }; int main(int argc, char** argv) { MockWorld World; cIncrementalRedstoneSimulator<MockChunk, MockWorld, MockHandlerFetcher, MockChest> Simulator(World); return 0; } <commit_msg>Update creatable.cpp<commit_after> #include "Globals.h" class MockChest; typedef cItemCallback<MockChest> cChestCallback; AString ItemToFullString(const cItem & a_Item) { return ""; } class cEntity { public: const Vector3d & GetPosition (void) const { return m_pos;} double GetWidth (void) const { return 0; } double GetHeight (void) const { return 0; } static const Vector3d m_pos; }; const Vector3d cEntity::m_pos = Vector3d(0,0,0); class cItem { public: cItem(BLOCKTYPE val) {} }; void cBlockInfo::Initialize(cBlockInfoArray & a_Info) {} cBlockInfo::~cBlockInfo () {} #include "Blocks/ChunkInterface.h" bool cChunkInterface::ForEachChunkInRect(int a_MinChunkX, int a_MaxChunkX, int a_MinChunkZ, int a_MaxChunkZ, cChunkDataCallback & a_Callback) { return false; } bool cChunkInterface::WriteBlockArea(cBlockArea & a_Area, int a_MinBlockX, int a_MinBlockY, int a_MinBlockZ, int a_DataTypes) { return false; } #include "Simulator/Simulator.inc" #include "Simulator/IncrementalRedstoneSimulator.inc" class MockWorld; class MockHandler { public: static eBlockFace MetadataToDirection(NIBBLETYPE a_MetaData) { return BLOCK_FACE_NONE; } static eBlockFace MetaDataToDirection(NIBBLETYPE a_MetaData) { return BLOCK_FACE_NONE; } static eBlockFace BlockMetaDataToBlockFace(NIBBLETYPE a_MetaData) { return BLOCK_FACE_NONE; } static NIBBLETYPE IsOpen(cChunkInterface & a_ChunkInterface, int a_BlockX, int a_BlockY, int a_BlockZ) { return 0; } static void ExtendPiston(int a_BlockX, int a_BlockY, int a_BlockZ, MockWorld * a_World) {} static void RetractPiston(int a_BlockX, int a_BlockY, int a_BlockZ, MockWorld * a_World) {} static void SetOpen(cChunkInterface & a_ChunkInterface, int a_BlockX, int a_BlockY, int a_BlockZ, bool a_Open) {} }; template<unsigned char val> class MockHandlerFetcher { public: typedef MockHandler type; }; class MockWorld { public: bool IsChunkLighted(int a_ChunkX, int a_ChunkZ) { return false; } bool ForEachEntityInChunk(int a_ChunkX, int a_ChunkZ, cEntityCallback & a_Callback) { return false; } void QueueLightChunk(int a_ChunkX, int a_ChunkZ, cChunkCoordCallback * a_Callback = NULL) {} NIBBLETYPE GetBlockSkyLight (int a_BlockX, int a_BlockY, int a_BlockZ) { return 0; } cPlayer * FindClosestPlayer(const Vector3d & a_Pos, float a_SightLimit, bool a_CheckLineOfSight = true) { return NULL; } void WakeUpSimulators(int a_BlockX, int a_BlockY, int a_BlockZ) {} void SpawnPrimedTNT(double a_X, double a_Y, double a_Z, int a_FuseTimeInSec = 80, double a_InitialVelocityCoeff = 1) {} bool SetTrapdoorOpen(int a_BlockX, int a_BlockY, int a_BlockZ, bool a_Open) {return false; } cChunkMap * GetChunkMap (void) { return NULL; } }; class MockChunk { public: cRedstoneSimulatorChunkData * GetRedstoneSimulatorData() { return NULL; } void SetRedstoneSimulatorData(cRedstoneSimulatorChunkData * a_Data) {} bool IsRedstoneDirty() { return true; } void SetIsRedstoneDirty(bool a_Param) {} void GetBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta) {} void SetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, bool a_SendToClients = true) {} void SetBlock( const Vector3i & a_RelBlockPos, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) {} int GetPosX(void) const { return 0; } int GetPosZ(void) const { return 0; } MockChunk * GetRelNeighborChunkAdjustCoords(int & a_RelX, int & a_RelZ) const { return NULL; } BLOCKTYPE GetBlock(int a_RelX, int a_RelY, int a_RelZ) const { return 0; } BLOCKTYPE GetBlock(const Vector3i & a_RelCoords) const { return 0; } NIBBLETYPE GetMeta(int a_RelX, int a_RelY, int a_RelZ) const { return 0; } void SetMeta(int a_RelX, int a_RelY, int a_RelZ, NIBBLETYPE a_Meta) {} bool UnboundedRelGetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta) const { return false; } bool UnboundedRelGetBlockType(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType) const { return false; } MockChunk * GetNeighborChunk(int a_BlockX, int a_BlockZ) { return NULL; } MockChunk * GetRelNeighborChunk(int a_RelX, int a_RelZ) { return NULL; } bool IsValid(void) const { return false; } NIBBLETYPE GetTimeAlteredLight(NIBBLETYPE a_Skylight) const { return 0; } void BroadcastSoundParticleEffect(int a_EffectID, int a_SrcX, int a_SrcY, int a_SrcZ, int a_Data, const cClientHandle * a_Exclude = NULL) {} void BroadcastSoundEffect (const AString & a_SoundName, double a_X, double a_Y, double a_Z, float a_Volume, float a_Pitch, const cClientHandle * a_Exclude = NULL) {} bool DoWithRedstonePoweredEntityAt(int a_BlockX, int a_BlockY, int a_BlockZ, cRedstonePoweredCallback & a_Callback) { return false; } template <class T> bool DoWithChestAt(int a_BlockX, int a_BlockY, int a_BlockZ, T & a_Callback) { return false; } }; class MockChest { public: BLOCKTYPE GetBlockType(void) const { return 0; } int GetNumberOfPlayers(void) const { return 0; } }; int main(int argc, char** argv) { MockWorld World; cIncrementalRedstoneSimulator<MockChunk, MockWorld, MockHandlerFetcher, MockChest> Simulator(World); return 0; } <|endoftext|>
<commit_before>/* The OpenTRV project licenses this file to you under the Apache Licence, Version 2.0 (the "Licence"); you may not use this file except in compliance with the Licence. You may obtain a copy of the Licence at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licence for the specific language governing permissions and limitations under the Licence. Author(s) / Copyright (s): Damon Hart-Davis 2016 Deniz Erbilgin 2016 */ /* * Driver and sanity test for portable C++ unit tests for this library. */ #include <stdint.h> #include <gtest/gtest.h> #include <utility/OTV0P2BASE_Util.h> // Sanity test. TEST(SanityTest,SelfTest) { EXPECT_EQ(42, 42); fputs("Built at: " __DATE__ " " __TIME__, stderr); } //// Minimally test a real library function. //TEST(SanityTest,ShouldConvertFromHex) //{ // const char s[] = "0a"; // // This works. It's inline and only in the header. // EXPECT_EQ(10, OTV0P2BASE::parseHexDigit(s[1])); // // The compiler can't find this for some reason (function def in source file). // EXPECT_EQ(10, OTV0P2BASE::parseHexByte(s)); //} /** * @brief Getting started with the gtest libraries. * @note - Add the following to Project>Properties>C/C++ Build>Settings>GCC G++ linker>Libraries (-l): * - gtest * - gtest_main * - pthread * - Select Google Testing in Run>Run Configuration>C/C++ Unit Test>testTest>C/C++ Testing and click Apply then Run * - Saved the test config */ /** * See also: https://github.com/google/googletest/blob/master/googletest/docs/Primer.md */ <commit_msg>TODO-996: more clear build time message<commit_after>/* The OpenTRV project licenses this file to you under the Apache Licence, Version 2.0 (the "Licence"); you may not use this file except in compliance with the Licence. You may obtain a copy of the Licence at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licence for the specific language governing permissions and limitations under the Licence. Author(s) / Copyright (s): Damon Hart-Davis 2016 Deniz Erbilgin 2016 */ /* * Driver and sanity test for portable C++ unit tests for this library. */ #include <stdint.h> #include <gtest/gtest.h> #include <utility/OTV0P2BASE_Util.h> // Sanity test. TEST(SanityTest,SelfTest) { EXPECT_EQ(42, 42); fputs("*** Tests built: " __DATE__ " " __TIME__ "\n", stderr); } //// Minimally test a real library function. //TEST(SanityTest,ShouldConvertFromHex) //{ // const char s[] = "0a"; // // This works. It's inline and only in the header. // EXPECT_EQ(10, OTV0P2BASE::parseHexDigit(s[1])); // // The compiler can't find this for some reason (function def in source file). // EXPECT_EQ(10, OTV0P2BASE::parseHexByte(s)); //} /** * @brief Getting started with the gtest libraries. * @note - Add the following to Project>Properties>C/C++ Build>Settings>GCC G++ linker>Libraries (-l): * - gtest * - gtest_main * - pthread * - Select Google Testing in Run>Run Configuration>C/C++ Unit Test>testTest>C/C++ Testing and click Apply then Run * - Saved the test config */ /** * See also: https://github.com/google/googletest/blob/master/googletest/docs/Primer.md */ <|endoftext|>
<commit_before>// Copyright (c) 2012 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 <map> #include <set> #include "build/build_config.h" // Need to include this before most other files because it defines // IPC_MESSAGE_LOG_ENABLED. We need to use it to define // IPC_MESSAGE_MACROS_LOG_ENABLED so ppapi_messages.h will generate the // ViewMsgLog et al. functions. #include "base/message_loop.h" #include "base/synchronization/waitable_event.h" #include "base/threading/thread.h" #include "ipc/ipc_channel_handle.h" #include "ipc/ipc_logging.h" #include "ipc/ipc_message.h" #include "native_client/src/shared/ppapi_proxy/ppruntime.h" #include "native_client/src/shared/srpc/nacl_srpc.h" #include "native_client/src/untrusted/irt/irt_ppapi.h" #include "ppapi/c/ppp.h" #include "ppapi/c/ppp_instance.h" #include "ppapi/proxy/plugin_dispatcher.h" #include "ppapi/proxy/plugin_globals.h" #include "ppapi/proxy/plugin_proxy_delegate.h" #include "ppapi/shared_impl/ppb_audio_shared.h" #if defined(IPC_MESSAGE_LOG_ENABLED) #define IPC_MESSAGE_MACROS_LOG_ENABLED #endif #include "ppapi/proxy/ppapi_messages.h" // This must match up with NACL_CHROME_INITIAL_IPC_DESC, // defined in sel_main_chrome.h #define NACL_IPC_FD 6 using ppapi::proxy::PluginDispatcher; using ppapi::proxy::PluginGlobals; using ppapi::proxy::PluginProxyDelegate; using ppapi::proxy::ProxyChannel; using ppapi::proxy::SerializedHandle; namespace { // This class manages communication between the plugin and the browser, and // manages the PluginDispatcher instances for communication between the plugin // and the renderer. class PpapiDispatcher : public ProxyChannel, public PluginDispatcher::PluginDelegate, public PluginProxyDelegate { public: explicit PpapiDispatcher(scoped_refptr<base::MessageLoopProxy> io_loop); // PluginDispatcher::PluginDelegate implementation. virtual base::MessageLoopProxy* GetIPCMessageLoop() OVERRIDE; virtual base::WaitableEvent* GetShutdownEvent() OVERRIDE; virtual IPC::PlatformFileForTransit ShareHandleWithRemote( base::PlatformFile handle, const IPC::SyncChannel& channel, bool should_close_source) OVERRIDE; virtual std::set<PP_Instance>* GetGloballySeenInstanceIDSet() OVERRIDE; virtual uint32 Register(PluginDispatcher* plugin_dispatcher) OVERRIDE; virtual void Unregister(uint32 plugin_dispatcher_id) OVERRIDE; // PluginProxyDelegate implementation. virtual bool SendToBrowser(IPC::Message* msg) OVERRIDE; virtual IPC::Sender* GetBrowserSender() OVERRIDE; virtual std::string GetUILanguage() OVERRIDE; virtual void PreCacheFont(const void* logfontw) OVERRIDE; virtual void SetActiveURL(const std::string& url) OVERRIDE; // IPC::Listener implementation. virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE; private: void OnMsgCreateNaClChannel(int renderer_id, const ppapi::PpapiPermissions& permissions, bool incognito, SerializedHandle handle); void OnPluginDispatcherMessageReceived(const IPC::Message& msg); std::set<PP_Instance> instances_; std::map<uint32, PluginDispatcher*> plugin_dispatchers_; uint32 next_plugin_dispatcher_id_; scoped_refptr<base::MessageLoopProxy> message_loop_; base::WaitableEvent shutdown_event_; }; PpapiDispatcher::PpapiDispatcher(scoped_refptr<base::MessageLoopProxy> io_loop) : message_loop_(io_loop), shutdown_event_(true, false) { IPC::ChannelHandle channel_handle( "NaCl IPC", base::FileDescriptor(NACL_IPC_FD, false)); InitWithChannel(this, channel_handle, false); // Channel is server. } base::MessageLoopProxy* PpapiDispatcher::GetIPCMessageLoop() { return message_loop_.get(); } base::WaitableEvent* PpapiDispatcher::GetShutdownEvent() { return &shutdown_event_; } IPC::PlatformFileForTransit PpapiDispatcher::ShareHandleWithRemote( base::PlatformFile handle, const IPC::SyncChannel& channel, bool should_close_source) { return IPC::InvalidPlatformFileForTransit(); } std::set<PP_Instance>* PpapiDispatcher::GetGloballySeenInstanceIDSet() { return &instances_; } uint32 PpapiDispatcher::Register(PluginDispatcher* plugin_dispatcher) { if (!plugin_dispatcher || plugin_dispatchers_.size() >= std::numeric_limits<uint32>::max()) { return 0; } uint32 id = 0; do { // Although it is unlikely, make sure that we won't cause any trouble // when the counter overflows. id = next_plugin_dispatcher_id_++; } while (id == 0 || plugin_dispatchers_.find(id) != plugin_dispatchers_.end()); plugin_dispatchers_[id] = plugin_dispatcher; return id; } void PpapiDispatcher::Unregister(uint32 plugin_dispatcher_id) { plugin_dispatchers_.erase(plugin_dispatcher_id); } bool PpapiDispatcher::SendToBrowser(IPC::Message* msg) { return Send(msg); } IPC::Sender* PpapiDispatcher::GetBrowserSender() { return this; } std::string PpapiDispatcher::GetUILanguage() { NOTIMPLEMENTED(); return std::string(); } void PpapiDispatcher::PreCacheFont(const void* logfontw) { NOTIMPLEMENTED(); } void PpapiDispatcher::SetActiveURL(const std::string& url) { NOTIMPLEMENTED(); } bool PpapiDispatcher::OnMessageReceived(const IPC::Message& msg) { IPC_BEGIN_MESSAGE_MAP(PpapiDispatcher, msg) IPC_MESSAGE_HANDLER(PpapiMsg_CreateNaClChannel, OnMsgCreateNaClChannel) IPC_MESSAGE_HANDLER_GENERIC(PpapiMsg_PPBTCPServerSocket_ListenACK, OnPluginDispatcherMessageReceived(msg)) IPC_MESSAGE_HANDLER_GENERIC(PpapiMsg_PPBTCPServerSocket_AcceptACK, OnPluginDispatcherMessageReceived(msg)) IPC_MESSAGE_HANDLER_GENERIC(PpapiMsg_PPBTCPSocket_ConnectACK, OnPluginDispatcherMessageReceived(msg)) IPC_MESSAGE_HANDLER_GENERIC(PpapiMsg_PPBTCPSocket_SSLHandshakeACK, OnPluginDispatcherMessageReceived(msg)) IPC_MESSAGE_HANDLER_GENERIC(PpapiMsg_PPBTCPSocket_ReadACK, OnPluginDispatcherMessageReceived(msg)) IPC_MESSAGE_HANDLER_GENERIC(PpapiMsg_PPBTCPSocket_WriteACK, OnPluginDispatcherMessageReceived(msg)) IPC_MESSAGE_HANDLER_GENERIC(PpapiMsg_PPBUDPSocket_RecvFromACK, OnPluginDispatcherMessageReceived(msg)) IPC_MESSAGE_HANDLER_GENERIC(PpapiMsg_PPBUDPSocket_SendToACK, OnPluginDispatcherMessageReceived(msg)) IPC_MESSAGE_HANDLER_GENERIC(PpapiMsg_PPBUDPSocket_BindACK, OnPluginDispatcherMessageReceived(msg)) IPC_END_MESSAGE_MAP() return true; } void PpapiDispatcher::OnMsgCreateNaClChannel( int renderer_id, const ppapi::PpapiPermissions& permissions, bool incognito, SerializedHandle handle) { // Tell the process-global GetInterface which interfaces it can return to the // plugin. ppapi::proxy::InterfaceList::SetProcessGlobalPermissions( permissions); PluginDispatcher* dispatcher = new PluginDispatcher(::PPP_GetInterface, permissions, incognito); // The channel handle's true name is not revealed here. IPC::ChannelHandle channel_handle("nacl", handle.descriptor()); if (!dispatcher->InitPluginWithChannel(this, channel_handle, false)) { delete dispatcher; return; } // From here, the dispatcher will manage its own lifetime according to the // lifetime of the attached channel. } void PpapiDispatcher::OnPluginDispatcherMessageReceived( const IPC::Message& msg) { // The first parameter should be a plugin dispatcher ID. PickleIterator iter(msg); uint32 id = 0; if (!msg.ReadUInt32(&iter, &id)) { NOTREACHED(); return; } std::map<uint32, ppapi::proxy::PluginDispatcher*>::iterator dispatcher = plugin_dispatchers_.find(id); if (dispatcher != plugin_dispatchers_.end()) dispatcher->second->OnMessageReceived(msg); } } // namespace void PpapiPluginRegisterThreadCreator( const struct PP_ThreadFunctions* thread_functions) { // Initialize all classes that need to create threads that call back into // user code. ppapi::PPB_Audio_Shared::SetThreadFunctions(thread_functions); } int IrtInit() { static int initialized = 0; if (initialized) { return 0; } if (!NaClSrpcModuleInit()) { return 1; } initialized = 1; return 0; } int PpapiPluginMain() { base::AtExitManager exit_manager; MessageLoop loop; IPC::Logging::set_log_function_map(&g_log_function_mapping); ppapi::proxy::PluginGlobals plugin_globals; base::Thread io_thread("Chrome_NaClIOThread"); base::Thread::Options options; options.message_loop_type = MessageLoop::TYPE_IO; io_thread.StartWithOptions(options); // Start up the SRPC server on another thread. Otherwise, when it blocks // on an RPC, the PPAPI proxy will hang. Do this before we initialize the // module and start the PPAPI proxy so that the NaCl plugin can continue // loading the app. static struct NaClSrpcHandlerDesc srpc_methods[] = { { NULL, NULL } }; if (!NaClSrpcAcceptClientOnThread(srpc_methods)) { return 1; } int32_t error = ::PPP_InitializeModule( 0 /* module */, &ppapi::proxy::PluginDispatcher::GetBrowserInterface); // TODO(dmichael): Handle other error conditions, like failure to connect? if (error) return error; PpapiDispatcher ppapi_dispatcher(io_thread.message_loop_proxy()); plugin_globals.set_plugin_proxy_delegate(&ppapi_dispatcher); loop.Run(); NaClSrpcModuleFini(); return 0; } <commit_msg>[Coverity] Fix uninitialized scalar field.<commit_after>// Copyright (c) 2012 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 <map> #include <set> #include "build/build_config.h" // Need to include this before most other files because it defines // IPC_MESSAGE_LOG_ENABLED. We need to use it to define // IPC_MESSAGE_MACROS_LOG_ENABLED so ppapi_messages.h will generate the // ViewMsgLog et al. functions. #include "base/message_loop.h" #include "base/synchronization/waitable_event.h" #include "base/threading/thread.h" #include "ipc/ipc_channel_handle.h" #include "ipc/ipc_logging.h" #include "ipc/ipc_message.h" #include "native_client/src/shared/ppapi_proxy/ppruntime.h" #include "native_client/src/shared/srpc/nacl_srpc.h" #include "native_client/src/untrusted/irt/irt_ppapi.h" #include "ppapi/c/ppp.h" #include "ppapi/c/ppp_instance.h" #include "ppapi/proxy/plugin_dispatcher.h" #include "ppapi/proxy/plugin_globals.h" #include "ppapi/proxy/plugin_proxy_delegate.h" #include "ppapi/shared_impl/ppb_audio_shared.h" #if defined(IPC_MESSAGE_LOG_ENABLED) #define IPC_MESSAGE_MACROS_LOG_ENABLED #endif #include "ppapi/proxy/ppapi_messages.h" // This must match up with NACL_CHROME_INITIAL_IPC_DESC, // defined in sel_main_chrome.h #define NACL_IPC_FD 6 using ppapi::proxy::PluginDispatcher; using ppapi::proxy::PluginGlobals; using ppapi::proxy::PluginProxyDelegate; using ppapi::proxy::ProxyChannel; using ppapi::proxy::SerializedHandle; namespace { // This class manages communication between the plugin and the browser, and // manages the PluginDispatcher instances for communication between the plugin // and the renderer. class PpapiDispatcher : public ProxyChannel, public PluginDispatcher::PluginDelegate, public PluginProxyDelegate { public: explicit PpapiDispatcher(scoped_refptr<base::MessageLoopProxy> io_loop); // PluginDispatcher::PluginDelegate implementation. virtual base::MessageLoopProxy* GetIPCMessageLoop() OVERRIDE; virtual base::WaitableEvent* GetShutdownEvent() OVERRIDE; virtual IPC::PlatformFileForTransit ShareHandleWithRemote( base::PlatformFile handle, const IPC::SyncChannel& channel, bool should_close_source) OVERRIDE; virtual std::set<PP_Instance>* GetGloballySeenInstanceIDSet() OVERRIDE; virtual uint32 Register(PluginDispatcher* plugin_dispatcher) OVERRIDE; virtual void Unregister(uint32 plugin_dispatcher_id) OVERRIDE; // PluginProxyDelegate implementation. virtual bool SendToBrowser(IPC::Message* msg) OVERRIDE; virtual IPC::Sender* GetBrowserSender() OVERRIDE; virtual std::string GetUILanguage() OVERRIDE; virtual void PreCacheFont(const void* logfontw) OVERRIDE; virtual void SetActiveURL(const std::string& url) OVERRIDE; // IPC::Listener implementation. virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE; private: void OnMsgCreateNaClChannel(int renderer_id, const ppapi::PpapiPermissions& permissions, bool incognito, SerializedHandle handle); void OnPluginDispatcherMessageReceived(const IPC::Message& msg); std::set<PP_Instance> instances_; std::map<uint32, PluginDispatcher*> plugin_dispatchers_; uint32 next_plugin_dispatcher_id_; scoped_refptr<base::MessageLoopProxy> message_loop_; base::WaitableEvent shutdown_event_; }; PpapiDispatcher::PpapiDispatcher(scoped_refptr<base::MessageLoopProxy> io_loop) : next_plugin_dispatcher_id_(0), message_loop_(io_loop), shutdown_event_(true, false) { IPC::ChannelHandle channel_handle( "NaCl IPC", base::FileDescriptor(NACL_IPC_FD, false)); InitWithChannel(this, channel_handle, false); // Channel is server. } base::MessageLoopProxy* PpapiDispatcher::GetIPCMessageLoop() { return message_loop_.get(); } base::WaitableEvent* PpapiDispatcher::GetShutdownEvent() { return &shutdown_event_; } IPC::PlatformFileForTransit PpapiDispatcher::ShareHandleWithRemote( base::PlatformFile handle, const IPC::SyncChannel& channel, bool should_close_source) { return IPC::InvalidPlatformFileForTransit(); } std::set<PP_Instance>* PpapiDispatcher::GetGloballySeenInstanceIDSet() { return &instances_; } uint32 PpapiDispatcher::Register(PluginDispatcher* plugin_dispatcher) { if (!plugin_dispatcher || plugin_dispatchers_.size() >= std::numeric_limits<uint32>::max()) { return 0; } uint32 id = 0; do { // Although it is unlikely, make sure that we won't cause any trouble // when the counter overflows. id = next_plugin_dispatcher_id_++; } while (id == 0 || plugin_dispatchers_.find(id) != plugin_dispatchers_.end()); plugin_dispatchers_[id] = plugin_dispatcher; return id; } void PpapiDispatcher::Unregister(uint32 plugin_dispatcher_id) { plugin_dispatchers_.erase(plugin_dispatcher_id); } bool PpapiDispatcher::SendToBrowser(IPC::Message* msg) { return Send(msg); } IPC::Sender* PpapiDispatcher::GetBrowserSender() { return this; } std::string PpapiDispatcher::GetUILanguage() { NOTIMPLEMENTED(); return std::string(); } void PpapiDispatcher::PreCacheFont(const void* logfontw) { NOTIMPLEMENTED(); } void PpapiDispatcher::SetActiveURL(const std::string& url) { NOTIMPLEMENTED(); } bool PpapiDispatcher::OnMessageReceived(const IPC::Message& msg) { IPC_BEGIN_MESSAGE_MAP(PpapiDispatcher, msg) IPC_MESSAGE_HANDLER(PpapiMsg_CreateNaClChannel, OnMsgCreateNaClChannel) IPC_MESSAGE_HANDLER_GENERIC(PpapiMsg_PPBTCPServerSocket_ListenACK, OnPluginDispatcherMessageReceived(msg)) IPC_MESSAGE_HANDLER_GENERIC(PpapiMsg_PPBTCPServerSocket_AcceptACK, OnPluginDispatcherMessageReceived(msg)) IPC_MESSAGE_HANDLER_GENERIC(PpapiMsg_PPBTCPSocket_ConnectACK, OnPluginDispatcherMessageReceived(msg)) IPC_MESSAGE_HANDLER_GENERIC(PpapiMsg_PPBTCPSocket_SSLHandshakeACK, OnPluginDispatcherMessageReceived(msg)) IPC_MESSAGE_HANDLER_GENERIC(PpapiMsg_PPBTCPSocket_ReadACK, OnPluginDispatcherMessageReceived(msg)) IPC_MESSAGE_HANDLER_GENERIC(PpapiMsg_PPBTCPSocket_WriteACK, OnPluginDispatcherMessageReceived(msg)) IPC_MESSAGE_HANDLER_GENERIC(PpapiMsg_PPBUDPSocket_RecvFromACK, OnPluginDispatcherMessageReceived(msg)) IPC_MESSAGE_HANDLER_GENERIC(PpapiMsg_PPBUDPSocket_SendToACK, OnPluginDispatcherMessageReceived(msg)) IPC_MESSAGE_HANDLER_GENERIC(PpapiMsg_PPBUDPSocket_BindACK, OnPluginDispatcherMessageReceived(msg)) IPC_END_MESSAGE_MAP() return true; } void PpapiDispatcher::OnMsgCreateNaClChannel( int renderer_id, const ppapi::PpapiPermissions& permissions, bool incognito, SerializedHandle handle) { // Tell the process-global GetInterface which interfaces it can return to the // plugin. ppapi::proxy::InterfaceList::SetProcessGlobalPermissions( permissions); PluginDispatcher* dispatcher = new PluginDispatcher(::PPP_GetInterface, permissions, incognito); // The channel handle's true name is not revealed here. IPC::ChannelHandle channel_handle("nacl", handle.descriptor()); if (!dispatcher->InitPluginWithChannel(this, channel_handle, false)) { delete dispatcher; return; } // From here, the dispatcher will manage its own lifetime according to the // lifetime of the attached channel. } void PpapiDispatcher::OnPluginDispatcherMessageReceived( const IPC::Message& msg) { // The first parameter should be a plugin dispatcher ID. PickleIterator iter(msg); uint32 id = 0; if (!msg.ReadUInt32(&iter, &id)) { NOTREACHED(); return; } std::map<uint32, ppapi::proxy::PluginDispatcher*>::iterator dispatcher = plugin_dispatchers_.find(id); if (dispatcher != plugin_dispatchers_.end()) dispatcher->second->OnMessageReceived(msg); } } // namespace void PpapiPluginRegisterThreadCreator( const struct PP_ThreadFunctions* thread_functions) { // Initialize all classes that need to create threads that call back into // user code. ppapi::PPB_Audio_Shared::SetThreadFunctions(thread_functions); } int IrtInit() { static int initialized = 0; if (initialized) { return 0; } if (!NaClSrpcModuleInit()) { return 1; } initialized = 1; return 0; } int PpapiPluginMain() { base::AtExitManager exit_manager; MessageLoop loop; IPC::Logging::set_log_function_map(&g_log_function_mapping); ppapi::proxy::PluginGlobals plugin_globals; base::Thread io_thread("Chrome_NaClIOThread"); base::Thread::Options options; options.message_loop_type = MessageLoop::TYPE_IO; io_thread.StartWithOptions(options); // Start up the SRPC server on another thread. Otherwise, when it blocks // on an RPC, the PPAPI proxy will hang. Do this before we initialize the // module and start the PPAPI proxy so that the NaCl plugin can continue // loading the app. static struct NaClSrpcHandlerDesc srpc_methods[] = { { NULL, NULL } }; if (!NaClSrpcAcceptClientOnThread(srpc_methods)) { return 1; } int32_t error = ::PPP_InitializeModule( 0 /* module */, &ppapi::proxy::PluginDispatcher::GetBrowserInterface); // TODO(dmichael): Handle other error conditions, like failure to connect? if (error) return error; PpapiDispatcher ppapi_dispatcher(io_thread.message_loop_proxy()); plugin_globals.set_plugin_proxy_delegate(&ppapi_dispatcher); loop.Run(); NaClSrpcModuleFini(); return 0; } <|endoftext|>
<commit_before>/*------------MD.cpp----------------------------------------------------------// * * MD.cpp -- a simple event-driven MD simulation * * Purpose: Figure out the pressure on the interior of a box based on * Boltzmann's theory and stuff * * Notes: This simulation will predominantly follow the logic of the link in * the README file * *-----------------------------------------------------------------------------*/ #include <iostream> #include <vector> #include <fstream> #include <random> //#include <algorithm> namespace sim{ /* putting our stuff in its own namespace so we can call "time" "time" without colliding with names from the standard library */ using time = double; } /*----------------------------------------------------------------------------// * STRUCTS AND FUNCTIONS *-----------------------------------------------------------------------------*/ // Holds our data in a central struct, to be called mainly in a vector struct Particle{ int PID; sim::time ts; double pos_x, pos_y, pos_z, vel_x, vel_y, vel_z; }; // holds interaction data struct Interaction{ sim::time rtime; int part1, part2; }; // Makes starting data std::vector<Particle> populate(int pnum, double box_length, double max_vel); // Makes the list for our simulation later, required starting data std::vector<Interaction> make_list(const std::vector<Particle> &curr_data, double box_length, double radius); // This performs our MD simulation with a vector of interactions // Also writes simulation to file, specified by README void simulate(std::vector<int> interactions, std::vector<Particle> curr_data); /*----------------------------------------------------------------------------// * MAIN *-----------------------------------------------------------------------------*/ int main(void){ int pnum = 100; double box_length = 10, max_vel = 0.01; std::vector<Particle> curr_data = populate(pnum, box_length, max_vel); for (auto &p : curr_data){ std::cout << p.pos_x << std::endl; } return 0; } /*----------------------------------------------------------------------------// * SUBROUTINES *-----------------------------------------------------------------------------*/ // Makes starting data std::vector<Particle> populate(int pnum, double box_length, double max_vel){ std::vector<Particle> curr_data(pnum); // static to create only 1 random_device static std::random_device rd; static std::mt19937 gen(rd()); /* instead of doing % and * to get the correct distribution we directly specify which distribution we want */ std::uniform_real_distribution<double> box_length_distribution(0, box_length); std::uniform_real_distribution<double> max_vel_distribution(0, max_vel); int PID_counter = 0; for (auto &p : curr_data){ //read: for all particles p in curr_data p.ts = 0; p.PID = PID_counter++; for (auto &pos : { &p.pos_x, &p.pos_y, &p.pos_z }) *pos = box_length_distribution(gen); for (auto &vel : { &p.vel_x, &p.vel_y, &p.vel_z }) *vel = max_vel_distribution(gen); } return curr_data; } // Makes the list for our simulation later, required starting data // Step 1: Check interactions between Particles, based on README link // Step 2: Update list. // Step 3: Sort list, lowest first std::vector<Interaction> make_list(const std::vector<Particle> &curr_data, double box_length, double radius){ /* passing curr_data as const reference to avoid the copy and accidental overwriting */ std::vector<Interaction> list; Interaction test; int i = 0,j = 0; double del_x, del_y, del_z, del_vx, del_vy, del_vz, r_prime, rad_d; // Step 1 -- find interactions for (auto &ip : curr_data){ for (auto &jp : curr_data){ del_x = ip.pos_x - jp.pos_x; del_y = ip.pos_y - jp.pos_y; del_z = ip.pos_z - jp.pos_y; del_vx = ip.vel_x - jp.vel_y; del_vy = ip.vel_y - jp.vel_y; del_vz = ip.vel_z - jp.vel_z; r_prime = 2 * radius; rad_d = (pow(del_vx * del_x + del_vy * del_y + del_vz * del_z, 2) - 4 * (del_vx * del_vx + del_vy * del_vy + del_vz * del_vz) * (del_x * del_x + del_y * del_y + del_z * del_z - r_prime * r_prime)); sim::time check; if (del_x * del_vx >= 0 && del_y * del_vy >= 0 && del_z * del_vz >= 0){ check = 0; } else if (rad_d > 0){ check = 0; } else { check = (-(del_vx * del_x + del_vy * del_y + del_vz * del_z) + sqrt(rad_d)) / (2 * (del_vx * del_vx + del_vz * del_vz + del_vy * del_vy)); } // Step 2 -- update list if (check != 0){ test.rtime = check; test.part1 = i; test.part2 = j; list.push_back(test); } j++; } i++; } // Step 3 -- sort the list /* // std::sort() vector <Interaction> dummy; for (auto &ele : list){ } std::sort(std::begin(vec), std::end(vec), [](const Particle &lhs, const Particle &rhs){ return lhs.ts < rhs.ts; }); */ return list; } // This performs our MD simulation with a vector of interactions // Also writes simulation to file, specified by README // Note: Time-loop here void simulate(std::vector<int> interactions, std::vector<Particle> curr_data){ } <commit_msg>fixed an error produsing NaN's. Sorry about that! ^^' I will be doing the sorting as soon as I can. Thanks Harha for already submitting!<commit_after>/*------------MD.cpp----------------------------------------------------------// * * MD.cpp -- a simple event-driven MD simulation * * Purpose: Figure out the pressure on the interior of a box based on * Boltzmann's theory and stuff * * Notes: This simulation will predominantly follow the logic of the link in * the README file * *-----------------------------------------------------------------------------*/ #include <iostream> #include <vector> #include <fstream> #include <random> //#include <algorithm> namespace sim{ /* putting our stuff in its own namespace so we can call "time" "time" without colliding with names from the standard library */ using time = double; } /*----------------------------------------------------------------------------// * STRUCTS AND FUNCTIONS *-----------------------------------------------------------------------------*/ // Holds our data in a central struct, to be called mainly in a vector struct Particle{ int PID; sim::time ts; double pos_x, pos_y, pos_z, vel_x, vel_y, vel_z; }; // holds interaction data struct Interaction{ sim::time rtime; int part1, part2; }; // Makes starting data std::vector<Particle> populate(int pnum, double box_length, double max_vel); // Makes the list for our simulation later, required starting data std::vector<Interaction> make_list(const std::vector<Particle> &curr_data, double box_length, double radius); // This performs our MD simulation with a vector of interactions // Also writes simulation to file, specified by README void simulate(std::vector<int> interactions, std::vector<Particle> curr_data); /*----------------------------------------------------------------------------// * MAIN *-----------------------------------------------------------------------------*/ int main(void){ int pnum = 1000; double box_length = 10, max_vel = 0.01; std::vector<Particle> curr_data = populate(pnum, box_length, max_vel); for (auto &p : curr_data){ std::cout << p.pos_x << std::endl; } std::vector<Interaction> list = make_list(curr_data, box_length,0.1); std::cout << std::endl << std::endl; for (auto &it : list){ std::cout << it.rtime << std::endl; } return 0; } /*----------------------------------------------------------------------------// * SUBROUTINES *-----------------------------------------------------------------------------*/ // Makes starting data std::vector<Particle> populate(int pnum, double box_length, double max_vel){ std::vector<Particle> curr_data(pnum); // static to create only 1 random_device static std::random_device rd; static std::mt19937 gen(rd()); /* instead of doing % and * to get the correct distribution we directly specify which distribution we want */ std::uniform_real_distribution<double> box_length_distribution(0, box_length); std::uniform_real_distribution<double> max_vel_distribution(0, max_vel); int PID_counter = 0; for (auto &p : curr_data){ //read: for all particles p in curr_data p.ts = 0; p.PID = PID_counter++; for (auto &pos : { &p.pos_x, &p.pos_y, &p.pos_z }) *pos = box_length_distribution(gen); for (auto &vel : { &p.vel_x, &p.vel_y, &p.vel_z }) *vel = max_vel_distribution(gen); } return curr_data; } // Makes the list for our simulation later, required starting data // Step 1: Check interactions between Particles, based on README link // Step 2: Update list. // Step 3: Sort list, lowest first std::vector<Interaction> make_list(const std::vector<Particle> &curr_data, double box_length, double radius){ /* passing curr_data as const reference to avoid the copy and accidental overwriting */ std::vector<Interaction> list; Interaction test; int i = 0,j = 0; double del_x, del_y, del_z, del_vx, del_vy, del_vz, r_tot, rad_d; // Step 1 -- find interactions for (auto &ip : curr_data){ for (auto &jp : curr_data){ if (i != j){ del_x = ip.pos_x - jp.pos_x; del_y = ip.pos_y - jp.pos_y; del_z = ip.pos_z - jp.pos_y; del_vx = ip.vel_x - jp.vel_y; del_vy = ip.vel_y - jp.vel_y; del_vz = ip.vel_z - jp.vel_z; r_tot = 2 * radius; rad_d = (pow(del_vx*del_x + del_vy*del_y + del_vz*del_z, 2) - 4 * (del_vx*del_vx + del_vy*del_vy + del_vz*del_vz) * (del_x*del_x + del_y*del_y + del_z*del_z - r_tot*r_tot)); sim::time check; if (del_x * del_vx >= 0 && del_y * del_vy >= 0 && del_z * del_vz >= 0){ check = 0; } // NaN error here! Sorry about that ^^ else if (rad_d < 0){ check = 0; } else { check = (-(del_vx*del_x + del_vy*del_y + del_vz*del_z) + sqrt(rad_d)) / (2 * (del_vx*del_vx + del_vz*del_vz + del_vy*del_vy)); + del_vy*del_vy)); } // Step 2 -- update list if (check != 0){ std::cout << "found one!" << std::endl; test.rtime = check; test.part1 = i; test.part2 = j; list.push_back(test); } } j++; } i++; } // Step 3 -- sort the list TODO return list; } // This performs our MD simulation with a vector of interactions // Also writes simulation to file, specified by README // Note: Time-loop here void simulate(std::vector<int> interactions, std::vector<Particle> curr_data){ } <|endoftext|>
<commit_before> #include <scene.h> /// global to keep persistence over instances of scene // Grid* Scene::grid_ = NULL; Scene::Scene(const ros::NodeHandle& node) : Ped::Tscene(), nh_(node) { // start the time steps timestep = 0; /// setup the list of all agents and the robot agent all_agents_.clear(); // setup services and publishers pub_all_agents_ = nh_.advertise<pedsim_msgs::AllAgentsState>("AllAgentsStatus", 0); pub_agent_visuals_ = nh_.advertise<visualization_msgs::Marker>( "visualization_marker", 0 ); srv_move_agent_ = nh_.advertiseService("SetAgentState", &Scene::srvMoveAgentHandler, this); } bool Scene::srvMoveAgentHandler(pedsim_srvs::SetAgentState::Request& req, pedsim_srvs::SetAgentState::Response& res) { pedsim_msgs::AgentState state = req.state; ROS_INFO("Rceived (%f) (%f)", state.position.x, state.position.y); if (robot_->getid() == state.id) { robot_->setPosition(state.position.x*20.0, state.position.y*20.0, state.position.z*20.0 ); // robot_->setPosition(state.position.y*20.0, state.position.x*20.0, state.position.z*20.0 ); robot_->setvx(state.velocity.x); robot_->setvy(state.velocity.y); moveAgent(robot_); } res.finished = true; return true; } void Scene::cleanupSlot() { cleanup(); } void Scene::clear() { foreach(Agent* agent, agents) delete agent; agents.clear(); all_agents_.clear(); foreach(Waypoint* waypoint, waypoints) delete waypoint; waypoints.clear(); foreach(Obstacle* obs, obstacles) delete obs; obstacles.clear(); } void Scene::runSimulation() { ros::Rate r(20); while (ros::ok()) { moveAllAgents(); publicAgentStatus(); publishAgentVisuals(); ros::spinOnce(); r.sleep(); } } void Scene::moveAllAgents() { all_agents_ = getAllAgents(); for (vector<Ped::Tagent*>::const_iterator iter = all_agents_.begin(); iter != all_agents_.end(); ++iter) { Ped::Tagent *a = (*iter); if (a->gettype() == 2) robot_ = a; } timestep++; // move the agents by social force Ped::Tscene::moveAgents(CONFIG.simh); } void Scene::publicAgentStatus() { pedsim_msgs::AllAgentsState all_status; all_status.header.stamp = ros::Time::now(); for (vector<Ped::Tagent*>::const_iterator iter = all_agents_.begin(); iter != all_agents_.end(); ++iter) { Ped::Tagent *a = (*iter); pedsim_msgs::AgentState state; state.header.stamp = ros::Time::now(); state.id = a->getid(); state.position.x = a->getx() * (1/20.0); state.position.y = a->gety() * (1/20.0); state.position.z = a->getz() * (1/20.0); state.velocity.x = a->getvx(); state.velocity.y = a->getvy(); state.velocity.z = a->getvz(); all_status.agent_states.push_back(state); } pub_all_agents_.publish(all_status); } void Scene::publishAgentVisuals() { for (vector<Ped::Tagent*>::const_iterator iter = all_agents_.begin(); iter != all_agents_.end(); ++iter) { Ped::Tagent *a = (*iter); visualization_msgs::Marker marker; marker.header.frame_id = "pedsim_base"; marker.header.stamp = ros::Time(); marker.ns = "pedsim"; marker.id = a->getid(); if (a->gettype() == robot_->gettype()) { // marker.type = visualization_msgs::Marker::CUBE; marker.type = visualization_msgs::Marker::MESH_RESOURCE; marker.mesh_resource = "package://simulator/images/darylbot.dae"; marker.color.a = 1.0; marker.color.r = 1.0; marker.color.g = 1.0; marker.color.b = 1.0; marker.scale.x = 0.5; marker.scale.y = 0.5; marker.scale.z = 0.5; } else { marker.type = visualization_msgs::Marker::CYLINDER; marker.color.a = 1.0; marker.color.r = 0.0; marker.color.g = 1.0; marker.color.b = 0.0; marker.scale.x = 0.2; marker.scale.y = 0.2; marker.scale.z = 1; } marker.action = 0; // add or modify marker.pose.position.x = a->getx() * (1/20.0); marker.pose.position.y = a->gety() * (1/20.0); marker.pose.position.z = 0; marker.pose.orientation.x = 0.0; marker.pose.orientation.y = 0.0; marker.pose.orientation.z = 0.0; marker.pose.orientation.w = 1.0; pub_agent_visuals_.publish( marker ); } } std::set<const Ped::Tagent*> Scene::getNeighbors(double x, double y, double maxDist) { std::set<const Ped::Tagent*> potentialNeighbours = Ped::Tscene::getNeighbors(x, y, maxDist); // filter according to euclidean distance auto agentIter = potentialNeighbours.begin(); while(agentIter != potentialNeighbours.end()) { double aX = (*agentIter)->getx(); double aY = (*agentIter)->gety(); double distance = sqrt((x-aX)*(x-aX) + (y-aY)*(y-aY)); // remove distant neighbors if(distance > maxDist) { potentialNeighbours.erase(agentIter++); } else { ++agentIter; } } return potentialNeighbours; } bool Scene::readFromFile(const QString& filename) { // ROS_INFO("Loading scenario file '%s'.", filename.toStdString); // open file QFile file(filename); if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) { // ERROR_LOG("Couldn't open scenario file!"); return false; } // read input while(!file.atEnd()) { QByteArray line = file.readLine(); processData(line); } // report success return true; } /// Called for each line in the file /// \date 2012-02-03 void Scene::processData(QByteArray& data) { xmlReader.addData(data); CONFIG.obstacle_positions.clear(); while(!xmlReader.atEnd()) { xmlReader.readNext(); if(xmlReader.isStartElement()) { if((xmlReader.name() == "scenario") || (xmlReader.name() == "welcome")) { // nothing to do } else if(xmlReader.name() == "obstacle") { double x1 = xmlReader.attributes().value("x1").toString().toDouble(); double y1 = xmlReader.attributes().value("y1").toString().toDouble(); double x2 = xmlReader.attributes().value("x2").toString().toDouble(); double y2 = xmlReader.attributes().value("y2").toString().toDouble(); Obstacle* obs = new Obstacle(x1, y1, x2, y2); this->addObstacle(obs); // drawObstacles(x1, y1, x2, y2); } else if(xmlReader.name() == "waypoint") { // TODO - add an explicit waypoint type QString id = xmlReader.attributes().value("id").toString(); double x = xmlReader.attributes().value("x").toString().toDouble(); double y = xmlReader.attributes().value("y").toString().toDouble(); double r = xmlReader.attributes().value("r").toString().toDouble(); Waypoint* w = new Waypoint(id, x, y, r); // if (boost::starts_with(id, "start")) { // w->setType(Ped::Twaypoint::TYPE_BIRTH); // std::cout << "adding a birth waypoint" << std::endl; // } // if (boost::starts_with(id, "stop")) { // w->setType(Ped::Twaypoint::TYPE_DEATH); // std::cout << "adding a death waypoint" << std::endl; // } this->waypoints[id] = w; } else if(xmlReader.name() == "agent") { double x = xmlReader.attributes().value("x").toString().toDouble(); double y = xmlReader.attributes().value("y").toString().toDouble(); int n = xmlReader.attributes().value("n").toString().toDouble(); double dx = xmlReader.attributes().value("dx").toString().toDouble(); double dy = xmlReader.attributes().value("dy").toString().toDouble(); double type = xmlReader.attributes().value("type").toString().toInt(); //TODO: keep agent group and expand later!? for (int i=0; i<n; i++) { Agent* a = new Agent(); double randomizedX = x; double randomizedY = y; // handle dx=0 or dy=0 cases //TODO: qrand() actually needs to be seeded to create different runs if(dx != 0) randomizedX += qrand()/(double)RAND_MAX * dx - dx/2; if(dy != 0) randomizedY += qrand()/(double)RAND_MAX * dy - dy/2; a->setPosition(randomizedX, randomizedY); a->setType(type); this->addAgent(a); currentAgents.append(a); } } else if(xmlReader.name() == "addwaypoint") { QString id = xmlReader.attributes().value("id").toString(); // add waypoints to current agents, not just those of the current <agent> element foreach(Agent* a, currentAgents) a->addWaypoint(this->waypoints[id]); } else { // inform the user about invalid elements // ROS_WARN("Unknown element: %s", xmlReader.name().toString()); } } else if(xmlReader.isEndElement()) { if (xmlReader.name() == "agent") { currentAgents.clear(); } } } } int main(int argc, char** argv) { // initialize resources ros::init(argc, argv, "simulator"); ROS_INFO("node initialized"); ros::NodeHandle node; Scene sim_scene(node); ROS_INFO("Simulation scene started"); // load parameters std::string scene_file_param; node.getParam("/simulator/scene_file", scene_file_param); double cell_size; node.getParam("/simulator/cell_size", cell_size); CONFIG.width = cell_size; CONFIG.height = cell_size; // load scenario file QString scenefile = QString::fromStdString(scene_file_param); if (!sim_scene.readFromFile(scenefile)) { ROS_WARN("Could not load the scene file, check paths"); } ROS_INFO("loaded parameters"); sim_scene.runSimulation(); // ScenarioReader scenarioReader(scene); return 0; } <commit_msg>avoid looping over all agents at every time step<commit_after> #include <scene.h> /// global to keep persistence over instances of scene // Grid* Scene::grid_ = NULL; Scene::Scene(const ros::NodeHandle& node) : Ped::Tscene(), nh_(node) { // start the time steps timestep = 0; /// setup the list of all agents and the robot agent all_agents_.clear(); // setup services and publishers pub_all_agents_ = nh_.advertise<pedsim_msgs::AllAgentsState>("AllAgentsStatus", 0); pub_agent_visuals_ = nh_.advertise<visualization_msgs::Marker>( "visualization_marker", 0 ); srv_move_agent_ = nh_.advertiseService("SetAgentState", &Scene::srvMoveAgentHandler, this); } bool Scene::srvMoveAgentHandler(pedsim_srvs::SetAgentState::Request& req, pedsim_srvs::SetAgentState::Response& res) { pedsim_msgs::AgentState state = req.state; ROS_INFO("Rceived (%f) (%f)", state.position.x, state.position.y); if (robot_->getid() == state.id) { robot_->setPosition(state.position.x*20.0, state.position.y*20.0, state.position.z*20.0 ); // robot_->setPosition(state.position.y*20.0, state.position.x*20.0, state.position.z*20.0 ); robot_->setvx(state.velocity.x); robot_->setvy(state.velocity.y); moveAgent(robot_); } res.finished = true; return true; } void Scene::cleanupSlot() { cleanup(); } void Scene::clear() { foreach(Agent* agent, agents) delete agent; agents.clear(); all_agents_.clear(); foreach(Waypoint* waypoint, waypoints) delete waypoint; waypoints.clear(); foreach(Obstacle* obs, obstacles) delete obs; obstacles.clear(); } void Scene::runSimulation() { /// setup the agents and the robot all_agents_ = getAllAgents(); for (vector<Ped::Tagent*>::const_iterator iter = all_agents_.begin(); iter != all_agents_.end(); ++iter) { Ped::Tagent *a = (*iter); if (a->gettype() == 2) robot_ = a; } ros::Rate r(20); while (ros::ok()) { moveAllAgents(); publicAgentStatus(); publishAgentVisuals(); ros::spinOnce(); r.sleep(); } } void Scene::moveAllAgents() { timestep++; // move the agents by social force Ped::Tscene::moveAgents(CONFIG.simh); } void Scene::publicAgentStatus() { pedsim_msgs::AllAgentsState all_status; all_status.header.stamp = ros::Time::now(); for (vector<Ped::Tagent*>::const_iterator iter = all_agents_.begin(); iter != all_agents_.end(); ++iter) { Ped::Tagent *a = (*iter); pedsim_msgs::AgentState state; state.header.stamp = ros::Time::now(); state.id = a->getid(); state.position.x = a->getx() * (1/20.0); state.position.y = a->gety() * (1/20.0); state.position.z = a->getz() * (1/20.0); state.velocity.x = a->getvx(); state.velocity.y = a->getvy(); state.velocity.z = a->getvz(); all_status.agent_states.push_back(state); } pub_all_agents_.publish(all_status); } void Scene::publishAgentVisuals() { for (vector<Ped::Tagent*>::const_iterator iter = all_agents_.begin(); iter != all_agents_.end(); ++iter) { Ped::Tagent *a = (*iter); visualization_msgs::Marker marker; marker.header.frame_id = "pedsim_base"; marker.header.stamp = ros::Time(); marker.ns = "pedsim"; marker.id = a->getid(); if (a->gettype() == robot_->gettype()) { // marker.type = visualization_msgs::Marker::CUBE; marker.type = visualization_msgs::Marker::MESH_RESOURCE; marker.mesh_resource = "package://simulator/images/darylbot.dae"; marker.color.a = 1.0; marker.color.r = 1.0; marker.color.g = 1.0; marker.color.b = 1.0; marker.scale.x = 0.5; marker.scale.y = 0.5; marker.scale.z = 0.5; } else { marker.type = visualization_msgs::Marker::CYLINDER; marker.color.a = 1.0; marker.color.r = 0.0; marker.color.g = 1.0; marker.color.b = 0.0; marker.scale.x = 0.2; marker.scale.y = 0.2; marker.scale.z = 1; } marker.action = 0; // add or modify marker.pose.position.x = a->getx() * (1/20.0); marker.pose.position.y = a->gety() * (1/20.0); marker.pose.position.z = 0; marker.pose.orientation.x = 0.0; marker.pose.orientation.y = 0.0; marker.pose.orientation.z = 0.0; marker.pose.orientation.w = 1.0; pub_agent_visuals_.publish( marker ); } } std::set<const Ped::Tagent*> Scene::getNeighbors(double x, double y, double maxDist) { std::set<const Ped::Tagent*> potentialNeighbours = Ped::Tscene::getNeighbors(x, y, maxDist); // filter according to euclidean distance auto agentIter = potentialNeighbours.begin(); while(agentIter != potentialNeighbours.end()) { double aX = (*agentIter)->getx(); double aY = (*agentIter)->gety(); double distance = sqrt((x-aX)*(x-aX) + (y-aY)*(y-aY)); // remove distant neighbors if(distance > maxDist) { potentialNeighbours.erase(agentIter++); } else { ++agentIter; } } return potentialNeighbours; } bool Scene::readFromFile(const QString& filename) { // ROS_INFO("Loading scenario file '%s'.", filename.toStdString); // open file QFile file(filename); if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) { // ERROR_LOG("Couldn't open scenario file!"); return false; } // read input while(!file.atEnd()) { QByteArray line = file.readLine(); processData(line); } // report success return true; } /// Called for each line in the file void Scene::processData(QByteArray& data) { xmlReader.addData(data); CONFIG.obstacle_positions.clear(); while(!xmlReader.atEnd()) { xmlReader.readNext(); if(xmlReader.isStartElement()) { if((xmlReader.name() == "scenario") || (xmlReader.name() == "welcome")) { // nothing to do } else if(xmlReader.name() == "obstacle") { double x1 = xmlReader.attributes().value("x1").toString().toDouble(); double y1 = xmlReader.attributes().value("y1").toString().toDouble(); double x2 = xmlReader.attributes().value("x2").toString().toDouble(); double y2 = xmlReader.attributes().value("y2").toString().toDouble(); Obstacle* obs = new Obstacle(x1, y1, x2, y2); this->addObstacle(obs); // drawObstacles(x1, y1, x2, y2); } else if(xmlReader.name() == "waypoint") { // TODO - add an explicit waypoint type QString id = xmlReader.attributes().value("id").toString(); double x = xmlReader.attributes().value("x").toString().toDouble(); double y = xmlReader.attributes().value("y").toString().toDouble(); double r = xmlReader.attributes().value("r").toString().toDouble(); Waypoint* w = new Waypoint(id, x, y, r); // if (boost::starts_with(id, "start")) { // w->setType(Ped::Twaypoint::TYPE_BIRTH); // std::cout << "adding a birth waypoint" << std::endl; // } // if (boost::starts_with(id, "stop")) { // w->setType(Ped::Twaypoint::TYPE_DEATH); // std::cout << "adding a death waypoint" << std::endl; // } this->waypoints[id] = w; } else if(xmlReader.name() == "agent") { double x = xmlReader.attributes().value("x").toString().toDouble(); double y = xmlReader.attributes().value("y").toString().toDouble(); int n = xmlReader.attributes().value("n").toString().toDouble(); double dx = xmlReader.attributes().value("dx").toString().toDouble(); double dy = xmlReader.attributes().value("dy").toString().toDouble(); double type = xmlReader.attributes().value("type").toString().toInt(); //TODO: keep agent group and expand later!? for (int i=0; i<n; i++) { Agent* a = new Agent(); double randomizedX = x; double randomizedY = y; // handle dx=0 or dy=0 cases //TODO: qrand() actually needs to be seeded to create different runs if(dx != 0) randomizedX += qrand()/(double)RAND_MAX * dx - dx/2; if(dy != 0) randomizedY += qrand()/(double)RAND_MAX * dy - dy/2; a->setPosition(randomizedX, randomizedY); a->setType(type); this->addAgent(a); currentAgents.append(a); } } else if(xmlReader.name() == "addwaypoint") { QString id = xmlReader.attributes().value("id").toString(); // add waypoints to current agents, not just those of the current <agent> element foreach(Agent* a, currentAgents) a->addWaypoint(this->waypoints[id]); } else { // inform the user about invalid elements // ROS_WARN("Unknown element: %s", xmlReader.name().toString()); } } else if(xmlReader.isEndElement()) { if (xmlReader.name() == "agent") { currentAgents.clear(); } } } } int main(int argc, char** argv) { // initialize resources ros::init(argc, argv, "simulator"); ROS_INFO("node initialized"); ros::NodeHandle node; Scene sim_scene(node); ROS_INFO("Simulation scene started"); // load parameters std::string scene_file_param; node.getParam("/simulator/scene_file", scene_file_param); double cell_size; node.getParam("/simulator/cell_size", cell_size); CONFIG.width = cell_size; CONFIG.height = cell_size; // load scenario file QString scenefile = QString::fromStdString(scene_file_param); if (!sim_scene.readFromFile(scenefile)) { ROS_WARN("Could not load the scene file, check paths"); } ROS_INFO("loaded parameters"); sim_scene.runSimulation(); // ScenarioReader scenarioReader(scene); return 0; } <|endoftext|>
<commit_before>// Copyright (c) Andrew Fischer. See LICENSE file for license terms. #include "framework.h" #include "object.h" #include "evaluation.h" using namespace circa; namespace c_objects { struct CustomObject { bool initialized; bool checked; bool destroyed; }; int g_currentlyAllocated = 0; int g_totalAllocated = 0; void create_object(caStack* stack) { CustomObject* object = (CustomObject*) circa_create_object_output(stack, 0); object->initialized = true; object->checked = false; object->destroyed = false; g_currentlyAllocated++; g_totalAllocated++; } void check_object(caStack* stack) { CustomObject* object = (CustomObject*) circa_object_input(stack, 0); test_assert(object->initialized); test_assert(!object->checked); test_assert(!object->destroyed); object->checked = true; } void CustomObjectRelease(void* object) { CustomObject* obj = (CustomObject*) object; test_assert(obj->initialized); test_assert(obj->checked); test_assert(!obj->destroyed); g_currentlyAllocated--; } void test_custom_object() { g_currentlyAllocated = 0; g_totalAllocated = 0; Branch branch; branch.compile( "type MyType; \n" "def create_object() -> MyType\n" "def check_object(MyType t)\n" "s = create_object()\n" "check_object(s)\n" ); circa_install_function(&branch, "create_object", create_object); circa_install_function(&branch, "check_object", check_object); circa_setup_object_type(circa_find_type(&branch, "MyType"), sizeof(CustomObject), CustomObjectRelease); // Shouldn't allocate any objects before running. test_equals(g_currentlyAllocated, 0); test_equals(g_totalAllocated, 0); Stack stack; push_frame(&stack, &branch); run_interpreter(&stack); test_assert(&stack); circa_clear_stack(&stack); // Running the script should only cause 1 object allocation. test_equals(g_currentlyAllocated, 0); test_equals(g_totalAllocated, 1); } } // namespace c_objects void c_objects_register_tests() { REGISTER_TEST_CASE(c_objects::test_custom_object); } <commit_msg>add test around Type.inUse<commit_after>// Copyright (c) Andrew Fischer. See LICENSE file for license terms. #include "framework.h" #include "object.h" #include "type.h" #include "evaluation.h" using namespace circa; namespace c_objects { struct CustomObject { bool initialized; bool checked; bool destroyed; }; int g_currentlyAllocated = 0; int g_totalAllocated = 0; void create_object(caStack* stack) { CustomObject* object = (CustomObject*) circa_create_object_output(stack, 0); object->initialized = true; object->checked = false; object->destroyed = false; g_currentlyAllocated++; g_totalAllocated++; } void check_object(caStack* stack) { CustomObject* object = (CustomObject*) circa_object_input(stack, 0); test_assert(object->initialized); test_assert(!object->checked); test_assert(!object->destroyed); object->checked = true; } void CustomObjectRelease(void* object) { CustomObject* obj = (CustomObject*) object; test_assert(obj->initialized); test_assert(obj->checked); test_assert(!obj->destroyed); g_currentlyAllocated--; } void test_custom_object() { g_currentlyAllocated = 0; g_totalAllocated = 0; Branch branch; branch.compile( "type MyType; \n" "def create_object() -> MyType\n" "def check_object(MyType t)\n" "s = create_object()\n" "check_object(s)\n" ); circa_install_function(&branch, "create_object", create_object); circa_install_function(&branch, "check_object", check_object); circa_setup_object_type(circa_find_type(&branch, "MyType"), sizeof(CustomObject), CustomObjectRelease); // Shouldn't allocate any objects before running. test_equals(g_currentlyAllocated, 0); test_equals(g_totalAllocated, 0); Stack stack; push_frame(&stack, &branch); run_interpreter(&stack); test_assert(&stack); circa_clear_stack(&stack); // Running the script should only cause 1 object allocation. test_equals(g_currentlyAllocated, 0); test_equals(g_totalAllocated, 1); } void test_type_not_prematurely_used() { // Verify that a circa-defined type is not used until interpreter time. Modifying // a type's release() handler after there are already instances of it, is not good. Branch branch; branch.compile( "type MyType; \n" "def f() -> MyType\n" "def g(MyType t)\n" "s = f()\n" "g(s)\n" "l = [s s s]\n" "type MyCompoundType {\n" " MyType t\n" "}\n" "state MyType st\n" "state MyType st2 = create(MyType)\n" ); Type* myType = (Type*) circa_find_type(&branch, "MyType"); Type* myCompoundType = (Type*) circa_find_type(&branch, "MyCompoundType"); test_assert(!myType->inUse); test_assert(!myCompoundType->inUse); circa::Value value1, value2; create(myType, &value1); create(myCompoundType, &value2); test_assert(myType->inUse); test_assert(myCompoundType->inUse); } } // namespace c_objects void c_objects_register_tests() { REGISTER_TEST_CASE(c_objects::test_custom_object); REGISTER_TEST_CASE(c_objects::test_type_not_prematurely_used); } <|endoftext|>
<commit_before>/** \file base.hpp \brief Defines base formal language types used throughout this project. \author Radek Vít */ #ifndef CTF_BASE_H #define CTF_BASE_H #include <any> #include <ostream> #include <stdexcept> #include "generic_types.hpp" namespace ctf { /** \brief Attribute class. Holds values of any type. */ class Attribute { private: /** \brief Stores any value. */ std::any storage_; public: /** \brief Default copy constructor. */ Attribute(const Attribute&) = default; /** \brief Constructs Attribute from a reference to any type. \tparam T The type of stored object. */ template <typename T> Attribute(const T& arg) : storage_(arg) {} /** \brief Constructs Attribute from a rvalue reference. \tparam T The type of stored object. */ template <typename T> Attribute(T&& arg) : storage_(arg) {} /** \brief Constructs Attribute by passing constructor arguments to std::any. \tparam Args Variadic arguments type to be passed to std::any constuctor. */ template <typename... Args> Attribute(Args&&... args) : storage_(std::forward(args)...) {} /** \brief Default assignment operator. */ Attribute& operator=(const Attribute&) = default; /** \brief Default assignment operator. */ Attribute& operator=(Attribute&&) = default; /** \brief Assigns rhs to the Attribute object. \tparam T The type of the assigned object. */ template <typename T> Attribute& operator=(T& rhs) { storage_ = rhs; return *this; } /** \brief Assigns rhs to the Attribute object. \tparam T The type of the assigned object. */ template <typename T> Attribute& operator=(T&& rhs) { storage_ = rhs; return *this; } /** \brief Default destructor. */ ~Attribute() = default; /** \brief Retreives a value from storage. \tparam T The type of the retreived object. \return The stored value. */ template <typename T> T get() const { return std::any_cast<T>(storage_); } /** \brief Sets a value. \tparam T The type of the assigned value. \param[in] value A constant reference to the stored value. */ template <typename T> void set(const T& value) { storage_.emplace(value); } /** \brief Sets a value. \tparam T The type of the assigned value. \param[in] value A rvalue reference to the stored value. */ template <typename T> void set(T&& value) { storage_.emplace(value); } /** \brief Emplaces a value. \tparam T The type of stored object. \tparam Args The variadic arguments passed to the constructor of T. \param[in] args The arguments forwarded to std::any::emplace. \returns A reference to the emplaced object. */ template <typename T, typename... Args> auto emplace(Args&&... args) { return storage_.emplace<T>(std::forward(args)...); } /** \brief Resets the stored value. */ void clear() noexcept { storage_.reset(); } /** \brief Staps the contents of an Attribute with another. \param[in/out] other The other Attribute to be swapped. */ void swap(Attribute& other) { storage_.swap(other.storage_); } /** \brief Returns true if there is no value stored. \returns True when no value is stored in the Attribute. */ bool empty() const noexcept { return !storage_.has_value(); } /** \brief Get the type info of the stored object. */ const std::type_info& type() const noexcept { return storage_.type(); } /** \name Comparison operators \brief If compared to the same type, it compares the contents of Attribute to the other value. \returns True when the operands are of the same type and they are equal. */ ///@{ template <typename T> friend bool operator==(const Attribute& lhs, const T& rhs) { if (lhs.type() != typeid(rhs)) return false; return lhs.get<T>() == rhs; } template <typename T> friend bool operator==(const T& lhs, const Attribute& rhs) { if (lhs.type() != typeid(rhs)) return false; return lhs == rhs.get<T>(); } ///@} }; /** \brief Base exception class for ctf specific exceptions. */ class TranslationException : public std::runtime_error { using std::runtime_error::runtime_error; }; /** \brief POD struct holding location coordinates. Valid row and col numbers start at 1. Zero value row or col values are equal to the invalid() constant. **/ struct Location { /** \brief Row number. The lowest valid row number is 1. */ uint64_t row; /** \brief Col number. The lowest valid col number is 1. */ uint64_t col; /** \brief The name of the source of the location. */ string fileName; /** \brief Basic constructor. \param[in] _row The row of the created object. \param[in] _col The col of the created object. \param[in] _fileName The name of the source file. */ Location(uint64_t _row, uint64_t _col, string _fileName = "") : row(_row), col(_col), fileName(_fileName) { if (row == 0 || col == 0) { throw std::invalid_argument( "ctf::Location constructed with row or col with value 0."); } } /** \brief Implicit first location constructor. \param[in] _fileName The name of the source file. */ Location(string _fileName = "") : row(1), col(1), fileName(_fileName) {} Location(const Location&) = default; Location(Location&&) noexcept = default; ~Location() = default; /** \brief Static constant invalid location object. \returns A const reference to the single invalid Location object. */ static const Location& invalid() noexcept { static const Location ns{false}; return ns; } Location& operator=(const Location&) = default; Location& operator=(Location&&) noexcept = default; /** \brief Compares two Location objects by row and col numbers. \param[in] lhs The left-hand side Location. \param[in] rhs The right-hand side Location. \returns True if both are invalid or when both have the same row and col. False otherwise. */ friend bool operator==(const Location& lhs, const Location& rhs) { // Location::invalid comparison if ((lhs.row == 0 || lhs.col == 0) && (rhs.row == 0 || rhs.col == 0)) return true; // regular comparison return lhs.row == rhs.row && lhs.col == rhs.col; } /** \brief Compares two Location objects by row and col numbers. \param[in] lhs The left-hand side Location. \param[in] rhs The right-hand side Location. \returns False if both are invalid or when both have the same row and col. True otherwise. */ friend bool operator!=(const Location& lhs, const Location& rhs) { return !(lhs == rhs); } /** \brief Creates a string from this Location. \returns A string in the format "fileName:row:col" */ string to_string() const { if (*this == Location::invalid()) { return ""; } return fileName + ":" + std::to_string(row) + ":" + std::to_string(col); } private: /** \brief Constructs an invalid Location. */ Location(bool) : row(0), col(0) {} }; /** \brief A single symbol in the translation process. May represent a Terminal, Nonterminal or end of input. */ class Symbol { inline static unordered_map<string, size_t> reverseNameMap; inline static vector<string> nameMap; public: /** \brief Type of the Symbol. */ enum class Type : unsigned char { /** \brief Undefined type */ UNKNOWN, /** \brief Terminal symbol */ TERMINAL, /** \brief Nonterminal symbol */ NONTERMINAL, /** \brief End of input */ EOI, /** \brief Denotes a symbol with special meaning for translation control or output generator. */ SPECIAL, }; protected: /** \brief Type of this Symbol. */ Type type_; /** \brief Id of this Symbol. */ size_t id_; /** \brief Attribute of this Symbol. Only valid for some types. */ Attribute attribute_; /** \brief Location of the origin of this Symbol. */ Location location_; static size_t name_index(const string& name) { auto it = reverseNameMap.find(name); if (it == reverseNameMap.end()) { size_t result = nameMap.size(); reverseNameMap[name] = result; nameMap.push_back(name); return result; } return it->second; } public: /** \brief Constructs a Symbol with a given type. If specified, sets Symbol's name and attribute. \param[in] type Type of constructed Symbol. \param[in] name Name of constructed Symbol. Defaults to "". "" is only valid for Type::EOI. \param[in] atr Attribute of constructed Symbol. */ Symbol(Type type, const string& name = "", const Attribute& atr = Attribute{}, const Location& loc = Location::invalid()) : type_(type), id_(name_index(name)), attribute_(atr), location_(loc) { if (type != Symbol::Type::EOI && name == "") throw std::invalid_argument( "Empty name when constructing non-EOI Symbol."); } /** \brief Constructs a Symbol with unspecified type. Sets Symbol's name and if specified, sets attribute. \param[in] name Name of constructed Symbol. \param[in] atr Attribute of constructed Symbol. Defaults to "". */ Symbol(const string& name, const Attribute& atr = Attribute{}, const Location& loc = Location::invalid()) : Symbol(Type::UNKNOWN, name, atr, loc) {} /** \brief Default destructor. */ ~Symbol() = default; /** \brief Creates an EOF Symbol. \returns An EOF Symbol. */ static Symbol eof() { return Symbol(Type::EOI); } size_t id() const { return id_; } /** \brief Returns a const reference to name. \returns A const reference to name. May be invalidated by constructing a Symbol with a previously unused name. */ const string& name() const { return nameMap[id_]; } /** \brief Returns a reference to attribute. \returns A reference to attribute. */ Attribute& attribute() { return attribute_; } /** \brief Returns a const reference to attribute. \returns A const reference to attribute. */ const Attribute& attribute() const { return attribute_; } /** \brief Returns a const reference to type. \returns A const reference to type. */ const Type& type() const { return type_; } /** \brief Returns the Symbol's location. \returns The Symbol's original location. */ const Location& location() const { return location_; } /** \brief Merges symbol's attribute and sets location if not set. */ void set_attribute(const Symbol& other) { // TODO change for future Attribute type attribute_ = other.attribute(); if (location_ == Location::invalid()) location_ = other.location(); } /** \name Comparison operators \brief Numeric comparison of types and lexicographic comparison of names. Types have higher priority. \param[in] lhs Left Symbol of the comparison. \param[out] rhs Right Symbol of the comparison. \returns True when the lexicographic comparison is true. */ ///@{ friend bool operator<(const Symbol& lhs, const Symbol& rhs) { return lhs.type_ < rhs.type_ || (lhs.type_ == rhs.type_ && lhs.id_ < rhs.id_); } friend bool operator==(const Symbol& lhs, const Symbol& rhs) { return lhs.type_ == rhs.type_ && lhs.id_ == rhs.id_; } friend bool operator!=(const Symbol& lhs, const Symbol& rhs) { return !(lhs == rhs); } friend bool operator>(const Symbol& lhs, const Symbol& rhs) { return rhs < lhs; } friend bool operator<=(const Symbol& lhs, const Symbol& rhs) { return lhs == rhs || lhs < rhs; } friend bool operator>=(const Symbol& lhs, const Symbol& rhs) { return rhs <= lhs; } ///@} }; /** \brief Returns a Symbol with Type::Terminal, given name and attribute. \param[in] name Name of returned symbol. \param[in] attribute Attribute of returned Symbol. Defaults to "". \returns A Symbol with type Terminal, given name and given attribute. */ inline Symbol Terminal(const string& name, const Attribute& attribute = Attribute{}, const Location& loc = Location::invalid()) { return Symbol(Symbol::Type::TERMINAL, name, attribute, loc); } /** \brief Returns a Symbol with Type::Nonterminal, given name and attribute. \param[in] name Name of returned symbol. \returns A Symbol with type Nonterminal and given name. */ inline Symbol Nonterminal(const string& name) { return Symbol(Symbol::Type::NONTERMINAL, name); } #ifndef CTF_NO_QUOTE_OPERATORS inline namespace literals { /** \brief Returns a Symbol of Type::Terminal with given name. \param[in] s C string representing the name of the returned Symbol. \returns Symbol with type Terminal and given name. */ inline Symbol operator""_t(const char* s, size_t) { return Terminal({s}); } /** \brief Returns a Symbol of Type::Nonterminal with given name. \param[in] s C string representing the name of the returned Symbol. \returns Symbol with type Terminal and given name. */ inline Symbol operator""_nt(const char* s, size_t) { return Nonterminal({s}); } /** \brief Returns a Symbol of Type::Special with given name. \param[in] s C string representing the name of the returned Symbol. \returns Symbol with type Special and given name. */ inline Symbol operator""_s(const char* s, size_t) { return Symbol(Symbol::Type::SPECIAL, {s}); } } // inline namespace literals #endif } // namespace ctf namespace std { inline void swap(ctf::Attribute& lhs, ctf::Attribute& rhs) noexcept { lhs.swap(rhs); } template <> struct hash<ctf::Symbol> { using argument_type = ctf::Symbol; using result_type = size_t; result_type operator()(argument_type const& s) const noexcept { return std::hash<size_t>{}(s.id()); } }; } // namespace std #endif /*** End of file base.hpp ***/<commit_msg>Fixed initialization order issue; added multithread variant for Symbol<commit_after>/** \file base.hpp \brief Defines base formal language types used throughout this project. \author Radek Vít */ #ifndef CTF_BASE_H #define CTF_BASE_H #include <any> #include <ostream> #include <stdexcept> #include "generic_types.hpp" #ifdef CTF_MULTITHREAD #include <mutex> #endif namespace ctf { /** \brief Attribute class. Holds values of any type. */ class Attribute { private: /** \brief Stores any value. */ std::any storage_; public: /** \brief Default copy constructor. */ Attribute(const Attribute&) = default; /** \brief Constructs Attribute from a reference to any type. \tparam T The type of stored object. */ template <typename T> Attribute(const T& arg) : storage_(arg) {} /** \brief Constructs Attribute from a rvalue reference. \tparam T The type of stored object. */ template <typename T> Attribute(T&& arg) : storage_(arg) {} /** \brief Constructs Attribute by passing constructor arguments to std::any. \tparam Args Variadic arguments type to be passed to std::any constuctor. */ template <typename... Args> Attribute(Args&&... args) : storage_(std::forward(args)...) {} /** \brief Default assignment operator. */ Attribute& operator=(const Attribute&) = default; /** \brief Default assignment operator. */ Attribute& operator=(Attribute&&) = default; /** \brief Assigns rhs to the Attribute object. \tparam T The type of the assigned object. */ template <typename T> Attribute& operator=(T& rhs) { storage_ = rhs; return *this; } /** \brief Assigns rhs to the Attribute object. \tparam T The type of the assigned object. */ template <typename T> Attribute& operator=(T&& rhs) { storage_ = rhs; return *this; } /** \brief Default destructor. */ ~Attribute() = default; /** \brief Retreives a value from storage. \tparam T The type of the retreived object. \return The stored value. */ template <typename T> T get() const { return std::any_cast<T>(storage_); } /** \brief Sets a value. \tparam T The type of the assigned value. \param[in] value A constant reference to the stored value. */ template <typename T> void set(const T& value) { storage_.emplace(value); } /** \brief Sets a value. \tparam T The type of the assigned value. \param[in] value A rvalue reference to the stored value. */ template <typename T> void set(T&& value) { storage_.emplace(value); } /** \brief Emplaces a value. \tparam T The type of stored object. \tparam Args The variadic arguments passed to the constructor of T. \param[in] args The arguments forwarded to std::any::emplace. \returns A reference to the emplaced object. */ template <typename T, typename... Args> auto emplace(Args&&... args) { return storage_.emplace<T>(std::forward(args)...); } /** \brief Resets the stored value. */ void clear() noexcept { storage_.reset(); } /** \brief Staps the contents of an Attribute with another. \param[in/out] other The other Attribute to be swapped. */ void swap(Attribute& other) { storage_.swap(other.storage_); } /** \brief Returns true if there is no value stored. \returns True when no value is stored in the Attribute. */ bool empty() const noexcept { return !storage_.has_value(); } /** \brief Get the type info of the stored object. */ const std::type_info& type() const noexcept { return storage_.type(); } /** \name Comparison operators \brief If compared to the same type, it compares the contents of Attribute to the other value. \returns True when the operands are of the same type and they are equal. */ ///@{ template <typename T> friend bool operator==(const Attribute& lhs, const T& rhs) { if (lhs.type() != typeid(rhs)) return false; return lhs.get<T>() == rhs; } template <typename T> friend bool operator==(const T& lhs, const Attribute& rhs) { if (lhs.type() != typeid(rhs)) return false; return lhs == rhs.get<T>(); } ///@} }; /** \brief Base exception class for ctf specific exceptions. */ class TranslationException : public std::runtime_error { using std::runtime_error::runtime_error; }; /** \brief POD struct holding location coordinates. Valid row and col numbers start at 1. Zero value row or col values are equal to the invalid() constant. **/ struct Location { /** \brief Row number. The lowest valid row number is 1. */ uint64_t row; /** \brief Col number. The lowest valid col number is 1. */ uint64_t col; /** \brief The name of the source of the location. */ string fileName; /** \brief Basic constructor. \param[in] _row The row of the created object. \param[in] _col The col of the created object. \param[in] _fileName The name of the source file. */ Location(uint64_t _row, uint64_t _col, string _fileName = "") : row(_row), col(_col), fileName(_fileName) { if (row == 0 || col == 0) { throw std::invalid_argument( "ctf::Location constructed with row or col with value 0."); } } /** \brief Implicit first location constructor. \param[in] _fileName The name of the source file. */ Location(string _fileName = "") : row(1), col(1), fileName(_fileName) {} Location(const Location&) = default; Location(Location&&) noexcept = default; ~Location() = default; /** \brief Static constant invalid location object. \returns A const reference to the single invalid Location object. */ static const Location& invalid() noexcept { static const Location ns{false}; return ns; } Location& operator=(const Location&) = default; Location& operator=(Location&&) noexcept = default; /** \brief Compares two Location objects by row and col numbers. \param[in] lhs The left-hand side Location. \param[in] rhs The right-hand side Location. \returns True if both are invalid or when both have the same row and col. False otherwise. */ friend bool operator==(const Location& lhs, const Location& rhs) { // Location::invalid comparison if ((lhs.row == 0 || lhs.col == 0) && (rhs.row == 0 || rhs.col == 0)) return true; // regular comparison return lhs.row == rhs.row && lhs.col == rhs.col; } /** \brief Compares two Location objects by row and col numbers. \param[in] lhs The left-hand side Location. \param[in] rhs The right-hand side Location. \returns False if both are invalid or when both have the same row and col. True otherwise. */ friend bool operator!=(const Location& lhs, const Location& rhs) { return !(lhs == rhs); } /** \brief Creates a string from this Location. \returns A string in the format "fileName:row:col" */ string to_string() const { if (*this == Location::invalid()) { return ""; } return fileName + ":" + std::to_string(row) + ":" + std::to_string(col); } private: /** \brief Constructs an invalid Location. */ Location(bool) : row(0), col(0) {} }; /** \brief A single symbol in the translation process. May represent a Terminal, Nonterminal or end of input. */ class Symbol { #ifdef CTF_MULTITHREAD inline static std::mutex& nameLock() { static std::mutex nl; return nl; } #endif inline static unordered_map<string, size_t>& reverseNameMap() { static unordered_map<string, size_t> rnm; return rnm; } inline static vector<string>& nameMap() { static vector<string> nm; return nm; } public: /** \brief Type of the Symbol. */ enum class Type : unsigned char { /** \brief Undefined type */ UNKNOWN, /** \brief Terminal symbol */ TERMINAL, /** \brief Nonterminal symbol */ NONTERMINAL, /** \brief End of input */ EOI, /** \brief Denotes a symbol with special meaning for translation control or output generator. */ SPECIAL, }; protected: /** \brief Type of this Symbol. */ Type type_; /** \brief Id of this Symbol. */ size_t id_; /** \brief Attribute of this Symbol. Only valid for some types. */ Attribute attribute_; /** \brief Location of the origin of this Symbol. */ Location location_; static size_t name_index(const string& name) { #ifdef CTF_MULTITHREAD std::lock_guard l(nameLock()); #endif auto it = reversenameMap().find(name); if (it == reversenameMap().end()) { size_t result = nameMap().size(); reversenameMap()[name] = result; nameMap().push_back(name); return result; } return it->second; } public: /** \brief Constructs a Symbol with a given type. If specified, sets Symbol's name and attribute. \param[in] type Type of constructed Symbol. \param[in] name Name of constructed Symbol. Defaults to "". "" is only valid for Type::EOI. \param[in] atr Attribute of constructed Symbol. */ Symbol(Type type, const string& name = "", const Attribute& atr = Attribute{}, const Location& loc = Location::invalid()) : type_(type), id_(name_index(name)), attribute_(atr), location_(loc) { if (type != Symbol::Type::EOI && name == "") throw std::invalid_argument( "Empty name when constructing non-EOI Symbol."); } /** \brief Constructs a Symbol with unspecified type. Sets Symbol's name and if specified, sets attribute. \param[in] name Name of constructed Symbol. \param[in] atr Attribute of constructed Symbol. Defaults to "". */ Symbol(const string& name, const Attribute& atr = Attribute{}, const Location& loc = Location::invalid()) : Symbol(Type::UNKNOWN, name, atr, loc) {} /** \brief Default destructor. */ ~Symbol() = default; /** \brief Creates an EOF Symbol. \returns An EOF Symbol. */ static Symbol eof() { return Symbol(Type::EOI); } size_t id() const { return id_; } /** \brief Returns a const reference to name. \returns A const reference to name. May be invalidated by constructing a Symbol with a previously unused name. */ const string& name() const { #ifdef CTF_MULTITHREAD std::lock_guard l(nameLock()); #endif return nameMap()[id_]; } /** \brief Returns a reference to attribute. \returns A reference to attribute. */ Attribute& attribute() { return attribute_; } /** \brief Returns a const reference to attribute. \returns A const reference to attribute. */ const Attribute& attribute() const { return attribute_; } /** \brief Returns a const reference to type. \returns A const reference to type. */ const Type& type() const { return type_; } /** \brief Returns the Symbol's location. \returns The Symbol's original location. */ const Location& location() const { return location_; } /** \brief Merges symbol's attribute and sets location if not set. */ void set_attribute(const Symbol& other) { // TODO change for future Attribute type attribute_ = other.attribute(); if (location_ == Location::invalid()) location_ = other.location(); } /** \name Comparison operators \brief Numeric comparison of types and lexicographic comparison of names. Types have higher priority. \param[in] lhs Left Symbol of the comparison. \param[out] rhs Right Symbol of the comparison. \returns True when the lexicographic comparison is true. */ ///@{ friend bool operator<(const Symbol& lhs, const Symbol& rhs) { return lhs.type_ < rhs.type_ || (lhs.type_ == rhs.type_ && lhs.id_ < rhs.id_); } friend bool operator==(const Symbol& lhs, const Symbol& rhs) { return lhs.type_ == rhs.type_ && lhs.id_ == rhs.id_; } friend bool operator!=(const Symbol& lhs, const Symbol& rhs) { return !(lhs == rhs); } friend bool operator>(const Symbol& lhs, const Symbol& rhs) { return rhs < lhs; } friend bool operator<=(const Symbol& lhs, const Symbol& rhs) { return lhs == rhs || lhs < rhs; } friend bool operator>=(const Symbol& lhs, const Symbol& rhs) { return rhs <= lhs; } ///@} }; /** \brief Returns a Symbol with Type::Terminal, given name and attribute. \param[in] name Name of returned symbol. \param[in] attribute Attribute of returned Symbol. Defaults to "". \returns A Symbol with type Terminal, given name and given attribute. */ inline Symbol Terminal(const string& name, const Attribute& attribute = Attribute{}, const Location& loc = Location::invalid()) { return Symbol(Symbol::Type::TERMINAL, name, attribute, loc); } /** \brief Returns a Symbol with Type::Nonterminal, given name and attribute. \param[in] name Name of returned symbol. \returns A Symbol with type Nonterminal and given name. */ inline Symbol Nonterminal(const string& name) { return Symbol(Symbol::Type::NONTERMINAL, name); } #ifndef CTF_NO_QUOTE_OPERATORS inline namespace literals { /** \brief Returns a Symbol of Type::Terminal with given name. \param[in] s C string representing the name of the returned Symbol. \returns Symbol with type Terminal and given name. */ inline Symbol operator""_t(const char* s, size_t) { return Terminal({s}); } /** \brief Returns a Symbol of Type::Nonterminal with given name. \param[in] s C string representing the name of the returned Symbol. \returns Symbol with type Terminal and given name. */ inline Symbol operator""_nt(const char* s, size_t) { return Nonterminal({s}); } /** \brief Returns a Symbol of Type::Special with given name. \param[in] s C string representing the name of the returned Symbol. \returns Symbol with type Special and given name. */ inline Symbol operator""_s(const char* s, size_t) { return Symbol(Symbol::Type::SPECIAL, {s}); } } // inline namespace literals #endif } // namespace ctf namespace std { inline void swap(ctf::Attribute& lhs, ctf::Attribute& rhs) noexcept { lhs.swap(rhs); } template <> struct hash<ctf::Symbol> { using argument_type = ctf::Symbol; using result_type = size_t; result_type operator()(argument_type const& s) const noexcept { return std::hash<size_t>{}(s.id()); } }; } // namespace std #endif /*** End of file base.hpp ***/<|endoftext|>
<commit_before>/* Copyright libCellML Contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "test_utils.h" #include "gtest/gtest.h" #include <libcellml> TEST(Generator, isolatedFirstOrderModel) { // This test resulted from https://github.com/cellml/libcellml/issues/432 // 1.a Create the model instance libcellml::ModelPtr model = libcellml::Model::create(); model->setName("Tutorial4_FirstOrderModel"); // 1.b Create a component and add it into the model libcellml::ComponentPtr component = libcellml::Component::create(); component->setName("IonChannel"); model->addComponent(component); // 2.a Define the mathematics. std::string mathHeader = "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" xmlns:cellml=\"http://www.cellml.org/cellml/2.0#\">"; // dy/dt = alpha_y*(1-y) - beta_y*y std::string equation1 = "<apply>\ <eq/>\ <apply>\ <diff/>\ <bvar>\ <ci>t</ci>\ </bvar>\ <ci>y</ci>\ </apply>\ <apply>\ <minus/>\ <apply>\ <times/>\ <ci>alpha_y</ci>\ <apply>\ <minus/>\ <cn cellml:units=\"dimensionless\">1</cn>\ <ci>y</ci>\ </apply>\ </apply>\ <apply>\ <times/>\ <ci>beta_y</ci>\ <ci>y</ci>\ </apply>\ </apply>\ </apply>"; // i_y = g_y*power(y,gamma)*(V-E_y) std::string equation2 = "<apply>\ <eq/>\ <ci>i_y</ci>\ <apply>\ <times/>\ <ci>g_y</ci>\ <apply>\ <minus/>\ <ci>V</ci>\ <ci>E_y</ci>\ </apply>\ <apply>\ <power/>\ <ci>y</ci>\ <ci>gamma</ci>\ </apply>\ </apply>\ </apply>"; std::string mathFooter = "</math>"; // 2.b Add the maths to the component. Note that there is only one maths // string stored, so parts which are appended must create a viable // MathML2 string when concantenated. To clear any string which is // already stored, simply call setMath("") with an empty string. component->setMath(mathHeader); component->appendMath(equation1); component->appendMath(equation2); component->appendMath(mathFooter); // 3.a,b Declaring the variables, their names, units, and initial conditions // Note that the names given to variables must be the same as that used // within the <ci> blocks in the MathML string we created in step 2.a. libcellml::VariablePtr t = libcellml::Variable::create(); t->setName("t"); t->setUnits("millisecond"); // Note: time is our integration base variable so is not initialised libcellml::VariablePtr V = libcellml::Variable::create(); V->setName("V"); V->setUnits("millivolt"); V->setInitialValue(0.0); libcellml::VariablePtr alpha_y = libcellml::Variable::create(); alpha_y->setName("alpha_y"); alpha_y->setUnits("per_millisecond"); alpha_y->setInitialValue(1.0); libcellml::VariablePtr beta_y = libcellml::Variable::create(); beta_y->setName("beta_y"); beta_y->setUnits("per_millisecond"); beta_y->setInitialValue(2.0); libcellml::VariablePtr y = libcellml::Variable::create(); y->setName("y"); y->setUnits("dimensionless"); y->setInitialValue(1.0); libcellml::VariablePtr E_y = libcellml::Variable::create(); E_y->setName("E_y"); E_y->setUnits("millivolt"); E_y->setInitialValue(-85.0); libcellml::VariablePtr i_y = libcellml::Variable::create(); i_y->setName("i_y"); i_y->setUnits("microA_per_cm2"); // Note that no initial value is needed for this variable as its value // is defined by equation2 libcellml::VariablePtr g_y = libcellml::Variable::create(); g_y->setName("g_y"); g_y->setUnits("milliS_per_cm2"); g_y->setInitialValue(36.0); libcellml::VariablePtr gamma = libcellml::Variable::create(); gamma->setName("gamma"); gamma->setUnits("dimensionless"); gamma->setInitialValue(4.0); // 3.c Adding the variables to the component. Note that Variables are // added by their pointer (cf. their name) component->addVariable(t); component->addVariable(V); component->addVariable(E_y); component->addVariable(gamma); component->addVariable(i_y); component->addVariable(g_y); component->addVariable(alpha_y); component->addVariable(beta_y); component->addVariable(y); // 4.a Defining the units of millisecond, millivolt, per_millisecond, // microA_per_cm2, and milliS_per_cm2. Note that the dimensionless // units are part of those built-in already, so do not need to be // defined here. libcellml::UnitsPtr ms = libcellml::Units::create(); ms->setName("millisecond"); ms->addUnit("second", "milli"); libcellml::UnitsPtr mV = libcellml::Units::create(); mV->setName("millivolt"); mV->addUnit("volt", "milli"); libcellml::UnitsPtr per_ms = libcellml::Units::create(); per_ms->setName("per_millisecond"); per_ms->addUnit("millisecond", -1.0); libcellml::UnitsPtr microA_per_cm2 = libcellml::Units::create(); microA_per_cm2->setName("microA_per_cm2"); microA_per_cm2->addUnit("ampere", "micro"); microA_per_cm2->addUnit("metre", "centi", -2.0); libcellml::UnitsPtr mS_per_cm2 = libcellml::Units::create(); mS_per_cm2->setName("milliS_per_cm2"); mS_per_cm2->addUnit("siemens", "milli"); mS_per_cm2->addUnit("metre", "centi", -2.0); // 4.b Add these units into the model model->addUnits(ms); model->addUnits(mV); model->addUnits(per_ms); model->addUnits(microA_per_cm2); model->addUnits(mS_per_cm2); // 4.c Validate the final arrangement. No errors are expected at this stage. libcellml::Validator validator; validator.validateModel(model); printErrors(validator); // 5.a Create a Generator instance. By default the options set in the // generator constructor are: // - profile() return "C" (cf "PYTHON") // - modelType() returns "ODE" libcellml::Generator generator; generator.processModel(model); // 5.b Check whether the generator has encountered any errors printErrors(generator); EXPECT_EQ(size_t(0), generator.errorCount()); } <commit_msg>Isolated generator test: some minor cleaning up of the code.<commit_after>/* Copyright libCellML Contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "test_utils.h" #include "gtest/gtest.h" #include <libcellml> TEST(Generator, isolatedFirstOrderModel) { // This test resulted from https://github.com/cellml/libcellml/issues/432 // 1.a Create the model instance. libcellml::ModelPtr model = libcellml::Model::create(); model->setName("Tutorial4_FirstOrderModel"); // 1.b Create a component and add it into the model. libcellml::ComponentPtr component = libcellml::Component::create(); component->setName("IonChannel"); model->addComponent(component); // 2.a Define the mathematics. const std::string mathHeader = "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" xmlns:cellml=\"http://www.cellml.org/cellml/2.0#\">"; // dy/dt = alpha_y*(1-y) - beta_y*y const std::string equation1 = "<apply>\n" " <eq/>\n" " <apply>\n" " <diff/>\n" " <bvar>\n" " <ci>t</ci>\n" " </bvar>\n" " <ci>y</ci>\n" " </apply>\n" " <apply>\n" " <minus/>\n" " <apply>\n" " <times/>\n" " <ci>alpha_y</ci>\n" " <apply>\n" " <minus/>\n" " <cn cellml:units=\"dimensionless\">1</cn>\n" " <ci>y</ci>\n" " </apply>\n" " </apply>\n" " <apply>\n" " <times/>\n" " <ci>beta_y</ci>\n" " <ci>y</ci>\n" " </apply>\n" " </apply>\n" "</apply>\n"; // i_y = g_y*power(y,gamma)*(V-E_y) const std::string equation2 = "<apply>\n" " <eq/>\n" " <ci>i_y</ci>\n" " <apply>\n" " <times/>\n" " <ci>g_y</ci>\n" " <apply>\n" " <minus/>\n" " <ci>V</ci>\n" " <ci>E_y</ci>\n" " </apply>\n" " <apply>\n" " <power/>\n" " <ci>y</ci>\n" " <ci>gamma</ci>\n" " </apply>\n" " </apply>\n" "</apply>"; const std::string mathFooter = "</math>"; // 2.b Add the maths to the component. Note that there is only one maths // string stored, so parts which are appended must create a viable // MathML string when concantenated. To clear any string, which is // already stored, simply call setMath("") with an empty string. component->setMath(mathHeader); component->appendMath(equation1); component->appendMath(equation2); component->appendMath(mathFooter); // 3.a,b Declaring the variables, their names, units, and initial conditions // Note that the names given to variables must be the same as that used // within the <ci> blocks in the MathML string we created in step 2.a. libcellml::VariablePtr t = libcellml::Variable::create(); t->setName("t"); t->setUnits("millisecond"); // Note: time is our integration base variable so it is not initialised. libcellml::VariablePtr V = libcellml::Variable::create(); V->setName("V"); V->setUnits("millivolt"); V->setInitialValue(0.0); libcellml::VariablePtr alpha_y = libcellml::Variable::create(); alpha_y->setName("alpha_y"); alpha_y->setUnits("per_millisecond"); alpha_y->setInitialValue(1.0); libcellml::VariablePtr beta_y = libcellml::Variable::create(); beta_y->setName("beta_y"); beta_y->setUnits("per_millisecond"); beta_y->setInitialValue(2.0); libcellml::VariablePtr y = libcellml::Variable::create(); y->setName("y"); y->setUnits("dimensionless"); y->setInitialValue(1.0); libcellml::VariablePtr E_y = libcellml::Variable::create(); E_y->setName("E_y"); E_y->setUnits("millivolt"); E_y->setInitialValue(-85.0); libcellml::VariablePtr i_y = libcellml::Variable::create(); i_y->setName("i_y"); i_y->setUnits("microA_per_cm2"); // Note that no initial value is needed for this variable as its value // is defined by equation2. libcellml::VariablePtr g_y = libcellml::Variable::create(); g_y->setName("g_y"); g_y->setUnits("milliS_per_cm2"); g_y->setInitialValue(36.0); libcellml::VariablePtr gamma = libcellml::Variable::create(); gamma->setName("gamma"); gamma->setUnits("dimensionless"); gamma->setInitialValue(4.0); // 3.c Adding the variables to the component. Note that Variables are // added by their pointer (cf. their name). component->addVariable(t); component->addVariable(V); component->addVariable(E_y); component->addVariable(gamma); component->addVariable(i_y); component->addVariable(g_y); component->addVariable(alpha_y); component->addVariable(beta_y); component->addVariable(y); // 4.a Defining the units of millisecond, millivolt, per_millisecond, // microA_per_cm2, and milliS_per_cm2. Note that the dimensionless // units are part of those built-in already, so they don't need to be // defined here. libcellml::UnitsPtr ms = libcellml::Units::create(); ms->setName("millisecond"); ms->addUnit("second", "milli"); libcellml::UnitsPtr mV = libcellml::Units::create(); mV->setName("millivolt"); mV->addUnit("volt", "milli"); libcellml::UnitsPtr per_ms = libcellml::Units::create(); per_ms->setName("per_millisecond"); per_ms->addUnit("millisecond", -1.0); libcellml::UnitsPtr microA_per_cm2 = libcellml::Units::create(); microA_per_cm2->setName("microA_per_cm2"); microA_per_cm2->addUnit("ampere", "micro"); microA_per_cm2->addUnit("metre", "centi", -2.0); libcellml::UnitsPtr mS_per_cm2 = libcellml::Units::create(); mS_per_cm2->setName("milliS_per_cm2"); mS_per_cm2->addUnit("siemens", "milli"); mS_per_cm2->addUnit("metre", "centi", -2.0); // 4.b Add these units into the model. model->addUnits(ms); model->addUnits(mV); model->addUnits(per_ms); model->addUnits(microA_per_cm2); model->addUnits(mS_per_cm2); // 4.c Validate the final arrangement. No errors are expected at this stage. libcellml::Validator validator; validator.validateModel(model); printErrors(validator); // 5.a Create a Generator instance. By default the options set in the // generator constructor are: // - profile() return "C" (cf "PYTHON"); and // - modelType() returns "ODE". libcellml::Generator generator; generator.processModel(model); // 5.b Check whether the generator has encountered any errors. printErrors(generator); EXPECT_EQ(size_t(0), generator.errorCount()); } <|endoftext|>
<commit_before>#include <iostream> #include <primesieve.hpp> #include <boost/multiprecision/cpp_int.hpp> #include <boost/multiprecision/miller_rabin.hpp> #include <boost/math/common_factor.hpp> using namespace boost::multiprecision; cpp_int phi(const cpp_int x) { if (x == 1) { return 1; } if (miller_rabin_test(x, 50)) { return x-1; } if (x % 2 == 0){ cpp_int y = x >> 1; return !(y & 1) ? phi(y)<<1 : phi(y); } primesieve::iterator pi; cpp_int prime; for (prime = pi.next_prime(); prime < x; prime=pi.next_prime()) { cpp_int k = prime; if (x % k) continue; cpp_int o = x/k; cpp_int d = boost::math::gcd(k, o); if (d == 1) { return phi(k) * phi(o); } return phi(k) * phi(o) * d / phi(d); } } int main(void) { cpp_int small = 99; cpp_int large = 756928375693284658; std::cout << phi(9007199254740881); return 0; } <commit_msg>Removed ternaries<commit_after>#include <iostream> #include <primesieve.hpp> #include <boost/multiprecision/cpp_int.hpp> #include <boost/multiprecision/miller_rabin.hpp> #include <boost/math/common_factor.hpp> using namespace boost::multiprecision; cpp_int phi(const cpp_int x) { if (x == 1) { return 1; } if (miller_rabin_test(x, 50)) { return x-1; } if (x % 2 == 0){ cpp_int y = x >> 1; if (!(y & 1)) { return phi(y) << 1; } return phi(y); } primesieve::iterator pi; cpp_int prime; for (prime = pi.next_prime(); prime < x; prime=pi.next_prime()) { cpp_int k = prime; if (x % k) continue; cpp_int o = x/k; cpp_int d = boost::math::gcd(k, o); if (d == 1) { return phi(k) * phi(o); } return phi(k) * phi(o) * d / phi(d); } } int main(void) { cpp_int small = 99; cpp_int large = 756928375693284658; std::cout << phi(9007199254740881); return 0; } <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include "gmock/gmock.h" #include <string> #include "hybrid_automaton/JumpCondition.h" #include "hybrid_automaton/DescriptionTreeNode.h" #include "hybrid_automaton/JointConfigurationSensor.h" #include "hybrid_automaton/FrameOrientationSensor.h" #include "hybrid_automaton/FrameDisplacementSensor.h" #include "hybrid_automaton/FramePoseSensor.h" #include "tests/MockDescriptionTree.h" #include "tests/MockDescriptionTreeNode.h" using ::testing::Return; using ::testing::DoAll; using ::testing::SetArgReferee; using ::testing::AtLeast; using ::testing::_; using namespace ::ha; namespace JumpConditionSerialization1 { class MockSystem : public ha::System { public: MOCK_CONST_METHOD0(getDof, int () ); MOCK_CONST_METHOD0(getConfiguration, ::Eigen::MatrixXd () ); MOCK_CONST_METHOD0(getForceTorqueMeasurement, ::Eigen::MatrixXd () ); MOCK_CONST_METHOD0(getCurrentTime, ::Eigen::MatrixXd () ); MOCK_CONST_METHOD1(getFramePose, ::Eigen::MatrixXd (const std::string& frame_id) ); }; } TEST(JumpCondition, Serialization) { using namespace ha; using namespace std; //------- // Serialized and deserialized sensor System::ConstPtr _ms = System::ConstPtr(new JumpConditionSerialization1::MockSystem()); JointConfigurationSensorPtr js_s = JointConfigurationSensorPtr(new JointConfigurationSensor()); js_s->setSystem(_ms); // Mocked description returned by jump condition MockDescriptionTreeNode* _jc_node = new MockDescriptionTreeNode; DescriptionTreeNode::Ptr jc_node(_jc_node); EXPECT_CALL(*_jc_node, getType()).WillRepeatedly(Return("JumpCondition")); EXPECT_CALL(*_jc_node, getAttributeString(_, _)) .WillRepeatedly(DoAll(SetArgReferee<1>(""),Return(true))); //------- // TEST ControlMode // Mocked tree factory MockDescriptionTree* _tree = new MockDescriptionTree; MockDescriptionTree::Ptr tree(_tree); JumpCondition* _jc1 = new JumpCondition; JumpCondition::Ptr jc1(_jc1); MockDescriptionTreeNode::Ptr cm1_node_faulty(new MockDescriptionTreeNode); EXPECT_CALL(*cm1_node_faulty, setAttributeString(_,_)) .Times(AtLeast(0)); // assert throwing of exception if no sensor has been set EXPECT_CALL(*_tree, createNode("JumpCondition")) .WillOnce(Return(cm1_node_faulty)); ASSERT_ANY_THROW(jc1->serialize(tree)); jc1->setSensor(js_s); // this will be the node "generated" by the tree MockDescriptionTreeNode* _jc1_node = new MockDescriptionTreeNode; DescriptionTreeNode::Ptr jc1_node(_jc1_node); // and one for the sensot MockDescriptionTreeNode* _sensor_node = new MockDescriptionTreeNode; DescriptionTreeNode::Ptr sensor_node(_sensor_node); EXPECT_CALL(*_tree, createNode("JumpCondition")) .WillOnce(Return(jc1_node)); EXPECT_CALL(*_tree, createNode("Sensor")) .WillOnce(Return(sensor_node)); // Expect that exactly one child node = sensor will be added as child node EXPECT_CALL(*_jc1_node, addChildNode(_)) .Times(AtLeast(1)); EXPECT_CALL(*_sensor_node, addChildNode(_)) .Times(AtLeast(0)); // -> some properties (don't care) EXPECT_CALL(*_jc1_node, setAttributeString(_,_)) .Times(AtLeast(0)); EXPECT_CALL(*_sensor_node, setAttributeString(_,_)) .Times(AtLeast(0)); DescriptionTreeNode::Ptr jc_serialized; jc_serialized = jc1->serialize(tree); } TEST(JumpCondition, Activation) { using namespace ha; using namespace std; //------- // Serialized and deserialized sensor JumpConditionSerialization1::MockSystem* _ms = new JumpConditionSerialization1::MockSystem(); System::ConstPtr ms(_ms); JointConfigurationSensor* _js_s = new JointConfigurationSensor(); JointConfigurationSensor::Ptr js_s(_js_s); js_s->setSystem(ms); JumpCondition* _jc1 = new JumpCondition; JumpCondition::Ptr jc1(_jc1); jc1->setSensor(js_s); //The sensor reading of the system - we will mock it as constant ::Eigen::MatrixXd sensorMat(3,1); sensorMat<<1.0,1.0,1.0; EXPECT_CALL(*_ms, getConfiguration()) .WillRepeatedly(Return(sensorMat)); ///////////////////////////////////////////////// //test 1: invalid dimensions //The goal of the system - we will change it in this test ::Eigen::MatrixXd goalMat(2,1); goalMat<<1.0,2.0; jc1->setConstantGoal(goalMat); EXPECT_ANY_THROW(jc1->isActive()); goalMat.resize(1,3); goalMat<<1.0,2.0,3.0; jc1->setConstantGoal(goalMat); EXPECT_ANY_THROW(jc1->isActive()); //Also test for initialization goalMat.resize(3,1); goalMat<<1.0,2.0,3.0; jc1->setConstantGoal(goalMat); EXPECT_ANY_THROW(jc1->isActive()); jc1->initialize(0.0); ///////////////////////////////////////////////// //test 2: Norms //current sensor reading is (1.0,1.0,1.0) ::Eigen::MatrixXd weights(3,1); weights<<1.0,1.0,1.0; jc1->setJumpCriterion(JumpCondition::NORM_L1, weights); jc1->setEpsilon(0.1); goalMat.resize(3,1); goalMat<<1.1,1.0,1.01; jc1->setConstantGoal(goalMat); EXPECT_FALSE(jc1->isActive()); goalMat<<1.08,1.0,1.01; jc1->setConstantGoal(goalMat); EXPECT_TRUE(jc1->isActive()); //L_INF jc1->setJumpCriterion(JumpCondition::NORM_L_INF, weights); goalMat<<1.11,1.0,1.0; jc1->setConstantGoal(goalMat); EXPECT_FALSE(jc1->isActive()); goalMat<<1.09,1.09,1.09; jc1->setConstantGoal(goalMat); EXPECT_TRUE(jc1->isActive()); jc1->setEpsilon(0.0); //upper bound jc1->setJumpCriterion(JumpCondition::THRESH_UPPER_BOUND, weights); goalMat<<0.9,1.1,0.9; jc1->setConstantGoal(goalMat); EXPECT_FALSE(jc1->isActive()); goalMat<<0.9,0.9,0.9; jc1->setConstantGoal(goalMat); EXPECT_TRUE(jc1->isActive()); //lower bound jc1->setJumpCriterion(JumpCondition::THRESH_LOWER_BOUND, weights); goalMat<<0.9,1.1,1.1; jc1->setConstantGoal(goalMat); EXPECT_FALSE(jc1->isActive()); goalMat<<1.1,1.1,1.1; jc1->setConstantGoal(goalMat); EXPECT_TRUE(jc1->isActive()); //Now with weights (first entry does not matter) weights<<0.0,1.0,1.0; jc1->setJumpCriterion(JumpCondition::THRESH_LOWER_BOUND, weights); goalMat<<0.9,1.1,1.1; jc1->setConstantGoal(goalMat); EXPECT_TRUE(jc1->isActive()); goalMat<<1.1,0.9,1.1; jc1->setConstantGoal(goalMat); EXPECT_FALSE(jc1->isActive()); //Test the norm of the rotation OrientationSensor* _js_s = new JointConfigurationSensor(); JointConfigurationSensor::Ptr js_s(_js_s); js_s->setSystem(ms); JumpCondition* _jc1 = new JumpCondition; JumpCondition::Ptr jc1(_jc1); jc1->setSensor(js_s); jc1->setJumpCriterion(JumpCondition::NORM_ROTATION, weights); goalMat<<1.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0; jc1->setConstantGoal(goalMat); EXPECT_TRUE(jc1->isActive()); goalMat<<1.1,0.9,1.1; jc1->setConstantGoal(goalMat); EXPECT_FALSE(jc1->isActive()); } <commit_msg>jumpcondition_test now compiles<commit_after>#include "gtest/gtest.h" #include "gmock/gmock.h" #include <string> #include "hybrid_automaton/JumpCondition.h" #include "hybrid_automaton/DescriptionTreeNode.h" #include "hybrid_automaton/JointConfigurationSensor.h" #include "hybrid_automaton/FrameOrientationSensor.h" #include "hybrid_automaton/FrameDisplacementSensor.h" #include "hybrid_automaton/FramePoseSensor.h" #include "tests/MockDescriptionTree.h" #include "tests/MockDescriptionTreeNode.h" using ::testing::Return; using ::testing::DoAll; using ::testing::SetArgReferee; using ::testing::AtLeast; using ::testing::_; using namespace ::ha; namespace JumpConditionSerialization1 { class MockSystem : public ha::System { public: MOCK_CONST_METHOD0(getDof, int () ); MOCK_CONST_METHOD0(getConfiguration, ::Eigen::MatrixXd () ); MOCK_CONST_METHOD0(getForceTorqueMeasurement, ::Eigen::MatrixXd () ); MOCK_CONST_METHOD0(getCurrentTime, ::Eigen::MatrixXd () ); MOCK_CONST_METHOD1(getFramePose, ::Eigen::MatrixXd (const std::string& frame_id) ); }; } TEST(JumpCondition, Serialization) { using namespace ha; using namespace std; //------- // Serialized and deserialized sensor System::ConstPtr _ms = System::ConstPtr(new JumpConditionSerialization1::MockSystem()); JointConfigurationSensorPtr js_s = JointConfigurationSensorPtr(new JointConfigurationSensor()); js_s->setSystem(_ms); // Mocked description returned by jump condition MockDescriptionTreeNode* _jc_node = new MockDescriptionTreeNode; DescriptionTreeNode::Ptr jc_node(_jc_node); EXPECT_CALL(*_jc_node, getType()).WillRepeatedly(Return("JumpCondition")); EXPECT_CALL(*_jc_node, getAttributeString(_, _)) .WillRepeatedly(DoAll(SetArgReferee<1>(""),Return(true))); //------- // TEST ControlMode // Mocked tree factory MockDescriptionTree* _tree = new MockDescriptionTree; MockDescriptionTree::Ptr tree(_tree); JumpCondition* _jc1 = new JumpCondition; JumpCondition::Ptr jc1(_jc1); MockDescriptionTreeNode::Ptr cm1_node_faulty(new MockDescriptionTreeNode); EXPECT_CALL(*cm1_node_faulty, setAttributeString(_,_)) .Times(AtLeast(0)); // assert throwing of exception if no sensor has been set EXPECT_CALL(*_tree, createNode("JumpCondition")) .WillOnce(Return(cm1_node_faulty)); ASSERT_ANY_THROW(jc1->serialize(tree)); jc1->setSensor(js_s); // this will be the node "generated" by the tree MockDescriptionTreeNode* _jc1_node = new MockDescriptionTreeNode; DescriptionTreeNode::Ptr jc1_node(_jc1_node); // and one for the sensot MockDescriptionTreeNode* _sensor_node = new MockDescriptionTreeNode; DescriptionTreeNode::Ptr sensor_node(_sensor_node); EXPECT_CALL(*_tree, createNode("JumpCondition")) .WillOnce(Return(jc1_node)); EXPECT_CALL(*_tree, createNode("Sensor")) .WillOnce(Return(sensor_node)); // Expect that exactly one child node = sensor will be added as child node EXPECT_CALL(*_jc1_node, addChildNode(_)) .Times(AtLeast(1)); EXPECT_CALL(*_sensor_node, addChildNode(_)) .Times(AtLeast(0)); // -> some properties (don't care) EXPECT_CALL(*_jc1_node, setAttributeString(_,_)) .Times(AtLeast(0)); EXPECT_CALL(*_sensor_node, setAttributeString(_,_)) .Times(AtLeast(0)); DescriptionTreeNode::Ptr jc_serialized; jc_serialized = jc1->serialize(tree); } TEST(JumpCondition, Activation) { using namespace ha; using namespace std; //------- // Serialized and deserialized sensor JumpConditionSerialization1::MockSystem* _ms = new JumpConditionSerialization1::MockSystem(); System::ConstPtr ms(_ms); JointConfigurationSensor* _js_s = new JointConfigurationSensor(); JointConfigurationSensor::Ptr js_s(_js_s); js_s->setSystem(ms); JumpCondition* _jc1 = new JumpCondition; JumpCondition::Ptr jc1(_jc1); jc1->setSensor(js_s); //The sensor reading of the system - we will mock it as constant ::Eigen::MatrixXd sensorMat(3,1); sensorMat<<1.0,1.0,1.0; EXPECT_CALL(*_ms, getConfiguration()) .WillRepeatedly(Return(sensorMat)); ///////////////////////////////////////////////// //test 1: invalid dimensions //The goal of the system - we will change it in this test ::Eigen::MatrixXd goalMat(2,1); goalMat<<1.0,2.0; jc1->setConstantGoal(goalMat); EXPECT_ANY_THROW(jc1->isActive()); goalMat.resize(1,3); goalMat<<1.0,2.0,3.0; jc1->setConstantGoal(goalMat); EXPECT_ANY_THROW(jc1->isActive()); //Also test for initialization goalMat.resize(3,1); goalMat<<1.0,2.0,3.0; jc1->setConstantGoal(goalMat); EXPECT_ANY_THROW(jc1->isActive()); jc1->initialize(0.0); ///////////////////////////////////////////////// //test 2: Norms //current sensor reading is (1.0,1.0,1.0) ::Eigen::MatrixXd weights(3,1); weights<<1.0,1.0,1.0; jc1->setJumpCriterion(JumpCondition::NORM_L1, weights); jc1->setEpsilon(0.1); goalMat.resize(3,1); goalMat<<1.1,1.0,1.01; jc1->setConstantGoal(goalMat); EXPECT_FALSE(jc1->isActive()); goalMat<<1.08,1.0,1.01; jc1->setConstantGoal(goalMat); EXPECT_TRUE(jc1->isActive()); //L_INF jc1->setJumpCriterion(JumpCondition::NORM_L_INF, weights); goalMat<<1.11,1.0,1.0; jc1->setConstantGoal(goalMat); EXPECT_FALSE(jc1->isActive()); goalMat<<1.09,1.09,1.09; jc1->setConstantGoal(goalMat); EXPECT_TRUE(jc1->isActive()); jc1->setEpsilon(0.0); //upper bound jc1->setJumpCriterion(JumpCondition::THRESH_UPPER_BOUND, weights); goalMat<<0.9,1.1,0.9; jc1->setConstantGoal(goalMat); EXPECT_FALSE(jc1->isActive()); goalMat<<0.9,0.9,0.9; jc1->setConstantGoal(goalMat); EXPECT_TRUE(jc1->isActive()); //lower bound jc1->setJumpCriterion(JumpCondition::THRESH_LOWER_BOUND, weights); goalMat<<0.9,1.1,1.1; jc1->setConstantGoal(goalMat); EXPECT_FALSE(jc1->isActive()); goalMat<<1.1,1.1,1.1; jc1->setConstantGoal(goalMat); EXPECT_TRUE(jc1->isActive()); //Now with weights (first entry does not matter) weights<<0.0,1.0,1.0; jc1->setJumpCriterion(JumpCondition::THRESH_LOWER_BOUND, weights); goalMat<<0.9,1.1,1.1; jc1->setConstantGoal(goalMat); EXPECT_TRUE(jc1->isActive()); goalMat<<1.1,0.9,1.1; jc1->setConstantGoal(goalMat); EXPECT_FALSE(jc1->isActive()); //Test the norm of the rotation FrameOrientationSensor* _fo_s = new FrameOrientationSensor(); FrameOrientationSensor::Ptr fo_s(_fo_s); fo_s->setSystem(ms); JumpCondition* _jc2 = new JumpCondition; JumpCondition::Ptr jc2(_jc2); jc2->setSensor(fo_s); jc2->setJumpCriterion(JumpCondition::NORM_ROTATION, weights); goalMat<<1.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0; jc2->setConstantGoal(goalMat); EXPECT_TRUE(jc2->isActive()); goalMat<<1.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0; jc2->setConstantGoal(goalMat); EXPECT_FALSE(jc2->isActive()); } <|endoftext|>
<commit_before>#include <cstring> #include <inttypes.h> #include <math.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #ifndef JSON_TEST_NUMBERS #define JSON_TEST_NUMBERS #endif #if (!(_MSC_VER) && !(__MINGW32__) && !(__MINGW64__)) #include <dirent.h> #else #include <dirent_portable.h> #endif #include "simdjson.h" // ulp distance // Marc B. Reynolds, 2016-2019 // Public Domain under http://unlicense.org, see link for details. // adapted by D. Lemire inline uint32_t f32_ulp_dist(float a, float b) { uint32_t ua, ub; memcpy(&ua, &a, sizeof(ua)); memcpy(&ub, &b, sizeof(ub)); if ((int32_t)(ub ^ ua) >= 0) return (int32_t)(ua - ub) >= 0 ? (ua - ub) : (ub - ua); return ua + ub + 0x80000000; } // ulp distance // Marc B. Reynolds, 2016-2019 // Public Domain under http://unlicense.org, see link for details. // adapted by D. Lemire inline uint64_t f64_ulp_dist(double a, double b) { uint64_t ua, ub; memcpy(&ua, &a, sizeof(ua)); memcpy(&ub, &b, sizeof(ub)); if ((int64_t)(ub ^ ua) >= 0) return (int64_t)(ua - ub) >= 0 ? (ua - ub) : (ub - ua); return ua + ub + 0x80000000; } int parse_error; char *fullpath; enum { PARSE_WARNING, PARSE_ERROR }; size_t float_count; size_t int_count; size_t invalid_count; // strings that start with these should not be parsed as numbers const char *really_bad[] = {"013}", "0x14", "0e]", "0e+]", "0e+-1]"}; bool starts_with(const char *pre, const char *str) { size_t lenpre = std::strlen(pre); return strncmp(pre, str, lenpre) == 0; } bool is_in_bad_list(const char *buf) { if (buf[0] != '0') return false; for (size_t i = 0; i < sizeof(really_bad) / sizeof(really_bad[0]); i++) if (starts_with(really_bad[i], buf)) return true; return false; } void found_invalid_number(const uint8_t *buf) { invalid_count++; char *endptr; #ifdef _WIN32 static _locale_t c_locale = _create_locale(LC_ALL, "C"); double expected = _strtod_l((const char *)buf, &endptr, c_locale); #else static locale_t c_locale = newlocale(LC_ALL_MASK, "C", NULL); double expected = strtod_l((const char *)buf, &endptr, c_locale); #endif if (endptr != (const char *)buf) { if (!is_in_bad_list((const char *)buf)) { printf("Warning: found_invalid_number %.32s whereas strtod parses it to " "%f, ", buf, expected); printf(" while parsing %s \n", fullpath); parse_error |= PARSE_WARNING; } } } void found_integer(int64_t result, const uint8_t *buf) { int_count++; char *endptr; long long expected = strtoll((const char *)buf, &endptr, 10); if ((endptr == (const char *)buf) || (expected != result)) { #if (!(__MINGW32__) && !(__MINGW64__)) fprintf(stderr, "Error: parsed %" PRId64 " out of %.32s, ", result, buf); #else // mingw is busted since we include #include <inttypes.h> fprintf(stderr, "Error: parsed %lld out of %.32s, ", (long long)result, buf); #endif fprintf(stderr, " while parsing %s \n", fullpath); parse_error |= PARSE_ERROR; } } void found_unsigned_integer(uint64_t result, const uint8_t *buf) { int_count++; char *endptr; unsigned long long expected = strtoull((const char *)buf, &endptr, 10); if ((endptr == (const char *)buf) || (expected != result)) { #if (!(__MINGW32__) && !(__MINGW64__)) fprintf(stderr, "Error: parsed %" PRIu64 " out of %.32s, ", result, buf); #else // mingw is busted since we include #include <inttypes.h> fprintf(stderr, "Error: parsed %llu out of %.32s, ", (unsigned long long)result, buf); #endif fprintf(stderr, " while parsing %s \n", fullpath); parse_error |= PARSE_ERROR; } } void found_float(double result, const uint8_t *buf) { char *endptr; float_count++; #ifdef _WIN32 static _locale_t c_locale = _create_locale(LC_ALL, "C"); double expected = _strtod_l((const char *)buf, &endptr, c_locale); #else static locale_t c_locale = newlocale(LC_ALL_MASK, "C", NULL); double expected = strtod_l((const char *)buf, &endptr, c_locale); #endif if (endptr == (const char *)buf) { fprintf(stderr, "parsed %f from %.32s whereas strtod refuses to parse a float, ", result, buf); fprintf(stderr, " while parsing %s \n", fullpath); parse_error |= PARSE_ERROR; } if (fpclassify(expected) != fpclassify(result)) { fprintf(stderr, "floats not in the same category expected: %f observed: %f \n", expected, result); fprintf(stderr, "%.32s\n", buf); parse_error |= PARSE_ERROR; return; } if (expected != result) { fprintf(stderr, "parsed %.128e from \n", result); fprintf(stderr, " %.32s whereas strtod gives\n", buf); fprintf(stderr, " %.128e,", expected); fprintf(stderr, " while parsing %s \n", fullpath); fprintf(stderr, " =========== ULP: %u,", (unsigned int)f64_ulp_dist(expected, result)); parse_error |= PARSE_ERROR; } } #include "simdjson.h" #include "simdjson.cpp" /** * Does the file filename ends with the given extension. */ static bool has_extension(const char *filename, const char *extension) { const char *ext = strrchr(filename, '.'); return (ext && !strcmp(ext, extension)); } bool validate(const char *dirname) { parse_error = 0; size_t total_count = 0; const char *extension = ".json"; size_t dirlen = std::strlen(dirname); struct dirent **entry_list; int c = scandir(dirname, &entry_list, 0, alphasort); if (c < 0) { printf("error accessing %s \n", dirname); return false; } if (c == 0) { printf("nothing in dir %s \n", dirname); return false; } bool needsep = (strlen(dirname) > 1) && (dirname[strlen(dirname) - 1] != '/'); for (int i = 0; i < c; i++) { const char *name = entry_list[i]->d_name; if (has_extension(name, extension)) { size_t filelen = std::strlen(name); fullpath = (char *)malloc(dirlen + filelen + 1 + 1); strcpy(fullpath, dirname); if (needsep) { fullpath[dirlen] = '/'; strcpy(fullpath + dirlen + 1, name); } else { strcpy(fullpath + dirlen, name); } simdjson::padded_string p; auto error = simdjson::padded_string::load(fullpath).get(p); if (error) { std::cerr << "Could not load the file " << fullpath << std::endl; return EXIT_FAILURE; } // terrible hack but just to get it working float_count = 0; int_count = 0; invalid_count = 0; total_count += float_count + int_count + invalid_count; simdjson::dom::parser parser; auto err = parser.parse(p).error(); bool isok = (err == simdjson::error_code::SUCCESS); if (int_count + float_count + invalid_count > 0) { printf("File %40s %s --- integers: %10zu floats: %10zu invalid: %10zu " "total numbers: %10zu \n", name, isok ? " is valid " : " is not valid ", int_count, float_count, invalid_count, int_count + float_count + invalid_count); } free(fullpath); } } if ((parse_error & PARSE_ERROR) != 0) { printf("NUMBER PARSING FAILS?\n"); } else { printf("All ok.\n"); } for (int i = 0; i < c; ++i) free(entry_list[i]); free(entry_list); return ((parse_error & PARSE_ERROR) == 0); } int main(int argc, char *argv[]) { if (argc != 2) { std::cerr << "Usage: " << argv[0] << " <directorywithjsonfiles>" << std::endl; #if defined(SIMDJSON_TEST_DATA_DIR) && defined(SIMDJSON_BENCHMARK_DATA_DIR) std::cout << "We are going to assume you mean to use the '" << SIMDJSON_TEST_DATA_DIR << "' and '" << SIMDJSON_BENCHMARK_DATA_DIR << "'directories." << std::endl; return validate(SIMDJSON_TEST_DATA_DIR) && validate(SIMDJSON_BENCHMARK_DATA_DIR) ? EXIT_SUCCESS : EXIT_FAILURE; #else std::cout << "We are going to assume you mean to use the 'jsonchecker' and " "'jsonexamples' directories." << std::endl; return validate("jsonchecker/") && validate("jsonexamples/") ? EXIT_SUCCESS : EXIT_FAILURE; #endif } return validate(argv[1]) ? EXIT_SUCCESS : EXIT_FAILURE; } <commit_msg>Fix numberparsingcheck to define found_invalid_number before simdjson.h<commit_after>#include <cstring> #include <inttypes.h> #include <math.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #ifndef JSON_TEST_NUMBERS #define JSON_TEST_NUMBERS #endif #if (!(_MSC_VER) && !(__MINGW32__) && !(__MINGW64__)) #include <dirent.h> #else #include <dirent_portable.h> #endif void found_invalid_number(const uint8_t *buf); void found_float(double result, const uint8_t *buf); void found_integer(int64_t result, const uint8_t *buf); void found_unsigned_integer(uint64_t result, const uint8_t *buf); #include "simdjson.h" // ulp distance // Marc B. Reynolds, 2016-2019 // Public Domain under http://unlicense.org, see link for details. // adapted by D. Lemire inline uint32_t f32_ulp_dist(float a, float b) { uint32_t ua, ub; memcpy(&ua, &a, sizeof(ua)); memcpy(&ub, &b, sizeof(ub)); if ((int32_t)(ub ^ ua) >= 0) return (int32_t)(ua - ub) >= 0 ? (ua - ub) : (ub - ua); return ua + ub + 0x80000000; } // ulp distance // Marc B. Reynolds, 2016-2019 // Public Domain under http://unlicense.org, see link for details. // adapted by D. Lemire inline uint64_t f64_ulp_dist(double a, double b) { uint64_t ua, ub; memcpy(&ua, &a, sizeof(ua)); memcpy(&ub, &b, sizeof(ub)); if ((int64_t)(ub ^ ua) >= 0) return (int64_t)(ua - ub) >= 0 ? (ua - ub) : (ub - ua); return ua + ub + 0x80000000; } int parse_error; char *fullpath; enum { PARSE_WARNING, PARSE_ERROR }; size_t float_count; size_t int_count; size_t invalid_count; // strings that start with these should not be parsed as numbers const char *really_bad[] = {"013}", "0x14", "0e]", "0e+]", "0e+-1]"}; bool starts_with(const char *pre, const char *str) { size_t lenpre = std::strlen(pre); return strncmp(pre, str, lenpre) == 0; } bool is_in_bad_list(const char *buf) { if (buf[0] != '0') return false; for (size_t i = 0; i < sizeof(really_bad) / sizeof(really_bad[0]); i++) if (starts_with(really_bad[i], buf)) return true; return false; } void found_invalid_number(const uint8_t *buf) { invalid_count++; char *endptr; #ifdef _WIN32 static _locale_t c_locale = _create_locale(LC_ALL, "C"); double expected = _strtod_l((const char *)buf, &endptr, c_locale); #else static locale_t c_locale = newlocale(LC_ALL_MASK, "C", NULL); double expected = strtod_l((const char *)buf, &endptr, c_locale); #endif if (endptr != (const char *)buf) { if (!is_in_bad_list((const char *)buf)) { printf("Warning: found_invalid_number %.32s whereas strtod parses it to " "%f, ", buf, expected); printf(" while parsing %s \n", fullpath); parse_error |= PARSE_WARNING; } } } void found_integer(int64_t result, const uint8_t *buf) { int_count++; char *endptr; long long expected = strtoll((const char *)buf, &endptr, 10); if ((endptr == (const char *)buf) || (expected != result)) { #if (!(__MINGW32__) && !(__MINGW64__)) fprintf(stderr, "Error: parsed %" PRId64 " out of %.32s, ", result, buf); #else // mingw is busted since we include #include <inttypes.h> fprintf(stderr, "Error: parsed %lld out of %.32s, ", (long long)result, buf); #endif fprintf(stderr, " while parsing %s \n", fullpath); parse_error |= PARSE_ERROR; } } void found_unsigned_integer(uint64_t result, const uint8_t *buf) { int_count++; char *endptr; unsigned long long expected = strtoull((const char *)buf, &endptr, 10); if ((endptr == (const char *)buf) || (expected != result)) { #if (!(__MINGW32__) && !(__MINGW64__)) fprintf(stderr, "Error: parsed %" PRIu64 " out of %.32s, ", result, buf); #else // mingw is busted since we include #include <inttypes.h> fprintf(stderr, "Error: parsed %llu out of %.32s, ", (unsigned long long)result, buf); #endif fprintf(stderr, " while parsing %s \n", fullpath); parse_error |= PARSE_ERROR; } } void found_float(double result, const uint8_t *buf) { char *endptr; float_count++; #ifdef _WIN32 static _locale_t c_locale = _create_locale(LC_ALL, "C"); double expected = _strtod_l((const char *)buf, &endptr, c_locale); #else static locale_t c_locale = newlocale(LC_ALL_MASK, "C", NULL); double expected = strtod_l((const char *)buf, &endptr, c_locale); #endif if (endptr == (const char *)buf) { fprintf(stderr, "parsed %f from %.32s whereas strtod refuses to parse a float, ", result, buf); fprintf(stderr, " while parsing %s \n", fullpath); parse_error |= PARSE_ERROR; } if (fpclassify(expected) != fpclassify(result)) { fprintf(stderr, "floats not in the same category expected: %f observed: %f \n", expected, result); fprintf(stderr, "%.32s\n", buf); parse_error |= PARSE_ERROR; return; } if (expected != result) { fprintf(stderr, "parsed %.128e from \n", result); fprintf(stderr, " %.32s whereas strtod gives\n", buf); fprintf(stderr, " %.128e,", expected); fprintf(stderr, " while parsing %s \n", fullpath); fprintf(stderr, " =========== ULP: %u,", (unsigned int)f64_ulp_dist(expected, result)); parse_error |= PARSE_ERROR; } } #include "simdjson.h" #include "simdjson.cpp" /** * Does the file filename ends with the given extension. */ static bool has_extension(const char *filename, const char *extension) { const char *ext = strrchr(filename, '.'); return (ext && !strcmp(ext, extension)); } bool validate(const char *dirname) { parse_error = 0; size_t total_count = 0; const char *extension = ".json"; size_t dirlen = std::strlen(dirname); struct dirent **entry_list; int c = scandir(dirname, &entry_list, 0, alphasort); if (c < 0) { printf("error accessing %s \n", dirname); return false; } if (c == 0) { printf("nothing in dir %s \n", dirname); return false; } bool needsep = (strlen(dirname) > 1) && (dirname[strlen(dirname) - 1] != '/'); for (int i = 0; i < c; i++) { const char *name = entry_list[i]->d_name; if (has_extension(name, extension)) { size_t filelen = std::strlen(name); fullpath = (char *)malloc(dirlen + filelen + 1 + 1); strcpy(fullpath, dirname); if (needsep) { fullpath[dirlen] = '/'; strcpy(fullpath + dirlen + 1, name); } else { strcpy(fullpath + dirlen, name); } simdjson::padded_string p; auto error = simdjson::padded_string::load(fullpath).get(p); if (error) { std::cerr << "Could not load the file " << fullpath << std::endl; return EXIT_FAILURE; } // terrible hack but just to get it working float_count = 0; int_count = 0; invalid_count = 0; total_count += float_count + int_count + invalid_count; simdjson::dom::parser parser; auto err = parser.parse(p).error(); bool isok = (err == simdjson::error_code::SUCCESS); if (int_count + float_count + invalid_count > 0) { printf("File %40s %s --- integers: %10zu floats: %10zu invalid: %10zu " "total numbers: %10zu \n", name, isok ? " is valid " : " is not valid ", int_count, float_count, invalid_count, int_count + float_count + invalid_count); } free(fullpath); } } if ((parse_error & PARSE_ERROR) != 0) { printf("NUMBER PARSING FAILS?\n"); } else { printf("All ok.\n"); } for (int i = 0; i < c; ++i) free(entry_list[i]); free(entry_list); return ((parse_error & PARSE_ERROR) == 0); } int main(int argc, char *argv[]) { if (argc != 2) { std::cerr << "Usage: " << argv[0] << " <directorywithjsonfiles>" << std::endl; #if defined(SIMDJSON_TEST_DATA_DIR) && defined(SIMDJSON_BENCHMARK_DATA_DIR) std::cout << "We are going to assume you mean to use the '" << SIMDJSON_TEST_DATA_DIR << "' and '" << SIMDJSON_BENCHMARK_DATA_DIR << "'directories." << std::endl; return validate(SIMDJSON_TEST_DATA_DIR) && validate(SIMDJSON_BENCHMARK_DATA_DIR) ? EXIT_SUCCESS : EXIT_FAILURE; #else std::cout << "We are going to assume you mean to use the 'jsonchecker' and " "'jsonexamples' directories." << std::endl; return validate("jsonchecker/") && validate("jsonexamples/") ? EXIT_SUCCESS : EXIT_FAILURE; #endif } return validate(argv[1]) ? EXIT_SUCCESS : EXIT_FAILURE; } <|endoftext|>
<commit_before>#include <stdio.h> #include <sstream> #include <cstdlib> #include <cstring> #include <set> #include <string> #include <iostream> #include <unistd.h> #include "Compile.h" #include "Parser.h" int run_on_bash(std::istream &is) { FILE *bash = popen("bash", "w"); char buf[4096]; do { is.read(buf, sizeof(buf)); fwrite(buf, 1, is.gcount(), bash); } while (is.gcount() > 0); fflush(bash); int e = pclose(bash)/256; return e; } void usage(char *argv0) { std::cerr << "USAGE: " << argv0 << " [-r] <INPUT>\n"; std::cerr << " Compiles Bish file <INPUT> to bash.\n"; std::cerr << "\nOPTIONS:\n"; std::cerr << " -r: compiles and runs the file.\n"; } int main(int argc, char **argv) { if (argc < 2) { usage(argv[0]); return 1; } int c; bool run_after_compile = false; while ((c = getopt(argc,argv, "r")) != -1) { switch (c) { case 'r': run_after_compile = true; break; default: break; } } if (optind == argc && run_after_compile) { std::cerr << "-r needs a filename" << std::endl; return 1; } std::string path(argv[optind]); Bish::Parser p; Bish::Module *m = p.parse(path); std::stringstream s; Bish::compile_to_bash(run_after_compile ? s : std::cout, m); if (run_after_compile) { int exit_status = 0; exit_status = run_on_bash(s); exit(exit_status); } return 0; } <commit_msg>Make getting the exit status more clear<commit_after>#include <stdio.h> #include <sstream> #include <cstdlib> #include <cstring> #include <set> #include <string> #include <iostream> #include <unistd.h> #include "Compile.h" #include "Parser.h" int run_on_bash(std::istream &is) { FILE *bash = popen("bash", "w"); char buf[4096]; do { is.read(buf, sizeof(buf)); fwrite(buf, 1, is.gcount(), bash); } while (is.gcount() > 0); fflush(bash); // pclose returns the exit status of the process, // but shifted to the left by 8 bits. int e = pclose(bash) >> 8; return e; } void usage(char *argv0) { std::cerr << "USAGE: " << argv0 << " [-r] <INPUT>\n"; std::cerr << " Compiles Bish file <INPUT> to bash.\n"; std::cerr << "\nOPTIONS:\n"; std::cerr << " -r: compiles and runs the file.\n"; } int main(int argc, char **argv) { if (argc < 2) { usage(argv[0]); return 1; } int c; bool run_after_compile = false; while ((c = getopt(argc,argv, "r")) != -1) { switch (c) { case 'r': run_after_compile = true; break; default: break; } } if (optind == argc && run_after_compile) { std::cerr << "-r needs a filename" << std::endl; return 1; } std::string path(argv[optind]); Bish::Parser p; Bish::Module *m = p.parse(path); std::stringstream s; Bish::compile_to_bash(run_after_compile ? s : std::cout, m); if (run_after_compile) { int exit_status = 0; exit_status = run_on_bash(s); exit(exit_status); } return 0; } <|endoftext|>
<commit_before>/* This file is part of Groho, a simulator for inter-planetary travel and warfare. Copyright (c) 2017-2018 by Kaushik Ghose. Some rights reserved, see LICENSE We have two types of objects in the simulation - Orrery bodies (planets/moons/asteroid) and spaceships. They have some metadata in common and some that are unique. To simplify our first iteration we combine all the metadata and state information and use a unifed system with a type flag to indicate what type of object we are refering to. This determines which fields make sense to access. */ #pragma once #include <cstdint> #include <optional> #include <string> #include <vector> #include "spkid.hpp" #include "vector.hpp" namespace sim { enum BodyType { ROCK, BARYCENTER, SPACESHIP }; enum FlightState { FALLING, LANDED }; struct BodyConstant { BodyType body_type; int code; // SPK code for body (made up ones for spaceships) std::string name; // Human readable name for body float GM; // GM value for body float r; // Radius of body (for collision tests) uint32_t color; // For display purposes }; struct ShipCharacteristic { float max_acc; // Maximum acceleration possible for ship m/s^2 float max_fuel; // Maximum fuel reserve (U) float burn_rate; // Fuel consumption rate (U/ (m/s^2)) }; struct BodyState { double t; Vector pos; // Position referenced to solar system barycenter Vector vel; // Velocity Vector att; // Attitude float acc; // Current acceleration km/s^2 float fuel; // Current fuel reserve (U) FlightState flight_state; }; struct Body { BodyConstant property; ShipCharacteristic param; BodyState state; }; inline std::optional<size_t> body_index(const std::vector<Body>& bodies, spkid_t spkid) { for (size_t i = 0; i < bodies.size(); i++) { if (bodies[i].property.code == spkid.id) { return i; } } return {}; } } <commit_msg>refactor: Separate out Rock and Ship<commit_after>/* This file is part of Groho, a simulator for inter-planetary travel and warfare. Copyright (c) 2017-2018 by Kaushik Ghose. Some rights reserved, see LICENSE We have two types of objects in the simulation - Orrery bodies (planets/moons/asteroid) and spaceships. They behave quite differently and are described as separate classes of objects with some elements in common */ #pragma once #include <cstdint> #include <optional> #include <string> #include <vector> #include "naifbody.hpp" #include "vector.hpp" namespace sim { struct Rock { struct Property { NAIFbody naif; float GM; // GM value for body float r; // Radius of body (for collision tests) uint32_t color; // For display purposes } property; struct State { Vector pos; // Position referenced to solar system barycenter Vector vel; // Velocity double t_s; } state; }; struct Ship { struct Property { NAIFbody naif; float max_acc; // Maximum acceleration possible for ship m/s^2 float max_fuel; // Maximum fuel reserve (U) float burn_rate; // Fuel consumption rate (U/ (m/s^2)) uint32_t color; // For display purposes } property; struct State { Vector pos; // Position referenced to solar system barycenter Vector vel; // Velocity Vector att; // Attitude float fuel; // Current fuel reserve (U) float acc; // Current acceleration km/s^2 double t_s; } state; }; template <typename T> inline std::optional<size_t> find(const std::vector<T>& bodies, const NAIFbody& naif) { for (size_t i = 0; i < bodies.size(); i++) { if (bodies[i].naif == naif) { return i; } } return {}; } } <|endoftext|>
<commit_before>#include <taichi/common/util.h> #include <taichi/common/task.h> #include <taichi/visual/gui.h> TC_NAMESPACE_BEGIN constexpr int n = 100; constexpr real dx = 1.0_f / n; constexpr real c = 340; constexpr real alpha = 0.001; Array2D<real> p, q, r; void advance(real dt) { r.reset_zero(); constexpr real inv_dx2 = pow<2>(1.0_f / dx); for (int i = 1; i < n - 1; i++) { for (int j = 1; j < n - 1; j++) { real laplacian_p = inv_dx2 * (p[i - 1][j] + p[i][j - 1] + p[i + 1][j] + p[i][j + 1] - 4 * p[i][j]); real laplacian_q = inv_dx2 * (q[i - 1][j] + q[i][j - 1] + q[i + 1][j] + q[i][j + 1] - 4 * q[i][j]); r[i][j] = 2 * q[i][j] + (c * c * dt * dt + c * alpha * dt) * laplacian_q - p[i][j] - c * alpha * dt * laplacian_p; } } std::swap(p.data, q.data); std::swap(q.data, r.data); } auto sound = []() { int window_size = 800; int scale = window_size / n; q.initialize(Vector2i(n)); p = r = q; GUI gui("Sound simulation", Vector2i(window_size)); real t = 0, dt = (std::sqrt(alpha * alpha + dx * dx / 3) - alpha) / c; // p[n / 2][n / 2] = std::sin(t); p[n / 2][n / 2] = 1; while (1) { for (int i = 0; i < 10; i++) { advance(dt); } t += dt; for (int i = 0; i < window_size; i++) { for (int j = 0; j < window_size; j++) { auto c = p[i / scale][j / scale]; gui.get_canvas().img[i][j] = Vector3(c + 0.5_f); } } gui.update(); } }; TC_REGISTER_TASK(sound); TC_NAMESPACE_END <commit_msg>input sound<commit_after>#include <taichi/common/util.h> #include <taichi/common/task.h> #include <taichi/visual/gui.h> TC_NAMESPACE_BEGIN constexpr int n = 100; constexpr real room_size = 20.0_f; constexpr real dx = room_size / n; constexpr real c = 340; constexpr real alpha = 0.001; Array2D<real> p, q, r; void advance(real dt) { r.reset_zero(); constexpr real inv_dx2 = pow<2>(1.0_f / dx); for (int i = 1; i < n - 1; i++) { for (int j = 1; j < n - 1; j++) { real laplacian_p = inv_dx2 * (p[i - 1][j] + p[i][j - 1] + p[i + 1][j] + p[i][j + 1] - 4 * p[i][j]); real laplacian_q = inv_dx2 * (q[i - 1][j] + q[i][j - 1] + q[i + 1][j] + q[i][j + 1] - 4 * q[i][j]); r[i][j] = 2 * q[i][j] + (c * c * dt * dt + c * alpha * dt) * laplacian_q - p[i][j] - c * alpha * dt * laplacian_p; } } std::swap(p.data, q.data); std::swap(q.data, r.data); } auto sound = []() { int window_size = 800; int scale = window_size / n; q.initialize(Vector2i(n)); p = r = q; GUI gui("Sound simulation", Vector2i(window_size)); real t = 0, dt = (std::sqrt(alpha * alpha + dx * dx / 3) - alpha) / c; // p[n / 2][n / 2] = std::sin(t); FILE *f = fopen("data/wave.txt", "r"); while (1) { for (int i = 0; i < 1000; i++) { real l, r; fscanf(f, "%f%f", &l, &r); q[n / 2][n / 2] = (l + r) / 65536.0; advance(dt); } t += dt; for (int i = 0; i < window_size; i++) { for (int j = 0; j < window_size; j++) { auto c = p[i / scale][j / scale]; gui.get_canvas().img[i][j] = Vector3(c + 0.5_f); } } gui.update(); } }; TC_REGISTER_TASK(sound); TC_NAMESPACE_END <|endoftext|>
<commit_before>// Copyright (c) 2014-2017 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "spork.h" #include "base58.h" #include "chainparams.h" #include "validation.h" #include "messagesigner.h" #include "net_processing.h" #include "netmessagemaker.h" #include <boost/lexical_cast.hpp> CSporkManager sporkManager; std::map<uint256, CSporkMessage> mapSporks; std::map<int, int64_t> mapSporkDefaults = { {SPORK_2_INSTANTSEND_ENABLED, 0}, // ON {SPORK_3_INSTANTSEND_BLOCK_FILTERING, 0}, // ON {SPORK_5_INSTANTSEND_MAX_VALUE, 100000}, // 100000 Syscoin {SPORK_6_NEW_SIGS, 0}, // ON {SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT, 0}, // ON {SPORK_9_SUPERBLOCKS_ENABLED, 0}, // ON {SPORK_10_MASTERNODE_PAY_UPDATED_NODES, 0}, // ON {SPORK_12_RECONSIDER_BLOCKS, 0}, // 0 BLOCKS {SPORK_14_REQUIRE_SENTINEL_FLAG, 0}, // ON }; void CSporkManager::ProcessSpork(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, CConnman& connman) { if(fLiteMode) return; // disable all Syscoin specific functionality if (strCommand == NetMsgType::SPORK) { CSporkMessage spork; vRecv >> spork; uint256 hash = spork.GetHash(); std::string strLogMsg; { LOCK(cs_main); pfrom->setAskFor.erase(hash); if(!chainActive.Tip()) return; strLogMsg = strprintf("SPORK -- hash: %s id: %d value: %10d bestHeight: %d peer=%d", hash.ToString(), spork.nSporkID, spork.nValue, chainActive.Height(), pfrom->id); } if(mapSporksActive.count(spork.nSporkID)) { if (mapSporksActive[spork.nSporkID].nTimeSigned >= spork.nTimeSigned) { LogPrint("spork", "%s seen\n", strLogMsg); return; } else { LogPrintf("%s updated\n", strLogMsg); } } else { LogPrintf("%s new\n", strLogMsg); } if(!spork.CheckSignature(sporkPubKeyID)) { LOCK(cs_main); LogPrintf("CSporkManager::ProcessSpork -- ERROR: invalid signature\n"); Misbehaving(pfrom->GetId(), 100); return; } mapSporks[hash] = spork; mapSporksActive[spork.nSporkID] = spork; spork.Relay(connman); //does a task if needed ExecuteSpork(spork.nSporkID, spork.nValue); } else if (strCommand == NetMsgType::GETSPORKS) { std::map<int, CSporkMessage>::iterator it = mapSporksActive.begin(); while(it != mapSporksActive.end()) { connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::SPORK, it->second)); it++; } } } void CSporkManager::ExecuteSpork(int nSporkID, int nValue) { //correct fork via spork technology if(nSporkID == SPORK_12_RECONSIDER_BLOCKS && nValue > 0) { // allow to reprocess 24h of blocks max, which should be enough to resolve any issues int64_t nMaxBlocks = 1440; // this potentially can be a heavy operation, so only allow this to be executed once per 10 minutes int64_t nTimeout = 10 * 60; static int64_t nTimeExecuted = 0; // i.e. it was never executed before if(GetTime() - nTimeExecuted < nTimeout) { LogPrint("spork", "CSporkManager::ExecuteSpork -- ERROR: Trying to reconsider blocks, too soon - %d/%d\n", GetTime() - nTimeExecuted, nTimeout); return; } if(nValue > nMaxBlocks) { LogPrintf("CSporkManager::ExecuteSpork -- ERROR: Trying to reconsider too many blocks %d/%d\n", nValue, nMaxBlocks); return; } LogPrintf("CSporkManager::ExecuteSpork -- Reconsider Last %d Blocks\n", nValue); ReprocessBlocks(nValue); nTimeExecuted = GetTime(); } } bool CSporkManager::UpdateSpork(int nSporkID, int64_t nValue, CConnman& connman) { CSporkMessage spork = CSporkMessage(nSporkID, nValue, GetAdjustedTime()); if(spork.Sign(sporkPrivKey)) { spork.Relay(connman); mapSporks[spork.GetHash()] = spork; mapSporksActive[nSporkID] = spork; return true; } return false; } // grab the spork, otherwise say it's off bool CSporkManager::IsSporkActive(int nSporkID) { int64_t r = -1; if(mapSporksActive.count(nSporkID)){ r = mapSporksActive[nSporkID].nValue; } else if (mapSporkDefaults.count(nSporkID)) { r = mapSporkDefaults[nSporkID]; } else { LogPrint("spork", "CSporkManager::IsSporkActive -- Unknown Spork ID %d\n", nSporkID); r = 4070908800ULL; // 2099-1-1 i.e. off by default } return r < GetAdjustedTime(); } // grab the value of the spork on the network, or the default int64_t CSporkManager::GetSporkValue(int nSporkID) { if (mapSporksActive.count(nSporkID)) return mapSporksActive[nSporkID].nValue; if (mapSporkDefaults.count(nSporkID)) { return mapSporkDefaults[nSporkID]; } LogPrint("spork", "CSporkManager::GetSporkValue -- Unknown Spork ID %d\n", nSporkID); return -1; } int CSporkManager::GetSporkIDByName(const std::string& strName) { if (strName == "SPORK_2_INSTANTSEND_ENABLED") return SPORK_2_INSTANTSEND_ENABLED; if (strName == "SPORK_3_INSTANTSEND_BLOCK_FILTERING") return SPORK_3_INSTANTSEND_BLOCK_FILTERING; if (strName == "SPORK_5_INSTANTSEND_MAX_VALUE") return SPORK_5_INSTANTSEND_MAX_VALUE; if (strName == "SPORK_6_NEW_SIGS") return SPORK_6_NEW_SIGS; if (strName == "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT") return SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT; if (strName == "SPORK_9_SUPERBLOCKS_ENABLED") return SPORK_9_SUPERBLOCKS_ENABLED; if (strName == "SPORK_10_MASTERNODE_PAY_UPDATED_NODES") return SPORK_10_MASTERNODE_PAY_UPDATED_NODES; if (strName == "SPORK_12_RECONSIDER_BLOCKS") return SPORK_12_RECONSIDER_BLOCKS; if (strName == "SPORK_14_REQUIRE_SENTINEL_FLAG") return SPORK_14_REQUIRE_SENTINEL_FLAG; LogPrint("spork", "CSporkManager::GetSporkIDByName -- Unknown Spork name '%s'\n", strName); return -1; } std::string CSporkManager::GetSporkNameByID(int nSporkID) { switch (nSporkID) { case SPORK_2_INSTANTSEND_ENABLED: return "SPORK_2_INSTANTSEND_ENABLED"; case SPORK_3_INSTANTSEND_BLOCK_FILTERING: return "SPORK_3_INSTANTSEND_BLOCK_FILTERING"; case SPORK_5_INSTANTSEND_MAX_VALUE: return "SPORK_5_INSTANTSEND_MAX_VALUE"; case SPORK_6_NEW_SIGS: return "SPORK_6_NEW_SIGS"; case SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT: return "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT"; case SPORK_9_SUPERBLOCKS_ENABLED: return "SPORK_9_SUPERBLOCKS_ENABLED"; case SPORK_10_MASTERNODE_PAY_UPDATED_NODES: return "SPORK_10_MASTERNODE_PAY_UPDATED_NODES"; case SPORK_12_RECONSIDER_BLOCKS: return "SPORK_12_RECONSIDER_BLOCKS"; case SPORK_14_REQUIRE_SENTINEL_FLAG: return "SPORK_14_REQUIRE_SENTINEL_FLAG"; default: LogPrint("spork", "CSporkManager::GetSporkNameByID -- Unknown Spork ID %d\n", nSporkID); return "Unknown"; } } bool CSporkManager::SetSporkAddress(const std::string& strAddress) { CSyscoinAddress address(strAddress); if (!address.IsValid() || !address.GetKeyID(sporkPubKeyID)) { LogPrintf("CSporkManager::SetSporkAddress -- Failed to parse spork address\n"); return false; } return true; } bool CSporkManager::SetPrivKey(const std::string& strPrivKey) { CKey key; CPubKey pubKey; if(!CMessageSigner::GetKeysFromSecret(strPrivKey, key, pubKey)) { LogPrintf("CSporkManager::SetPrivKey -- Failed to parse private key\n"); return false; } if (pubKey.GetID() != sporkPubKeyID) { LogPrintf("CSporkManager::SetPrivKey -- New private key does not belong to spork address\n"); return false; } CSporkMessage spork; if (spork.Sign(key)) { // Test signing successful, proceed LogPrintf("CSporkManager::SetPrivKey -- Successfully initialized as spork signer\n"); sporkPrivKey = key; return true; } else { LogPrintf("CSporkManager::SetPrivKey -- Test signing failed\n"); return false; } } uint256 CSporkMessage::GetHash() const { return SerializeHash(*this); } uint256 CSporkMessage::GetSignatureHash() const { return GetHash(); } bool CSporkMessage::Sign(const CKey& key) { if (!key.IsValid()) { LogPrintf("CSporkMessage::Sign -- signing key is not valid\n"); return false; } CKeyID pubKeyId = key.GetPubKey().GetID(); std::string strError = ""; if (sporkManager.IsSporkActive(SPORK_6_NEW_SIGS)) { uint256 hash = GetSignatureHash(); if(!CHashSigner::SignHash(hash, key, vchSig)) { LogPrintf("CSporkMessage::Sign -- SignHash() failed\n"); return false; } if (!CHashSigner::VerifyHash(hash, pubKeyId, vchSig, strError)) { LogPrintf("CSporkMessage::Sign -- VerifyHash() failed, error: %s\n", strError); return false; } } return true; } bool CSporkMessage::CheckSignature(const CKeyID& pubKeyId) const { std::string strError = ""; if (sporkManager.IsSporkActive(SPORK_6_NEW_SIGS)) { uint256 hash = GetSignatureHash(); if (!CHashSigner::VerifyHash(hash, pubKeyId, vchSig, strError)) { // Note: unlike for many other messages when SPORK_6_NEW_SIGS is ON sporks with sigs in old format // and newer timestamps should not be accepted, so if we failed here - that's it LogPrintf("CSporkMessage::CheckSignature -- VerifyHash() failed, error: %s\n", strError); return false; } <<<<<<< HEAD ======= } else { std::string strMessage = boost::lexical_cast<std::string>(nSporkID) + boost::lexical_cast<std::string>(nValue) + boost::lexical_cast<std::string>(nTimeSigned); if (!CMessageSigner::VerifyMessage(pubKeyId, vchSig, strMessage, strError)){ // Note: unlike for other messages we have to check for new format even with SPORK_6_NEW_SIGS // inactive because SPORK_6_NEW_SIGS default is OFF and it is not the first spork to sync // (and even if it would, spork order can't be guaranteed anyway). uint256 hash = GetSignatureHash(); if (!CHashSigner::VerifyHash(hash, pubKeyId, vchSig, strError)) { LogPrintf("CSporkMessage::CheckSignature -- VerifyHash() failed, error: %s\n", strError); return false; } } >>>>>>> 6410705... Fix 2 small issues in sporks module (#2133) } return true; } void CSporkMessage::Relay(CConnman& connman) { CInv inv(MSG_SPORK, GetHash()); connman.RelayInv(inv); } <commit_msg>Fixed merge conflict<commit_after>// Copyright (c) 2014-2017 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "spork.h" #include "base58.h" #include "chainparams.h" #include "validation.h" #include "messagesigner.h" #include "net_processing.h" #include "netmessagemaker.h" #include <boost/lexical_cast.hpp> CSporkManager sporkManager; std::map<uint256, CSporkMessage> mapSporks; std::map<int, int64_t> mapSporkDefaults = { {SPORK_2_INSTANTSEND_ENABLED, 0}, // ON {SPORK_3_INSTANTSEND_BLOCK_FILTERING, 0}, // ON {SPORK_5_INSTANTSEND_MAX_VALUE, 100000}, // 100000 Syscoin {SPORK_6_NEW_SIGS, 0}, // ON {SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT, 0}, // ON {SPORK_9_SUPERBLOCKS_ENABLED, 0}, // ON {SPORK_10_MASTERNODE_PAY_UPDATED_NODES, 0}, // ON {SPORK_12_RECONSIDER_BLOCKS, 0}, // 0 BLOCKS {SPORK_14_REQUIRE_SENTINEL_FLAG, 0}, // ON }; void CSporkManager::ProcessSpork(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, CConnman& connman) { if(fLiteMode) return; // disable all Syscoin specific functionality if (strCommand == NetMsgType::SPORK) { CSporkMessage spork; vRecv >> spork; uint256 hash = spork.GetHash(); std::string strLogMsg; { LOCK(cs_main); pfrom->setAskFor.erase(hash); if(!chainActive.Tip()) return; strLogMsg = strprintf("SPORK -- hash: %s id: %d value: %10d bestHeight: %d peer=%d", hash.ToString(), spork.nSporkID, spork.nValue, chainActive.Height(), pfrom->id); } if(mapSporksActive.count(spork.nSporkID)) { if (mapSporksActive[spork.nSporkID].nTimeSigned >= spork.nTimeSigned) { LogPrint("spork", "%s seen\n", strLogMsg); return; } else { LogPrintf("%s updated\n", strLogMsg); } } else { LogPrintf("%s new\n", strLogMsg); } if(!spork.CheckSignature(sporkPubKeyID)) { LOCK(cs_main); LogPrintf("CSporkManager::ProcessSpork -- ERROR: invalid signature\n"); Misbehaving(pfrom->GetId(), 100); return; } mapSporks[hash] = spork; mapSporksActive[spork.nSporkID] = spork; spork.Relay(connman); //does a task if needed ExecuteSpork(spork.nSporkID, spork.nValue); } else if (strCommand == NetMsgType::GETSPORKS) { std::map<int, CSporkMessage>::iterator it = mapSporksActive.begin(); while(it != mapSporksActive.end()) { connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::SPORK, it->second)); it++; } } } void CSporkManager::ExecuteSpork(int nSporkID, int nValue) { //correct fork via spork technology if(nSporkID == SPORK_12_RECONSIDER_BLOCKS && nValue > 0) { // allow to reprocess 24h of blocks max, which should be enough to resolve any issues int64_t nMaxBlocks = 1440; // this potentially can be a heavy operation, so only allow this to be executed once per 10 minutes int64_t nTimeout = 10 * 60; static int64_t nTimeExecuted = 0; // i.e. it was never executed before if(GetTime() - nTimeExecuted < nTimeout) { LogPrint("spork", "CSporkManager::ExecuteSpork -- ERROR: Trying to reconsider blocks, too soon - %d/%d\n", GetTime() - nTimeExecuted, nTimeout); return; } if(nValue > nMaxBlocks) { LogPrintf("CSporkManager::ExecuteSpork -- ERROR: Trying to reconsider too many blocks %d/%d\n", nValue, nMaxBlocks); return; } LogPrintf("CSporkManager::ExecuteSpork -- Reconsider Last %d Blocks\n", nValue); ReprocessBlocks(nValue); nTimeExecuted = GetTime(); } } bool CSporkManager::UpdateSpork(int nSporkID, int64_t nValue, CConnman& connman) { CSporkMessage spork = CSporkMessage(nSporkID, nValue, GetAdjustedTime()); if(spork.Sign(sporkPrivKey)) { spork.Relay(connman); mapSporks[spork.GetHash()] = spork; mapSporksActive[nSporkID] = spork; return true; } return false; } // grab the spork, otherwise say it's off bool CSporkManager::IsSporkActive(int nSporkID) { int64_t r = -1; if(mapSporksActive.count(nSporkID)){ r = mapSporksActive[nSporkID].nValue; } else if (mapSporkDefaults.count(nSporkID)) { r = mapSporkDefaults[nSporkID]; } else { LogPrint("spork", "CSporkManager::IsSporkActive -- Unknown Spork ID %d\n", nSporkID); r = 4070908800ULL; // 2099-1-1 i.e. off by default } return r < GetAdjustedTime(); } // grab the value of the spork on the network, or the default int64_t CSporkManager::GetSporkValue(int nSporkID) { if (mapSporksActive.count(nSporkID)) return mapSporksActive[nSporkID].nValue; if (mapSporkDefaults.count(nSporkID)) { return mapSporkDefaults[nSporkID]; } LogPrint("spork", "CSporkManager::GetSporkValue -- Unknown Spork ID %d\n", nSporkID); return -1; } int CSporkManager::GetSporkIDByName(const std::string& strName) { if (strName == "SPORK_2_INSTANTSEND_ENABLED") return SPORK_2_INSTANTSEND_ENABLED; if (strName == "SPORK_3_INSTANTSEND_BLOCK_FILTERING") return SPORK_3_INSTANTSEND_BLOCK_FILTERING; if (strName == "SPORK_5_INSTANTSEND_MAX_VALUE") return SPORK_5_INSTANTSEND_MAX_VALUE; if (strName == "SPORK_6_NEW_SIGS") return SPORK_6_NEW_SIGS; if (strName == "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT") return SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT; if (strName == "SPORK_9_SUPERBLOCKS_ENABLED") return SPORK_9_SUPERBLOCKS_ENABLED; if (strName == "SPORK_10_MASTERNODE_PAY_UPDATED_NODES") return SPORK_10_MASTERNODE_PAY_UPDATED_NODES; if (strName == "SPORK_12_RECONSIDER_BLOCKS") return SPORK_12_RECONSIDER_BLOCKS; if (strName == "SPORK_14_REQUIRE_SENTINEL_FLAG") return SPORK_14_REQUIRE_SENTINEL_FLAG; LogPrint("spork", "CSporkManager::GetSporkIDByName -- Unknown Spork name '%s'\n", strName); return -1; } std::string CSporkManager::GetSporkNameByID(int nSporkID) { switch (nSporkID) { case SPORK_2_INSTANTSEND_ENABLED: return "SPORK_2_INSTANTSEND_ENABLED"; case SPORK_3_INSTANTSEND_BLOCK_FILTERING: return "SPORK_3_INSTANTSEND_BLOCK_FILTERING"; case SPORK_5_INSTANTSEND_MAX_VALUE: return "SPORK_5_INSTANTSEND_MAX_VALUE"; case SPORK_6_NEW_SIGS: return "SPORK_6_NEW_SIGS"; case SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT: return "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT"; case SPORK_9_SUPERBLOCKS_ENABLED: return "SPORK_9_SUPERBLOCKS_ENABLED"; case SPORK_10_MASTERNODE_PAY_UPDATED_NODES: return "SPORK_10_MASTERNODE_PAY_UPDATED_NODES"; case SPORK_12_RECONSIDER_BLOCKS: return "SPORK_12_RECONSIDER_BLOCKS"; case SPORK_14_REQUIRE_SENTINEL_FLAG: return "SPORK_14_REQUIRE_SENTINEL_FLAG"; default: LogPrint("spork", "CSporkManager::GetSporkNameByID -- Unknown Spork ID %d\n", nSporkID); return "Unknown"; } } bool CSporkManager::SetSporkAddress(const std::string& strAddress) { CSyscoinAddress address(strAddress); if (!address.IsValid() || !address.GetKeyID(sporkPubKeyID)) { LogPrintf("CSporkManager::SetSporkAddress -- Failed to parse spork address\n"); return false; } return true; } bool CSporkManager::SetPrivKey(const std::string& strPrivKey) { CKey key; CPubKey pubKey; if(!CMessageSigner::GetKeysFromSecret(strPrivKey, key, pubKey)) { LogPrintf("CSporkManager::SetPrivKey -- Failed to parse private key\n"); return false; } if (pubKey.GetID() != sporkPubKeyID) { LogPrintf("CSporkManager::SetPrivKey -- New private key does not belong to spork address\n"); return false; } CSporkMessage spork; if (spork.Sign(key)) { // Test signing successful, proceed LogPrintf("CSporkManager::SetPrivKey -- Successfully initialized as spork signer\n"); sporkPrivKey = key; return true; } else { LogPrintf("CSporkManager::SetPrivKey -- Test signing failed\n"); return false; } } uint256 CSporkMessage::GetHash() const { return SerializeHash(*this); } uint256 CSporkMessage::GetSignatureHash() const { return GetHash(); } bool CSporkMessage::Sign(const CKey& key) { if (!key.IsValid()) { LogPrintf("CSporkMessage::Sign -- signing key is not valid\n"); return false; } CKeyID pubKeyId = key.GetPubKey().GetID(); std::string strError = ""; if (sporkManager.IsSporkActive(SPORK_6_NEW_SIGS)) { uint256 hash = GetSignatureHash(); if(!CHashSigner::SignHash(hash, key, vchSig)) { LogPrintf("CSporkMessage::Sign -- SignHash() failed\n"); return false; } if (!CHashSigner::VerifyHash(hash, pubKeyId, vchSig, strError)) { LogPrintf("CSporkMessage::Sign -- VerifyHash() failed, error: %s\n", strError); return false; } } return true; } bool CSporkMessage::CheckSignature(const CKeyID& pubKeyId) const { std::string strError = ""; if (sporkManager.IsSporkActive(SPORK_6_NEW_SIGS)) { uint256 hash = GetSignatureHash(); if (!CHashSigner::VerifyHash(hash, pubKeyId, vchSig, strError)) { // Note: unlike for many other messages when SPORK_6_NEW_SIGS is ON sporks with sigs in old format // and newer timestamps should not be accepted, so if we failed here - that's it LogPrintf("CSporkMessage::CheckSignature -- VerifyHash() failed, error: %s\n", strError); return false; } } else { std::string strMessage = boost::lexical_cast<std::string>(nSporkID) + boost::lexical_cast<std::string>(nValue) + boost::lexical_cast<std::string>(nTimeSigned); if (!CMessageSigner::VerifyMessage(pubKeyId, vchSig, strMessage, strError)){ // Note: unlike for other messages we have to check for new format even with SPORK_6_NEW_SIGS // inactive because SPORK_6_NEW_SIGS default is OFF and it is not the first spork to sync // (and even if it would, spork order can't be guaranteed anyway). uint256 hash = GetSignatureHash(); if (!CHashSigner::VerifyHash(hash, pubKeyId, vchSig, strError)) { LogPrintf("CSporkMessage::CheckSignature -- VerifyHash() failed, error: %s\n", strError); return false; } } } return true; } void CSporkMessage::Relay(CConnman& connman) { CInv inv(MSG_SPORK, GetHash()); connman.RelayInv(inv); } <|endoftext|>
<commit_before>#include "internal.hpp" namespace CaDiCaL { /*------------------------------------------------------------------------*/ Stats::Stats () { memset (this, 0, sizeof *this); } /*------------------------------------------------------------------------*/ void Stats::print (Internal * internal) { #ifndef QUIET Stats & stats = internal->stats; double t = process_time (); size_t m = maximum_resident_set_size (); int max_var = internal->external->max_var; #ifdef STATS int verbose = 1; #else int verbose = internal->opts.verbose; #ifdef LOGGING if (internal->opts.log) verbose = 1; #endif // ifdef LOGGING #endif // ifdef STATS if (internal->opts.profile) internal->print_profile (t); SECTION ("statistics"); MSG ("probings: %15ld %10.2f conflicts per probing", stats.probings, relative (stats.conflicts, stats.probings)); MSG ("vivifications: %15ld %10.2f conflicts per vivification", stats.vivifications, relative (stats.conflicts, stats.vivifications)); MSG ("transreductions: %15ld %10.2f conflicts per reduction", stats.transreds, relative (stats.conflicts, stats.transreds)); MSG ("eliminations: %15ld %10.2f conflicts per elimination", stats.eliminations, relative (stats.conflicts, stats.eliminations)); MSG ("subsumptions: %15ld %10.2f conflicts per subsumption", stats.subsumptions, relative (stats.conflicts, stats.subsumptions)); MSG ("decompositions: %15ld %10.2f decompositions per probing", stats.decompositions, relative (stats.decompositions, stats.probings)); MSG ("reductions: %15ld %10.2f conflicts per reduction", stats.reductions, relative (stats.conflicts, stats.reductions)); MSG ("restarts: %15ld %10.2f conflicts per restart", stats.restarts, relative (stats.conflicts, stats.restarts)); MSG ("compacts: %15ld %10.2f conflicts per compact", stats.compacts, relative (stats.conflicts, stats.compacts)); MSG ("conflicts: %15ld %10.2f per second", stats.conflicts, relative (stats.conflicts, t)); MSG ("decisions: %15ld %10.2f per second", stats.decisions, relative (stats.decisions, t)); long propagations = stats.propagations.search; propagations += stats.propagations.transred; propagations += stats.propagations.probe; propagations += stats.propagations.vivify; MSG ("propagations: %15ld %10.2f millions per second", propagations, relative (propagations/1e6, t)); if (verbose) { MSG (" searchprops: %15ld %10.2f %% of propagations", stats.propagations.search, percent (stats.propagations.search, propagations)); MSG (" transredprops: %15ld %10.2f %% of propagations", stats.propagations.transred, percent (stats.propagations.transred, propagations)); MSG (" probeprops: %15ld %10.2f %% of propagations", stats.propagations.probe, percent (stats.propagations.probe, propagations)); MSG (" vivifyprops: %15ld %10.2f %% of propagations", stats.propagations.vivify, percent (stats.propagations.vivify, propagations)); #ifdef STATS MSG (" visits: %15ld %10.2f per searchprop", stats.visits, relative (stats.visits, stats.propagations.search)); MSG (" traversed: %15ld %10.2f per visit", stats.traversed, relative (stats.traversed, stats.visits)); #endif } MSG ("probed: %15ld %10.2f per failed", stats.probed, relative (stats.probed, stats.failed)); if (verbose) { MSG (" hbrs: %15ld %10.2f per probed", stats.hbrs, relative (stats.hbrs, stats.probed)); MSG (" hbrsizes: %15ld %10.2f per hbr", stats.hbrsizes, relative (stats.hbrsizes, stats.hbrs)); MSG (" hbreds: %15ld %10.2f %% per hbr", stats.hbreds, percent (stats.hbreds, stats.hbrs)); MSG (" hbrsubs: %15ld %10.2f %% per hbr", stats.hbrsubs, percent (stats.hbrsubs, stats.hbrs)); } long vivified = stats.vivifysubs + stats.vivifystrs; MSG ("vivified: %15ld %10.2f %% per vivify check", vivified, percent (vivified, stats.vivifychecks)); if (verbose) { MSG (" vivifychecks: %15ld %10.2f %% per conflict", stats.vivifychecks, percent (stats.vivifychecks, stats.conflicts)); MSG (" vivifysched: %15ld %10.2f %% checks per scheduled", stats.vivifysched, percent (stats.vivifychecks, stats.vivifysched)); MSG (" vivifyunits: %15ld %10.2f %% per vivify check", stats.vivifyunits, percent (stats.vivifyunits, stats.vivifychecks)); MSG (" vivifysubs: %15ld %10.2f %% per subsumed", stats.vivifysubs, percent (stats.vivifysubs, stats.subsumed)); MSG (" vivifystrs: %15ld %10.2f %% per strengthened", stats.vivifystrs, percent (stats.vivifystrs, stats.strengthened)); MSG (" vivifydecs: %15ld %10.2f per checks", stats.vivifydecs, relative (stats.vivifydecs, stats.vivifychecks)); MSG (" vivifyreused: %15ld %10.2f %% per decision", stats.vivifyreused, percent (stats.vivifyreused, stats.vivifydecs)); } MSG ("reused: %15ld %10.2f %% per restart", stats.reused, percent (stats.reused, stats.restarts)); MSG ("resolutions: %15ld %10.2f per eliminated", stats.elimres, relative (stats.elimres, stats.all.eliminated)); if (verbose) { MSG (" elimres2: %15ld %10.2f %% per resolved", stats.elimres2, percent (stats.elimres, stats.elimres)); MSG (" elimrestried: %15ld %10.2f %% per resolved", stats.elimrestried, percent (stats.elimrestried, stats.elimres)); } MSG ("eliminated: %15ld %10.2f %% of all variables", stats.all.eliminated, percent (stats.all.eliminated, max_var)); MSG ("fixed: %15ld %10.2f %% of all variables", stats.all.fixed, percent (stats.all.fixed, max_var)); if (verbose) { MSG (" units: %15ld %10.2f conflicts per unit", stats.units, relative (stats.conflicts, stats.units)); MSG (" binaries: %15ld %10.2f conflicts per binary", stats.binaries, relative (stats.conflicts, stats.binaries)); } MSG ("substituted: %15ld %10.2f %% of all variables", stats.all.substituted, percent (stats.all.substituted, max_var)); MSG ("failed: %15ld %10.2f %% of all variables", stats.failed, percent (stats.failed, max_var)); long learned = stats.learned - stats.minimized; MSG ("learned: %15ld %10.2f per conflict", learned, relative (learned, stats.conflicts)); if (verbose) { MSG (" analyzed: %15ld %10.2f per conflict", stats.analyzed, relative (stats.analyzed, stats.conflicts)); MSG (" trailbumped: %15ld %10.2f %% per conflict", stats.trailbumped, percent (stats.trailbumped, stats.conflicts)); } MSG ("minimized: %15ld %10.2f %% of 1st-UIP-literals", stats.minimized, percent (stats.minimized, stats.learned)); MSG ("subsumed: %15ld %10.2f tried per subsumed", stats.subsumed, relative (stats.subtried, stats.subsumed)); if (verbose) { MSG (" duplicated: %15ld %10.2f %% per subsumed", stats.duplicated, percent (stats.duplicated, stats.subsumed)); MSG (" transitive: %15ld %10.2f %% per subsumed", stats.transitive, percent (stats.transitive, stats.subsumed)); } MSG ("strengthened: %15ld %10.2f per subsumed", stats.strengthened, relative (stats.strengthened, stats.subsumed)); if (verbose) { MSG (" subirr: %15ld %10.2f %% of subsumed", stats.subirr, percent (stats.subirr, stats.subsumed)); MSG (" subred: %15ld %10.2f %% of subsumed", stats.subred, percent (stats.subred, stats.subsumed)); MSG (" subtried: %15ld %10.2f per conflict", stats.subtried, relative (stats.subtried, stats.conflicts)); MSG (" subchecks: %15ld %10.2f per tried", stats.subchecks, relative (stats.subchecks, stats.subtried)); MSG (" subchecks2: %15ld %10.2f %% per subcheck", stats.subchecks2, percent (stats.subchecks2, stats.subchecks)); } MSG ("searched: %15ld %10.2f per decision", stats.searched, relative (stats.searched, stats.decisions)); MSG ("bumped: %15ld %10.2f per conflict", stats.bumped, relative (stats.bumped, stats.conflicts)); MSG ("reduced: %15ld %10.2f %% clauses per conflict", stats.reduced, percent (stats.reduced, stats.conflicts)); if (verbose) MSG (" collections: %15ld %10.2f conflicts per collection", stats.collections, relative (stats.conflicts, stats.collections)); size_t extendbytes = internal->external->extension.capacity (); extendbytes *= sizeof (int); // if (verbose) MSG (" extendbytes: %15ld %10.2f bytes and MB", extendbytes, extendbytes/(double)(1l<<20)); MSG ("memory: %15ld %10.2f bytes and MB", m, m/(double)(1l<<20)); MSG ("time: %15s %10.2f seconds", "", t); MSG (""); #endif } }; <commit_msg>fixed<commit_after>#include "internal.hpp" namespace CaDiCaL { /*------------------------------------------------------------------------*/ Stats::Stats () { memset (this, 0, sizeof *this); } /*------------------------------------------------------------------------*/ void Stats::print (Internal * internal) { #ifndef QUIET Stats & stats = internal->stats; double t = process_time (); size_t m = maximum_resident_set_size (); int max_var = internal->external->max_var; #ifdef STATS int verbose = 1; #else int verbose = internal->opts.verbose; #ifdef LOGGING if (internal->opts.log) verbose = 1; #endif // ifdef LOGGING #endif // ifdef STATS if (internal->opts.profile) internal->print_profile (t); SECTION ("statistics"); MSG ("probings: %15ld %10.2f conflicts per probing", stats.probings, relative (stats.conflicts, stats.probings)); MSG ("vivifications: %15ld %10.2f conflicts per vivification", stats.vivifications, relative (stats.conflicts, stats.vivifications)); MSG ("transreductions: %15ld %10.2f conflicts per reduction", stats.transreds, relative (stats.conflicts, stats.transreds)); MSG ("eliminations: %15ld %10.2f conflicts per elimination", stats.eliminations, relative (stats.conflicts, stats.eliminations)); MSG ("subsumptions: %15ld %10.2f conflicts per subsumption", stats.subsumptions, relative (stats.conflicts, stats.subsumptions)); MSG ("decompositions: %15ld %10.2f decompositions per probing", stats.decompositions, relative (stats.decompositions, stats.probings)); MSG ("reductions: %15ld %10.2f conflicts per reduction", stats.reductions, relative (stats.conflicts, stats.reductions)); MSG ("restarts: %15ld %10.2f conflicts per restart", stats.restarts, relative (stats.conflicts, stats.restarts)); MSG ("compacts: %15ld %10.2f conflicts per compact", stats.compacts, relative (stats.conflicts, stats.compacts)); MSG ("conflicts: %15ld %10.2f per second", stats.conflicts, relative (stats.conflicts, t)); MSG ("decisions: %15ld %10.2f per second", stats.decisions, relative (stats.decisions, t)); long propagations = stats.propagations.search; propagations += stats.propagations.transred; propagations += stats.propagations.probe; propagations += stats.propagations.vivify; MSG ("propagations: %15ld %10.2f millions per second", propagations, relative (propagations/1e6, t)); if (verbose) { MSG (" searchprops: %15ld %10.2f %% of propagations", stats.propagations.search, percent (stats.propagations.search, propagations)); MSG (" transredprops: %15ld %10.2f %% of propagations", stats.propagations.transred, percent (stats.propagations.transred, propagations)); MSG (" probeprops: %15ld %10.2f %% of propagations", stats.propagations.probe, percent (stats.propagations.probe, propagations)); MSG (" vivifyprops: %15ld %10.2f %% of propagations", stats.propagations.vivify, percent (stats.propagations.vivify, propagations)); #ifdef STATS MSG (" visits: %15ld %10.2f per searchprop", stats.visits, relative (stats.visits, stats.propagations.search)); MSG (" traversed: %15ld %10.2f per visit", stats.traversed, relative (stats.traversed, stats.visits)); #endif } MSG ("probed: %15ld %10.2f per failed", stats.probed, relative (stats.probed, stats.failed)); if (verbose) { MSG (" hbrs: %15ld %10.2f per probed", stats.hbrs, relative (stats.hbrs, stats.probed)); MSG (" hbrsizes: %15ld %10.2f per hbr", stats.hbrsizes, relative (stats.hbrsizes, stats.hbrs)); MSG (" hbreds: %15ld %10.2f %% per hbr", stats.hbreds, percent (stats.hbreds, stats.hbrs)); MSG (" hbrsubs: %15ld %10.2f %% per hbr", stats.hbrsubs, percent (stats.hbrsubs, stats.hbrs)); } long vivified = stats.vivifysubs + stats.vivifystrs; MSG ("vivified: %15ld %10.2f %% per vivify check", vivified, percent (vivified, stats.vivifychecks)); if (verbose) { MSG (" vivifychecks: %15ld %10.2f %% per conflict", stats.vivifychecks, percent (stats.vivifychecks, stats.conflicts)); MSG (" vivifysched: %15ld %10.2f %% checks per scheduled", stats.vivifysched, percent (stats.vivifychecks, stats.vivifysched)); MSG (" vivifyunits: %15ld %10.2f %% per vivify check", stats.vivifyunits, percent (stats.vivifyunits, stats.vivifychecks)); MSG (" vivifysubs: %15ld %10.2f %% per subsumed", stats.vivifysubs, percent (stats.vivifysubs, stats.subsumed)); MSG (" vivifystrs: %15ld %10.2f %% per strengthened", stats.vivifystrs, percent (stats.vivifystrs, stats.strengthened)); MSG (" vivifydecs: %15ld %10.2f per checks", stats.vivifydecs, relative (stats.vivifydecs, stats.vivifychecks)); MSG (" vivifyreused: %15ld %10.2f %% per decision", stats.vivifyreused, percent (stats.vivifyreused, stats.vivifydecs)); } MSG ("reused: %15ld %10.2f %% per restart", stats.reused, percent (stats.reused, stats.restarts)); MSG ("resolutions: %15ld %10.2f per eliminated", stats.elimres, relative (stats.elimres, stats.all.eliminated)); if (verbose) { MSG (" elimres2: %15ld %10.2f %% per resolved", stats.elimres2, percent (stats.elimres, stats.elimres)); MSG (" elimrestried: %15ld %10.2f %% per resolved", stats.elimrestried, percent (stats.elimrestried, stats.elimres)); } MSG ("eliminated: %15ld %10.2f %% of all variables", stats.all.eliminated, percent (stats.all.eliminated, max_var)); MSG ("fixed: %15ld %10.2f %% of all variables", stats.all.fixed, percent (stats.all.fixed, max_var)); if (verbose) { MSG (" units: %15ld %10.2f conflicts per unit", stats.units, relative (stats.conflicts, stats.units)); MSG (" binaries: %15ld %10.2f conflicts per binary", stats.binaries, relative (stats.conflicts, stats.binaries)); } MSG ("substituted: %15ld %10.2f %% of all variables", stats.all.substituted, percent (stats.all.substituted, max_var)); MSG ("failed: %15ld %10.2f %% of all variables", stats.failed, percent (stats.failed, max_var)); long learned = stats.learned - stats.minimized; MSG ("learned: %15ld %10.2f per conflict", learned, relative (learned, stats.conflicts)); if (verbose) { MSG (" analyzed: %15ld %10.2f per conflict", stats.analyzed, relative (stats.analyzed, stats.conflicts)); MSG (" trailbumped: %15ld %10.2f %% per conflict", stats.trailbumped, percent (stats.trailbumped, stats.conflicts)); } MSG ("minimized: %15ld %10.2f %% of 1st-UIP-literals", stats.minimized, percent (stats.minimized, stats.learned)); MSG ("subsumed: %15ld %10.2f tried per subsumed", stats.subsumed, relative (stats.subtried, stats.subsumed)); if (verbose) { MSG (" duplicated: %15ld %10.2f %% per subsumed", stats.duplicated, percent (stats.duplicated, stats.subsumed)); MSG (" transitive: %15ld %10.2f %% per subsumed", stats.transitive, percent (stats.transitive, stats.subsumed)); } MSG ("strengthened: %15ld %10.2f per subsumed", stats.strengthened, relative (stats.strengthened, stats.subsumed)); if (verbose) { MSG (" subirr: %15ld %10.2f %% of subsumed", stats.subirr, percent (stats.subirr, stats.subsumed)); MSG (" subred: %15ld %10.2f %% of subsumed", stats.subred, percent (stats.subred, stats.subsumed)); MSG (" subtried: %15ld %10.2f per conflict", stats.subtried, relative (stats.subtried, stats.conflicts)); MSG (" subchecks: %15ld %10.2f per tried", stats.subchecks, relative (stats.subchecks, stats.subtried)); MSG (" subchecks2: %15ld %10.2f %% per subcheck", stats.subchecks2, percent (stats.subchecks2, stats.subchecks)); } MSG ("searched: %15ld %10.2f per decision", stats.searched, relative (stats.searched, stats.decisions)); MSG ("bumped: %15ld %10.2f per conflict", stats.bumped, relative (stats.bumped, stats.conflicts)); MSG ("reduced: %15ld %10.2f %% clauses per conflict", stats.reduced, percent (stats.reduced, stats.conflicts)); if (verbose) MSG (" collections: %15ld %10.2f conflicts per collection", stats.collections, relative (stats.conflicts, stats.collections)); size_t extendbytes = internal->external->extension.capacity (); extendbytes *= sizeof (int); if (verbose) MSG (" extendbytes: %15ld %10.2f bytes and MB", extendbytes, extendbytes/(double)(1l<<20)); MSG ("memory: %15ld %10.2f bytes and MB", m, m/(double)(1l<<20)); MSG ("time: %15s %10.2f seconds", "", t); MSG (""); #endif } }; <|endoftext|>
<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights // reserved. See file COPYRIGHT for details. // // This file is part of the MFEM library. For more information and source code // availability see http://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the GNU Lesser General Public License (as published by the Free // Software Foundation) version 2.1 dated February 1999. #include "catch.hpp" #include "mfem.hpp" using namespace mfem; namespace pa_conv { int dimension; // Velocity coefficient void velocity_function(const Vector &x, Vector &v) { if (dimension == 2) { v(0) = sqrt(2./3.); v(1) = sqrt(1./3.); } if (dimension == 3) { v(0) = sqrt(3./6.); v(1) = sqrt(2./6.); v(2) = sqrt(1./6.); } } //Basic unit test for convection TEST_CASE("conv") { for (dimension = 2; dimension < 4; ++dimension) { for (int imesh = 0; imesh<2; ++imesh) { const char *mesh_file; if(dimension == 2) { switch (imesh) { case 0: mesh_file = "../../data/periodic-square.mesh"; break; case 1: mesh_file = "../../data/amr-quad.mesh"; break; } } if(dimension == 3) { switch (imesh) { case 0: mesh_file = "../../data/periodic-cube.mesh"; break; case 1: mesh_file = "../../data/amr-hex.mesh"; break; } } Mesh *mesh = new Mesh(mesh_file, 1, 1); for(int order = 1; order < 5; ++order) { H1_FECollection *fec = new H1_FECollection(order, dimension); FiniteElementSpace *fespace = new FiniteElementSpace(mesh, fec); BilinearForm k(fespace); BilinearForm pak(fespace); //Partial assembly version of k VectorFunctionCoefficient velocity(dimension, velocity_function); k.AddDomainIntegrator(new ConvectionIntegrator(velocity, -1.0)); pak.AddDomainIntegrator(new ConvectionIntegrator(velocity, -1.0)); int skip_zeros = 0; k.Assemble(skip_zeros); k.Finalize(skip_zeros); pak.SetAssemblyLevel(AssemblyLevel::PARTIAL); pak.Assemble(); Vector x(k.Size()); Vector y(k.Size()), y_pa(k.Size()); for(int i=0; i<x.Size(); ++i) {x(i) = i/10.0;}; pak.Mult(x,y_pa); k.Mult(x,y); y_pa -= y; double pa_error =- y_pa.Norml2(); std::cout << " ConvectionIntegrator " << " dim: " << dimension << " conforming: " << imesh << " order: " << order << ", pa error norm: " << pa_error << std::endl; REQUIRE(pa_error < 1.e-12); }//order loop }//mesh loop }//dimension loop }//case } // namespace pa_conv <commit_msg>Use abs value in the unit test check.<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights // reserved. See file COPYRIGHT for details. // // This file is part of the MFEM library. For more information and source code // availability see http://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the GNU Lesser General Public License (as published by the Free // Software Foundation) version 2.1 dated February 1999. #include "catch.hpp" #include "mfem.hpp" using namespace mfem; namespace pa_conv { int dimension; // Velocity coefficient void velocity_function(const Vector &x, Vector &v) { if (dimension == 2) { v(0) = sqrt(2./3.); v(1) = sqrt(1./3.); } if (dimension == 3) { v(0) = sqrt(3./6.); v(1) = sqrt(2./6.); v(2) = sqrt(1./6.); } } //Basic unit test for convection TEST_CASE("conv") { for (dimension = 2; dimension < 4; ++dimension) { for (int imesh = 0; imesh<2; ++imesh) { const char *mesh_file; if(dimension == 2) { switch (imesh) { case 0: mesh_file = "../../data/periodic-square.mesh"; break; case 1: mesh_file = "../../data/amr-quad.mesh"; break; } } if(dimension == 3) { switch (imesh) { case 0: mesh_file = "../../data/periodic-cube.mesh"; break; case 1: mesh_file = "../../data/amr-hex.mesh"; break; } } Mesh *mesh = new Mesh(mesh_file, 1, 1); for(int order = 1; order < 5; ++order) { H1_FECollection *fec = new H1_FECollection(order, dimension); FiniteElementSpace *fespace = new FiniteElementSpace(mesh, fec); BilinearForm k(fespace); BilinearForm pak(fespace); //Partial assembly version of k VectorFunctionCoefficient velocity(dimension, velocity_function); k.AddDomainIntegrator(new ConvectionIntegrator(velocity, -1.0)); pak.AddDomainIntegrator(new ConvectionIntegrator(velocity, -1.0)); int skip_zeros = 0; k.Assemble(skip_zeros); k.Finalize(skip_zeros); pak.SetAssemblyLevel(AssemblyLevel::PARTIAL); pak.Assemble(); Vector x(k.Size()); Vector y(k.Size()), y_pa(k.Size()); for(int i=0; i<x.Size(); ++i) {x(i) = i/10.0;}; pak.Mult(x,y_pa); k.Mult(x,y); y_pa -= y; double pa_error =- y_pa.Norml2(); std::cout << " ConvectionIntegrator " << " dim: " << dimension << " conforming: " << imesh << " order: " << order << ", pa error norm: " << pa_error << std::endl; REQUIRE(fabs(pa_error) < 1.e-12); }//order loop }//mesh loop }//dimension loop }//case } // namespace pa_conv <|endoftext|>
<commit_before>/* gobby - A GTKmm driven libobby client * Copyright (C) 2005 0x539 dev group * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <gtkmm/stock.h> #include "common.hpp" #include "chat.hpp" Gobby::Chat::Chat() : Gtk::VBox(), m_img_btn(Gtk::Stock::JUMP_TO, Gtk::ICON_SIZE_BUTTON) { m_btn_chat.set_label(_("Send")); m_btn_chat.set_image(m_img_btn); m_btn_chat.set_size_request(100, -1); m_btn_chat.signal_clicked().connect( sigc::mem_fun(*this, &Chat::on_chat) ); m_ent_chat.signal_activate().connect( sigc::mem_fun(*this, &Chat::on_chat) ); m_wnd_chat.add(m_log_chat); m_wnd_chat.set_shadow_type(Gtk::SHADOW_IN); m_wnd_chat.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); m_box_chat.pack_start(m_ent_chat, Gtk::PACK_EXPAND_WIDGET); m_box_chat.pack_start(m_btn_chat, Gtk::PACK_SHRINK); m_box_chat.set_spacing(5); pack_start(m_wnd_chat, Gtk::PACK_EXPAND_WIDGET); pack_start(m_box_chat, Gtk::PACK_SHRINK); set_spacing(5); set_sensitive(false); } Gobby::Chat::~Chat() { } Gobby::Chat::signal_chat_type Gobby::Chat::chat_event() const { return m_signal_chat; } void Gobby::Chat::obby_start() { m_log_chat.clear(); m_ent_chat.set_sensitive(true); m_btn_chat.set_sensitive(true); set_sensitive(true); } void Gobby::Chat::obby_end() { m_ent_chat.clear_history(); m_ent_chat.set_sensitive(false); m_btn_chat.set_sensitive(false); } void Gobby::Chat::obby_user_join(obby::user& user) { m_log_chat.log(user.get_name() + " has joined", "blue"); } void Gobby::Chat::obby_user_part(obby::user& user) { m_log_chat.log(user.get_name() + " has left", "blue"); } void Gobby::Chat::obby_document_insert(obby::document& document) { } void Gobby::Chat::obby_document_remove(obby::document& document) { } void Gobby::Chat::obby_message(obby::user& user, const Glib::ustring& message) { m_log_chat.log("<" + user.get_name() + "> " + message, "black"); } void Gobby::Chat::obby_server_message(const Glib::ustring& message) { m_log_chat.log(message, "forest green"); } void Gobby::Chat::on_chat() { Glib::ustring message = m_ent_chat.get_text(); if(message.empty() ) return; m_ent_chat.set_text(""); m_signal_chat.emit(message); } <commit_msg>[project @ Send lines separately in chat]<commit_after>/* gobby - A GTKmm driven libobby client * Copyright (C) 2005 0x539 dev group * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <gtkmm/stock.h> #include "common.hpp" #include "chat.hpp" Gobby::Chat::Chat() : Gtk::VBox(), m_img_btn(Gtk::Stock::JUMP_TO, Gtk::ICON_SIZE_BUTTON) { m_btn_chat.set_label(_("Send")); m_btn_chat.set_image(m_img_btn); m_btn_chat.set_size_request(100, -1); m_btn_chat.signal_clicked().connect( sigc::mem_fun(*this, &Chat::on_chat) ); m_ent_chat.signal_activate().connect( sigc::mem_fun(*this, &Chat::on_chat) ); m_wnd_chat.add(m_log_chat); m_wnd_chat.set_shadow_type(Gtk::SHADOW_IN); m_wnd_chat.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); m_box_chat.pack_start(m_ent_chat, Gtk::PACK_EXPAND_WIDGET); m_box_chat.pack_start(m_btn_chat, Gtk::PACK_SHRINK); m_box_chat.set_spacing(5); pack_start(m_wnd_chat, Gtk::PACK_EXPAND_WIDGET); pack_start(m_box_chat, Gtk::PACK_SHRINK); set_spacing(5); set_sensitive(false); } Gobby::Chat::~Chat() { } Gobby::Chat::signal_chat_type Gobby::Chat::chat_event() const { return m_signal_chat; } void Gobby::Chat::obby_start() { m_log_chat.clear(); m_ent_chat.set_sensitive(true); m_btn_chat.set_sensitive(true); set_sensitive(true); } void Gobby::Chat::obby_end() { m_ent_chat.clear_history(); m_ent_chat.set_sensitive(false); m_btn_chat.set_sensitive(false); } void Gobby::Chat::obby_user_join(obby::user& user) { m_log_chat.log(user.get_name() + " has joined", "blue"); } void Gobby::Chat::obby_user_part(obby::user& user) { m_log_chat.log(user.get_name() + " has left", "blue"); } void Gobby::Chat::obby_document_insert(obby::document& document) { } void Gobby::Chat::obby_document_remove(obby::document& document) { } void Gobby::Chat::obby_message(obby::user& user, const Glib::ustring& message) { m_log_chat.log("<" + user.get_name() + "> " + message, "black"); } void Gobby::Chat::obby_server_message(const Glib::ustring& message) { m_log_chat.log(message, "forest green"); } void Gobby::Chat::on_chat() { Glib::ustring message = m_ent_chat.get_text(); if(message.empty() ) return; m_ent_chat.set_text(""); // Send each line separately Glib::ustring::size_type prev = 0, pos = 0; while( (pos = message.find('\n', pos)) != Glib::ustring::npos) { m_signal_chat.emit(message.substr(prev, pos - prev) ); prev = ++pos; } m_signal_chat.emit(message.substr(prev) ); } <|endoftext|>
<commit_before>/** * Copyright (C) 2021 3D Repo Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "repo_license.h" #include "repo_log.h" #include "datastructure/repo_uuid.h" #include "repo_exception.h" #include "repo_utils.h" using namespace repo::lib; #ifdef REPO_LICENSE_CHECK #include "cryptolens/Error.hpp" static const std::string licenseEnvVarName = "REPO_LICENSE"; static const std::string instanceUuidEnvVarName = "REPO_INSTANCE_ID"; static const std::string pubKeyModulus = LICENSE_RSA_PUB_KEY_MOD; static const std::string pubKeyExponent = LICENSE_RSA_PUB_KEY_EXP; static const std::string authToken = LICENSE_AUTH_TOKEN; static const int floatingTimeIntervalSec = LICENSE_TIMEOUT_SECONDS; static const int productId = LICENSE_PRODUCT_ID; std::string LicenseValidator::getInstanceUuid() { instanceUuid = instanceUuid.empty() ? repo::lib::getEnvString(instanceUuidEnvVarName) : instanceUuid; if (instanceUuid.empty()) { instanceUuid = repo::lib::RepoUUID::createUUID().toString(); repoInfo << instanceUuidEnvVarName << " is not set. Setting machine instance ID to " << instanceUuid; } return instanceUuid; } std::string LicenseValidator::getLicenseString() { std::string licenseStr = repo::lib::getEnvString(licenseEnvVarName); if (licenseStr.empty()) { std::string errMsg = "License not found, please ensure " + licenseEnvVarName + " is set."; repoError << errMsg; throw repo::lib::RepoInvalidLicenseException(errMsg); } return licenseStr; } std::string LicenseValidator::getFormattedUtcTime(time_t timeStamp) { struct tm tstruct = *gmtime(&timeStamp); char buf[80]; strftime(buf, sizeof(buf), "%Y/%m/%d %X", &tstruct); std::string formatedStr(buf); return formatedStr; } bool LicenseValidator::sendActivateRequest(bool verbose) { cryptolens::Error e; cryptolens::optional<cryptolens::LicenseKey> licenseKey = cryptolensHandle->activate_floating ( e, authToken, productId, license, floatingTimeIntervalSec ); if (e) { cryptolens::ActivateError error = cryptolens::ActivateError::from_reason(e.get_reason()); std::string errMsg = error.what(); repoError << "License activation failed: " << errMsg; return false; } else { bool licenseBlocked = licenseKey->get_block(); bool licenseExpired = static_cast<bool>(licenseKey->check().has_expired(time(0))); if (!licenseExpired && !licenseBlocked) { if (verbose) { repoTrace << "****License activation summary****"; repoTrace << "- session license ID: " << instanceUuid; repoTrace << "- server message: " << (licenseKey->get_notes().has_value() ? licenseKey->get_notes().value() : ""); repoTrace << "- server respose ok: true"; repoTrace << "- license blocked: " << licenseBlocked; repoTrace << "- license expired: " << licenseExpired; repoTrace << "- license expiry on: " << getFormattedUtcTime(licenseKey->get_expires()) << " (UTC)"; if (licenseKey->get_activated_machines().has_value()) repoTrace << "- #activated instances: " << licenseKey->get_activated_machines()->size(); if (licenseKey->get_maxnoofmachines().has_value()) repoTrace << "- allowed instances: " << licenseKey->get_maxnoofmachines().value(); repoInfo << "License activated"; repoTrace << "**********************************"; } return true; } else { std::string errMsg = licenseExpired ? "License expired." : " License is blocked"; repoError << "License activation failed: " << errMsg; deactivate(); return false; } } } void LicenseValidator::runHeartBeatLoop() { auto interval = floatingTimeIntervalSec <= 10 ? floatingTimeIntervalSec / 2 : 5; while (true) { std::this_thread::sleep_for(std::chrono::seconds(interval)); if (!sendHeartBeat.load()) { repoTrace << "Signal received to stop heart beat"; break; } auto start = std::chrono::high_resolution_clock::now(); if (!sendActivateRequest()) { auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start); repoError << "Heart beat to license server was not acknowledged [" << duration << "ms]"; break; } auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start); repoTrace << "Heart beat acknowledged ["<< duration<< "ms]"; } } #endif void LicenseValidator::activate() { #ifdef REPO_LICENSE_CHECK if (!instanceUuid.empty() || cryptolensHandle) { repoError << " Attempting to activate more than once, aborting activation"; return; } license = getLicenseString(); cryptolens::Error e; cryptolensHandle = std::unique_ptr<Cryptolens>(new Cryptolens(e)); cryptolensHandle->signature_verifier.set_modulus_base64(e, pubKeyModulus); cryptolensHandle->signature_verifier.set_exponent_base64(e, pubKeyExponent); cryptolensHandle->machine_code_computer.set_machine_code(e, getInstanceUuid()); if (e || !sendActivateRequest(true)) { std::string errMsg = "Failed to activate license"; if (e) { cryptolens::ActivateError error = cryptolens::ActivateError::from_reason(e.get_reason()); errMsg = error.what(); } throw repo::lib::RepoInvalidLicenseException(errMsg); } // launch a thread to keep sending heart beats auto thread = new std::thread([](LicenseValidator *obj) {obj->runHeartBeatLoop();}, this); heartBeatThread = std::unique_ptr<std::thread>(thread); #endif } void LicenseValidator::deactivate() { #ifdef REPO_LICENSE_CHECK if (instanceUuid.empty() || !cryptolensHandle) { repoError << " Attempting to deactivate without activation, aborting deactivation"; return; } if (heartBeatThread) { repoInfo << "Waiting for heart beat thread to finish..."; sendHeartBeat.store(false); heartBeatThread->join(); } cryptolens::Error e; cryptolensHandle->deactivate( e, authToken, productId, license, instanceUuid, true); if (e) { repoTrace << "****License deactivation summary****"; cryptolens::ActivateError error = cryptolens::ActivateError::from_reason(e.get_reason()); repoTrace << "- server message: " << error.what(); repoTrace << "- session license ID: " << instanceUuid; repoTrace << "- deactivation result: session not removed from license. Error trying to deactivate license. "; repoTrace << " this allocation will time out in less than " << floatingTimeIntervalSec << " seconds"; repoTrace << "************************************"; repoTrace << "License deactivation failed: " << error.what(); } cryptolensHandle.reset(); instanceUuid.clear(); #endif }<commit_msg>ISSUE #519 need .count() to print out chrono::ms<commit_after>/** * Copyright (C) 2021 3D Repo Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "repo_license.h" #include "repo_log.h" #include "datastructure/repo_uuid.h" #include "repo_exception.h" #include "repo_utils.h" using namespace repo::lib; #ifdef REPO_LICENSE_CHECK #include "cryptolens/Error.hpp" static const std::string licenseEnvVarName = "REPO_LICENSE"; static const std::string instanceUuidEnvVarName = "REPO_INSTANCE_ID"; static const std::string pubKeyModulus = LICENSE_RSA_PUB_KEY_MOD; static const std::string pubKeyExponent = LICENSE_RSA_PUB_KEY_EXP; static const std::string authToken = LICENSE_AUTH_TOKEN; static const int floatingTimeIntervalSec = LICENSE_TIMEOUT_SECONDS; static const int productId = LICENSE_PRODUCT_ID; std::string LicenseValidator::getInstanceUuid() { instanceUuid = instanceUuid.empty() ? repo::lib::getEnvString(instanceUuidEnvVarName) : instanceUuid; if (instanceUuid.empty()) { instanceUuid = repo::lib::RepoUUID::createUUID().toString(); repoInfo << instanceUuidEnvVarName << " is not set. Setting machine instance ID to " << instanceUuid; } return instanceUuid; } std::string LicenseValidator::getLicenseString() { std::string licenseStr = repo::lib::getEnvString(licenseEnvVarName); if (licenseStr.empty()) { std::string errMsg = "License not found, please ensure " + licenseEnvVarName + " is set."; repoError << errMsg; throw repo::lib::RepoInvalidLicenseException(errMsg); } return licenseStr; } std::string LicenseValidator::getFormattedUtcTime(time_t timeStamp) { struct tm tstruct = *gmtime(&timeStamp); char buf[80]; strftime(buf, sizeof(buf), "%Y/%m/%d %X", &tstruct); std::string formatedStr(buf); return formatedStr; } bool LicenseValidator::sendActivateRequest(bool verbose) { cryptolens::Error e; cryptolens::optional<cryptolens::LicenseKey> licenseKey = cryptolensHandle->activate_floating ( e, authToken, productId, license, floatingTimeIntervalSec ); if (e) { cryptolens::ActivateError error = cryptolens::ActivateError::from_reason(e.get_reason()); std::string errMsg = error.what(); repoError << "License activation failed: " << errMsg; return false; } else { bool licenseBlocked = licenseKey->get_block(); bool licenseExpired = static_cast<bool>(licenseKey->check().has_expired(time(0))); if (!licenseExpired && !licenseBlocked) { if (verbose) { repoTrace << "****License activation summary****"; repoTrace << "- session license ID: " << instanceUuid; repoTrace << "- server message: " << (licenseKey->get_notes().has_value() ? licenseKey->get_notes().value() : ""); repoTrace << "- server respose ok: true"; repoTrace << "- license blocked: " << licenseBlocked; repoTrace << "- license expired: " << licenseExpired; repoTrace << "- license expiry on: " << getFormattedUtcTime(licenseKey->get_expires()) << " (UTC)"; if (licenseKey->get_activated_machines().has_value()) repoTrace << "- #activated instances: " << licenseKey->get_activated_machines()->size(); if (licenseKey->get_maxnoofmachines().has_value()) repoTrace << "- allowed instances: " << licenseKey->get_maxnoofmachines().value(); repoInfo << "License activated"; repoTrace << "**********************************"; } return true; } else { std::string errMsg = licenseExpired ? "License expired." : " License is blocked"; repoError << "License activation failed: " << errMsg; deactivate(); return false; } } } void LicenseValidator::runHeartBeatLoop() { auto interval = floatingTimeIntervalSec <= 10 ? floatingTimeIntervalSec / 2 : 5; while (true) { std::this_thread::sleep_for(std::chrono::seconds(interval)); if (!sendHeartBeat.load()) { repoTrace << "Signal received to stop heart beat"; break; } auto start = std::chrono::high_resolution_clock::now(); if (!sendActivateRequest()) { auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start); repoError << "Heart beat to license server was not acknowledged [" << std::to_string(duration.count()) << "ms]"; break; } auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start); repoTrace << "Heart beat acknowledged ["<< std::to_string(duration.count()) << "ms]"; } } #endif void LicenseValidator::activate() { #ifdef REPO_LICENSE_CHECK if (!instanceUuid.empty() || cryptolensHandle) { repoError << " Attempting to activate more than once, aborting activation"; return; } license = getLicenseString(); cryptolens::Error e; cryptolensHandle = std::unique_ptr<Cryptolens>(new Cryptolens(e)); cryptolensHandle->signature_verifier.set_modulus_base64(e, pubKeyModulus); cryptolensHandle->signature_verifier.set_exponent_base64(e, pubKeyExponent); cryptolensHandle->machine_code_computer.set_machine_code(e, getInstanceUuid()); if (e || !sendActivateRequest(true)) { std::string errMsg = "Failed to activate license"; if (e) { cryptolens::ActivateError error = cryptolens::ActivateError::from_reason(e.get_reason()); errMsg = error.what(); } throw repo::lib::RepoInvalidLicenseException(errMsg); } // launch a thread to keep sending heart beats auto thread = new std::thread([](LicenseValidator *obj) {obj->runHeartBeatLoop();}, this); heartBeatThread = std::unique_ptr<std::thread>(thread); #endif } void LicenseValidator::deactivate() { #ifdef REPO_LICENSE_CHECK if (instanceUuid.empty() || !cryptolensHandle) { repoError << " Attempting to deactivate without activation, aborting deactivation"; return; } if (heartBeatThread) { repoInfo << "Waiting for heart beat thread to finish..."; sendHeartBeat.store(false); heartBeatThread->join(); } cryptolens::Error e; cryptolensHandle->deactivate( e, authToken, productId, license, instanceUuid, true); if (e) { repoTrace << "****License deactivation summary****"; cryptolens::ActivateError error = cryptolens::ActivateError::from_reason(e.get_reason()); repoTrace << "- server message: " << error.what(); repoTrace << "- session license ID: " << instanceUuid; repoTrace << "- deactivation result: session not removed from license. Error trying to deactivate license. "; repoTrace << " this allocation will time out in less than " << floatingTimeIntervalSec << " seconds"; repoTrace << "************************************"; repoTrace << "License deactivation failed: " << error.what(); } cryptolensHandle.reset(); instanceUuid.clear(); #endif }<|endoftext|>
<commit_before>// Copyright (c) 2012 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-CHROMIUM file. #include "browser/url_request_context_getter.h" #include "network_delegate.h" #include "base/string_util.h" #include "base/threading/worker_pool.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/cookie_store_factory.h" #include "content/public/common/url_constants.h" #include "net/cert/cert_verifier.h" #include "net/cookies/cookie_monster.h" #include "net/http/http_auth_handler_factory.h" #include "net/http/http_cache.h" #include "net/http/http_server_properties_impl.h" #include "net/proxy/proxy_service.h" #include "net/ssl/default_server_bound_cert_store.h" #include "net/ssl/server_bound_cert_service.h" #include "net/ssl/ssl_config_service_defaults.h" #include "net/url_request/static_http_user_agent_settings.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_storage.h" #include "net/url_request/url_request_job_factory_impl.h" namespace brightray { URLRequestContextGetter::URLRequestContextGetter( const base::FilePath& base_path, MessageLoop* io_loop, MessageLoop* file_loop, content::ProtocolHandlerMap* protocol_handlers) : base_path_(base_path), io_loop_(io_loop), file_loop_(file_loop) { // Must first be created on the UI thread. DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); std::swap(protocol_handlers_, *protocol_handlers); proxy_config_service_.reset(net::ProxyService::CreateSystemProxyConfigService(io_loop_->message_loop_proxy(), file_loop_)); } URLRequestContextGetter::~URLRequestContextGetter() { } net::HostResolver* URLRequestContextGetter::host_resolver() { return url_request_context_->host_resolver(); } net::URLRequestContext* URLRequestContextGetter::GetURLRequestContext() { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); if (!url_request_context_.get()) { url_request_context_.reset(new net::URLRequestContext()); network_delegate_.reset(new NetworkDelegate); url_request_context_->set_network_delegate(network_delegate_.get()); storage_.reset( new net::URLRequestContextStorage(url_request_context_.get())); storage_->set_cookie_store(content::CreatePersistentCookieStore( base_path_.Append(FILE_PATH_LITERAL("Cookies")), false, nullptr, nullptr)); storage_->set_server_bound_cert_service(new net::ServerBoundCertService( new net::DefaultServerBoundCertStore(NULL), base::WorkerPool::GetTaskRunner(true))); storage_->set_http_user_agent_settings( new net::StaticHttpUserAgentSettings( "en-us,en", EmptyString())); scoped_ptr<net::HostResolver> host_resolver( net::HostResolver::CreateDefaultResolver(NULL)); storage_->set_cert_verifier(net::CertVerifier::CreateDefault()); // TODO(jam): use v8 if possible, look at chrome code. storage_->set_proxy_service( net::ProxyService::CreateUsingSystemProxyResolver( proxy_config_service_.release(), 0, NULL)); storage_->set_ssl_config_service(new net::SSLConfigServiceDefaults); storage_->set_http_auth_handler_factory( net::HttpAuthHandlerFactory::CreateDefault(host_resolver.get())); storage_->set_http_server_properties(new net::HttpServerPropertiesImpl); base::FilePath cache_path = base_path_.Append(FILE_PATH_LITERAL("Cache")); net::HttpCache::DefaultBackend* main_backend = new net::HttpCache::DefaultBackend( net::DISK_CACHE, net::CACHE_BACKEND_DEFAULT, cache_path, 0, content::BrowserThread::GetMessageLoopProxyForThread( content::BrowserThread::CACHE)); net::HttpNetworkSession::Params network_session_params; network_session_params.cert_verifier = url_request_context_->cert_verifier(); network_session_params.server_bound_cert_service = url_request_context_->server_bound_cert_service(); network_session_params.proxy_service = url_request_context_->proxy_service(); network_session_params.ssl_config_service = url_request_context_->ssl_config_service(); network_session_params.http_auth_handler_factory = url_request_context_->http_auth_handler_factory(); network_session_params.network_delegate = url_request_context_->network_delegate(); network_session_params.http_server_properties = url_request_context_->http_server_properties(); network_session_params.ignore_certificate_errors = false; // Give |storage_| ownership at the end in case it's |mapped_host_resolver|. storage_->set_host_resolver(host_resolver.Pass()); network_session_params.host_resolver = url_request_context_->host_resolver(); net::HttpCache* main_cache = new net::HttpCache( network_session_params, main_backend); storage_->set_http_transaction_factory(main_cache); scoped_ptr<net::URLRequestJobFactoryImpl> job_factory( new net::URLRequestJobFactoryImpl()); for (auto it = protocol_handlers_.begin(), end = protocol_handlers_.end(); it != end; ++it) { bool set_protocol = job_factory->SetProtocolHandler(it->first, it->second.release()); DCHECK(set_protocol); } protocol_handlers_.clear(); storage_->set_job_factory(job_factory.release()); } return url_request_context_.get(); } scoped_refptr<base::SingleThreadTaskRunner> URLRequestContextGetter::GetNetworkTaskRunner() const { return content::BrowserThread::GetMessageLoopProxyForThread(content::BrowserThread::IO); } } <commit_msg>Set file and data protocol handler.<commit_after>// Copyright (c) 2012 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-CHROMIUM file. #include "browser/url_request_context_getter.h" #include "network_delegate.h" #include "base/string_util.h" #include "base/threading/worker_pool.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/cookie_store_factory.h" #include "content/public/common/url_constants.h" #include "net/cert/cert_verifier.h" #include "net/cookies/cookie_monster.h" #include "net/http/http_auth_handler_factory.h" #include "net/http/http_cache.h" #include "net/http/http_server_properties_impl.h" #include "net/proxy/proxy_service.h" #include "net/ssl/default_server_bound_cert_store.h" #include "net/ssl/server_bound_cert_service.h" #include "net/ssl/ssl_config_service_defaults.h" #include "net/url_request/data_protocol_handler.h" #include "net/url_request/file_protocol_handler.h" #include "net/url_request/static_http_user_agent_settings.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_storage.h" #include "net/url_request/url_request_job_factory_impl.h" namespace brightray { URLRequestContextGetter::URLRequestContextGetter( const base::FilePath& base_path, MessageLoop* io_loop, MessageLoop* file_loop, content::ProtocolHandlerMap* protocol_handlers) : base_path_(base_path), io_loop_(io_loop), file_loop_(file_loop) { // Must first be created on the UI thread. DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); std::swap(protocol_handlers_, *protocol_handlers); proxy_config_service_.reset(net::ProxyService::CreateSystemProxyConfigService(io_loop_->message_loop_proxy(), file_loop_)); } URLRequestContextGetter::~URLRequestContextGetter() { } net::HostResolver* URLRequestContextGetter::host_resolver() { return url_request_context_->host_resolver(); } net::URLRequestContext* URLRequestContextGetter::GetURLRequestContext() { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); if (!url_request_context_.get()) { url_request_context_.reset(new net::URLRequestContext()); network_delegate_.reset(new NetworkDelegate); url_request_context_->set_network_delegate(network_delegate_.get()); storage_.reset( new net::URLRequestContextStorage(url_request_context_.get())); storage_->set_cookie_store(content::CreatePersistentCookieStore( base_path_.Append(FILE_PATH_LITERAL("Cookies")), false, nullptr, nullptr)); storage_->set_server_bound_cert_service(new net::ServerBoundCertService( new net::DefaultServerBoundCertStore(NULL), base::WorkerPool::GetTaskRunner(true))); storage_->set_http_user_agent_settings( new net::StaticHttpUserAgentSettings( "en-us,en", EmptyString())); scoped_ptr<net::HostResolver> host_resolver( net::HostResolver::CreateDefaultResolver(NULL)); storage_->set_cert_verifier(net::CertVerifier::CreateDefault()); // TODO(jam): use v8 if possible, look at chrome code. storage_->set_proxy_service( net::ProxyService::CreateUsingSystemProxyResolver( proxy_config_service_.release(), 0, NULL)); storage_->set_ssl_config_service(new net::SSLConfigServiceDefaults); storage_->set_http_auth_handler_factory( net::HttpAuthHandlerFactory::CreateDefault(host_resolver.get())); storage_->set_http_server_properties(new net::HttpServerPropertiesImpl); base::FilePath cache_path = base_path_.Append(FILE_PATH_LITERAL("Cache")); net::HttpCache::DefaultBackend* main_backend = new net::HttpCache::DefaultBackend( net::DISK_CACHE, net::CACHE_BACKEND_DEFAULT, cache_path, 0, content::BrowserThread::GetMessageLoopProxyForThread( content::BrowserThread::CACHE)); net::HttpNetworkSession::Params network_session_params; network_session_params.cert_verifier = url_request_context_->cert_verifier(); network_session_params.server_bound_cert_service = url_request_context_->server_bound_cert_service(); network_session_params.proxy_service = url_request_context_->proxy_service(); network_session_params.ssl_config_service = url_request_context_->ssl_config_service(); network_session_params.http_auth_handler_factory = url_request_context_->http_auth_handler_factory(); network_session_params.network_delegate = url_request_context_->network_delegate(); network_session_params.http_server_properties = url_request_context_->http_server_properties(); network_session_params.ignore_certificate_errors = false; // Give |storage_| ownership at the end in case it's |mapped_host_resolver|. storage_->set_host_resolver(host_resolver.Pass()); network_session_params.host_resolver = url_request_context_->host_resolver(); net::HttpCache* main_cache = new net::HttpCache( network_session_params, main_backend); storage_->set_http_transaction_factory(main_cache); scoped_ptr<net::URLRequestJobFactoryImpl> job_factory( new net::URLRequestJobFactoryImpl()); for (auto it = protocol_handlers_.begin(), end = protocol_handlers_.end(); it != end; ++it) { bool set_protocol = job_factory->SetProtocolHandler(it->first, it->second.release()); DCHECK(set_protocol); } protocol_handlers_.clear(); job_factory->SetProtocolHandler(chrome::kDataScheme, new net::DataProtocolHandler); job_factory->SetProtocolHandler(chrome::kFileScheme, new net::FileProtocolHandler); storage_->set_job_factory(job_factory.release()); } return url_request_context_.get(); } scoped_refptr<base::SingleThreadTaskRunner> URLRequestContextGetter::GetNetworkTaskRunner() const { return content::BrowserThread::GetMessageLoopProxyForThread(content::BrowserThread::IO); } } <|endoftext|>
<commit_before>// ===================================================================================== // // Filename: demo.cpp // // Description: replacement for LRC (demo) // // Version: 1.0 // Created: 2013/8/26 下午 08:33:37 // Revision: none // Compiler: g++ // // Author: Shuai YUAN (galoisplusplus), yszheda AT gmail DOT com // Company: // // ===================================================================================== #include <iostream> #include <algorithm> #include <vector> #include <map> #include <limits> #include <cmath> #include <cassert> // #include "GaloisFieldValue.hpp" using namespace std; //---------------------------------------------------------------------- // Input //---------------------------------------------------------------------- // erasure code parameter // required node number // int n; // minimum decodable chunk number // int k; // normally it should contains n and k // vector<int> param; // LRC parameter // parameter k int in_chunk_num = 6; int group_num = 2; int global_parities_num = 2; // parameter n int out_chunk_num = in_chunk_num + group_num + global_parities_num; // encoding matrix const int gf_width = 4; // vector< GaloisFieldValue<gf_width> > encoding_matrix; // total node number int node_num = 20; // node_num node availability vector vector<double> avail(node_num); // required system availability double delta = 0.99; //---------------------------------------------------------------------- // Output //---------------------------------------------------------------------- // optimal assignment vector // store the corresponding chunk index for each node // -1 for not assigned vector<int> opt_assignment; //---------------------------------------------------------------------- // Variables //---------------------------------------------------------------------- // recoverable failure and its min regeneration cost list // up to 2^n // <recoverable_failure_state, cost> vector< pair<long, int> > recoverable_failure_cost_list; // availability list of the n selected nodes vector<double> selected_avail(out_chunk_num); // failure counter struct counter { int total_cnt = 0; int global_parities_cnt = 0; vector<int> local_parities_cnt = {0}; vector<int> native_chunks_cnt = {0}; } failure_cnt; // ---------- end of struct counter ---------- // === FUNCTION ====================================================================== // Name: update_failure_cnt // Description: update failure counter // ===================================================================================== void update_failure_cnt( const long failure_state ) { for (auto i = 0; i < out_chunk_num; i++) { if (failure_state & 0x01 == 1) { failure_cnt.total_cnt ++; if (i < global_parities_num) { failure_cnt.global_parities_cnt ++; } else if (i < global_parities_num + group_num) { failure_cnt.local_parities_cnt[i - global_parities_num] = 1; } else { failure_cnt.native_chunks_cnt[i - global_parities_num - group_num] ++; } } } } /* template < typename T > bool check_invertable( int size, vector< T >& matrix ) { bool is_invertable = true; for (auto row = 0; row < size; row++) { int pivot_idx = -1; for (auto col = 0; col < size; col++) { if (matrix[row * size + col] != T(0)) { pivot_idx = col; break; } } if (pivot_idx == -1) { is_invertable = false; } } return is_invertable; } void get_solver_matrix( long failure_state, vector< GaloisFieldValue<gf_width> > &encoding_matrix, vector< GaloisFieldValue<gf_width> > &slover_matrix ) { } */ // === FUNCTION ====================================================================== // Name: check_recovable // Description: check whether the current failure state is recoverable // ===================================================================================== bool check_recoverable( const long failure_state ) { bool is_recovable = false; update_failure_cnt(failure_state); if (failure_cnt.total_cnt <= global_parities_num + 1) { is_recoverable = true; } else if (failure_cnt.total_cnt == global_parities_num + 2) { // Currently work for LRC(6, 2, 2) if (failure_cnt.local_parities_cnt[0] == 1 && failure_cnt.local_parities_cnt[1] == 1) { if (failure_cnt.native_chunks_cnt[0] = 1 && failure_cnt.native_chunks_cnt[1] == 1) { is_recoverable = true; } } else if (failure_cnt.local_parities_cnt[0] == 1 || failure_cnt.local_parities_cnt[1] == 1) { int group_fail_cnt[2]; group_fail_cnt[0] = failure_cnt.native_chunks_cnt[0] + failure_cnt.local_parities_cnt[0]; group_fail_cnt[1] = failure_cnt.native_chunks_cnt[1] + failure_cnt.local_parities_cnt[1]; if (group_fail_cnt[0] == 2 && group_fail_cnt[1] == 2) { is_recoverable = true; } } else if (failure_cnt.local_parities_cnt[0] == 0 && failure_cnt.local_parities_cnt[1] == 0) { if (failure_cnt.native_chunks_cnt[0] == 2 && failure_cnt.native_chunks_cnt[1] == 2) { is_recoverable = true; } } } return is_recoverable; } // === FUNCTION ====================================================================== // Name: get_min_cost // Description: obtain the min cost for the current failure state // ===================================================================================== int get_min_cost( const long failure_state ) { update_failure_cnt(failure_state); int min_cost = 0; if (failure_cnt.global_parities_cnt > 0) { min_cost = in_chunk_num; } else { bool is_local_recovable = true; int failed_group = 0; for (auto i = 0; i < group_num; i++) { if (failure_cnt.native_chunks_cnt[i] + failure_cnt.local_parities_cnt[i] > 1) { is_local_recovable = false; min_cost = in_chunk_num; } if (failure_cnt.native_chunks_cnt[i] + failure_cnt.local_parities_cnt[i] > 0) { failed_group ++; } } if (is_local_recovable == true) { min_cost = failed_group * (in_chunk_num / group_num); } } return min_cost; } // === FUNCTION ====================================================================== // Name: gen_recoverable_failure_cost_list // Description: generate the list of recoverable failure and its min cost // ===================================================================================== void gen_recoverable_failure_cost_list ( ) { long failure_state = 0; // failure_state is a n-bit bitmap long max_failure_state = (1 << out_chunk_num) - 1; while ( failure_state <= max_failure_state ) { bool is_recoverable = check_recoverable(failure_state); if ( is_recoverable == true ) { int min_cost = get_min_cost(failure_state); pair<long, int> failure_cost_pair(failure_state, min_cost); recoverable_failure_cost_list.push_back(failure_cost_pair); } failure_state ++; } return ; } // === FUNCTION ====================================================================== // Name: gen_selected_node_avail_list // Description: generate the availability list of the selected nodes // ===================================================================================== void gen_selected_node_avail_list ( const vector<int>& assignment ) { for ( auto idx = 0; idx < assignment.size(); idx++ ) { int chunk_idx = assignment[idx]; selected_avail[idx] = avail[chunk_idx]; } return ; } // === FUNCTION ====================================================================== // Name: get_system_avail // Description: get the system availability according to the current assignment // ===================================================================================== double get_system_avail ( const vector<int>& assignment ) { gen_selected_node_avail_list(assignment); double system_avail = 0.0; for ( vector< pair<long, int> >::const_iterator it = recoverable_failure_cost_list.begin(); it != recoverable_failure_cost_list.end(); it++ ) { long failure_state = it->first; double failure_state_avail = 1; for ( auto i = 0; i < out_chunk_num ; i++ ) { if ( failure_state & 0x01 == 1 ) { failure_state_avail *= (1 - selected_avail[i]); } else { failure_state_avail *= selected_avail[i]; } failure_state >>= 1; } system_avail += failure_state_avail; } return system_avail; } // ----- end of function get_system_avail ----- // === FUNCTION ====================================================================== // Name: get_total_cost // Description: get total regeneration cost for the current assignment // ===================================================================================== double get_total_cost ( const vector<int>& assignment ) { gen_selected_node_avail_list(assignment); double total_cost = 0.0; for ( vector< pair<long, int> >::const_iterator it = recoverable_failure_cost_list.begin(); it != recoverable_failure_cost_list.end(); it++ ) { long failure_state = it->first; int failure_state_cost = it->second; double failure_state_avail = 1; for ( auto i = 0; i < out_chunk_num ; i++ ) { if ( failure_state & 0x01 == 1 ) { failure_state_avail *= (1 - selected_avail[i]); } else { failure_state_avail *= selected_avail[i]; } failure_state >>= 1; } total_cost += failure_state_avail * failure_state_cost; } return total_cost; } // ----- end of function get_total_cost ----- bool next_combination( const int total_size, const int subset_size, vector<int>&subset ) { // int i; // for (i = 0; i < subset_size-1; i++) { // if (subset[i+1] == subset[i] + 1) { // subset[i] = i + 1; // } else { // break; // } // } // if (total_size < subset[i] - 1) { // } if (subset[0] >= total_size - subset_size) { return false; } int pivot_idx; for (pivot_idx = subset_size-1; pivot_idx > 0; pivot_idx --) { if (subset[pivot_idx] - pivot_idx < total_size - subset_size) { break; } } int pivot = subset[pivot_idx]; for (auto i = pivot; i < subset_size; i++) { subset[pivot_idx] = ++pivot; } return true; } int main ( int argc, char *argv[] ) { // SpecifiedCode someCode(param); // ErasureCode& code = someCode; // gen_recoverable_failure_list(code); // gen_min_cost_list(code); gen_recoverable_failure_cost_list(); vector<int> assignment; for (auto i = 0; i < out_chunk_num; i++) { assignment[i] = i; } double min_total_cost = numeric_limits<double>::infinity(); do { do { double system_avail = get_system_avail(assignment); // check whether the availability violates the SLA if ( system_avail >= delta ) { double total_cost = get_total_cost(assignment); if ( total_cost < min_total_cost ) { min_total_cost = total_cost; opt_assignment = assignment; } } } while ( std::next_permutation(assignment.begin(), assignment.end()) ); } while ( next_combination(node_num, out_chunk_num, assignment) ); return EXIT_SUCCESS; } // ---------- end of function main ---------- <commit_msg>complete demo for LRC(6,2,2)<commit_after>// ===================================================================================== // // Filename: demo.cpp // // Description: replacement for LRC (demo) // // Version: 1.0 // Created: 2013/8/26 下午 08:33:37 // Revision: none // Compiler: g++ // // Author: Shuai YUAN (galoisplusplus), yszheda AT gmail DOT com // Company: // // ===================================================================================== #include <iostream> #include <fstream> #include <iterator> #include <algorithm> #include <vector> #include <map> #include <limits> #include <cmath> #include <cassert> // #include "GaloisFieldValue.hpp" using namespace std; //---------------------------------------------------------------------- // Input //---------------------------------------------------------------------- // erasure code parameter // required node number // int n; // minimum decodable chunk number // int k; // normally it should contains n and k // vector<int> param; // LRC parameter // parameter k int in_chunk_num = 6; int group_num = 2; int global_parities_num = 2; // parameter n int out_chunk_num = in_chunk_num + group_num + global_parities_num; // encoding matrix const int gf_width = 4; // vector< GaloisFieldValue<gf_width> > encoding_matrix; // total node number int node_num = 20; // node_num node availability vector // vector<double> avail(node_num); vector<double> avail; // required system availability double delta = 0.99; //---------------------------------------------------------------------- // Output //---------------------------------------------------------------------- // optimal assignment vector // store the corresponding chunk index for each node // -1 for not assigned vector<int> opt_assignment; //---------------------------------------------------------------------- // Variables //---------------------------------------------------------------------- // recoverable failure and its min regeneration cost list // up to 2^n // <recoverable_failure_state, cost> vector< pair<long, int> > recoverable_failure_cost_list; // availability list of the n selected nodes vector<double> selected_avail(out_chunk_num); // failure counter struct counter { int total_cnt = 0; int global_parities_cnt = 0; vector<int> local_parities_cnt = {0}; vector<int> native_chunks_cnt = {0}; } failure_cnt; // ---------- end of struct counter ---------- // === FUNCTION ====================================================================== // Name: update_failure_cnt // Description: update failure counter // ===================================================================================== void update_failure_cnt( const long failure_state ) { for (auto i = 0; i < out_chunk_num; i++) { if (failure_state & 0x01 == 1) { failure_cnt.total_cnt ++; if (i < global_parities_num) { failure_cnt.global_parities_cnt ++; } else if (i < global_parities_num + group_num) { failure_cnt.local_parities_cnt[i - global_parities_num] = 1; } else { failure_cnt.native_chunks_cnt[i - global_parities_num - group_num] ++; } } } } /* template < typename T > bool check_invertable( int size, vector< T >& matrix ) { bool is_invertable = true; for (auto row = 0; row < size; row++) { int pivot_idx = -1; for (auto col = 0; col < size; col++) { if (matrix[row * size + col] != T(0)) { pivot_idx = col; break; } } if (pivot_idx == -1) { is_invertable = false; } } return is_invertable; } void get_solver_matrix( long failure_state, vector< GaloisFieldValue<gf_width> > &encoding_matrix, vector< GaloisFieldValue<gf_width> > &slover_matrix ) { } */ // === FUNCTION ====================================================================== // Name: check_recovable // Description: check whether the current failure state is recoverable // ===================================================================================== bool check_recoverable( const long failure_state ) { bool is_recoverable = false; update_failure_cnt(failure_state); if (failure_cnt.total_cnt <= global_parities_num + 1) { is_recoverable = true; } else if (failure_cnt.total_cnt == global_parities_num + 2) { // Currently work for LRC(6, 2, 2) if (failure_cnt.local_parities_cnt[0] == 1 && failure_cnt.local_parities_cnt[1] == 1) { if (failure_cnt.native_chunks_cnt[0] = 1 && failure_cnt.native_chunks_cnt[1] == 1) { is_recoverable = true; } } else if (failure_cnt.local_parities_cnt[0] == 1 || failure_cnt.local_parities_cnt[1] == 1) { int group_fail_cnt[2]; group_fail_cnt[0] = failure_cnt.native_chunks_cnt[0] + failure_cnt.local_parities_cnt[0]; group_fail_cnt[1] = failure_cnt.native_chunks_cnt[1] + failure_cnt.local_parities_cnt[1]; if (group_fail_cnt[0] == 2 && group_fail_cnt[1] == 2) { is_recoverable = true; } } else if (failure_cnt.local_parities_cnt[0] == 0 && failure_cnt.local_parities_cnt[1] == 0) { if (failure_cnt.native_chunks_cnt[0] == 2 && failure_cnt.native_chunks_cnt[1] == 2) { is_recoverable = true; } } } return is_recoverable; } // === FUNCTION ====================================================================== // Name: get_min_cost // Description: obtain the min cost for the current failure state // ===================================================================================== int get_min_cost( const long failure_state ) { update_failure_cnt(failure_state); int min_cost = 0; if (failure_cnt.global_parities_cnt > 0) { min_cost = in_chunk_num; } else { bool is_local_recovable = true; int failed_group = 0; for (auto i = 0; i < group_num; i++) { if (failure_cnt.native_chunks_cnt[i] + failure_cnt.local_parities_cnt[i] > 1) { is_local_recovable = false; min_cost = in_chunk_num; } if (failure_cnt.native_chunks_cnt[i] + failure_cnt.local_parities_cnt[i] > 0) { failed_group ++; } } if (is_local_recovable == true) { min_cost = failed_group * (in_chunk_num / group_num); } } return min_cost; } // === FUNCTION ====================================================================== // Name: gen_recoverable_failure_cost_list // Description: generate the list of recoverable failure and its min cost // ===================================================================================== void gen_recoverable_failure_cost_list ( ) { long failure_state = 0; // failure_state is a n-bit bitmap long max_failure_state = (1 << out_chunk_num) - 1; while ( failure_state <= max_failure_state ) { bool is_recoverable = check_recoverable(failure_state); if ( is_recoverable == true ) { int min_cost = get_min_cost(failure_state); pair<long, int> failure_cost_pair(failure_state, min_cost); recoverable_failure_cost_list.push_back(failure_cost_pair); } failure_state ++; } return ; } // === FUNCTION ====================================================================== // Name: gen_selected_node_avail_list // Description: generate the availability list of the selected nodes // ===================================================================================== void gen_selected_node_avail_list ( const vector<int>& assignment ) { for ( auto idx = 0; idx < assignment.size(); idx++ ) { int chunk_idx = assignment[idx]; selected_avail[idx] = avail[chunk_idx]; } return ; } // === FUNCTION ====================================================================== // Name: get_system_avail // Description: get the system availability according to the current assignment // ===================================================================================== double get_system_avail ( const vector<int>& assignment ) { gen_selected_node_avail_list(assignment); double system_avail = 0.0; for ( vector< pair<long, int> >::const_iterator it = recoverable_failure_cost_list.begin(); it != recoverable_failure_cost_list.end(); it++ ) { long failure_state = it->first; double failure_state_avail = 1; for ( auto i = 0; i < out_chunk_num ; i++ ) { if ( failure_state & 0x01 == 1 ) { failure_state_avail *= (1 - selected_avail[i]); } else { failure_state_avail *= selected_avail[i]; } failure_state >>= 1; } system_avail += failure_state_avail; } return system_avail; } // ----- end of function get_system_avail ----- // === FUNCTION ====================================================================== // Name: get_total_cost // Description: get total regeneration cost for the current assignment // ===================================================================================== double get_total_cost ( const vector<int>& assignment ) { gen_selected_node_avail_list(assignment); double total_cost = 0.0; for ( vector< pair<long, int> >::const_iterator it = recoverable_failure_cost_list.begin(); it != recoverable_failure_cost_list.end(); it++ ) { long failure_state = it->first; int failure_state_cost = it->second; double failure_state_avail = 1; for ( auto i = 0; i < out_chunk_num ; i++ ) { if ( failure_state & 0x01 == 1 ) { failure_state_avail *= (1 - selected_avail[i]); } else { failure_state_avail *= selected_avail[i]; } failure_state >>= 1; } total_cost += failure_state_avail * failure_state_cost; } return total_cost; } // ----- end of function get_total_cost ----- bool next_combination( const int total_size, const int subset_size, vector<int>&subset ) { // int i; // for (i = 0; i < subset_size-1; i++) { // if (subset[i+1] == subset[i] + 1) { // subset[i] = i + 1; // } else { // break; // } // } // if (total_size < subset[i] - 1) { // } if (subset[0] >= total_size - subset_size) { return false; } int pivot_idx; for (pivot_idx = subset_size-1; pivot_idx > 0; pivot_idx --) { if (subset[pivot_idx] - pivot_idx < total_size - subset_size) { break; } } int pivot = subset[pivot_idx]; for (auto i = pivot; i < subset_size; i++) { subset[pivot_idx] = ++pivot; } return true; } void print_vector(vector<int> &v) { for (auto e: v) { cout << e << " "; } cout << endl; } int main ( int argc, char *argv[] ) { ifstream fs("demo-input.txt"); copy(istream_iterator<double>(fs), istream_iterator<double>(), back_inserter(avail)); for (auto availability: avail) { cout << availability << endl; } fs.close(); // SpecifiedCode someCode(param); // ErasureCode& code = someCode; // gen_recoverable_failure_list(code); // gen_min_cost_list(code); gen_recoverable_failure_cost_list(); vector<int> assignment; for (auto i = 0; i < out_chunk_num; i++) { assignment.push_back(i); } double min_total_cost = numeric_limits<double>::infinity(); do { vector<int> permutation(assignment); do { #ifdef DEBUG print_vector(permutation); #endif double system_avail = get_system_avail(permutation); // check whether the availability violates the SLA if ( system_avail >= delta ) { double total_cost = get_total_cost(permutation); if ( total_cost < min_total_cost ) { min_total_cost = total_cost; opt_assignment = assignment; } } } while ( std::next_permutation(permutation.begin(), permutation.end()) ); permutation.clear(); } while ( next_combination(node_num, out_chunk_num, assignment) ); cout << "min total cost is " << min_total_cost << endl; for (auto i = 0; i < out_chunk_num; ++i) { cout << "Chunk " << i << " is stored in node " << assignment[i] << endl; } return EXIT_SUCCESS; } // ---------- end of function main ---------- <|endoftext|>
<commit_before>/* SWARM Copyright (C) 2012-2022 Torbjorn Rognes and Frederic Mahe This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Contact: Torbjorn Rognes <torognes@ifi.uio.no>, Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ #include <cstdint> #include "swarm.h" #include "db.h" #include "util.h" #include "utils/hashtable_size.h" #include "zobrist.h" struct bucket { uint64_t hash = 0; unsigned int seqno_first = 0; unsigned int seqno_last = 0; uint64_t mass = 0; unsigned int size = 0; unsigned int singletons = 0; }; auto derep_compare(const void * a, const void * b) -> int { const auto * x = static_cast<const struct bucket *>(a); const auto * y = static_cast<const struct bucket *>(b); int status {0}; /* highest abundance first, otherwise keep order */ if (x->mass < y->mass) { status = +1; } else if (x->mass > y->mass) { status = -1; } else { if (x->seqno_first < y->seqno_first) { status = -1; } else if (x->seqno_first > y->seqno_first) { status = +1; } else { status = 0; } } return status; } auto write_stats_file(const uint64_t swarmcount, struct Parameters const & p, struct bucket * hashtable) -> void { progress_init("Writing stats: ", swarmcount); for(auto i = 0ULL; i < swarmcount; i++) { struct bucket * sp = hashtable + i; fprintf(statsfile, "%u\t%" PRIu64 "\t", sp->size, sp->mass); fprint_id_noabundance(statsfile, sp->seqno_first, p.opt_usearch_abundance); fprintf(statsfile, "\t%" PRIu64 "\t%u\t%u\t%u\n", db_getabundance(sp->seqno_first), sp->singletons, 0U, 0U); progress_update(i); } progress_done(); } auto write_structure_file(const uint64_t swarmcount, struct Parameters const & p, struct bucket * hashtable, unsigned int * nextseqtab) -> void { progress_init("Writing structure:", swarmcount); for(uint64_t i = 0; i < swarmcount; i++) { struct bucket * sp = hashtable + i; uint64_t seed = sp->seqno_first; unsigned int a = nextseqtab[seed]; while (a != 0U) { fprint_id_noabundance(internal_structure_file, seed, p.opt_usearch_abundance); fprintf(internal_structure_file, "\t"); fprint_id_noabundance(internal_structure_file, a, p.opt_usearch_abundance); fprintf(internal_structure_file, "\t%d\t%" PRIu64 "\t%d\n", 0, i+1, 0); a = nextseqtab[a]; } progress_update(i); } progress_done(); } auto write_swarms_uclust_format(const uint64_t swarmcount, struct Parameters const & p, struct bucket * hashtable, unsigned int * nextseqtab) -> void { progress_init("Writing UCLUST: ", swarmcount); for(auto swarmid = 0U; swarmid < swarmcount; swarmid++) { struct bucket * bp = hashtable + swarmid; unsigned int seed = bp->seqno_first; fprintf(uclustfile, "C\t%u\t%u\t*\t*\t*\t*\t*\t", swarmid, bp->size); fprint_id(uclustfile, seed, p.opt_usearch_abundance, p.opt_append_abundance); fprintf(uclustfile, "\t*\n"); fprintf(uclustfile, "S\t%u\t%u\t*\t*\t*\t*\t*\t", swarmid, db_getsequencelen(seed)); fprint_id(uclustfile, seed, p.opt_usearch_abundance, p.opt_append_abundance); fprintf(uclustfile, "\t*\n"); unsigned int a = nextseqtab[seed]; while (a != 0U) { fprintf(uclustfile, "H\t%u\t%u\t%.1f\t+\t0\t0\t%s\t", swarmid, db_getsequencelen(a), 100.0, "="); fprint_id(uclustfile, a, p.opt_usearch_abundance, p.opt_append_abundance); fprintf(uclustfile, "\t"); fprint_id(uclustfile, seed, p.opt_usearch_abundance, p.opt_append_abundance); fprintf(uclustfile, "\n"); a = nextseqtab[a]; } progress_update(swarmid+1); } progress_done(); } auto write_representative_sequences(const uint64_t swarmcount, struct Parameters const & p, struct bucket * hashtable) -> void { progress_init("Writing seeds: ", swarmcount); for(auto i = 0U; i < swarmcount; i++) { unsigned int seed = hashtable[i].seqno_first; fprintf(fp_seeds, ">"); fprint_id_with_new_abundance(fp_seeds, seed, hashtable[i].mass, p.opt_usearch_abundance); fprintf(fp_seeds, "\n"); db_fprintseq(fp_seeds, seed); progress_update(i+1); } progress_done(); } auto write_swarms_mothur_format(const uint64_t swarmcount, struct Parameters const & p, struct bucket * hashtable, unsigned int * nextseqtab) -> void { progress_init("Writing swarms: ", swarmcount); fprintf(outfile, "swarm_%" PRId64 "\t%" PRIu64, p.opt_differences, swarmcount); for(auto i = 0U; i < swarmcount; i++) { unsigned int seed = hashtable[i].seqno_first; fputc('\t', outfile); fprint_id(outfile, seed, p.opt_usearch_abundance, p.opt_append_abundance); unsigned int a = nextseqtab[seed]; while (a != 0U) { fputc(',', outfile); fprint_id(outfile, a, p.opt_usearch_abundance, p.opt_append_abundance); a = nextseqtab[a]; } progress_update(i+1); } fputc('\n', outfile); progress_done(); } auto write_swarms_default_format(const uint64_t swarmcount, struct Parameters const & p, struct bucket * hashtable, unsigned int * nextseqtab) -> void { progress_init("Writing swarms: ", swarmcount); for(auto i = 0U; i < swarmcount; i++) { unsigned int seed = hashtable[i].seqno_first; fprint_id(outfile, seed, p.opt_usearch_abundance, p.opt_append_abundance); unsigned int a = nextseqtab[seed]; while (a != 0U) { fputc(sepchar, outfile); fprint_id(outfile, a, p.opt_usearch_abundance, p.opt_append_abundance); a = nextseqtab[a]; } fputc('\n', outfile); progress_update(i+1); } progress_done(); } void dereplicate(struct Parameters const & p) { const uint64_t dbsequencecount = db_getsequencecount(); const uint64_t hashtablesize {compute_hashtable_size(dbsequencecount)}; const uint64_t derep_hash_mask = hashtablesize - 1; auto * hashtable = new struct bucket[hashtablesize]; uint64_t swarmcount = 0; uint64_t maxmass = 0; unsigned int maxsize = 0; /* alloc and init table of links to other sequences in cluster */ auto * nextseqtab = new unsigned int[dbsequencecount] { }; progress_init("Dereplicating: ", dbsequencecount); for(auto i = 0U; i < dbsequencecount; i++) { unsigned int seqlen = db_getsequencelen(i); char * seq = db_getsequence(i); /* Find free bucket or bucket for identical sequence. Make sure sequences are exactly identical in case of any hash collision. With 64-bit hashes, there is about 50% chance of a collision when the number of sequences is about 5e9. */ uint64_t hash = zobrist_hash(reinterpret_cast<unsigned char *>(seq), seqlen); uint64_t j = hash & derep_hash_mask; struct bucket * bp = hashtable + j; while (((bp->mass) != 0U) && ((bp->hash != hash) || (seqlen != db_getsequencelen(bp->seqno_first)) || (memcmp(seq, db_getsequence(bp->seqno_first), nt_bytelength(seqlen)) != 0))) { bp++; j++; if (bp >= hashtable + hashtablesize) { bp = hashtable; j = 0; } } uint64_t ab = db_getabundance(i); if ((bp->mass) != 0U) { /* at least one identical sequence already */ nextseqtab[bp->seqno_last] = i; } else { /* no identical sequences yet, start a new cluster */ swarmcount++; bp->hash = hash; bp->seqno_first = i; bp->size = 0; bp->singletons = 0; } bp->size++; bp->seqno_last = i; bp->mass += ab; if (ab == 1) { bp->singletons++; } if (bp->mass > maxmass) { maxmass = bp->mass; } if (bp->size > maxsize) { maxsize = bp->size; } progress_update(i); } progress_done(); progress_init("Sorting: ", 1); qsort(hashtable, hashtablesize, sizeof(bucket), derep_compare); progress_done(); /* dump swarms */ if (p.opt_mothur) { write_swarms_mothur_format(swarmcount, p, hashtable, nextseqtab); } else { write_swarms_default_format(swarmcount, p, hashtable, nextseqtab); } /* dump seeds in fasta format with sum of abundances */ if (not p.opt_seeds.empty()) { write_representative_sequences(swarmcount, p, hashtable); } /* output swarm in uclust format */ if (uclustfile != nullptr) { write_swarms_uclust_format(swarmcount, p, hashtable, nextseqtab); } /* output internal structure to file */ if (not p.opt_internal_structure.empty()) { write_structure_file(swarmcount, p, hashtable, nextseqtab); } /* output statistics to file */ if (statsfile != nullptr) { write_stats_file(swarmcount, p, hashtable); } fprintf(logfile, "\n"); fprintf(logfile, "Number of swarms: %" PRIu64 "\n", swarmcount); fprintf(logfile, "Largest swarm: %u\n", maxsize); fprintf(logfile, "Heaviest swarm: %" PRIu64 "\n", maxmass); delete [] nextseqtab; nextseqtab = nullptr; delete [] hashtable; hashtable = nullptr; } <commit_msg>comment<commit_after>/* SWARM Copyright (C) 2012-2022 Torbjorn Rognes and Frederic Mahe This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Contact: Torbjorn Rognes <torognes@ifi.uio.no>, Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ #include <cstdint> #include "swarm.h" #include "db.h" #include "util.h" #include "utils/hashtable_size.h" #include "zobrist.h" struct bucket { uint64_t hash = 0; unsigned int seqno_first = 0; unsigned int seqno_last = 0; uint64_t mass = 0; unsigned int size = 0; unsigned int singletons = 0; }; auto derep_compare(const void * a, const void * b) -> int { const auto * x = static_cast<const struct bucket *>(a); const auto * y = static_cast<const struct bucket *>(b); int status {0}; /* highest abundance first, otherwise keep order */ if (x->mass < y->mass) { status = +1; } else if (x->mass > y->mass) { status = -1; } else { if (x->seqno_first < y->seqno_first) { status = -1; } else if (x->seqno_first > y->seqno_first) { status = +1; } else { status = 0; } } return status; } auto write_stats_file(const uint64_t swarmcount, struct Parameters const & p, struct bucket * hashtable) -> void { progress_init("Writing stats: ", swarmcount); for(auto i = 0ULL; i < swarmcount; i++) { struct bucket * sp = hashtable + i; fprintf(statsfile, "%u\t%" PRIu64 "\t", sp->size, sp->mass); fprint_id_noabundance(statsfile, sp->seqno_first, p.opt_usearch_abundance); fprintf(statsfile, "\t%" PRIu64 "\t%u\t%u\t%u\n", db_getabundance(sp->seqno_first), sp->singletons, 0U, 0U); progress_update(i); } progress_done(); } auto write_structure_file(const uint64_t swarmcount, struct Parameters const & p, struct bucket * hashtable, unsigned int * nextseqtab) -> void { progress_init("Writing structure:", swarmcount); for(uint64_t i = 0; i < swarmcount; i++) { struct bucket * sp = hashtable + i; uint64_t seed = sp->seqno_first; unsigned int a = nextseqtab[seed]; while (a != 0U) { fprint_id_noabundance(internal_structure_file, seed, p.opt_usearch_abundance); fprintf(internal_structure_file, "\t"); fprint_id_noabundance(internal_structure_file, a, p.opt_usearch_abundance); fprintf(internal_structure_file, "\t%d\t%" PRIu64 "\t%d\n", 0, i+1, 0); a = nextseqtab[a]; } progress_update(i); } progress_done(); } auto write_swarms_uclust_format(const uint64_t swarmcount, struct Parameters const & p, struct bucket * hashtable, unsigned int * nextseqtab) -> void { progress_init("Writing UCLUST: ", swarmcount); for(auto swarmid = 0U; swarmid < swarmcount; swarmid++) { struct bucket * bp = hashtable + swarmid; unsigned int seed = bp->seqno_first; fprintf(uclustfile, "C\t%u\t%u\t*\t*\t*\t*\t*\t", swarmid, bp->size); fprint_id(uclustfile, seed, p.opt_usearch_abundance, p.opt_append_abundance); fprintf(uclustfile, "\t*\n"); fprintf(uclustfile, "S\t%u\t%u\t*\t*\t*\t*\t*\t", swarmid, db_getsequencelen(seed)); fprint_id(uclustfile, seed, p.opt_usearch_abundance, p.opt_append_abundance); fprintf(uclustfile, "\t*\n"); unsigned int a = nextseqtab[seed]; while (a != 0U) { fprintf(uclustfile, "H\t%u\t%u\t%.1f\t+\t0\t0\t%s\t", swarmid, db_getsequencelen(a), 100.0, "="); fprint_id(uclustfile, a, p.opt_usearch_abundance, p.opt_append_abundance); fprintf(uclustfile, "\t"); fprint_id(uclustfile, seed, p.opt_usearch_abundance, p.opt_append_abundance); fprintf(uclustfile, "\n"); a = nextseqtab[a]; } progress_update(swarmid+1); } progress_done(); } auto write_representative_sequences(const uint64_t swarmcount, struct Parameters const & p, struct bucket * hashtable) -> void { progress_init("Writing seeds: ", swarmcount); for(auto i = 0U; i < swarmcount; i++) { unsigned int seed = hashtable[i].seqno_first; fprintf(fp_seeds, ">"); fprint_id_with_new_abundance(fp_seeds, seed, hashtable[i].mass, p.opt_usearch_abundance); fprintf(fp_seeds, "\n"); db_fprintseq(fp_seeds, seed); progress_update(i+1); } progress_done(); } auto write_swarms_mothur_format(const uint64_t swarmcount, struct Parameters const & p, struct bucket * hashtable, unsigned int * nextseqtab) -> void { progress_init("Writing swarms: ", swarmcount); fprintf(outfile, "swarm_%" PRId64 "\t%" PRIu64, p.opt_differences, swarmcount); for(auto i = 0U; i < swarmcount; i++) { unsigned int seed = hashtable[i].seqno_first; fputc('\t', outfile); fprint_id(outfile, seed, p.opt_usearch_abundance, p.opt_append_abundance); unsigned int a = nextseqtab[seed]; while (a != 0U) { fputc(',', outfile); fprint_id(outfile, a, p.opt_usearch_abundance, p.opt_append_abundance); a = nextseqtab[a]; } progress_update(i+1); } fputc('\n', outfile); progress_done(); } auto write_swarms_default_format(const uint64_t swarmcount, struct Parameters const & p, struct bucket * hashtable, unsigned int * nextseqtab) -> void { progress_init("Writing swarms: ", swarmcount); for(auto i = 0U; i < swarmcount; i++) { unsigned int seed = hashtable[i].seqno_first; fprint_id(outfile, seed, p.opt_usearch_abundance, p.opt_append_abundance); unsigned int a = nextseqtab[seed]; while (a != 0U) { fputc(sepchar, outfile); fprint_id(outfile, a, p.opt_usearch_abundance, p.opt_append_abundance); a = nextseqtab[a]; } fputc('\n', outfile); progress_update(i+1); } progress_done(); } void dereplicate(struct Parameters const & p) { const uint64_t dbsequencecount = db_getsequencecount(); const uint64_t hashtablesize {compute_hashtable_size(dbsequencecount)}; const uint64_t derep_hash_mask = hashtablesize - 1; auto * hashtable = new struct bucket[hashtablesize]; uint64_t swarmcount = 0; uint64_t maxmass = 0; unsigned int maxsize = 0; /* alloc and init table of links to other sequences in cluster */ auto * nextseqtab = new unsigned int[dbsequencecount] { }; progress_init("Dereplicating: ", dbsequencecount); for(auto i = 0U; i < dbsequencecount; i++) { unsigned int seqlen = db_getsequencelen(i); char * seq = db_getsequence(i); /* Find free bucket or bucket for identical sequence. Make sure sequences are exactly identical in case of any hash collision. With 64-bit hashes, there is about 50% chance of a collision when the number of sequences is about 5e9. */ uint64_t hash = zobrist_hash(reinterpret_cast<unsigned char *>(seq), seqlen); uint64_t j = hash & derep_hash_mask; struct bucket * bp = hashtable + j; while (((bp->mass) != 0U) && ((bp->hash != hash) || (seqlen != db_getsequencelen(bp->seqno_first)) || (memcmp(seq, db_getsequence(bp->seqno_first), nt_bytelength(seqlen)) != 0))) { bp++; j++; if (bp >= hashtable + hashtablesize) // wrap around the table if we reach the end { bp = hashtable; j = 0; } } uint64_t ab = db_getabundance(i); if ((bp->mass) != 0U) { /* at least one identical sequence already */ nextseqtab[bp->seqno_last] = i; } else { /* no identical sequences yet, start a new cluster */ swarmcount++; bp->hash = hash; bp->seqno_first = i; bp->size = 0; bp->singletons = 0; } bp->size++; bp->seqno_last = i; bp->mass += ab; if (ab == 1) { bp->singletons++; } if (bp->mass > maxmass) { maxmass = bp->mass; } if (bp->size > maxsize) { maxsize = bp->size; } progress_update(i); } progress_done(); progress_init("Sorting: ", 1); qsort(hashtable, hashtablesize, sizeof(bucket), derep_compare); progress_done(); /* dump swarms */ if (p.opt_mothur) { write_swarms_mothur_format(swarmcount, p, hashtable, nextseqtab); } else { write_swarms_default_format(swarmcount, p, hashtable, nextseqtab); } /* dump seeds in fasta format with sum of abundances */ if (not p.opt_seeds.empty()) { write_representative_sequences(swarmcount, p, hashtable); } /* output swarm in uclust format */ if (uclustfile != nullptr) { write_swarms_uclust_format(swarmcount, p, hashtable, nextseqtab); } /* output internal structure to file */ if (not p.opt_internal_structure.empty()) { write_structure_file(swarmcount, p, hashtable, nextseqtab); } /* output statistics to file */ if (statsfile != nullptr) { write_stats_file(swarmcount, p, hashtable); } fprintf(logfile, "\n"); fprintf(logfile, "Number of swarms: %" PRIu64 "\n", swarmcount); fprintf(logfile, "Largest swarm: %u\n", maxsize); fprintf(logfile, "Heaviest swarm: %" PRIu64 "\n", maxmass); delete [] nextseqtab; nextseqtab = nullptr; delete [] hashtable; hashtable = nullptr; } <|endoftext|>
<commit_before>/* * Copyright 2002-2005 The Apache Software 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. */ /* * XSEC * * TXFMOutputFile := Transform that outputs the byte stream to a file without changing * the actual data in any way * * $Id$ * */ #include <xsec/transformers/TXFMOutputFile.hpp> #include <xsec/framework/XSECException.hpp> XERCES_CPP_NAMESPACE_USE // Destructor TXFMOutputFile::~TXFMOutputFile() { f.close(); } // Methods to set the inputs void TXFMOutputFile::setInput(TXFMBase *newInput) { input = newInput; if (newInput->getOutputType() != TXFMBase::BYTE_STREAM) { throw XSECException(XSECException::TransformInputOutputFail, "OutputFile transform requires BYTE_STREAM input"); } keepComments = input->getCommentsStatus(); } bool TXFMOutputFile::setFile(char * const fileName) { // Open a file for outputting using std::ios; f.open(fileName, ios::binary|ios::out|ios::app); if (f.is_open()) { f.write("\n----- BEGIN -----\n", 19); return true; } return false; } // Methods to get tranform output type and input requirement TXFMBase::ioType TXFMOutputFile::getInputType(void) { return TXFMBase::BYTE_STREAM; } TXFMBase::ioType TXFMOutputFile::getOutputType(void) { return TXFMBase::BYTE_STREAM; } TXFMBase::nodeType TXFMOutputFile::getNodeType(void) { return TXFMBase::DOM_NODE_NONE; } // Methods to get output data unsigned int TXFMOutputFile::readBytes(XMLByte * const toFill, unsigned int maxToFill) { unsigned int sz; sz = input->readBytes(toFill, maxToFill); if (f.is_open()) f.write((char *) toFill, sz); return sz; } DOMDocument * TXFMOutputFile::getDocument() { return NULL; } DOMNode * TXFMOutputFile::getFragmentNode() { return NULL; }; const XMLCh * TXFMOutputFile::getFragmentId() { return NULL; // Empty string } <commit_msg>Add an END to bracket the output.<commit_after>/* * Copyright 2002-2005 The Apache Software 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. */ /* * XSEC * * TXFMOutputFile := Transform that outputs the byte stream to a file without changing * the actual data in any way * * $Id$ * */ #include <xsec/transformers/TXFMOutputFile.hpp> #include <xsec/framework/XSECException.hpp> XERCES_CPP_NAMESPACE_USE // Destructor TXFMOutputFile::~TXFMOutputFile() { if (f.is_open()) f.write("\n----- END -----\n", 17); f.close(); } // Methods to set the inputs void TXFMOutputFile::setInput(TXFMBase *newInput) { input = newInput; if (newInput->getOutputType() != TXFMBase::BYTE_STREAM) { throw XSECException(XSECException::TransformInputOutputFail, "OutputFile transform requires BYTE_STREAM input"); } keepComments = input->getCommentsStatus(); } bool TXFMOutputFile::setFile(char * const fileName) { // Open a file for outputting using std::ios; f.open(fileName, ios::binary|ios::out|ios::app); if (f.is_open()) { f.write("\n----- BEGIN -----\n", 19); return true; } return false; } // Methods to get tranform output type and input requirement TXFMBase::ioType TXFMOutputFile::getInputType(void) { return TXFMBase::BYTE_STREAM; } TXFMBase::ioType TXFMOutputFile::getOutputType(void) { return TXFMBase::BYTE_STREAM; } TXFMBase::nodeType TXFMOutputFile::getNodeType(void) { return TXFMBase::DOM_NODE_NONE; } // Methods to get output data unsigned int TXFMOutputFile::readBytes(XMLByte * const toFill, unsigned int maxToFill) { unsigned int sz; sz = input->readBytes(toFill, maxToFill); if (f.is_open()) f.write((char *) toFill, sz); return sz; } DOMDocument * TXFMOutputFile::getDocument() { return NULL; } DOMNode * TXFMOutputFile::getFragmentNode() { return NULL; }; const XMLCh * TXFMOutputFile::getFragmentId() { return NULL; // Empty string } <|endoftext|>
<commit_before>#include "eval.h" #include "board.h" #include "int64.h" ////////////////////////////////////////////////////////////////////////////// //Returns a static evaluation score of the board in the //perspective of the player given ////////////////////////////////////////////////////////////////////////////// short Eval :: evalBoard(Board& board, unsigned char color) { //do scores assuming GOLD's perspective. if it is SILVER that is really //desired, then just negate at the end as this is a zero sum game int score; //material int material = __builtin_popcountll(board.pieces[GOLD][ELEPHANT]) * 2000 + __builtin_popcountll(board.pieces[GOLD][CAMEL]) * 700 + __builtin_popcountll(board.pieces[GOLD][HORSE]) * 500 + __builtin_popcountll(board.pieces[GOLD][DOG]) * 300 + __builtin_popcountll(board.pieces[GOLD][CAT]) * 200 + __builtin_popcountll(board.pieces[GOLD][RABBIT]) * 100 - __builtin_popcountll(board.pieces[SILVER][ELEPHANT]) * 2000 - __builtin_popcountll(board.pieces[SILVER][CAMEL]) * 700 - __builtin_popcountll(board.pieces[SILVER][HORSE]) * 500 - __builtin_popcountll(board.pieces[SILVER][DOG]) * 300 - __builtin_popcountll(board.pieces[SILVER][CAT]) * 200 - __builtin_popcountll(board.pieces[SILVER][RABBIT]) * 100; //rabbit advancement int advance = __builtin_popcountll(board.pieces[GOLD][RABBIT] & getRow(0)) * 30000 + __builtin_popcountll(board.pieces[GOLD][RABBIT] & getRow(1)) * 100 + __builtin_popcountll(board.pieces[GOLD][RABBIT] & getRow(2)) * 10 + __builtin_popcountll(board.pieces[GOLD][RABBIT] & getRow(3)) * 9 + __builtin_popcountll(board.pieces[GOLD][RABBIT] & getRow(4)) * 8 + __builtin_popcountll(board.pieces[GOLD][RABBIT] & getRow(5)) * 7 + __builtin_popcountll(board.pieces[GOLD][RABBIT] & getRow(6)) * 6 + __builtin_popcountll(board.pieces[GOLD][RABBIT] & getRow(7)) * 50 - __builtin_popcountll(board.pieces[SILVER][RABBIT] & getRow(7)) * 30000 - __builtin_popcountll(board.pieces[SILVER][RABBIT] & getRow(6)) * 100 - __builtin_popcountll(board.pieces[SILVER][RABBIT] & getRow(5)) * 10 - __builtin_popcountll(board.pieces[SILVER][RABBIT] & getRow(4)) * 9 - __builtin_popcountll(board.pieces[SILVER][RABBIT] & getRow(3)) * 8 - __builtin_popcountll(board.pieces[SILVER][RABBIT] & getRow(2)) * 7 - __builtin_popcountll(board.pieces[SILVER][RABBIT] & getRow(1)) * 6 - __builtin_popcountll(board.pieces[SILVER][RABBIT] & getRow(0)) * 50; //keeps center control with the strong board.pieces int strongCenter = __builtin_popcountll(board.pieces[GOLD][ELEPHANT] & getCenterRing(0)) * 50 + __builtin_popcountll(board.pieces[GOLD][ELEPHANT] & getCenterRing(1)) * 40 + __builtin_popcountll(board.pieces[GOLD][ELEPHANT] & getCenterRing(2)) * 30 + __builtin_popcountll(board.pieces[GOLD][ELEPHANT] & getCenterRing(3)) * 20 + __builtin_popcountll(board.pieces[GOLD][CAMEL] & getCenterRing(0)) * 30 + __builtin_popcountll(board.pieces[GOLD][CAMEL] & getCenterRing(1)) * 20 + __builtin_popcountll(board.pieces[GOLD][CAMEL] & getCenterRing(2)) * -50 + __builtin_popcountll(board.pieces[GOLD][CAMEL] & getCenterRing(3)) * -100 + __builtin_popcountll(board.pieces[GOLD][HORSE] & getCenterRing(0)) * 40 + __builtin_popcountll(board.pieces[GOLD][HORSE] & getCenterRing(1)) * 30 + __builtin_popcountll(board.pieces[GOLD][HORSE] & getCenterRing(2)) * 20 + __builtin_popcountll(board.pieces[GOLD][HORSE] & getCenterRing(3)) * 30 - __builtin_popcountll(board.pieces[SILVER][ELEPHANT] & getCenterRing(0)) * 50 - __builtin_popcountll(board.pieces[SILVER][ELEPHANT] & getCenterRing(1)) * 40 - __builtin_popcountll(board.pieces[SILVER][ELEPHANT] & getCenterRing(2)) * 30 - __builtin_popcountll(board.pieces[SILVER][ELEPHANT] & getCenterRing(3)) * 20 - __builtin_popcountll(board.pieces[SILVER][CAMEL] & getCenterRing(0)) * 40 - __builtin_popcountll(board.pieces[SILVER][CAMEL] & getCenterRing(1)) * 20 - __builtin_popcountll(board.pieces[SILVER][CAMEL] & getCenterRing(2)) * -50 - __builtin_popcountll(board.pieces[SILVER][CAMEL] & getCenterRing(3)) * -100 - __builtin_popcountll(board.pieces[SILVER][HORSE] & getCenterRing(0)) * 40 - __builtin_popcountll(board.pieces[SILVER][HORSE] & getCenterRing(1)) * 30 - __builtin_popcountll(board.pieces[SILVER][HORSE] & getCenterRing(2)) * 20 - __builtin_popcountll(board.pieces[SILVER][HORSE] & getCenterRing(3)) * 30; //keep rabbits away from center int rabbitCenterAvoid = __builtin_popcountll(board.pieces[GOLD][RABBIT] & getCenterRing(0)) * -100 + __builtin_popcountll(board.pieces[GOLD][RABBIT] & getCenterRing(1)) * -75 + __builtin_popcountll(board.pieces[GOLD][RABBIT] & getCenterRing(2)) * -25 + __builtin_popcountll(board.pieces[GOLD][RABBIT] & getCenterRing(3)) * 25; - __builtin_popcountll(board.pieces[SILVER][RABBIT] & getCenterRing(0)) * -100 - __builtin_popcountll(board.pieces[SILVER][RABBIT] & getCenterRing(1)) * -75 - __builtin_popcountll(board.pieces[SILVER][RABBIT] & getCenterRing(2)) * -25 - __builtin_popcountll(board.pieces[SILVER][RABBIT] & getCenterRing(3)) * 25; //keep pieces away from traps int trapAvoid = __builtin_popcountll(board.pieces[GOLD][CAMEL] & (getTraps() | getTrapNeighbors())) * -300 + __builtin_popcountll(board.pieces[GOLD][HORSE] & (getTraps() | getTrapNeighbors())) * -100 + __builtin_popcountll(board.pieces[GOLD][DOG] & (getTraps() | getTrapNeighbors())) * -50 + __builtin_popcountll(board.pieces[GOLD][CAT] & (getTraps() | getTrapNeighbors())) * -25 + __builtin_popcountll(board.pieces[GOLD][RABBIT] & (getTraps() | getTrapNeighbors())) * -50 - __builtin_popcountll(board.pieces[SILVER][CAMEL] & (getTraps() | getTrapNeighbors())) * -300 - __builtin_popcountll(board.pieces[SILVER][HORSE] & (getTraps() | getTrapNeighbors())) * -100 - __builtin_popcountll(board.pieces[SILVER][DOG] & (getTraps() | getTrapNeighbors())) * -50 - __builtin_popcountll(board.pieces[SILVER][CAT] & (getTraps() | getTrapNeighbors())) * -25 - __builtin_popcountll(board.pieces[SILVER][RABBIT] & (getTraps() | getTrapNeighbors())) * -50; //guard local traps with weaker pieces int trapGuard = __builtin_popcountll(board.pieces[GOLD][DOG] & (getTrapNeighbors()) & (getRow(5) | getRow(6) | getRow(7) )) * 100 + __builtin_popcountll(board.pieces[GOLD][CAT] & (getTrapNeighbors()) & (getRow(5) | getRow(6) | getRow(7) )) * 75 - __builtin_popcountll(board.pieces[SILVER][DOG] & (getTrapNeighbors()) & (getRow(1) | getRow(2) | getRow(3) )) * 100 - __builtin_popcountll(board.pieces[SILVER][CAT] & (getTrapNeighbors()) & (getRow(1) | getRow(2) | getRow(3) )) * 70; score = material + advance + strongCenter + rabbitCenterAvoid + trapAvoid + trapGuard; if (color == GOLD) return score; else return -score; } ////////////////////////////////////////////////////////////////////////////// //returns true if the position is a win for the color specified. ////////////////////////////////////////////////////////////////////////////// bool Eval :: isWin(Board& board, unsigned char color) { if (color == GOLD) return board.pieces[GOLD][RABBIT] & getRow(0); else return board.pieces[SILVER][RABBIT] & getRow(7); } ////////////////////////////////////////////////////////////////////////////// //gives the combo in the array some heurisitic scores to see which order the //moves should be considered in. The bestIndex variable should be set to the //index referenced by the hashtable if there are any, if one does not //wish to provide one, it should be set to -1 ////////////////////////////////////////////////////////////////////////////// void Eval :: scoreCombos(StepCombo combos[], int num, unsigned char color, int bestIndex) { for (int i = 0; i < num; ++i) { combos[i].score = 0; //give moves some score based on captures, note that pieces are //numerically ordered with ELEPHANT being 0, and RABBIT being 5, so //to give a sensical score in respect to type, value should reversed //in respect to these numbers if (combos[i].hasFriendlyCapture) { combos[i].score -= 50 * (MAX_TYPES - combos[i].friendlyCaptureType); } if (combos[i].hasEnemyCapture) { combos[i].score += 50 * (MAX_TYPES - combos[i].enemyCaptureType); } //give some score for killer moves combos[i].score += killermove[combos[i].steps[0].getFrom()] [combos[i].steps[0].getTo()] [color] * 10; } //give some bonus to the purported best move if (bestIndex != -1) combos[bestIndex].score += 10000; } <commit_msg>Change evaluation to value material much more<commit_after>#include "eval.h" #include "board.h" #include "int64.h" ////////////////////////////////////////////////////////////////////////////// //Returns a static evaluation score of the board in the //perspective of the player given ////////////////////////////////////////////////////////////////////////////// short Eval :: evalBoard(Board& board, unsigned char color) { //do scores assuming GOLD's perspective. if it is SILVER that is really //desired, then just negate at the end as this is a zero sum game int score; //material int material = __builtin_popcountll(board.pieces[GOLD][ELEPHANT]) * 2000 + __builtin_popcountll(board.pieces[GOLD][CAMEL]) * 700 + __builtin_popcountll(board.pieces[GOLD][HORSE]) * 500 + __builtin_popcountll(board.pieces[GOLD][DOG]) * 300 + __builtin_popcountll(board.pieces[GOLD][CAT]) * 200 + __builtin_popcountll(board.pieces[GOLD][RABBIT]) * 100 - __builtin_popcountll(board.pieces[SILVER][ELEPHANT]) * 2000 - __builtin_popcountll(board.pieces[SILVER][CAMEL]) * 700 - __builtin_popcountll(board.pieces[SILVER][HORSE]) * 500 - __builtin_popcountll(board.pieces[SILVER][DOG]) * 300 - __builtin_popcountll(board.pieces[SILVER][CAT]) * 200 - __builtin_popcountll(board.pieces[SILVER][RABBIT]) * 100; //rabbit advancement int advance = __builtin_popcountll(board.pieces[GOLD][RABBIT] & getRow(0)) * 30000 + __builtin_popcountll(board.pieces[GOLD][RABBIT] & getRow(1)) * 100 + __builtin_popcountll(board.pieces[GOLD][RABBIT] & getRow(2)) * 50 + __builtin_popcountll(board.pieces[GOLD][RABBIT] & getRow(3)) * 25 + __builtin_popcountll(board.pieces[GOLD][RABBIT] & getRow(4)) * 10 + __builtin_popcountll(board.pieces[GOLD][RABBIT] & getRow(5)) * 5 + __builtin_popcountll(board.pieces[GOLD][RABBIT] & getRow(6)) * 5 + __builtin_popcountll(board.pieces[GOLD][RABBIT] & getRow(7)) * 50 - __builtin_popcountll(board.pieces[SILVER][RABBIT] & getRow(7)) * 30000 - __builtin_popcountll(board.pieces[SILVER][RABBIT] & getRow(6)) * 100 - __builtin_popcountll(board.pieces[SILVER][RABBIT] & getRow(5)) * 50 - __builtin_popcountll(board.pieces[SILVER][RABBIT] & getRow(4)) * 25 - __builtin_popcountll(board.pieces[SILVER][RABBIT] & getRow(3)) * 10 - __builtin_popcountll(board.pieces[SILVER][RABBIT] & getRow(2)) * 5 - __builtin_popcountll(board.pieces[SILVER][RABBIT] & getRow(1)) * 5 - __builtin_popcountll(board.pieces[SILVER][RABBIT] & getRow(0)) * 50; //keeps center control with the strong board.pieces int strongCenter = __builtin_popcountll(board.pieces[GOLD][ELEPHANT] & getCenterRing(0)) * 50 + __builtin_popcountll(board.pieces[GOLD][ELEPHANT] & getCenterRing(1)) * 40 + __builtin_popcountll(board.pieces[GOLD][ELEPHANT] & getCenterRing(2)) * 30 + __builtin_popcountll(board.pieces[GOLD][ELEPHANT] & getCenterRing(3)) * 20 + __builtin_popcountll(board.pieces[GOLD][CAMEL] & getCenterRing(0)) * 30 + __builtin_popcountll(board.pieces[GOLD][CAMEL] & getCenterRing(1)) * 20 + __builtin_popcountll(board.pieces[GOLD][CAMEL] & getCenterRing(2)) * -50 + __builtin_popcountll(board.pieces[GOLD][CAMEL] & getCenterRing(3)) * -75 + __builtin_popcountll(board.pieces[GOLD][HORSE] & getCenterRing(0)) * 40 + __builtin_popcountll(board.pieces[GOLD][HORSE] & getCenterRing(1)) * 30 + __builtin_popcountll(board.pieces[GOLD][HORSE] & getCenterRing(2)) * 20 + __builtin_popcountll(board.pieces[GOLD][HORSE] & getCenterRing(3)) * 30 - __builtin_popcountll(board.pieces[SILVER][ELEPHANT] & getCenterRing(0)) * 50 - __builtin_popcountll(board.pieces[SILVER][ELEPHANT] & getCenterRing(1)) * 40 - __builtin_popcountll(board.pieces[SILVER][ELEPHANT] & getCenterRing(2)) * 30 - __builtin_popcountll(board.pieces[SILVER][ELEPHANT] & getCenterRing(3)) * 20 - __builtin_popcountll(board.pieces[SILVER][CAMEL] & getCenterRing(0)) * 40 - __builtin_popcountll(board.pieces[SILVER][CAMEL] & getCenterRing(1)) * 20 - __builtin_popcountll(board.pieces[SILVER][CAMEL] & getCenterRing(2)) * -50 - __builtin_popcountll(board.pieces[SILVER][CAMEL] & getCenterRing(3)) * -75 - __builtin_popcountll(board.pieces[SILVER][HORSE] & getCenterRing(0)) * 40 - __builtin_popcountll(board.pieces[SILVER][HORSE] & getCenterRing(1)) * 30 - __builtin_popcountll(board.pieces[SILVER][HORSE] & getCenterRing(2)) * 20 - __builtin_popcountll(board.pieces[SILVER][HORSE] & getCenterRing(3)) * 30; //keep rabbits away from center int rabbitCenterAvoid = __builtin_popcountll(board.pieces[GOLD][RABBIT] & getCenterRing(0)) * -100 + __builtin_popcountll(board.pieces[GOLD][RABBIT] & getCenterRing(1)) * -75 + __builtin_popcountll(board.pieces[GOLD][RABBIT] & getCenterRing(2)) * -25 + __builtin_popcountll(board.pieces[GOLD][RABBIT] & getCenterRing(3)) * 25; - __builtin_popcountll(board.pieces[SILVER][RABBIT] & getCenterRing(0)) * -100 - __builtin_popcountll(board.pieces[SILVER][RABBIT] & getCenterRing(1)) * -75 - __builtin_popcountll(board.pieces[SILVER][RABBIT] & getCenterRing(2)) * -25 - __builtin_popcountll(board.pieces[SILVER][RABBIT] & getCenterRing(3)) * 25; //keep pieces away from traps int trapAvoid = __builtin_popcountll(board.pieces[GOLD][CAMEL] & (getTraps() | getTrapNeighbors())) * -50 + __builtin_popcountll(board.pieces[GOLD][HORSE] & (getTraps() | getTrapNeighbors())) * -40 + __builtin_popcountll(board.pieces[GOLD][DOG] & (getTraps() | getTrapNeighbors())) * -20 + __builtin_popcountll(board.pieces[GOLD][CAT] & (getTraps() | getTrapNeighbors())) * -20 + __builtin_popcountll(board.pieces[GOLD][RABBIT] & (getTraps() | getTrapNeighbors())) * -50 - __builtin_popcountll(board.pieces[SILVER][CAMEL] & (getTraps() | getTrapNeighbors())) * -50 - __builtin_popcountll(board.pieces[SILVER][HORSE] & (getTraps() | getTrapNeighbors())) * -40 - __builtin_popcountll(board.pieces[SILVER][DOG] & (getTraps() | getTrapNeighbors())) * -20 - __builtin_popcountll(board.pieces[SILVER][CAT] & (getTraps() | getTrapNeighbors())) * -20 - __builtin_popcountll(board.pieces[SILVER][RABBIT] & (getTraps() | getTrapNeighbors())) * -50; //guard local traps with weaker pieces int trapGuard = __builtin_popcountll(board.pieces[GOLD][DOG] & (getTrapNeighbors()) & (getRow(5) | getRow(6) | getRow(7) )) * 50 + __builtin_popcountll(board.pieces[GOLD][CAT] & (getTrapNeighbors()) & (getRow(5) | getRow(6) | getRow(7) )) * 30 - __builtin_popcountll(board.pieces[SILVER][DOG] & (getTrapNeighbors()) & (getRow(1) | getRow(2) | getRow(3) )) * 50 - __builtin_popcountll(board.pieces[SILVER][CAT] & (getTrapNeighbors()) & (getRow(1) | getRow(2) | getRow(3) )) * 30; score = material + advance + strongCenter + rabbitCenterAvoid + trapAvoid + trapGuard; if (color == GOLD) return score; else return -score; } ////////////////////////////////////////////////////////////////////////////// //returns true if the position is a win for the color specified. ////////////////////////////////////////////////////////////////////////////// bool Eval :: isWin(Board& board, unsigned char color) { if (color == GOLD) return board.pieces[GOLD][RABBIT] & getRow(0); else return board.pieces[SILVER][RABBIT] & getRow(7); } ////////////////////////////////////////////////////////////////////////////// //gives the combo in the array some heurisitic scores to see which order the //moves should be considered in. The bestIndex variable should be set to the //index referenced by the hashtable if there are any, if one does not //wish to provide one, it should be set to -1 ////////////////////////////////////////////////////////////////////////////// void Eval :: scoreCombos(StepCombo combos[], int num, unsigned char color, int bestIndex) { for (int i = 0; i < num; ++i) { combos[i].score = 0; //give moves some score based on captures, note that pieces are //numerically ordered with ELEPHANT being 0, and RABBIT being 5, so //to give a sensical score in respect to type, value should reversed //in respect to these numbers if (combos[i].hasFriendlyCapture) { combos[i].score -= 50 * (MAX_TYPES - combos[i].friendlyCaptureType); } if (combos[i].hasEnemyCapture) { combos[i].score += 50 * (MAX_TYPES - combos[i].enemyCaptureType); } //give some score for killer moves combos[i].score += killermove[combos[i].steps[0].getFrom()] [combos[i].steps[0].getTo()] [color] * 10; } //give some bonus to the purported best move if (bestIndex != -1) combos[bestIndex].score += 10000; } <|endoftext|>
<commit_before>/** * @file file.cpp * @brief Classes for transferring files * * (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/file.h" #include "mega/transfer.h" #include "mega/transferslot.h" #include "mega/megaclient.h" #include "mega/sync.h" #include "mega/command.h" #include "mega/logging.h" namespace mega { File::File() { transfer = NULL; hprivate = true; hforeign = false; syncxfer = false; temporaryfile = false; h = UNDEF; tag = 0; } File::~File() { // if transfer currently running, stop if (transfer) { transfer->client->stopxfer(this); } } bool File::serialize(string *d) { char type = transfer->type; d->append((const char*)&type, sizeof(type)); if (!FileFingerprint::serialize(d)) { LOG_err << "Error serializing File: Unable to serialize FileFingerprint"; return false; } unsigned short ll; bool flag; ll = (unsigned short)name.size(); d->append((char*)&ll, sizeof(ll)); d->append(name.data(), ll); ll = (unsigned short)localname.size(); d->append((char*)&ll, sizeof(ll)); d->append(localname.data(), ll); ll = (unsigned short)targetuser.size(); d->append((char*)&ll, sizeof(ll)); d->append(targetuser.data(), ll); ll = (unsigned short)privauth.size(); d->append((char*)&ll, sizeof(ll)); d->append(privauth.data(), ll); ll = (unsigned short)pubauth.size(); d->append((char*)&ll, sizeof(ll)); d->append(pubauth.data(), ll); d->append((const char*)&h, sizeof(h)); d->append((const char*)filekey, sizeof(filekey)); flag = hprivate; d->append((const char*)&flag, sizeof(flag)); flag = hforeign; d->append((const char*)&flag, sizeof(flag)); flag = syncxfer; d->append((const char*)&flag, sizeof(flag)); flag = temporaryfile; d->append((const char*)&flag, sizeof(flag)); d->append("\0\0\0\0\0\0\0\0", 9); return true; } File *File::unserialize(string *d) { if (!d->size()) { LOG_err << "Error unserializing File: Empty string"; return NULL; } d->erase(0, 1); FileFingerprint *fp = FileFingerprint::unserialize(d); if (!fp) { LOG_err << "Error unserializing File: Unable to unserialize FileFingerprint"; return NULL; } const char* ptr = d->data(); const char* end = ptr + d->size(); if (ptr + sizeof(unsigned short) > end) { LOG_err << "File unserialization failed - serialized string too short"; return NULL; } // read name unsigned short namelen = MemAccess::get<unsigned short>(ptr); ptr += sizeof(namelen); if (ptr + namelen + sizeof(unsigned short) > end) { LOG_err << "File unserialization failed - name too long"; return NULL; } const char *name = ptr; ptr += namelen; // read localname unsigned short localnamelen = MemAccess::get<unsigned short>(ptr); ptr += sizeof(localnamelen); if (ptr + localnamelen + sizeof(unsigned short) > end) { LOG_err << "File unserialization failed - localname too long"; return NULL; } const char *localname = ptr; ptr += localnamelen; // read targetuser unsigned short targetuserlen = MemAccess::get<unsigned short>(ptr); ptr += sizeof(targetuserlen); if (ptr + targetuserlen + sizeof(unsigned short) > end) { LOG_err << "File unserialization failed - targetuser too long"; return NULL; } const char *targetuser = ptr; ptr += targetuserlen; // read private auth unsigned short privauthlen = MemAccess::get<unsigned short>(ptr); ptr += sizeof(privauthlen); if (ptr + privauthlen + sizeof(unsigned short) > end) { LOG_err << "File unserialization failed - private auth too long"; return NULL; } const char *privauth = ptr; ptr += privauthlen; unsigned short pubauthlen = MemAccess::get<unsigned short>(ptr); ptr += sizeof(pubauthlen); if (ptr + pubauthlen + sizeof(handle) + FILENODEKEYLENGTH + sizeof(bool) + sizeof(bool) + sizeof(bool) + 10 > end) { LOG_err << "File unserialization failed - public auth too long"; return NULL; } const char *pubauth = ptr; ptr += pubauthlen; File *file = new File(); *(FileFingerprint *)file = *(FileFingerprint *)fp; file->name.assign(name, namelen); file->localname.assign(localname, localnamelen); file->targetuser.assign(targetuser, targetuserlen); file->privauth.assign(privauth, privauthlen); file->pubauth.assign(pubauth, pubauthlen); file->h = MemAccess::get<handle>(ptr); ptr += sizeof(handle); memcpy(file->filekey, ptr, FILENODEKEYLENGTH); ptr += FILENODEKEYLENGTH; file->hprivate = MemAccess::get<bool>(ptr); ptr += sizeof(bool); file->hforeign = MemAccess::get<bool>(ptr); ptr += sizeof(bool); file->syncxfer = MemAccess::get<bool>(ptr); ptr += sizeof(bool); file->temporaryfile = MemAccess::get<bool>(ptr); ptr += sizeof(bool); if (memcmp(ptr, "\0\0\0\0\0\0\0\0", 9)) { LOG_err << "File unserialization failed - invalid version"; delete file; return NULL; } ptr += 9; d->erase(0, ptr - d->data()); return file; } void File::prepare() { transfer->localfilename = localname; } void File::start() { } void File::progress() { } void File::completed(Transfer* t, LocalNode* l) { if (t->type == PUT) { NewNode* newnode = new NewNode[1]; // build new node newnode->source = NEW_UPLOAD; // upload handle required to retrieve/include pending file attributes newnode->uploadhandle = t->uploadhandle; // reference to uploaded file memcpy(newnode->uploadtoken, t->ultoken, sizeof newnode->uploadtoken); // file's crypto key newnode->nodekey.assign((char*)t->filekey, FILENODEKEYLENGTH); newnode->type = FILENODE; newnode->parenthandle = UNDEF; #ifdef ENABLE_SYNC if ((newnode->localnode = l)) { l->newnode = newnode; newnode->syncid = l->syncid; } #endif AttrMap attrs; // store filename attrs.map['n'] = name; // store fingerprint t->serializefingerprint(&attrs.map['c']); string tattrstring; attrs.getjson(&tattrstring); newnode->attrstring = new string; t->client->makeattr(&t->key, newnode->attrstring, tattrstring.c_str()); if (targetuser.size()) { // drop file into targetuser's inbox int creqtag = t->client->reqtag; t->client->reqtag = tag; t->client->putnodes(targetuser.c_str(), newnode, 1); t->client->reqtag = creqtag; } else { handle th = h; // inaccessible target folder - use / instead if (!t->client->nodebyhandle(th)) { th = t->client->rootnodes[0]; } #ifdef ENABLE_SYNC if (l) { t->client->syncadding++; } #endif t->client->reqs.add(new CommandPutNodes(t->client, th, NULL, newnode, 1, tag, #ifdef ENABLE_SYNC l ? PUTNODES_SYNC : PUTNODES_APP)); #else PUTNODES_APP)); #endif } } } void File::terminated() { } // do not retry crypto errors or administrative takedowns; retry other types of // failuresup to 16 times, except I/O errors (6 times) bool File::failed(error e) { if (e == API_EKEY) { if (!transfer->hascurrentmetamac) { // several integrity check errors uploading chunks return transfer->failcount < 1; } if (transfer->hasprevmetamac && transfer->prevmetamac == transfer->currentmetamac) { // integrity check failed after download, two times with the same value return false; } // integrity check failed once, try again transfer->prevmetamac = transfer->currentmetamac; transfer->hasprevmetamac = true; return transfer->failcount < 16; } return (e != API_EBLOCKED && e != API_ENOENT && e != API_EINTERNAL && transfer->failcount < 16) && !((e == API_EREAD || e == API_EWRITE) && transfer->failcount > 6); } void File::displayname(string* dname) { if (name.size()) { *dname = name; } else { Node* n; if ((n = transfer->client->nodebyhandle(h))) { *dname = n->displayname(); } else { *dname = "DELETED/UNAVAILABLE"; } } } #ifdef ENABLE_SYNC SyncFileGet::SyncFileGet(Sync* csync, Node* cn, string* clocalname) { sync = csync; n = cn; h = n->nodehandle; *(FileFingerprint*)this = *n; localname = *clocalname; syncxfer = true; n->syncget = this; } SyncFileGet::~SyncFileGet() { n->syncget = NULL; } // create sync-specific temp download directory and set unique filename void SyncFileGet::prepare() { if (!transfer->localfilename.size()) { int i; string tmpname, lockname; tmpname = "tmp"; sync->client->fsaccess->name2local(&tmpname); if (!sync->tmpfa) { sync->tmpfa = sync->client->fsaccess->newfileaccess(); for (i = 3; i--;) { LOG_verbose << "Creating tmp folder"; transfer->localfilename = sync->localdebris; sync->client->fsaccess->mkdirlocal(&transfer->localfilename, true); transfer->localfilename.append(sync->client->fsaccess->localseparator); transfer->localfilename.append(tmpname); sync->client->fsaccess->mkdirlocal(&transfer->localfilename); // lock it transfer->localfilename.append(sync->client->fsaccess->localseparator); lockname = "lock"; sync->client->fsaccess->name2local(&lockname); transfer->localfilename.append(lockname); if (sync->tmpfa->fopen(&transfer->localfilename, false, true)) { break; } } // if we failed to create the tmp dir three times in a row, fall // back to the sync's root if (i < 0) { delete sync->tmpfa; sync->tmpfa = NULL; } } if (sync->tmpfa) { transfer->localfilename = sync->localdebris; transfer->localfilename.append(sync->client->fsaccess->localseparator); transfer->localfilename.append(tmpname); } else { transfer->localfilename = sync->localroot.localname; } sync->client->fsaccess->tmpnamelocal(&tmpname); transfer->localfilename.append(sync->client->fsaccess->localseparator); transfer->localfilename.append(tmpname); } if (n->parent && n->parent->localnode) { n->parent->localnode->treestate(TREESTATE_SYNCING); } } bool SyncFileGet::failed(error e) { bool retry = File::failed(e); if (n->parent && n->parent->localnode) { n->parent->localnode->treestate(TREESTATE_PENDING); if (!retry && (e == API_EBLOCKED || e == API_EKEY)) { n->parent->client->movetosyncdebris(n, n->parent->localnode->sync->inshare); } } return retry; } void SyncFileGet::progress() { File::progress(); if (n->parent && n->parent->localnode && n->parent->localnode->ts != TREESTATE_SYNCING) { n->parent->localnode->treestate(TREESTATE_SYNCING); } } // update localname (parent's localnode) void SyncFileGet::updatelocalname() { attr_map::iterator ait; if ((ait = n->attrs.map.find('n')) != n->attrs.map.end()) { if (n->parent && n->parent->localnode) { string tmpname = ait->second; sync->client->fsaccess->name2local(&tmpname); n->parent->localnode->getlocalpath(&localname); localname.append(sync->client->fsaccess->localseparator); localname.append(tmpname); } } } // add corresponding LocalNode (by path), then self-destruct void SyncFileGet::completed(Transfer*, LocalNode*) { sync->checkpath(NULL, &localname); delete this; } void SyncFileGet::terminated() { delete this; } #endif } // namespace <commit_msg>Fixed the leak of a FileFingerprint object unserializing File<commit_after>/** * @file file.cpp * @brief Classes for transferring files * * (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/file.h" #include "mega/transfer.h" #include "mega/transferslot.h" #include "mega/megaclient.h" #include "mega/sync.h" #include "mega/command.h" #include "mega/logging.h" namespace mega { File::File() { transfer = NULL; hprivate = true; hforeign = false; syncxfer = false; temporaryfile = false; h = UNDEF; tag = 0; } File::~File() { // if transfer currently running, stop if (transfer) { transfer->client->stopxfer(this); } } bool File::serialize(string *d) { char type = transfer->type; d->append((const char*)&type, sizeof(type)); if (!FileFingerprint::serialize(d)) { LOG_err << "Error serializing File: Unable to serialize FileFingerprint"; return false; } unsigned short ll; bool flag; ll = (unsigned short)name.size(); d->append((char*)&ll, sizeof(ll)); d->append(name.data(), ll); ll = (unsigned short)localname.size(); d->append((char*)&ll, sizeof(ll)); d->append(localname.data(), ll); ll = (unsigned short)targetuser.size(); d->append((char*)&ll, sizeof(ll)); d->append(targetuser.data(), ll); ll = (unsigned short)privauth.size(); d->append((char*)&ll, sizeof(ll)); d->append(privauth.data(), ll); ll = (unsigned short)pubauth.size(); d->append((char*)&ll, sizeof(ll)); d->append(pubauth.data(), ll); d->append((const char*)&h, sizeof(h)); d->append((const char*)filekey, sizeof(filekey)); flag = hprivate; d->append((const char*)&flag, sizeof(flag)); flag = hforeign; d->append((const char*)&flag, sizeof(flag)); flag = syncxfer; d->append((const char*)&flag, sizeof(flag)); flag = temporaryfile; d->append((const char*)&flag, sizeof(flag)); d->append("\0\0\0\0\0\0\0\0", 9); return true; } File *File::unserialize(string *d) { if (!d->size()) { LOG_err << "Error unserializing File: Empty string"; return NULL; } d->erase(0, 1); FileFingerprint *fp = FileFingerprint::unserialize(d); if (!fp) { LOG_err << "Error unserializing File: Unable to unserialize FileFingerprint"; return NULL; } const char* ptr = d->data(); const char* end = ptr + d->size(); if (ptr + sizeof(unsigned short) > end) { LOG_err << "File unserialization failed - serialized string too short"; delete fp; return NULL; } // read name unsigned short namelen = MemAccess::get<unsigned short>(ptr); ptr += sizeof(namelen); if (ptr + namelen + sizeof(unsigned short) > end) { LOG_err << "File unserialization failed - name too long"; delete fp; return NULL; } const char *name = ptr; ptr += namelen; // read localname unsigned short localnamelen = MemAccess::get<unsigned short>(ptr); ptr += sizeof(localnamelen); if (ptr + localnamelen + sizeof(unsigned short) > end) { LOG_err << "File unserialization failed - localname too long"; delete fp; return NULL; } const char *localname = ptr; ptr += localnamelen; // read targetuser unsigned short targetuserlen = MemAccess::get<unsigned short>(ptr); ptr += sizeof(targetuserlen); if (ptr + targetuserlen + sizeof(unsigned short) > end) { LOG_err << "File unserialization failed - targetuser too long"; delete fp; return NULL; } const char *targetuser = ptr; ptr += targetuserlen; // read private auth unsigned short privauthlen = MemAccess::get<unsigned short>(ptr); ptr += sizeof(privauthlen); if (ptr + privauthlen + sizeof(unsigned short) > end) { LOG_err << "File unserialization failed - private auth too long"; delete fp; return NULL; } const char *privauth = ptr; ptr += privauthlen; unsigned short pubauthlen = MemAccess::get<unsigned short>(ptr); ptr += sizeof(pubauthlen); if (ptr + pubauthlen + sizeof(handle) + FILENODEKEYLENGTH + sizeof(bool) + sizeof(bool) + sizeof(bool) + 10 > end) { LOG_err << "File unserialization failed - public auth too long"; delete fp; return NULL; } const char *pubauth = ptr; ptr += pubauthlen; File *file = new File(); *(FileFingerprint *)file = *(FileFingerprint *)fp; delete fp; file->name.assign(name, namelen); file->localname.assign(localname, localnamelen); file->targetuser.assign(targetuser, targetuserlen); file->privauth.assign(privauth, privauthlen); file->pubauth.assign(pubauth, pubauthlen); file->h = MemAccess::get<handle>(ptr); ptr += sizeof(handle); memcpy(file->filekey, ptr, FILENODEKEYLENGTH); ptr += FILENODEKEYLENGTH; file->hprivate = MemAccess::get<bool>(ptr); ptr += sizeof(bool); file->hforeign = MemAccess::get<bool>(ptr); ptr += sizeof(bool); file->syncxfer = MemAccess::get<bool>(ptr); ptr += sizeof(bool); file->temporaryfile = MemAccess::get<bool>(ptr); ptr += sizeof(bool); if (memcmp(ptr, "\0\0\0\0\0\0\0\0", 9)) { LOG_err << "File unserialization failed - invalid version"; delete file; return NULL; } ptr += 9; d->erase(0, ptr - d->data()); return file; } void File::prepare() { transfer->localfilename = localname; } void File::start() { } void File::progress() { } void File::completed(Transfer* t, LocalNode* l) { if (t->type == PUT) { NewNode* newnode = new NewNode[1]; // build new node newnode->source = NEW_UPLOAD; // upload handle required to retrieve/include pending file attributes newnode->uploadhandle = t->uploadhandle; // reference to uploaded file memcpy(newnode->uploadtoken, t->ultoken, sizeof newnode->uploadtoken); // file's crypto key newnode->nodekey.assign((char*)t->filekey, FILENODEKEYLENGTH); newnode->type = FILENODE; newnode->parenthandle = UNDEF; #ifdef ENABLE_SYNC if ((newnode->localnode = l)) { l->newnode = newnode; newnode->syncid = l->syncid; } #endif AttrMap attrs; // store filename attrs.map['n'] = name; // store fingerprint t->serializefingerprint(&attrs.map['c']); string tattrstring; attrs.getjson(&tattrstring); newnode->attrstring = new string; t->client->makeattr(&t->key, newnode->attrstring, tattrstring.c_str()); if (targetuser.size()) { // drop file into targetuser's inbox int creqtag = t->client->reqtag; t->client->reqtag = tag; t->client->putnodes(targetuser.c_str(), newnode, 1); t->client->reqtag = creqtag; } else { handle th = h; // inaccessible target folder - use / instead if (!t->client->nodebyhandle(th)) { th = t->client->rootnodes[0]; } #ifdef ENABLE_SYNC if (l) { t->client->syncadding++; } #endif t->client->reqs.add(new CommandPutNodes(t->client, th, NULL, newnode, 1, tag, #ifdef ENABLE_SYNC l ? PUTNODES_SYNC : PUTNODES_APP)); #else PUTNODES_APP)); #endif } } } void File::terminated() { } // do not retry crypto errors or administrative takedowns; retry other types of // failuresup to 16 times, except I/O errors (6 times) bool File::failed(error e) { if (e == API_EKEY) { if (!transfer->hascurrentmetamac) { // several integrity check errors uploading chunks return transfer->failcount < 1; } if (transfer->hasprevmetamac && transfer->prevmetamac == transfer->currentmetamac) { // integrity check failed after download, two times with the same value return false; } // integrity check failed once, try again transfer->prevmetamac = transfer->currentmetamac; transfer->hasprevmetamac = true; return transfer->failcount < 16; } return (e != API_EBLOCKED && e != API_ENOENT && e != API_EINTERNAL && transfer->failcount < 16) && !((e == API_EREAD || e == API_EWRITE) && transfer->failcount > 6); } void File::displayname(string* dname) { if (name.size()) { *dname = name; } else { Node* n; if ((n = transfer->client->nodebyhandle(h))) { *dname = n->displayname(); } else { *dname = "DELETED/UNAVAILABLE"; } } } #ifdef ENABLE_SYNC SyncFileGet::SyncFileGet(Sync* csync, Node* cn, string* clocalname) { sync = csync; n = cn; h = n->nodehandle; *(FileFingerprint*)this = *n; localname = *clocalname; syncxfer = true; n->syncget = this; } SyncFileGet::~SyncFileGet() { n->syncget = NULL; } // create sync-specific temp download directory and set unique filename void SyncFileGet::prepare() { if (!transfer->localfilename.size()) { int i; string tmpname, lockname; tmpname = "tmp"; sync->client->fsaccess->name2local(&tmpname); if (!sync->tmpfa) { sync->tmpfa = sync->client->fsaccess->newfileaccess(); for (i = 3; i--;) { LOG_verbose << "Creating tmp folder"; transfer->localfilename = sync->localdebris; sync->client->fsaccess->mkdirlocal(&transfer->localfilename, true); transfer->localfilename.append(sync->client->fsaccess->localseparator); transfer->localfilename.append(tmpname); sync->client->fsaccess->mkdirlocal(&transfer->localfilename); // lock it transfer->localfilename.append(sync->client->fsaccess->localseparator); lockname = "lock"; sync->client->fsaccess->name2local(&lockname); transfer->localfilename.append(lockname); if (sync->tmpfa->fopen(&transfer->localfilename, false, true)) { break; } } // if we failed to create the tmp dir three times in a row, fall // back to the sync's root if (i < 0) { delete sync->tmpfa; sync->tmpfa = NULL; } } if (sync->tmpfa) { transfer->localfilename = sync->localdebris; transfer->localfilename.append(sync->client->fsaccess->localseparator); transfer->localfilename.append(tmpname); } else { transfer->localfilename = sync->localroot.localname; } sync->client->fsaccess->tmpnamelocal(&tmpname); transfer->localfilename.append(sync->client->fsaccess->localseparator); transfer->localfilename.append(tmpname); } if (n->parent && n->parent->localnode) { n->parent->localnode->treestate(TREESTATE_SYNCING); } } bool SyncFileGet::failed(error e) { bool retry = File::failed(e); if (n->parent && n->parent->localnode) { n->parent->localnode->treestate(TREESTATE_PENDING); if (!retry && (e == API_EBLOCKED || e == API_EKEY)) { n->parent->client->movetosyncdebris(n, n->parent->localnode->sync->inshare); } } return retry; } void SyncFileGet::progress() { File::progress(); if (n->parent && n->parent->localnode && n->parent->localnode->ts != TREESTATE_SYNCING) { n->parent->localnode->treestate(TREESTATE_SYNCING); } } // update localname (parent's localnode) void SyncFileGet::updatelocalname() { attr_map::iterator ait; if ((ait = n->attrs.map.find('n')) != n->attrs.map.end()) { if (n->parent && n->parent->localnode) { string tmpname = ait->second; sync->client->fsaccess->name2local(&tmpname); n->parent->localnode->getlocalpath(&localname); localname.append(sync->client->fsaccess->localseparator); localname.append(tmpname); } } } // add corresponding LocalNode (by path), then self-destruct void SyncFileGet::completed(Transfer*, LocalNode*) { sync->checkpath(NULL, &localname); delete this; } void SyncFileGet::terminated() { delete this; } #endif } // namespace <|endoftext|>
<commit_before>#include <SDL/SDL.h> #ifdef __APPLE__ #include <SDL_mixer/SDL_mixer.h> #else #include <SDL/SDL_mixer.h> #endif #include "main.h" #include "game.h" #include "map.h" #include "hud.h" #include "sprite.h" #include "image.h" extern int resetTimer; extern SDL_Surface *screen; Game::Game() { } bool Game::hitTarget(Sprite *hero,Image *target,Map &map,Hud &hud) { float deltax,deltay; float dist; deltax=target->x-hero->x; deltay=target->y-hero->y; dist=deltax*deltax+deltay*deltay; if(dist<32*32) { hero->score++; hud.animateScore(map.viewx,map.viewy,hero); int x,j; x=(rand()%(map.getTilesAcross()-3))+2; j=(rand()%(map.getTilesDown()-2))+1; target->reset(32*x, 32*j); this->update(map, hud); return true; } return false; } bool Game::hitTarget(Sprite *hero,Map &map,Hud &hud) { // printf("hitTarget called"); for(ImageList::iterator p=_itemList.begin(); p!=_itemList.end(); p++) { Image *target=*p; bool result=hitTarget(hero,target,map,hud); if(result) return result; } return false; } void Game::mapReset(Map &map) { // hero.reset(64,128); // baddie.reset(64,128); // i=(rand()%(map.getTilesAcross()-3))+2; // j=(rand()%(map.getTilesDown()-2))+1; // target.reset(32*i,32*j); int x,j; for( SpriteList::iterator p=_playerList.begin(); p!=_playerList.end(); p++) { x=(rand()%(map.getTilesAcross()-3))+2; j=(rand()%(map.getTilesDown()-2))+1; Sprite *player=*p; player->reset(32*x, 32*j); } for( ImageList::iterator p=_itemList.begin(); p!=_itemList.end(); p++) { x=(rand()%(map.getTilesAcross()-3))+2; j=(rand()%(map.getTilesDown()-2))+1; Image *item=*p; item->reset(32*x, 32*j); } // map.calculateGradient(&target); // resetTimer=3000; // Mix_PauseMusic(); // map.updateView(&target); } void Game::newGame(Map &map) { //for (int i = 0; i < _playerList.size(); i++) { for( SpriteList::iterator p=_playerList.begin(); p!=_playerList.end(); p++) { Sprite *player=*p; player->score = 0; } // for( SpriteList::iterator p=_itemList.begin(); p!=_itemList.end(); p++) { // Sprite *item=*p; // item->score = 0; // } mapReset(map); playSound(S_START); } void Game::update(Map &map,Hud &hud) { map.updatePhysics(); for( SpriteList::iterator p=_playerList.begin(); p!=_playerList.end(); p++) { Sprite *player=*p; player->updatePhysics(&map); this->hitTarget(player, map, hud); } hud.update(_playerList); for( ImageList::iterator p=_itemList.begin(); p!=_itemList.end(); p++) { Image *item=*p; item->updatePhysics(&map); } //baddie.x=200; // if(resetTimer>0) { // resetTimer-=16; // if(resetTimer<=0) { // resetTimer=0; // Mix_ResumeMusic(); // } // } else { // map.updateView(&hero); //, &baddie); // } // hud.update(&hero, &baddie); // if( hitTarget(&hero,&target,map,hud) || hitTarget(&baddie,&target,map,hud)) { // mapReset(map); // playSound(S_MATCH); // if(hud.leftScore>8 || hud.rightScore>8) gameMode=MODE_WINNER; // } } SDL_Surface *titleImage=0; SDL_Surface *menuImage=0; void Game::draw(Map &map,Hud &hud) { #ifdef _PSP oslStartDrawing(); //To be able to draw on the screen #else static SDL_Surface *bgImage=0; //if(!bgImage) bgImage=IMG_Load("data/title.png"); //if(bgImage) SDL_BlitSurface(bgImage,0,screen,0); //else SDL_FillRect(screen,0,SDL_MapRGB(screen->format,189, 237, 255)); #endif map.draw(); //Draw the images to the screen for( SpriteList::iterator p=_playerList.begin(); p!=_playerList.end(); p++) { Sprite *player=*p; player->draw(map.viewx,map.viewy); } for( ImageList::iterator p=_itemList.begin(); p!=_itemList.end(); p++) { Image *item=*p; item->draw(map.viewx,map.viewy); } hud.draw(); if( gameMode==MODE_TITLE) { if(!titleImage) titleImage=IMG_Load("data/title.png"); if(titleImage) SDL_BlitSurface( titleImage, NULL, screen, NULL); } else { if(titleImage) SDL_FreeSurface( titleImage); titleImage=0; } if( gameMode==MODE_MENU) { if(!menuImage) menuImage=IMG_Load("data/menu.png"); if(menuImage) SDL_BlitSurface( menuImage, NULL, screen, NULL); } else { if(menuImage) SDL_FreeSurface( menuImage); menuImage=0; } #ifdef _PSP oslEndDrawing(); //Ends drawing mode oslEndFrame(); oslSyncFrame(); //Synchronizes the screen #else SDL_Flip(screen); static long before; long now=SDL_GetTicks(); long delay=before+32-now; if(delay>0 && delay<60) SDL_Delay(delay); before=now; #endif } void Game::handleUp(int key) { } void Game::handleDown(int key) { } void Game::addCharSprite(Sprite* spriteToAdd){ _playerList.push_back(spriteToAdd); printf("Success\n"); } void Game::addItemImage(Image *imageToAdd){ _itemList.push_back(imageToAdd); printf("Success\n"); } <commit_msg>Updated item placement.<commit_after>#include <SDL/SDL.h> #ifdef __APPLE__ #include <SDL_mixer/SDL_mixer.h> #else #include <SDL/SDL_mixer.h> #endif #include "main.h" #include "game.h" #include "map.h" #include "hud.h" #include "sprite.h" #include "image.h" extern int resetTimer; extern SDL_Surface *screen; Game::Game() { } bool Game::hitTarget(Sprite *hero,Image *target,Map &map,Hud &hud) { float deltax,deltay; float dist; deltax=target->x-hero->x; deltay=target->y-hero->y; dist=deltax*deltax+deltay*deltay; if(dist<32*32) { hero->score++; hud.animateScore(map.viewx,map.viewy,hero); int x,j; x=(rand()%(map.getTilesAcross()-3))+2; j=(rand()%(map.getTilesDown()-2))+1; target->reset(64*x, 64*j); this->update(map, hud); return true; } return false; } bool Game::hitTarget(Sprite *hero,Map &map,Hud &hud) { // printf("hitTarget called"); for(ImageList::iterator p=_itemList.begin(); p!=_itemList.end(); p++) { Image *target=*p; bool result=hitTarget(hero,target,map,hud); if(result) return result; } return false; } void Game::mapReset(Map &map) { // hero.reset(64,128); // baddie.reset(64,128); // i=(rand()%(map.getTilesAcross()-3))+2; // j=(rand()%(map.getTilesDown()-2))+1; // target.reset(32*i,32*j); int x,j; for( SpriteList::iterator p=_playerList.begin(); p!=_playerList.end(); p++) { x=(rand()%(map.getTilesAcross()-3))+2; j=(rand()%(map.getTilesDown()-2))+1; Sprite *player=*p; player->reset(64*x, 64*j); } for( ImageList::iterator p=_itemList.begin(); p!=_itemList.end(); p++) { x=(rand()%(map.getTilesAcross()-3))+2; j=(rand()%(map.getTilesDown()-2))+1; Image *item=*p; item->reset(64*x, 64*j); } // map.calculateGradient(&target); // resetTimer=3000; // Mix_PauseMusic(); // map.updateView(&target); } void Game::newGame(Map &map) { //for (int i = 0; i < _playerList.size(); i++) { for( SpriteList::iterator p=_playerList.begin(); p!=_playerList.end(); p++) { Sprite *player=*p; player->score = 0; } // for( SpriteList::iterator p=_itemList.begin(); p!=_itemList.end(); p++) { // Sprite *item=*p; // item->score = 0; // } mapReset(map); playSound(S_START); } void Game::update(Map &map,Hud &hud) { map.updatePhysics(); for( ImageList::iterator p=_itemList.begin(); p!=_itemList.end(); p++) { Image *item=*p; item->updatePhysics(&map); } for( SpriteList::iterator p=_playerList.begin(); p!=_playerList.end(); p++) { Sprite *player=*p; player->updatePhysics(&map); if(this->hitTarget(player, map, hud)) { playSound(S_MATCH); if(player->score>8) gameMode=MODE_WINNER; } } hud.update(_playerList); //baddie.x=200; // if(resetTimer>0) { // resetTimer-=16; // if(resetTimer<=0) { // resetTimer=0; // Mix_ResumeMusic(); // } // } else { // map.updateView(&hero); //, &baddie); // } // hud.update(&hero, &baddie); // if( hitTarget(&hero,&target,map,hud) || hitTarget(&baddie,&target,map,hud)) { // mapReset(map); // playSound(S_MATCH); // if(hud.leftScore>8 || hud.rightScore>8) gameMode=MODE_WINNER; // } } SDL_Surface *titleImage=0; SDL_Surface *menuImage=0; void Game::draw(Map &map,Hud &hud) { #ifdef _PSP oslStartDrawing(); //To be able to draw on the screen #else static SDL_Surface *bgImage=0; //if(!bgImage) bgImage=IMG_Load("data/title.png"); //if(bgImage) SDL_BlitSurface(bgImage,0,screen,0); //else SDL_FillRect(screen,0,SDL_MapRGB(screen->format,189, 237, 255)); #endif map.draw(); //Draw the images to the screen for( SpriteList::iterator p=_playerList.begin(); p!=_playerList.end(); p++) { Sprite *player=*p; player->draw(map.viewx,map.viewy); } for( ImageList::iterator p=_itemList.begin(); p!=_itemList.end(); p++) { Image *item=*p; item->draw(map.viewx,map.viewy); } hud.draw(); if( gameMode==MODE_TITLE) { if(!titleImage) titleImage=IMG_Load("data/title.png"); if(titleImage) SDL_BlitSurface( titleImage, NULL, screen, NULL); } else { if(titleImage) SDL_FreeSurface( titleImage); titleImage=0; } if( gameMode==MODE_MENU) { if(!menuImage) menuImage=IMG_Load("data/menu.png"); if(menuImage) SDL_BlitSurface( menuImage, NULL, screen, NULL); } else { if(menuImage) SDL_FreeSurface( menuImage); menuImage=0; } #ifdef _PSP oslEndDrawing(); //Ends drawing mode oslEndFrame(); oslSyncFrame(); //Synchronizes the screen #else SDL_Flip(screen); static long before; long now=SDL_GetTicks(); long delay=before+32-now; if(delay>0 && delay<60) SDL_Delay(delay); before=now; #endif } void Game::handleUp(int key) { } void Game::handleDown(int key) { } void Game::addCharSprite(Sprite* spriteToAdd){ _playerList.push_back(spriteToAdd); printf("Success\n"); } void Game::addItemImage(Image *imageToAdd){ _itemList.push_back(imageToAdd); printf("Success\n"); } <|endoftext|>
<commit_before>#include <Bridge.h> #include <BridgeClient.h> #include <MQTT.h> #include <ArduinoJson.h> // Sensors and actuators libs #include "Ultrasonic.h" #include "DHT.h" // Networking BridgeClient net; MQTTClient client; // Sensors and actuators #define DHTTYPE DHT11 int ultrasonicPin = 2; int DHTPin = 4; int buzzerPin = 8; int ledPin = 3; DHT dht(DHTPin, DHTTYPE); Ultrasonic ultrasonic(ultrasonicPin); // Program void connect() { Serial.print("Connecting..."); while (!client.connect("hytta", MQTT_USERNAME, MQTT_PASSWORD)) { Serial.print("."); delay(1000); } Serial.println("\nConnected!"); client.subscribe("/hello"); } void messageReceived(String &topic, String &payload) { Serial.println("incoming: " + topic + " - " + payload); } void setup() { Bridge.begin(); Serial.begin(115200); client.begin(MQTT_HOSTNAME, net); client.onMessage(messageReceived); connect(); Serial.begin(9600); dht.begin(); pinMode(buzzerPin, OUTPUT); pinMode(ledPin, OUTPUT); } void loop() { // MQTT client.loop(); if (!client.connected()) { connect(); } // read message and operate delay(1000); } void toggleDigital(int pin, int delayTime) { digitalWrite(pin, HIGH); delay(delayTime); digitalWrite(pin, LOW); } void printDHT(float h, int t) { Serial.print("Humidity: "); Serial.print(h); Serial.print("\t Temperature: "); Serial.print(t); Serial.println(" *C"); } <commit_msg>message<commit_after>#include <Bridge.h> #include <BridgeClient.h> #include <MQTT.h> #include <ArduinoJson.h> // Sensors and actuators libs #include "Ultrasonic.h" #include "DHT.h" // Networking BridgeClient net; MQTTClient client; // Sensors and actuators #define DHTTYPE DHT11 int ultrasonicPin = 2; int DHTPin = 4; int buzzerPin = 8; int ledPin = 3; DHT dht(DHTPin, DHTTYPE); Ultrasonic ultrasonic(ultrasonicPin); // Program void connect() { Serial.print("Connecting to MQTT..."); while (!client.connect("hytta", MQTT_USERNAME, MQTT_PASSWORD)) { Serial.print("."); delay(1000); } Serial.println("\nConnected!"); client.subscribe("/hello"); } void messageReceived(String &topic, String &payload) { Serial.println("incoming: " + topic + " - " + payload); } void setup() { Bridge.begin(); Serial.begin(115200); client.begin(MQTT_HOSTNAME, net); client.onMessage(messageReceived); connect(); Serial.begin(9600); dht.begin(); pinMode(buzzerPin, OUTPUT); pinMode(ledPin, OUTPUT); } void loop() { // MQTT client.loop(); if (!client.connected()) { connect(); } // read message and operate delay(1000); } void toggleDigital(int pin, int delayTime) { digitalWrite(pin, HIGH); delay(delayTime); digitalWrite(pin, LOW); } void printDHT(float h, int t) { Serial.print("Humidity: "); Serial.print(h); Serial.print("\t Temperature: "); Serial.print(t); Serial.println(" *C"); } <|endoftext|>
<commit_before> int main(int argc, char** argv) { // silence unused warnings (void)argc; (void)argv; return 0; } <commit_msg>travis: trigger build<commit_after> int main(int argc, char** argv) { // silence unused warnings (void)argc; (void)argv; return 0; } <|endoftext|>
<commit_before> #include "GmshReader.hpp" #include <boost/program_options.hpp> #include <iostream> int main(int argc, char* argv[]) { using namespace gmsh; // Parse the command line options and process the mesh try { // Define and parse the program options namespace po = boost::program_options; po::options_description visible("Options"); visible.add_options()("help", "Print help messages"); visible.add_options()( "zero-based", "Use zero based indexing for elements and nodes. Default: one-based."); visible.add_options()("local-ordering", "For distributed meshes, each processor has local indexing " "and a local to global mapping. Default: global-ordering"); visible.add_options()("with-indices", "Write out extra indices (results in file size increase). " "Default without-indices"); po::options_description hidden("Hidden options"); hidden.add_options()("input-file", po::value<std::vector<std::string>>(), "input file"); po::options_description cmdline_options; cmdline_options.add(visible).add(hidden); po::positional_options_description p; p.add("input-file", -1); po::variables_map vm; try { po::store(po::command_line_parser(argc, argv) .options(cmdline_options) .positional(p) .run(), vm); if (vm.count("help") || argc < 2) { std::cout << "\nA serial and parallel gmsh processing tool to convert " ".msh to .json files\n\n" << "gmshreader [Options] filename.msh\n\n" << visible << std::endl; return 0; } po::notify(vm); // throws on error, so do after help in case // there are any problems } catch (po::error& e) { std::cerr << "ERROR: " << e.what() << std::endl << std::endl; std::cerr << visible << std::endl; return 1; } Reader::IndexingBase indexing = vm.count("zero-based") > 1 ? Reader::IndexingBase::Zero : Reader::IndexingBase::One; Reader::NodalOrdering ordering = vm.count("local-ordering") > 1 ? Reader::NodalOrdering::Local : Reader::NodalOrdering::Global; if (vm.count("input-file")) { for (auto const& input : vm["input-file"].as<std::vector<std::string>>()) { Reader reader(input, ordering, indexing); reader.writeMeshToJson(vm.count("with-indices") > 1); } } else { throw std::runtime_error("Missing \".msh\" input file!\n"); } } catch (std::exception& e) { std::cerr << "Unhandled Exception reached the top of main: " << e.what() << ", application will now exit" << std::endl; return 1; } return 0; } <commit_msg>Fixed bug in counting the input arguments<commit_after> #include "GmshReader.hpp" #include <boost/program_options.hpp> #include <iostream> int main(int argc, char* argv[]) { using namespace gmsh; // Parse the command line options and process the mesh try { // Define and parse the program options namespace po = boost::program_options; po::options_description visible("Options"); visible.add_options()("help", "Print help messages"); visible.add_options()( "zero-based", "Use zero based indexing for elements and nodes. Default: one-based."); visible.add_options()("local-ordering", "For distributed meshes, each processor has local indexing " "and a local to global mapping. Default: global-ordering"); visible.add_options()("with-indices", "Write out extra indices (results in file size increase). " "Default without-indices"); po::options_description hidden("Hidden options"); hidden.add_options()("input-file", po::value<std::vector<std::string>>(), "input file"); po::options_description cmdline_options; cmdline_options.add(visible).add(hidden); po::positional_options_description p; p.add("input-file", -1); po::variables_map vm; try { po::store(po::command_line_parser(argc, argv) .options(cmdline_options) .positional(p) .run(), vm); if (vm.count("help") || argc < 2) { std::cout << "\nA serial and parallel gmsh processing tool to convert " ".msh to .json files\n\n" << "gmshreader [Options] filename.msh\n\n" << visible << std::endl; return 0; } po::notify(vm); // throws on error, so do after help in case // there are any problems } catch (po::error& e) { std::cerr << "ERROR: " << e.what() << std::endl << std::endl; std::cerr << visible << std::endl; return 1; } Reader::IndexingBase indexing = vm.count("zero-based") > 0 ? Reader::IndexingBase::Zero : Reader::IndexingBase::One; Reader::NodalOrdering ordering = vm.count("local-ordering") > 0 ? Reader::NodalOrdering::Local : Reader::NodalOrdering::Global; if (vm.count("input-file")) { for (auto const& input : vm["input-file"].as<std::vector<std::string>>()) { Reader reader(input, ordering, indexing); reader.writeMeshToJson(vm.count("with-indices") > 1); } } else { throw std::runtime_error("Missing \".msh\" input file!\n"); } } catch (std::exception& e) { std::cerr << "Unhandled Exception reached the top of main: " << e.what() << ", application will now exit" << std::endl; return 1; } return 0; } <|endoftext|>
<commit_before>/** * libcec-daemon * A simple daemon to connect libcec to uinput. That is, using your TV to control your PC! * by Andrew Brampton * * TODO * */ #include "main.h" #define VERSION "libcec-daemon v0.9" #define CEC_NAME "linux PC" #define UINPUT_NAME "libcec-daemon" #include <algorithm> #include <cstdio> #include <iostream> #include <cstdint> #include <cstddef> #include <csignal> #include <vector> #include <boost/program_options.hpp> #include "accumulator.hpp" #include <log4cplus/logger.h> #include <log4cplus/loggingmacros.h> #include <log4cplus/configurator.h> using namespace CEC; using namespace log4cplus; using std::cout; using std::cerr; using std::endl; using std::min; using std::string; using std::vector; static Logger logger = Logger::getInstance("main"); const vector<__u16> Main::uinputCecMap = Main::setupUinputMap(); Main & Main::instance() { // Singleton pattern so we can use main from a sighandle static Main main; return main; } Main::Main() : cec(CEC_NAME, this), uinput(UINPUT_NAME, uinputCecMap), running(true) { LOG4CPLUS_TRACE_STR(logger, "Main::Main()"); signal (SIGINT, &Main::signalHandler); signal (SIGTERM, &Main::signalHandler); } Main::~Main() { LOG4CPLUS_TRACE_STR(logger, "Main::~Main()"); stop(); } void Main::loop() { LOG4CPLUS_TRACE_STR(logger, "Main::loop()"); cec.open(); while (running) { LOG4CPLUS_TRACE_STR(logger, "Loop"); sleep(1); } cec.close(); } void Main::stop() { LOG4CPLUS_TRACE_STR(logger, "Main::stop()"); running = false; } void Main::listDevices() { LOG4CPLUS_TRACE_STR(logger, "Main::listDevices()"); cec.listDevices(cout); } void Main::signalHandler(int sigNum) { LOG4CPLUS_DEBUG_STR(logger, "Main::signalHandler()"); Main::instance().stop(); } const std::vector<__u16> & Main::setupUinputMap() { static std::vector<__u16> uinputCecMap; if (uinputCecMap.empty()) { uinputCecMap.resize(CEC_USER_CONTROL_CODE_MAX + 1, 0); uinputCecMap[CEC_USER_CONTROL_CODE_SELECT ] = KEY_ENTER; uinputCecMap[CEC_USER_CONTROL_CODE_UP ] = KEY_UP; uinputCecMap[CEC_USER_CONTROL_CODE_DOWN ] = KEY_DOWN; uinputCecMap[CEC_USER_CONTROL_CODE_LEFT ] = KEY_LEFT; uinputCecMap[CEC_USER_CONTROL_CODE_RIGHT ] = KEY_RIGHT; uinputCecMap[CEC_USER_CONTROL_CODE_RIGHT_UP ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_RIGHT_DOWN ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_LEFT_UP ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_LEFT_DOWN ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_ROOT_MENU ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_SETUP_MENU ] = KEY_SETUP; uinputCecMap[CEC_USER_CONTROL_CODE_CONTENTS_MENU ] = KEY_MENU; uinputCecMap[CEC_USER_CONTROL_CODE_FAVORITE_MENU ] = KEY_FAVORITES; uinputCecMap[CEC_USER_CONTROL_CODE_EXIT ] = KEY_BACKSPACE; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER0 ] = KEY_0; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER1 ] = KEY_1; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER2 ] = KEY_2; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER3 ] = KEY_3; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER4 ] = KEY_4; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER5 ] = KEY_5; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER6 ] = KEY_6; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER7 ] = KEY_7; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER8 ] = KEY_8; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER9 ] = KEY_9; uinputCecMap[CEC_USER_CONTROL_CODE_DOT ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_ENTER ] = KEY_ENTER; uinputCecMap[CEC_USER_CONTROL_CODE_CLEAR ] = KEY_EXIT; uinputCecMap[CEC_USER_CONTROL_CODE_NEXT_FAVORITE ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_CHANNEL_UP ] = KEY_CHANNELUP; uinputCecMap[CEC_USER_CONTROL_CODE_CHANNEL_DOWN ] = KEY_CHANNELDOWN; uinputCecMap[CEC_USER_CONTROL_CODE_PREVIOUS_CHANNEL ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_SOUND_SELECT ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_INPUT_SELECT ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_DISPLAY_INFORMATION ] = KEY_INFO; uinputCecMap[CEC_USER_CONTROL_CODE_HELP ] = KEY_HELP; uinputCecMap[CEC_USER_CONTROL_CODE_PAGE_UP ] = KEY_PAGEUP; uinputCecMap[CEC_USER_CONTROL_CODE_PAGE_DOWN ] = KEY_PAGEDOWN; uinputCecMap[CEC_USER_CONTROL_CODE_POWER ] = KEY_POWER; uinputCecMap[CEC_USER_CONTROL_CODE_VOLUME_UP ] = KEY_VOLUMEUP; uinputCecMap[CEC_USER_CONTROL_CODE_VOLUME_DOWN ] = KEY_VOLUMEDOWN; uinputCecMap[CEC_USER_CONTROL_CODE_MUTE ] = KEY_MUTE; uinputCecMap[CEC_USER_CONTROL_CODE_PLAY ] = KEY_PLAY; uinputCecMap[CEC_USER_CONTROL_CODE_STOP ] = KEY_STOP; uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE ] = KEY_PAUSE; uinputCecMap[CEC_USER_CONTROL_CODE_RECORD ] = KEY_RECORD; uinputCecMap[CEC_USER_CONTROL_CODE_REWIND ] = KEY_REWIND; uinputCecMap[CEC_USER_CONTROL_CODE_FAST_FORWARD ] = KEY_FASTFORWARD; uinputCecMap[CEC_USER_CONTROL_CODE_EJECT ] = KEY_EJECTCD; uinputCecMap[CEC_USER_CONTROL_CODE_FORWARD ] = KEY_NEXTSONG; uinputCecMap[CEC_USER_CONTROL_CODE_BACKWARD ] = KEY_PREVIOUSSONG; uinputCecMap[CEC_USER_CONTROL_CODE_STOP_RECORD ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE_RECORD ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_ANGLE ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_SUB_PICTURE ] = KEY_SUBTITLE; uinputCecMap[CEC_USER_CONTROL_CODE_VIDEO_ON_DEMAND ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_ELECTRONIC_PROGRAM_GUIDE ] = KEY_EPG; uinputCecMap[CEC_USER_CONTROL_CODE_TIMER_PROGRAMMING ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_INITIAL_CONFIGURATION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_PLAY_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE_PLAY_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_RECORD_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE_RECORD_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_STOP_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_MUTE_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_RESTORE_VOLUME_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_TUNE_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_SELECT_MEDIA_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_SELECT_AV_INPUT_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_SELECT_AUDIO_INPUT_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_POWER_TOGGLE_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_POWER_OFF_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_POWER_ON_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_F1_BLUE ] = KEY_BLUE; uinputCecMap[CEC_USER_CONTROL_CODE_F2_RED ] = KEY_RED; uinputCecMap[CEC_USER_CONTROL_CODE_F3_GREEN ] = KEY_GREEN; uinputCecMap[CEC_USER_CONTROL_CODE_F4_YELLOW ] = KEY_YELLOW; uinputCecMap[CEC_USER_CONTROL_CODE_F5 ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_DATA ] = KEY_TEXT; uinputCecMap[CEC_USER_CONTROL_CODE_AN_RETURN ] = 0; } return uinputCecMap; } int Main::onCecLogMessage(const cec_log_message &message) { LOG4CPLUS_DEBUG(logger, "Main::onCecLogMessage(" << message << ")"); return 1; } int Main::onCecKeyPress(const cec_keypress &key) { LOG4CPLUS_DEBUG(logger, "Main::onCecKeyPress(" << key << ")"); int uinputKey = 0; // Check bounds and find uinput code for this cec keypress if (key.keycode >= 0 && key.keycode <= CEC_USER_CONTROL_CODE_MAX) uinputKey = uinputCecMap[key.keycode]; if (uinputKey != 0) { LOG4CPLUS_DEBUG(logger, "sent " << uinputKey); // Fix for issues with ealier veriosns of libcec and key repeats below < 2.0.5 #if LIBCEC_VERSION_CURRENT < 0x2005 uinput.send_event(EV_KEY, uinputKey, key.duration == 0 ? 1 : 0); #else uinput.send_event(EV_KEY, uinputKey, key.duration == 0 ? 2 : 0); #endif uinput.sync(); } return 1; } int Main::onCecCommand(const cec_command & command) { LOG4CPLUS_DEBUG(logger, "Main::onCecCommand(" << command << ")"); return 1; } int Main::onCecConfigurationChanged(const libcec_configuration & configuration) { LOG4CPLUS_DEBUG(logger, "Main::onCecConfigurationChanged(" << configuration << ")"); return 1; } int main (int argc, char *argv[]) { BasicConfigurator config; config.configure(); int loglevel = 0; namespace po = boost::program_options; po::options_description desc("Allowed options"); desc.add_options() ("help,h", "show help message") ("version,V", "show version (and exit)") ("daemon,d", "daemon mode, run in background") ("list,l", "list available CEC adapters and devices") ("verbose,v", accumulator<int>(&loglevel)->implicit_value(1), "verbose output (use -vv for more)") ("quiet,q", "quiet output (print almost nothing)") ("usb", po::value<std::string>(), "USB adapter path (as shown by --list)") ; po::positional_options_description p; p.add("usb", 1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); po::notify(vm); if (vm.count("help")) { cout << "Usage: " << argv[0] << " [-h] [-v] [-d] [usb]" << endl << endl; cout << desc << endl; return 0; } if (vm.count("version")) { cout << VERSION << endl; return 0; } if(vm.count("quiet")) { loglevel = -1; } else { loglevel = min(loglevel, 2); } Logger root = Logger::getRoot(); switch (loglevel) { case 2: root.setLogLevel(TRACE_LOG_LEVEL); break; case 1: root.setLogLevel(DEBUG_LOG_LEVEL); break; default: root.setLogLevel(INFO_LOG_LEVEL); break; case -1: root.setLogLevel(FATAL_LOG_LEVEL); break; } try { // Create the main Main & main = Main::instance(); if (vm.count("list")) { main.listDevices(); return 0; } if (vm.count("usb")) { cout << vm["usb"].as< string >() << endl; } if (vm.count("daemon")) { daemon(0, 0); } main.loop(); } catch (std::exception & e) { cerr << e.what() << endl; return -1; } return 0; } <commit_msg>Add mapping for ROOT MENU to HOME<commit_after>/** * libcec-daemon * A simple daemon to connect libcec to uinput. That is, using your TV to control your PC! * by Andrew Brampton * * TODO * */ #include "main.h" #define VERSION "libcec-daemon v0.9" #define CEC_NAME "linux PC" #define UINPUT_NAME "libcec-daemon" #include <algorithm> #include <cstdio> #include <iostream> #include <cstdint> #include <cstddef> #include <csignal> #include <vector> #include <boost/program_options.hpp> #include "accumulator.hpp" #include <log4cplus/logger.h> #include <log4cplus/loggingmacros.h> #include <log4cplus/configurator.h> using namespace CEC; using namespace log4cplus; using std::cout; using std::cerr; using std::endl; using std::min; using std::string; using std::vector; static Logger logger = Logger::getInstance("main"); const vector<__u16> Main::uinputCecMap = Main::setupUinputMap(); Main & Main::instance() { // Singleton pattern so we can use main from a sighandle static Main main; return main; } Main::Main() : cec(CEC_NAME, this), uinput(UINPUT_NAME, uinputCecMap), running(true) { LOG4CPLUS_TRACE_STR(logger, "Main::Main()"); signal (SIGINT, &Main::signalHandler); signal (SIGTERM, &Main::signalHandler); } Main::~Main() { LOG4CPLUS_TRACE_STR(logger, "Main::~Main()"); stop(); } void Main::loop() { LOG4CPLUS_TRACE_STR(logger, "Main::loop()"); cec.open(); while (running) { LOG4CPLUS_TRACE_STR(logger, "Loop"); sleep(1); } cec.close(); } void Main::stop() { LOG4CPLUS_TRACE_STR(logger, "Main::stop()"); running = false; } void Main::listDevices() { LOG4CPLUS_TRACE_STR(logger, "Main::listDevices()"); cec.listDevices(cout); } void Main::signalHandler(int sigNum) { LOG4CPLUS_DEBUG_STR(logger, "Main::signalHandler()"); Main::instance().stop(); } const std::vector<__u16> & Main::setupUinputMap() { static std::vector<__u16> uinputCecMap; if (uinputCecMap.empty()) { uinputCecMap.resize(CEC_USER_CONTROL_CODE_MAX + 1, 0); uinputCecMap[CEC_USER_CONTROL_CODE_SELECT ] = KEY_ENTER; uinputCecMap[CEC_USER_CONTROL_CODE_UP ] = KEY_UP; uinputCecMap[CEC_USER_CONTROL_CODE_DOWN ] = KEY_DOWN; uinputCecMap[CEC_USER_CONTROL_CODE_LEFT ] = KEY_LEFT; uinputCecMap[CEC_USER_CONTROL_CODE_RIGHT ] = KEY_RIGHT; uinputCecMap[CEC_USER_CONTROL_CODE_RIGHT_UP ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_RIGHT_DOWN ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_LEFT_UP ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_LEFT_DOWN ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_ROOT_MENU ] = KEY_HOME; uinputCecMap[CEC_USER_CONTROL_CODE_SETUP_MENU ] = KEY_SETUP; uinputCecMap[CEC_USER_CONTROL_CODE_CONTENTS_MENU ] = KEY_MENU; uinputCecMap[CEC_USER_CONTROL_CODE_FAVORITE_MENU ] = KEY_FAVORITES; uinputCecMap[CEC_USER_CONTROL_CODE_EXIT ] = KEY_BACKSPACE; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER0 ] = KEY_0; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER1 ] = KEY_1; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER2 ] = KEY_2; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER3 ] = KEY_3; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER4 ] = KEY_4; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER5 ] = KEY_5; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER6 ] = KEY_6; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER7 ] = KEY_7; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER8 ] = KEY_8; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER9 ] = KEY_9; uinputCecMap[CEC_USER_CONTROL_CODE_DOT ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_ENTER ] = KEY_ENTER; uinputCecMap[CEC_USER_CONTROL_CODE_CLEAR ] = KEY_EXIT; uinputCecMap[CEC_USER_CONTROL_CODE_NEXT_FAVORITE ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_CHANNEL_UP ] = KEY_CHANNELUP; uinputCecMap[CEC_USER_CONTROL_CODE_CHANNEL_DOWN ] = KEY_CHANNELDOWN; uinputCecMap[CEC_USER_CONTROL_CODE_PREVIOUS_CHANNEL ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_SOUND_SELECT ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_INPUT_SELECT ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_DISPLAY_INFORMATION ] = KEY_INFO; uinputCecMap[CEC_USER_CONTROL_CODE_HELP ] = KEY_HELP; uinputCecMap[CEC_USER_CONTROL_CODE_PAGE_UP ] = KEY_PAGEUP; uinputCecMap[CEC_USER_CONTROL_CODE_PAGE_DOWN ] = KEY_PAGEDOWN; uinputCecMap[CEC_USER_CONTROL_CODE_POWER ] = KEY_POWER; uinputCecMap[CEC_USER_CONTROL_CODE_VOLUME_UP ] = KEY_VOLUMEUP; uinputCecMap[CEC_USER_CONTROL_CODE_VOLUME_DOWN ] = KEY_VOLUMEDOWN; uinputCecMap[CEC_USER_CONTROL_CODE_MUTE ] = KEY_MUTE; uinputCecMap[CEC_USER_CONTROL_CODE_PLAY ] = KEY_PLAY; uinputCecMap[CEC_USER_CONTROL_CODE_STOP ] = KEY_STOP; uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE ] = KEY_PAUSE; uinputCecMap[CEC_USER_CONTROL_CODE_RECORD ] = KEY_RECORD; uinputCecMap[CEC_USER_CONTROL_CODE_REWIND ] = KEY_REWIND; uinputCecMap[CEC_USER_CONTROL_CODE_FAST_FORWARD ] = KEY_FASTFORWARD; uinputCecMap[CEC_USER_CONTROL_CODE_EJECT ] = KEY_EJECTCD; uinputCecMap[CEC_USER_CONTROL_CODE_FORWARD ] = KEY_NEXTSONG; uinputCecMap[CEC_USER_CONTROL_CODE_BACKWARD ] = KEY_PREVIOUSSONG; uinputCecMap[CEC_USER_CONTROL_CODE_STOP_RECORD ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE_RECORD ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_ANGLE ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_SUB_PICTURE ] = KEY_SUBTITLE; uinputCecMap[CEC_USER_CONTROL_CODE_VIDEO_ON_DEMAND ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_ELECTRONIC_PROGRAM_GUIDE ] = KEY_EPG; uinputCecMap[CEC_USER_CONTROL_CODE_TIMER_PROGRAMMING ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_INITIAL_CONFIGURATION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_PLAY_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE_PLAY_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_RECORD_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE_RECORD_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_STOP_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_MUTE_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_RESTORE_VOLUME_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_TUNE_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_SELECT_MEDIA_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_SELECT_AV_INPUT_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_SELECT_AUDIO_INPUT_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_POWER_TOGGLE_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_POWER_OFF_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_POWER_ON_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_F1_BLUE ] = KEY_BLUE; uinputCecMap[CEC_USER_CONTROL_CODE_F2_RED ] = KEY_RED; uinputCecMap[CEC_USER_CONTROL_CODE_F3_GREEN ] = KEY_GREEN; uinputCecMap[CEC_USER_CONTROL_CODE_F4_YELLOW ] = KEY_YELLOW; uinputCecMap[CEC_USER_CONTROL_CODE_F5 ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_DATA ] = KEY_TEXT; uinputCecMap[CEC_USER_CONTROL_CODE_AN_RETURN ] = 0; } return uinputCecMap; } int Main::onCecLogMessage(const cec_log_message &message) { LOG4CPLUS_DEBUG(logger, "Main::onCecLogMessage(" << message << ")"); return 1; } int Main::onCecKeyPress(const cec_keypress &key) { LOG4CPLUS_DEBUG(logger, "Main::onCecKeyPress(" << key << ")"); int uinputKey = 0; // Check bounds and find uinput code for this cec keypress if (key.keycode >= 0 && key.keycode <= CEC_USER_CONTROL_CODE_MAX) uinputKey = uinputCecMap[key.keycode]; if (uinputKey != 0) { LOG4CPLUS_DEBUG(logger, "sent " << uinputKey); // Fix for issues with ealier veriosns of libcec and key repeats below < 2.0.5 #if LIBCEC_VERSION_CURRENT < 0x2005 uinput.send_event(EV_KEY, uinputKey, key.duration == 0 ? 1 : 0); #else uinput.send_event(EV_KEY, uinputKey, key.duration == 0 ? 2 : 0); #endif uinput.sync(); } return 1; } int Main::onCecCommand(const cec_command & command) { LOG4CPLUS_DEBUG(logger, "Main::onCecCommand(" << command << ")"); return 1; } int Main::onCecConfigurationChanged(const libcec_configuration & configuration) { LOG4CPLUS_DEBUG(logger, "Main::onCecConfigurationChanged(" << configuration << ")"); return 1; } int main (int argc, char *argv[]) { BasicConfigurator config; config.configure(); int loglevel = 0; namespace po = boost::program_options; po::options_description desc("Allowed options"); desc.add_options() ("help,h", "show help message") ("version,V", "show version (and exit)") ("daemon,d", "daemon mode, run in background") ("list,l", "list available CEC adapters and devices") ("verbose,v", accumulator<int>(&loglevel)->implicit_value(1), "verbose output (use -vv for more)") ("quiet,q", "quiet output (print almost nothing)") ("usb", po::value<std::string>(), "USB adapter path (as shown by --list)") ; po::positional_options_description p; p.add("usb", 1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); po::notify(vm); if (vm.count("help")) { cout << "Usage: " << argv[0] << " [-h] [-v] [-d] [usb]" << endl << endl; cout << desc << endl; return 0; } if (vm.count("version")) { cout << VERSION << endl; return 0; } if(vm.count("quiet")) { loglevel = -1; } else { loglevel = min(loglevel, 2); } Logger root = Logger::getRoot(); switch (loglevel) { case 2: root.setLogLevel(TRACE_LOG_LEVEL); break; case 1: root.setLogLevel(DEBUG_LOG_LEVEL); break; default: root.setLogLevel(INFO_LOG_LEVEL); break; case -1: root.setLogLevel(FATAL_LOG_LEVEL); break; } try { // Create the main Main & main = Main::instance(); if (vm.count("list")) { main.listDevices(); return 0; } if (vm.count("usb")) { cout << vm["usb"].as< string >() << endl; } if (vm.count("daemon")) { daemon(0, 0); } main.loop(); } catch (std::exception & e) { cerr << e.what() << endl; return -1; } return 0; } <|endoftext|>
<commit_before>// main.cpp // 26. April 2017 // Created by: // Bryan Burkhardt (bmburkhardt@alaska.edu) // Alexander Eckert (aeckert@alaska.edu) // Jeremiah Jacobson (jjjacobson2@alaska.edu) // Jarye Murphy (jmurphy11@alaska.edu) // Cameron Showalter (cjshowalter@alaska.edu) // // Main file for MusicPlayer372, the project from CS372 // with Professor Chris Hartman #include "../include/musicPlayer.hpp" int main() { std::cout << "MusicPlayer372" << std::endl; std::cout << "Version " << myproject_VERSION_MAJOR << "." << myproject_VERSION_MINOR << std::endl; MusicPlayer musicPlayer; musicPlayer.playerLoop(); return 0; }<commit_msg>testing if branch is deleted<commit_after>// main.cpp // 26. April 2017 // Created by: // Bryan Burkhardt (bmburkhardt@alaska.edu) // Alexander Eckert (aeckert@alaska.edu) // Jeremiah Jacobson (jjjacobson2@alaska.edu) // Jarye Murphy (jmurphy11@alaska.edu) // Cameron Showalter (cjshowalter@alaska.edu) // // Main file for MusicPlayer372, the project from CS372 // with Professor Chris Hartman #include "../include/musicPlayer.hpp" int main() { std::cout << "MusicPlayer" << std::endl; std::cout << "Version " << myproject_VERSION_MAJOR << "." << myproject_VERSION_MINOR << std::endl; MusicPlayer musicPlayer; musicPlayer.playerLoop(); return 0; } <|endoftext|>
<commit_before>#include <cstdlib> #include <sys/wait.h> #include <string> #include <vector> #include <cstring> #include <iostream> #include <unistd.h> #include <pwd.h> #include <sys/types.h> #include <stdio.h> #include <errno.h> #include <stdlib.h> #include "main.h" using namespace std; int main() { string userinput; string login = getlogin(); if(login == "") perror("getlogin"); char hostname[128]; if(gethostname(hostname, sizeof hostname)) perror("gethostname"); bool ext = false; string exit_status = "exit"; while(!ext) { char *pPath/*, *dPath*/; pPath = getenv("PWD"); //dPath = getenv("OLDPWD"); cout << login << "@" << hostname << "~" << pPath << " $ "; char *command_a; char *command; getline(cin, userinput); if(userinput.find("#") != string::npos) userinput.erase(userinput.find("#"), userinput.size()); command = new char[userinput.size()]; vector<int> c_pat; vector<int> c_pos; bool first = false; bool multiple = false; if(userinput.size() != 0) connectors(userinput, c_pat, c_pos, first, multiple); int x = 0; unsigned int b = 0; int y = 0; char *arg[50000]; int status; redir condition; if(userinput.size() != 0) { while(userinput.substr(x, 1) != "") { if(multiple) { cout << "Error: Incorrect connector config" << endl; break; } if(first) { cout << "Error: file does not exist" << endl; break; } redir_check(condition, userinput.substr(x, c_pos.at(y) -x).c_str()); strcpy(command, userinput.substr(x, c_pos.at(y) - x).c_str()); command_a = strtok(command, "&;| \t"); while(command_a != NULL) { arg[b] = command_a; command_a = strtok(NULL, "&;| \t"); b++; } if(userinput.substr(x, c_pos.at(y) - x).find("exit") != string::npos && b==1) { ext = true; break; } if(condition.redir_x) { redir_action(condition); nullify(condition); } else if(strcmp(arg[0], "cd") == 0) { cout << "cd\n" << b; if(b == 1) { if(setenv("OLDPWD", "PWD", 1) == -1) perror("setenv_1.1"); char *home; if((home = getenv("HOME")) == NULL) perror("getenv_1.1"); chdir(home); if(setenv("PWD", home, 1) == -1) perror("setenv_1.2"); } else if(strcmp(arg[1], "-") == 0) { char *old, *newDir; if((old = getenv("PWD")) == NULL) perror("getenv_2.1"); if(() == NULL) perror("getenv_2.2"); } } else { int i = fork(); if(i == -1) perror("fork"); if(i == 0) { if(execvp(arg[0], arg) == -1) { perror("execvp"); exit(-1); } exit(0); } if(wait(&status) == -1) perror("wait"); } x = c_pos.at(y); unsigned int help = c_pat.at(y); for(unsigned int i = 0; i < b; i++) arg[i] = NULL; if((help == 1 && status == 0) || (help == 0 && status != 0) || help == 2) y++; else if(help == 1 && status != 0 && (userinput.find("||", x) != string::npos || userinput.find(";", x) != string::npos)) { x = c_pos.at(y + 1); y+=2; } else if(help == 0 && status == 0 && (userinput.find("&&", x) != string::npos || userinput.find(";", x) != string::npos)) { x = c_pos.at(y + 1); y+=2; } else break; b = 0; } } delete []command; } return 0; } <commit_msg>cd almost done<commit_after>#include <cstdlib> #include <sys/wait.h> #include <string> #include <vector> #include <cstring> #include <iostream> #include <unistd.h> #include <pwd.h> #include <sys/types.h> #include <stdio.h> #include <errno.h> #include <stdlib.h> #include "main.h" using namespace std; int main() { string userinput; string login = getlogin(); if(login == "") perror("getlogin"); char hostname[128]; if(gethostname(hostname, sizeof hostname)) perror("gethostname"); bool ext = false; string exit_status = "exit"; while(!ext) { char *pPath/*, *dPath*/; pPath = getenv("PWD"); //dPath = getenv("OLDPWD"); cout << login << "@" << hostname << "~" << pPath << " $ "; char *command_a; char *command; getline(cin, userinput); if(userinput.find("#") != string::npos) userinput.erase(userinput.find("#"), userinput.size()); command = new char[userinput.size()]; vector<int> c_pat; vector<int> c_pos; bool first = false; bool multiple = false; if(userinput.size() != 0) connectors(userinput, c_pat, c_pos, first, multiple); int x = 0; unsigned int b = 0; int y = 0; char *arg[50000]; int status; redir condition; if(userinput.size() != 0) { while(userinput.substr(x, 1) != "") { if(multiple) { cout << "Error: Incorrect connector config" << endl; break; } if(first) { cout << "Error: file does not exist" << endl; break; } redir_check(condition, userinput.substr(x, c_pos.at(y) -x).c_str()); strcpy(command, userinput.substr(x, c_pos.at(y) - x).c_str()); command_a = strtok(command, "&;| \t"); while(command_a != NULL) { arg[b] = command_a; command_a = strtok(NULL, "&;| \t"); b++; } if(userinput.substr(x, c_pos.at(y) - x).find("exit") != string::npos && b==1) { ext = true; break; } if(condition.redir_x) { redir_action(condition); nullify(condition); } else if(strcmp(arg[0], "cd") == 0) { cout << "cd\n" << b; if(b == 1) { if(setenv("OLDPWD", "PWD", 1) == -1) perror("setenv_1.1"); char *home; if((home = getenv("HOME")) == NULL) perror("getenv_1.1"); chdir(home); if(setenv("PWD", home, 1) == -1) perror("setenv_1.2"); } else if(strcmp(arg[1], "-") == 0) { char *old, *newDir; if((old = getenv("PWD")) == NULL) perror("getenv_2.1"); if((newDir = getenv("OLDPWD")) == NULL) perror("getenv_2.2"); chdir(newDir); if(setenv("PWD", newDir, 1) == -1) perror("setenv_2.1"); if(setenv("OLDPWD", old, 1) == -1) perror("setenv_2.2"); } } else { int i = fork(); if(i == -1) perror("fork"); if(i == 0) { if(execvp(arg[0], arg) == -1) { perror("execvp"); exit(-1); } exit(0); } if(wait(&status) == -1) perror("wait"); } x = c_pos.at(y); unsigned int help = c_pat.at(y); for(unsigned int i = 0; i < b; i++) arg[i] = NULL; if((help == 1 && status == 0) || (help == 0 && status != 0) || help == 2) y++; else if(help == 1 && status != 0 && (userinput.find("||", x) != string::npos || userinput.find(";", x) != string::npos)) { x = c_pos.at(y + 1); y+=2; } else if(help == 0 && status == 0 && (userinput.find("&&", x) != string::npos || userinput.find(";", x) != string::npos)) { x = c_pos.at(y + 1); y+=2; } else break; b = 0; } } delete []command; } return 0; } <|endoftext|>
<commit_before>#include <iostream> #include "main.hpp" #include "util.hpp" #include "system/printer.hpp" #ifndef OBJ_PATH #define OBJ_PATH "share/sphere.obj" #endif /*#ifndef MTL_PATH #define MTL_PATH "share/cube.mtl" #endif*/ #ifndef VERT_PATH #define VERT_PATH "share/fallback.vert" #endif #ifndef FRAG_PATH #define FRAG_PATH "share/shade.frag" #endif void printErrors(std::ostream &oss) {} template<typename T1, typename... TN> void printErrors(std::ostream &oss, T1 &t1, TN &... tn) { for(auto e : t1) { oss << e << std::endl; } printErrors(oss, tn...); } int main(int argc, const char **argv) { using namespace Util; using namespace System; if(glfwInit() == 0) { std::cout << "Failed to initialize GLFW " << glfwGetVersionString() << std::endl; return 1; } const char *obj_fname, *mtl_fname, *vert_fname, *frag_fname; if(argc >= 2) obj_fname = argv[1]; else obj_fname = OBJ_PATH; if(argc >= 3) mtl_fname = argv[2]; else mtl_fname = MTL_PATH; if(argc >= 4) vert_fname = argv[3]; else vert_fname = VERT_PATH; if(argc >= 5) frag_fname = argv[4]; else frag_fname = FRAG_PATH; std::atomic_bool alive(true); Control::control ctl(alive, obj_fname); if(!alive) { std::cout << "Control construction failed." << std::endl; printErrors(std::cout, ctl.viewer.errors, ctl.errors); return 1; } if(!ctl.viewer.setProg(alive, vert_fname, frag_fname)) { std::cout << "Failed to compile or link shaders." << std::endl; printErrors(std::cout, ctl.viewer.errors, ctl.errors); return 1; } using namespace System; Printer<6> printer; std::string cols[]{"GLFW", "OpenGL", "Path"}, rows[]{"", "Major", "Minor", "Revision", "", "", "Wavefront obj", "Wavefront mtl", "Vertex shader", "Fragment shader", ""}, paths[]{obj_fname, mtl_fname, vert_fname, frag_fname}; int versions[6]{0}; glfwGetVersion(&versions[0], &versions[2], &versions[4]); glGetIntegerv(GL_MAJOR_VERSION, &versions[1]); glGetIntegerv(GL_MINOR_VERSION, &versions[3]); printer.push(&rows[5], &rows[5]+6) .level().insert(0, " ").level() .push<std::string, 4, 1, 31>(paths, &cols[2], &cols[3]+1) .level().insert(0, " ").level() .push(&rows[0], &rows[5]) .level().insert(0, " ").level() .push<int, 3, 2>(versions, &cols[0], &cols[2]); std::cout << printer << std::endl; if(!task::init(alive, &ctl)) { std::cout << "Control Initialization failed." << std::endl; printErrors(std::cout, ctl.viewer.errors, ctl.errors); return 1; } if(!task::run(alive, &ctl)) { printErrors(std::cout, ctl.viewer.errors, ctl.errors); } glfwTerminate(); return 0; } <commit_msg>Removed references to missing cube.mtl<commit_after>#include <iostream> #include "main.hpp" #include "util.hpp" #include "system/printer.hpp" #ifndef OBJ_PATH #define OBJ_PATH "share/sphere.obj" #endif /*#ifndef MTL_PATH #define MTL_PATH "share/cube.mtl" #endif*/ #ifndef VERT_PATH #define VERT_PATH "share/fallback.vert" #endif #ifndef FRAG_PATH #define FRAG_PATH "share/shade.frag" #endif void printErrors(std::ostream &oss) {} template<typename T1, typename... TN> void printErrors(std::ostream &oss, T1 &t1, TN &... tn) { for(auto e : t1) { oss << e << std::endl; } printErrors(oss, tn...); } int main(int argc, const char **argv) { using namespace Util; using namespace System; if(glfwInit() == 0) { std::cout << "Failed to initialize GLFW " << glfwGetVersionString() << std::endl; return 1; } const char *obj_fname, *vert_fname, *frag_fname; if(argc >= 2) obj_fname = argv[1]; else obj_fname = OBJ_PATH; /*if(argc >= 3) mtl_fname = argv[2]; else mtl_fname = MTL_PATH;*/ if(argc >= 4) vert_fname = argv[2]; else vert_fname = VERT_PATH; if(argc >= 5) frag_fname = argv[3]; else frag_fname = FRAG_PATH; std::atomic_bool alive(true); Control::control ctl(alive, obj_fname); if(!alive) { std::cout << "Control construction failed." << std::endl; printErrors(std::cout, ctl.viewer.errors, ctl.errors); return 1; } if(!ctl.viewer.setProg(alive, vert_fname, frag_fname)) { std::cout << "Failed to compile or link shaders." << std::endl; printErrors(std::cout, ctl.viewer.errors, ctl.errors); return 1; } using namespace System; Printer<5> printer; std::string cols[]{"GLFW", "OpenGL", "Path"}, rows[]{"", "Major", "Minor", "Revision", "", "", "Wavefront obj", /*"Wavefront mtl",*/ "Vertex shader", "Fragment shader", ""}, paths[]{obj_fname,/* mtl_fname,*/ vert_fname, frag_fname}; int versions[6]{0}; glfwGetVersion(&versions[0], &versions[2], &versions[4]); glGetIntegerv(GL_MAJOR_VERSION, &versions[1]); glGetIntegerv(GL_MINOR_VERSION, &versions[3]); printer.push(&rows[5], &rows[5]+5) .level().insert(0, " ").level() .push<std::string, 3, 1, 31>(paths, &cols[2], &cols[3]+1) .level().insert(0, " ").level() .push(&rows[0], &rows[5]) .level().insert(0, " ").level() .push<int, 3, 2>(versions, &cols[0], &cols[2]); std::cout << printer << std::endl; if(!task::init(alive, &ctl)) { std::cout << "Control Initialization failed." << std::endl; printErrors(std::cout, ctl.viewer.errors, ctl.errors); return 1; } if(!task::run(alive, &ctl)) { printErrors(std::cout, ctl.viewer.errors, ctl.errors); } glfwTerminate(); return 0; } <|endoftext|>
<commit_before>#include <memory> #include <iostream> #include <string> #include <sstream> #include <functional> #include <utility> #include <unordered_map> #include <vector> #include <nan.h> #include <v8.h> #include <uv.h> #include "log.h" #include "queue.h" #include "worker/worker_thread.h" using v8::Local; using v8::Value; using v8::Object; using v8::String; using v8::Number; using v8::Function; using v8::FunctionTemplate; using v8::Array; using std::shared_ptr; using std::unique_ptr; using std::string; using std::ostringstream; using std::endl; using std::unordered_map; using std::vector; using std::move; using std::make_pair; static void handle_events_helper(uv_async_t *handle); class Main { public: Main() : worker_thread{&event_handler} { int err; next_command_id = 0; next_channel_id = NULL_CHANNEL_ID + 1; err = uv_async_init(uv_default_loop(), &event_handler, handle_events_helper); if (err) return; worker_thread.run(); } ChannelID send_worker_command( const CommandAction action, const std::string &&root, unique_ptr<Nan::Callback> callback, bool assign_channel_id = false ) { CommandID command_id = next_command_id; ChannelID channel_id = NULL_CHANNEL_ID; if (assign_channel_id) { channel_id = next_channel_id; next_channel_id++; } CommandPayload command_payload(next_command_id, action, move(root), channel_id); Message command_message(move(command_payload)); pending_callbacks.emplace(command_id, move(callback)); next_command_id++; LOGGER << "Sending command " << command_message << " to worker thread." << endl; worker_thread.send(move(command_message)); return channel_id; } void use_main_log_file(string &&main_log_file) { Logger::to_file(main_log_file.c_str()); } void use_worker_log_file(string &&worker_log_file, unique_ptr<Nan::Callback> callback) { send_worker_command(COMMAND_LOG_FILE, move(worker_log_file), move(callback)); } void watch(string &&root, unique_ptr<Nan::Callback> ack_callback, unique_ptr<Nan::Callback> event_callback) { string root_dup(root); ChannelID channel_id = send_worker_command(COMMAND_ADD, move(root), move(ack_callback), true); channel_callbacks.emplace(channel_id, move(event_callback)); LOGGER << "Worker is listening for changes at " << root_dup << " on channel " << channel_id << "." << endl; } void handle_events() { Nan::HandleScope scope; LOGGER << "Handling messages from the worker thread." << endl; unique_ptr<vector<Message>> accepted = worker_thread.receive_all(); if (!accepted) { LOGGER << "No messages waiting." << endl; return; } LOGGER << accepted->size() << " messages to process." << endl; unordered_map<ChannelID, vector<Local<Object>>> to_deliver; for (auto it = accepted->begin(); it != accepted->end(); ++it) { const AckPayload *ack_message = it->as_ack(); if (ack_message) { auto maybe_callback = pending_callbacks.find(ack_message->get_key()); if (maybe_callback == pending_callbacks.end()) { LOGGER << "Ignoring unexpected ack " << *it << endl; continue; } unique_ptr<Nan::Callback> callback = move(maybe_callback->second); pending_callbacks.erase(maybe_callback); callback->Call(0, nullptr); continue; } const FileSystemPayload *filesystem_message = it->as_filesystem(); if (filesystem_message) { LOGGER << "Received filesystem event message " << *it << endl; ChannelID channel_id = filesystem_message->get_channel_id(); Local<Object> js_event = Nan::New<Object>(); js_event->Set( Nan::New<String>("actionType").ToLocalChecked(), Nan::New<Number>(static_cast<int>(filesystem_message->get_filesystem_action())) ); js_event->Set( Nan::New<String>("entryKind").ToLocalChecked(), Nan::New<Number>(static_cast<int>(filesystem_message->get_entry_kind())) ); js_event->Set( Nan::New<String>("oldPath").ToLocalChecked(), Nan::New<String>(filesystem_message->get_old_path()).ToLocalChecked() ); js_event->Set( Nan::New<String>("newPath").ToLocalChecked(), Nan::New<String>(filesystem_message->get_new_path()).ToLocalChecked() ); to_deliver[channel_id].push_back(js_event); continue; } LOGGER << "Received unexpected message " << *it << endl; } for (auto it = to_deliver.begin(); it != to_deliver.end(); ++it) { ChannelID channel_id = it->first; vector<Local<Object>> js_events = it->second; auto maybe_callback = channel_callbacks.find(channel_id); if (maybe_callback == channel_callbacks.end()) { LOGGER << "Ignoring unexpected filesystem event channel " << channel_id << endl; continue; } shared_ptr<Nan::Callback> callback = maybe_callback->second; LOGGER << "Dispatching " << js_events.size() << " events on channel " << channel_id << "." << endl; Local<Array> js_array = Nan::New<Array>(js_events.size()); int index = 0; for (auto et = js_events.begin(); et != js_events.end(); ++et) { js_array->Set(index, *et); index++; } Local<Value> argv[] = { Nan::Null(), js_array }; callback->Call(2, argv); } } private: uv_async_t event_handler; WorkerThread worker_thread; CommandID next_command_id; ChannelID next_channel_id; unordered_map<CommandID, unique_ptr<Nan::Callback>> pending_callbacks; unordered_map<ChannelID, shared_ptr<Nan::Callback>> channel_callbacks; }; static Main instance; static void handle_events_helper(uv_async_t *handle) { instance.handle_events(); } static bool get_string_option(Local<Object>& options, const char *key_name, string &out) { Nan::HandleScope scope; const Local<String> key = Nan::New<String>(key_name).ToLocalChecked(); Nan::MaybeLocal<Value> as_maybe_value = Nan::Get(options, key); if (as_maybe_value.IsEmpty()) { return true; } Local<Value> as_value = as_maybe_value.ToLocalChecked(); if (as_value->IsUndefined()) { return true; } if (!as_value->IsString()) { ostringstream message; message << "configure() option " << key_name << " must be a String"; Nan::ThrowError(message.str().c_str()); return false; } Nan::Utf8String as_string(as_value); if (*as_string == nullptr) { ostringstream message; message << "configure() option " << key_name << " must be a valid UTF-8 String"; Nan::ThrowError(message.str().c_str()); return false; } out.assign(*as_string, as_string.length()); return true; } void configure(const Nan::FunctionCallbackInfo<Value> &info) { string main_log_file; string worker_log_file; bool async = false; Nan::MaybeLocal<Object> maybe_options = Nan::To<Object>(info[0]); if (maybe_options.IsEmpty()) { Nan::ThrowError("configure() requires an option object"); return; } Local<Object> options = maybe_options.ToLocalChecked(); if (!get_string_option(options, "mainLogFile", main_log_file)) return; if (!get_string_option(options, "workerLogFile", worker_log_file)) return; unique_ptr<Nan::Callback> callback(new Nan::Callback(info[1].As<Function>())); if (!main_log_file.empty()) { instance.use_main_log_file(move(main_log_file)); } if (!worker_log_file.empty()) { instance.use_worker_log_file(move(worker_log_file), move(callback)); async = true; } if (!async) { callback->Call(0, 0); } } void watch(const Nan::FunctionCallbackInfo<Value> &info) { if (info.Length() != 3) { return Nan::ThrowError("watch() requires three arguments"); } Nan::MaybeLocal<String> maybe_root = Nan::To<String>(info[0]); if (maybe_root.IsEmpty()) { Nan::ThrowError("watch() requires a string as argument one"); return; } Local<String> root_v8_string = maybe_root.ToLocalChecked(); Nan::Utf8String root_utf8(root_v8_string); if (*root_utf8 == nullptr) { Nan::ThrowError("watch() argument one must be a valid UTF-8 string"); return; } string root_str(*root_utf8, root_utf8.length()); unique_ptr<Nan::Callback> ack_callback(new Nan::Callback(info[1].As<Function>())); unique_ptr<Nan::Callback> event_callback(new Nan::Callback(info[2].As<Function>())); instance.watch(move(root_str), move(ack_callback), move(event_callback)); } void unwatch(const Nan::FunctionCallbackInfo<Value> &info) { if (info.Length() != 2) { return Nan::ThrowError("watch() requires two arguments"); } } void initialize(Local<Object> exports) { exports->Set( Nan::New<String>("configure").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(configure)).ToLocalChecked() ); exports->Set( Nan::New<String>("watch").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(watch)).ToLocalChecked() ); exports->Set( Nan::New<String>("unwatch").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(unwatch)).ToLocalChecked() ); } NODE_MODULE(sfw, initialize); <commit_msg>Stub unwatch function<commit_after>#include <memory> #include <iostream> #include <string> #include <sstream> #include <functional> #include <utility> #include <unordered_map> #include <vector> #include <nan.h> #include <v8.h> #include <uv.h> #include "log.h" #include "queue.h" #include "worker/worker_thread.h" using v8::Local; using v8::Value; using v8::Object; using v8::String; using v8::Number; using v8::Function; using v8::FunctionTemplate; using v8::Array; using std::shared_ptr; using std::unique_ptr; using std::string; using std::ostringstream; using std::endl; using std::unordered_map; using std::vector; using std::move; using std::make_pair; static void handle_events_helper(uv_async_t *handle); class Main { public: Main() : worker_thread{&event_handler} { int err; next_command_id = 0; next_channel_id = NULL_CHANNEL_ID + 1; err = uv_async_init(uv_default_loop(), &event_handler, handle_events_helper); if (err) return; worker_thread.run(); } ChannelID send_worker_command( const CommandAction action, const std::string &&root, unique_ptr<Nan::Callback> callback, bool assign_channel_id = false ) { CommandID command_id = next_command_id; ChannelID channel_id = NULL_CHANNEL_ID; if (assign_channel_id) { channel_id = next_channel_id; next_channel_id++; } CommandPayload command_payload(next_command_id, action, move(root), channel_id); Message command_message(move(command_payload)); pending_callbacks.emplace(command_id, move(callback)); next_command_id++; LOGGER << "Sending command " << command_message << " to worker thread." << endl; worker_thread.send(move(command_message)); return channel_id; } void use_main_log_file(string &&main_log_file) { Logger::to_file(main_log_file.c_str()); } void use_worker_log_file(string &&worker_log_file, unique_ptr<Nan::Callback> callback) { send_worker_command(COMMAND_LOG_FILE, move(worker_log_file), move(callback)); } void watch(string &&root, unique_ptr<Nan::Callback> ack_callback, unique_ptr<Nan::Callback> event_callback) { string root_dup(root); ChannelID channel_id = send_worker_command(COMMAND_ADD, move(root), move(ack_callback), true); channel_callbacks.emplace(channel_id, move(event_callback)); LOGGER << "Worker is listening for changes at " << root_dup << " on channel " << channel_id << "." << endl; } void handle_events() { Nan::HandleScope scope; LOGGER << "Handling messages from the worker thread." << endl; unique_ptr<vector<Message>> accepted = worker_thread.receive_all(); if (!accepted) { LOGGER << "No messages waiting." << endl; return; } LOGGER << accepted->size() << " messages to process." << endl; unordered_map<ChannelID, vector<Local<Object>>> to_deliver; for (auto it = accepted->begin(); it != accepted->end(); ++it) { const AckPayload *ack_message = it->as_ack(); if (ack_message) { auto maybe_callback = pending_callbacks.find(ack_message->get_key()); if (maybe_callback == pending_callbacks.end()) { LOGGER << "Ignoring unexpected ack " << *it << endl; continue; } unique_ptr<Nan::Callback> callback = move(maybe_callback->second); pending_callbacks.erase(maybe_callback); callback->Call(0, nullptr); continue; } const FileSystemPayload *filesystem_message = it->as_filesystem(); if (filesystem_message) { LOGGER << "Received filesystem event message " << *it << endl; ChannelID channel_id = filesystem_message->get_channel_id(); Local<Object> js_event = Nan::New<Object>(); js_event->Set( Nan::New<String>("actionType").ToLocalChecked(), Nan::New<Number>(static_cast<int>(filesystem_message->get_filesystem_action())) ); js_event->Set( Nan::New<String>("entryKind").ToLocalChecked(), Nan::New<Number>(static_cast<int>(filesystem_message->get_entry_kind())) ); js_event->Set( Nan::New<String>("oldPath").ToLocalChecked(), Nan::New<String>(filesystem_message->get_old_path()).ToLocalChecked() ); js_event->Set( Nan::New<String>("newPath").ToLocalChecked(), Nan::New<String>(filesystem_message->get_new_path()).ToLocalChecked() ); to_deliver[channel_id].push_back(js_event); continue; } LOGGER << "Received unexpected message " << *it << endl; } for (auto it = to_deliver.begin(); it != to_deliver.end(); ++it) { ChannelID channel_id = it->first; vector<Local<Object>> js_events = it->second; auto maybe_callback = channel_callbacks.find(channel_id); if (maybe_callback == channel_callbacks.end()) { LOGGER << "Ignoring unexpected filesystem event channel " << channel_id << endl; continue; } shared_ptr<Nan::Callback> callback = maybe_callback->second; LOGGER << "Dispatching " << js_events.size() << " events on channel " << channel_id << "." << endl; Local<Array> js_array = Nan::New<Array>(js_events.size()); int index = 0; for (auto et = js_events.begin(); et != js_events.end(); ++et) { js_array->Set(index, *et); index++; } Local<Value> argv[] = { Nan::Null(), js_array }; callback->Call(2, argv); } } private: uv_async_t event_handler; WorkerThread worker_thread; CommandID next_command_id; ChannelID next_channel_id; unordered_map<CommandID, unique_ptr<Nan::Callback>> pending_callbacks; unordered_map<ChannelID, shared_ptr<Nan::Callback>> channel_callbacks; }; static Main instance; static void handle_events_helper(uv_async_t *handle) { instance.handle_events(); } static bool get_string_option(Local<Object>& options, const char *key_name, string &out) { Nan::HandleScope scope; const Local<String> key = Nan::New<String>(key_name).ToLocalChecked(); Nan::MaybeLocal<Value> as_maybe_value = Nan::Get(options, key); if (as_maybe_value.IsEmpty()) { return true; } Local<Value> as_value = as_maybe_value.ToLocalChecked(); if (as_value->IsUndefined()) { return true; } if (!as_value->IsString()) { ostringstream message; message << "configure() option " << key_name << " must be a String"; Nan::ThrowError(message.str().c_str()); return false; } Nan::Utf8String as_string(as_value); if (*as_string == nullptr) { ostringstream message; message << "configure() option " << key_name << " must be a valid UTF-8 String"; Nan::ThrowError(message.str().c_str()); return false; } out.assign(*as_string, as_string.length()); return true; } void configure(const Nan::FunctionCallbackInfo<Value> &info) { string main_log_file; string worker_log_file; bool async = false; Nan::MaybeLocal<Object> maybe_options = Nan::To<Object>(info[0]); if (maybe_options.IsEmpty()) { Nan::ThrowError("configure() requires an option object"); return; } Local<Object> options = maybe_options.ToLocalChecked(); if (!get_string_option(options, "mainLogFile", main_log_file)) return; if (!get_string_option(options, "workerLogFile", worker_log_file)) return; unique_ptr<Nan::Callback> callback(new Nan::Callback(info[1].As<Function>())); if (!main_log_file.empty()) { instance.use_main_log_file(move(main_log_file)); } if (!worker_log_file.empty()) { instance.use_worker_log_file(move(worker_log_file), move(callback)); async = true; } if (!async) { callback->Call(0, 0); } } void watch(const Nan::FunctionCallbackInfo<Value> &info) { if (info.Length() != 3) { return Nan::ThrowError("watch() requires three arguments"); } Nan::MaybeLocal<String> maybe_root = Nan::To<String>(info[0]); if (maybe_root.IsEmpty()) { Nan::ThrowError("watch() requires a string as argument one"); return; } Local<String> root_v8_string = maybe_root.ToLocalChecked(); Nan::Utf8String root_utf8(root_v8_string); if (*root_utf8 == nullptr) { Nan::ThrowError("watch() argument one must be a valid UTF-8 string"); return; } string root_str(*root_utf8, root_utf8.length()); unique_ptr<Nan::Callback> ack_callback(new Nan::Callback(info[1].As<Function>())); unique_ptr<Nan::Callback> event_callback(new Nan::Callback(info[2].As<Function>())); instance.watch(move(root_str), move(ack_callback), move(event_callback)); } void unwatch(const Nan::FunctionCallbackInfo<Value> &info) { if (info.Length() != 2) { return Nan::ThrowError("watch() requires two arguments"); } unique_ptr<Nan::Callback> ack_callback(new Nan::Callback(info[1].As<Function>())); ack_callback->Call(0, nullptr); } void initialize(Local<Object> exports) { exports->Set( Nan::New<String>("configure").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(configure)).ToLocalChecked() ); exports->Set( Nan::New<String>("watch").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(watch)).ToLocalChecked() ); exports->Set( Nan::New<String>("unwatch").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(unwatch)).ToLocalChecked() ); } NODE_MODULE(sfw, initialize); <|endoftext|>
<commit_before>#include "common.h" #include <boost/program_options/cmdline.hpp> #include <boost/program_options/options_description.hpp> #include <boost/program_options/parsers.hpp> #include <boost/program_options/variables_map.hpp> #include "hex/generate.h" #include "hex/ai/ai.h" #include "hex/ai/ai_updater.h" #include "hex/audio/audio.h" #include "hex/basics/error.h" #include "hex/chat/chat.h" #include "hex/game/game.h" #include "hex/game/game_arbiter.h" #include "hex/game/game_messages.h" #include "hex/game/game_updater.h" #include "hex/game/game_writer.h" #include "hex/graphics/graphics.h" #include "hex/messaging/event_pusher.h" #include "hex/messaging/writer.h" #include "hex/networking/networking.h" #include "hex/view/level_renderer.h" #include "hex/view/level_window.h" #include "hex/view/map_window.h" #include "hex/view/message_window.h" #include "hex/view/stack_window.h" #include "hex/view/status_window.h" #include "hex/view/player.h" #include "hex/view/view.h" #include "hex/view/view_updater.h" struct Options { bool server_mode; bool client_mode; std::string host_name; std::string host_addr; }; void load_resources(Resources *resources, Graphics *graphics) { ImageLoader image_loader(resources, graphics); ResourceLoader loader(resources, &image_loader); loader.load(std::string("data/resources.txt")); resources->resolve_references(); } void save_game(const std::string& filename, Game *game) { std::ofstream f(filename.c_str()); MessageWriter message_writer(f); GameWriter game_writer(&message_writer); game_writer.write(game); } class BackgroundWindow: public UiWindow { public: BackgroundWindow(UiLoop *loop, Options *options, Game *game, GameView *game_view, Ai *independent_ai, EventPusher *event_pusher, GameArbiter *arbiter, Updater *updater, LevelRenderer *level_renderer): UiWindow(0, 0, 0, 0), loop(loop), options(options), game(game), game_view(game_view), independent_ai(independent_ai), event_pusher(event_pusher), arbiter(arbiter), updater(updater), level_renderer(level_renderer) { } bool receive_event(SDL_Event *evt) { if (evt->type == SDL_QUIT || (evt->type == SDL_KEYDOWN && evt->key.keysym.sym == SDLK_ESCAPE)) { loop->running = false; return true; } else if (evt->type == event_pusher->event_type) { boost::shared_ptr<Message> msg = event_pusher->get_message(*evt); if (options->server_mode) { arbiter->receive(msg); } else if (options->client_mode) { updater->receive(msg); } return true; } if (evt->type == SDL_KEYDOWN && evt->key.keysym.sym == SDLK_F2) { save_game("save.txt", game); return true; } else if (evt->type == SDL_KEYDOWN && evt->key.keysym.sym == SDLK_F5) { game_view->debug_mode = !game_view->debug_mode; level_renderer->show_hexagons = game_view->debug_mode; return true; } if (evt->type == SDL_KEYDOWN && evt->key.keysym.sym == SDLK_F12) { game_view->mark_ready(); } return false; } bool contains(int px, int py) { return true; } void draw() { game_view->update(); independent_ai->update(); } private: UiLoop *loop; Options *options; Game *game; GameView *game_view; Ai *independent_ai; EventPusher *event_pusher; GameArbiter *arbiter; Updater *updater; LevelRenderer *level_renderer; }; class TopWindow: public UiWindow { public: TopWindow(Graphics *graphics, Audio *audio): UiWindow(0, 0, 0, 0), graphics(graphics), audio(audio) { } void draw() { graphics->update(); audio->update(); } private: Graphics *graphics; Audio *audio; }; void run(Options& options) { Graphics graphics; graphics.start(); Resources resources; load_resources(&resources, &graphics); EventPusher event_pusher; Server server(9999, &event_pusher); Client client(&event_pusher); Player player(0, std::string("player")); Game game; Updater updater(1000); GameArbiter arbiter(&game, &updater); Updater dispatcher(1000); GameUpdater game_updater(&game); updater.subscribe(&game_updater); GameView game_view(&game, &player, &resources, &dispatcher); ViewUpdater view_updater(&game, &game_view, &resources); updater.subscribe(&view_updater); Ai independent_ai(&game, std::string("independent"), &dispatcher); AiUpdater independent_ai_updater(&independent_ai); if (options.server_mode) { server.start(); updater.subscribe(&server); } if (options.client_mode) { client.connect(options.host_addr); dispatcher.subscribe(&client); } else { dispatcher.subscribe(&arbiter); updater.subscribe(&independent_ai_updater); create_game(game, updater); } int sidebar_width = StackWindow::window_width; int sidebar_position = graphics.width - sidebar_width; int map_window_height = 200; int stack_window_height = StackWindow::window_height; int status_window_height = StatusWindow::window_height; int message_window_height = graphics.height - map_window_height - stack_window_height - status_window_height; LevelRenderer level_renderer(&graphics, &resources, &game.level, &game_view); LevelWindow level_window(graphics.width - sidebar_width, graphics.height - StatusWindow::window_height, &game_view, &level_renderer, &resources); ChatWindow chat_window(200, graphics.height, &resources, &graphics, &dispatcher); ChatUpdater chat_updater(&chat_window); updater.subscribe(&chat_updater); MapWindow map_window(sidebar_position, 0, sidebar_width, map_window_height, &game_view, &level_window, &graphics, &resources); StackWindow stack_window(sidebar_position, 200, sidebar_width, StackWindow::window_height, &resources, &graphics, &game_view, &level_renderer); MessageWindow message_window(sidebar_position, map_window_height + stack_window_height, sidebar_width, message_window_height, &resources, &graphics, &game_view); StatusWindow status_window(0, level_window.height, graphics.width, status_window_height, &resources, &graphics, &game_view); Audio audio(&resources); audio.start(); UiLoop loop(25); BackgroundWindow bw(&loop, &options, &game, &game_view, &independent_ai, &event_pusher, &arbiter, &updater, &level_renderer); loop.add_window(&bw); loop.add_window(&level_window); loop.add_window(&map_window); loop.add_window(&stack_window); loop.add_window(&message_window); loop.add_window(&status_window); loop.add_window(&chat_window); TopWindow tw(&graphics, &audio); loop.add_window(&tw); loop.run(); server.stop(); client.disconnect(); audio.stop(); graphics.stop(); } bool parse_options(int argc, char *argv[], Options& options) { namespace po = boost::program_options; po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("server", "run in server mode") ("connect", po::value<std::string>(), "connect to server") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { std::cout << desc << "\n"; return false; } if (vm.count("server")) { options.server_mode = true; } else { options.server_mode = false; } if (vm.count("connect")) { options.client_mode = true; options.host_addr = vm["connect"].as<std::string>(); } else { options.client_mode = false; } return true; } int main(int argc, char *argv[]) { try { Options options; if (parse_options(argc, argv, options)) run(options); } catch (Error &ex) { BOOST_LOG_TRIVIAL(fatal) << "Failed with: " << ex.what(); } return 0; } <commit_msg>Don't try to update the Ai when running in client mode.<commit_after>#include "common.h" #include <boost/program_options/cmdline.hpp> #include <boost/program_options/options_description.hpp> #include <boost/program_options/parsers.hpp> #include <boost/program_options/variables_map.hpp> #include "hex/generate.h" #include "hex/ai/ai.h" #include "hex/ai/ai_updater.h" #include "hex/audio/audio.h" #include "hex/basics/error.h" #include "hex/chat/chat.h" #include "hex/game/game.h" #include "hex/game/game_arbiter.h" #include "hex/game/game_messages.h" #include "hex/game/game_updater.h" #include "hex/game/game_writer.h" #include "hex/graphics/graphics.h" #include "hex/messaging/event_pusher.h" #include "hex/messaging/writer.h" #include "hex/networking/networking.h" #include "hex/view/level_renderer.h" #include "hex/view/level_window.h" #include "hex/view/map_window.h" #include "hex/view/message_window.h" #include "hex/view/stack_window.h" #include "hex/view/status_window.h" #include "hex/view/player.h" #include "hex/view/view.h" #include "hex/view/view_updater.h" struct Options { bool server_mode; bool client_mode; std::string host_name; std::string host_addr; }; void load_resources(Resources *resources, Graphics *graphics) { ImageLoader image_loader(resources, graphics); ResourceLoader loader(resources, &image_loader); loader.load(std::string("data/resources.txt")); resources->resolve_references(); } void save_game(const std::string& filename, Game *game) { std::ofstream f(filename.c_str()); MessageWriter message_writer(f); GameWriter game_writer(&message_writer); game_writer.write(game); } class BackgroundWindow: public UiWindow { public: BackgroundWindow(UiLoop *loop, Options *options, Game *game, GameView *game_view, std::vector<Ai *> ais, EventPusher *event_pusher, GameArbiter *arbiter, Updater *updater, LevelRenderer *level_renderer): UiWindow(0, 0, 0, 0), loop(loop), options(options), game(game), game_view(game_view), ais(ais), event_pusher(event_pusher), arbiter(arbiter), updater(updater), level_renderer(level_renderer) { } bool receive_event(SDL_Event *evt) { if (evt->type == SDL_QUIT || (evt->type == SDL_KEYDOWN && evt->key.keysym.sym == SDLK_ESCAPE)) { loop->running = false; return true; } else if (evt->type == event_pusher->event_type) { boost::shared_ptr<Message> msg = event_pusher->get_message(*evt); if (options->server_mode) { arbiter->receive(msg); } else if (options->client_mode) { updater->receive(msg); } return true; } if (evt->type == SDL_KEYDOWN && evt->key.keysym.sym == SDLK_F2) { save_game("save.txt", game); return true; } else if (evt->type == SDL_KEYDOWN && evt->key.keysym.sym == SDLK_F5) { game_view->debug_mode = !game_view->debug_mode; level_renderer->show_hexagons = game_view->debug_mode; return true; } if (evt->type == SDL_KEYDOWN && evt->key.keysym.sym == SDLK_F12) { game_view->mark_ready(); } return false; } bool contains(int px, int py) { return true; } void draw() { game_view->update(); for (std::vector<Ai *>::iterator iter = ais.begin(); iter != ais.end(); iter++) { (*iter)->update(); } } private: UiLoop *loop; Options *options; Game *game; GameView *game_view; std::vector<Ai *> ais; EventPusher *event_pusher; GameArbiter *arbiter; Updater *updater; LevelRenderer *level_renderer; }; class TopWindow: public UiWindow { public: TopWindow(Graphics *graphics, Audio *audio): UiWindow(0, 0, 0, 0), graphics(graphics), audio(audio) { } void draw() { graphics->update(); audio->update(); } private: Graphics *graphics; Audio *audio; }; void run(Options& options) { Graphics graphics; graphics.start(); Resources resources; load_resources(&resources, &graphics); EventPusher event_pusher; Server server(9999, &event_pusher); Client client(&event_pusher); Player player(0, std::string("player")); Game game; Updater updater(1000); GameArbiter arbiter(&game, &updater); Updater dispatcher(1000); GameUpdater game_updater(&game); updater.subscribe(&game_updater); GameView game_view(&game, &player, &resources, &dispatcher); ViewUpdater view_updater(&game, &game_view, &resources); updater.subscribe(&view_updater); std::vector<Ai *> ais; if (options.server_mode) { server.start(); updater.subscribe(&server); } if (options.client_mode) { client.connect(options.host_addr); dispatcher.subscribe(&client); } else { Ai *independent_ai = new Ai(&game, std::string("independent"), &dispatcher); AiUpdater *independent_ai_updater = new AiUpdater(independent_ai); ais.push_back(independent_ai); dispatcher.subscribe(&arbiter); updater.subscribe(independent_ai_updater); create_game(game, updater); } int sidebar_width = StackWindow::window_width; int sidebar_position = graphics.width - sidebar_width; int map_window_height = 200; int stack_window_height = StackWindow::window_height; int status_window_height = StatusWindow::window_height; int message_window_height = graphics.height - map_window_height - stack_window_height - status_window_height; LevelRenderer level_renderer(&graphics, &resources, &game.level, &game_view); LevelWindow level_window(graphics.width - sidebar_width, graphics.height - StatusWindow::window_height, &game_view, &level_renderer, &resources); ChatWindow chat_window(200, graphics.height, &resources, &graphics, &dispatcher); ChatUpdater chat_updater(&chat_window); updater.subscribe(&chat_updater); MapWindow map_window(sidebar_position, 0, sidebar_width, map_window_height, &game_view, &level_window, &graphics, &resources); StackWindow stack_window(sidebar_position, 200, sidebar_width, StackWindow::window_height, &resources, &graphics, &game_view, &level_renderer); MessageWindow message_window(sidebar_position, map_window_height + stack_window_height, sidebar_width, message_window_height, &resources, &graphics, &game_view); StatusWindow status_window(0, level_window.height, graphics.width, status_window_height, &resources, &graphics, &game_view); Audio audio(&resources); audio.start(); UiLoop loop(25); BackgroundWindow bw(&loop, &options, &game, &game_view, ais, &event_pusher, &arbiter, &updater, &level_renderer); loop.add_window(&bw); loop.add_window(&level_window); loop.add_window(&map_window); loop.add_window(&stack_window); loop.add_window(&message_window); loop.add_window(&status_window); loop.add_window(&chat_window); TopWindow tw(&graphics, &audio); loop.add_window(&tw); loop.run(); server.stop(); client.disconnect(); audio.stop(); graphics.stop(); } bool parse_options(int argc, char *argv[], Options& options) { namespace po = boost::program_options; po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("server", "run in server mode") ("connect", po::value<std::string>(), "connect to server") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { std::cout << desc << "\n"; return false; } if (vm.count("server")) { options.server_mode = true; } else { options.server_mode = false; } if (vm.count("connect")) { options.client_mode = true; options.host_addr = vm["connect"].as<std::string>(); } else { options.client_mode = false; } return true; } int main(int argc, char *argv[]) { try { Options options; if (parse_options(argc, argv, options)) run(options); } catch (Error &ex) { BOOST_LOG_TRIVIAL(fatal) << "Failed with: " << ex.what(); } return 0; } <|endoftext|>
<commit_before>#include "parser.h" #include "tests/alltests.h" using namespace ical; int main() { return tests::AllTests::run(); } <commit_msg>Implemented CLI for the parser.<commit_after>#ifdef RUN_TESTS #include "tests/alltests.h" #else /* RUN_TESTS */ #include "parser.h" #include <memory> #include <iostream> #include <fstream> static void printUsage(const char *progname) { std::cerr << "Usage: " << progname << " [FILE]" << std::endl << std::endl << " Parses the given iCalendar file and outputs its contents." << std::endl << std::endl << "Arguments:" << std::endl << " FILE - the input file (stdin if not specified)" << std::endl; } #endif /* RUN_TESTS */ using namespace ical; int main(int argc, const char * const *argv) { #ifdef RUN_TESTS /* quench unused variable warnings: */ (void)argc; (void)argv; return tests::AllTests::run(); #else if (argc > 2) { std::cerr << "ERROR: Too many arguments!" << std::endl << std::endl; printUsage(argv[0]); return 2; } std::istream *in = &std::cin; std::ifstream file; if (argc == 2) { file.open(argv[1]); if (file.fail()) { std::cerr << "ERROR: Unable to open file!" << std::endl; return 2; } in = dynamic_cast<std::istream *>(&file); } std::vector<components::VCalendar> objects; try { in->exceptions(); objects = std::move(Parser::parseStream(*in)); } catch (ParserException &ex) { std::cerr << "ERROR: ParserException: " << ex.what() << std::endl; return 1; } catch (std::bad_alloc &) { std::cerr << "ERROR: Memory allocation failed!" << std::endl; return 2; } catch (std::ios::failure &ex) { std::cerr << "ERROR: I/O error: " << ex.what() << std::endl; return 2; } catch (std::exception &ex) { std::cerr << "ERROR: Unknown exception: " << ex.what() << std::endl; return 2; } try { std::cout.exceptions(); for (auto &obj : objects) { obj.print(std::cout); } } catch (std::ios::failure &ex) { std::cerr << "ERROR: I/O error: " << ex.what() << std::endl; return 2; } catch (std::exception &ex) { std::cerr << "ERROR: Unknown exception: " << ex.what() << std::endl; return 2; } return 0; #endif } <|endoftext|>
<commit_before>#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "mySocket.h" #include "error.h" #include "sdrplay.h" #define SERVER_VERSION "1.0.1" struct sdr_info { char magic[4]; int32_t tuner_type; int32_t tuner_gain_count; } __attribute__((packed)); struct sdr_command { int8_t cmd; int32_t param; } __attribute__((packed)); #define RTLSDR_TUNER_R820T 5 // We don't actually use the R820T gain list.. for a start they go up to 1/10db and we don't support that, // but ours go in the other direction too (they're more losses than gains.. the docs really don't explain why). const int gain_list[] = { 84, 81, 78, 75, 72, 69, 66, 63, 60, 57, 54, 51, 48, 45, 42, 39, 36, 33, 30, 27, 24, 21, 18, 15, 12, 9, 6, 3, 0 }; class sdrServer : socketEvent { private: bool mDebug; bool mIpv4, mIpv6; int mPort; mir_sdr_Bw_MHzT mBandwidth; short *mI, *mQ; uint8_t *mS; double mFrequency, mSampleRate; int mGain; double mOldFrequency, mOldSampleRate; int mOldGain; bool mFrequencyChanged, mSamplerateChanged, mGainChanged; bool mAgc; mySocket mSocket; SDRPlay mSdrPlay; uint8_t mPartialCommand[sizeof(sdr_command)]; uint8_t *mPartialCommandPtr; void processSdrCommand(sdr_command *sdrcmd); double intToDouble(int freq); int classifyFrequency(double frequency); void updateFrequency(); void updateSampleRate(); void updateGain(); void reinit(); public: sdrServer(int frequency, int port, int samplerate, bool ipv4, bool ipv6, bool debug); virtual ~sdrServer(); int run(); virtual bool clientConnected(mySocket *socket); virtual void clientDisconnected(mySocket *socket); virtual void packetReceived(mySocket *socket, const void *packet, ssize_t packetLen, sockaddr *, socklen_t); virtual bool needPacket(mySocket *socket); }; void usage() { printf("SDRPlay tcp server version "SERVER_VERSION"\n"); printf("usage: sdrplay [-f frequency][-p port][-s samplerate][-4][-6][-d][-v][-g]\n"); } int main(int argc, char **argv) { int c; int frequency = 14200000; int port = 1234; int samplerate = 2048000; bool ipv4 = true; bool ipv6 = true; bool debug = false; bool foreground = false; while((c = getopt(argc, argv, "f:p:s:46dvg")) > 0) switch(c) { case 'f': frequency = atoi(optarg); break; case 'p': port = atoi(optarg); break; case 's': samplerate = atoi(optarg); break; case '4': ipv6 = false; break; case '6': ipv4 = false; break; case 'd': debug = true; foreground = true; break; case 'g': foreground = true; break; case 'v': printf("SRPplay tcp server version "SERVER_VERSION"\n"); return 0; default: usage(); return -1; } if(!foreground) daemon(0,0); sdrServer server(frequency, port, samplerate, ipv4, ipv6, debug); for(;;) { server.run(); sleep(1000); } } /* sdrServer */ sdrServer::sdrServer(int frequency, int port, int samplerate, bool ipv4, bool ipv6, bool debug) { mFrequency = intToDouble(frequency); mSampleRate = intToDouble(samplerate); mGain = 70; mPort = port; mIpv4 = ipv4; mIpv6 = ipv6; mDebug = debug; mPartialCommandPtr = mPartialCommand; mI = NULL; mQ = NULL; mS = NULL; mBandwidth = mir_sdr_BW_1_536; try { mSocket.init(this, true); } catch(error *e) { fprintf(stderr,"%s\n", e->text()); exit(-1); } } sdrServer::~sdrServer() { delete[] mI; delete[] mQ; delete[] mS; } int sdrServer::run() { try { mSdrPlay.init(mGain, mSampleRate, mFrequency, mBandwidth, mir_sdr_IF_Zero); mSdrPlay.setDCMode(dcmOneShot, false); mSdrPlay.setDCTrackTime(63); mI = new short[mSdrPlay.getSamplesPerPacket()]; mQ = new short[mSdrPlay.getSamplesPerPacket()]; mS = new uint8_t[mSdrPlay.getSamplesPerPacket() * 2]; if(mDebug) printf("SDR server listening on port %d\n", mPort); mSocket.bind(mPort, mIpv4, mIpv6); mSocket.listen(); } catch(error *e) { fprintf(stderr,"%s\n", e->text()); exit(-1); } return 0; } bool sdrServer::clientConnected(mySocket *socket) { /* We pretend to be and R820 as that seems to be the one with the most settings. The protocol * doesn't allow for arbitrary devices */ sdr_info info = { {'R', 'T', 'L', '0' } }; info.tuner_type = htonl(RTLSDR_TUNER_R820T); info.tuner_gain_count = htonl(sizeof(gain_list)/sizeof(gain_list[0])); if(mDebug) printf("Connection made from %s\n", socket->endpointAddress()); if(socket->send(&info, sizeof(info)) <= 0) { if(mDebug) printf("Sending initial packet failed\n"); return false; } return true; } void sdrServer::clientDisconnected(mySocket *socket) { if(mDebug) printf("Connection lost from %s\n", socket->endpointAddress()); } void sdrServer::packetReceived(mySocket *socket, const void *packet, ssize_t packetLen, sockaddr *, socklen_t) { sdr_command *s; if(mDebug) printf("Received %d byte packet from %s\n", (int)packetLen, socket->endpointAddress()); if(mPartialCommandPtr > mPartialCommand) { ssize_t l = mPartialCommandPtr - mPartialCommand; ssize_t r = sizeof(sdr_command) - l; if(packetLen >= r) { memcpy(mPartialCommandPtr, packet, (size_t)r); packetLen -= r; packet = ((uint8_t *)packet) + r; processSdrCommand((sdr_command *)mPartialCommand); mPartialCommandPtr = mPartialCommand; } else { memcpy(mPartialCommandPtr, packet, (size_t)packetLen); mPartialCommandPtr += (size_t)packetLen; return; } } s = (sdr_command *)packet; while((size_t)packetLen >= sizeof(sdr_command)) { processSdrCommand(s++); packetLen -= sizeof(sdr_command); } if(packetLen != 0) { memcpy(mPartialCommand, s, (size_t)packetLen); mPartialCommandPtr = mPartialCommand + packetLen; } } bool sdrServer::needPacket(mySocket *socket) { short *i, *q; uint8_t *s; int count = mSdrPlay.getSamplesPerPacket(); bool grChanged, rfChanged, fsChanged; try { if(mGainChanged) updateGain(); if(mSamplerateChanged) updateSampleRate(); if(mFrequencyChanged) updateFrequency(); if(mSdrPlay.readPacket(mI, mQ, &grChanged, &rfChanged, &fsChanged) == 0) { for(i=mI, q=mQ, s=mS; i<mI+count; i++, q++) { *(s++) = (uint8_t)((*i>>8)+128); *(s++) = (uint8_t)((*q>>8)+128); } socket->send(mS, (size_t) count * 2); } } catch(error *e) { printf("%s\n", e->text()); return false; } return true; } void sdrServer::processSdrCommand(sdr_command *sdrcmd) { int cmd = sdrcmd->cmd; int arg = htonl(sdrcmd->param); switch(cmd) { case 1: // Set Frequency mOldFrequency = mFrequency; mFrequency = intToDouble(arg); if(mDebug) printf("Set frequency in Mhz to %f\n", mFrequency); mFrequencyChanged = true; break; case 2: // Set Sample Rate mOldSampleRate = mSampleRate; mSampleRate = intToDouble(arg); if(mDebug) printf("Set sample rate in Hz to %f\n", mSampleRate); mSamplerateChanged = true; break; case 3: // Set Gain Mode if(mDebug) printf("Set gain mode to %d\n", arg); break; case 4: // Set Tuner Gain mOldGain = mGain; mGain = arg; if(mDebug) printf("Set tuner gain to %d\n", mGain); mGainChanged = true; break; case 5: // Set Freq Correction if(mDebug) printf("Set frequency correction %f\n", intToDouble(arg)); break; case 6: // Set IF Gain if(mDebug) printf("Set if gain to %d\n", arg); break; case 7: // Set test mode if(mDebug) printf("Set test mode to %d\n", arg); break; case 8: // Set AGC mode if(mDebug) printf("Set agc mode to %d\n", arg); mAgc = arg != 0; break; case 9: // Set direct sampling // Sample directly off IF or tuner if(mDebug) printf("Set direct sampling to %d\n", arg); break; case 10: // Set offset tuning // Essentially whether to use IF stage or not if(mDebug) printf("Set offset tuning to %d\n", arg); break; case 11: // Set rtl xtal if(mDebug) printf("Set rtl xtal to %d\n", arg); break; case 12: // Set tuner xtal if(mDebug) printf("Set tuner xtal to %d\n", arg); break; case 13: // Set gain by index if(mDebug) printf("Set gain to index %d\n", arg); if(arg<0 || arg>(int)(sizeof(gain_list)/sizeof(gain_list[0]))) break; mGain = gain_list[arg]; if(mDebug) printf(" %d\n", mGain); mGainChanged = true; break; default: if(mDebug) printf("Unknown Cmd = %d, arg = %d\n", cmd, arg ); break; } } double sdrServer::intToDouble(int freq) { return double(freq) / 1000000.0; } int sdrServer::classifyFrequency(double frequency) { if(frequency < 0.1 || frequency > 2000) return -1; // Out of spec if(frequency < 60) return 1; // 100Khz - 60Mhz if(frequency < 120) return 2; // 60Mhz - 120Mhz if(frequency < 245) return 3; // 120Mhz - 245Mhz if(frequency < 380) return 4; // 245Mhz - 380Mhz if(frequency < 430) return -1; // 380Mhz - 430Mhz unsupported if(frequency < 1000) return 5; // 430Mhz - 1Ghz return 6; // 1Ghz - 2Ghz; } void sdrServer::updateFrequency() { int oldFrequencyClass, newFrequencyClass; oldFrequencyClass = classifyFrequency(mOldFrequency); newFrequencyClass = classifyFrequency(mFrequency); if(newFrequencyClass == -1) { if(mDebug) printf("Out of spec"); return; } if(mDebug) printf("New frequency class is %d\n", newFrequencyClass); if(oldFrequencyClass!=newFrequencyClass) { reinit(); } else { mFrequencyChanged = false; mSdrPlay.setRF((mFrequency - mOldFrequency) * 1000, false, false); // mSdrPlay.setRF(mFrequency * 1000, true, false); } } void sdrServer::updateSampleRate() { double diff; if(mSampleRate < (((int)mBandwidth)/1000.0)) { if(mSampleRate >= 1.536) mBandwidth = mir_sdr_BW_1_536; else if(mSampleRate >= 0.6) mBandwidth = mir_sdr_BW_0_600; else if(mSampleRate >= 0.3) mBandwidth = mir_sdr_BW_0_300; else if(mSampleRate >= 0.2) mBandwidth = mir_sdr_BW_0_200; else { if(mDebug) printf("Sample rate below 200 not supported\n"); mBandwidth = mir_sdr_BW_1_536; mSampleRate = 2.048; } reinit(); } else if(mSampleRate > 1.536 && (int)mBandwidth < 1536) { mBandwidth = mir_sdr_BW_1_536; reinit(); } else { diff = fabs(mSampleRate - mOldSampleRate); // in Hz // From the docs, changes over >1000 need a reinit (so we use +/-500). if(diff > 500) { reinit(); } else mSamplerateChanged = false; mSdrPlay.setFS(mSampleRate, true, false, false); } } void sdrServer::updateGain() { mGainChanged = false; mSdrPlay.setGR(mGain, true, false); } void sdrServer::reinit() { mFrequencyChanged = false; mSamplerateChanged = false; mGainChanged = false; mSdrPlay.uninit(); mSdrPlay.init(mGain, mSampleRate, mFrequency, mBandwidth, mir_sdr_IF_Zero); } <commit_msg>Back to absolute settings, as relative seem odd too. Sigh.<commit_after>#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "mySocket.h" #include "error.h" #include "sdrplay.h" #define SERVER_VERSION "1.0.1" struct sdr_info { char magic[4]; int32_t tuner_type; int32_t tuner_gain_count; } __attribute__((packed)); struct sdr_command { int8_t cmd; int32_t param; } __attribute__((packed)); #define RTLSDR_TUNER_R820T 5 // We don't actually use the R820T gain list.. for a start they go up to 1/10db and we don't support that, // but ours go in the other direction too (they're more losses than gains.. the docs really don't explain why). const int gain_list[] = { 84, 81, 78, 75, 72, 69, 66, 63, 60, 57, 54, 51, 48, 45, 42, 39, 36, 33, 30, 27, 24, 21, 18, 15, 12, 9, 6, 3, 0 }; class sdrServer : socketEvent { private: bool mDebug; bool mIpv4, mIpv6; int mPort; mir_sdr_Bw_MHzT mBandwidth; short *mI, *mQ; uint8_t *mS; double mFrequency, mSampleRate; int mGain; double mOldFrequency, mOldSampleRate; int mOldGain; bool mFrequencyChanged, mSamplerateChanged, mGainChanged; bool mAgc; mySocket mSocket; SDRPlay mSdrPlay; uint8_t mPartialCommand[sizeof(sdr_command)]; uint8_t *mPartialCommandPtr; void processSdrCommand(sdr_command *sdrcmd); double intToDouble(int freq); int classifyFrequency(double frequency); void updateFrequency(); void updateSampleRate(); void updateGain(); void reinit(); void init(); public: sdrServer(int frequency, int port, int samplerate, bool ipv4, bool ipv6, bool debug); virtual ~sdrServer(); int run(); virtual bool clientConnected(mySocket *socket); virtual void clientDisconnected(mySocket *socket); virtual void packetReceived(mySocket *socket, const void *packet, ssize_t packetLen, sockaddr *, socklen_t); virtual bool needPacket(mySocket *socket); }; void usage() { printf("SDRPlay tcp server version "SERVER_VERSION"\n"); printf("usage: sdrplay [-f frequency][-p port][-s samplerate][-4][-6][-d][-v][-g]\n"); } int main(int argc, char **argv) { int c; int frequency = 14200000; int port = 1234; int samplerate = 2048000; bool ipv4 = true; bool ipv6 = true; bool debug = false; bool foreground = false; while((c = getopt(argc, argv, "f:p:s:46dvg")) > 0) switch(c) { case 'f': frequency = atoi(optarg); break; case 'p': port = atoi(optarg); break; case 's': samplerate = atoi(optarg); break; case '4': ipv6 = false; break; case '6': ipv4 = false; break; case 'd': debug = true; foreground = true; break; case 'g': foreground = true; break; case 'v': printf("SRPplay tcp server version "SERVER_VERSION"\n"); return 0; default: usage(); return -1; } if(!foreground) daemon(0,0); sdrServer server(frequency, port, samplerate, ipv4, ipv6, debug); for(;;) { server.run(); sleep(1000); } } /* sdrServer */ sdrServer::sdrServer(int frequency, int port, int samplerate, bool ipv4, bool ipv6, bool debug) { mFrequency = intToDouble(frequency); mSampleRate = intToDouble(samplerate); mGain = 70; mPort = port; mIpv4 = ipv4; mIpv6 = ipv6; mDebug = debug; mPartialCommandPtr = mPartialCommand; mI = NULL; mQ = NULL; mS = NULL; mBandwidth = mir_sdr_BW_1_536; try { mSocket.init(this, true); } catch(error *e) { fprintf(stderr,"%s\n", e->text()); exit(-1); } } sdrServer::~sdrServer() { delete[] mI; delete[] mQ; delete[] mS; } int sdrServer::run() { try { mSdrPlay.setDCMode(dcmOneShot, false); mSdrPlay.setDCTrackTime(63); if(mDebug) printf("SDR server listening on port %d\n", mPort); mSocket.bind(mPort, mIpv4, mIpv6); mSocket.listen(); } catch(error *e) { fprintf(stderr,"%s\n", e->text()); exit(-1); } return 0; } bool sdrServer::clientConnected(mySocket *socket) { /* We pretend to be and R820 as that seems to be the one with the most settings. The protocol * doesn't allow for arbitrary devices */ sdr_info info = { {'R', 'T', 'L', '0' } }; info.tuner_type = htonl(RTLSDR_TUNER_R820T); info.tuner_gain_count = htonl(sizeof(gain_list)/sizeof(gain_list[0])); if(mDebug) printf("Connection made from %s\n", socket->endpointAddress()); if(socket->send(&info, sizeof(info)) <= 0) { if(mDebug) printf("Sending initial packet failed\n"); return false; } init(); return true; } void sdrServer::clientDisconnected(mySocket *socket) { if(mDebug) printf("Connection lost from %s\n", socket->endpointAddress()); mSdrPlay.uninit(); } void sdrServer::packetReceived(mySocket *socket, const void *packet, ssize_t packetLen, sockaddr *, socklen_t) { sdr_command *s; if(mDebug) printf("Received %d byte packet from %s\n", (int)packetLen, socket->endpointAddress()); if(mPartialCommandPtr > mPartialCommand) { ssize_t l = mPartialCommandPtr - mPartialCommand; ssize_t r = sizeof(sdr_command) - l; if(packetLen >= r) { memcpy(mPartialCommandPtr, packet, (size_t)r); packetLen -= r; packet = ((uint8_t *)packet) + r; processSdrCommand((sdr_command *)mPartialCommand); mPartialCommandPtr = mPartialCommand; } else { memcpy(mPartialCommandPtr, packet, (size_t)packetLen); mPartialCommandPtr += (size_t)packetLen; return; } } s = (sdr_command *)packet; while((size_t)packetLen >= sizeof(sdr_command)) { processSdrCommand(s++); packetLen -= sizeof(sdr_command); } if(packetLen != 0) { memcpy(mPartialCommand, s, (size_t)packetLen); mPartialCommandPtr = mPartialCommand + packetLen; } } bool sdrServer::needPacket(mySocket *socket) { short *i, *q; uint8_t *s; int count = mSdrPlay.getSamplesPerPacket(); bool grChanged, rfChanged, fsChanged; try { if(mFrequencyChanged) updateFrequency(); if(mSamplerateChanged) updateSampleRate(); if(mGainChanged) updateGain(); if(mSdrPlay.readPacket(mI, mQ, &grChanged, &rfChanged, &fsChanged) == 0) { for(i=mI, q=mQ, s=mS; i<mI+count; i++, q++) { *(s++) = (uint8_t)((*i>>8)+128); *(s++) = (uint8_t)((*q>>8)+128); } socket->send(mS, (size_t) count * 2); } } catch(error *e) { printf("%s\n", e->text()); return false; } return true; } void sdrServer::processSdrCommand(sdr_command *sdrcmd) { int cmd = sdrcmd->cmd; int arg = htonl(sdrcmd->param); switch(cmd) { case 1: // Set Frequency mOldFrequency = mFrequency; mFrequency = intToDouble(arg); if(mDebug) printf("Set frequency in Mhz to %f\n", mFrequency); mFrequencyChanged = true; break; case 2: // Set Sample Rate mOldSampleRate = mSampleRate; mSampleRate = intToDouble(arg); if(mDebug) printf("Set sample rate in Hz to %f\n", mSampleRate); mSamplerateChanged = true; break; case 3: // Set Gain Mode if(mDebug) printf("Set gain mode to %d\n", arg); break; case 4: // Set Tuner Gain mOldGain = mGain; mGain = arg; if(mDebug) printf("Set tuner gain to %d\n", mGain); mGainChanged = true; break; case 5: // Set Freq Correction if(mDebug) printf("Set frequency correction %f\n", intToDouble(arg)); break; case 6: // Set IF Gain if(mDebug) printf("Set if gain to %d\n", arg); break; case 7: // Set test mode if(mDebug) printf("Set test mode to %d\n", arg); break; case 8: // Set AGC mode if(mDebug) printf("Set agc mode to %d\n", arg); mAgc = arg != 0; break; case 9: // Set direct sampling // Sample directly off IF or tuner if(mDebug) printf("Set direct sampling to %d\n", arg); break; case 10: // Set offset tuning // Essentially whether to use IF stage or not if(mDebug) printf("Set offset tuning to %d\n", arg); break; case 11: // Set rtl xtal if(mDebug) printf("Set rtl xtal to %d\n", arg); break; case 12: // Set tuner xtal if(mDebug) printf("Set tuner xtal to %d\n", arg); break; case 13: // Set gain by index if(mDebug) printf("Set gain to index %d\n", arg); if(arg<0 || arg>(int)(sizeof(gain_list)/sizeof(gain_list[0]))) break; mGain = gain_list[arg]; if(mDebug) printf(" %d\n", mGain); mGainChanged = true; break; default: if(mDebug) printf("Unknown Cmd = %d, arg = %d\n", cmd, arg ); break; } } double sdrServer::intToDouble(int freq) { return double(freq) / 1000000.0; } int sdrServer::classifyFrequency(double frequency) { if(frequency < 0.1 || frequency > 2000) return -1; // Out of spec if(frequency < 60) return 1; // 100Khz - 60Mhz if(frequency < 120) return 2; // 60Mhz - 120Mhz if(frequency < 245) return 3; // 120Mhz - 245Mhz if(frequency < 380) return 4; // 245Mhz - 380Mhz if(frequency < 430) return -1; // 380Mhz - 430Mhz unsupported if(frequency < 1000) return 5; // 430Mhz - 1Ghz return 6; // 1Ghz - 2Ghz; } void sdrServer::updateFrequency() { int oldFrequencyClass, newFrequencyClass; oldFrequencyClass = classifyFrequency(mOldFrequency); newFrequencyClass = classifyFrequency(mFrequency); if(newFrequencyClass == -1) { if(mDebug) printf("Out of spec"); return; } if(mDebug) printf("New frequency class is %d\n", newFrequencyClass); if(oldFrequencyClass!=newFrequencyClass) { reinit(); } else { mFrequencyChanged = false; mSdrPlay.setRF(mFrequency * 1000000, true, false); } } void sdrServer::updateSampleRate() { double diff; if(mSampleRate < (((int)mBandwidth)/1000.0)) { if(mSampleRate >= 1.536) mBandwidth = mir_sdr_BW_1_536; else if(mSampleRate >= 0.6) mBandwidth = mir_sdr_BW_0_600; else if(mSampleRate >= 0.3) mBandwidth = mir_sdr_BW_0_300; else if(mSampleRate >= 0.2) mBandwidth = mir_sdr_BW_0_200; else { if(mDebug) printf("Sample rate below 200 not supported\n"); mBandwidth = mir_sdr_BW_1_536; mSampleRate = 2.048; } reinit(); } else if(mSampleRate > 1.536 && (int)mBandwidth < 1536) { mBandwidth = mir_sdr_BW_1_536; reinit(); } else { diff = fabs(mSampleRate - mOldSampleRate); // in Hz // From the docs, changes over >1000 need a reinit (so we use +/-500). if(diff > 500) { reinit(); } else mSamplerateChanged = false; /* SetFS occasionally fails anyway.. */ if(mSdrPlay.setFS(mSampleRate, true, false, false)) reinit(); } } void sdrServer::updateGain() { mGainChanged = false; mSdrPlay.setGR(mGain, true, false); } void sdrServer::reinit() { mSdrPlay.uninit(); init(); } void sdrServer::init() { mFrequencyChanged = false; mSamplerateChanged = false; mGainChanged = false; mSdrPlay.init(mGain, mSampleRate, mFrequency, mBandwidth, mir_sdr_IF_Zero); delete[] mI; delete[] mQ; delete[] mS; mI = new short[mSdrPlay.getSamplesPerPacket()]; mQ = new short[mSdrPlay.getSamplesPerPacket()]; mS = new uint8_t[mSdrPlay.getSamplesPerPacket() * 2]; } <|endoftext|>
<commit_before>// ----------------------------------------------------------------------------- // // MIT License // // Copyright (c) 2016 Alberto Sola // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // Remember // // Simple command line task-manager. // // ----------------------------------------------------------------------------- #include <cstring> #include <iostream> #include <string> #include "task.hpp" #include "taskdb.hpp" #include "tasker.hpp" #include "command.hpp" #include "cmdget.hpp" #include "cmdadd.hpp" #include "cmddel.hpp" // TODO: Improve Command * parse_args(int args, char * argc[]){ const std::string COMMAND_UNKNOWN_ERROR = "Unknown command."; Command * cmd; std::string cmd_name; std::string data; char add[] = "add"; char del[] = "del"; if(args > 2){ // ADD TASK // ----------------------------------------------- if( strcmp(argc[1],add) == 0 ){ for(int i = 2; i < args; i++){ data += argc[i]; data += " "; } cmd = new CmdAdd(data); } // DELETE TASK // ----------------------------------------------- else if( strcmp(argc[1],del) == 0 ){ cmd = new CmdDel( std::atoi(argc[2]) ); } // ERROR // ----------------------------------------------- else{ std::cout << COMMAND_UNKNOWN_ERROR << std::endl; exit(-1); // TODO: Show help. } } else{ cmd = new CmdGet(); } return cmd; } int main( int args, char ** argc ){ Command * command; Tasker tasker; command->set_tasker(&tasker); command = parse_args(args,argc); command->execute(); delete command; } <commit_msg>Fixed command uninitialized.<commit_after>// ----------------------------------------------------------------------------- // // MIT License // // Copyright (c) 2016 Alberto Sola // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // Remember // // Simple command line task-manager. // // ----------------------------------------------------------------------------- #include <cstring> #include <iostream> #include <string> #include "task.hpp" #include "taskdb.hpp" #include "tasker.hpp" #include "command.hpp" #include "cmdget.hpp" #include "cmdadd.hpp" #include "cmddel.hpp" // TODO: Improve Command * parse_args(int args, char * argc[]){ const std::string COMMAND_UNKNOWN_ERROR = "Unknown command."; Command * cmd; std::string cmd_name; std::string data; char add[] = "add"; char del[] = "del"; if(args > 2){ // ADD TASK // ----------------------------------------------- if( strcmp(argc[1],add) == 0 ){ for(int i = 2; i < args; i++){ data += argc[i]; data += " "; } cmd = new CmdAdd(data); } // DELETE TASK // ----------------------------------------------- else if( strcmp(argc[1],del) == 0 ){ cmd = new CmdDel( std::atoi(argc[2]) ); } // ERROR // ----------------------------------------------- else{ std::cout << COMMAND_UNKNOWN_ERROR << std::endl; exit(-1); // TODO: Show help. } } else{ cmd = new CmdGet(); } return cmd; } int main( int args, char ** argc ){ Command * command; Tasker tasker; command = parse_args(args,argc); command->set_tasker(&tasker); command->execute(); delete command; } <|endoftext|>
<commit_before>#include <logging/Logger.h> #include <graphics/GlfwContext.h> #include <graphics/GlfwWindow.h> #include <graphics/Renderer.h> #include <gamemodel/GameState.h> #include <input/Input.h> int main(int argc, char ** argv) { Logger::initSystem(argc, argv); GlfwContext glfwContext(Logger::glfwErrorCallback); GlfwWindow glfwWindow(1200, 800); GameState gameState; Input input(gameState); Renderer renderer(glfwWindow, gameState); glfwWindow.makeCurrent(); glfwWindow.setKeyCallback(input.handleKeyboardFcnPtr); glfwWindow.enterMainLoop([&] { const double t = glfwGetTime(); input.update(t); gameState.update(t); renderer.draw(t); return t < 3600.0; }); return 0; } <commit_msg>Move some resources to heap<commit_after>#include <memory> #include <logging/Logger.h> #include <graphics/GlfwContext.h> #include <graphics/GlfwWindow.h> #include <graphics/Renderer.h> #include <gamemodel/GameState.h> #include <input/Input.h> int main(int argc, char ** argv) { Logger::initSystem(argc, argv); GlfwContext glfwContext(Logger::glfwErrorCallback); GlfwWindow glfwWindow(1200, 800); auto gameState = std::make_unique<GameState>(); auto input = std::make_unique<Input>(*gameState); auto renderer = std::make_unique<Renderer>(glfwWindow, *gameState); glfwWindow.makeCurrent(); glfwWindow.setKeyCallback(input->handleKeyboardFcnPtr); glfwWindow.enterMainLoop([&] { const double t = glfwGetTime(); input->update(t); gameState->update(t); renderer->draw(t); return t < 3600.0; }); return 0; } <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (people-users@projects.maemo.org) ** ** This file is part of contactsd. ** ** If you have questions regarding the use of this file, please contact ** Nokia at people-users@projects.maemo.org. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QCoreApplication> #include <QDBusConnection> #include <QTimer> #include "contactsd.h" #include "debug.h" using namespace Contactsd; static void usage() { qDebug() << "Usage: contactsd [OPTION]...\n"; qDebug() << " --plugins PLUGINS Comma separated list of plugins to load\n"; qDebug() << " --log-console Enable Console Logging \n"; qDebug() << " --version Output version information and exit"; qDebug() << " --help Display this help and exit"; } int main(int argc, char **argv) { QCoreApplication app(argc, argv); QStringList plugins; const QStringList args = app.arguments(); QString arg; int i = 1; // ignore argv[0] bool logConsole = !qgetenv("CONTACTSD_DEBUG").isEmpty(); while (i < args.count()) { arg = args.at(i); if (arg == "--plugins") { if (++i == args.count()) { usage(); return -1; } QString value = args.at(i); value.replace(" ", ","); plugins << value.split(",", QString::SkipEmptyParts); } if (arg == "--version") { qDebug() << "contactsd version" << VERSION; return 0; } else if (arg == "--help") { usage(); return 0; } else if (arg == "--log-console") { logConsole = true; } else { qWarning() << "Invalid argument" << arg; usage(); return -1; } ++i; } enableDebug(logConsole); debug() << "contactsd version" << VERSION << "started"; ContactsDaemon *daemon = new ContactsDaemon(&app); daemon->loadPlugins(plugins); return app.exec(); } <commit_msg>Changes: Fix usage of --plugins command line option<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (people-users@projects.maemo.org) ** ** This file is part of contactsd. ** ** If you have questions regarding the use of this file, please contact ** Nokia at people-users@projects.maemo.org. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QCoreApplication> #include <QDBusConnection> #include <QTimer> #include "contactsd.h" #include "debug.h" using namespace Contactsd; static void usage() { qDebug() << "Usage: contactsd [OPTION]...\n"; qDebug() << " --plugins PLUGINS Comma separated list of plugins to load\n"; qDebug() << " --log-console Enable Console Logging \n"; qDebug() << " --version Output version information and exit"; qDebug() << " --help Display this help and exit"; } int main(int argc, char **argv) { QCoreApplication app(argc, argv); QStringList plugins; const QStringList args = app.arguments(); QString arg; int i = 1; // ignore argv[0] bool logConsole = !qgetenv("CONTACTSD_DEBUG").isEmpty(); while (i < args.count()) { arg = args.at(i); if (arg == "--plugins") { if (++i == args.count()) { usage(); return -1; } QString value = args.at(i); value.replace(" ", ","); plugins << value.split(",", QString::SkipEmptyParts); } else if (arg == "--version") { qDebug() << "contactsd version" << VERSION; return 0; } else if (arg == "--help") { usage(); return 0; } else if (arg == "--log-console") { logConsole = true; } else { qWarning() << "Invalid argument" << arg; usage(); return -1; } ++i; } enableDebug(logConsole); debug() << "contactsd version" << VERSION << "started"; ContactsDaemon *daemon = new ContactsDaemon(&app); daemon->loadPlugins(plugins); return app.exec(); } <|endoftext|>
<commit_before>#include <fstream> #include <iostream> #include <iterator> #include <map> #include <stdexcept> #include <string> #include <utility> #include <vector> #include <boost/algorithm/string/split.hpp> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/serialization/base_object.hpp> #include <boost/serialization/map.hpp> #include <boost/config/select_platform_config.hpp> namespace po = boost::program_options; typedef std::map<std::string, std::string> MapAlias; std::string getStorageFile() { boost::filesystem::path path; path = std::getenv(BOOST_WINDOWS ? "HOMEPATH" : "HOME"); path /= ".kd_database"; return path.string(); } // add a new alias or throw in case it already exists. void add(const std::string& alias, const std::string& path, MapAlias& map_alias) { auto it = map_alias.find(alias); if (it != map_alias.end()) throw(std::runtime_error("alias already exists!")); map_alias[alias] = path; } // remove an alias or throw in the case it doesn't exist. void remove(const std::string& alias, MapAlias& map_alias) { auto it = map_alias.find(alias); if (it != map_alias.end()) map_alias.erase(it); return; throw(std::runtime_error("alias doesn't exists!")); } // return how many characters the greatest alias has... size_t get_max_alias_size(const MapAlias& map_alias) { size_t size = 0; for (auto it : map_alias) if (it.first.size() > size) size = it.first.size(); return size; } // list all aliases. void list(const MapAlias& map_alias) { size_t max_columns = get_max_alias_size(map_alias); std::cout.flags(std::ios::left); std::cout.width(max_columns); for (const auto& it : map_alias) std::cout << it.first << " -> " << it.second << std::endl; } // serialize the map of aliases. void save(const MapAlias& map_alias) { std::ofstream ofs(getStorageFile()); if (ofs.is_open()) { boost::archive::text_oarchive output(ofs); output << map_alias; } } // deserialize the map of aliases. void load(MapAlias& map_alias) { std::ifstream ifs(getStorageFile()); if (ifs.is_open()) { boost::archive::text_iarchive input(ifs); input >> map_alias; } } // serialization for a vetor of T. template<class T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { std::copy(v.begin(), v.end(), std::ostream_iterator<T>(os, " ")); return os; } int main(int argc, char *argv[]) { getStorageFile(); MapAlias map_alias; load(map_alias); try { po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("add,a", po::value<std::string>(), "create a new alias") ("alias", po::value<std::string>(), "") ("remove,r", po::value<std::string>(), "remove an alias") ("list,l", "") ; po::positional_options_description p; p.add("alias", -1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); po::notify(vm); if (vm.count("help")) { std::cout << "Usage: options_description [options]\n"; std::cout << desc; return 0; } if (vm.count("add")) { if (vm.count("alias")) { add(vm["alias"].as<std::string>(), vm["add"].as<std::string>(), map_alias); save(map_alias); } else throw(std::runtime_error("an alias should be specified")); } else if (vm.count("remove")) { remove(vm["remove"].as<std::string>(), map_alias); save(map_alias); } else if (vm.count("list")) { list(map_alias); } else if (vm.count("alias")) { auto it = map_alias.find(vm["alias"].as<std::string>()); if (it != map_alias.end()) std::cout << it->second; } } catch(std::exception& e) { std::cout << e.what() << "\n"; return 1; } return 0; } <commit_msg>implemented to save the aliases inside a file located in the $HOME directory.<commit_after>#include <fstream> #include <iostream> #include <iterator> #include <map> #include <stdexcept> #include <string> #include <utility> #include <vector> #include <boost/algorithm/string/split.hpp> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/serialization/base_object.hpp> #include <boost/serialization/map.hpp> #include <boost/config/select_platform_config.hpp> namespace po = boost::program_options; typedef std::map<std::string, std::string> MapAlias; std::string getStorageFile() { boost::filesystem::path path; path = std::getenv(BOOST_WINDOWS ? "HOMEPATH" : "HOME"); path /= ".kd_database"; return path.string(); } // add a new alias or throw in case it already exists. void add(const std::string& alias, const std::string& path, MapAlias& map_alias) { auto it = map_alias.find(alias); if (it != map_alias.end()) throw(std::runtime_error("alias already exists!")); map_alias[alias] = path; } // remove an alias or throw in the case it doesn't exist. void remove(const std::string& alias, MapAlias& map_alias) { auto it = map_alias.find(alias); if (it != map_alias.end()) map_alias.erase(it); return; throw(std::runtime_error("alias doesn't exists!")); } // return how many characters the greatest alias has... size_t get_max_alias_size(const MapAlias& map_alias) { size_t size = 0; for (auto it : map_alias) if (it.first.size() > size) size = it.first.size(); return size; } // list all aliases. void list(const MapAlias& map_alias) { size_t max_columns = get_max_alias_size(map_alias); std::cout.flags(std::ios::left); std::cout.width(max_columns); for (const auto& it : map_alias) std::cout << it.first << " -> " << it.second << std::endl; } // serialize the map of aliases. void save(const MapAlias& map_alias) { std::ofstream ofs(getStorageFile()); if (ofs.is_open()) { boost::archive::text_oarchive output(ofs); output << map_alias; } } // deserialize the map of aliases. void load(MapAlias& map_alias) { std::ifstream ifs(getStorageFile()); if (ifs.is_open()) { boost::archive::text_iarchive input(ifs); input >> map_alias; } } // serialization for a vetor of T. template<class T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { std::copy(v.begin(), v.end(), std::ostream_iterator<T>(os, " ")); return os; } int main(int argc, char *argv[]) { getStorageFile(); MapAlias map_alias; load(map_alias); try { po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("add,a", po::value<std::string>(), "create a new alias") ("alias", po::value<std::string>(), "") ("remove,r", po::value<std::string>(), "remove an alias") ("list,l", "") ; po::positional_options_description p; p.add("alias", -1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); po::notify(vm); if (vm.count("help")) { std::cout << "Usage: options_description [options]\n"; std::cout << desc; return 0; } if (vm.count("add")) { if (vm.count("alias")) { add(vm["alias"].as<std::string>(), vm["add"].as<std::string>(), map_alias); save(map_alias); } else throw(std::runtime_error("an alias should be specified")); } else if (vm.count("remove")) { remove(vm["remove"].as<std::string>(), map_alias); save(map_alias); } else if (vm.count("list")) { list(map_alias); } else if (vm.count("alias")) { auto it = map_alias.find(vm["alias"].as<std::string>()); if (it != map_alias.end()) std::cout << it->second; } } catch(std::exception& e) { std::cout << e.what() << "\n"; return 1; } return 0; } <|endoftext|>
<commit_before>#include "includes.hpp" #include "interface.hpp" namespace ProjectInfo { const char* const projectName = "Kiwano"; const char* const versionString = "0.1"; const int versionNumber = 0x10000; } class MainWindow : public DocumentWindow { user_interface itf; base::lisp gl; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(MainWindow); public: MainWindow(String name) : DocumentWindow(name, Colours::lightgrey, DocumentWindow::allButtons), itf(gl) { //setUsingNativeTitleBar(true); // TODO: fix blink on startup setContentOwned(&itf, false); setSize(800, 600); setTopLeftPosition(200, 200); setResizable(true, true); setVisible(true); // initialize playback playback::init(); // initialize GLISP using namespace std::placeholders; gl.init(); // GUI gl.addProcedure("create-playlist", std::bind(&user_interface::create_playlist, &itf, _1, _2)); gl.addProcedure("create-layout", std::bind(&user_interface::create_layout, &itf, _1, _2)); gl.addProcedure("create-interpreter", std::bind(&user_interface::create_interpreter, &itf, _1, _2)); gl.addProcedure("create-tabs", std::bind(&user_interface::create_tabs, &itf, _1, _2)); gl.addProcedure("create-audio-settings", std::bind(&user_interface::create_audio_settings, &itf, _1, _2)); gl.addProcedure("create-text-button", std::bind(&user_interface::create_text_button, &itf, _1, _2)); gl.addProcedure("layout-add-component", std::bind(&user_interface::layout_add_component, &itf, _1, _2)); gl.addProcedure("layout-remove-component", std::bind(&user_interface::layout_remove_component, &itf, _1, _2)); gl.addProcedure("layout-add-splitter", std::bind(&user_interface::layout_add_splitter, &itf, _1, _2)); gl.addProcedure("layout-get-splitter-count", std::bind(&user_interface::layout_get_splitters_count, &itf, _1, _2)); gl.addProcedure("layout-remove-splitter", std::bind(&user_interface::layout_remove_splitter, &itf, _1, _2)); gl.addProcedure("tabs-add-component", std::bind(&user_interface::tabs_add_component, &itf, _1, _2)); gl.addProcedure("set-main-component", std::bind(&user_interface::set_main_component, &itf, _1, _2)); gl.addProcedure("refresh-interface", std::bind(&user_interface::refresh_interface, &itf, _1, _2)); // GUI event binding gl.addProcedure("bind-mouse-click", std::bind(&user_interface::bind_mouse_listener<mouseUpListener>, &itf, _1, _2)); gl.addProcedure("bind-mouse-double-click", std::bind(&user_interface::bind_mouse_listener<mouseDoubleClickListener>, &itf, _1, _2)); gl.addProcedure("unbind-mouse", std::bind(&user_interface::unbind_mouse_listener, &itf, _1, _2)); gl.addProcedure("playlist-get-selected", std::bind(&user_interface::playlist_get_selected, &itf, _1, _2)); // playback API gl.addProcedure("playback-set-file", std::bind(&playback::set_file, std::ref(gl), _1, _2)); gl.addProcedure("playback-unload-file", std::bind(&playback::unload_file, std::ref(gl), _1, _2)); gl.addProcedure("playback-start", std::bind(&playback::start, std::ref(gl), _1, _2)); gl.addProcedure("playback-stop", std::bind(&playback::stop, std::ref(gl), _1, _2)); gl.addProcedure("playback-seek", std::bind(&playback::seek, std::ref(gl), _1, _2)); gl.addProcedure("playback-length", std::bind(&playback::length, std::ref(gl), _1, _2)); gl.addProcedure("playback-get-pos", std::bind(&playback::get_pos, std::ref(gl), _1, _2)); gl.addProcedure("playback-is-playing", std::bind(&playback::is_playing, std::ref(gl), _1, _2)); // test gl.eval("(defun on-playlist-click (item-str) (playback-set-file item-str) (playback-start) )"); // prepare settings folder base::string appPath = base::fs::getUserDirectory() + "/.kiwano"; base::fs::createFolderTree(appPath); base::fs::open(appPath); // load ELISP config file gl.eval(base::toStr(base::fs::load("init.lisp"))); } void closeButtonPressed() override { base::fs::close(); gl.close(); playback::shutdown(); JUCEApplication::getInstance()->systemRequestedQuit(); } }; class KiwanoApplication : public JUCEApplication { ScopedPointer<MainWindow> mainWindow; public: KiwanoApplication() {} const String getApplicationName() override { return ProjectInfo::projectName; } const String getApplicationVersion() override { return ProjectInfo::versionString; } bool moreThanOneInstanceAllowed() override { return false; } void initialise(const String& commandLine) override { mainWindow = new MainWindow(getApplicationName()); } void shutdown() override { mainWindow = nullptr; } void systemRequestedQuit() override { quit(); } void anotherInstanceStarted (const String& commandLine) override { } }; START_JUCE_APPLICATION(KiwanoApplication); // TODO: load default config <commit_msg>+ mouse callbacks added to lisp<commit_after>#include "includes.hpp" #include "interface.hpp" namespace ProjectInfo { const char* const projectName = "Kiwano"; const char* const versionString = "0.1"; const int versionNumber = 0x10000; } class MainWindow : public DocumentWindow { user_interface itf; base::lisp gl; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(MainWindow); public: MainWindow(String name) : DocumentWindow(name, Colours::lightgrey, DocumentWindow::allButtons), itf(gl) { //setUsingNativeTitleBar(true); // TODO: fix blink on startup setContentOwned(&itf, false); setSize(800, 600); setTopLeftPosition(200, 200); setResizable(true, true); setVisible(true); // initialize playback playback::init(); // initialize GLISP using namespace std::placeholders; gl.init(); // GUI gl.addProcedure("create-playlist", std::bind(&user_interface::create_playlist, &itf, _1, _2)); gl.addProcedure("create-layout", std::bind(&user_interface::create_layout, &itf, _1, _2)); gl.addProcedure("create-interpreter", std::bind(&user_interface::create_interpreter, &itf, _1, _2)); gl.addProcedure("create-tabs", std::bind(&user_interface::create_tabs, &itf, _1, _2)); gl.addProcedure("create-audio-settings", std::bind(&user_interface::create_audio_settings, &itf, _1, _2)); gl.addProcedure("create-text-button", std::bind(&user_interface::create_text_button, &itf, _1, _2)); gl.addProcedure("layout-add-component", std::bind(&user_interface::layout_add_component, &itf, _1, _2)); gl.addProcedure("layout-remove-component", std::bind(&user_interface::layout_remove_component, &itf, _1, _2)); gl.addProcedure("layout-add-splitter", std::bind(&user_interface::layout_add_splitter, &itf, _1, _2)); gl.addProcedure("layout-get-splitter-count", std::bind(&user_interface::layout_get_splitters_count, &itf, _1, _2)); gl.addProcedure("layout-remove-splitter", std::bind(&user_interface::layout_remove_splitter, &itf, _1, _2)); gl.addProcedure("tabs-add-component", std::bind(&user_interface::tabs_add_component, &itf, _1, _2)); gl.addProcedure("set-main-component", std::bind(&user_interface::set_main_component, &itf, _1, _2)); gl.addProcedure("refresh-interface", std::bind(&user_interface::refresh_interface, &itf, _1, _2)); // GUI event binding gl.addProcedure("bind-mouse-click", std::bind(&user_interface::bind_mouse_listener<mouseUpListener>, &itf, _1, _2)); gl.addProcedure("bind-mouse-up", std::bind(&user_interface::bind_mouse_listener<mouseUpListener>, &itf, _1, _2)); gl.addProcedure("bind-mouse-double-click", std::bind(&user_interface::bind_mouse_listener<mouseDoubleClickListener>, &itf, _1, _2)); gl.addProcedure("bind-mouse-down", std::bind(&user_interface::bind_mouse_listener<mouseDownListener>, &itf, _1, _2)); gl.addProcedure("unbind-mouse", std::bind(&user_interface::unbind_mouse_listener, &itf, _1, _2)); gl.addProcedure("playlist-get-selected", std::bind(&user_interface::playlist_get_selected, &itf, _1, _2)); // playback API gl.addProcedure("playback-set-file", std::bind(&playback::set_file, std::ref(gl), _1, _2)); gl.addProcedure("playback-unload-file", std::bind(&playback::unload_file, std::ref(gl), _1, _2)); gl.addProcedure("playback-start", std::bind(&playback::start, std::ref(gl), _1, _2)); gl.addProcedure("playback-stop", std::bind(&playback::stop, std::ref(gl), _1, _2)); gl.addProcedure("playback-seek", std::bind(&playback::seek, std::ref(gl), _1, _2)); gl.addProcedure("playback-length", std::bind(&playback::length, std::ref(gl), _1, _2)); gl.addProcedure("playback-get-pos", std::bind(&playback::get_pos, std::ref(gl), _1, _2)); gl.addProcedure("playback-is-playing", std::bind(&playback::is_playing, std::ref(gl), _1, _2)); // test gl.eval("(defun on-playlist-click (item-str) (playback-set-file item-str) (playback-start) )"); // prepare settings folder base::string appPath = base::fs::getUserDirectory() + "/.kiwano"; base::fs::createFolderTree(appPath); base::fs::open(appPath); // load ELISP config file gl.eval(base::toStr(base::fs::load("init.lisp"))); } void closeButtonPressed() override { base::fs::close(); gl.close(); playback::shutdown(); JUCEApplication::getInstance()->systemRequestedQuit(); } }; class KiwanoApplication : public JUCEApplication { ScopedPointer<MainWindow> mainWindow; public: KiwanoApplication() {} const String getApplicationName() override { return ProjectInfo::projectName; } const String getApplicationVersion() override { return ProjectInfo::versionString; } bool moreThanOneInstanceAllowed() override { return false; } void initialise(const String& commandLine) override { mainWindow = new MainWindow(getApplicationName()); } void shutdown() override { mainWindow = nullptr; } void systemRequestedQuit() override { quit(); } void anotherInstanceStarted (const String& commandLine) override { } }; START_JUCE_APPLICATION(KiwanoApplication); // TODO: load default config <|endoftext|>
<commit_before>#include <string.h> #include <stdlib.h> #include <iostream> #include <unistd.h> #include <string> #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> #include <errno.h> #include <vector> using namespace std; void parse_input(char* (&args)[100], string usrString){ char *cstr = new char[usrString.length()+1]; strcpy(cstr,usrString.c_str()); char *temp = strtok(cstr, " &|"); int cnt = 0; while (temp != 0){ args[cnt] = temp; ++cnt; temp = strtok(NULL, " &|"); } args[cnt] = NULL; for(int i = 0; i < cnt; i++){ cout << args[i] << endl; } delete[] cstr; return; } //Function checks for connectors and returns a number based on which one is found //Pass in a string, a position integer, and a starting point integer int check_connect(const string& str, int& pos, int start){ unsigned found = 0; found = str.find_first_of(";&|#",start); if (found >= str.size()){ //If not found... pos = -1; return -1; } else{ if (str.at(found) == ';'){ pos = found; return 1; } else if (str.at(found) == '&'){ if (str.at(found+1) == '&'){ pos = found; return 2; } else{ return check_connect(str,pos,found+1); } } else if (str.at(found) == '|'){ if (str.at(found+1) == '|'){ pos = found; return 3; } else{ return check_connect(str,pos,found+1); } } else if (str.at(found) == '#'){ pos = found; return 4; } } return -1; } int main() { int start = 0; // int c_stat; // int pos = -1; vector<string> str; str.push_back("ls -a"); str.push_back("pwd"); str.push_back("&Third: && got that ampersand"); str.push_back("We has | in i||t"); str.push_back("This has a #comment"); char **args = new char*[100]; parse_input(*args,str.at(0)); cout << "command: " << args[0] << endl; int pid = fork(); if (pid == -1){ perror("fork"); } else if (pid == 0){ if(execvp(args[0],args) == -1){ perror("execvp"); } exit(0); } else if(pid > 0){ if(wait(0) == -1){ perror("wait"); } cout << "Done!" << endl; } // for (int i = 0; i < 5; ++i){ // parse_input(args,str.at(i)); // } delete[] args; return 0; } <commit_msg>combined parse/exec into one function<commit_after>#include <string.h> #include <stdlib.h> #include <iostream> #include <unistd.h> #include <string> #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> #include <errno.h> #include <vector> using namespace std; bool parse_exec(string usrString, int size){ int status; char **args = new char*[size+1]; char *cstr = new char[size+1]; strcpy(cstr,usrString.c_str()); char *temp = strtok(cstr, " &|;#"); int cnt = 0; while (temp != 0){ args[cnt] = temp; ++cnt; temp = strtok(NULL, " &|"); } args[cnt] = NULL; for(int i = 0; i < cnt; i++){ cout << args[i] << endl; } if (!strcmp(args[0],"exit")){ exit(0); } int pid = fork(); if (pid == -1){ perror("fork"); } else if(pid == 0){ if (execvp(args[0],args) == -1){ perror("execvp"); } exit(0); } else if(pid > 0){ if(-1 == wait(&status)){ perror("wait"); } } delete[] cstr; delete[] args; if(WIFEXITED(status) != 0){ cout << "Success!" << endl; return true; } else{ cout << "Failure!" << endl; return false; } } //Function checks for connectors and returns a number based on which one is found //Pass in a string, a position integer, and a starting point integer int check_connect(const string& str, int& pos, int start){ unsigned found = 0; found = str.find_first_of(";&|#",start); if (found >= str.size()){ //If not found... pos = -1; return -1; } else{ if (str.at(found) == ';'){ pos = found; return 1; } else if (str.at(found) == '&'){ if (str.at(found+1) == '&'){ pos = found; return 2; } else{ return check_connect(str,pos,found+1); } } else if (str.at(found) == '|'){ if (str.at(found+1) == '|'){ pos = found; return 3; } else{ return check_connect(str,pos,found+1); } } else if (str.at(found) == '#'){ pos = found; return 4; } } return -1; } int main() { //Get User Info while(1){ //Get User Input bool exec_stat = true; //Connector Status int con_stat = 0; int pos = 0; int start = 0; int size = 0; string usrString; cout << "$ "; getline(cin,usrString); size = usrString.size(); if (size == 0){ continue; } //Check Connectors while(1){ con_stat = check_connect(usrString,pos,start); if (con_stat == -1){ exec_stat = parse_exec(usrString.substr(start),size); break; } else if (con_stat == 1){ exec_stat = parse_exec(usrString.substr(start,pos), size); start = pos + 1; continue; } else if (con_stat == 2){ exec_stat = parse_exec(usrString.substr(start,pos), size); start = pos + 2; if (exec_stat == true){ continue; } else{ break; } } else if (con_stat == 3){ exec_stat = parse_exec(usrString.substr(start,pos), size); start = pos + 2; if (exec_stat == true){ break; } else{ continue; } } else if (con_stat == 4){ exec_stat = parse_exec(usrString.substr(start,pos), size); break; } } } return 0; } // while (pos != -1){ // //Parsing and Executing Section // char **args = new char*[usrString.length()+1]; // char *cstr = new char[usrString.length()+1]; // strcpy(cstr,usrString.c_str()); // char *temp = strtok(cstr, " &|"); // int cnt = 0; // // while (temp != 0){ // args[cnt] = temp; // ++cnt; // temp = strtok(NULL, " &|"); // } // args[cnt] = NULL; // for(int i = 0; i < cnt; i++){ // cout << args[i] << endl; // } // // //Execution // if(!strcmp(args[0], safe_word)){ //Check for exit command // exit(0); // } // // int pid = fork(); // if (pid == -1){ // perror("fork"); // } // else if (pid == 0){ // if(execvp(args[0],args) == -1){ // perror("execvp"); // } // exit(0); // } // else if(pid > 0){ // if(wait(0) == -1){ // perror("wait"); // } // } // // // delete[] cstr; // delete[] args; // } <|endoftext|>
<commit_before>#include "AppInfo.h" #include "FileUtils.h" #include "Log.h" #include "Platform.h" #include "ProcessUtils.h" #include "StringUtils.h" #include "UpdateScript.h" #include "UpdaterOptions.h" #include "tinythread.h" #if defined(PLATFORM_LINUX) #include "UpdateDialogGtkWrapper.h" #include "UpdateDialogAscii.h" #endif #if defined(PLATFORM_MAC) #include "MacBundle.h" #include "UpdateDialogCocoa.h" #endif #if defined(PLATFORM_WINDOWS) #include "UpdateDialogWin32.h" #endif #include <iostream> #define UPDATER_VERSION "0.8" void runWithUi(int argc, char** argv, UpdateInstaller* installer); void runUpdaterThread(void* arg) { #ifdef PLATFORM_MAC // create an autorelease pool to free any temporary objects // created by Cocoa whilst handling notifications from the UpdateInstaller void* pool = UpdateDialogCocoa::createAutoreleasePool(); #endif try { UpdateInstaller* installer = static_cast<UpdateInstaller*>(arg); installer->run(); } catch (const std::exception& ex) { LOG(Error,"Unexpected exception " + std::string(ex.what())); } #ifdef PLATFORM_MAC UpdateDialogCocoa::releaseAutoreleasePool(pool); #endif } #ifdef PLATFORM_MAC extern unsigned char Info_plist[]; extern unsigned int Info_plist_len; extern unsigned char mac_icns[]; extern unsigned int mac_icns_len; bool unpackBundle(int argc, char** argv) { MacBundle bundle(FileUtils::tempPath(),AppInfo::name()); std::string currentExePath = ProcessUtils::currentProcessPath(); if (currentExePath.find(bundle.bundlePath()) != std::string::npos) { // already running from a bundle return false; } LOG(Info,"Creating bundle " + bundle.bundlePath()); // create a Mac app bundle std::string plistContent(reinterpret_cast<const char*>(Info_plist),Info_plist_len); std::string iconContent(reinterpret_cast<const char*>(mac_icns),mac_icns_len); bundle.create(plistContent,iconContent,ProcessUtils::currentProcessPath()); std::list<std::string> args; for (int i = 1; i < argc; i++) { args.push_back(argv[i]); } ProcessUtils::runSync(bundle.executablePath(),args); return true; } #endif void setupConsole() { #ifdef PLATFORM_WINDOWS // see http://stackoverflow.com/questions/587767/how-to-output-to-console-in-c-windows // and http://www.libsdl.org/cgi/docwiki.cgi/FAQ_Console AttachConsole(ATTACH_PARENT_PROCESS); freopen( "CON", "w", stdout ); freopen( "CON", "w", stderr ); #endif } int main(int argc, char** argv) { #ifdef PLATFORM_MAC void* pool = UpdateDialogCocoa::createAutoreleasePool(); #endif Log::instance()->open(AppInfo::logFilePath()); #ifdef PLATFORM_MAC // when the updater is run for the first time, create a Mac app bundle // and re-launch the application from the bundle. This permits // setting up bundle properties (such as application icon) if (unpackBundle(argc,argv)) { return 0; } #endif UpdaterOptions options; options.parse(argc,argv); if (options.showVersion) { setupConsole(); std::cout << "Update installer version " << UPDATER_VERSION << std::endl; return 0; } UpdateInstaller installer; UpdateScript script; if (!options.scriptPath.empty()) { script.parse(FileUtils::makeAbsolute(options.scriptPath.c_str(),options.packageDir.c_str())); } LOG(Info,"started updater. install-dir: " + options.installDir + ", package-dir: " + options.packageDir + ", wait-pid: " + intToStr(options.waitPid) + ", script-path: " + options.scriptPath + ", mode: " + intToStr(options.mode)); installer.setMode(options.mode); installer.setInstallDir(options.installDir); installer.setPackageDir(options.packageDir); installer.setScript(&script); installer.setWaitPid(options.waitPid); installer.setForceElevated(options.forceElevated); if (options.mode == UpdateInstaller::Main) { runWithUi(argc,argv,&installer); } else { installer.run(); } #ifdef PLATFORM_MAC UpdateDialogCocoa::releaseAutoreleasePool(pool); #endif return 0; } #ifdef PLATFORM_LINUX void runWithUi(int argc, char** argv, UpdateInstaller* installer) { UpdateDialogAscii asciiDialog; UpdateDialogGtkWrapper dialog; bool useGtk = dialog.init(argc,argv); if (useGtk) { installer->setObserver(&dialog); } else { asciiDialog.init(); installer->setObserver(&asciiDialog); } tthread::thread updaterThread(runUpdaterThread,installer); if (useGtk) { dialog.exec(); } updaterThread.join(); } #endif #ifdef PLATFORM_MAC void runWithUi(int argc, char** argv, UpdateInstaller* installer) { UpdateDialogCocoa dialog; installer->setObserver(&dialog); dialog.init(); tthread::thread updaterThread(runUpdaterThread,installer); dialog.exec(); updaterThread.join(); } #endif #ifdef PLATFORM_WINDOWS // application entry point under Windows int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int argc = 0; char** argv; ProcessUtils::convertWindowsCommandLine(GetCommandLineW(),argc,argv); return main(argc,argv); } void runWithUi(int argc, char** argv, UpdateInstaller* installer) { UpdateDialogWin32 dialog; installer->setObserver(&dialog); dialog.init(); tthread::thread updaterThread(runUpdaterThread,installer); dialog.exec(); updaterThread.join(); } #endif <commit_msg>Bump version number to 0.9.1<commit_after>#include "AppInfo.h" #include "FileUtils.h" #include "Log.h" #include "Platform.h" #include "ProcessUtils.h" #include "StringUtils.h" #include "UpdateScript.h" #include "UpdaterOptions.h" #include "tinythread.h" #if defined(PLATFORM_LINUX) #include "UpdateDialogGtkWrapper.h" #include "UpdateDialogAscii.h" #endif #if defined(PLATFORM_MAC) #include "MacBundle.h" #include "UpdateDialogCocoa.h" #endif #if defined(PLATFORM_WINDOWS) #include "UpdateDialogWin32.h" #endif #include <iostream> #define UPDATER_VERSION "0.9.1" void runWithUi(int argc, char** argv, UpdateInstaller* installer); void runUpdaterThread(void* arg) { #ifdef PLATFORM_MAC // create an autorelease pool to free any temporary objects // created by Cocoa whilst handling notifications from the UpdateInstaller void* pool = UpdateDialogCocoa::createAutoreleasePool(); #endif try { UpdateInstaller* installer = static_cast<UpdateInstaller*>(arg); installer->run(); } catch (const std::exception& ex) { LOG(Error,"Unexpected exception " + std::string(ex.what())); } #ifdef PLATFORM_MAC UpdateDialogCocoa::releaseAutoreleasePool(pool); #endif } #ifdef PLATFORM_MAC extern unsigned char Info_plist[]; extern unsigned int Info_plist_len; extern unsigned char mac_icns[]; extern unsigned int mac_icns_len; bool unpackBundle(int argc, char** argv) { MacBundle bundle(FileUtils::tempPath(),AppInfo::name()); std::string currentExePath = ProcessUtils::currentProcessPath(); if (currentExePath.find(bundle.bundlePath()) != std::string::npos) { // already running from a bundle return false; } LOG(Info,"Creating bundle " + bundle.bundlePath()); // create a Mac app bundle std::string plistContent(reinterpret_cast<const char*>(Info_plist),Info_plist_len); std::string iconContent(reinterpret_cast<const char*>(mac_icns),mac_icns_len); bundle.create(plistContent,iconContent,ProcessUtils::currentProcessPath()); std::list<std::string> args; for (int i = 1; i < argc; i++) { args.push_back(argv[i]); } ProcessUtils::runSync(bundle.executablePath(),args); return true; } #endif void setupConsole() { #ifdef PLATFORM_WINDOWS // see http://stackoverflow.com/questions/587767/how-to-output-to-console-in-c-windows // and http://www.libsdl.org/cgi/docwiki.cgi/FAQ_Console AttachConsole(ATTACH_PARENT_PROCESS); freopen( "CON", "w", stdout ); freopen( "CON", "w", stderr ); #endif } int main(int argc, char** argv) { #ifdef PLATFORM_MAC void* pool = UpdateDialogCocoa::createAutoreleasePool(); #endif Log::instance()->open(AppInfo::logFilePath()); #ifdef PLATFORM_MAC // when the updater is run for the first time, create a Mac app bundle // and re-launch the application from the bundle. This permits // setting up bundle properties (such as application icon) if (unpackBundle(argc,argv)) { return 0; } #endif UpdaterOptions options; options.parse(argc,argv); if (options.showVersion) { setupConsole(); std::cout << "Update installer version " << UPDATER_VERSION << std::endl; return 0; } UpdateInstaller installer; UpdateScript script; if (!options.scriptPath.empty()) { script.parse(FileUtils::makeAbsolute(options.scriptPath.c_str(),options.packageDir.c_str())); } LOG(Info,"started updater. install-dir: " + options.installDir + ", package-dir: " + options.packageDir + ", wait-pid: " + intToStr(options.waitPid) + ", script-path: " + options.scriptPath + ", mode: " + intToStr(options.mode)); installer.setMode(options.mode); installer.setInstallDir(options.installDir); installer.setPackageDir(options.packageDir); installer.setScript(&script); installer.setWaitPid(options.waitPid); installer.setForceElevated(options.forceElevated); if (options.mode == UpdateInstaller::Main) { runWithUi(argc,argv,&installer); } else { installer.run(); } #ifdef PLATFORM_MAC UpdateDialogCocoa::releaseAutoreleasePool(pool); #endif return 0; } #ifdef PLATFORM_LINUX void runWithUi(int argc, char** argv, UpdateInstaller* installer) { UpdateDialogAscii asciiDialog; UpdateDialogGtkWrapper dialog; bool useGtk = dialog.init(argc,argv); if (useGtk) { installer->setObserver(&dialog); } else { asciiDialog.init(); installer->setObserver(&asciiDialog); } tthread::thread updaterThread(runUpdaterThread,installer); if (useGtk) { dialog.exec(); } updaterThread.join(); } #endif #ifdef PLATFORM_MAC void runWithUi(int argc, char** argv, UpdateInstaller* installer) { UpdateDialogCocoa dialog; installer->setObserver(&dialog); dialog.init(); tthread::thread updaterThread(runUpdaterThread,installer); dialog.exec(); updaterThread.join(); } #endif #ifdef PLATFORM_WINDOWS // application entry point under Windows int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int argc = 0; char** argv; ProcessUtils::convertWindowsCommandLine(GetCommandLineW(),argc,argv); return main(argc,argv); } void runWithUi(int argc, char** argv, UpdateInstaller* installer) { UpdateDialogWin32 dialog; installer->setObserver(&dialog); dialog.init(); tthread::thread updaterThread(runUpdaterThread,installer); dialog.exec(); updaterThread.join(); } #endif <|endoftext|>
<commit_before>#include <fstream> #include <iostream> #include <Refal2.h> using namespace Refal2; class CMyClass : public IVariablesBuilderListener, public IFunctionBuilderListener, public IScannerListener, public IParserListener { public: virtual void OnScannerError(const TScannerErrorCodes errorCode, char c); virtual void OnParserError(const TParserErrorCodes errorCode); virtual void OnFunctionBuilderError(const TFunctionBuilderErrorCodes errorCode); virtual void OnVariablesBuilderError(const TVariablesBuilderErrorCodes errorCode); }; void CMyClass::OnScannerError(const TScannerErrorCodes errorCode, char c) { static const char* errorText[] = { "SEC_UnexpectedControlSequence", "SEC_SymbolAfterPlus", "SEC_UnexpectedCharacter", "SEC_IllegalCharacterInLabelOrNumberBegin", "SEC_IllegalCharacterInLabel", "SEC_IllegalCharacterInNumber", "SEC_IllegalCharacterInQualifierNameBegin", "SEC_IllegalCharacterInQualifierName", "SEC_IllegalCharacterInStringAfterBackslash", "SEC_IllegalCharacterInStringInHexadecimal", "SEC_TryingAppendNullByteToString", "SEC_IllegalCharacterInStringInOctal", "SEC_UnclosedStringConstantAtTheEndOfFile", "SEC_UnclosedStringConstant", "SEC_UnclosedLabelOrNumberAtTheEndOfFile", "SEC_UnclosedLabelOrNumber", "SEC_UnclosedLabelAtTheEndOfFile", "SEC_UnclosedLabel", "SEC_UnclosedNumberAtTheEndOfFile", "SEC_UnclosedNumber", "SEC_UnclosedQualifierAtTheEndOfFile", "SEC_UnclosedQualifier", "SEC_UnexpectedEndOfFil" }; std::cout << "ScannerError: " /*<< line << ": " << localOffset << ": "*/; /*if( c != '\0' ) { std::cout << c << ": "; }*/ std::cout << errorText[errorCode] << "\n"; } void CMyClass::OnParserError(const TParserErrorCodes errorCode) { static const char* errorText[] = { "PEC_LineShouldBeginWithIdentifierOrSpace", "PEC_NewLineExpected", "PEC_UnexpectedLexemeAfterIdentifierInTheBeginningOfLine" }; std::cout << errorText[errorCode] << "\n"; } void CMyClass::OnFunctionBuilderError(const Refal2::TFunctionBuilderErrorCodes errorCode) { static const char* errorText[] = { "FBEC_ThereAreNoRulesInFunction", "FBEC_IllegalLeftBracketInLeftPart", "FBEC_IllegalRightBracketInLeftPart", "FBEC_RightParenDoesNotMatchLeftParen", "FBEC_RightBracketDoesNotMatchLeftBracket", "FBEC_UnclosedLeftParenInLeftPart", "FBEC_UnclosedLeftParenInRightPart", "FBEC_UnclosedLeftBracketInRightPart", "FBEC_IllegalQualifierInRightPart" }; printf("CFunctionBuilder error: %s\n", errorText[errorCode]); } void CMyClass::OnVariablesBuilderError(const Refal2::TVariablesBuilderErrorCodes errorCode) { static const char* errorText[] = { "VBEC_InvalidVatiableName", "VBEC_NoSuchTypeOfVariable", "VBEC_TypeOfVariableDoesNotMatch", "VBEC_NoSuchVariableInLeftPart" }; printf("CVariablesBuilder error: %s\n", errorText[errorCode]); } int main(int argc, const char* argv[]) { try { const char* filename = "../tests/simple.ref"; if( argc == 2 ) { filename = argv[1]; } CMyClass ca; CParser parser( &ca ); std::ifstream f( filename ); if( !f.good() ) { std::cerr << "Can't open file\n"; return 1; } while( true ) { int c = f.get(); if( c == -1 ) { parser.AddEndOfFile(); break; } else { parser.AddChar(c); } } std::cout << "\n--------------------------------------------------\n\n"; for( int i = LabelTable.GetFirstLabel(); i != InvalidLabel; i = LabelTable.GetNextLabel( i ) ) { CFunction* function = LabelTable.GetLabelFunction( i ); if( function->IsParsed() ) { std::cout << "{START:" << LabelTable.GetLabelText( i ) << "}\n"; PrintFunction( *function ); CFunctionCompiler compiler; compiler.Compile( function ); std::cout << "{END:" << LabelTable.GetLabelText( i ) << "}\n"; } } } catch(bool) { return 1; } return 0; } #if 0 #include <iostream> #include <fstream> #include <Refal2.h> using namespace Refal2; int main(int argc, const char* argv[]) { CQualifier a; { CQualifierBuilder tmp; tmp.Char('H'); tmp.Char('e'); tmp.Char('l'); tmp.B(); tmp.N(); tmp.Negative(); tmp.Get(&a); } /* CFunctionBuilder bf; bf.Char('a'); bf.LeftParen(); bf.Char('b'); bf.RightParen(); bf.EndOfLeftPart(); bf.Number(444); bf.Char('c'); bf.Number(7); bf.EndOfRule(); CRule* rule; bf.Get(&rule); print_function(rule);*/ COperationsBuilder builder; CFieldOfView view; CUnitLink* left; CUnitLink* right; right = CFieldOfView::Insert(view.First(), CUnitValue(CLink::T_right_paren)); left = CFieldOfView::Insert(view.First(), CUnitValue(CLink::T_left_paren)); left->PairedParen() = right; right->PairedParen() = left; CUnitLink char_value(CUnitLink::T_char); CUnitLink number_value(CUnitLink::T_number); CUnitLink left_paren(CUnitLink::T_left_paren); CUnitLink right_paren(CUnitLink::T_right_paren); COperation* func = builder.Add(COperation::OT_left_max_qualifier, &a); builder.Add(COperation::OT_closed_e_variable_match); builder.Add(COperation::OT_matching_complete); char_value.Char() = '%'; builder.Add(COperation::OT_insert_symbol, CUnitValue(char_value)); builder.Add(COperation::OT_move_e, 1); char_value.Char() = '$'; builder.Add(COperation::OT_insert_symbol, CUnitValue(char_value)); builder.Add(COperation::OT_copy_wve, 3); char_value.Char() = '*'; builder.Add(COperation::OT_insert_symbol, CUnitValue(char_value)); builder.Add(COperation::OT_move_e, 3); char_value.Char() = '#'; builder.Add(COperation::OT_insert_symbol, CUnitValue(char_value)); builder.Add(COperation::OT_return); COperation* go = builder.Add(COperation::OT_empty_expression_match); builder.Add(COperation::OT_matching_complete); /* = */ builder.Add(COperation::OT_insert_left_paren); /* < */ CUnitLink label_func(CLink::T_label); label_func.Label() = new TLabels::value_type; const_cast<std::string&>(label_func.Label()->first) = "Mama"; label_func.Label()->second.operation = func; builder.Add(COperation::OT_insert_symbol, label_func); /* /Mama/ */ const char* tmp = "Hello, World!"; for( const char* i = tmp; i[0] != '\0'; ++i ) { char_value.Char() = i[0]; number_value.Number() = i - tmp; builder.Add(COperation::OT_insert_symbol, char_value); builder.Add(COperation::OT_insert_left_paren); builder.Add(COperation::OT_insert_symbol, number_value); builder.Add(COperation::OT_insert_right_paren); } builder.Add(COperation::OT_insert_right_bracket); /* > */ builder.Add(COperation::OT_insert_left_paren); /* < */ builder.Add(COperation::OT_insert_symbol, label_func); /* /Mama/ */ builder.Add(COperation::OT_insert_right_bracket); /* > */ builder.Add(COperation::OT_return); CUnitLink* location = left; for( const char* i = tmp; i[0] != '\0'; ++i ) { char_value.Char() = i[0]; location = CFieldOfView::Insert(location, char_value); } COperation* jump = builder.Add(COperation::OT_insert_jump, static_cast<COperation*>(0)); COperation* reverse = jump; builder.Add(COperation::OT_left_s_variable_match); CUnitLink label_reverse(CLink::T_label); label_reverse.Label() = new TLabels::value_type; const_cast<std::string&>(label_reverse.Label()->first) = "reverse"; label_reverse.Label()->second.operation = reverse; builder.Add(COperation::OT_closed_e_variable_match); builder.Add(COperation::OT_matching_complete); builder.Add(COperation::OT_insert_left_paren); /* < */ builder.Add(COperation::OT_insert_symbol, label_reverse); /* /reverse/ */ builder.Add(COperation::OT_move_e, 2); builder.Add(COperation::OT_insert_right_bracket); /* > */ builder.Add(COperation::OT_move_s, 0); builder.Add(COperation::OT_return); jump->Operation()->operation = builder.Add(COperation::OT_empty_expression_match); builder.Add(COperation::OT_matching_complete); builder.Add(COperation::OT_return); CExecuter exe; exe.SetStackSize(1024); exe.SetTableSize(128); std::cout << "\n-----\n"; view.Print(); std::cout << "\n-----\n"; exe.Run(reverse, left, right); std::cout << "\n-----\n"; view.Print(); std::cout << "\n-----\n"; /*exe.Run(func, view); std::cout << "\n-----\n"; view.Print(); std::cout << "\n-----\n";*/ return 0; } #endif <commit_msg>switch file to program.ref<commit_after>#include <fstream> #include <iostream> #include <Refal2.h> using namespace Refal2; class CMyClass : public IVariablesBuilderListener, public IFunctionBuilderListener, public IScannerListener, public IParserListener { public: virtual void OnScannerError(const TScannerErrorCodes errorCode, char c); virtual void OnParserError(const TParserErrorCodes errorCode); virtual void OnFunctionBuilderError(const TFunctionBuilderErrorCodes errorCode); virtual void OnVariablesBuilderError(const TVariablesBuilderErrorCodes errorCode); }; void CMyClass::OnScannerError(const TScannerErrorCodes errorCode, char c) { static const char* errorText[] = { "SEC_UnexpectedControlSequence", "SEC_SymbolAfterPlus", "SEC_UnexpectedCharacter", "SEC_IllegalCharacterInLabelOrNumberBegin", "SEC_IllegalCharacterInLabel", "SEC_IllegalCharacterInNumber", "SEC_IllegalCharacterInQualifierNameBegin", "SEC_IllegalCharacterInQualifierName", "SEC_IllegalCharacterInStringAfterBackslash", "SEC_IllegalCharacterInStringInHexadecimal", "SEC_TryingAppendNullByteToString", "SEC_IllegalCharacterInStringInOctal", "SEC_UnclosedStringConstantAtTheEndOfFile", "SEC_UnclosedStringConstant", "SEC_UnclosedLabelOrNumberAtTheEndOfFile", "SEC_UnclosedLabelOrNumber", "SEC_UnclosedLabelAtTheEndOfFile", "SEC_UnclosedLabel", "SEC_UnclosedNumberAtTheEndOfFile", "SEC_UnclosedNumber", "SEC_UnclosedQualifierAtTheEndOfFile", "SEC_UnclosedQualifier", "SEC_UnexpectedEndOfFil" }; std::cout << "ScannerError: " /*<< line << ": " << localOffset << ": "*/; /*if( c != '\0' ) { std::cout << c << ": "; }*/ std::cout << errorText[errorCode] << "\n"; } void CMyClass::OnParserError(const TParserErrorCodes errorCode) { static const char* errorText[] = { "PEC_LineShouldBeginWithIdentifierOrSpace", "PEC_NewLineExpected", "PEC_UnexpectedLexemeAfterIdentifierInTheBeginningOfLine" }; std::cout << errorText[errorCode] << "\n"; } void CMyClass::OnFunctionBuilderError(const Refal2::TFunctionBuilderErrorCodes errorCode) { static const char* errorText[] = { "FBEC_ThereAreNoRulesInFunction", "FBEC_IllegalLeftBracketInLeftPart", "FBEC_IllegalRightBracketInLeftPart", "FBEC_RightParenDoesNotMatchLeftParen", "FBEC_RightBracketDoesNotMatchLeftBracket", "FBEC_UnclosedLeftParenInLeftPart", "FBEC_UnclosedLeftParenInRightPart", "FBEC_UnclosedLeftBracketInRightPart", "FBEC_IllegalQualifierInRightPart" }; printf("CFunctionBuilder error: %s\n", errorText[errorCode]); } void CMyClass::OnVariablesBuilderError(const Refal2::TVariablesBuilderErrorCodes errorCode) { static const char* errorText[] = { "VBEC_InvalidVatiableName", "VBEC_NoSuchTypeOfVariable", "VBEC_TypeOfVariableDoesNotMatch", "VBEC_NoSuchVariableInLeftPart" }; printf("CVariablesBuilder error: %s\n", errorText[errorCode]); } int main(int argc, const char* argv[]) { try { //const char* filename = "../tests/simple.ref"; const char* filename = "../tests/PROGRAM.REF"; if( argc == 2 ) { filename = argv[1]; } CMyClass ca; CParser parser( &ca ); std::ifstream f( filename ); if( !f.good() ) { std::cerr << "Can't open file\n"; return 1; } while( true ) { int c = f.get(); if( c == -1 ) { parser.AddEndOfFile(); break; } else { parser.AddChar(c); } } std::cout << "\n--------------------------------------------------\n\n"; for( int i = LabelTable.GetFirstLabel(); i != InvalidLabel; i = LabelTable.GetNextLabel( i ) ) { CFunction* function = LabelTable.GetLabelFunction( i ); if( function->IsParsed() ) { std::cout << "{START:" << LabelTable.GetLabelText( i ) << "}\n"; PrintFunction( *function ); CFunctionCompiler compiler; compiler.Compile( function ); std::cout << "{END:" << LabelTable.GetLabelText( i ) << "}\n"; } } } catch(bool) { return 1; } return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <set> #include <algorithm> #include <queue> #include <boost/asio.hpp> #include <boost/thread.hpp> #include <google/protobuf/io/coded_stream.h> #include "message.pb.h" using namespace boost::asio; using ru::spbau::chat::commons::protocol::Message; using google::protobuf::io::CodedInputStream; using google::protobuf::io::CodedOutputStream; using google::protobuf::uint8; using google::protobuf::uint32; typedef std::pair<size_t, std::shared_ptr<uint8>> serialized_message; #ifdef DEBUG static size_t const INITIAL_BUFFER_SIZE = 1 << 2; // 4 b #else static size_t const INITIAL_BUFFER_SIZE = 1 << 12; // 4 Kb #endif static size_t const MESSAGES_IN_QUEUE_TO_FALLBACK = 1 << 12; static size_t const MAX_VARINT_BYTES = 10; class chat_user { public: virtual void accept_message_size() = 0; virtual void deliver_message(serialized_message const &message) = 0; }; typedef std::shared_ptr<chat_user> user_ptr; class chat_room { public: chat_room() { } void add_new_user(user_ptr user) { rw_mutex.lock(); users.push_back(user); rw_mutex.unlock(); #ifdef DEBUG std::cout << "User connected" << std::endl; #endif user->accept_message_size(); } void on_user_leave(user_ptr user) { rw_mutex.lock(); auto pos = std::find_if(users.begin(), users.end(), [user](user_ptr &ptr) { return ptr.get() == user.get(); }); if (pos != users.end()) { users.erase(pos); } rw_mutex.unlock(); #ifdef DEBUG std::cout << "User leaved" << std::endl; #endif } void deliver_message_to_all(std::shared_ptr<Message> const &message) { size_t msg_size = message->ByteSize(); size_t size = msg_size + MAX_VARINT_BYTES; std::shared_ptr<uint8> buffer(new uint8[size]); auto it = CodedOutputStream::WriteVarint32ToArray(msg_size, buffer.get()); bool written = message->SerializeToArray(it, msg_size); assert(written); serialized_message message_serialized(msg_size + (it - buffer.get()), buffer); rw_mutex.lock_shared(); for(auto &user_p: users) { user_p->deliver_message(message_serialized); } rw_mutex.unlock_shared(); } private: std::vector<user_ptr> users; boost::shared_mutex rw_mutex; }; class user : public chat_user, public std::enable_shared_from_this<user> { public: user(ip::tcp::socket sock, chat_room &chat, io_service &service) : socket(std::move(sock)), chat(chat), service(service), message_buffer(std::max(INITIAL_BUFFER_SIZE, MAX_VARINT_BYTES)), buffer_offset(0), buffer_red(0), write_buffer(std::max(INITIAL_BUFFER_SIZE, MAX_VARINT_BYTES)), write_in_progress(false) { } void accept_message_size() { check_enougth_space(MAX_VARINT_BYTES); if (buffer_red) { bool read_succ; size_t read_bytes_count; uint32 message_size; { CodedInputStream input(message_buffer.data() + buffer_offset, buffer_red); read_succ = input.ReadVarint32(&message_size); read_bytes_count = input.CurrentPosition(); } if (read_succ) { buffer_offset += read_bytes_count; buffer_red -= read_bytes_count; accept_message(message_size); return; } if (buffer_red > MAX_VARINT_BYTES) { #ifdef DEBUG std::cout << "invalid varint: " << std::endl; #endif chat.on_user_leave(shared_from_this()); return; } } auto ancor(shared_from_this()); async_read(socket, buffer(message_buffer.data() + buffer_offset + buffer_red, message_buffer.size() - buffer_offset - buffer_red), transfer_at_least(1), [this, ancor](boost::system::error_code ec, std::size_t bytes_red) { #ifdef DEBUG std::cout << "Reading message size: bytes red " << buffer_red + bytes_red << std::endl; #endif if (ec) { #ifdef DEBUG std::cout << "error on reading message_size: " << ec.message() << std::endl; #endif chat.on_user_leave(shared_from_this()); return; } else { buffer_red += bytes_red; accept_message_size(); } }); } void accept_message(uint32 message_size) { check_enougth_space(message_size); if (buffer_red >= message_size) { { std::shared_ptr<Message> message(new Message()); try { message->ParseFromArray(message_buffer.data() + buffer_offset, message_size); } catch (std::exception &) { #ifdef DEBUG std::cout << "Failed to parse protobuf message" << std::endl; #endif chat.on_user_leave(shared_from_this()); return; } buffer_offset += message_size; buffer_red -= message_size; #ifdef DEBUG std::cout << "message red [" << (message->has_type() ? message->type() : -1) << ", " << (message->has_author() ? message->author() : "no author") << ", " << (message->text_size() ? message->text(0) : "no text") << "]" << std::endl; #endif chat.deliver_message_to_all(message); } accept_message_size(); return; } auto ancor(shared_from_this()); async_read(socket, buffer(message_buffer.data() + buffer_offset + buffer_red, message_buffer.size() - buffer_offset - buffer_red), transfer_at_least(message_size - buffer_red), [this, ancor, message_size](boost::system::error_code ec, std::size_t bytes_red) { #ifdef DEBUG std::cout << "Reading message: bytes red " << buffer_red + bytes_red << " from " << message_size << std::endl; #endif if (ec) { #ifdef DEBUG std::cout << "error: " << ec.message() << std::endl; #endif chat.on_user_leave(shared_from_this()); return; } else { buffer_red += bytes_red; accept_message(message_size); } }); } void deliver_message(serialized_message const &message) { bool do_poll_here; { boost::lock_guard<boost::mutex> guard(deliver_queue_mutex); messages_to_deliver.push(message); if (!write_in_progress) { write_in_progress = true; auto ancor(shared_from_this()); service.post([this, ancor](){do_write();}); } do_poll_here = messages_to_deliver.size() >= MESSAGES_IN_QUEUE_TO_FALLBACK; } if (do_poll_here) { service.poll_one(); } } ~user() { #ifdef DEBUG std::cout << "user destroyed" << std::endl; #endif } private: void check_enougth_space(size_t space_needed) { assert(buffer_offset + buffer_red <= message_buffer.size()); if (!buffer_red) { buffer_offset = 0; } if (buffer_offset + space_needed <= message_buffer.size()) { return; } memmove(message_buffer.data(), message_buffer.data() + buffer_offset, buffer_red); buffer_offset = 0; if (space_needed > message_buffer.size()) { message_buffer.resize(space_needed); } } void do_write() { boost::lock_guard<boost::mutex> guard(deliver_queue_mutex); size_t min_size = messages_to_deliver.front().first; if (write_buffer.size() < min_size) { write_buffer.resize(min_size); } size_t write_buffer_offset = 0; while (!messages_to_deliver.empty()) { serialized_message const &message = messages_to_deliver.front(); if (message.first > write_buffer.size() - write_buffer_offset) { break; } #ifdef DEBUG std::cout << "message written" << std::endl; #endif memcpy(write_buffer.data() + write_buffer_offset, message.second.get(), message.first); write_buffer_offset += message.first; messages_to_deliver.pop(); } auto ancor(shared_from_this()); async_write(socket, buffer(write_buffer.data(), write_buffer_offset), [this, ancor](boost::system::error_code ec, std::size_t) { if (ec) { #ifdef DEBUG std::cout << "error writing: " << ec.message() << std::endl; #endif chat.on_user_leave(shared_from_this()); return; } else { { boost::lock_guard<boost::mutex> guard(deliver_queue_mutex); if (messages_to_deliver.empty()) { write_in_progress = false; return; } } do_write(); } }); } private: ip::tcp::socket socket; chat_room &chat; io_service &service; std::vector<uint8> message_buffer; size_t buffer_offset; size_t buffer_red; std::vector<uint8> write_buffer; std::queue<serialized_message> messages_to_deliver; boost::mutex deliver_queue_mutex; bool write_in_progress; }; class connection_handler { public: connection_handler(io_service &service, int port, chat_room &chat) : sock(service), service(service), acc(service, ip::tcp::endpoint(ip::tcp::v4(), port)), chat(chat) { } public: void accept_new_connection() { acc.async_accept(sock, [this](boost::system::error_code) { assert(sock.is_open()); chat.add_new_user(std::make_shared<user>(std::move(sock), chat, service)); accept_new_connection(); }); } private: ip::tcp::socket sock; io_service &service; ip::tcp::acceptor acc; chat_room &chat; }; int main(int argc, char *argv[]) { if (argc < 3) { std::cout << "Usage: ./chat_server $PORT_NUMBER$ $CONCURRENCY_LEVEL$" << std::endl << "Where $CONCURRENCY_LEVEL$ - number of the worker threads" << std::endl; return -1; } size_t port = std::atoi(argv[1]); size_t concurrency_level = std::atoi(argv[2]); try { std::cout << "Starting chat server on port " << port << " with concurrency level " << concurrency_level << " ..." << std::endl; io_service service(concurrency_level); chat_room chat; connection_handler handler(service, port, chat); handler.accept_new_connection(); boost::thread_group workers; auto const worker = boost::bind(&io_service::run, &service); for (size_t idx = 0; idx < concurrency_level; ++idx) { workers.create_thread(worker); } std::cout << "The server is started" << std::endl; std::cout << "Press 'enter' to stop the server" << std::endl; std::cin.get(); std::cout << "Stopping the server..." << std::endl; service.stop(); workers.join_all(); std::cout << "The server is stopped" << std::endl; } catch(std::exception &e) { std::cerr << "An exception occured with "; if (e.what()) { std::cerr << "message: \"" << e.what() << '"'; } else { std::cerr << "no message"; } std::cerr << std::endl; google::protobuf::ShutdownProtobufLibrary(); return -1; } google::protobuf::ShutdownProtobufLibrary(); return 0; } <commit_msg>Polling fixed<commit_after>#include <iostream> #include <vector> #include <set> #include <algorithm> #include <queue> #include <boost/asio.hpp> #include <boost/thread.hpp> #include <google/protobuf/io/coded_stream.h> #include "message.pb.h" using namespace boost::asio; using ru::spbau::chat::commons::protocol::Message; using google::protobuf::io::CodedInputStream; using google::protobuf::io::CodedOutputStream; using google::protobuf::uint8; using google::protobuf::uint32; typedef std::pair<size_t, std::shared_ptr<uint8>> serialized_message; #ifdef DEBUG static size_t const INITIAL_BUFFER_SIZE = 1 << 2; // 4 b #else static size_t const INITIAL_BUFFER_SIZE = 1 << 12; // 4 Kb #endif static size_t const MESSAGES_IN_QUEUE_TO_FALLBACK = 1 << 12; static size_t const MAX_VARINT_BYTES = 10; class chat_user { public: virtual void accept_message_size() = 0; virtual bool deliver_message(serialized_message const &message) = 0; }; typedef std::shared_ptr<chat_user> user_ptr; class chat_room { public: chat_room() { } void add_new_user(user_ptr user) { rw_mutex.lock(); users.push_back(user); rw_mutex.unlock(); #ifdef DEBUG std::cout << "User connected" << std::endl; #endif user->accept_message_size(); } void on_user_leave(user_ptr user) { rw_mutex.lock(); auto pos = std::find_if(users.begin(), users.end(), [user](user_ptr &ptr) { return ptr.get() == user.get(); }); if (pos != users.end()) { users.erase(pos); } rw_mutex.unlock(); #ifdef DEBUG std::cout << "User leaved" << std::endl; #endif } size_t deliver_message_to_all(std::shared_ptr<Message> const &message) { size_t msg_size = message->ByteSize(); size_t size = msg_size + MAX_VARINT_BYTES; std::shared_ptr<uint8> buffer(new uint8[size]); auto it = CodedOutputStream::WriteVarint32ToArray(msg_size, buffer.get()); bool written = message->SerializeToArray(it, msg_size); assert(written); serialized_message message_serialized(msg_size + (it - buffer.get()), buffer); size_t overflow_queues = 0; rw_mutex.lock_shared(); for(auto &user_p: users) { overflow_queues += user_p->deliver_message(message_serialized); } rw_mutex.unlock_shared(); return overflow_queues; } private: std::vector<user_ptr> users; boost::shared_mutex rw_mutex; }; class user : public chat_user, public std::enable_shared_from_this<user> { public: user(ip::tcp::socket sock, chat_room &chat, io_service &service) : socket(std::move(sock)), chat(chat), service(service), message_buffer(std::max(INITIAL_BUFFER_SIZE, MAX_VARINT_BYTES)), buffer_offset(0), buffer_red(0), write_buffer(std::max(INITIAL_BUFFER_SIZE, MAX_VARINT_BYTES)), write_in_progress(false) { } void accept_message_size() { check_enougth_space(MAX_VARINT_BYTES); if (buffer_red) { bool read_succ; size_t read_bytes_count; uint32 message_size; { CodedInputStream input(message_buffer.data() + buffer_offset, buffer_red); read_succ = input.ReadVarint32(&message_size); read_bytes_count = input.CurrentPosition(); } if (read_succ) { buffer_offset += read_bytes_count; buffer_red -= read_bytes_count; accept_message(message_size); return; } if (buffer_red > MAX_VARINT_BYTES) { #ifdef DEBUG std::cout << "invalid varint: " << std::endl; #endif chat.on_user_leave(shared_from_this()); return; } } auto ancor(shared_from_this()); async_read(socket, buffer(message_buffer.data() + buffer_offset + buffer_red, message_buffer.size() - buffer_offset - buffer_red), transfer_at_least(1), [this, ancor](boost::system::error_code ec, std::size_t bytes_red) { #ifdef DEBUG std::cout << "Reading message size: bytes red " << buffer_red + bytes_red << std::endl; #endif if (ec) { #ifdef DEBUG std::cout << "error on reading message_size: " << ec.message() << std::endl; #endif chat.on_user_leave(shared_from_this()); return; } else { buffer_red += bytes_red; accept_message_size(); } }); } void accept_message(uint32 message_size) { check_enougth_space(message_size); if (buffer_red >= message_size) { std::shared_ptr<Message> message(new Message()); try { message->ParseFromArray(message_buffer.data() + buffer_offset, message_size); } catch (std::exception &) { #ifdef DEBUG std::cout << "Failed to parse protobuf message" << std::endl; #endif chat.on_user_leave(shared_from_this()); return; } buffer_offset += message_size; buffer_red -= message_size; #ifdef DEBUG std::cout << "message red [" << (message->has_type() ? message->type() : -1) << ", " << (message->has_author() ? message->author() : "no author") << ", " << (message->text_size() ? message->text(0) : "no text") << "]" << std::endl; #endif size_t busy_factor = chat.deliver_message_to_all(message); for (size_t idx = 0; idx < busy_factor; ++idx) { if (!service.poll_one()) { break; } } accept_message_size(); return; } auto ancor(shared_from_this()); async_read(socket, buffer(message_buffer.data() + buffer_offset + buffer_red, message_buffer.size() - buffer_offset - buffer_red), transfer_at_least(message_size - buffer_red), [this, ancor, message_size](boost::system::error_code ec, std::size_t bytes_red) { #ifdef DEBUG std::cout << "Reading message: bytes red " << buffer_red + bytes_red << " from " << message_size << std::endl; #endif if (ec) { #ifdef DEBUG std::cout << "error: " << ec.message() << std::endl; #endif chat.on_user_leave(shared_from_this()); return; } else { buffer_red += bytes_red; accept_message(message_size); } }); } bool deliver_message(serialized_message const &message) { boost::lock_guard<boost::mutex> guard(deliver_queue_mutex); messages_to_deliver.push(message); if (!write_in_progress) { write_in_progress = true; auto ancor(shared_from_this()); service.post([this, ancor](){do_write();}); } return messages_to_deliver.size() >= MESSAGES_IN_QUEUE_TO_FALLBACK; } ~user() { #ifdef DEBUG std::cout << "user destroyed" << std::endl; #endif } private: void check_enougth_space(size_t space_needed) { assert(buffer_offset + buffer_red <= message_buffer.size()); if (!buffer_red) { buffer_offset = 0; } if (buffer_offset + space_needed <= message_buffer.size()) { return; } memmove(message_buffer.data(), message_buffer.data() + buffer_offset, buffer_red); buffer_offset = 0; if (space_needed > message_buffer.size()) { message_buffer.resize(space_needed); } } void do_write() { boost::lock_guard<boost::mutex> guard(deliver_queue_mutex); size_t min_size = messages_to_deliver.front().first; if (write_buffer.size() < min_size) { write_buffer.resize(min_size); } size_t write_buffer_offset = 0; while (!messages_to_deliver.empty()) { serialized_message const &message = messages_to_deliver.front(); if (message.first > write_buffer.size() - write_buffer_offset) { break; } #ifdef DEBUG std::cout << "message written" << std::endl; #endif memcpy(write_buffer.data() + write_buffer_offset, message.second.get(), message.first); write_buffer_offset += message.first; messages_to_deliver.pop(); } auto ancor(shared_from_this()); async_write(socket, buffer(write_buffer.data(), write_buffer_offset), [this, ancor](boost::system::error_code ec, std::size_t) { if (ec) { #ifdef DEBUG std::cout << "error writing: " << ec.message() << std::endl; #endif chat.on_user_leave(shared_from_this()); return; } else { { boost::lock_guard<boost::mutex> guard(deliver_queue_mutex); if (messages_to_deliver.empty()) { write_in_progress = false; return; } } do_write(); } }); } private: ip::tcp::socket socket; chat_room &chat; io_service &service; std::vector<uint8> message_buffer; size_t buffer_offset; size_t buffer_red; std::vector<uint8> write_buffer; std::queue<serialized_message> messages_to_deliver; boost::mutex deliver_queue_mutex; bool write_in_progress; }; class connection_handler { public: connection_handler(io_service &service, int port, chat_room &chat) : sock(service), service(service), acc(service, ip::tcp::endpoint(ip::tcp::v4(), port)), chat(chat) { } public: void accept_new_connection() { acc.async_accept(sock, [this](boost::system::error_code) { assert(sock.is_open()); chat.add_new_user(std::make_shared<user>(std::move(sock), chat, service)); accept_new_connection(); }); } private: ip::tcp::socket sock; io_service &service; ip::tcp::acceptor acc; chat_room &chat; }; int main(int argc, char *argv[]) { if (argc < 3) { std::cout << "Usage: ./chat_server $PORT_NUMBER$ $CONCURRENCY_LEVEL$" << std::endl << "Where $CONCURRENCY_LEVEL$ - number of the worker threads" << std::endl; return -1; } size_t port = std::atoi(argv[1]); size_t concurrency_level = std::atoi(argv[2]); try { std::cout << "Starting chat server on port " << port << " with concurrency level " << concurrency_level << " ..." << std::endl; io_service service(concurrency_level); chat_room chat; connection_handler handler(service, port, chat); handler.accept_new_connection(); boost::thread_group workers; auto const worker = boost::bind(&io_service::run, &service); for (size_t idx = 0; idx < concurrency_level; ++idx) { workers.create_thread(worker); } std::cout << "The server is started" << std::endl; std::cout << "Press 'enter' to stop the server" << std::endl; std::cin.get(); std::cout << "Stopping the server..." << std::endl; service.stop(); workers.join_all(); std::cout << "The server is stopped" << std::endl; } catch(std::exception &e) { std::cerr << "An exception occured with "; if (e.what()) { std::cerr << "message: \"" << e.what() << '"'; } else { std::cerr << "no message"; } std::cerr << std::endl; google::protobuf::ShutdownProtobufLibrary(); return -1; } google::protobuf::ShutdownProtobufLibrary(); return 0; } <|endoftext|>
<commit_before>/* The MIT License (MIT) * * Copyright (c) 2013 nitoyon * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <windows.h> #include <tchar.h> #include <stdio.h> int SetCtime(LPWSTR path); int wmain() { int ret = 0; int argc; LPWSTR *argv = CommandLineToArgvW(GetCommandLine(), &argc); if (argv == NULL) { wprintf_s(L"Failed to parse\n"); ret = 1; goto done; } if (argc == 1) { wprintf_s(L"File not specified\n"); ret = 1; goto done; } for (int i = 1; i < argc; i++) { wprintf_s(L"%s ... ", argv[i]); ret = SetCtime(argv[i]); if (ret != 0) { wprintf_s(L"FAIL (%d)\n", ret); break; } wprintf_s(L"done\n"); } done: if (argv != NULL) { LocalFree(argv); } } int SetCtime(LPWSTR path) { int ret = 0; HANDLE hFile = INVALID_HANDLE_VALUE; hFile = CreateFile(path, FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING, 0, NULL); if (hFile == INVALID_HANDLE_VALUE) { ret = 2; goto done; } FILETIME ft; if (!GetFileTime(hFile, NULL, NULL, &ft)) { ret = 3; goto done; } if (!SetFileTime(hFile, &ft, NULL, NULL)) { ret = 4; goto done; } done: if (hFile != INVALID_HANDLE_VALUE) { CloseHandle(hFile); } return ret; } <commit_msg>Add support for * and ? in command line arguments<commit_after>/* The MIT License (MIT) * * Copyright (c) 2013 nitoyon * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <windows.h> #include <tchar.h> #include <stdio.h> int SetCtime(LPWSTR path); int wmain() { int ret = 0; int argc; LPWSTR *argv = CommandLineToArgvW(GetCommandLine(), &argc); if (argv == NULL) { wprintf_s(L"Failed to parse\n"); ret = 1; goto done; } if (argc == 1) { wprintf_s(L"File not specified\n"); ret = 1; goto done; } for (int i = 1; i < argc; i++) { WIN32_FIND_DATA fd; HANDLE hFind = FindFirstFile(argv[i], &fd); if (hFind == INVALID_HANDLE_VALUE) { wprintf_s(L"%s ... FAIL\n", argv[i]); break; } do { wprintf_s(L"%s ... ", fd.cFileName); ret = SetCtime(fd.cFileName); if (ret != 0) { wprintf_s(L"FAIL (%d)\n", ret); FindClose(hFind); goto done; } wprintf_s(L"done\n"); } while (FindNextFile(hFind, &fd)); } done: if (argv != NULL) { LocalFree(argv); } } int SetCtime(LPWSTR path) { int ret = 0; HANDLE hFile = INVALID_HANDLE_VALUE; hFile = CreateFile(path, FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING, 0, NULL); if (hFile == INVALID_HANDLE_VALUE) { ret = 2; goto done; } FILETIME ft; if (!GetFileTime(hFile, NULL, NULL, &ft)) { ret = 3; goto done; } if (!SetFileTime(hFile, &ft, NULL, NULL)) { ret = 4; goto done; } done: if (hFile != INVALID_HANDLE_VALUE) { CloseHandle(hFile); } return ret; } <|endoftext|>
<commit_before>#include <memory> #include <iostream> #include <string> #include <sstream> #include <functional> #include <utility> #include <unordered_map> #include <vector> #include <nan.h> #include <v8.h> #include <uv.h> #include "log.h" #include "queue.h" #include "worker/worker_thread.h" using v8::Local; using v8::Value; using v8::Object; using v8::String; using v8::Function; using v8::FunctionTemplate; using std::unique_ptr; using std::string; using std::ostringstream; using std::endl; using std::unordered_map; using std::vector; using std::move; using std::make_pair; static void handle_events_helper(uv_async_t *handle); class Main { public: Main() : worker_thread{&event_handler} { int err; next_command_id = 0; next_channel_id = NULL_CHANNEL_ID + 1; err = uv_async_init(uv_default_loop(), &event_handler, handle_events_helper); if (err) return; worker_thread.run(); } ChannelID send_worker_command( const CommandAction action, const std::string &&root, unique_ptr<Nan::Callback> callback, bool assign_channel_id = false ) { CommandID command_id = next_command_id; ChannelID channel_id = NULL_CHANNEL_ID; if (assign_channel_id) { channel_id = next_channel_id; next_channel_id++; } CommandPayload command_payload(next_command_id, action, move(root), channel_id); Message command_message(move(command_payload)); pending_callbacks.emplace(command_id, move(callback)); next_command_id++; LOGGER << "Sending command " << command_message << " to worker thread." << endl; worker_thread.send(move(command_message)); return channel_id; } void use_main_log_file(string &&main_log_file) { Logger::to_file(main_log_file.c_str()); } void use_worker_log_file(string &&worker_log_file, unique_ptr<Nan::Callback> callback) { send_worker_command(COMMAND_LOG_FILE, move(worker_log_file), move(callback)); } void watch(string &&root, unique_ptr<Nan::Callback> ack_callback, unique_ptr<Nan::Callback> event_callback) { string root_dup(root); ChannelID channel_id = send_worker_command(COMMAND_ADD, move(root), move(ack_callback), true); channel_callbacks.emplace(channel_id, move(event_callback)); LOGGER << "Worker is listening for changes at " << root_dup << " on channel " << channel_id << "." << endl; } void handle_events() { Nan::HandleScope scope; LOGGER << "Handling messages from the worker thread." << endl; unique_ptr<vector<Message>> accepted = worker_thread.receive_all(); if (!accepted) { LOGGER << "No messages waiting." << endl; return; } LOGGER << accepted->size() << " messages to process." << endl; for (auto it = accepted->begin(); it != accepted->end(); ++it) { const AckPayload *ack_message = it->as_ack(); if (ack_message) { auto maybe_callback = pending_callbacks.find(ack_message->get_key()); if (maybe_callback == pending_callbacks.end()) { LOGGER << "Ignoring unexpected ack " << *it << endl; continue; } unique_ptr<Nan::Callback> callback = move(maybe_callback->second); pending_callbacks.erase(maybe_callback); callback->Call(0, nullptr); continue; } const FileSystemPayload *filesystem_message = it->as_filesystem(); if (filesystem_message) { LOGGER << "Received filesystem event message " << *it << endl; auto maybe_callback = channel_callbacks.find(filesystem_message->get_channel_id()); if (maybe_callback == channel_callbacks.end()) { LOGGER << "Ignoring unexpected filesystem event " << *it << endl; continue; } unique_ptr<Nan::Callback> callback = move(maybe_callback->second); channel_callbacks.erase(maybe_callback); callback->Call(0, nullptr); continue; } LOGGER << "Received unexpected message " << *it << endl; } } private: uv_async_t event_handler; WorkerThread worker_thread; CommandID next_command_id; ChannelID next_channel_id; unordered_map<CommandID, unique_ptr<Nan::Callback>> pending_callbacks; unordered_map<ChannelID, unique_ptr<Nan::Callback>> channel_callbacks; }; static Main instance; static void handle_events_helper(uv_async_t *handle) { instance.handle_events(); } static bool get_string_option(Local<Object>& options, const char *key_name, string &out) { Nan::HandleScope scope; const Local<String> key = Nan::New<String>(key_name).ToLocalChecked(); Nan::MaybeLocal<Value> as_maybe_value = Nan::Get(options, key); if (as_maybe_value.IsEmpty()) { return true; } Local<Value> as_value = as_maybe_value.ToLocalChecked(); if (as_value->IsUndefined()) { return true; } if (!as_value->IsString()) { ostringstream message; message << "configure() option " << key_name << " must be a String"; Nan::ThrowError(message.str().c_str()); return false; } Nan::Utf8String as_string(as_value); if (*as_string == nullptr) { ostringstream message; message << "configure() option " << key_name << " must be a valid UTF-8 String"; Nan::ThrowError(message.str().c_str()); return false; } out.assign(*as_string, as_string.length()); return true; } void configure(const Nan::FunctionCallbackInfo<Value> &info) { string main_log_file; string worker_log_file; bool async = false; Nan::MaybeLocal<Object> maybe_options = Nan::To<Object>(info[0]); if (maybe_options.IsEmpty()) { Nan::ThrowError("configure() requires an option object"); return; } Local<Object> options = maybe_options.ToLocalChecked(); if (!get_string_option(options, "mainLogFile", main_log_file)) return; if (!get_string_option(options, "workerLogFile", worker_log_file)) return; unique_ptr<Nan::Callback> callback(new Nan::Callback(info[1].As<Function>())); if (!main_log_file.empty()) { instance.use_main_log_file(move(main_log_file)); } if (!worker_log_file.empty()) { instance.use_worker_log_file(move(worker_log_file), move(callback)); async = true; } if (!async) { callback->Call(0, 0); } } void watch(const Nan::FunctionCallbackInfo<Value> &info) { if (info.Length() != 3) { return Nan::ThrowError("watch() requires three arguments"); } Nan::MaybeLocal<String> maybe_root = Nan::To<String>(info[0]); if (maybe_root.IsEmpty()) { Nan::ThrowError("watch() requires a string as argument one"); return; } Local<String> root_v8_string = maybe_root.ToLocalChecked(); Nan::Utf8String root_utf8(root_v8_string); if (*root_utf8 == nullptr) { Nan::ThrowError("watch() argument one must be a valid UTF-8 string"); return; } string root_str(*root_utf8, root_utf8.length()); unique_ptr<Nan::Callback> ack_callback(new Nan::Callback(info[1].As<Function>())); unique_ptr<Nan::Callback> event_callback(new Nan::Callback(info[2].As<Function>())); instance.watch(move(root_str), move(ack_callback), move(event_callback)); } void unwatch(const Nan::FunctionCallbackInfo<Value> &info) { if (info.Length() != 2) { return Nan::ThrowError("watch() requires two arguments"); } } void initialize(Local<Object> exports) { exports->Set( Nan::New<String>("configure").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(configure)).ToLocalChecked() ); exports->Set( Nan::New<String>("watch").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(watch)).ToLocalChecked() ); exports->Set( Nan::New<String>("unwatch").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(unwatch)).ToLocalChecked() ); } NODE_MODULE(sfw, initialize); <commit_msg>Convert FileSystemPayloads to Node objects<commit_after>#include <memory> #include <iostream> #include <string> #include <sstream> #include <functional> #include <utility> #include <unordered_map> #include <vector> #include <nan.h> #include <v8.h> #include <uv.h> #include "log.h" #include "queue.h" #include "worker/worker_thread.h" using v8::Local; using v8::Value; using v8::Object; using v8::String; using v8::Number; using v8::Function; using v8::FunctionTemplate; using v8::Array; using std::shared_ptr; using std::unique_ptr; using std::string; using std::ostringstream; using std::endl; using std::unordered_map; using std::vector; using std::move; using std::make_pair; static void handle_events_helper(uv_async_t *handle); class Main { public: Main() : worker_thread{&event_handler} { int err; next_command_id = 0; next_channel_id = NULL_CHANNEL_ID + 1; err = uv_async_init(uv_default_loop(), &event_handler, handle_events_helper); if (err) return; worker_thread.run(); } ChannelID send_worker_command( const CommandAction action, const std::string &&root, unique_ptr<Nan::Callback> callback, bool assign_channel_id = false ) { CommandID command_id = next_command_id; ChannelID channel_id = NULL_CHANNEL_ID; if (assign_channel_id) { channel_id = next_channel_id; next_channel_id++; } CommandPayload command_payload(next_command_id, action, move(root), channel_id); Message command_message(move(command_payload)); pending_callbacks.emplace(command_id, move(callback)); next_command_id++; LOGGER << "Sending command " << command_message << " to worker thread." << endl; worker_thread.send(move(command_message)); return channel_id; } void use_main_log_file(string &&main_log_file) { Logger::to_file(main_log_file.c_str()); } void use_worker_log_file(string &&worker_log_file, unique_ptr<Nan::Callback> callback) { send_worker_command(COMMAND_LOG_FILE, move(worker_log_file), move(callback)); } void watch(string &&root, unique_ptr<Nan::Callback> ack_callback, unique_ptr<Nan::Callback> event_callback) { string root_dup(root); ChannelID channel_id = send_worker_command(COMMAND_ADD, move(root), move(ack_callback), true); channel_callbacks.emplace(channel_id, move(event_callback)); LOGGER << "Worker is listening for changes at " << root_dup << " on channel " << channel_id << "." << endl; } void handle_events() { Nan::HandleScope scope; LOGGER << "Handling messages from the worker thread." << endl; unique_ptr<vector<Message>> accepted = worker_thread.receive_all(); if (!accepted) { LOGGER << "No messages waiting." << endl; return; } LOGGER << accepted->size() << " messages to process." << endl; unordered_map<ChannelID, vector<Local<Object>>> to_deliver; for (auto it = accepted->begin(); it != accepted->end(); ++it) { const AckPayload *ack_message = it->as_ack(); if (ack_message) { auto maybe_callback = pending_callbacks.find(ack_message->get_key()); if (maybe_callback == pending_callbacks.end()) { LOGGER << "Ignoring unexpected ack " << *it << endl; continue; } unique_ptr<Nan::Callback> callback = move(maybe_callback->second); pending_callbacks.erase(maybe_callback); callback->Call(0, nullptr); continue; } const FileSystemPayload *filesystem_message = it->as_filesystem(); if (filesystem_message) { LOGGER << "Received filesystem event message " << *it << endl; ChannelID channel_id = filesystem_message->get_channel_id(); Local<Object> js_event = Nan::New<Object>(); js_event->Set( Nan::New<String>("actionType").ToLocalChecked(), Nan::New<Number>(static_cast<int>(filesystem_message->get_filesystem_action())) ); js_event->Set( Nan::New<String>("entryKind").ToLocalChecked(), Nan::New<Number>(static_cast<int>(filesystem_message->get_entry_kind())) ); js_event->Set( Nan::New<String>("oldPath").ToLocalChecked(), Nan::New<String>(filesystem_message->get_old_path()).ToLocalChecked() ); js_event->Set( Nan::New<String>("newPath").ToLocalChecked(), Nan::New<String>(filesystem_message->get_new_path()).ToLocalChecked() ); to_deliver[channel_id].push_back(js_event); continue; } LOGGER << "Received unexpected message " << *it << endl; } for (auto it = to_deliver.begin(); it != to_deliver.end(); ++it) { ChannelID channel_id = it->first; vector<Local<Object>> js_events = it->second; auto maybe_callback = channel_callbacks.find(channel_id); if (maybe_callback == channel_callbacks.end()) { LOGGER << "Ignoring unexpected filesystem event channel " << channel_id << endl; continue; } shared_ptr<Nan::Callback> callback = maybe_callback->second; LOGGER << "Dispatching " << js_events.size() << " events on channel " << channel_id << "." << endl; Local<Array> js_array = Nan::New<Array>(js_events.size()); int index = 0; for (auto et = js_events.begin(); et != js_events.end(); ++et) { js_array->Set(index, *et); index++; } Local<Value> argv[] = { Nan::Null(), js_array }; callback->Call(2, argv); } } private: uv_async_t event_handler; WorkerThread worker_thread; CommandID next_command_id; ChannelID next_channel_id; unordered_map<CommandID, unique_ptr<Nan::Callback>> pending_callbacks; unordered_map<ChannelID, shared_ptr<Nan::Callback>> channel_callbacks; }; static Main instance; static void handle_events_helper(uv_async_t *handle) { instance.handle_events(); } static bool get_string_option(Local<Object>& options, const char *key_name, string &out) { Nan::HandleScope scope; const Local<String> key = Nan::New<String>(key_name).ToLocalChecked(); Nan::MaybeLocal<Value> as_maybe_value = Nan::Get(options, key); if (as_maybe_value.IsEmpty()) { return true; } Local<Value> as_value = as_maybe_value.ToLocalChecked(); if (as_value->IsUndefined()) { return true; } if (!as_value->IsString()) { ostringstream message; message << "configure() option " << key_name << " must be a String"; Nan::ThrowError(message.str().c_str()); return false; } Nan::Utf8String as_string(as_value); if (*as_string == nullptr) { ostringstream message; message << "configure() option " << key_name << " must be a valid UTF-8 String"; Nan::ThrowError(message.str().c_str()); return false; } out.assign(*as_string, as_string.length()); return true; } void configure(const Nan::FunctionCallbackInfo<Value> &info) { string main_log_file; string worker_log_file; bool async = false; Nan::MaybeLocal<Object> maybe_options = Nan::To<Object>(info[0]); if (maybe_options.IsEmpty()) { Nan::ThrowError("configure() requires an option object"); return; } Local<Object> options = maybe_options.ToLocalChecked(); if (!get_string_option(options, "mainLogFile", main_log_file)) return; if (!get_string_option(options, "workerLogFile", worker_log_file)) return; unique_ptr<Nan::Callback> callback(new Nan::Callback(info[1].As<Function>())); if (!main_log_file.empty()) { instance.use_main_log_file(move(main_log_file)); } if (!worker_log_file.empty()) { instance.use_worker_log_file(move(worker_log_file), move(callback)); async = true; } if (!async) { callback->Call(0, 0); } } void watch(const Nan::FunctionCallbackInfo<Value> &info) { if (info.Length() != 3) { return Nan::ThrowError("watch() requires three arguments"); } Nan::MaybeLocal<String> maybe_root = Nan::To<String>(info[0]); if (maybe_root.IsEmpty()) { Nan::ThrowError("watch() requires a string as argument one"); return; } Local<String> root_v8_string = maybe_root.ToLocalChecked(); Nan::Utf8String root_utf8(root_v8_string); if (*root_utf8 == nullptr) { Nan::ThrowError("watch() argument one must be a valid UTF-8 string"); return; } string root_str(*root_utf8, root_utf8.length()); unique_ptr<Nan::Callback> ack_callback(new Nan::Callback(info[1].As<Function>())); unique_ptr<Nan::Callback> event_callback(new Nan::Callback(info[2].As<Function>())); instance.watch(move(root_str), move(ack_callback), move(event_callback)); } void unwatch(const Nan::FunctionCallbackInfo<Value> &info) { if (info.Length() != 2) { return Nan::ThrowError("watch() requires two arguments"); } } void initialize(Local<Object> exports) { exports->Set( Nan::New<String>("configure").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(configure)).ToLocalChecked() ); exports->Set( Nan::New<String>("watch").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(watch)).ToLocalChecked() ); exports->Set( Nan::New<String>("unwatch").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(unwatch)).ToLocalChecked() ); } NODE_MODULE(sfw, initialize); <|endoftext|>
<commit_before>/* * MRustC - Rust Compiler * - By John Hodge (Mutabah/thePowersGang) * * main.cpp * - Compiler Entrypoint */ #include <iostream> #include <iomanip> #include <string> #include <set> #include "parse/lex.hpp" #include "parse/parseerror.hpp" #include "ast/ast.hpp" #include "ast/crate.hpp" #include <serialiser_texttree.hpp> #include <cstring> #include <main_bindings.hpp> #include "resolve/main_bindings.hpp" #include "hir/main_bindings.hpp" #include "hir_conv/main_bindings.hpp" #include "hir_typeck/main_bindings.hpp" #include "hir_expand/main_bindings.hpp" #include "mir/main_bindings.hpp" #include "expand/cfg.hpp" int g_debug_indent_level = 0; ::std::string g_cur_phase; ::std::set< ::std::string> g_debug_disable_map; void init_debug_list() { g_debug_disable_map.insert( "Parse" ); g_debug_disable_map.insert( "Expand" ); g_debug_disable_map.insert( "Resolve" ); g_debug_disable_map.insert( "HIR Lower" ); g_debug_disable_map.insert( "Resolve Type Aliases" ); g_debug_disable_map.insert( "Resolve Bind" ); g_debug_disable_map.insert( "Resolve UFCS paths" ); g_debug_disable_map.insert( "Constant Evaluate" ); g_debug_disable_map.insert( "Typecheck Outer"); g_debug_disable_map.insert( "Typecheck Expressions" ); g_debug_disable_map.insert( "Expand HIR Annotate" ); g_debug_disable_map.insert( "Expand HIR Closures" ); g_debug_disable_map.insert( "Expand HIR Calls" ); g_debug_disable_map.insert( "Expand HIR Reborrows" ); g_debug_disable_map.insert( "Typecheck Expressions (validate)" ); g_debug_disable_map.insert( "Dump HIR" ); g_debug_disable_map.insert( "Lower MIR" ); g_debug_disable_map.insert( "MIR Validate" ); g_debug_disable_map.insert( "Dump MIR" ); g_debug_disable_map.insert( "HIR Serialise" ); } bool debug_enabled() { // TODO: Have an explicit enable list? if( g_debug_disable_map.count(g_cur_phase) != 0 ) { return false; } else { return true; } } ::std::ostream& debug_output(int indent, const char* function) { return ::std::cout << g_cur_phase << "- " << RepeatLitStr { " ", indent } << function << ": "; } struct ProgramParams { enum eLastStage { STAGE_PARSE, STAGE_EXPAND, STAGE_RESOLVE, STAGE_TYPECK, STAGE_BORROWCK, STAGE_MIR, STAGE_ALL, } last_stage = STAGE_ALL; const char *infile = NULL; ::std::string outfile; const char *crate_path = "."; ProgramParams(int argc, char *argv[]); }; template <typename Rv, typename Fcn> Rv CompilePhase(const char *name, Fcn f) { ::std::cout << name << ": V V V" << ::std::endl; g_cur_phase = name; auto start = clock(); auto rv = f(); auto end = clock(); g_cur_phase = ""; ::std::cout <<"(" << ::std::fixed << ::std::setprecision(2) << static_cast<double>(end - start) / static_cast<double>(CLOCKS_PER_SEC) << " s) "; ::std::cout << name << ": DONE"; ::std::cout << ::std::endl; return rv; } template <typename Fcn> void CompilePhaseV(const char *name, Fcn f) { CompilePhase<int>(name, [&]() { f(); return 0; }); } /// main! int main(int argc, char *argv[]) { init_debug_list(); ProgramParams params(argc, argv); // Set up cfg values // TODO: Target spec Cfg_SetFlag("linux"); Cfg_SetValue("target_pointer_width", "64"); Cfg_SetValue("target_endian", "little"); Cfg_SetValue("target_arch", "x86-noasm"); // TODO: asm! macro Cfg_SetValueCb("target_has_atomic", [](const ::std::string& s) { if(s == "8") return true; // Has an atomic byte if(s == "ptr") return true; // Has an atomic pointer-sized value return false; }); Cfg_SetValueCb("target_feature", [](const ::std::string& s) { return false; }); try { // Parse the crate into AST AST::Crate crate = CompilePhase<AST::Crate>("Parse", [&]() { return Parse_Crate(params.infile); }); if( params.last_stage == ProgramParams::STAGE_PARSE ) { return 0; } // Load external crates. CompilePhaseV("LoadCrates", [&]() { crate.load_externs(); }); // Iterate all items in the AST, applying syntax extensions CompilePhaseV("Expand", [&]() { Expand(crate); }); // XXX: Dump crate before resolve CompilePhaseV("Temp output - Parsed", [&]() { Dump_Rust( FMT(params.outfile << "_0_pp.rs").c_str(), crate ); }); if( params.last_stage == ProgramParams::STAGE_EXPAND ) { return 0; } // Resolve names to be absolute names (include references to the relevant struct/global/function) // - This does name checking on types and free functions. // - Resolves all identifiers/paths to references CompilePhaseV("Resolve", [&]() { Resolve_Use(crate); // - Absolutise and resolve use statements Resolve_Index(crate); // - Build up a per-module index of avalable names (faster and simpler later resolve) Resolve_Absolutise(crate); // - Convert all paths to Absolute or UFCS, and resolve variables }); // XXX: Dump crate before typecheck CompilePhaseV("Temp output - Resolved", [&]() { Dump_Rust( FMT(params.outfile << "_1_res.rs").c_str(), crate ); }); if( params.last_stage == ProgramParams::STAGE_RESOLVE ) { return 0; } // Extract the crate type and name from the crate attributes auto crate_type = crate.m_crate_type; if( crate_type == ::AST::Crate::Type::Unknown ) { // Assume to be executable crate_type = ::AST::Crate::Type::Executable; } auto crate_name = crate.m_crate_name; if( crate_name == "" ) { // TODO: Take the crate name from the input filename } // -------------------------------------- // HIR Section // -------------------------------------- // Construc the HIR from the AST ::HIR::CratePtr hir_crate = CompilePhase< ::HIR::CratePtr>("HIR Lower", [&]() { return LowerHIR_FromAST(mv$( crate )); }); // Deallocate the original crate crate = ::AST::Crate(); // Replace type aliases (`type`) into the actual type CompilePhaseV("Resolve Type Aliases", [&]() { ConvertHIR_ExpandAliases(*hir_crate); }); CompilePhaseV("Resolve Bind", [&]() { ConvertHIR_Bind(*hir_crate); }); CompilePhaseV("Resolve UFCS paths", [&]() { ConvertHIR_ResolveUFCS(*hir_crate); }); CompilePhaseV("Constant Evaluate", [&]() { ConvertHIR_ConstantEvaluate(*hir_crate); }); // === Type checking === // - This can recurse and call the MIR lower to evaluate constants // Check outer items first (types of constants/functions/statics/impls/...) // - Doesn't do any expressions except those in types CompilePhaseV("Typecheck Outer", [&]() { Typecheck_ModuleLevel(*hir_crate); }); // Check the rest of the expressions (including function bodies) CompilePhaseV("Typecheck Expressions", [&]() { Typecheck_Expressions(*hir_crate); }); // === HIR Expansion === // Annotate how each node's result is used CompilePhaseV("Expand HIR Annotate", [&]() { HIR_Expand_AnnotateUsage(*hir_crate); }); // - Now that all types are known, closures can be desugared CompilePhaseV("Expand HIR Closures", [&]() { HIR_Expand_Closures(*hir_crate); }); // - And calls can be turned into UFCS CompilePhaseV("Expand HIR Calls", [&]() { HIR_Expand_UfcsEverything(*hir_crate); }); CompilePhaseV("Expand HIR Reborrows", [&]() { HIR_Expand_Reborrows(*hir_crate); }); // - Ensure that typeck worked (including Fn trait call insertion etc) CompilePhaseV("Typecheck Expressions (validate)", [&]() { Typecheck_Expressions_Validate(*hir_crate); }); CompilePhaseV("Dump HIR", [&]() { ::std::ofstream os (FMT(params.outfile << "_2_hir.rs")); HIR_Dump( os, *hir_crate ); }); if( params.last_stage == ProgramParams::STAGE_TYPECK ) { return 0; } // Lower expressions into MIR CompilePhaseV("Lower MIR", [&]() { HIR_GenerateMIR(*hir_crate); }); // Validate the MIR CompilePhaseV("MIR Validate", [&]() { MIR_CheckCrate(*hir_crate); }); CompilePhaseV("Dump MIR", [&]() { ::std::ofstream os (FMT(params.outfile << "_3_mir.rs")); MIR_Dump( os, *hir_crate ); }); if( params.last_stage == ProgramParams::STAGE_MIR ) { return 0; } // Optimise the MIR //CompilePhaseV("Dump MIR", [&]() { // ::std::ofstream os (FMT(params.outfile << "_4_mir_opt.rs")); // MIR_Dump( os, *hir_crate ); // }); // TODO: Pass to mark items that are // - Signature Exportable (public) // - MIR Exportable (public generic, #[inline], or used by a either of those) // - Require codegen (public or used by an exported function) // Generate code for non-generic public items (if requested) switch( crate_type ) { case ::AST::Crate::Type::Unknown: // ERROR? break; case ::AST::Crate::Type::RustLib: // Save a loadable HIR dump CompilePhaseV("HIR Serialise", [&]() { //HIR_Serialise(params.outfile + ".meta", *hir_crate); HIR_Serialise(params.outfile, *hir_crate); }); // Generate a .o //HIR_Codegen(params.outfile + ".o", *hir_crate); // Link into a .rlib break; case ::AST::Crate::Type::RustDylib: // Save a loadable HIR dump // Generate a .so/.dll break; case ::AST::Crate::Type::CDylib: // Generate a .so/.dll break; case ::AST::Crate::Type::Executable: // Generate a binary break; } } catch(unsigned int) {} //catch(const CompileError::Base& e) //{ // ::std::cerr << "Parser Error: " << e.what() << ::std::endl; // return 2; //} //catch(const ::std::exception& e) //{ // ::std::cerr << "Misc Error: " << e.what() << ::std::endl; // return 2; //} //catch(const char* e) //{ // ::std::cerr << "Internal Compiler Error: " << e << ::std::endl; // return 2; //} return 0; } ProgramParams::ProgramParams(int argc, char *argv[]) { // Hacky command-line parsing for( int i = 1; i < argc; i ++ ) { const char* arg = argv[i]; if( arg[0] != '-' ) { this->infile = arg; } else if( arg[1] != '-' ) { arg ++; // eat '-' for( ; *arg; arg ++ ) { switch(*arg) { // "-o <file>" : Set output file case 'o': if( i == argc - 1 ) { // TODO: BAIL! exit(1); } this->outfile = argv[++i]; break; default: exit(1); } } } else { if( strcmp(arg, "--crate-path") == 0 ) { if( i == argc - 1 ) { // TODO: BAIL! exit(1); } this->crate_path = argv[++i]; } else if( strcmp(arg, "--stop-after") == 0 ) { if( i == argc - 1 ) { // TODO: BAIL! exit(1); } arg = argv[++i]; if( strcmp(arg, "parse") == 0 ) this->last_stage = STAGE_PARSE; else { ::std::cerr << "Unknown argument to --stop-after : '" << arg << "'" << ::std::endl; exit(1); } } else { ::std::cerr << "Unknown option '" << arg << "'" << ::std::endl; exit(1); } } } if( this->outfile == "" ) { this->outfile = (::std::string)this->infile + ".o"; } } <commit_msg>Main - Split resolve into three logged passes<commit_after>/* * MRustC - Rust Compiler * - By John Hodge (Mutabah/thePowersGang) * * main.cpp * - Compiler Entrypoint */ #include <iostream> #include <iomanip> #include <string> #include <set> #include "parse/lex.hpp" #include "parse/parseerror.hpp" #include "ast/ast.hpp" #include "ast/crate.hpp" #include <serialiser_texttree.hpp> #include <cstring> #include <main_bindings.hpp> #include "resolve/main_bindings.hpp" #include "hir/main_bindings.hpp" #include "hir_conv/main_bindings.hpp" #include "hir_typeck/main_bindings.hpp" #include "hir_expand/main_bindings.hpp" #include "mir/main_bindings.hpp" #include "expand/cfg.hpp" int g_debug_indent_level = 0; ::std::string g_cur_phase; ::std::set< ::std::string> g_debug_disable_map; void init_debug_list() { g_debug_disable_map.insert( "Parse" ); g_debug_disable_map.insert( "Expand" ); g_debug_disable_map.insert( "Resolve Use" ); g_debug_disable_map.insert( "Resolve Index" ); g_debug_disable_map.insert( "Resolve Absolute" ); g_debug_disable_map.insert( "HIR Lower" ); g_debug_disable_map.insert( "Resolve Type Aliases" ); g_debug_disable_map.insert( "Resolve Bind" ); g_debug_disable_map.insert( "Resolve UFCS paths" ); g_debug_disable_map.insert( "Constant Evaluate" ); g_debug_disable_map.insert( "Typecheck Outer"); g_debug_disable_map.insert( "Typecheck Expressions" ); g_debug_disable_map.insert( "Expand HIR Annotate" ); g_debug_disable_map.insert( "Expand HIR Closures" ); g_debug_disable_map.insert( "Expand HIR Calls" ); g_debug_disable_map.insert( "Expand HIR Reborrows" ); g_debug_disable_map.insert( "Typecheck Expressions (validate)" ); g_debug_disable_map.insert( "Dump HIR" ); g_debug_disable_map.insert( "Lower MIR" ); g_debug_disable_map.insert( "MIR Validate" ); g_debug_disable_map.insert( "Dump MIR" ); g_debug_disable_map.insert( "HIR Serialise" ); } bool debug_enabled() { // TODO: Have an explicit enable list? if( g_debug_disable_map.count(g_cur_phase) != 0 ) { return false; } else { return true; } } ::std::ostream& debug_output(int indent, const char* function) { return ::std::cout << g_cur_phase << "- " << RepeatLitStr { " ", indent } << function << ": "; } struct ProgramParams { enum eLastStage { STAGE_PARSE, STAGE_EXPAND, STAGE_RESOLVE, STAGE_TYPECK, STAGE_BORROWCK, STAGE_MIR, STAGE_ALL, } last_stage = STAGE_ALL; const char *infile = NULL; ::std::string outfile; const char *crate_path = "."; ProgramParams(int argc, char *argv[]); }; template <typename Rv, typename Fcn> Rv CompilePhase(const char *name, Fcn f) { ::std::cout << name << ": V V V" << ::std::endl; g_cur_phase = name; auto start = clock(); auto rv = f(); auto end = clock(); g_cur_phase = ""; ::std::cout <<"(" << ::std::fixed << ::std::setprecision(2) << static_cast<double>(end - start) / static_cast<double>(CLOCKS_PER_SEC) << " s) "; ::std::cout << name << ": DONE"; ::std::cout << ::std::endl; return rv; } template <typename Fcn> void CompilePhaseV(const char *name, Fcn f) { CompilePhase<int>(name, [&]() { f(); return 0; }); } /// main! int main(int argc, char *argv[]) { init_debug_list(); ProgramParams params(argc, argv); // Set up cfg values // TODO: Target spec Cfg_SetFlag("linux"); Cfg_SetValue("target_pointer_width", "64"); Cfg_SetValue("target_endian", "little"); Cfg_SetValue("target_arch", "x86-noasm"); // TODO: asm! macro Cfg_SetValueCb("target_has_atomic", [](const ::std::string& s) { if(s == "8") return true; // Has an atomic byte if(s == "ptr") return true; // Has an atomic pointer-sized value return false; }); Cfg_SetValueCb("target_feature", [](const ::std::string& s) { return false; }); try { // Parse the crate into AST AST::Crate crate = CompilePhase<AST::Crate>("Parse", [&]() { return Parse_Crate(params.infile); }); if( params.last_stage == ProgramParams::STAGE_PARSE ) { return 0; } // Load external crates. CompilePhaseV("LoadCrates", [&]() { crate.load_externs(); }); // Iterate all items in the AST, applying syntax extensions CompilePhaseV("Expand", [&]() { Expand(crate); }); // XXX: Dump crate before resolve CompilePhaseV("Temp output - Parsed", [&]() { Dump_Rust( FMT(params.outfile << "_0_pp.rs").c_str(), crate ); }); if( params.last_stage == ProgramParams::STAGE_EXPAND ) { return 0; } // Resolve names to be absolute names (include references to the relevant struct/global/function) // - This does name checking on types and free functions. // - Resolves all identifiers/paths to references CompilePhaseV("Resolve Use", [&]() { Resolve_Use(crate); // - Absolutise and resolve use statements }); CompilePhaseV("Resolve Index", [&]() { Resolve_Index(crate); // - Build up a per-module index of avalable names (faster and simpler later resolve) }); CompilePhaseV("Resolve Absolute", [&]() { Resolve_Absolutise(crate); // - Convert all paths to Absolute or UFCS, and resolve variables }); // XXX: Dump crate before HIR CompilePhaseV("Temp output - Resolved", [&]() { Dump_Rust( FMT(params.outfile << "_1_res.rs").c_str(), crate ); }); if( params.last_stage == ProgramParams::STAGE_RESOLVE ) { return 0; } // Extract the crate type and name from the crate attributes auto crate_type = crate.m_crate_type; if( crate_type == ::AST::Crate::Type::Unknown ) { // Assume to be executable crate_type = ::AST::Crate::Type::Executable; } auto crate_name = crate.m_crate_name; if( crate_name == "" ) { // TODO: Take the crate name from the input filename } // -------------------------------------- // HIR Section // -------------------------------------- // Construc the HIR from the AST ::HIR::CratePtr hir_crate = CompilePhase< ::HIR::CratePtr>("HIR Lower", [&]() { return LowerHIR_FromAST(mv$( crate )); }); // Deallocate the original crate crate = ::AST::Crate(); // Replace type aliases (`type`) into the actual type CompilePhaseV("Resolve Type Aliases", [&]() { ConvertHIR_ExpandAliases(*hir_crate); }); CompilePhaseV("Resolve Bind", [&]() { ConvertHIR_Bind(*hir_crate); }); CompilePhaseV("Resolve UFCS paths", [&]() { ConvertHIR_ResolveUFCS(*hir_crate); }); CompilePhaseV("Constant Evaluate", [&]() { ConvertHIR_ConstantEvaluate(*hir_crate); }); // === Type checking === // - This can recurse and call the MIR lower to evaluate constants // Check outer items first (types of constants/functions/statics/impls/...) // - Doesn't do any expressions except those in types CompilePhaseV("Typecheck Outer", [&]() { Typecheck_ModuleLevel(*hir_crate); }); // Check the rest of the expressions (including function bodies) CompilePhaseV("Typecheck Expressions", [&]() { Typecheck_Expressions(*hir_crate); }); // === HIR Expansion === // Annotate how each node's result is used CompilePhaseV("Expand HIR Annotate", [&]() { HIR_Expand_AnnotateUsage(*hir_crate); }); // - Now that all types are known, closures can be desugared CompilePhaseV("Expand HIR Closures", [&]() { HIR_Expand_Closures(*hir_crate); }); // - And calls can be turned into UFCS CompilePhaseV("Expand HIR Calls", [&]() { HIR_Expand_UfcsEverything(*hir_crate); }); CompilePhaseV("Expand HIR Reborrows", [&]() { HIR_Expand_Reborrows(*hir_crate); }); // - Ensure that typeck worked (including Fn trait call insertion etc) CompilePhaseV("Typecheck Expressions (validate)", [&]() { Typecheck_Expressions_Validate(*hir_crate); }); CompilePhaseV("Dump HIR", [&]() { ::std::ofstream os (FMT(params.outfile << "_2_hir.rs")); HIR_Dump( os, *hir_crate ); }); if( params.last_stage == ProgramParams::STAGE_TYPECK ) { return 0; } // Lower expressions into MIR CompilePhaseV("Lower MIR", [&]() { HIR_GenerateMIR(*hir_crate); }); // Validate the MIR CompilePhaseV("MIR Validate", [&]() { MIR_CheckCrate(*hir_crate); }); CompilePhaseV("Dump MIR", [&]() { ::std::ofstream os (FMT(params.outfile << "_3_mir.rs")); MIR_Dump( os, *hir_crate ); }); if( params.last_stage == ProgramParams::STAGE_MIR ) { return 0; } // Optimise the MIR //CompilePhaseV("Dump MIR", [&]() { // ::std::ofstream os (FMT(params.outfile << "_4_mir_opt.rs")); // MIR_Dump( os, *hir_crate ); // }); // TODO: Pass to mark items that are // - Signature Exportable (public) // - MIR Exportable (public generic, #[inline], or used by a either of those) // - Require codegen (public or used by an exported function) // Generate code for non-generic public items (if requested) switch( crate_type ) { case ::AST::Crate::Type::Unknown: // ERROR? break; case ::AST::Crate::Type::RustLib: // Save a loadable HIR dump CompilePhaseV("HIR Serialise", [&]() { //HIR_Serialise(params.outfile + ".meta", *hir_crate); HIR_Serialise(params.outfile, *hir_crate); }); // Generate a .o //HIR_Codegen(params.outfile + ".o", *hir_crate); // Link into a .rlib break; case ::AST::Crate::Type::RustDylib: // Save a loadable HIR dump // Generate a .so/.dll break; case ::AST::Crate::Type::CDylib: // Generate a .so/.dll break; case ::AST::Crate::Type::Executable: // Generate a binary break; } } catch(unsigned int) {} //catch(const CompileError::Base& e) //{ // ::std::cerr << "Parser Error: " << e.what() << ::std::endl; // return 2; //} //catch(const ::std::exception& e) //{ // ::std::cerr << "Misc Error: " << e.what() << ::std::endl; // return 2; //} //catch(const char* e) //{ // ::std::cerr << "Internal Compiler Error: " << e << ::std::endl; // return 2; //} return 0; } ProgramParams::ProgramParams(int argc, char *argv[]) { // Hacky command-line parsing for( int i = 1; i < argc; i ++ ) { const char* arg = argv[i]; if( arg[0] != '-' ) { this->infile = arg; } else if( arg[1] != '-' ) { arg ++; // eat '-' for( ; *arg; arg ++ ) { switch(*arg) { // "-o <file>" : Set output file case 'o': if( i == argc - 1 ) { // TODO: BAIL! exit(1); } this->outfile = argv[++i]; break; default: exit(1); } } } else { if( strcmp(arg, "--crate-path") == 0 ) { if( i == argc - 1 ) { // TODO: BAIL! exit(1); } this->crate_path = argv[++i]; } else if( strcmp(arg, "--stop-after") == 0 ) { if( i == argc - 1 ) { // TODO: BAIL! exit(1); } arg = argv[++i]; if( strcmp(arg, "parse") == 0 ) this->last_stage = STAGE_PARSE; else { ::std::cerr << "Unknown argument to --stop-after : '" << arg << "'" << ::std::endl; exit(1); } } else { ::std::cerr << "Unknown option '" << arg << "'" << ::std::endl; exit(1); } } } if( this->outfile == "" ) { this->outfile = (::std::string)this->infile + ".o"; } } <|endoftext|>
<commit_before>#include <iostream> #include <SDL2/SDL.h> #include <mosquitto.h> #include <math.h> void message_callback(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *message) { //Simply print the data to standard out. if(message->payloadlen) { //Data is binary, but we cast it to a string because we're crazy. std::cout << message->topic << ": " << (const char*)message->payload << std::endl; } } void connect_callback_log(int resultCode) { switch( resultCode ) { case MOSQ_ERR_SUCCESS: std::cout << "OK" << std::endl; break; case MOSQ_ERR_INVAL: std::cout << "Invalid parameter" << std::endl; break; default: break; } } void connect_callback(struct mosquitto *mosq, void *userdata, int result) { if(result == MOSQ_ERR_SUCCESS) { std::cout << "Connected to broker." << std::endl; //Subscribe to broker information topics on successful connect. mosquitto_subscribe(mosq, NULL, "$SYS/#", 2); int res = mosquitto_subscribe(mosq, NULL, "$SYS/recruitment/ciot/state", 2); std::cout << "Connected to sensor state: "; connect_callback_log( res ); res = mosquitto_subscribe(mosq, NULL, "recruitment/ciot/sensor1", 2); std::cout << "Connected to sensor value: "; connect_callback_log( res ); } else { std::cout << "Failed to connect to broker :(" << std::endl; } } //Draws a simple bar chart with a blue background in the center of the screen. void draw(SDL_Renderer* renderer, float delta_time) { static float time = 0; time += delta_time; SDL_SetRenderDrawColor(renderer, 0x00, 0x9f, 0xe3, 0xFF ); SDL_Rect rect = {100, 240, 600, 120}; //Background SDL_RenderFillRect(renderer, &rect); //Bars int count = 6; int padding = 2; int start_x = 120; int y = 340; int width = (rect.w - (start_x - rect.x) * 2 - padding * (count - 1))/count; //Draw the bars with a simple sine-wave modulation on height and transparency. for (int i = 0; i < count; ++i) { float offset = ((float)sin(time * 4 + i) + 1.0f)/2.f; int height = offset * 20 + 20; SDL_Rect bar = {start_x, y - height, width, height}; SDL_SetRenderDrawColor(renderer, 0xff, 0xff, 0xff, (unsigned char)(255 * (offset/2 + 0.5f))); SDL_RenderFillRect(renderer, &bar); start_x += padding + width; } } int main(int, char**) { SDL_Window *window = 0; SDL_Renderer *renderer = 0; int code = 0; struct mosquitto* mosq; bool run = true; unsigned int t0 = 0, t1 = 0; mosquitto_lib_init(); if((mosq = mosquitto_new(0, true, 0)) == 0) { std::cout << "Failed to initialize mosquitto." << std::endl; code = 1; goto end; } mosquitto_connect_callback_set(mosq, connect_callback); mosquitto_message_callback_set(mosq, message_callback); //Init SDL if (SDL_Init(SDL_INIT_VIDEO) != 0){ std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl; code = 1; goto end; } //Create a window and renderer attached to it. window = SDL_CreateWindow("SDL Skeleton", 100, 100, 800, 600, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL); renderer = SDL_CreateRenderer(window, 0, SDL_RENDERER_PRESENTVSYNC); if(!window || !renderer) { std::cout << "SDL_CreateWindow or SDL_CreateRenderer Error: " << SDL_GetError() << std::endl; code = 1; goto end; } SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND); //Attempt mosquitto connection to local host. mosquitto_connect_async(mosq, "amee.interaktionsbyran.se", 1883, 60); //Start the mosquitto network thread. if(mosquitto_loop_start(mosq) != MOSQ_ERR_SUCCESS) { std::cout << "Failed mosquitto init " << mosq << std::endl; code = 1; goto end; } //Block untill the user closes the window SDL_Event e; while (run) { t1 = SDL_GetTicks(); float delta_time = (float)(t1 - t0)/1000.f; // check if the devices is sleeping at recruitment/ciot/state // wake up the device at recruitment/ciot/wake = 1 // ask for the data at recruitment/ciot/sensor1 while( SDL_PollEvent( &e ) != 0) { if( e.type == SDL_QUIT ) { run = false; break; } } //Clear buffer. SDL_SetRenderDrawColor(renderer, 0xff, 0xff, 0xff, 0xff); SDL_RenderClear(renderer); draw(renderer, delta_time); SDL_RenderPresent(renderer); t0 = t1; } end: SDL_Quit(); //Cleanup mqtt mosquitto_loop_stop(mosq, true); mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return code; } <commit_msg>adding headers, publisher callback<commit_after>#include <iostream> #include <SDL2/SDL.h> #include <mosquitto.h> #include <math.h> void message_callback(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *message); void log_result(int resultCode); void connect_callback(struct mosquitto *mosq, void *userdata, int result); void draw(SDL_Renderer* renderer, float delta_time); int main(int, char**); void message_callback(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *message) { //Simply print the data to standard out. if(message->payloadlen) { //Data is binary, but we cast it to a string because we're crazy. std::cout << message->topic << ": " << (const char*)message->payload << std::endl; } } void log_result(int resultCode) { switch( resultCode ) { case MOSQ_ERR_SUCCESS: std::cout << "OK" << std::endl; break; case MOSQ_ERR_INVAL: std::cout << "Invalid parameter" << std::endl; break; default: std::cout << "Error:" << resultCode << std::endl; break; } } void connect_callback(struct mosquitto *mosq, void *userdata, int result) { if(result == MOSQ_ERR_SUCCESS) { std::cout << "Connected to broker." << std::endl; //Subscribe to broker information topics on successful connect. //mosquitto_subscribe(mosq, NULL, "$SYS/#", 2); int res = mosquitto_subscribe(mosq, NULL, "recruitment/ciot/state", 2); std::cout << "Connected to sensor state: "; log_result( res ); res = mosquitto_subscribe(mosq, NULL, "recruitment/ciot/sensor1", 2); std::cout << "Connected to sensor value: "; log_result( res ); } else { std::cout << "Failed to connect to broker :(" << std::endl; } } void publish_callback(struct mosquitto *mosq, void *userdata, int result) { std::cout << "Sensor wakeup sent: "; log_result( result ); } //Draws a simple bar chart with a blue background in the center of the screen. void draw(SDL_Renderer* renderer, float delta_time) { static float time = 0; time += delta_time; SDL_SetRenderDrawColor(renderer, 0x00, 0x9f, 0xe3, 0xFF ); SDL_Rect rect = {100, 240, 600, 120}; //Background SDL_RenderFillRect(renderer, &rect); //Bars int count = 6; int padding = 2; int start_x = 120; int y = 340; int width = (rect.w - (start_x - rect.x) * 2 - padding * (count - 1))/count; //Draw the bars with a simple sine-wave modulation on height and transparency. for (int i = 0; i < count; ++i) { float offset = ((float)sin(time * 4 + i) + 1.0f)/2.f; int height = offset * 20 + 20; SDL_Rect bar = {start_x, y - height, width, height}; SDL_SetRenderDrawColor(renderer, 0xff, 0xff, 0xff, (unsigned char)(255 * (offset/2 + 0.5f))); SDL_RenderFillRect(renderer, &bar); start_x += padding + width; } } int main(int, char**) { SDL_Window *window = 0; SDL_Renderer *renderer = 0; int code = 0; struct mosquitto* mosq; bool run = true; unsigned int t0 = 0, t1 = 0; mosquitto_lib_init(); if((mosq = mosquitto_new(0, true, 0)) == 0) { std::cout << "Failed to initialize mosquitto." << std::endl; code = 1; goto end; } mosquitto_connect_callback_set(mosq, connect_callback); mosquitto_message_callback_set(mosq, message_callback); mosquitto_publish_callback_set(mosq, publish_callback); //Init SDL if (SDL_Init(SDL_INIT_VIDEO) != 0){ std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl; code = 1; goto end; } //Create a window and renderer attached to it. window = SDL_CreateWindow("SDL Skeleton", 100, 100, 800, 600, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL); renderer = SDL_CreateRenderer(window, 0, SDL_RENDERER_PRESENTVSYNC); if(!window || !renderer) { std::cout << "SDL_CreateWindow or SDL_CreateRenderer Error: " << SDL_GetError() << std::endl; code = 1; goto end; } SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND); //Attempt mosquitto connection to local host. mosquitto_connect_async(mosq, "amee.interaktionsbyran.se", 1883, 60); //Start the mosquitto network thread. if(mosquitto_loop_start(mosq) != MOSQ_ERR_SUCCESS) { std::cout << "Failed mosquitto init " << mosq << std::endl; code = 1; goto end; } //Block untill the user closes the window SDL_Event e; while (run) { t1 = SDL_GetTicks(); float delta_time = (float)(t1 - t0)/1000.f; // check if the devices is sleeping at recruitment/ciot/state // wake up the device at recruitment/ciot/wake = 1 // ask for the data at recruitment/ciot/sensor1 while( SDL_PollEvent( &e ) != 0) { if( e.type == SDL_QUIT ) { run = false; break; } } //Clear buffer. SDL_SetRenderDrawColor(renderer, 0xff, 0xff, 0xff, 0xff); SDL_RenderClear(renderer); draw(renderer, delta_time); SDL_RenderPresent(renderer); t0 = t1; } end: SDL_Quit(); //Cleanup mqtt mosquitto_loop_stop(mosq, true); mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return code; } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include <fstream> #include <sstream> #include <cstdlib> #include <vector> #include <thread> #include <future> #include "common/log.h" #include "gfx/gl/driver.h" #include "gfx/camera.h" #include "gfx/mesh_chunk.h" #include "gfx/idriver_ui_adapter.h" #include "gfx/support/load_wavefront.h" #include "gfx/support/mesh_conversion.h" #include "gfx/support/generate_aabb.h" #include "gfx/support/write_data_to_mesh.h" #include "gfx/support/texture_load.h" #include "gfx/support/software_texture.h" #include "gfx/support/unproject.h" #include "ui/load.h" #include "ui/freetype_renderer.h" #include "ui/mouse_logic.h" #include "ui/simple_controller.h" #include "map/map.h" #include "map/water.h" #include "map/terrain.h" #include "stratlib/player_state.h" #include "glad/glad.h" #include "glfw3.h" #define GLM_FORCE_RADIANS #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "uv.h" #define CATCH_CONFIG_RUNNER #include "catch/catch.hpp" glm::vec4 project_point(glm::vec4 pt, glm::mat4 const& model, glm::mat4 const& view, glm::mat4 const& proj) noexcept { pt = proj * view * model * pt; pt /= pt.w; return pt; } void scroll_callback(GLFWwindow* window, double, double deltay) { auto cam_ptr = glfwGetWindowUserPointer(window); auto& camera = *((game::gfx::Camera*) cam_ptr); camera.fp.pos += -deltay; } game::ui::Mouse_State gen_mouse_state(GLFWwindow* w) { game::ui::Mouse_State ret; ret.button_down =glfwGetMouseButton(w, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS; game::Vec<double> pos; glfwGetCursorPos(w, &pos.x, &pos.y); ret.position = game::vec_cast<int>(pos); return ret; } void log_gl_limits(game::Log_Severity s) noexcept { GLint i = 0; glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &i); log(s, "GL_MAX_ELEMENTS_VERTICES: %", i); } struct Command_Options { }; Command_Options parse_command_line(int argc, char**) { Command_Options opt; for(int i = 0; i < argc; ++i) { //auto option = argv[i]; } return opt; } int main(int argc, char** argv) { using namespace game; set_log_level(Log_Severity::Debug); uv_chdir("assets/"); // Initialize logger. Scoped_Log_Init log_init_raii_lock{}; // Parse command line arguments. auto options = parse_command_line(argc - 1, argv+1); // Init glfw. if(!glfwInit()) return EXIT_FAILURE; auto window = glfwCreateWindow(1000, 1000, "Hello World", NULL, NULL); if(!window) { glfwTerminate(); return EXIT_FAILURE; } // Init context + load gl functions. glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); // Log glfw version. log_i("Initialized GLFW %", glfwGetVersionString()); int maj = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR); int min = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR); int rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION); // Log GL profile. log_i("OpenGL core profile %.%.%", maj, min, rev); { // Make an OpenGL driver. gfx::gl::Driver driver{Vec<int>{1000, 1000}}; // Load our default shader. auto default_shader = driver.make_shader_repr(); default_shader->load_vertex_part("shader/basic/v"); default_shader->load_fragment_part("shader/basic/f"); default_shader->set_projection_name("proj"); default_shader->set_view_name("view"); default_shader->set_model_name("model"); default_shader->set_sampler_name("tex"); default_shader->set_diffuse_name("dif"); driver.use_shader(*default_shader); default_shader->set_sampler(0); // Load our textures. auto grass_tex = driver.make_texture_repr(); load_png("tex/grass.png", *grass_tex); // Make an isometric camera. auto cam = gfx::make_isometric_camera(); // Load the image Software_Texture terrain_image; load_png("map/default.png", terrain_image); // Convert it into a heightmap Maybe_Owned<Mesh> terrain = driver.make_mesh_repr(); auto terrain_heightmap = make_heightmap_from_image(terrain_image); auto terrain_data = make_terrain_mesh(terrain_heightmap, {20, 20}, .001f, .01); auto terrain_model = glm::scale(glm::mat4(1.0f),glm::vec3(5.0f, 1.0f, 5.0f)); gfx::allocate_mesh_buffers(terrain_data.mesh, *terrain); gfx::write_data_to_mesh(terrain_data.mesh, ref_mo(terrain)); gfx::format_mesh_buffers(*terrain); terrain->set_primitive_type(Primitive_Type::Triangle); // Map + structures. Maybe_Owned<Mesh> structure_mesh = driver.make_mesh_repr(); Map map({1000, 1000}); // <-- Map size for now strat::Player_State player_state{strat::Player_State_Type::Nothing}; auto structures_future = std::async(std::launch::async, load_structures,"structure/structures.json", ref_mo(structure_mesh)); int fps = 0; int time = glfwGetTime(); // Set up some pre-rendering state. driver.clear_color_value(Color{0x55, 0x66, 0x77}); driver.clear_depth_value(1.0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_CULL_FACE); // Our quick hack to avoid splitting into multiple functions and dealing // either with global variables or like a bound struct or something. bool has_clicked_down = false; // Load our ui gfx::IDriver_UI_Adapter ui_adapter{driver}; ui::Freetype_Renderer freetype_font; auto ui_load_params = ui::Load_Params{freetype_font, ui_adapter}; auto hud = ui::load("ui/hud.json", ui_load_params); auto controller = ui::Simple_Controller{}; auto structures = structures_future.get(); hud->find_child_r("build_house")->add_click_listener([&](auto const& pt) { player_state.type = strat::Player_State_Type::Building; player_state.building.to_build = &structures[0]; }); hud->find_child_r("build_gvn_build")->add_click_listener([&](auto const& pt) { player_state.type = strat::Player_State_Type::Building; player_state.building.to_build = &structures[1]; }); hud->layout(driver.window_extents()); controller.add_drag_listener([&](auto const& np, auto const& op) { // pan auto movement = vec_cast<float>(np - op); movement /= -75; glm::vec4 move_vec(movement.x, 0.0f, movement.y, 0.0f); move_vec = glm::inverse(camera_view_matrix(cam)) * move_vec; cam.fp.pos.x += move_vec.x; cam.fp.pos.z += move_vec.z; }); glfwSetWindowUserPointer(window, &cam); glfwSetScrollCallback(window, scroll_callback); //water_obj.material->diffuse_color = Color{0xaa, 0xaa, 0xff}; while(!glfwWindowShouldClose(window)) { ++fps; glfwPollEvents(); // Clear the screen and render the terrain. driver.clear(); use_camera(driver, cam); driver.bind_texture(*grass_tex, 0); default_shader->set_diffuse(colors::white); default_shader->set_model(terrain_model); // Render the terrain before we calculate the depth of the mouse position. terrain->draw_elements(0, terrain_data.mesh.elements.size()); auto mouse_state = gen_mouse_state(window); auto map_coord = gfx::unproject_screen(driver, cam, terrain_model, mouse_state.position); log_i("% %", map_coord.x, map_coord.z); controller.step(hud, mouse_state); { ui::Draw_Scoped_Lock scoped_draw_lock{ui_adapter}; hud->render(ui_adapter); } glfwSwapBuffers(window); if(int(glfwGetTime()) != time) { time = glfwGetTime(); log_d("fps: %", fps); fps = 0; } flush_log(); } } glfwTerminate(); return 0; } <commit_msg>Added proper panning based on depth.<commit_after>/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include <fstream> #include <sstream> #include <cstdlib> #include <vector> #include <thread> #include <future> #include "common/log.h" #include "gfx/gl/driver.h" #include "gfx/camera.h" #include "gfx/mesh_chunk.h" #include "gfx/idriver_ui_adapter.h" #include "gfx/support/load_wavefront.h" #include "gfx/support/mesh_conversion.h" #include "gfx/support/generate_aabb.h" #include "gfx/support/write_data_to_mesh.h" #include "gfx/support/texture_load.h" #include "gfx/support/software_texture.h" #include "gfx/support/unproject.h" #include "ui/load.h" #include "ui/freetype_renderer.h" #include "ui/mouse_logic.h" #include "ui/simple_controller.h" #include "map/map.h" #include "map/water.h" #include "map/terrain.h" #include "stratlib/player_state.h" #include "glad/glad.h" #include "glfw3.h" #define GLM_FORCE_RADIANS #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "uv.h" #define CATCH_CONFIG_RUNNER #include "catch/catch.hpp" glm::vec4 project_point(glm::vec4 pt, glm::mat4 const& model, glm::mat4 const& view, glm::mat4 const& proj) noexcept { pt = proj * view * model * pt; pt /= pt.w; return pt; } void scroll_callback(GLFWwindow* window, double, double deltay) { auto cam_ptr = glfwGetWindowUserPointer(window); auto& camera = *((game::gfx::Camera*) cam_ptr); camera.fp.pos += -deltay; } game::ui::Mouse_State gen_mouse_state(GLFWwindow* w) { game::ui::Mouse_State ret; ret.button_down =glfwGetMouseButton(w, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS; game::Vec<double> pos; glfwGetCursorPos(w, &pos.x, &pos.y); ret.position = game::vec_cast<int>(pos); return ret; } void log_gl_limits(game::Log_Severity s) noexcept { GLint i = 0; glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &i); log(s, "GL_MAX_ELEMENTS_VERTICES: %", i); } struct Command_Options { }; Command_Options parse_command_line(int argc, char**) { Command_Options opt; for(int i = 0; i < argc; ++i) { //auto option = argv[i]; } return opt; } int main(int argc, char** argv) { using namespace game; set_log_level(Log_Severity::Debug); uv_chdir("assets/"); // Initialize logger. Scoped_Log_Init log_init_raii_lock{}; // Parse command line arguments. auto options = parse_command_line(argc - 1, argv+1); // Init glfw. if(!glfwInit()) return EXIT_FAILURE; auto window = glfwCreateWindow(1000, 1000, "Hello World", NULL, NULL); if(!window) { glfwTerminate(); return EXIT_FAILURE; } // Init context + load gl functions. glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); // Log glfw version. log_i("Initialized GLFW %", glfwGetVersionString()); int maj = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR); int min = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR); int rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION); // Log GL profile. log_i("OpenGL core profile %.%.%", maj, min, rev); { // Make an OpenGL driver. gfx::gl::Driver driver{Vec<int>{1000, 1000}}; // Load our default shader. auto default_shader = driver.make_shader_repr(); default_shader->load_vertex_part("shader/basic/v"); default_shader->load_fragment_part("shader/basic/f"); default_shader->set_projection_name("proj"); default_shader->set_view_name("view"); default_shader->set_model_name("model"); default_shader->set_sampler_name("tex"); default_shader->set_diffuse_name("dif"); driver.use_shader(*default_shader); default_shader->set_sampler(0); // Load our textures. auto grass_tex = driver.make_texture_repr(); load_png("tex/grass.png", *grass_tex); // Make an isometric camera. auto cam = gfx::make_isometric_camera(); // Load the image Software_Texture terrain_image; load_png("map/default.png", terrain_image); // Convert it into a heightmap Maybe_Owned<Mesh> terrain = driver.make_mesh_repr(); auto terrain_heightmap = make_heightmap_from_image(terrain_image); auto terrain_data = make_terrain_mesh(terrain_heightmap, {20, 20}, .001f, .01); auto terrain_model = glm::scale(glm::mat4(1.0f),glm::vec3(5.0f, 1.0f, 5.0f)); gfx::allocate_mesh_buffers(terrain_data.mesh, *terrain); gfx::write_data_to_mesh(terrain_data.mesh, ref_mo(terrain)); gfx::format_mesh_buffers(*terrain); terrain->set_primitive_type(Primitive_Type::Triangle); // Map + structures. Maybe_Owned<Mesh> structure_mesh = driver.make_mesh_repr(); Map map({1000, 1000}); // <-- Map size for now strat::Player_State player_state{strat::Player_State_Type::Nothing}; auto structures_future = std::async(std::launch::async, load_structures,"structure/structures.json", ref_mo(structure_mesh)); int fps = 0; int time = glfwGetTime(); // Set up some pre-rendering state. driver.clear_color_value(Color{0x55, 0x66, 0x77}); driver.clear_depth_value(1.0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_CULL_FACE); // Our quick hack to avoid splitting into multiple functions and dealing // either with global variables or like a bound struct or something. bool has_clicked_down = false; // Load our ui gfx::IDriver_UI_Adapter ui_adapter{driver}; ui::Freetype_Renderer freetype_font; auto ui_load_params = ui::Load_Params{freetype_font, ui_adapter}; auto hud = ui::load("ui/hud.json", ui_load_params); auto controller = ui::Simple_Controller{}; auto structures = structures_future.get(); hud->find_child_r("build_house")->add_click_listener([&](auto const& pt) { player_state.type = strat::Player_State_Type::Building; player_state.building.to_build = &structures[0]; }); hud->find_child_r("build_gvn_build")->add_click_listener([&](auto const& pt) { player_state.type = strat::Player_State_Type::Building; player_state.building.to_build = &structures[1]; }); hud->layout(driver.window_extents()); controller.add_drag_listener([&](auto const& np, auto const& op) { auto oworld = gfx::unproject_screen(driver, cam, glm::mat4(1.0f), op); auto nworld = gfx::unproject_screen(driver, cam, glm::mat4(1.0f), np); cam.fp.pos += oworld - nworld; // This will give erroneous results if the user clicks on the part of the // screen with nothing drawn on it. So TODO: Put some checks in place so // we don't go messing with the camera zoom and whatnot. }); glfwSetWindowUserPointer(window, &cam); glfwSetScrollCallback(window, scroll_callback); //water_obj.material->diffuse_color = Color{0xaa, 0xaa, 0xff}; while(!glfwWindowShouldClose(window)) { ++fps; glfwPollEvents(); // Clear the screen and render the terrain. driver.clear(); use_camera(driver, cam); driver.bind_texture(*grass_tex, 0); default_shader->set_diffuse(colors::white); default_shader->set_model(terrain_model); // Render the terrain before we calculate the depth of the mouse position. terrain->draw_elements(0, terrain_data.mesh.elements.size()); auto mouse_state = gen_mouse_state(window); auto map_coord = gfx::unproject_screen(driver, cam, terrain_model, mouse_state.position); log_i("% %", map_coord.x, map_coord.z); controller.step(hud, mouse_state); { ui::Draw_Scoped_Lock scoped_draw_lock{ui_adapter}; hud->render(ui_adapter); } glfwSwapBuffers(window); if(int(glfwGetTime()) != time) { time = glfwGetTime(); log_d("fps: %", fps); fps = 0; } flush_log(); } } glfwTerminate(); return 0; } <|endoftext|>
<commit_before>#include <FS.h> #include <ESP8266WiFi.h> // https://github.com/esp8266/Arduino //#include <DNSServer.h> //#include <ESP8266WebServer.h> #include "mqtthandler.h" #include "confighandler.h" constexpr int8_t PIN_01 = 0; constexpr int8_t PIN_02 = 1; constexpr int8_t PIN_03 = 3; constexpr int8_t PIN_04 = 4; constexpr int8_t PIN_05 = 5; constexpr int8_t PIN_06 = 12; constexpr int8_t PIN_07 = 13; constexpr int8_t PIN_08 = 14; constexpr int8_t PIN_09 = 15; constexpr int8_t PIN_19 = 16; uint16_t status = 0; MqttHandler mqtthandler{}; /** Callback from MqttServer when getting a new message */ void mqttCallback(char *topic, byte *payload, unsigned int length) {} void interruptOne() {} void interruptTwo() {} void interruptThree() {} void interruptFour() {} /** Setup all the inputs and outputs */ void setupIOPins() { pinMode(PIN_01, OUTPUT); pinMode(PIN_02, OUTPUT); pinMode(PIN_03, OUTPUT); pinMode(PIN_04, OUTPUT); pinMode(PIN_05, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(PIN_05), interruptOne, FALLING); attachInterrupt(digitalPinToInterrupt(PIN_06), interruptTwo, FALLING); attachInterrupt(digitalPinToInterrupt(PIN_07), interruptThree, FALLING); attachInterrupt(digitalPinToInterrupt(PIN_08), interruptFour, FALLING); } /** The setup entry point, gets called on start up */ void setup() { mqtthandler.loadFromConfigFile("/config.bin"); if (runWiFiManager(mqtthandler, "mqttbtnswitch", "1234")) { mqtthandler.saveToConfigFile("/config.bin"); } mqtthandler.setup(mqttCallback); setupIOPins(); } /** The main loop to run. */ void loop() { mqtthandler.loop(); // if ((status & PIN_05) == PIN_05) { // mqtt_client.publish(mqtt_topic, "1"); // TODO add /out to topic // status ^= PIN_05; // } } <commit_msg>added interrupt handler<commit_after>#include <FS.h> #include <ESP8266WiFi.h> // https://github.com/esp8266/Arduino //#include <DNSServer.h> //#include <ESP8266WebServer.h> #include "mqtthandler.h" #include "confighandler.h" constexpr int8_t PIN_01 = 0; constexpr int8_t PIN_02 = 1; constexpr int8_t PIN_03 = 3; constexpr int8_t PIN_04 = 4; constexpr int8_t PIN_05 = 5; constexpr int8_t PIN_06 = 12; constexpr int8_t PIN_07 = 13; constexpr int8_t PIN_08 = 14; constexpr int8_t PIN_09 = 15; constexpr int8_t PIN_19 = 16; uint16_t status = 0; MqttHandler mqtthandler{}; /** Callback from MqttServer when getting a new message */ void mqttCallback(char *topic, byte *payload, unsigned int length) {} void interruptOne() { status |= 1; } void interruptTwo() { status |= 1 << 1; } void interruptThree() { status |= 1 << 2; } void interruptFour() { status |= 1 << 3; } /** Setup all the inputs and outputs */ void setupIOPins() { pinMode(PIN_01, OUTPUT); pinMode(PIN_02, OUTPUT); pinMode(PIN_03, OUTPUT); pinMode(PIN_04, OUTPUT); pinMode(PIN_05, INPUT_PULLUP); pinMode(PIN_06, INPUT_PULLUP); pinMode(PIN_07, INPUT_PULLUP); pinMode(PIN_08, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(PIN_05), interruptOne, FALLING); attachInterrupt(digitalPinToInterrupt(PIN_06), interruptTwo, FALLING); attachInterrupt(digitalPinToInterrupt(PIN_07), interruptThree, FALLING); attachInterrupt(digitalPinToInterrupt(PIN_08), interruptFour, FALLING); } /** The setup entry point, gets called on start up */ void setup() { mqtthandler.loadFromConfigFile("/config.bin"); if (runWiFiManager(mqtthandler, "mqttbtnswitch", "1234")) { mqtthandler.saveToConfigFile("/config.bin"); } mqtthandler.setup(mqttCallback); setupIOPins(); } /** The main loop to run. */ void loop() { mqtthandler.loop(); // if ((status & PIN_05) == PIN_05) { // mqtt_client.publish(mqtt_topic, "1"); // TODO add /out to topic // status ^= PIN_05; // } } <|endoftext|>
<commit_before>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { //// Initializations --------------------------------------------- srand48(1234); // Make sure we have reproducability check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read galaxies Gals G; if(F.Ascii){ G=read_galaxies_ascii(F);} else{ G = read_galaxies(F); } F.Ngal = G.size(); printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str()); std::vector<int> count; count=count_galaxies(G); for(int i=0;i<8;i++){printf (" %d \n",count[i]);} // make MTL MTL M=make_MTL(G,F); for(int i=0;i<M.priority_list.size();++i){ printf(" priority %f",M.priority_list[i]); } printf(" \n"); assign_priority_class(M); //find available SS and SF galaxies on each petal std::vector <int> count_class(M.priority_list.size(),0); for(int i;i<M.size();++i){ count_class[M[i].priority_class]+=1; } for(int i;i<M.priority_list.size();++i){ printf(" class %d number %d\n",i,count_class[i]); } printf(" number of MTL galaxies %d\n",M.size()); printf("Read fiber center positions and compute related things\n"); PP pp; pp.read_fiber_positions(F); F.Nfiber = pp.fp.size()/2; F.Npetal = max(pp.spectrom)+1; printf("spectrometer has to be identified from 0 to F.Npetal-1\n"); F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500 pp.get_neighbors(F); pp.compute_fibsofsp(F); printf("get neighbors of each fiber;\n"); //for each spectrometer, get list of fibers printf("Read plates in order they are to be observed\n "); Plates P_original = read_plate_centers(F); F.Nplate=P_original.size(); printf("This takes the place of Opsim or NextFieldSelector; will be replaced by appropriate code\n"); Plates P; P.resize(F.Nplate); List permut = random_permut(F.Nplate); for (int jj=0; jj<F.Nplate; jj++){ P[jj]=P_original[permut[jj]]; } printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct target> T(M,MinTreeSize); print_time(time,"# ... took :");//T.stats(); // For plates/fibers, collect available galaxies; done in parallel P[plate j].av_gal[k]=[g1,g2,..] collect_galaxies_for_all(M,T,P,pp,F); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,P,F); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf("before assignment\n"); Assignment A(M,F); print_time(t,"# Start assignment at : "); // Make a plan ---------------------------------------------------- //new_assign_fibers(G,P,pp,F,A); // Plans whole survey without sky fibers, standard stars // assumes maximum number of observations needed for QSOs, LRGs printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); simple_assign(M,P,pp,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs // Want to have even distribution of unused fibers // so we can put in sky fibers and standard stars // Smooth out distribution of free fibers, and increase the number of assignments for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);// more iterations will improve performance slightly for (int i=0; i<1; i++) { // more iterations will improve performance slightly improve(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); } for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Still not updated, so all QSO targets have multiple observations etc // Apply and update the plan -------------------------------------- init_time_at(time,"# Begin real time assignment",t); for (int jj=0; jj<F.Nplate; jj++) { int j = A.next_plate; //printf(" - Plate %d :",j); //assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF just before an observation assign_unused(j,M,P,pp,F,A); //if (j%2000==0) pyplotTile(j,"doc/figs",G,P,pp,F,A); // Picture of positioners, galaxies //printf(" %s not as - ",format(5,f(A.unused_f(j,F))).c_str()); fl(); // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else if (0<=j-F.Analysis) update_plan_from_one_obs(G,M,P,pp,F,A,F.Nplate-1); else printf("\n"); A.next_plate++; // Redistribute and improve on various occasions add more times if desired if ( j==2000 || j==4000) { redistribute_tf(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); improve(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); } } print_time(time,"# ... took :"); // Results ------------------------------------------------------- if (F.Output) for (int j=0; j<F.Nplate; j++) write_FAtile_ascii(j,F.outDir,M,P,pp,F,A); // Write output display_results("doc/figs/",M,P,pp,F,A,true); if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane print_time(t,"# Finished !... in"); return(0); } <commit_msg>add diagnostic<commit_after>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { //// Initializations --------------------------------------------- srand48(1234); // Make sure we have reproducability check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read galaxies Gals G; if(F.Ascii){ G=read_galaxies_ascii(F);} else{ G = read_galaxies(F); } F.Ngal = G.size(); printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str()); std::vector<int> count; count=count_galaxies(G); for(int i=0;i<8;i++){printf (" %d \n",count[i]);} // make MTL MTL M=make_MTL(G,F); for(int i=0;i<M.priority_list.size();++i){ printf(" priority %f",M.priority_list[i]); } printf(" \n"); assign_priority_class(M); //find available SS and SF galaxies on each petal std::vector <int> count_class(M.priority_list.size(),0); for(int i;i<M.size();++i){ count_class[M[i].priority_class]+=1; } for(int i;i<M.priority_list.size();++i){ printf(" class %d number %d\n",i,count_class[i]); } printf(" number of MTL galaxies %d\n",M.size()); printf("Read fiber center positions and compute related things\n"); PP pp; pp.read_fiber_positions(F); F.Nfiber = pp.fp.size()/2; F.Npetal = max(pp.spectrom)+1; printf("spectrometer has to be identified from 0 to F.Npetal-1\n"); F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500 pp.get_neighbors(F); pp.compute_fibsofsp(F); printf("get neighbors of each fiber;\n"); //for each spectrometer, get list of fibers printf("Read plates in order they are to be observed\n "); Plates P_original = read_plate_centers(F); F.Nplate=P_original.size(); printf("This takes the place of Opsim or NextFieldSelector; will be replaced by appropriate code\n"); Plates P; P.resize(F.Nplate); List permut = random_permut(F.Nplate); for (int jj=0; jj<F.Nplate; jj++){ P[jj]=P_original[permut[jj]]; } printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct target> T(M,MinTreeSize); print_time(time,"# ... took :");//T.stats(); // For plates/fibers, collect available galaxies; done in parallel P[plate j].av_gal[k]=[g1,g2,..] collect_galaxies_for_all(M,T,P,pp,F); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,P,F); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf("before assignment\n"); Assignment A(M,F); print_time(t,"# Start assignment at : "); // Make a plan ---------------------------------------------------- //new_assign_fibers(G,P,pp,F,A); // Plans whole survey without sky fibers, standard stars // assumes maximum number of observations needed for QSOs, LRGs printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); simple_assign(M,P,pp,F,A); // diagnostic int count_by_class(M.priority_list.size(),0); for (int j=0;j<F.Nplate;++j){ for(int k=0;k<F.Nfiber;++k){ int g=A.TF[j][k]; if(g!=-1){count_by_class[M[g].Priority_class]+=1; } } } for(int i=0,i<M.priority_list.size();++i){ printf(" i %d number %d \n",count_by_class[i]):; } //end diagnostic print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs // Want to have even distribution of unused fibers // so we can put in sky fibers and standard stars // Smooth out distribution of free fibers, and increase the number of assignments for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);// more iterations will improve performance slightly for (int i=0; i<1; i++) { // more iterations will improve performance slightly improve(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); } for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Still not updated, so all QSO targets have multiple observations etc // Apply and update the plan -------------------------------------- init_time_at(time,"# Begin real time assignment",t); for (int jj=0; jj<F.Nplate; jj++) { int j = A.next_plate; //printf(" - Plate %d :",j); //assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF just before an observation assign_unused(j,M,P,pp,F,A); //if (j%2000==0) pyplotTile(j,"doc/figs",G,P,pp,F,A); // Picture of positioners, galaxies //printf(" %s not as - ",format(5,f(A.unused_f(j,F))).c_str()); fl(); // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else if (0<=j-F.Analysis) update_plan_from_one_obs(G,M,P,pp,F,A,F.Nplate-1); else printf("\n"); A.next_plate++; // Redistribute and improve on various occasions add more times if desired if ( j==2000 || j==4000) { redistribute_tf(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); improve(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); } } print_time(time,"# ... took :"); // Results ------------------------------------------------------- if (F.Output) for (int j=0; j<F.Nplate; j++) write_FAtile_ascii(j,F.outDir,M,P,pp,F,A); // Write output display_results("doc/figs/",M,P,pp,F,A,true); if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane print_time(t,"# Finished !... in"); return(0); } <|endoftext|>
<commit_before>#include "system.hpp" #include "control.hpp" #include "math.hpp" #include "main.hpp" #include <iostream> #include "omp.h" #include <boost/asio.hpp> #include <boost/date_time/posix_time/posix_time.hpp> int main(int argc, const char **argv) { using namespace Util; glfwInit(); std::atomic_bool alive(true); Control::control ctl(alive, "share/icosahedron.obj", "share/fallback.vert", "share/shade.frag"); task::init(alive, &ctl); task::run(alive, &ctl); glfwTerminate(); return 0; } <commit_msg>Changed path back to icosahedron<commit_after>#include "system.hpp" #include "control.hpp" #include "math.hpp" #include "main.hpp" #include <iostream> #include "omp.h" #include <boost/asio.hpp> #include <boost/date_time/posix_time/posix_time.hpp> int main(int argc, const char **argv) { using namespace Util; glfwInit(); std::atomic_bool alive(true); Control::control ctl(alive, "share/lamp.obj", "share/fallback.vert", "share/shade.frag"); task::init(alive, &ctl); task::run(alive, &ctl); glfwTerminate(); return 0; } <|endoftext|>
<commit_before>#include <SDL/SDL.h> #include <GL/gl.h> SDL_Surface *screen = NULL; void drawScene(void) { glClear(GL_COLOR_BUFFER_BIT); glColor3f(1.0f, 0.0f, 0.0f); glBegin(GL_TRIANGLES); glVertex3f(-0.5f, -0.7f, 0.0f); glVertex3f( 0.5f, -0.7f, 0.0f); glVertex3f( 0.0f, 0.7f, 0.0f); glEnd(); SDL_GL_SwapBuffers(); } void handleKey(SDL_keysym *key) { switch (key->sym) { case SDLK_ESCAPE: SDL_Quit(); exit(0); break; default: break; } } int main(int argc, char *argv[]) { bool done = false; SDL_Event event; int flags; if (SDL_Init(SDL_INIT_VIDEO) < 0) { fprintf(stderr, "Could not initialize SDL: %s\n", SDL_GetError()); exit(1); } flags = SDL_OPENGL | SDL_GL_DOUBLEBUFFER; screen = SDL_SetVideoMode(640, 480, 32, flags); if (!screen) { fprintf(stderr, "Could not initialize video: %s\n", SDL_GetError()); SDL_Quit(); exit(1); } glClearColor(0.0f, 0.0f, 0.0f, 0.0f); while (!done) { drawScene(); while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: handleKey(&event.key.keysym); break; case SDL_QUIT: done = true; break; } } } SDL_Quit(); return 0; } <commit_msg>Changed OpenGL include to be more portable.<commit_after>#include <SDL/SDL.h> #include <SDL/SDL_opengl.h> SDL_Surface *screen = NULL; void drawScene(void) { glClear(GL_COLOR_BUFFER_BIT); glColor3f(1.0f, 0.0f, 0.0f); glBegin(GL_TRIANGLES); glVertex3f(-0.5f, -0.7f, 0.0f); glVertex3f( 0.5f, -0.7f, 0.0f); glVertex3f( 0.0f, 0.7f, 0.0f); glEnd(); SDL_GL_SwapBuffers(); } void handleKey(SDL_keysym *key) { switch (key->sym) { case SDLK_ESCAPE: SDL_Quit(); exit(0); break; default: break; } } int main(int argc, char *argv[]) { bool done = false; SDL_Event event; int flags; if (SDL_Init(SDL_INIT_VIDEO) < 0) { fprintf(stderr, "Could not initialize SDL: %s\n", SDL_GetError()); exit(1); } flags = SDL_OPENGL | SDL_GL_DOUBLEBUFFER; screen = SDL_SetVideoMode(640, 480, 32, flags); if (!screen) { fprintf(stderr, "Could not initialize video: %s\n", SDL_GetError()); SDL_Quit(); exit(1); } glClearColor(0.0f, 0.0f, 0.0f, 0.0f); while (!done) { drawScene(); while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: handleKey(&event.key.keysym); break; case SDL_QUIT: done = true; break; } } } SDL_Quit(); return 0; } <|endoftext|>
<commit_before>#include <QtGui/QGuiApplication> #include <QQmlContext> #include <QStateMachine> #include <QDebug> #include <memory> #include "./window.h" #include "./scene.h" #include "./nodes.h" #include "./label_node.h" #include "./input/invoke_manager.h" #include "./input/signal_manager.h" #include "./input/scxml_importer.h" #include "./mouse_shape_controller.h" #include "./labeller_model.h" #include "./labels_model.h" #include "./labelling/labels.h" #include "./picking_controller.h" #include "./forces_visualizer_node.h" #include "./default_scene_creator.h" void onLabelChangedUpdateLabelNodes(std::shared_ptr<Nodes> nodes, Labels::Action action, const Label &label) { auto labelNodes = nodes->getLabelNodes(); auto labelNode = std::find_if(labelNodes.begin(), labelNodes.end(), [label](std::shared_ptr<LabelNode> labelNode) { return labelNode->label.id == label.id; }); if (labelNode == labelNodes.end()) { nodes->addNode(std::make_shared<LabelNode>(label)); } else if (action == Labels::Action::Delete) { nodes->removeNode(*labelNode); } else { (*labelNode)->label = label; } }; int main(int argc, char **argv) { qputenv("QT_MESSAGE_PATTERN", QString("%{time [yyyy'-'MM'-'dd' 'hh':'mm':'ss]} - %{threadid} " "%{if-category}%{category}: %{endif}%{message}").toUtf8()); if (qgetenv("QT_LOGGING_CONF").size() == 0) qputenv("QT_LOGGING_CONF", "../config/logging.ini"); QGuiApplication application(argc, argv); qDebug() << "Application start"; auto invokeManager = std::shared_ptr<InvokeManager>(new InvokeManager()); auto nodes = std::make_shared<Nodes>(); auto labels = std::make_shared<Labels>(); auto labeller = std::make_shared<Forces::Labeller>(labels); auto forcesVisualizerNode = std::make_shared<ForcesVisualizerNode>(labeller); nodes->addNode(forcesVisualizerNode); DefaultSceneCreator sceneCreator(nodes, labels); sceneCreator.create(); auto scene = std::make_shared<Scene>(invokeManager, nodes, labels, labeller); auto unsubscribeLabelChanges = labels->subscribe( std::bind(&onLabelChangedUpdateLabelNodes, nodes, std::placeholders::_1, std::placeholders::_2)); Window window(scene); window.setResizeMode(QQuickView::SizeRootObjectToView); window.rootContext()->setContextProperty("window", &window); window.rootContext()->setContextProperty("nodes", nodes.get()); MouseShapeController mouseShapeController; PickingController pickingController(scene); LabellerModel labellerModel(labeller); labellerModel.connect(&labellerModel, &LabellerModel::isVisibleChanged, [&labellerModel, &nodes, &forcesVisualizerNode]() { if (labellerModel.getIsVisible()) nodes->addNode(forcesVisualizerNode); else nodes->removeNode(forcesVisualizerNode); }); window.rootContext()->setContextProperty("labeller", &labellerModel); LabelsModel labelsModel(labels, pickingController); window.rootContext()->setContextProperty("labels", &labelsModel); window.setSource(QUrl("qrc:ui.qml")); auto signalManager = std::shared_ptr<SignalManager>(new SignalManager()); ScxmlImporter importer(QUrl::fromLocalFile("config/states.xml"), invokeManager, signalManager); invokeManager->addHandler(&window); invokeManager->addHandler("mouseShape", &mouseShapeController); invokeManager->addHandler("picking", &pickingController); signalManager->addSender("KeyboardEventSender", &window); signalManager->addSender("labels", &labelsModel); auto stateMachine = importer.import(); // just for printCurrentState slot for debugging window.stateMachine = stateMachine; stateMachine->start(); window.show(); auto resultCode = application.exec(); unsubscribeLabelChanges(); return resultCode; } <commit_msg>Colors for logging output.<commit_after>#include <QtGui/QGuiApplication> #include <QQmlContext> #include <QStateMachine> #include <QDebug> #include <memory> #include "./window.h" #include "./scene.h" #include "./nodes.h" #include "./label_node.h" #include "./input/invoke_manager.h" #include "./input/signal_manager.h" #include "./input/scxml_importer.h" #include "./mouse_shape_controller.h" #include "./labeller_model.h" #include "./labels_model.h" #include "./labelling/labels.h" #include "./picking_controller.h" #include "./forces_visualizer_node.h" #include "./default_scene_creator.h" void onLabelChangedUpdateLabelNodes(std::shared_ptr<Nodes> nodes, Labels::Action action, const Label &label) { auto labelNodes = nodes->getLabelNodes(); auto labelNode = std::find_if(labelNodes.begin(), labelNodes.end(), [label](std::shared_ptr<LabelNode> labelNode) { return labelNode->label.id == label.id; }); if (labelNode == labelNodes.end()) { nodes->addNode(std::make_shared<LabelNode>(label)); } else if (action == Labels::Action::Delete) { nodes->removeNode(*labelNode); } else { (*labelNode)->label = label; } }; int main(int argc, char **argv) { qputenv("QT_MESSAGE_PATTERN", QString("%{time [yyyy'-'MM'-'dd' " "'hh':'mm':'ss]} " "%{if-fatal}\033[31;1m%{endif}" "%{if-critical}\033[31m%{endif}" "%{if-warning}\033[33m%{endif}" "%{if-info}\033[34m%{endif}" "- %{threadid} " "%{if-category}%{category}: %{endif}%{message}" "%{if-warning}\n\t%{file}:%{line}\n\t%{backtrace depth=3 " "separator=\"\n\t\"}%{endif}" "%{if-critical}\n\t%{file}:%{line}\n\t%{backtrace depth=3 " "separator=\"\n\t\"}%{endif}\033[0m").toUtf8()); if (qgetenv("QT_LOGGING_CONF").size() == 0) qputenv("QT_LOGGING_CONF", "../config/logging.ini"); QGuiApplication application(argc, argv); qInfo() << "Application start"; auto invokeManager = std::shared_ptr<InvokeManager>(new InvokeManager()); auto nodes = std::make_shared<Nodes>(); auto labels = std::make_shared<Labels>(); auto labeller = std::make_shared<Forces::Labeller>(labels); auto forcesVisualizerNode = std::make_shared<ForcesVisualizerNode>(labeller); nodes->addNode(forcesVisualizerNode); DefaultSceneCreator sceneCreator(nodes, labels); sceneCreator.create(); auto scene = std::make_shared<Scene>(invokeManager, nodes, labels, labeller); auto unsubscribeLabelChanges = labels->subscribe( std::bind(&onLabelChangedUpdateLabelNodes, nodes, std::placeholders::_1, std::placeholders::_2)); Window window(scene); window.setResizeMode(QQuickView::SizeRootObjectToView); window.rootContext()->setContextProperty("window", &window); window.rootContext()->setContextProperty("nodes", nodes.get()); MouseShapeController mouseShapeController; PickingController pickingController(scene); LabellerModel labellerModel(labeller); labellerModel.connect(&labellerModel, &LabellerModel::isVisibleChanged, [&labellerModel, &nodes, &forcesVisualizerNode]() { if (labellerModel.getIsVisible()) nodes->addNode(forcesVisualizerNode); else nodes->removeNode(forcesVisualizerNode); }); window.rootContext()->setContextProperty("labeller", &labellerModel); LabelsModel labelsModel(labels, pickingController); window.rootContext()->setContextProperty("labels", &labelsModel); window.setSource(QUrl("qrc:ui.qml")); auto signalManager = std::shared_ptr<SignalManager>(new SignalManager()); ScxmlImporter importer(QUrl::fromLocalFile("config/states.xml"), invokeManager, signalManager); invokeManager->addHandler(&window); invokeManager->addHandler("mouseShape", &mouseShapeController); invokeManager->addHandler("picking", &pickingController); signalManager->addSender("KeyboardEventSender", &window); signalManager->addSender("labels", &labelsModel); auto stateMachine = importer.import(); // just for printCurrentState slot for debugging window.stateMachine = stateMachine; stateMachine->start(); window.show(); auto resultCode = application.exec(); unsubscribeLabelChanges(); return resultCode; } <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2014-2015 Andrea Scarpino <me@andreascarpino.it> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <QtQuick> #include <sailfishapp.h> #include "hostsmanager.h" int main(int argc, char *argv[]) { QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv)); QScopedPointer<QQuickView> view(SailfishApp::createView()); QCoreApplication::setApplicationName(QStringLiteral("HostIsDown")); HostsManager manager; view->rootContext()->setContextProperty("manager", &manager); HostsSqlModel* recentHosts = manager.recentHosts(); view->rootContext()->setContextProperty("recentHosts", recentHosts); view->setSource(SailfishApp::pathTo("qml/HostIsDown.qml")); view->showFullScreen(); return app->exec(); } <commit_msg>Set Organization Domain<commit_after>/* The MIT License (MIT) Copyright (c) 2014-2016 Andrea Scarpino <me@andreascarpino.it> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <QtQuick> #include <sailfishapp.h> #include "hostsmanager.h" int main(int argc, char *argv[]) { QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv)); QScopedPointer<QQuickView> view(SailfishApp::createView()); QCoreApplication::setApplicationName(QStringLiteral("HostIsDown")); QCoreApplication::setOrganizationDomain(QStringLiteral("it.andreascarpino")); HostsManager manager; view->rootContext()->setContextProperty("manager", &manager); HostsSqlModel* recentHosts = manager.recentHosts(); view->rootContext()->setContextProperty("recentHosts", recentHosts); view->setSource(SailfishApp::pathTo("qml/HostIsDown.qml")); view->showFullScreen(); return app->exec(); } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <vector> #include <stdlib.h> #include <chrono> #include "lexer.h" #include "tokens.h" #include "parser.h" #include "astnode.h" #include "asttransforms.h" #include "irgen.h" #include "ccodegen.h" bool debug_lexer; bool debug_parser; bool semantic_error = false; bool timedOut = false; bool outputIR = false; void badargspass() { std::cout << "Usage:\n Neuro <inputfiles>\n"; std::cout << "Options:\n -dbgl = lexer debug output\n -dbgp = print AST generated by parser\n"; std::cout << " -t = print timing information\n -l = output ir\n"; std::cout << "Coming:\n -dbga = all debug output\n"; } void parseargs(int argc, char** argv, std::vector<std::string>& cmd_args) { std::string dbgl("-dbgl"); std::string dbgp("-dbgp"); std::string t("-t"); std::string l("-l"); std::string h("-h"); for(int i = 1; i < argc; i++) { if(dbgl.compare(argv[i]) == 0) { debug_lexer = true; } else if(dbgp.compare(argv[i]) == 0) { debug_parser = true; } else if(t.compare(argv[i]) == 0) { timedOut = true; } else if(l.compare(argv[i]) == 0) { outputIR = true; } else if(h.compare(argv[i]) == 0) { badargspass(); } else { cmd_args.push_back(argv[i]); } } } void linkFile(std::string file); void makeDotGraph(std::ofstream& outfile, AstNode* ast); int main(int argc, char** argv) { std::cout << "Welcome to the neuro compiler.\n"; if(argc < 2) { badargspass(); return 0; } else { std::vector<std::string> sources; parseargs(argc, argv, sources); if(sources.size() == 0) { badargspass(); return 0; } //std::cout << "Sizeof(AstNode) = " << sizeof(AstNode) << '\n'; //std::cout << "Sizeof(Token) = " << sizeof(Token) << '\n'; //std::cout << "Sizeof(TypeInfo) = " << sizeof(TypeInfo) << '\n'; //std::cout << "Beginning Lexing...\ndebug: " << debug_lexer << "\n"; for (auto f : sources) { auto start_total = std::chrono::steady_clock::now(); LexerTarget target1 = LexerTarget(f, debug_lexer); target1.lexFile(); auto end_lex = std::chrono::steady_clock::now(); auto diff_lex = end_lex-start_total; auto start_parse = std::chrono::steady_clock::now(); Parser parser = Parser(&target1); AstNode* ast = parser.parse(); auto end_parse = std::chrono::steady_clock::now(); auto diff_parse = end_parse - start_parse; //std::cout << "Beginning AST transformations and Semantic analysis\n"; auto start_semantic = std::chrono::steady_clock::now(); transformAssignments(ast); populateTypeList(ast); resolveSizeOfs(ast); importPrepass(ast); populateSymbolTableFunctions(ast); semanticPass1(ast); //printSymbolTable(); typeCheckPass(ast); //printSymbolTable(); //decorateAst(ast); deferPass(ast); auto end_semantic = std::chrono::steady_clock::now(); auto diff_semantic = end_semantic - start_semantic; if(debug_parser) { //Generate Dot file for debugging std::ofstream dotfileout(target1.targetName()+".dot",std::ofstream::out); auto start = std::chrono::steady_clock::now(); makeDotGraph(dotfileout,ast); auto end = std::chrono::steady_clock::now(); auto diff = end - start; std::cout << "Time for make graph: " << std::chrono::duration_cast<std::chrono::milliseconds>(diff).count() << "ms\n"; dotfileout.close(); std::string cmd = "dot -Tpng "+target1.targetName()+".dot -o "+target1.targetName()+".png"; std::cout << "Running command: " << cmd << "\n"; system(cmd.c_str()); } auto start_ir = std::chrono::steady_clock::now(); auto start_link = start_ir; if(!semantic_error) { //std::cout << "Generating IR code\n"; //Generate IR code generateIR(ast); if(outputIR) { std::cout << "IR output:\n"; dumpIR(); } start_link = std::chrono::steady_clock::now(); writeObj(target1.targetName()); linkFile(target1.targetName()); //writeIR(target1.targetName()); } auto end_total = std::chrono::steady_clock::now(); auto diff_total = end_total - start_total; auto diff_ir = start_link - start_ir; auto diff_link = end_total - start_link; if(timedOut) { auto lex_time = std::chrono::duration_cast<std::chrono::milliseconds>(diff_lex).count(); auto parse_time = std::chrono::duration_cast<std::chrono::milliseconds>(diff_parse).count(); auto semantic_time = std::chrono::duration_cast<std::chrono::milliseconds>(diff_semantic).count(); auto ir_time = std::chrono::duration_cast<std::chrono::milliseconds>(diff_ir).count(); auto link_time = std::chrono::duration_cast<std::chrono::milliseconds>(diff_ir).count(); auto total_time = std::chrono::duration_cast<std::chrono::milliseconds>(diff_total).count(); std::cout << "Lex Time: " << lex_time << "ms\n"; std::cout << "Time for parsing: " << parse_time << "ms\n"; std::cout << "Time for semantic passes: " << semantic_time << "ms\n"; if(!semantic_error) { std::cout << "Time for IR generation: " << ir_time << "ms\n"; std::cout << "Time for linking: " << link_time << "ms\n"; } std::cout << "Total Time: " << total_time << "ms\n"; //BinOpNode::printDeleted(); } if(false) { SymbolTable* s = getSymtab(f); const std::vector<SymbolTableEntry*> symtab_entries = getFunctionEntries(s); genCFile(f,symtab_entries); } } return 0; } //Should never reach! std::cerr << "Well this is awkward...\n"; return -1; } <commit_msg>Use the correct difference for printing link time.<commit_after>#include <iostream> #include <string> #include <vector> #include <stdlib.h> #include <chrono> #include "lexer.h" #include "tokens.h" #include "parser.h" #include "astnode.h" #include "asttransforms.h" #include "irgen.h" #include "ccodegen.h" bool debug_lexer; bool debug_parser; bool semantic_error = false; bool timedOut = false; bool outputIR = false; void badargspass() { std::cout << "Usage:\n Neuro <inputfiles>\n"; std::cout << "Options:\n -dbgl = lexer debug output\n -dbgp = print AST generated by parser\n"; std::cout << " -t = print timing information\n -l = output ir\n"; std::cout << "Coming:\n -dbga = all debug output\n"; } void parseargs(int argc, char** argv, std::vector<std::string>& cmd_args) { std::string dbgl("-dbgl"); std::string dbgp("-dbgp"); std::string t("-t"); std::string l("-l"); std::string h("-h"); for(int i = 1; i < argc; i++) { if(dbgl.compare(argv[i]) == 0) { debug_lexer = true; } else if(dbgp.compare(argv[i]) == 0) { debug_parser = true; } else if(t.compare(argv[i]) == 0) { timedOut = true; } else if(l.compare(argv[i]) == 0) { outputIR = true; } else if(h.compare(argv[i]) == 0) { badargspass(); } else { cmd_args.push_back(argv[i]); } } } void linkFile(std::string file); void makeDotGraph(std::ofstream& outfile, AstNode* ast); int main(int argc, char** argv) { std::cout << "Welcome to the neuro compiler.\n"; if(argc < 2) { badargspass(); return 0; } else { std::vector<std::string> sources; parseargs(argc, argv, sources); if(sources.size() == 0) { badargspass(); return 0; } //std::cout << "Sizeof(AstNode) = " << sizeof(AstNode) << '\n'; //std::cout << "Sizeof(Token) = " << sizeof(Token) << '\n'; //std::cout << "Sizeof(TypeInfo) = " << sizeof(TypeInfo) << '\n'; //std::cout << "Beginning Lexing...\ndebug: " << debug_lexer << "\n"; for (auto f : sources) { auto start_total = std::chrono::steady_clock::now(); LexerTarget target1 = LexerTarget(f, debug_lexer); target1.lexFile(); auto end_lex = std::chrono::steady_clock::now(); auto diff_lex = end_lex-start_total; auto start_parse = std::chrono::steady_clock::now(); Parser parser = Parser(&target1); AstNode* ast = parser.parse(); auto end_parse = std::chrono::steady_clock::now(); auto diff_parse = end_parse - start_parse; //std::cout << "Beginning AST transformations and Semantic analysis\n"; auto start_semantic = std::chrono::steady_clock::now(); transformAssignments(ast); populateTypeList(ast); resolveSizeOfs(ast); importPrepass(ast); populateSymbolTableFunctions(ast); semanticPass1(ast); //printSymbolTable(); typeCheckPass(ast); //printSymbolTable(); //decorateAst(ast); deferPass(ast); auto end_semantic = std::chrono::steady_clock::now(); auto diff_semantic = end_semantic - start_semantic; if(debug_parser) { //Generate Dot file for debugging std::ofstream dotfileout(target1.targetName()+".dot",std::ofstream::out); auto start = std::chrono::steady_clock::now(); makeDotGraph(dotfileout,ast); auto end = std::chrono::steady_clock::now(); auto diff = end - start; std::cout << "Time for make graph: " << std::chrono::duration_cast<std::chrono::milliseconds>(diff).count() << "ms\n"; dotfileout.close(); std::string cmd = "dot -Tpng "+target1.targetName()+".dot -o "+target1.targetName()+".png"; std::cout << "Running command: " << cmd << "\n"; system(cmd.c_str()); } auto start_ir = std::chrono::steady_clock::now(); auto start_link = start_ir; if(!semantic_error) { //std::cout << "Generating IR code\n"; //Generate IR code generateIR(ast); if(outputIR) { std::cout << "IR output:\n"; dumpIR(); } start_link = std::chrono::steady_clock::now(); writeObj(target1.targetName()); linkFile(target1.targetName()); //writeIR(target1.targetName()); } auto end_total = std::chrono::steady_clock::now(); auto diff_total = end_total - start_total; auto diff_ir = start_link - start_ir; auto diff_link = end_total - start_link; if(timedOut) { auto lex_time = std::chrono::duration_cast<std::chrono::milliseconds>(diff_lex).count(); auto parse_time = std::chrono::duration_cast<std::chrono::milliseconds>(diff_parse).count(); auto semantic_time = std::chrono::duration_cast<std::chrono::milliseconds>(diff_semantic).count(); auto ir_time = std::chrono::duration_cast<std::chrono::milliseconds>(diff_ir).count(); auto link_time = std::chrono::duration_cast<std::chrono::milliseconds>(diff_link).count(); auto total_time = std::chrono::duration_cast<std::chrono::milliseconds>(diff_total).count(); std::cout << "Lex Time: " << lex_time << "ms\n"; std::cout << "Time for parsing: " << parse_time << "ms\n"; std::cout << "Time for semantic passes: " << semantic_time << "ms\n"; if(!semantic_error) { std::cout << "Time for IR generation: " << ir_time << "ms\n"; std::cout << "Time for linking: " << link_time << "ms\n"; } std::cout << "Total Time: " << total_time << "ms\n"; //BinOpNode::printDeleted(); } if(false) { SymbolTable* s = getSymtab(f); const std::vector<SymbolTableEntry*> symtab_entries = getFunctionEntries(s); genCFile(f,symtab_entries); } } return 0; } //Should never reach! std::cerr << "Well this is awkward...\n"; return -1; } <|endoftext|>
<commit_before>#include <iostream> #include "main.hpp" #include "omp.h" #include <boost/asio.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #ifndef OBJ_PATH #define OBJ_PATH "share/icosahedron.obj" #endif #ifndef VERT_PATH #define VERT_PATH "share/fallback.vert" #endif #ifndef FRAG_PATH #define FRAG_PATH "share/shade.frag" #endif int main(int argc, const char **argv) { using namespace Util; glfwInit(); std::atomic_bool alive(true); Control::control ctl(alive, OBJ_PATH, VERT_PATH, FRAG_PATH); task::init(alive, &ctl); task::run(alive, &ctl); glfwTerminate(); return 0; } <commit_msg>Added GLFW version to init failure<commit_after>#include <iostream> #include "main.hpp" #include "omp.h" #include <boost/asio.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #ifndef OBJ_PATH #define OBJ_PATH "share/icosahedron.obj" #endif #ifndef VERT_PATH #define VERT_PATH "share/fallback.vert" #endif #ifndef FRAG_PATH #define FRAG_PATH "share/shade.frag" #endif int main(int argc, const char **argv) { using namespace Util; std::atomic_bool alive(true); if(glfwInit() == 0) { std::cout << "Failed to initialize GLFW " << glfwGetVersionString() << std::endl; return 1; } Control::control ctl(alive, OBJ_PATH, VERT_PATH, FRAG_PATH); task::init(alive, &ctl); task::run(alive, &ctl); glfwTerminate(); return 0; } <|endoftext|>
<commit_before>/* Copyright (C) 2016 Jeremy Starnes This file is part of TDSE. TDSE is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. TDSE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with TDSE; see the file COPYING. If not, see <http://www.gnu.org/licenses/agpl> */ #include <stdexcept> #include <iostream> #include "camera.h" #include "shape_renderer.h" #include "biped.h" #include "turret.h" #include <random> class soldier : public biped, public shooter { public: soldier(const glm::vec2 & position, std::default_random_engine & prand) : biped(position), shooter( std::chrono::milliseconds(100) ), bullet_type(0.008f), weapon(8.0f), prand_(prand) {} soldier(const soldier &) = delete; void operator=(const soldier &) = delete; projectile::properties bullet_type; turret weapon; private: std::default_random_engine & prand_; static std::normal_distribution<float> normal_dist; protected: virtual projectile fire() override { glm::vec2 velocity(400.0f, 0.0f); glm::mat2 direction = mat2_from_angle( weapon.aim_angle() + normal_dist(prand_) ); return projectile( bullet_type, real_position(), direction*velocity ); } }; std::normal_distribution<float> soldier::normal_dist(0.0f, 0.02f); class human_interface { public: human_interface(window & win) : win_(win), wasd(0, 0), mouse(0, 0), space(false) { win_.input_handler( std::bind(&human_interface::handle_input, this, std::placeholders::_1) ); } void handle_input(const SDL_Event & event) { switch(event.type) { case SDL_KEYDOWN: if(event.key.repeat) break; switch(event.key.keysym.scancode) { case SDL_SCANCODE_W: wasd.y += 1; break; case SDL_SCANCODE_A: wasd.x -= 1; break; case SDL_SCANCODE_S: wasd.y -= 1; break; case SDL_SCANCODE_D: wasd.x += 1; break; case SDL_SCANCODE_SPACE: space = true; break; } break; case SDL_KEYUP: if(event.key.repeat) break; switch(event.key.keysym.scancode) { case SDL_SCANCODE_W: wasd.y -= 1; break; case SDL_SCANCODE_A: wasd.x += 1; break; case SDL_SCANCODE_S: wasd.y += 1; break; case SDL_SCANCODE_D: wasd.x -= 1; break; case SDL_SCANCODE_SPACE: space = false; break; } break; case SDL_MOUSEMOTION: mouse.x = event.motion.x; mouse.y = event.motion.y; break; } } void apply_input(soldier & player) { // Transform mouse coordinates to world space auto window_size = win_.size(); glm::vec2 view_pos(mouse.x - window_size.x/2.0f, window_size.y/2.0f - mouse.y); camera default_camera(player.position(), 0.0f, 40.0f); glm::vec2 world_pos = glm::vec3(view_pos, 1.0f) *default_camera.transform() /default_camera.magnification; // Apply control inputs to test_biped glm::vec2 player_dist = world_pos - player.position(); player.weapon.target = glm::atan(player_dist.y, player_dist.x); player.force( glm::vec2(wasd.x*biped::max_linear_force, wasd.y*biped::max_linear_force) ); player.wants_fire = space; } private: glm::ivec2 wasd, mouse; bool space; window & win_; }; #include <chrono> #include <thread> class lap_timer { public: typedef std::chrono::steady_clock::time_point time_point; typedef std::chrono::steady_clock::duration duration; lap_timer(); time_point last() const; duration lap(); private: time_point _last; }; lap_timer::lap_timer() : _last( std::chrono::steady_clock::now() ) {} lap_timer::time_point lap_timer::last() const { return _last; } lap_timer::duration lap_timer::lap() { time_point __last = _last; _last = std::chrono::steady_clock::now(); return _last - __last; } #include <glm/gtc/constants.hpp> int main(int argc, char * argv[]) { try { std::random_device::result_type seed; { std::random_device r; seed = r(); } std::default_random_engine prand(seed); projectile_world physics( glm::vec2(1000.0f, 1000.0f) ); soldier player(glm::vec2(0.0f, 0.0f), prand); physics.add(player); // Instantiate targets to shoot at std::vector<biped> test_bipeds; static constexpr glm::vec2 start(-6.25f, -6.25f); static constexpr int width = 5; static constexpr int num_test_bipeds = 25; static constexpr float spacing = 2.5f; test_bipeds.reserve(num_test_bipeds); for(int i = 0; i < num_test_bipeds; ++i) { test_bipeds.emplace_back( start + glm::vec2( spacing*(i%width), spacing*(i/width) ) ); physics.add( test_bipeds[i] ); } sdl media_layer(SDL_INIT_VIDEO); media_layer.gl_version(1, 4); window win( media_layer, "", glm::ivec2(640, 480) ); shape_renderer ren(win); human_interface input(win); // Construct circle shape constexpr int num_circle_vertices = 8; std::array<glm::vec2, num_circle_vertices> circle_vertices; { float angle = 0.0f; float increment = ( 2*glm::pi<float>() )/num_circle_vertices; for(int i = 0; i < num_circle_vertices; ++i) { circle_vertices[i].x = biped::size*glm::cos(angle); circle_vertices[i].y = biped::size*glm::sin(angle); angle += increment; } } std::array<unsigned short, circle_vertices.size()> circle_indices; for(unsigned short i = 0; i < circle_indices.size(); ++i) circle_indices[i] = i; shape test_biped_shape(circle_vertices, circle_indices, GL_LINE_LOOP); camera test_camera(player.position(), 0.0f, 40.0f); ren.view( test_camera.view() ); bool quit = false; lap_timer timer; while(!quit) { SDL_Event event; while( media_layer.poll(event) ) { switch(event.type) { case SDL_QUIT: quit = true; break; } } input.apply_input(player); // Calculate turret appearance float turret_aim = player.weapon.aim_angle(); glm::vec2 turret_end( biped::size*glm::cos(turret_aim), biped::size*glm::sin(turret_aim) ); segment turret_segment( player.position() ); turret_segment.end = turret_segment.start + turret_end; // Calculate segments from projectiles std::vector<segment> psegments; for(auto i = physics.projectiles.begin(); i != physics.projectiles.end(); ++i) { psegments.emplace_back(i->position, i->position - 0.01f*i->velocity); } // Render scene ren.clear(); ren.render(player.model(), test_biped_shape); for(auto i = test_bipeds.begin(); i != test_bipeds.end(); ++i) ren.render(i->model(), test_biped_shape); ren.render(turret_segment); ren.render(psegments); win.present(); // Advance auto lap_time = timer.lap(); player.weapon.step(lap_time); physics.step(lap_time); } } catch(const std::exception & e) { std::cout << e.what() << std::endl; } } <commit_msg>move camera state to class human_interface<commit_after>/* Copyright (C) 2016 Jeremy Starnes This file is part of TDSE. TDSE is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. TDSE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with TDSE; see the file COPYING. If not, see <http://www.gnu.org/licenses/agpl> */ #include <stdexcept> #include <iostream> #include "camera.h" #include "shape_renderer.h" #include "biped.h" #include "turret.h" #include <random> class soldier : public biped, public shooter { public: soldier(const glm::vec2 & position, std::default_random_engine & prand) : biped(position), shooter( std::chrono::milliseconds(100) ), bullet_type(0.008f), weapon(8.0f), prand_(prand) {} soldier(const soldier &) = delete; void operator=(const soldier &) = delete; projectile::properties bullet_type; turret weapon; private: std::default_random_engine & prand_; static std::normal_distribution<float> normal_dist; protected: virtual projectile fire() override { glm::vec2 velocity(400.0f, 0.0f); glm::mat2 direction = mat2_from_angle( weapon.aim_angle() + normal_dist(prand_) ); return projectile( bullet_type, real_position(), direction*velocity ); } }; std::normal_distribution<float> soldier::normal_dist(0.0f, 0.02f); class human_interface { public: human_interface(window & win) : win_(win), wasd(0, 0), mouse(0, 0), zoom(0), space(false), cam(glm::vec2(0.0f, 0.0f), 0.0f, 40.0f) { win_.input_handler( std::bind(&human_interface::handle_input, this, std::placeholders::_1) ); } void handle_input(const SDL_Event & event) { switch(event.type) { case SDL_KEYDOWN: if(event.key.repeat) break; switch(event.key.keysym.scancode) { case SDL_SCANCODE_W: wasd.y += 1; break; case SDL_SCANCODE_A: wasd.x -= 1; break; case SDL_SCANCODE_S: wasd.y -= 1; break; case SDL_SCANCODE_D: wasd.x += 1; break; case SDL_SCANCODE_SPACE: space = true; break; case SDL_SCANCODE_R: zoom += 1; break; case SDL_SCANCODE_F: zoom -= 1; break; } break; case SDL_KEYUP: if(event.key.repeat) break; switch(event.key.keysym.scancode) { case SDL_SCANCODE_W: wasd.y -= 1; break; case SDL_SCANCODE_A: wasd.x += 1; break; case SDL_SCANCODE_S: wasd.y += 1; break; case SDL_SCANCODE_D: wasd.x -= 1; break; case SDL_SCANCODE_SPACE: space = false; break; case SDL_SCANCODE_R: zoom -= 1; break; case SDL_SCANCODE_F: zoom += 1; break; } break; case SDL_MOUSEMOTION: mouse.x = event.motion.x; mouse.y = event.motion.y; break; } } void apply_input(soldier & player) { // Transform mouse coordinates to world space auto window_size = win_.size(); glm::vec2 view_pos(mouse.x - window_size.x/2.0f, window_size.y/2.0f - mouse.y); glm::vec2 world_pos = cam.transform() *glm::vec3(view_pos/cam.magnification, 1.0f); // Apply control inputs to test_biped glm::vec2 player_dist = world_pos - player.position(); player.weapon.target = glm::atan(player_dist.y, player_dist.x); player.force( glm::vec2(wasd.x*biped::max_linear_force, wasd.y*biped::max_linear_force) ); player.wants_fire = space; cam.magnification_velocity = zoom*1.0f; } private: window & win_; glm::ivec2 wasd, mouse; float zoom; bool space; public: kinematic_camera cam; }; #include <chrono> #include <thread> class lap_timer { public: typedef std::chrono::steady_clock::time_point time_point; typedef std::chrono::steady_clock::duration duration; lap_timer(); time_point last() const; duration lap(); private: time_point _last; }; lap_timer::lap_timer() : _last( std::chrono::steady_clock::now() ) {} lap_timer::time_point lap_timer::last() const { return _last; } lap_timer::duration lap_timer::lap() { time_point __last = _last; _last = std::chrono::steady_clock::now(); return _last - __last; } #include <glm/gtc/constants.hpp> int main(int argc, char * argv[]) { try { std::random_device::result_type seed; { std::random_device r; seed = r(); } std::default_random_engine prand(seed); projectile_world physics( glm::vec2(1000.0f, 1000.0f) ); soldier player(glm::vec2(0.0f, 0.0f), prand); physics.add(player); // Instantiate targets to shoot at std::vector<biped> test_bipeds; static const glm::vec2 start(-6.25f, -6.25f); static const int width = 5; static const int num_test_bipeds = 25; static const float spacing = 2.5f; test_bipeds.reserve(num_test_bipeds); for(int i = 0; i < num_test_bipeds; ++i) { test_bipeds.emplace_back( start + glm::vec2( spacing*(i%width), spacing*(i/width) ) ); physics.add( test_bipeds[i] ); } sdl media_layer(SDL_INIT_VIDEO); media_layer.gl_version(1, 4); window win( media_layer, "", glm::ivec2(640, 480) ); shape_renderer ren(win); human_interface input(win); // Construct circle shape constexpr int num_circle_vertices = 8; std::array<glm::vec2, num_circle_vertices> circle_vertices; { float angle = 0.0f; float increment = ( 2*glm::pi<float>() )/num_circle_vertices; for(int i = 0; i < num_circle_vertices; ++i) { circle_vertices[i].x = biped::size*glm::cos(angle); circle_vertices[i].y = biped::size*glm::sin(angle); angle += increment; } } std::array<unsigned short, circle_vertices.size()> circle_indices; for(unsigned short i = 0; i < circle_indices.size(); ++i) circle_indices[i] = i; shape test_biped_shape(circle_vertices, circle_indices, GL_LINE_LOOP); bool quit = false; lap_timer timer; while(!quit) { SDL_Event event; while( media_layer.poll(event) ) { switch(event.type) { case SDL_QUIT: quit = true; break; } } input.apply_input(player); // Calculate turret appearance float turret_aim = player.weapon.aim_angle(); glm::vec2 turret_end( biped::size*glm::cos(turret_aim), biped::size*glm::sin(turret_aim) ); segment turret_segment( player.position() ); turret_segment.end = turret_segment.start + turret_end; // Calculate segments from projectiles std::vector<segment> psegments; for(auto i = physics.projectiles.begin(); i != physics.projectiles.end(); ++i) { psegments.emplace_back(i->position, i->position - 0.01f*i->velocity); } // Render scene ren.clear(); ren.view( input.cam.view() ); ren.render(player.model(), test_biped_shape); for(auto i = test_bipeds.begin(); i != test_bipeds.end(); ++i) ren.render(i->model(), test_biped_shape); ren.render(turret_segment); ren.render(psegments); win.present(); // Advance auto lap_time = timer.lap(); player.weapon.step(lap_time); physics.step(lap_time); input.cam.step(lap_time); } } catch(const std::exception & e) { std::cout << e.what() << std::endl; } } <|endoftext|>
<commit_before>#include <cstdio> #include <cstdlib> #include <unistd.h> #include <vector> #include <string> #include <iostream> int main(int argc, char** argv) { std::string line; // hold a raw line of input std::vector<char*> cmd; // holds a single command and its arguments std::vector<std::vector<char*> > cmds; // holds multiple commands printf("\nWelcome to rshell!\n"); while (1) { printf("$ "); getline(std::cin, line); if (line.substr(0, 4) == "exit") { printf("Goodbye!\n"); exit(0); } printf("You entered \"%s\"\n", line.c_str()); } return 0; } <commit_msg>Added support for comments<commit_after>#include <cstdio> #include <cstdlib> #include <unistd.h> #include <vector> #include <string> #include <iostream> int main(int argc, char** argv) { // hold a raw line of input std::string line; // print welcome message and prompt printf("Welcome to rshell!\n$ "); getline(std::cin, line); do { // holds a single command and its arguments std::vector<char*> cmd; // holds multiple commands std::vector<std::vector<char*> > cmds; // look for comments if (line.find("#") != std::string::npos) { // remove them if necessary line = line.substr(0, line.find("#")); } // add a space so that every space-separated entity has // at least one space directly to the right of it // (makes parsing easier) line += ' '; // if exit was entered properly if (line.substr(0,5) == "exit ") { // say goodbye, and quit printf("Goodbye!\n"); exit(0); } // handle the input printf("You entered \"%s\"\n", line.c_str()); // todo: split // print prompt and get a line of text printf("$ "); } while (getline(std::cin, line)); return 0; } <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2015-2016 Andrea Scarpino <me@andreascarpino.it> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <QApplication> #include <QtQuick> #include <sailfishapp.h> #include "lyricsmanager.h" int main(int argc, char *argv[]) { //QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv)); // Needed by QWebPage QScopedPointer<QApplication> app(new QApplication(argc, argv)); QScopedPointer<QQuickView> view(SailfishApp::createView()); QCoreApplication::setApplicationName(QStringLiteral("harbour-Lyrics")); QCoreApplication::setOrganizationDomain(QStringLiteral("it.andreascarpino")); LyricsManager manager; view->rootContext()->setContextProperty("manager", &manager); view->setSource(SailfishApp::pathTo("qml/Lyrics.qml")); view->show(); return app->exec(); } <commit_msg>Application name must be lowercase<commit_after>/* The MIT License (MIT) Copyright (c) 2015-2016 Andrea Scarpino <me@andreascarpino.it> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <QApplication> #include <QtQuick> #include <sailfishapp.h> #include "lyricsmanager.h" int main(int argc, char *argv[]) { //QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv)); // Needed by QWebPage QScopedPointer<QApplication> app(new QApplication(argc, argv)); QScopedPointer<QQuickView> view(SailfishApp::createView()); QCoreApplication::setApplicationName(QStringLiteral("harbour-lyrics")); QCoreApplication::setOrganizationDomain(QStringLiteral("andreascarpino.it")); LyricsManager manager; view->rootContext()->setContextProperty("manager", &manager); view->setSource(SailfishApp::pathTo("qml/Lyrics.qml")); view->show(); return app->exec(); } <|endoftext|>
<commit_before>/* my own headers */ #include "landscape.h" #include "error_handling.h" #include "command_line.h" #include "popsim.h" #include "stats.h" #include "sequence.h" /* system headers */ #include <iostream> #include <string> using namespace std; void usage(void); int main(int argc, char *argv[]) { try { Args ar; if (argc == 1) { usage(); return 0; } /* read in the command line arguments and print them out */ ar.populate(argc, argv); cout << "args: " << ar << endl; /* create the random number generator */ RandomNumberGenerator *rng = 0; rng = new RandomNumberGenerator(ar.rand_seed); /* create the landscape */ Landscape *l = 0; switch (ar.model) { case block: l = new LandscapeBlockModel(ar.num_blocks, ar.seq_length/ar.num_blocks, ar.distr_mean, ar.distr_sd, rng); break; case segal: if (ar.autofit) { cerr << "autofitting" << endl; l = new LandscapeSegalModelFitted(ar.num_tfs, ar.pwm_filename, ar.segal_conditions, (unsigned int)19, ar.steps, rng, ar.segal_obs_expr, ar.segal_sd_lambda, ar.segal_sd_alpha, ar.segal_sd_gamma, ar.sequences, ar.num_slots, ar.segal_logistic_parameter, ar.segal_min_tf_sep); } else { if (ar.sampling_method == importance) { cerr << "using importance sampling method" << endl; /* we use the IS_* parameters as the importance distribution * from which we'll sample. And then we pass the segal_* parameters * as the target distribution parameters that is then used to * calculate the importance weights */ l = new LandscapeSegalModelSpecifiedIS(ar.num_tfs, ar.pwm_filename, ar.segal_lambda, ar.IS_segal_alpha, ar.segal_conditions, ar.IS_segal_gamma, ar.steps, ar.segal_expr_fit_func, 19, rng, ar.segal_gamma, ar.segal_alpha, ar.segal_logistic_parameter, ar.segal_min_tf_sep); } else { /* regular iid sampling */ l = new LandscapeSegalModelSpecifiedIID(ar.num_tfs, ar.pwm_filename, ar.segal_lambda, ar.segal_alpha, ar.segal_conditions, ar.segal_gamma, ar.steps, ar.segal_expr_fit_func, 19, rng, ar.segal_logistic_parameter, ar.segal_min_tf_sep); } } break; case neutral: l = new LandscapeNeutralModel(rng); break; default: throw SimError("invalid landscape type"); } if (ar.autofit) { /* We're trying to fit fit the model to the provided expression data */ LandscapeSegalModelFitted *lpt = (LandscapeSegalModelFitted*)l; lpt->create_chains(ar.num_chains, *ar.segal_chain_temps); cerr << "auto fit created " << lpt->parallel_tempered.num_chains() << " chains" << endl; lpt->precompute_lookup_tables(ar.sequences, ar.steps); cerr << "initing energies" << endl; lpt->parallel_tempered.init_energies(); cerr << "running chains" << endl; lpt->parallel_tempered.run_chains(ar.segal_chain_steps); } else if (ar.do_popsim) { /* we're doing a population simulation */ PopState ps(ar.pop_size, ar.mu_rate, ar.rec_rate, l, ar.deletion_params, ar.duplication_params); /* give the popstats access to the popstate and set stats marked print * at end, to print at the end. */ for (vector<PopStat>::iterator i = ar.popstats.begin(); i != ar.popstats.end(); i++) { i->set_popstate(&ps); if (i->modulo == PRINT_STAT_AT_END) i->modulo = ar.generations; } /* create an allele unless we have ones from the command line */ if (ar.sequences.size() < 1) { string empty(ar.seq_length, l->alphabet[0]); Sequence s(empty, l->alphabet); l->rng->uniform_dna(s, ar.seq_length, l); ps.alleles[s] = new Allele(s, ps.N, ps.generation, l); } for (vector<string>::iterator i = ar.sequences.begin(); i != ar.sequences.end(); i++) { Sequence s(*i, l->alphabet); ps.alleles[s] = new Allele(s, ps.N/ar.sequences.size(), ps.generation, l); } /* run the simulation */ ps.run(ar.popstats, ar.generations); } else { /* characterization of landscape part */ /* make sure we're not asked for popstats if not doing a popsim */ if (ar.popstats.size() > 0) { cerr << "pop stats require --popsim option" << endl; usage(); } /* give the scapetats access to the landscape */ for (vector<ScapeStat>::iterator i = ar.scapestats.begin(); i != ar.scapestats.end(); i++) i->set_landscape(l); /* loop, sampling nodes in the landscape uniformly until we do enough */ set<Sequence> draws; for (vector<string>::iterator i = ar.sequences.begin(); i != ar.sequences.end(); i++) { Sequence s(*i, l->alphabet); draws.insert(s); } sort(ar.scapestats.rbegin(), ar.scapestats.rend()); for (l->cur_rep = 0; l->cur_rep < ar.max_reps; l->cur_rep++) { if (draws.size() == 0) { Sequence draw = l->sample(ar.seq_length); draws.insert(draw); } unsigned int ns = ar.neighbor_steps; while (ns-- > 0) { /* add neighbors */ l->insert_neighbors(draws); } for (set<Sequence>::iterator dr=draws.begin(); dr!=draws.end(); dr++) { for (vector<ScapeStat>::iterator i = ar.scapestats.begin(); i != ar.scapestats.end(); i++) { if (l->cur_rep < i->reps) { i->calc_and_show(cout, *dr); } else { /* since we've sorted the stats by reps required, when we * encounter a stat that's already done enough reps we know * the rest have also done enough reps */ break; } } } draws.clear(); } } if (rng != 0) delete rng; if (l!=0) delete l; /* deal with various possible errors */ } catch (SimUsageError e) { cerr << endl << "detected usage error: " << e.detail << endl << endl; usage(); return 1; } catch(SimError &e) { cerr << "uncaught exception: " << e.detail << endl; /* exit */ } return 0; } /* print out usage information */ void usage(void) { cerr << "usage: regevscape [options]\n" "\n" " general options:\n" " -m/--model (block|segal|neutral)\n" " --popsim - run a population simulation\n" " --seed <int> - random number generator seed\n" " --seq <string> - a sequence to queue\n" "\n" " model-specific options: \n" " block model:\n" " --mean <float> - mean of within-block distr.\n" " --sd <float> - sd of within-block distr.\n" " --blocks <int> - number of blocks\n" " --length <int> - length of sequence\n" "\n" " segal model, general:\n" " --length <int> - length of sequence\n" " --tfs <int> - number of transcription factors\n" " --pwm <filename> - filename containing PWM definitions\n" " --condition=c1,c2,... - list of floats specifying TF levels\n" " multiple of conditions may be specified\n" " --steps <int> - number of iid samples for estimating expr.\n" "\n" " segal model automatic parameter estimation:\n" " --autofit - when specified, will try and fit params\n" " --chains <int> - number of parallel tempering chains\n" " --chain_steps <int> - number of steps to run the chain\n" " --expression=e1,e2,... - observed expression. One entry per seq.\n" " --psd_lambda <float> - proposal variance for lambda updates\n" " --psd_alpha <float> - proposal variance for alpha updates\n" " --psd_gamma <float> - proposal variance for gamma updates\n" //" --alpha_lattice=a1,a2, - grid of alpha (expr scalar) values for IS\n" "\n" " segal model paremeters\n" " --lambda=l0,l1,l2,... - list of floats for baseline and TF lambda\n" " --gamma=g11,g21,g12,g22 - cooperativity matrix by column\n" " --alpha=s1,s2,... - expression scaling parameters\n" " --logistic_param=d - use 1/(1+exp(-x/d))\n" " --tfsep <int> - minimum spacing between TFs in a config\n" "\n" " segal expression-fitness function\n" " --ffunc <choice> - here are the fitness function choices.\n" " --coef must bi given with the correct\n" " number of coefficients.\n" " linear : f = <x> dot <c> where x is the expr. vec., c coef vec.\n" " nop : f = 1\n" " f1 : f = a * (x1-b)^2 + c * (x2-d)^2 + e\n" " f2 : f = a^(-b*(x1-c)^2) * d^(-e*(x2-f)^2)\n" " f3 : f = prod(a^(-b*(xi-ci)^2))^(1/C) : i in (1..C) for C cond.\n" " f4 : f = exp((-1)*sum((xi-bi)^2/a)) : i in (1...C) for C cond.\n" " --coef=a,b,c,.. - list of coefficients for chosen fit. func.\n" "\n" " segal model sampling parameters:\n" " --sampling=<iid|importance> - which sampling method to employ\n" " --IS_gamma=g11,g21,g12,g22 - IS distr. cooperativity matrix\n" " --IS_alpha=s1,s2,... - list of expr. scalars, one per TF\n" "\n" " population simulation options:\n" " -g/--generations <int> - number of gen to run\n" " -u/--mutation <float> - per bp mutation rate\n" " -N/--popsize <int> - effective population size\n" " --deletion=u,n,p - rate, and negative binomial dup params\n" " --duplication=u,n,p - rate, and negative binomial dup params\n" "\n" " population statistics options (only valid in the presence\n" " of --popsim. May use multiple pstat options. Of the form\n" " --pstat=statname to print at the end or --pstat=statname,2\n" " if one wants statname printed every 2 generations. Default is\n" " each generation).\n" " --pstat=most_freq_seq - most frequent allele\n" " --pstat=most_freq_noseq - most frequent allele minus the sequence\n" " --pstat=mean_fitness - population mean fitness\n" " --pstat=all_alleles - details of each allele, sorted by # copies\n" " --pstat=allele_counter - number of alleles queried so far\n" //" --pstat=site_frequencies - positions and frequencies of seg. sites\n" "\n" " population real-time statistics:\n" " --pstat=mutational_effects - print fitness info for new mutants\n" " --pstat=allele_loss - print the generation and allele id for\n" " alleles when they're lost\n" "\n" " landscape sampling/traversal options:\n" " --neighbors <int> - for each sample, include neighbors within\n" " the specified number of steps\n" "\n" " landscape statistic options (only valid in the absence of --popsim.\n" " May use multiple lstat options. In all cases, reps is the number\n" " of nodes for which the statistic will be printed, all uniformly\n" " sampled from the landscape. If multiple statistics are requested\n" " the same starting points will be used up until the number of reps\n" " for each particular statistic is reached. All parameters are\n" " always required for each statistic.)\n" " --lstat=fitness,reps - node fitness\n" " --lstat=n_step_mean,reps,n,s - mean fitness (s samples) n steps away\n" " --lstat=banding,reps,x - band statistics for tried size x\n" " --lstat=sequence,reps - print out sequence per rep\n" "\n" " landscape statistics specifically for Segal model\n" " --lstat=expression,reps - print vector of expression levels\n" " --lstat=tf_occupancy,reps - print list of TF occupancy levels for\n" " each condition and TF combination\n" " --lstat=wsum,reps - the sum of all configuration weights\n" " --lstat=configs,1 - print out configurations\n" "\n"; return; } <commit_msg>Removed from the help message several unimplemented statistics<commit_after>/* my own headers */ #include "landscape.h" #include "error_handling.h" #include "command_line.h" #include "popsim.h" #include "stats.h" #include "sequence.h" /* system headers */ #include <iostream> #include <string> using namespace std; void usage(void); int main(int argc, char *argv[]) { try { Args ar; if (argc == 1) { usage(); return 0; } /* read in the command line arguments and print them out */ ar.populate(argc, argv); cout << "args: " << ar << endl; /* create the random number generator */ RandomNumberGenerator *rng = 0; rng = new RandomNumberGenerator(ar.rand_seed); /* create the landscape */ Landscape *l = 0; switch (ar.model) { case block: l = new LandscapeBlockModel(ar.num_blocks, ar.seq_length/ar.num_blocks, ar.distr_mean, ar.distr_sd, rng); break; case segal: if (ar.autofit) { cerr << "autofitting" << endl; l = new LandscapeSegalModelFitted(ar.num_tfs, ar.pwm_filename, ar.segal_conditions, (unsigned int)19, ar.steps, rng, ar.segal_obs_expr, ar.segal_sd_lambda, ar.segal_sd_alpha, ar.segal_sd_gamma, ar.sequences, ar.num_slots, ar.segal_logistic_parameter, ar.segal_min_tf_sep); } else { if (ar.sampling_method == importance) { cerr << "using importance sampling method" << endl; /* we use the IS_* parameters as the importance distribution * from which we'll sample. And then we pass the segal_* parameters * as the target distribution parameters that is then used to * calculate the importance weights */ l = new LandscapeSegalModelSpecifiedIS(ar.num_tfs, ar.pwm_filename, ar.segal_lambda, ar.IS_segal_alpha, ar.segal_conditions, ar.IS_segal_gamma, ar.steps, ar.segal_expr_fit_func, 19, rng, ar.segal_gamma, ar.segal_alpha, ar.segal_logistic_parameter, ar.segal_min_tf_sep); } else { /* regular iid sampling */ l = new LandscapeSegalModelSpecifiedIID(ar.num_tfs, ar.pwm_filename, ar.segal_lambda, ar.segal_alpha, ar.segal_conditions, ar.segal_gamma, ar.steps, ar.segal_expr_fit_func, 19, rng, ar.segal_logistic_parameter, ar.segal_min_tf_sep); } } break; case neutral: l = new LandscapeNeutralModel(rng); break; default: throw SimError("invalid landscape type"); } if (ar.autofit) { /* We're trying to fit fit the model to the provided expression data */ LandscapeSegalModelFitted *lpt = (LandscapeSegalModelFitted*)l; lpt->create_chains(ar.num_chains, *ar.segal_chain_temps); cerr << "auto fit created " << lpt->parallel_tempered.num_chains() << " chains" << endl; lpt->precompute_lookup_tables(ar.sequences, ar.steps); cerr << "initing energies" << endl; lpt->parallel_tempered.init_energies(); cerr << "running chains" << endl; lpt->parallel_tempered.run_chains(ar.segal_chain_steps); } else if (ar.do_popsim) { /* we're doing a population simulation */ PopState ps(ar.pop_size, ar.mu_rate, ar.rec_rate, l, ar.deletion_params, ar.duplication_params); /* give the popstats access to the popstate and set stats marked print * at end, to print at the end. */ for (vector<PopStat>::iterator i = ar.popstats.begin(); i != ar.popstats.end(); i++) { i->set_popstate(&ps); if (i->modulo == PRINT_STAT_AT_END) i->modulo = ar.generations; } /* create an allele unless we have ones from the command line */ if (ar.sequences.size() < 1) { string empty(ar.seq_length, l->alphabet[0]); Sequence s(empty, l->alphabet); l->rng->uniform_dna(s, ar.seq_length, l); ps.alleles[s] = new Allele(s, ps.N, ps.generation, l); } for (vector<string>::iterator i = ar.sequences.begin(); i != ar.sequences.end(); i++) { Sequence s(*i, l->alphabet); ps.alleles[s] = new Allele(s, ps.N/ar.sequences.size(), ps.generation, l); } /* run the simulation */ ps.run(ar.popstats, ar.generations); } else { /* characterization of landscape part */ /* make sure we're not asked for popstats if not doing a popsim */ if (ar.popstats.size() > 0) { cerr << "pop stats require --popsim option" << endl; usage(); } /* give the scapetats access to the landscape */ for (vector<ScapeStat>::iterator i = ar.scapestats.begin(); i != ar.scapestats.end(); i++) i->set_landscape(l); /* loop, sampling nodes in the landscape uniformly until we do enough */ set<Sequence> draws; for (vector<string>::iterator i = ar.sequences.begin(); i != ar.sequences.end(); i++) { Sequence s(*i, l->alphabet); draws.insert(s); } sort(ar.scapestats.rbegin(), ar.scapestats.rend()); for (l->cur_rep = 0; l->cur_rep < ar.max_reps; l->cur_rep++) { if (draws.size() == 0) { Sequence draw = l->sample(ar.seq_length); draws.insert(draw); } unsigned int ns = ar.neighbor_steps; while (ns-- > 0) { /* add neighbors */ l->insert_neighbors(draws); } for (set<Sequence>::iterator dr=draws.begin(); dr!=draws.end(); dr++) { for (vector<ScapeStat>::iterator i = ar.scapestats.begin(); i != ar.scapestats.end(); i++) { if (l->cur_rep < i->reps) { i->calc_and_show(cout, *dr); } else { /* since we've sorted the stats by reps required, when we * encounter a stat that's already done enough reps we know * the rest have also done enough reps */ break; } } } draws.clear(); } } if (rng != 0) delete rng; if (l!=0) delete l; /* deal with various possible errors */ } catch (SimUsageError e) { cerr << endl << "detected usage error: " << e.detail << endl << endl; usage(); return 1; } catch(SimError &e) { cerr << "uncaught exception: " << e.detail << endl; /* exit */ } return 0; } /* print out usage information */ void usage(void) { cerr << "usage: regevscape [options]\n" "\n" " general options:\n" " -m/--model (block|segal|neutral)\n" " --popsim - run a population simulation\n" " --seed <int> - random number generator seed\n" " --seq <string> - a sequence to queue\n" "\n" " model-specific options: \n" " block model:\n" " --mean <float> - mean of within-block distr.\n" " --sd <float> - sd of within-block distr.\n" " --blocks <int> - number of blocks\n" " --length <int> - length of sequence\n" "\n" " segal model, general:\n" " --length <int> - length of sequence\n" " --tfs <int> - number of transcription factors\n" " --pwm <filename> - filename containing PWM definitions\n" " --condition=c1,c2,... - list of floats specifying TF levels\n" " multiple of conditions may be specified\n" " --steps <int> - number of iid samples for estimating expr.\n" "\n" " segal model automatic parameter estimation:\n" " --autofit - when specified, will try and fit params\n" " --chains <int> - number of parallel tempering chains\n" " --chain_steps <int> - number of steps to run the chain\n" " --expression=e1,e2,... - observed expression. One entry per seq.\n" " --psd_lambda <float> - proposal variance for lambda updates\n" " --psd_alpha <float> - proposal variance for alpha updates\n" " --psd_gamma <float> - proposal variance for gamma updates\n" //" --alpha_lattice=a1,a2, - grid of alpha (expr scalar) values for IS\n" "\n" " segal model paremeters\n" " --lambda=l0,l1,l2,... - list of floats for baseline and TF lambda\n" " --gamma=g11,g21,g12,g22 - cooperativity matrix by column\n" " --alpha=s1,s2,... - expression scaling parameters\n" " --logistic_param=d - use 1/(1+exp(-x/d))\n" " --tfsep <int> - minimum spacing between TFs in a config\n" "\n" " segal expression-fitness function\n" " --ffunc <choice> - here are the fitness function choices.\n" " --coef must bi given with the correct\n" " number of coefficients.\n" " linear : f = <x> dot <c> where x is the expr. vec., c coef vec.\n" " nop : f = 1\n" " f1 : f = a * (x1-b)^2 + c * (x2-d)^2 + e\n" " f2 : f = a^(-b*(x1-c)^2) * d^(-e*(x2-f)^2)\n" " f3 : f = prod(a^(-b*(xi-ci)^2))^(1/C) : i in (1..C) for C cond.\n" " f4 : f = exp((-1)*sum((xi-bi)^2/a)) : i in (1...C) for C cond.\n" " --coef=a,b,c,.. - list of coefficients for chosen fit. func.\n" "\n" " segal model sampling parameters:\n" " --sampling=<iid|importance> - which sampling method to employ\n" " --IS_gamma=g11,g21,g12,g22 - IS distr. cooperativity matrix\n" " --IS_alpha=s1,s2,... - list of expr. scalars, one per TF\n" "\n" " population simulation options:\n" " -g/--generations <int> - number of gen to run\n" " -u/--mutation <float> - per bp mutation rate\n" " -N/--popsize <int> - effective population size\n" " --deletion=u,n,p - rate, and negative binomial dup params\n" " --duplication=u,n,p - rate, and negative binomial dup params\n" "\n" " population statistics options (only valid in the presence\n" " of --popsim. May use multiple pstat options. Of the form\n" " --pstat=statname to print at the end or --pstat=statname,2\n" " if one wants statname printed every 2 generations. Default is\n" " each generation).\n" " --pstat=most_freq_seq - most frequent allele\n" " --pstat=most_freq_noseq - most frequent allele minus the sequence\n" " --pstat=mean_fitness - population mean fitness\n" " --pstat=all_alleles - details of each allele, sorted by # copies\n" " --pstat=allele_counter - number of alleles queried so far\n" //" --pstat=site_frequencies - positions and frequencies of seg. sites\n" "\n" " population real-time statistics:\n" " --pstat=mutational_effects - print fitness info for new mutants\n" " --pstat=allele_loss - print the generation and allele id for\n" " alleles when they're lost\n" "\n" " landscape sampling/traversal options:\n" " --neighbors <int> - for each sample, include neighbors within\n" " the specified number of steps\n" "\n" " landscape statistic options (only valid in the absence of --popsim.\n" " May use multiple lstat options. In all cases, reps is the number\n" " of nodes for which the statistic will be printed, all uniformly\n" " sampled from the landscape. If multiple statistics are requested\n" " the same starting points will be used up until the number of reps\n" " for each particular statistic is reached. All parameters are\n" " always required for each statistic.)\n" " --lstat=fitness,reps - node fitness\n" //" --lstat=n_step_mean,reps,n,s - mean fitness (s samples) n steps away\n" //" --lstat=banding,reps,x - band statistics for tried size x\n" " --lstat=sequence,reps - print out sequence per rep\n" "\n" " landscape statistics specifically for Segal model\n" " --lstat=expression,reps - print vector of expression levels\n" " --lstat=tf_occupancy,reps - print list of TF occupancy levels for\n" " each condition and TF combination\n" " --lstat=wsum,reps - the sum of all configuration weights\n" " --lstat=configs,1 - print out configurations\n" "\n"; return; } <|endoftext|>
<commit_before>// GPS Tracker project with Adafruit IO // Author: Martin Spier // Libraries #include <Arduino.h> #include <Adafruit_SleepyDog.h> #include <SoftwareSerial.h> #include "Adafruit_FONA.h" #include "Adafruit_MQTT.h" #include "Adafruit_MQTT_FONA.h" #include <Wire.h> #include <RTClib.h> #include <SPI.h> #include <SD.h> // Alarm pins const int ledPin = 6; // Latitude & longitude for distance measurement float latitude, longitude, speed_kph, heading, altitude; // FONA pins configuration #define FONA_RX 2 // FONA serial RX pin (pin 2 for shield). #define FONA_TX 3 // FONA serial TX pin (pin 3 for shield). #define FONA_RST 4 // FONA reset pin (pin 4 for shield) // FONA GPRS configuration #define FONA_APN "wholesale" // APN used by cell data service (leave blank if unused) #define FONA_USERNAME "" // Username used by cell data service (leave blank if unused). #define FONA_PASSWORD "" // Password used by cell data service (leave blank if unused). // Adafruit IO configuration #define AIO_SERVER "io.adafruit.com" // Adafruit IO server name. #define AIO_SERVERPORT 1883 // Adafruit IO port. #define AIO_USERNAME "mspier" // Adafruit IO username (see http://accounts.adafruit.com/). #define AIO_KEY "91ad2dfb5578457ead8c903353edd2a7" // Adafruit IO key (see settings page at: https://io.adafruit.com/settings). #define MAX_TX_FAILURES 3 // Maximum number of publish failures in a row before resetting the whole sketch. // FONA instance & configuration SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); // FONA software serial connection. Adafruit_FONA fona = Adafruit_FONA(FONA_RST); // FONA library connection. // Setup the FONA MQTT class by passing in the FONA class and MQTT server and login details. Adafruit_MQTT_FONA mqtt(&fona, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY); uint8_t txFailures = 0; // Count of how many publish failures have occured in a row. // Feeds configuration Adafruit_MQTT_Publish tracker_feed = Adafruit_MQTT_Publish(&mqtt, "mspier/feeds/tracker/csv"); // Halt function called when an error occurs. Will print an error and stop execution while // doing a fast blink of the LED. If the watchdog is enabled it will reset after 8 seconds. void halt(const __FlashStringHelper *error) { Serial.println(error); while (1) { digitalWrite(ledPin, LOW); delay(100); digitalWrite(ledPin, HIGH); delay(100); } } // Function to connect and reconnect as necessary to the MQTT server. // Should be called in the loop function and it will take care if connecting. void MQTT_connect() { int8_t ret; // Stop if already connected. if (mqtt.connected()) { return; } Serial.println("Connecting to MQTT... "); while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected Serial.println(mqtt.connectErrorString(ret)); Serial.println("Retrying MQTT connection in 5 seconds..."); mqtt.disconnect(); delay(5000); // wait 5 seconds } Serial.println("MQTT Connected!"); } // Serialize the lat, long, altitude to a CSV string that can be published to the specified feed. void logTracker(float speed, float latitude, float longitude, float altitude, Adafruit_MQTT_Publish& publishFeed) { // Initialize a string buffer to hold the data that will be published. char sendbuffer[120]; char *p = sendbuffer; // add speed value dtostrf(speed, 2, 6, p); p += strlen(p); p[0] = ','; p++; // concat latitude dtostrf(latitude, 2, 6, p); p += strlen(p); p[0] = ','; p++; // concat longitude dtostrf(longitude, 3, 6, p); p += strlen(p); p[0] = ','; p++; // concat altitude dtostrf(altitude, 2, 6, p); p += strlen(p); // null terminate p[0] = 0; // Finally publish the string to the feed. Serial.println(F("Publishing tracker information: ")); Serial.println(sendbuffer); if (!publishFeed.publish(sendbuffer)) { Serial.println(F("Publish failed!")); txFailures++; } else { Serial.println(F("Publish succeeded!")); txFailures = 0; } } void setup() { // Initialize serial output. Serial.begin(115200); Serial.println(F("Adafruit IO & FONA808 Tracker")); // Set alarm components pinMode(ledPin, OUTPUT); // Initialize the FONA module Serial.println(F("Initializing FONA....(may take 10 seconds)")); fonaSS.begin(4800); if (!fona.begin(fonaSS)) { halt(F("Couldn't find FONA")); } fonaSS.println("AT+CMEE=2"); Serial.println(F("FONA is OK")); // Use the watchdog to simplify retry logic and make things more robust. // Enable this after FONA is intialized because FONA init takes about 8-9 seconds. Watchdog.enable(8000); Watchdog.reset(); // Wait for FONA to connect to cell network (up to 8 seconds, then watchdog reset). Serial.println(F("Checking for network...")); while (fona.getNetworkStatus() != 1) { delay(500); } // Enable GPS. fona.enableGPS(true); // Start the GPRS data connection. Watchdog.reset(); //fona.setGPRSNetworkSettings(F(FONA_APN)); fona.setGPRSNetworkSettings(F(FONA_APN), F(FONA_USERNAME), F(FONA_PASSWORD)); delay(4000); Watchdog.reset(); Serial.println(F("Enabling GPRS")); if (!fona.enableGPRS(true)) { halt(F("Failed to turn GPRS on, resetting...")); } Serial.println(F("Connected to Cellular!")); // Wait a little bit to stabilize the connection. Watchdog.reset(); delay(3000); // Now make the MQTT connection. int8_t ret = mqtt.connect(); if (ret != 0) { Serial.println(mqtt.connectErrorString(ret)); halt(F("MQTT connection failed, resetting...")); } Serial.println(F("MQTT Connected!")); Watchdog.reset(); Serial.print("Initializing SD card..."); // On the Ethernet Shield, CS is pin 4. It's set as an output by default. // Note that even if it's not used as the CS pin, the hardware SS pin // (10 on most Arduino boards, 53 on the Mega) must be left as an output // or the SD library functions will not work. pinMode(10, OUTPUT); if (!SD.begin(10)) { Serial.println("Initialization failed!"); return; } Serial.println("Initialization done."); } void loop() { // Watchdog reset at start of loop--make sure everything below takes less than 8 seconds in normal operation! Watchdog.enable(8000); Watchdog.reset(); // Reset everything if disconnected or too many transmit failures occured in a row. if (!fona.TCPconnected() || (txFailures >= MAX_TX_FAILURES)) { halt(F("Connection lost, resetting...")); } // Grab a GPS reading. float latitude, longitude, speed_kph, heading, altitude; fona.getGPS(&latitude, &longitude, &speed_kph, &heading, &altitude); // Grab battery reading uint16_t vbat; fona.getBattPercent(&vbat); // Log the current location to the path feed, then reset the counter. logTracker(speed_kph, latitude, longitude, altitude, tracker_feed); // Disable Watchdog for delay Watchdog.disable(); // Wait 60 seconds delay(60000); } <commit_msg>Cleaning up code.<commit_after>// GPS Tracker project with Adafruit IO // Author: Martin Spier // Libraries #include <Arduino.h> #include <Adafruit_SleepyDog.h> #include <SoftwareSerial.h> #include "Adafruit_FONA.h" #include "Adafruit_MQTT.h" #include "Adafruit_MQTT_FONA.h" // Alarm pins const int ledPin = 6; // FONA pins configuration #define FONA_RX 2 // FONA serial RX pin (pin 2 for shield). #define FONA_TX 3 // FONA serial TX pin (pin 3 for shield). #define FONA_RST 4 // FONA reset pin (pin 4 for shield) // FONA GPRS configuration #define FONA_APN "wholesale" // APN used by cell data service (leave blank if unused) // Adafruit IO configuration #define AIO_SERVER "io.adafruit.com" // Adafruit IO server name. #define AIO_SERVERPORT 1883 // Adafruit IO port. #define AIO_USERNAME "mspier" // Adafruit IO username (see http://accounts.adafruit.com/). #define AIO_KEY "033fa997141c4230aa05dfb1c8c6bdc6" // Adafruit IO key (see settings page at: https://io.adafruit.com/settings). #define MAX_TX_FAILURES 3 // Maximum number of publish failures in a row before resetting the whole sketch. // FONA instance & configuration SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); // FONA software serial connection. Adafruit_FONA fona = Adafruit_FONA(FONA_RST); // FONA library connection. // Setup the FONA MQTT class by passing in the FONA class and MQTT server and login details. Adafruit_MQTT_FONA mqtt(&fona, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY); uint8_t txFailures = 0; // Count of how many publish failures have occured in a row. // Feeds configuration Adafruit_MQTT_Publish tracker_feed = Adafruit_MQTT_Publish(&mqtt, "mspier/feeds/tracker/csv"); // Halt function called when an error occurs. Will print an error and stop execution while // doing a fast blink of the LED. If the watchdog is enabled it will reset after 8 seconds. void halt(const __FlashStringHelper *error) { Serial.println(error); while (1) { digitalWrite(ledPin, LOW); delay(100); digitalWrite(ledPin, HIGH); delay(100); } } // Function to connect and reconnect as necessary to the MQTT server. // Should be called in the loop function and it will take care if connecting. void MQTT_connect() { int8_t ret; // Stop if already connected. if (mqtt.connected()) { return; } Serial.println(F("Connecting to MQTT... ")); while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected Serial.println(mqtt.connectErrorString(ret)); Serial.println(F("Retrying MQTT connection in 5 seconds...")); mqtt.disconnect(); delay(5000); // wait 5 seconds } Serial.println(F("MQTT Connected!")); } // Serialize the lat, long, altitude to a CSV string that can be published to the specified feed. void logTracker(float speed, float latitude, float longitude, float altitude, Adafruit_MQTT_Publish& publishFeed) { // Initialize a string buffer to hold the data that will be published. char sendbuffer[120]; char *p = sendbuffer; // add speed value dtostrf(speed, 2, 6, p); p += strlen(p); p[0] = ','; p++; // concat latitude dtostrf(latitude, 2, 6, p); p += strlen(p); p[0] = ','; p++; // concat longitude dtostrf(longitude, 3, 6, p); p += strlen(p); p[0] = ','; p++; // concat altitude dtostrf(altitude, 2, 6, p); p += strlen(p); // null terminate p[0] = 0; // Finally publish the string to the feed. Serial.println(F("Publishing tracker information: ")); Serial.println(sendbuffer); if (!publishFeed.publish(sendbuffer)) { Serial.println(F("Publish failed!")); txFailures++; } else { Serial.println(F("Publish succeeded!")); txFailures = 0; } } void setup() { // Initialize serial output. Serial.begin(115200); Serial.println(F("Adafruit IO & FONA808 Tracker")); // Set alarm components pinMode(ledPin, OUTPUT); // Initialize the FONA module Serial.println(F("Initializing FONA....(may take 10 seconds)")); fonaSS.begin(4800); if (!fona.begin(fonaSS)) { halt(F("Couldn't find FONA")); } fonaSS.println("AT+CMEE=2"); Serial.println(F("FONA is OK")); // Use the watchdog to simplify retry logic and make things more robust. // Enable this after FONA is intialized because FONA init takes about 8-9 seconds. Watchdog.enable(8000); Watchdog.reset(); // Wait for FONA to connect to cell network (up to 8 seconds, then watchdog reset). Serial.println(F("Checking for network...")); while (fona.getNetworkStatus() != 1) { delay(500); } // Enable GPS. fona.enableGPS(true); // Start the GPRS data connection. Watchdog.reset(); fona.setGPRSNetworkSettings(F(FONA_APN)); // fona.setGPRSNetworkSettings(F(FONA_APN), F(FONA_USERNAME), F(FONA_PASSWORD)); delay(4000); Watchdog.reset(); Serial.println(F("Enabling GPRS")); if (!fona.enableGPRS(true)) { halt(F("Failed to turn GPRS on, resetting...")); } Serial.println(F("Connected to Cellular!")); // Wait a little bit to stabilize the connection. Watchdog.reset(); delay(3000); // Now make the MQTT connection. int8_t ret = mqtt.connect(); if (ret != 0) { Serial.println(mqtt.connectErrorString(ret)); halt(F("MQTT connection failed, resetting...")); } Serial.println(F("MQTT Connected!")); } void loop() { // Watchdog reset at start of loop--make sure everything below takes less than 8 seconds in normal operation! Watchdog.enable(8000); Watchdog.reset(); // Reset everything if disconnected or too many transmit failures occured in a row. if (!fona.TCPconnected() || (txFailures >= MAX_TX_FAILURES)) { halt(F("Connection lost, resetting...")); } // Grab a GPS reading. float latitude, longitude, speed_kph, heading, altitude; fona.getGPS(&latitude, &longitude, &speed_kph, &heading, &altitude); // Grab battery reading uint16_t vbat; fona.getBattPercent(&vbat); // Log the current location to the path feed, then reset the counter. logTracker(speed_kph, latitude, longitude, altitude, tracker_feed); // Disable Watchdog for delay Watchdog.disable(); // Wait 60 seconds delay(60000); } <|endoftext|>
<commit_before>#include <QApplication> #include <QDir> #include <QDesktopServices> #include <QDate> #include <QIcon> #include <QPointer> #include <QLocalServer> #include <QLocalSocket> #include "window.h" #include "tracker.h" #include "updater.h" #ifdef Q_WS_MAC #include "cocoa_initializer.h" #include "sparkle_updater.h" #endif int main(int argc, char **argv) { // Enforce single instance QLocalSocket socket; socket.connectToServer("trackobot"); if(socket.waitForConnected(500)) { return 1; // already running } QLocalServer::removeServer("trackobot"); QLocalServer server(NULL); if(!server.listen("trackobot")) { return 2; } // Basic setup QApplication app(argc, argv); QIcon icon = QIcon(":/icons/tray_icon.png"); app.setApplicationName("Track-o-Bot"); // for proper DataLocation handling app.setOrganizationName("spidy.ch"); app.setOrganizationDomain("spidy.ch"); app.setWindowIcon(icon); // Logging QString dataLocation = QDesktopServices::storageLocation(QDesktopServices::DataLocation); if(!QFile::exists(dataLocation)) { QDir dir; dir.mkpath(dataLocation); } string logFilePath = (dataLocation + QDir::separator() + app.applicationName() + ".log").toStdString(); Logger::Instance()->SetLogPath(logFilePath); // Start LOG("--> Launched v%s On %s", VERSION, QDate::currentDate().toString(Qt::ISODate).toStdString().c_str()); Updater *updater = NULL; #ifdef Q_WS_MAC CocoaInitializer cocoaInitiarizer; updater = new SparkleUpdater(Tracker::Instance()->WebserviceURL("/appcast.xml")); #endif // Initalize Windows n stuff Window window; // Make sure Account exists or create one Tracker::Instance()->EnsureAccountIsSetUp(); // Main Loop int exitCode = app.exec(); // Tear down LOG("<-- Shutdown"); return exitCode; } <commit_msg>dry it up<commit_after>#include <QApplication> #include <QDir> #include <QDesktopServices> #include <QDate> #include <QIcon> #include <QPointer> #include <QLocalServer> #include <QLocalSocket> #include "window.h" #include "tracker.h" #include "updater.h" #ifdef Q_WS_MAC #include "cocoa_initializer.h" #include "sparkle_updater.h" #endif int main(int argc, char **argv) { const char serverName[] = "trackobot"; // Enforce single instance QLocalSocket socket; socket.connectToServer(serverName); if(socket.waitForConnected(500)) { return 1; // already running } QLocalServer::removeServer(serverName); QLocalServer server(NULL); if(!server.listen(serverName)) { return 2; } // Basic setup QApplication app(argc, argv); QIcon icon = QIcon(":/icons/tray_icon.png"); app.setApplicationName("Track-o-Bot"); // for proper DataLocation handling app.setOrganizationName("spidy.ch"); app.setOrganizationDomain("spidy.ch"); app.setWindowIcon(icon); // Logging QString dataLocation = QDesktopServices::storageLocation(QDesktopServices::DataLocation); if(!QFile::exists(dataLocation)) { QDir dir; dir.mkpath(dataLocation); } string logFilePath = (dataLocation + QDir::separator() + app.applicationName() + ".log").toStdString(); Logger::Instance()->SetLogPath(logFilePath); // Start LOG("--> Launched v%s On %s", VERSION, QDate::currentDate().toString(Qt::ISODate).toStdString().c_str()); Updater *updater = NULL; #ifdef Q_WS_MAC CocoaInitializer cocoaInitiarizer; updater = new SparkleUpdater(Tracker::Instance()->WebserviceURL("/appcast.xml")); #endif // Initalize Windows n stuff Window window; // Make sure Account exists or create one Tracker::Instance()->EnsureAccountIsSetUp(); // Main Loop int exitCode = app.exec(); // Tear down LOG("<-- Shutdown"); return exitCode; } <|endoftext|>
<commit_before>/* main.cpp This file is part of: GAME PENCIL ENGINE https://create.pawbyte.com Copyright (c) 2014-2020 Nathan Hurde, Chase Lee. Copyright (c) 2014-2020 PawByte LLC. Copyright (c) 2014-2020 Game Pencil Engine contributors ( Contributors Page ) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Game Pencil Engine <https://create.pawbyte.com> ____ ____ _ | _ \ __ ___ _| __ ) _ _| |_ ___ | |_) / _` \ \ /\ / / _ \| | | | __/ _ \ | __/ (_| |\ V V /| |_) | |_| | || __/ |_| \__,_| \_/\_/ |____/ \__, |\__\___| |___/ Created By PawByte Attribution required at start of program and in credits. SDL 2.0.9 used for this version... */ #include "GPE/GPE.h" #include "gpe_game_master_itenary.h" int main( int argc, char* args[] ) { int gameFailed = 0; GPE_Init_Settings(argc, args , "PawByte","GPE_Editor"); //Initialize if( GPE_Init(argc, args ) == false ) { GPE_Report(" Unable to properly initialize GPE!\n"); gameFailed = 1; } gpe->set_fps( GPE_ENGINE_SETTINGS->defaultFPS ); if( GPE_Init_Master_Itenary( argc, args) == false ) { gameFailed = 1; } if(gameFailed==1) { GPE_Quit(); return -1; } if( gpe->game_loop() ) { GPE_Report("Completed Game Loop...."); } //Clean up GPE_Quit_Master_Itenary(); GPE_Report("Deleting GPE..."); GPE_Quit(); GPE_Report("Program Exited with Return Status 0..."); return 0; } <commit_msg>Delete main.cpp<commit_after><|endoftext|>
<commit_before>/* videocapture is a tool with no special purpose * * Copyright (C) 2009 Ronny Brendel <ronnybrendel@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #include "Prereqs.hpp" #include <cassert> #include <iostream> #include <list> #include <string> #include <QApplication> #include "CaptureDevice.hpp" #include "MainWindow.hpp" using namespace std; int main(int argc, char **args) { VT QApplication app(argc, args); /* transform the arg array into a nice list of strings */ list<string> argList; for( int i = 0; i < argc; ++i ) { argList.push_back(string(args[i])); } list<CaptureDevice*> captureDevices; /* evaluate arguments start */ auto it = argList.begin(); ++it; for (; it != argList.end(); ++it) { if (*it == "-d") { CaptureDevice *newCaptureDevice = new CaptureDevice(); string deviceFile = *(++it); int width = atoi((++it)->c_str()); int height = atoi((++it)->c_str()); assert(deviceFile.empty() == false); assert(width > 0); assert(height > 0); bool initialized = newCaptureDevice->init(deviceFile, V4L2_PIX_FMT_RGB24, (unsigned int)width, (unsigned int)height); assert(initialized); newCaptureDevice->printDeviceInfo(); newCaptureDevice->printFormats(); newCaptureDevice->printTimerInformation(); newCaptureDevice->printControls(); captureDevices.push_back(newCaptureDevice); } else if (*it == "-h" || *it == "--help") { cout << "videocapture [-d ...] [-d ...] [-d ...] ..." << endl << endl << " arguments:" << endl << " -d <device file> <res width> <res height> use this device" << " -h, --help show this message" << endl; } else { cerr << "unknown argument: \"" << *it << endl; } } /* evaluate arguments end */ MainWindow mainWindow(0, captureDevices); mainWindow.show(); int ret = app.exec(); for (auto it = captureDevices.begin(); it != captureDevices.end(); ++it) { (*it)->finish(); } return ret; } <commit_msg>add missing newline and exit after help output<commit_after>/* videocapture is a tool with no special purpose * * Copyright (C) 2009 Ronny Brendel <ronnybrendel@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #include "Prereqs.hpp" #include <cassert> #include <iostream> #include <list> #include <string> #include <QApplication> #include "CaptureDevice.hpp" #include "MainWindow.hpp" using namespace std; int main(int argc, char **args) { VT QApplication app(argc, args); /* transform the arg array into a nice list of strings */ list<string> argList; for( int i = 0; i < argc; ++i ) { argList.push_back(string(args[i])); } list<CaptureDevice*> captureDevices; /* evaluate arguments start */ auto it = argList.begin(); ++it; for (; it != argList.end(); ++it) { if (*it == "-d") { CaptureDevice *newCaptureDevice = new CaptureDevice(); string deviceFile = *(++it); int width = atoi((++it)->c_str()); int height = atoi((++it)->c_str()); assert(deviceFile.empty() == false); assert(width > 0); assert(height > 0); bool initialized = newCaptureDevice->init(deviceFile, V4L2_PIX_FMT_RGB24, (unsigned int)width, (unsigned int)height); assert(initialized); newCaptureDevice->printDeviceInfo(); newCaptureDevice->printFormats(); newCaptureDevice->printTimerInformation(); newCaptureDevice->printControls(); captureDevices.push_back(newCaptureDevice); } else if (*it == "-h" || *it == "--help") { cout << "videocapture [-d ...] [-d ...] [-d ...] ..." << endl << endl << " arguments:" << endl << " -d <device file> <res width> <res height> use this device" << endl << " -h, --help show this message" << endl; return 0; } else { cerr << "unknown argument: \"" << *it << endl; } } /* evaluate arguments end */ MainWindow mainWindow(0, captureDevices); mainWindow.show(); int ret = app.exec(); for (auto it = captureDevices.begin(); it != captureDevices.end(); ++it) { (*it)->finish(); } return ret; } <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2016 Andrea Scarpino <me@andreascarpino.it> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <QtQuick> #include <sailfishapp.h> #include "mpwmanager.h" int main(int argc, char *argv[]) { QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv)); QScopedPointer<QQuickView> view(SailfishApp::createView()); QCoreApplication::setApplicationName(QStringLiteral("MPW")); qmlRegisterType<MPWManager>("harbour.mpw", 1, 0, "MPWManager"); MPWManager manager; view->rootContext()->setContextProperty("manager", &manager); view->setSource(SailfishApp::pathTo("qml/MPW.qml")); view->show(); return app->exec(); } <commit_msg>Set Organization Domain<commit_after>/* The MIT License (MIT) Copyright (c) 2016 Andrea Scarpino <me@andreascarpino.it> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <QtQuick> #include <sailfishapp.h> #include "mpwmanager.h" int main(int argc, char *argv[]) { QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv)); QScopedPointer<QQuickView> view(SailfishApp::createView()); QCoreApplication::setApplicationName(QStringLiteral("MPW")); QCoreApplication::setOrganizationDomain(QStringLiteral("it.andreascarpino")); qmlRegisterType<MPWManager>("harbour.mpw", 1, 0, "MPWManager"); MPWManager manager; view->rootContext()->setContextProperty("manager", &manager); view->setSource(SailfishApp::pathTo("qml/MPW.qml")); view->show(); return app->exec(); } <|endoftext|>
<commit_before>#include <cstdio> #include <iostream> #include <sys/stat.h> #include <unistd.h> #define GetCurrentDir getcwd #include <array> #include <string> #include <memory> #include <stdexcept> std::string exec(const char* cmd) { std::array<char, 128> buffer; std::string result; std::shared_ptr<FILE> pipe(popen(cmd, "r"), pclose); if (!pipe) throw std::runtime_error("popen() failed!"); while (!feof(pipe.get())) { if (fgets(buffer.data(), 128, pipe.get()) != NULL) result += buffer.data(); } return result; } inline bool is_file_exists (const std::string& name) { struct stat buffer; return (stat (name.c_str(), &buffer) == 0); } std::string GetCurrentWorkingDir( void ) { char buff[FILENAME_MAX]; GetCurrentDir( buff, FILENAME_MAX ); std::string current_working_dir(buff); return current_working_dir; } int main() { if (is_file_exists(GetCurrentWorkingDir() + "/.git")) { std::cout << exec("git add --all") << std::endl; std::cout << exec("git commit -m \"Doing work\"") << std::endl; std::cout << exec("git push origin master") << std::endl; return 0; } else { std::cerr << "The current directory is not a git repository!" << std::endl; return 1; } }<commit_msg>added code<commit_after>#include <cstdio> #include <iostream> #include <sys/stat.h> #include <unistd.h> #define GetCurrentDir getcwd #include <array> #include <string> #include <memory> #include <stdexcept> std::string exec(const char* cmd) { std::array<char, 128> buffer; std::string result; std::shared_ptr<FILE> pipe(popen(cmd, "r"), pclose); if (!pipe) throw std::runtime_error("popen() failed!"); while (!feof(pipe.get())) { if (fgets(buffer.data(), 128, pipe.get()) != NULL) result += buffer.data(); } return result; } inline bool is_file_exists (const std::string& name) { struct stat buffer; return (stat (name.c_str(), &buffer) == 0); } std::string GetCurrentWorkingDir( void ) { char buff[FILENAME_MAX]; GetCurrentDir( buff, FILENAME_MAX ); std::string current_working_dir(buff); return current_working_dir; } int main() { if (is_file_exists(GetCurrentWorkingDir() + "/.git")) { std::cout << exec("git add --all") << std::endl; std::cout << exec("git commit -m \"$(curl -s whatthecommit.com/index.txt)\"") << std::endl; std::cout << exec("git push origin master") << std::endl; return 0; } else { std::cerr << "The current directory is not a git repository!" << std::endl; return 1; } } <|endoftext|>